Skip to content

The open alternative to Salesforce, designed for AI.

5.5 KB
Raw Blame
import { useDuplicateFieldsWidgetForPageLayout } from '@/page-layout/hooks/useDuplicateFieldsWidgetForPageLayout';
import { useDuplicateRecordTableWidgetForPageLayout } from '@/page-layout/hooks/useDuplicateRecordTableWidgetForPageLayout';
import { PageLayoutComponentInstanceContext } from '@/page-layout/states/contexts/PageLayoutComponentInstanceContext';
import { pageLayoutCurrentLayoutsComponentState } from '@/page-layout/states/pageLayoutCurrentLayoutsComponentState';
import { pageLayoutDraftComponentState } from '@/page-layout/states/pageLayoutDraftComponentState';
import { pageLayoutEditingWidgetIdComponentState } from '@/page-layout/states/pageLayoutEditingWidgetIdComponentState';
import { type PageLayoutWidget } from '@/page-layout/types/PageLayoutWidget';
import { addWidgetToTab } from '@/page-layout/utils/addWidgetToTab';
import { generateDuplicatedTimestamps } from '@/page-layout/utils/generateDuplicatedTimestamps';
import { getUpdatedTabLayouts } from '@/page-layout/utils/getUpdatedTabLayouts';
import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';
import { useAtomComponentStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateCallbackState';
import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
import { useStore } from 'jotai';
import { useCallback } from 'react';
import { appendCopySuffix, isDefined } from 'twenty-shared/utils';
import { doNotTranslate } from 'twenty-shared/i18n';
import { v4 as uuidv4 } from 'uuid';

export const useDuplicatePageLayoutWidget = (
  pageLayoutIdFromProps?: string,
) => {
  const pageLayoutId = useAvailableComponentInstanceIdOrThrow(
    PageLayoutComponentInstanceContext,
    pageLayoutIdFromProps,
  );

  const pageLayoutDraftState = useAtomComponentStateCallbackState(
    pageLayoutDraftComponentState,
    pageLayoutId,
  );

  const pageLayoutCurrentLayoutsState = useAtomComponentStateCallbackState(
    pageLayoutCurrentLayoutsComponentState,
    pageLayoutId,
  );

  const setPageLayoutEditingWidgetId = useSetAtomComponentState(
    pageLayoutEditingWidgetIdComponentState,
    pageLayoutId,
  );

  const store = useStore();

  const { duplicateFieldsWidget } = useDuplicateFieldsWidgetForPageLayout({
    pageLayoutId,
  });

  const { duplicateRecordTableWidget } =
    useDuplicateRecordTableWidgetForPageLayout({
      pageLayoutId,
    });

  const duplicateWidget = useCallback(
    (widgetId: string): string => {
      const pageLayoutDraft = store.get(pageLayoutDraftState);

      const allTabLayouts = store.get(pageLayoutCurrentLayoutsState);

      const sourceWidget = pageLayoutDraft.tabs
        .flatMap((tab) => tab.widgets)
        .find((widget) => widget.id === widgetId);

      if (!isDefined(sourceWidget)) {
        throw new Error(doNotTranslate(`Widget with id ${widgetId} not found`));
      }

      const sourceTab = pageLayoutDraft.tabs.find(
        (tab) => tab.id === sourceWidget.pageLayoutTabId,
      );

      if (!isDefined(sourceTab)) {
        throw new Error(
          doNotTranslate(
            `Tab with id ${sourceWidget.pageLayoutTabId} not found`,
          ),
        );
      }

      const newWidgetId = uuidv4();

      const widgetViewCopyResult =
        duplicateFieldsWidget({ sourceWidget, newWidgetId }) ??
        duplicateRecordTableWidget({ sourceWidget, newWidgetId });

      const clonedConfiguration = isDefined(widgetViewCopyResult)
        ? {
            ...sourceWidget.configuration,
            viewId: widgetViewCopyResult.newViewId,
          }
        : sourceWidget.configuration;

      const clonedWidget: PageLayoutWidget = {
        ...sourceWidget,
        id: newWidgetId,
        title: appendCopySuffix(sourceWidget.title),
        configuration: clonedConfiguration,
        ...generateDuplicatedTimestamps(),
      };

      const currentTabDesktopLayouts =
        allTabLayouts[sourceTab.id]?.desktop ?? [];

      const sourceLayout = currentTabDesktopLayouts.find(
        (layout) => layout.i === widgetId,
      );

      if (!isDefined(sourceLayout)) {
        throw new Error(
          doNotTranslate(`Layout for widget ${widgetId} not found`),
        );
      }

      const maxY = currentTabDesktopLayouts.reduce(
        (max, layout) => Math.max(max, layout.y + layout.h),
        0,
      );

      const newLayout = {
        ...sourceLayout,
        i: newWidgetId,
        y: maxY,
      };

      const updatedLayouts = getUpdatedTabLayouts(
        allTabLayouts,
        sourceTab.id,
        newLayout,
      );

      store.set(pageLayoutCurrentLayoutsState, updatedLayouts);

      store.set(pageLayoutDraftState, (prev) => ({
        ...prev,
        tabs: addWidgetToTab(prev.tabs, sourceTab.id, clonedWidget),
      }));

      setPageLayoutEditingWidgetId(newWidgetId);

      requestAnimationFrame(() => {
        // The same page layout can be mounted in the main view and a side panel
        // at once, so every render of the new widget is brought into view.
        document
          .querySelectorAll(`[data-widget-id="${newWidgetId}"]`)
          .forEach((widgetElement) => {
            widgetElement.scrollIntoView({
              behavior: 'smooth',
              block: 'nearest',
            });
          });
      });

      return newWidgetId;
    },
    [
      duplicateFieldsWidget,
      duplicateRecordTableWidget,
      pageLayoutCurrentLayoutsState,
      pageLayoutDraftState,
      setPageLayoutEditingWidgetId,
      store,
    ],
  );

  return { duplicateWidget };
};