The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
import { PageLayoutComponentInstanceContext } from '@/page-layout/states/contexts/PageLayoutComponentInstanceContext';
import { pageLayoutCurrentLayoutsComponentState } from '@/page-layout/states/pageLayoutCurrentLayoutsComponentState';
import { pageLayoutDraftComponentState } from '@/page-layout/states/pageLayoutDraftComponentState';
import { convertLayoutsToWidgets } from '@/page-layout/utils/convertLayoutsToWidgets';
import { activeTabIdComponentState } from '@/ui/layout/tab-list/states/activeTabIdComponentState';
import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';
import { useAtomComponentStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateCallbackState';
import { useStore } from 'jotai';
import { useCallback } from 'react';
import { type Layout, type ResponsiveLayouts } from 'react-grid-layout';
import { isDefined } from 'twenty-shared/utils';
export const usePageLayoutHandleLayoutChange = ({
pageLayoutId: pageLayoutIdFromProps,
tabListInstanceId,
}: {
pageLayoutId: string;
tabListInstanceId: string;
}) => {
const pageLayoutId = useAvailableComponentInstanceIdOrThrow(
PageLayoutComponentInstanceContext,
pageLayoutIdFromProps,
);
const store = useStore();
const pageLayoutCurrentLayoutsState = useAtomComponentStateCallbackState(
pageLayoutCurrentLayoutsComponentState,
pageLayoutId,
);
const pageLayoutDraftState = useAtomComponentStateCallbackState(
pageLayoutDraftComponentState,
pageLayoutId,
);
const handleLayoutChange = useCallback(
(_: Layout, allLayouts: ResponsiveLayouts) => {
const activeTabId = store.get(
activeTabIdComponentState.atomFamily({
instanceId: tabListInstanceId,
}),
);
if (!isDefined(activeTabId)) return;
const currentTabLayouts = store.get(pageLayoutCurrentLayoutsState);
store.set(pageLayoutCurrentLayoutsState, {
...currentTabLayouts,
[activeTabId]: structuredClone(allLayouts),
});
const pageLayoutDraft = store.get(pageLayoutDraftState);
const currentTab = pageLayoutDraft.tabs.find(
(tab) => tab.id === activeTabId,
);
if (!currentTab) return;
const updatedWidgets = convertLayoutsToWidgets(
currentTab.widgets,
allLayouts,
);
if (isDefined(activeTabId)) {
store.set(pageLayoutDraftState, (prev) => ({
...prev,
tabs: prev.tabs.map((tab) => {
if (tab.id === activeTabId) {
const tabWidgets = updatedWidgets.filter(
(w) => w.pageLayoutTabId === activeTabId,
);
return {
...tab,
widgets: tabWidgets,
};
}
return tab;
}),
}));
}
},
[
tabListInstanceId,
pageLayoutCurrentLayoutsState,
pageLayoutDraftState,
store,
],
);
return { handleLayoutChange };
};