Skip to content

The open alternative to Salesforce, designed for AI.

[forms 1/3] Make record creation commands available across objects (#25890)

Thomas des Francs8a0d76de2490
diff --git a/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContext.ts b/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContext.ts
index 46bc547b683..634afaf8012 100644
--- a/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContext.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContext.ts
@@ -1,13 +1,13 @@
+import { type CommandMenuItemDefinition } from '@/command-menu-item/types/CommandMenuItemDefinition';
import { EMPTY_COMMAND_MENU_CONTEXT_API } from '@/command-menu-item/constants/EmptyCommandMenuContextApi';
import { CommandMenuItemContainerType } from '@/command-menu-item/types/CommandMenuItemContainerType';
import { createContext } from 'react';
import { type CommandMenuContextApi } from 'twenty-shared/types';
-import { type CommandMenuItemFieldsFragment } from '~/generated-metadata/graphql';
export type CommandMenuContextType = {
displayType: 'button' | 'listItem' | 'dropdownItem';
containerType: CommandMenuItemContainerType;
- commandMenuItems: CommandMenuItemFieldsFragment[];
+ commandMenuItems: CommandMenuItemDefinition[];
commandMenuContextApi: CommandMenuContextApi;
isInPreviewMode: boolean;
};
diff --git a/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContextProviderContent.tsx b/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContextProviderContent.tsx
index 17880212136..6d7e2041879 100644
--- a/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContextProviderContent.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContextProviderContent.tsx
@@ -1,3 +1,5 @@
+import { useGlobalRecordCreationCommandMenuItems } from '@/command-menu-item/hooks/useGlobalRecordCreationCommandMenuItems';
+import { CommandMenuItemContainerType } from '@/command-menu-item/types/CommandMenuItemContainerType';
import {
CommandMenuContext,
type CommandMenuContextType,
@@ -9,6 +11,7 @@ import { doesCommandMenuItemMatchPageLayoutId } from '@/command-menu-item/utils/
import { resolveCommandMenuItemPinning } from '@/command-menu-item/utils/resolveCommandMenuItemPinning';
import { doesCommandMenuItemMatchPageType } from '@/command-menu-item/utils/doesCommandMenuItemMatchPageType';
import { doesCommandMenuItemMatchSelectionState } from '@/command-menu-item/utils/doesCommandMenuItemMatchSelectionState';
+import { mergeGlobalRecordCreationCommandMenuItems } from '@/command-menu-item/utils/mergeGlobalRecordCreationCommandMenuItems';
import { useIsLayoutCustomizationAllowedOnCurrentPage } from '@/layout-customization/hooks/useIsLayoutCustomizationAllowedOnCurrentPage';
import {
currentPageLayoutIdState,
@@ -36,6 +39,15 @@ export const CommandMenuContextProviderContent = ({
isInPreviewMode,
}: CommandMenuContextProviderContentProps) => {
const commandMenuItems = useAtomStateValue(commandMenuItemsSelector);
+ const {
+ isRecordCreationFormEnabled,
+ hasGlobalRecordCreationCommandTemplate,
+ globalRecordCreationCommandMenuItems,
+ } = useGlobalRecordCreationCommandMenuItems(commandMenuItems);
+ const shouldDisplayGlobalRecordCreationCommands =
+ containerType === CommandMenuItemContainerType.CommandMenuList &&
+ isRecordCreationFormEnabled &&
+ hasGlobalRecordCreationCommandTemplate;
const isLayoutCustomizationAllowedOnCurrentPage =
useIsLayoutCustomizationAllowedOnCurrentPage();
const commandMenuItemsDraft = useAtomStateValue(commandMenuItemsDraftState);
@@ -55,7 +67,7 @@ export const CommandMenuContextProviderContent = ({
? (commandMenuItemsDraft ?? commandMenuItems)
: commandMenuItems;
- return commandMenuItemsToDisplay
+ const contextCommandMenuItems = commandMenuItemsToDisplay
.filter(
(item) =>
item.engineComponentKey !==
@@ -74,12 +86,19 @@ export const CommandMenuContextProviderContent = ({
commandMenuContextApi,
),
)
- .map((item) => resolveCommandMenuItemPinning(item, commandMenuContextApi))
- .sort(
- (firstItem, secondItem) => firstItem.position - secondItem.position,
+ .map((item) =>
+ resolveCommandMenuItemPinning(item, commandMenuContextApi),
);
+
+ return mergeGlobalRecordCreationCommandMenuItems({
+ commandMenuItems: contextCommandMenuItems,
+ globalRecordCreationCommandMenuItems,
+ shouldDisplayGlobalRecordCreationCommands,
+ });
}, [
commandMenuContextApi,
+ globalRecordCreationCommandMenuItems,
+ shouldDisplayGlobalRecordCreationCommands,
commandMenuItems,
commandMenuItemsDraft,
effectivePageLayoutId,
diff --git a/packages/twenty-front/src/modules/command-menu-item/display/components/CommandMenuItemRenderer.tsx b/packages/twenty-front/src/modules/command-menu-item/display/components/CommandMenuItemRenderer.tsx
index 606545baded..cb99084e50d 100644
--- a/packages/twenty-front/src/modules/command-menu-item/display/components/CommandMenuItemRenderer.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/display/components/CommandMenuItemRenderer.tsx
@@ -1,3 +1,4 @@
+import { type CommandMenuItemDefinition } from '@/command-menu-item/types/CommandMenuItemDefinition';
import { AppMenuItem } from '@/applications/components/AppMenuItem';
import { useIsThirdPartyApplication } from '@/applications/hooks/useIsThirdPartyApplication';
import { CommandMenuContext } from '@/command-menu-item/contexts/CommandMenuContext';
@@ -18,7 +19,6 @@ import { assertUnreachable, isDefined } from 'twenty-shared/utils';
import { useIcons } from 'twenty-ui/icon';
import { Loader } from 'twenty-ui/primitives/feedback';
import { MenuItem } from 'twenty-ui/primitives/navigation';
-import { type CommandMenuItemFieldsFragment } from '~/generated-metadata/graphql';
const StyledPreviewWrapper = styled.div`
cursor: not-allowed;
@@ -29,7 +29,7 @@ const StyledPreviewWrapper = styled.div`
`;
type CommandMenuItemRendererProps = {
- item: CommandMenuItemFieldsFragment;
+ item: CommandMenuItemDefinition;
isPrimaryAction?: boolean;
shouldHideLabel?: boolean;
};
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx
index 8f7ac40d451..baf6868c3c9 100644
--- a/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx
@@ -18,7 +18,7 @@ import { RestoreRecordsCommand } from '@/command-menu-item/engine-command/record
import { TriggerWorkflowVersionEngineCommand } from '@/command-menu-item/engine-command/record/components/TriggerWorkflowVersionEngineCommand';
import { MergeMultipleRecordsCommand } from '@/command-menu-item/engine-command/record/multiple-records/components/MergeMultipleRecordsCommand';
import { UpdateMultipleRecordsCommand } from '@/command-menu-item/engine-command/record/multiple-records/components/UpdateMultipleRecordsCommand';
-import { CreateNewIndexRecordNoSelectionRecordCommand } from '@/command-menu-item/engine-command/record/no-selection/components/CreateNewIndexRecordNoSelectionRecordCommand';
+import { CreateNewRecordCommand } from '@/command-menu-item/engine-command/record/no-selection/components/CreateNewRecordCommand';
import { CreateNewViewNoSelectionRecordCommand } from '@/command-menu-item/engine-command/record/no-selection/components/CreateNewViewNoSelectionRecordCommand';
import { HideDeletedRecordsNoSelectionRecordCommand } from '@/command-menu-item/engine-command/record/no-selection/components/HideDeletedRecordsNoSelectionRecordCommand';
import { ImportRecordsNoSelectionRecordCommand } from '@/command-menu-item/engine-command/record/no-selection/components/ImportRecordsNoSelectionRecordCommand';
@@ -62,9 +62,7 @@ export const ENGINE_COMPONENT_KEY_COMPONENT_MAP: Record<
EngineComponentKey,
React.ReactNode
> = {
- [EngineComponentKey.CREATE_NEW_RECORD]: (
- <CreateNewIndexRecordNoSelectionRecordCommand />
- ),
+ [EngineComponentKey.CREATE_NEW_RECORD]: <CreateNewRecordCommand />,
[EngineComponentKey.DELETE_RECORDS]: <DeleteRecordsCommand />,
[EngineComponentKey.RESTORE_RECORDS]: <RestoreRecordsCommand />,
[EngineComponentKey.DESTROY_RECORDS]: <DestroyRecordsCommand />,
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/hooks/useMountCommand.ts b/packages/twenty-front/src/modules/command-menu-item/engine-command/hooks/useMountCommand.ts
index 40a837b21b6..e16c2d0cf57 100644
--- a/packages/twenty-front/src/modules/command-menu-item/engine-command/hooks/useMountCommand.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/hooks/useMountCommand.ts
@@ -21,6 +21,7 @@ type MountCommandParams = {
availabilityObjectMetadataId?: string | null;
payload?: CommandMenuItemPayload | null;
navigationTargetObjectMetadataId?: string | null;
+ creationTargetObjectMetadataId?: string;
isInSidePanel?: boolean;
};
@@ -42,6 +43,7 @@ export const useMountCommand = () => {
availabilityObjectMetadataId,
payload,
navigationTargetObjectMetadataId,
+ creationTargetObjectMetadataId,
isInSidePanel,
}: MountCommandParams) => {
const headlessEngineCommandContextApi = buildHeadlessCommandContextApi({
@@ -50,6 +52,7 @@ export const useMountCommand = () => {
engineComponentKey,
payload,
navigationTargetObjectMetadataId,
+ creationTargetObjectMetadataId,
isInSidePanel,
});
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/components/CreateGlobalRecordCommand.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/components/CreateGlobalRecordCommand.tsx
new file mode 100644
index 00000000000..f85c6203d76
--- /dev/null
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/components/CreateGlobalRecordCommand.tsx
@@ -0,0 +1,19 @@
+import { HeadlessEngineCommandWrapperEffect } from '@/command-menu-item/engine-command/components/HeadlessEngineCommandWrapperEffect';
+import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
+import { useCreateNewRecord } from '@/object-record/hooks/useCreateNewRecord';
+
+type CreateGlobalRecordCommandProps = {
+ objectMetadataItem: EnrichedObjectMetadataItem;
+};
+
+export const CreateGlobalRecordCommand = ({
+ objectMetadataItem,
+}: CreateGlobalRecordCommandProps) => {
+ const { createNewRecord } = useCreateNewRecord({ objectMetadataItem });
+
+ return (
+ <HeadlessEngineCommandWrapperEffect
+ execute={() => createNewRecord({ position: 'first' })}
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/components/CreateNewIndexRecordNoSelectionRecordCommand.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/components/CreateNewIndexRecordNoSelectionRecordCommand.tsx
index 5ff5ab3393a..0abaefb09e8 100644
--- a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/components/CreateNewIndexRecordNoSelectionRecordCommand.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/components/CreateNewIndexRecordNoSelectionRecordCommand.tsx
@@ -1,19 +1,11 @@
-import { CoreObjectNameSingular, FeatureFlagKey } from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
-
import { HeadlessEngineCommandWrapperEffect } from '@/command-menu-item/engine-command/components/HeadlessEngineCommandWrapperEffect';
import { useHeadlessCommandContextApi } from '@/command-menu-item/engine-command/hooks/useHeadlessCommandContextApi';
-import { useCreateCoreWorkflow } from '@/object-core/workflows/hooks/useCreateCoreWorkflow';
import { useCreateNewIndexRecord } from '@/object-record/record-table/hooks/useCreateNewIndexRecord';
-import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
+import { isDefined } from 'twenty-shared/utils';
export const CreateNewIndexRecordNoSelectionRecordCommand = () => {
const { objectMetadataItem, recordIndexId } = useHeadlessCommandContextApi();
- const isWorkflowCoreIndexPageEnabled = useIsFeatureEnabled(
- FeatureFlagKey.IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED,
- );
-
if (!isDefined(objectMetadataItem) || !isDefined(recordIndexId)) {
throw new Error(
'Object metadata item and record index ID are required to create new index record',
@@ -25,19 +17,9 @@ export const CreateNewIndexRecordNoSelectionRecordCommand = () => {
instanceId: recordIndexId,
});
- const { createCoreWorkflow } = useCreateCoreWorkflow();
-
- const shouldCreateThroughCoreWorkflow =
- isWorkflowCoreIndexPageEnabled &&
- objectMetadataItem.nameSingular === CoreObjectNameSingular.Workflow;
-
return (
<HeadlessEngineCommandWrapperEffect
- execute={() =>
- shouldCreateThroughCoreWorkflow
- ? createCoreWorkflow()
- : createNewIndexRecord({ position: 'first' })
- }
+ execute={() => createNewIndexRecord({ position: 'first' })}
/>
);
};
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/components/CreateNewRecordCommand.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/components/CreateNewRecordCommand.tsx
new file mode 100644
index 00000000000..29ee2b561a9
--- /dev/null
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/components/CreateNewRecordCommand.tsx
@@ -0,0 +1,53 @@
+import { HeadlessEngineCommandWrapperEffect } from '@/command-menu-item/engine-command/components/HeadlessEngineCommandWrapperEffect';
+import { useHeadlessCommandContextApi } from '@/command-menu-item/engine-command/hooks/useHeadlessCommandContextApi';
+import { CreateGlobalRecordCommand } from '@/command-menu-item/engine-command/record/no-selection/components/CreateGlobalRecordCommand';
+import { CreateNewIndexRecordNoSelectionRecordCommand } from '@/command-menu-item/engine-command/record/no-selection/components/CreateNewIndexRecordNoSelectionRecordCommand';
+import { getRecordCreationCommandType } from '@/command-menu-item/engine-command/record/no-selection/utils/getRecordCreationCommandType';
+import { useCreateCoreWorkflow } from '@/object-core/workflows/hooks/useCreateCoreWorkflow';
+import { objectMetadataItemsSelector } from '@/object-metadata/states/objectMetadataItemsSelector';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
+import { FeatureFlagKey } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+export const CreateNewRecordCommand = () => {
+ const {
+ objectMetadataItem: contextObjectMetadataItem,
+ recordIndexId,
+ hasAnySoftDeleteFilterOnView,
+ creationTargetObjectMetadataId,
+ } = useHeadlessCommandContextApi();
+ const objectMetadataItems = useAtomStateValue(objectMetadataItemsSelector);
+ const objectMetadataItem = isDefined(creationTargetObjectMetadataId)
+ ? objectMetadataItems.find(
+ (item) => item.id === creationTargetObjectMetadataId,
+ )
+ : contextObjectMetadataItem;
+ const isWorkflowCoreIndexPageEnabled = useIsFeatureEnabled(
+ FeatureFlagKey.IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED,
+ );
+ const { createCoreWorkflow } = useCreateCoreWorkflow();
+
+ if (!isDefined(objectMetadataItem)) {
+ throw new Error('Object metadata item is required to create a record');
+ }
+
+ const commandType = getRecordCreationCommandType({
+ objectNameSingular: objectMetadataItem.nameSingular,
+ contextObjectMetadataId: contextObjectMetadataItem?.id,
+ recordIndexId,
+ hasAnySoftDeleteFilterOnView,
+ creationTargetObjectMetadataId,
+ isWorkflowCoreIndexPageEnabled,
+ });
+
+ if (commandType === 'workflow') {
+ return <HeadlessEngineCommandWrapperEffect execute={createCoreWorkflow} />;
+ }
+
+ return commandType === 'global' ? (
+ <CreateGlobalRecordCommand objectMetadataItem={objectMetadataItem} />
+ ) : (
+ <CreateNewIndexRecordNoSelectionRecordCommand />
+ );
+};
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/utils/getRecordCreationCommandType.ts b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/utils/getRecordCreationCommandType.ts
new file mode 100644
index 00000000000..f3c5f324350
--- /dev/null
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/utils/getRecordCreationCommandType.ts
@@ -0,0 +1,35 @@
+import { CoreObjectNameSingular } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+export const getRecordCreationCommandType = ({
+ objectNameSingular,
+ creationTargetObjectMetadataId,
+ isWorkflowCoreIndexPageEnabled,
+ contextObjectMetadataId,
+ recordIndexId,
+ hasAnySoftDeleteFilterOnView = false,
+}: {
+ objectNameSingular: string;
+ hasAnySoftDeleteFilterOnView?: boolean;
+ contextObjectMetadataId?: string | null;
+ recordIndexId?: string | null;
+ creationTargetObjectMetadataId?: string | null;
+ isWorkflowCoreIndexPageEnabled: boolean;
+}): 'workflow' | 'global' | 'index' => {
+ if (
+ isWorkflowCoreIndexPageEnabled &&
+ objectNameSingular === CoreObjectNameSingular.Workflow
+ ) {
+ return 'workflow';
+ }
+
+ if (!isDefined(creationTargetObjectMetadataId)) {
+ return 'index';
+ }
+
+ return creationTargetObjectMetadataId === contextObjectMetadataId &&
+ isDefined(recordIndexId) &&
+ !hasAnySoftDeleteFilterOnView
+ ? 'index'
+ : 'global';
+};
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/utils/getRecordCreationCommandType.util.spec.ts b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/utils/getRecordCreationCommandType.util.spec.ts
new file mode 100644
index 00000000000..d6a5de50fa1
--- /dev/null
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/no-selection/utils/getRecordCreationCommandType.util.spec.ts
@@ -0,0 +1,99 @@
+// oxlint-disable twenty/folder-structure -- Utility specs intentionally live beside their implementation.
+import { getRecordCreationCommandType } from '@/command-menu-item/engine-command/record/no-selection/utils/getRecordCreationCommandType';
+
+it.each([
+ {
+ objectNameSingular: 'company',
+ creationTargetObjectMetadataId: 'company-id',
+ isWorkflowCoreIndexPageEnabled: false,
+ expected: 'global',
+ },
+ {
+ objectNameSingular: 'task',
+ creationTargetObjectMetadataId: 'task-id',
+ isWorkflowCoreIndexPageEnabled: true,
+ expected: 'global',
+ },
+ {
+ objectNameSingular: 'company',
+ creationTargetObjectMetadataId: null,
+ isWorkflowCoreIndexPageEnabled: true,
+ expected: 'index',
+ },
+ {
+ objectNameSingular: 'task',
+ creationTargetObjectMetadataId: undefined,
+ isWorkflowCoreIndexPageEnabled: false,
+ expected: 'index',
+ },
+ {
+ objectNameSingular: 'workflow',
+ creationTargetObjectMetadataId: 'workflow-id',
+ isWorkflowCoreIndexPageEnabled: true,
+ expected: 'workflow',
+ },
+ {
+ objectNameSingular: 'workflow',
+ creationTargetObjectMetadataId: null,
+ isWorkflowCoreIndexPageEnabled: true,
+ expected: 'workflow',
+ },
+ {
+ objectNameSingular: 'workflow',
+ creationTargetObjectMetadataId: 'workflow-id',
+ isWorkflowCoreIndexPageEnabled: false,
+ expected: 'global',
+ },
+ {
+ objectNameSingular: 'workflow',
+ creationTargetObjectMetadataId: null,
+ isWorkflowCoreIndexPageEnabled: false,
+ expected: 'index',
+ },
+])('dispatches record creation to $expected: %j', ({ expected, ...params }) => {
+ expect(getRecordCreationCommandType(params)).toBe(expected);
+});
+
+it.each([
+ {
+ contextObjectMetadataId: 'company-id',
+ recordIndexId: 'company-index',
+ expected: 'index',
+ },
+ {
+ contextObjectMetadataId: 'task-id',
+ recordIndexId: 'task-index',
+ expected: 'global',
+ },
+ {
+ contextObjectMetadataId: 'company-id',
+ recordIndexId: null,
+ expected: 'global',
+ },
+ { contextObjectMetadataId: null, recordIndexId: null, expected: 'global' },
+])(
+ 'uses $expected creation for the available index context: %j',
+ ({ expected, ...context }) => {
+ expect(
+ getRecordCreationCommandType({
+ objectNameSingular: 'company',
+ creationTargetObjectMetadataId: 'company-id',
+ isWorkflowCoreIndexPageEnabled: false,
+ ...context,
+ }),
+ ).toBe(expected);
+ },
+);
+
+it('uses global creation for the current object in a trash view', () => {
+ expect(
+ getRecordCreationCommandType({
+ objectNameSingular: 'company',
+ contextObjectMetadataId: 'company-id',
+ creationTargetObjectMetadataId: 'company-id',
+ recordIndexId: 'company-index',
+ hasAnySoftDeleteFilterOnView: true,
+ isWorkflowCoreIndexPageEnabled: false,
+ }),
+ ).toBe('global');
+});
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/types/HeadlessCommandContextApi.ts b/packages/twenty-front/src/modules/command-menu-item/engine-command/types/HeadlessCommandContextApi.ts
index aa252659342..a39c15c996c 100644
--- a/packages/twenty-front/src/modules/command-menu-item/engine-command/types/HeadlessCommandContextApi.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/types/HeadlessCommandContextApi.ts
@@ -18,11 +18,13 @@ export type HeadlessEngineCommandContextApi = {
objectMetadataItem: Nullable<EnrichedObjectMetadataItem>;
currentViewId: Nullable<string>;
recordIndexId: Nullable<string>;
+ hasAnySoftDeleteFilterOnView?: boolean;
targetedRecordsRule: ContextStoreTargetedRecordsRule;
selectedRecords: ObjectRecord[];
graphqlFilter: Nullable<RecordGqlOperationFilter>;
payload: Nullable<CommandMenuItemPayload>;
navigationTargetObjectMetadataId: Nullable<string>;
+ creationTargetObjectMetadataId?: string;
isInSidePanel?: boolean;
};
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/utils/buildHeadlessCommandContextApi.ts b/packages/twenty-front/src/modules/command-menu-item/engine-command/utils/buildHeadlessCommandContextApi.ts
index ecc75d8f21b..21e4fc8d4c4 100644
--- a/packages/twenty-front/src/modules/command-menu-item/engine-command/utils/buildHeadlessCommandContextApi.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/utils/buildHeadlessCommandContextApi.ts
@@ -1,3 +1,4 @@
+import { isRecordFilterAboutSoftDelete } from '@/object-record/record-filter/utils/isRecordFilterAboutSoftDelete';
import type { Store } from 'jotai/vanilla/store';
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
@@ -26,6 +27,7 @@ export const buildHeadlessCommandContextApi = ({
engineComponentKey,
payload,
navigationTargetObjectMetadataId,
+ creationTargetObjectMetadataId,
isInSidePanel,
}: {
store: Store;
@@ -33,6 +35,7 @@ export const buildHeadlessCommandContextApi = ({
engineComponentKey: EngineComponentKey;
payload?: CommandMenuItemPayload | null;
navigationTargetObjectMetadataId?: string | null;
+ creationTargetObjectMetadataId?: string;
isInSidePanel?: boolean;
}): HeadlessEngineCommandContextApi => {
const objectMetadataItemId = store.get(
@@ -123,6 +126,9 @@ export const buildHeadlessCommandContextApi = ({
return {
engineComponentKey,
+ hasAnySoftDeleteFilterOnView: filters.some((recordFilter) =>
+ isRecordFilterAboutSoftDelete({ recordFilter, objectMetadataItems }),
+ ),
contextStoreInstanceId,
objectMetadataItem: objectMetadataItem ?? null,
currentViewId,
@@ -132,6 +138,7 @@ export const buildHeadlessCommandContextApi = ({
graphqlFilter,
payload: payload ?? null,
navigationTargetObjectMetadataId: navigationTargetObjectMetadataId ?? null,
+ creationTargetObjectMetadataId,
isInSidePanel: isInSidePanel ?? false,
};
};
diff --git a/packages/twenty-front/src/modules/command-menu-item/hooks/useCommandMenuItemClick.ts b/packages/twenty-front/src/modules/command-menu-item/hooks/useCommandMenuItemClick.ts
index 415c0306558..ee252628e23 100644
--- a/packages/twenty-front/src/modules/command-menu-item/hooks/useCommandMenuItemClick.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/hooks/useCommandMenuItemClick.ts
@@ -1,3 +1,4 @@
+import { type CommandMenuItemDefinition } from '@/command-menu-item/types/CommandMenuItemDefinition';
import { CommandMenuContext } from '@/command-menu-item/contexts/CommandMenuContext';
import { useMountCommand } from '@/command-menu-item/engine-command/hooks/useMountCommand';
import { isPathCommandMenuItemPayload } from '@/command-menu-item/engine-command/utils/isPathCommandMenuItemPayload';
@@ -12,14 +13,13 @@ import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAto
import { useContext } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { type IconComponent } from 'twenty-ui/icon';
-import { type CommandMenuItemFieldsFragment } from '~/generated-metadata/graphql';
export const useCommandMenuItemClick = ({
item,
Icon,
label,
}: {
- item: CommandMenuItemFieldsFragment;
+ item: CommandMenuItemDefinition;
Icon: IconComponent;
label: string;
}) => {
@@ -86,6 +86,7 @@ export const useCommandMenuItemClick = ({
? item.payload
: undefined,
navigationTargetObjectMetadataId: item.navigationTargetObjectMetadataId,
+ creationTargetObjectMetadataId: item.creationTargetObjectMetadataId,
isInSidePanel: commandMenuContextApi.isInSidePanel,
});
diff --git a/packages/twenty-front/src/modules/command-menu-item/hooks/useGlobalRecordCreationCommandMenuItems.ts b/packages/twenty-front/src/modules/command-menu-item/hooks/useGlobalRecordCreationCommandMenuItems.ts
new file mode 100644
index 00000000000..fee1c2847cb
--- /dev/null
+++ b/packages/twenty-front/src/modules/command-menu-item/hooks/useGlobalRecordCreationCommandMenuItems.ts
@@ -0,0 +1,52 @@
+import { buildGlobalRecordCreationCommandMenuItems } from '@/command-menu-item/utils/buildGlobalRecordCreationCommandMenuItems';
+import { type CommandMenuItemDefinition } from '@/command-menu-item/types/CommandMenuItemDefinition';
+import { useFilteredObjectMetadataItems } from '@/object-metadata/hooks/useFilteredObjectMetadataItems';
+import { useObjectPermissions } from '@/object-record/hooks/useObjectPermissions';
+import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
+import { useLingui } from '@lingui/react/macro';
+import { useMemo } from 'react';
+import { FeatureFlagKey } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { EngineComponentKey } from '~/generated-metadata/graphql';
+
+export const useGlobalRecordCreationCommandMenuItems = (
+ commandMenuItems: CommandMenuItemDefinition[],
+) => {
+ const { t } = useLingui();
+ const isRecordCreationFormEnabled = useIsFeatureEnabled(
+ FeatureFlagKey.IS_RECORD_CREATION_FORM_ENABLED,
+ );
+ const { activeObjectMetadataItems } = useFilteredObjectMetadataItems();
+ const { objectPermissionsByObjectMetadataId } = useObjectPermissions();
+ const createRecordCommand = commandMenuItems.find(
+ (item) =>
+ item.engineComponentKey === EngineComponentKey.CREATE_NEW_RECORD &&
+ !isDefined(item.availabilityObjectMetadataId),
+ );
+
+ const hasGlobalRecordCreationCommandTemplate = isDefined(createRecordCommand);
+ const globalRecordCreationCommandMenuItems = useMemo(() => {
+ if (!isRecordCreationFormEnabled || !isDefined(createRecordCommand)) {
+ return [];
+ }
+
+ return buildGlobalRecordCreationCommandMenuItems({
+ activeObjectMetadataItems,
+ objectPermissionsByObjectMetadataId,
+ createRecordCommand,
+ getLabel: (objectLabelSingular) => t`Create ${objectLabelSingular}`,
+ });
+ }, [
+ isRecordCreationFormEnabled,
+ createRecordCommand,
+ activeObjectMetadataItems,
+ objectPermissionsByObjectMetadataId,
+ t,
+ ]);
+
+ return {
+ isRecordCreationFormEnabled,
+ hasGlobalRecordCreationCommandTemplate,
+ globalRecordCreationCommandMenuItems,
+ };
+};
diff --git a/packages/twenty-front/src/modules/command-menu-item/types/CommandMenuItemDefinition.ts b/packages/twenty-front/src/modules/command-menu-item/types/CommandMenuItemDefinition.ts
new file mode 100644
index 00000000000..26c5b9066b3
--- /dev/null
+++ b/packages/twenty-front/src/modules/command-menu-item/types/CommandMenuItemDefinition.ts
@@ -0,0 +1,5 @@
+import { type CommandMenuItemFieldsFragment } from '~/generated-metadata/graphql';
+
+export type CommandMenuItemDefinition = CommandMenuItemFieldsFragment & {
+ creationTargetObjectMetadataId?: string;
+};
diff --git a/packages/twenty-front/src/modules/command-menu-item/utils/buildGlobalRecordCreationCommandMenuItems.ts b/packages/twenty-front/src/modules/command-menu-item/utils/buildGlobalRecordCreationCommandMenuItems.ts
new file mode 100644
index 00000000000..a0948ecd7fc
--- /dev/null
+++ b/packages/twenty-front/src/modules/command-menu-item/utils/buildGlobalRecordCreationCommandMenuItems.ts
@@ -0,0 +1,68 @@
+import { type CommandMenuItemDefinition } from '@/command-menu-item/types/CommandMenuItemDefinition';
+import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
+import { getObjectPermissionsForObject } from '@/object-metadata/utils/getObjectPermissionsForObject';
+import { canCreateRecordsForObjectMetadataItem } from '@/object-record/utils/canCreateRecordsForObjectMetadataItem';
+import { type ObjectPermissions } from 'twenty-shared/types';
+import { capitalize } from 'twenty-shared/utils';
+import { CommandMenuItemAvailabilityType } from '~/generated-metadata/graphql';
+
+type BuildGlobalRecordCreationCommandMenuItemsParams = {
+ activeObjectMetadataItems: Pick<
+ EnrichedObjectMetadataItem,
+ | 'id'
+ | 'labelSingular'
+ | 'icon'
+ | 'isUICreatable'
+ | 'isUIEditable'
+ | 'isRemote'
+ | 'writability'
+ >[];
+ objectPermissionsByObjectMetadataId: Record<
+ string,
+ ObjectPermissions & { objectMetadataId: string }
+ >;
+ createRecordCommand: CommandMenuItemDefinition;
+ getLabel: (objectLabelSingular: string) => string;
+};
+
+export const buildGlobalRecordCreationCommandMenuItems = ({
+ activeObjectMetadataItems,
+ objectPermissionsByObjectMetadataId,
+ createRecordCommand,
+ getLabel,
+}: BuildGlobalRecordCreationCommandMenuItemsParams): CommandMenuItemDefinition[] => {
+ return activeObjectMetadataItems
+ .filter((objectMetadataItem) => {
+ const permissions = getObjectPermissionsForObject(
+ objectPermissionsByObjectMetadataId,
+ objectMetadataItem.id,
+ );
+
+ return (
+ permissions.canReadObjectRecords &&
+ canCreateRecordsForObjectMetadataItem({
+ objectMetadataItem,
+ objectPermissions: permissions,
+ })
+ );
+ })
+ .map((objectMetadataItem): CommandMenuItemDefinition => {
+ const objectLabelSingular = capitalize(objectMetadataItem.labelSingular);
+
+ return {
+ ...createRecordCommand,
+ id: `${createRecordCommand.id}-${objectMetadataItem.id}`,
+ label: getLabel(objectLabelSingular),
+ icon: objectMetadataItem.icon,
+ shortLabel: null,
+ isPinned: false,
+ hotKeys: null,
+ availabilityType: CommandMenuItemAvailabilityType.GLOBAL,
+ availabilityObjectMetadataId: null,
+ conditionalAvailabilityExpression: null,
+ conditionalPinnedExpression: null,
+ navigationTargetObjectMetadataId: null,
+ creationTargetObjectMetadataId: objectMetadataItem.id,
+ };
+ });
+};
diff --git a/packages/twenty-front/src/modules/command-menu-item/utils/buildGlobalRecordCreationCommandMenuItems.util.spec.ts b/packages/twenty-front/src/modules/command-menu-item/utils/buildGlobalRecordCreationCommandMenuItems.util.spec.ts
new file mode 100644
index 00000000000..785e7d2e39b
--- /dev/null
+++ b/packages/twenty-front/src/modules/command-menu-item/utils/buildGlobalRecordCreationCommandMenuItems.util.spec.ts
@@ -0,0 +1,84 @@
+// oxlint-disable twenty/folder-structure -- Utility specs intentionally live beside their implementation.
+import { buildGlobalRecordCreationCommandMenuItems } from '@/command-menu-item/utils/buildGlobalRecordCreationCommandMenuItems';
+import { getObjectPermissionsForObject } from '@/object-metadata/utils/getObjectPermissionsForObject';
+import {
+ EngineComponentKey,
+ MetadataWritability,
+} from '~/generated-metadata/graphql';
+import { mockedCommandMenuItems } from '~/testing/mock-data/generated/metadata/command-menu-items/mock-command-menu-items-data';
+
+const createRecordCommand = mockedCommandMenuItems.find(
+ (item) =>
+ item.engineComponentKey === EngineComponentKey.CREATE_NEW_RECORD &&
+ !item.availabilityObjectMetadataId,
+)!;
+
+const objects = [
+ { id: 'company', labelSingular: 'company', icon: 'IconBuildingSkyscraper' },
+ { id: 'task', labelSingular: 'task', icon: 'IconCheckbox' },
+ { id: 'remote', labelSingular: 'remote', isRemote: true },
+ { id: 'readonly', labelSingular: 'readonly', isUIEditable: false },
+ { id: 'internal', labelSingular: 'internal', isUICreatable: false },
+ {
+ id: 'system',
+ labelSingular: 'system',
+ writability: MetadataWritability.SYSTEM,
+ },
+ {
+ id: 'application',
+ labelSingular: 'application',
+ writability: MetadataWritability.APPLICATION,
+ },
+].map((objectMetadataItem) => ({
+ icon: null,
+ writability: MetadataWritability.OPEN,
+ isUICreatable: true,
+ isUIEditable: true,
+ isRemote: false,
+ ...objectMetadataItem,
+}));
+
+it('offers every creatable object with its label, icon, and creation target', () => {
+ const items = buildGlobalRecordCreationCommandMenuItems({
+ activeObjectMetadataItems: objects,
+ objectPermissionsByObjectMetadataId: {},
+ createRecordCommand,
+ getLabel: (label) => `Create ${label}`,
+ });
+
+ expect(items).toEqual([
+ expect.objectContaining({
+ label: 'Create Company',
+ icon: 'IconBuildingSkyscraper',
+ creationTargetObjectMetadataId: 'company',
+ isPinned: false,
+ }),
+ expect.objectContaining({
+ label: 'Create Task',
+ icon: 'IconCheckbox',
+ creationTargetObjectMetadataId: 'task',
+ isPinned: false,
+ }),
+ ]);
+ expect(new Set(items.map((item) => item.id)).size).toBe(2);
+});
+
+it('does not offer objects without read or write permissions', () => {
+ const items = buildGlobalRecordCreationCommandMenuItems({
+ activeObjectMetadataItems: objects,
+ objectPermissionsByObjectMetadataId: {
+ company: {
+ ...getObjectPermissionsForObject({}, 'company'),
+ canUpdateObjectRecords: false,
+ },
+ task: {
+ ...getObjectPermissionsForObject({}, 'task'),
+ canReadObjectRecords: false,
+ },
+ },
+ createRecordCommand,
+ getLabel: (label) => `Create ${label}`,
+ });
+
+ expect(items).toEqual([]);
+});
diff --git a/packages/twenty-front/src/modules/command-menu-item/utils/mergeGlobalRecordCreationCommandMenuItems.ts b/packages/twenty-front/src/modules/command-menu-item/utils/mergeGlobalRecordCreationCommandMenuItems.ts
new file mode 100644
index 00000000000..2863ae161e6
--- /dev/null
+++ b/packages/twenty-front/src/modules/command-menu-item/utils/mergeGlobalRecordCreationCommandMenuItems.ts
@@ -0,0 +1,32 @@
+import { type CommandMenuItemDefinition } from '@/command-menu-item/types/CommandMenuItemDefinition';
+import { EngineComponentKey } from '~/generated-metadata/graphql';
+
+export const mergeGlobalRecordCreationCommandMenuItems = ({
+ commandMenuItems,
+ globalRecordCreationCommandMenuItems,
+ shouldDisplayGlobalRecordCreationCommands,
+}: {
+ commandMenuItems: CommandMenuItemDefinition[];
+ globalRecordCreationCommandMenuItems: CommandMenuItemDefinition[];
+ shouldDisplayGlobalRecordCreationCommands: boolean;
+}): CommandMenuItemDefinition[] => {
+ const sortedCommandMenuItems = [...commandMenuItems].sort(
+ (firstItem, secondItem) => firstItem.position - secondItem.position,
+ );
+
+ if (!shouldDisplayGlobalRecordCreationCommands) {
+ return sortedCommandMenuItems;
+ }
+
+ return [
+ ...sortedCommandMenuItems.filter(
+ (item) =>
+ item.engineComponentKey !== EngineComponentKey.CREATE_NEW_RECORD &&
+ item.engineComponentKey !== EngineComponentKey.NAVIGATION,
+ ),
+ ...globalRecordCreationCommandMenuItems,
+ ...sortedCommandMenuItems.filter(
+ (item) => item.engineComponentKey === EngineComponentKey.NAVIGATION,
+ ),
+ ];
+};
diff --git a/packages/twenty-front/src/modules/command-menu-item/utils/mergeGlobalRecordCreationCommandMenuItems.util.spec.ts b/packages/twenty-front/src/modules/command-menu-item/utils/mergeGlobalRecordCreationCommandMenuItems.util.spec.ts
new file mode 100644
index 00000000000..62f4a8f6c2c
--- /dev/null
+++ b/packages/twenty-front/src/modules/command-menu-item/utils/mergeGlobalRecordCreationCommandMenuItems.util.spec.ts
@@ -0,0 +1,83 @@
+// oxlint-disable twenty/folder-structure -- Utility specs intentionally live beside their implementation.
+import { mergeGlobalRecordCreationCommandMenuItems } from '@/command-menu-item/utils/mergeGlobalRecordCreationCommandMenuItems';
+import { EngineComponentKey } from '~/generated-metadata/graphql';
+import { mockedCommandMenuItems } from '~/testing/mock-data/generated/metadata/command-menu-items/mock-command-menu-items-data';
+
+const template = mockedCommandMenuItems[0];
+const pageCommand = { ...template, id: 'page', position: 20 };
+const navigationCommand = {
+ ...template,
+ id: 'navigation',
+ engineComponentKey: EngineComponentKey.NAVIGATION,
+ position: 10,
+};
+const legacyCreationCommand = {
+ ...template,
+ id: 'legacy-create',
+ engineComponentKey: EngineComponentKey.CREATE_NEW_RECORD,
+ position: 3,
+};
+const commandMenuItems = [
+ pageCommand,
+ navigationCommand,
+ legacyCreationCommand,
+];
+const globalRecordCreationCommandMenuItems = ['company', 'task'].map((id) => ({
+ ...legacyCreationCommand,
+ id: `create-${id}`,
+ creationTargetObjectMetadataId: id,
+}));
+
+it('places global creation after page commands and before navigation, replacing legacy creation', () => {
+ expect(
+ mergeGlobalRecordCreationCommandMenuItems({
+ commandMenuItems,
+ globalRecordCreationCommandMenuItems,
+ shouldDisplayGlobalRecordCreationCommands: true,
+ }),
+ ).toEqual([
+ pageCommand,
+ ...globalRecordCreationCommandMenuItems,
+ navigationCommand,
+ ]);
+ expect(commandMenuItems).toEqual([
+ pageCommand,
+ navigationCommand,
+ legacyCreationCommand,
+ ]);
+});
+
+it('preserves position ordering and legacy creation when global creation is disabled', () => {
+ expect(
+ mergeGlobalRecordCreationCommandMenuItems({
+ commandMenuItems,
+ globalRecordCreationCommandMenuItems,
+ shouldDisplayGlobalRecordCreationCommands: false,
+ }),
+ ).toEqual([legacyCreationCommand, navigationCommand, pageCommand]);
+});
+
+it('hides legacy creation even when no objects are eligible for global creation', () => {
+ expect(
+ mergeGlobalRecordCreationCommandMenuItems({
+ commandMenuItems,
+ globalRecordCreationCommandMenuItems: [],
+ shouldDisplayGlobalRecordCreationCommands: true,
+ }),
+ ).toEqual([pageCommand, navigationCommand]);
+});
+
+it('preserves object-scoped creation when a missing template disables replacement', () => {
+ const objectScopedCreationCommand = {
+ ...legacyCreationCommand,
+ availabilityObjectMetadataId: 'company-id',
+ };
+
+ expect(
+ mergeGlobalRecordCreationCommandMenuItems({
+ commandMenuItems: [pageCommand, objectScopedCreationCommand],
+ globalRecordCreationCommandMenuItems: [],
+ shouldDisplayGlobalRecordCreationCommands: false,
+ }),
+ ).toEqual([objectScopedCreationCommand, pageCommand]);
+});
diff --git a/packages/twenty-front/src/modules/object-record/hooks/useCreateNewRecord.ts b/packages/twenty-front/src/modules/object-record/hooks/useCreateNewRecord.ts
new file mode 100644
index 00000000000..f6ce06500c8
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/hooks/useCreateNewRecord.ts
@@ -0,0 +1,172 @@
+import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
+import { getLabelIdentifierFieldMetadataItem } from '@/object-metadata/utils/getLabelIdentifierFieldMetadataItem';
+import { useBuildRecordInputFromRLSPredicates } from '@/object-record/hooks/useBuildRecordInputFromRLSPredicates';
+import { useRecordCreationForm } from '@/object-record/record-form/hooks/useRecordCreationForm';
+import { useCreateOneRecord } from '@/object-record/hooks/useCreateOneRecord';
+import { getFieldMetadataItemGqlFieldName } from '@/object-metadata/utils/getFieldMetadataItemGqlFieldName';
+import { useResolveOpenRecordIn } from '@/object-record/record-index/hooks/useResolveOpenRecordIn';
+import { useUpsertRecordsInStore } from '@/object-record/record-store/hooks/useUpsertRecordsInStore';
+import { newRecordTitleCellToOpenState } from '@/object-record/record-title-cell/states/newRecordTitleCellToOpenState';
+import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
+import { useOpenRecordInSidePanel } from '@/side-panel/hooks/useOpenRecordInSidePanel';
+import { useSidePanelMenu } from '@/side-panel/hooks/useSidePanelMenu';
+import { useWorkspaceSurface } from '@/ui/layout/hooks/useWorkspaceSurface';
+import { useStore } from 'jotai';
+import { useCallback } from 'react';
+import { AppPath, OpenRecordIn } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { v4 } from 'uuid';
+import { useNavigateApp } from '~/hooks/useNavigateApp';
+
+type UseCreateNewRecordProps = {
+ objectMetadataItem: EnrichedObjectMetadataItem;
+ buildRecordInput?: () => Partial<ObjectRecord>;
+ onRecordCreated?: (
+ record: ObjectRecord,
+ recordInput?: Partial<ObjectRecord>,
+ ) => void;
+};
+
+export const useCreateNewRecord = ({
+ objectMetadataItem,
+ buildRecordInput,
+ onRecordCreated,
+}: UseCreateNewRecordProps) => {
+ const store = useStore();
+
+ const { openRecordInSidePanel } = useOpenRecordInSidePanel();
+ const workspaceSurface = useWorkspaceSurface();
+
+ const openRecordIn = useResolveOpenRecordIn(objectMetadataItem.nameSingular);
+
+ const { closeSidePanelMenu } = useSidePanelMenu();
+
+ const { createOneRecord } = useCreateOneRecord({
+ objectNameSingular: objectMetadataItem.nameSingular,
+ shouldMatchRootQueryFilter: true,
+ });
+
+ const { upsertRecordsInStore } = useUpsertRecordsInStore();
+
+ const { shouldOpenRecordCreationForm, requestRecordCreation } =
+ useRecordCreationForm({ objectMetadataItem });
+
+ const navigate = useNavigateApp();
+
+ const { buildRecordInputFromRLSPredicates } =
+ useBuildRecordInputFromRLSPredicates({
+ objectMetadataItem,
+ });
+
+ const createRecord = useCallback(
+ async (recordInput?: Partial<ObjectRecord>) => {
+ const recordId = v4();
+ const recordInputFromRLSPredicates = buildRecordInputFromRLSPredicates();
+ const additionalRecordInput = buildRecordInput?.();
+
+ const mergedRecordInput = {
+ ...recordInputFromRLSPredicates,
+ ...additionalRecordInput,
+ ...recordInput,
+ };
+
+ const createdRecord = await createOneRecord({
+ id: recordId,
+ ...mergedRecordInput,
+ });
+
+ const labelIdentifierFieldMetadataItem =
+ getLabelIdentifierFieldMetadataItem(objectMetadataItem);
+
+ const shouldOpenLabelIdentifierInEditMode =
+ !isDefined(labelIdentifierFieldMetadataItem) ||
+ !isDefined(
+ recordInput?.[
+ getFieldMetadataItemGqlFieldName(labelIdentifierFieldMetadataItem)
+ ],
+ );
+
+ if (workspaceSurface.type === 'side-panel') {
+ openRecordInSidePanel({
+ recordId,
+ objectNameSingular: objectMetadataItem.nameSingular,
+ isNewRecord: shouldOpenLabelIdentifierInEditMode,
+ resetNavigationStack: false,
+ });
+ } else if (openRecordIn === OpenRecordIn.SIDE_PANEL) {
+ openRecordInSidePanel({
+ recordId,
+ objectNameSingular: objectMetadataItem.nameSingular,
+ isNewRecord: shouldOpenLabelIdentifierInEditMode,
+ });
+ } else {
+ if (
+ shouldOpenLabelIdentifierInEditMode &&
+ isDefined(labelIdentifierFieldMetadataItem)
+ ) {
+ store.set(newRecordTitleCellToOpenState.atom, {
+ recordId,
+ fieldName: labelIdentifierFieldMetadataItem.name,
+ });
+ }
+
+ closeSidePanelMenu();
+ navigate(AppPath.RecordShowPage, {
+ objectNameSingular: objectMetadataItem.nameSingular,
+ objectRecordId: recordId,
+ });
+ }
+
+ onRecordCreated?.(createdRecord, recordInput);
+
+ upsertRecordsInStore({ partialRecords: [createdRecord] });
+
+ return createdRecord;
+ },
+ [
+ store,
+ buildRecordInputFromRLSPredicates,
+ buildRecordInput,
+ onRecordCreated,
+ createOneRecord,
+ navigate,
+ objectMetadataItem,
+ openRecordInSidePanel,
+ openRecordIn,
+ upsertRecordsInStore,
+ closeSidePanelMenu,
+ workspaceSurface.type,
+ ],
+ );
+
+ const createNewRecord = useCallback(
+ async (recordInput?: Partial<ObjectRecord>) => {
+ if (!shouldOpenRecordCreationForm) {
+ return createRecord(recordInput);
+ }
+
+ const createdRecord = await requestRecordCreation({
+ initialDraftRecord: {
+ ...buildRecordInputFromRLSPredicates(),
+ ...buildRecordInput?.(),
+ ...recordInput,
+ },
+ createRecord: (draftRecord) =>
+ createRecord({ ...recordInput, ...draftRecord }),
+ });
+
+ return createdRecord ?? undefined;
+ },
+ [
+ buildRecordInputFromRLSPredicates,
+ buildRecordInput,
+ createRecord,
+ requestRecordCreation,
+ shouldOpenRecordCreationForm,
+ ],
+ );
+
+ return {
+ createNewRecord,
+ };
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-table/hooks/useCreateNewIndexRecord.ts b/packages/twenty-front/src/modules/object-record/record-table/hooks/useCreateNewIndexRecord.ts
index 108245cb264..994e0546aab 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/hooks/useCreateNewIndexRecord.ts
+++ b/packages/twenty-front/src/modules/object-record/record-table/hooks/useCreateNewIndexRecord.ts
@@ -1,29 +1,17 @@
import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
-import { getLabelIdentifierFieldMetadataItem } from '@/object-metadata/utils/getLabelIdentifierFieldMetadataItem';
-import { useBuildRecordInputFromRLSPredicates } from '@/object-record/hooks/useBuildRecordInputFromRLSPredicates';
-import { useRecordCreationForm } from '@/object-record/record-form/hooks/useRecordCreationForm';
-import { useCreateOneRecord } from '@/object-record/hooks/useCreateOneRecord';
-import { recordGroupDefinitionsComponentSelector } from '@/object-record/record-group/states/selectors/recordGroupDefinitionsComponentSelector';
import { getFieldMetadataItemGqlFieldName } from '@/object-metadata/utils/getFieldMetadataItemGqlFieldName';
+import { useCreateNewRecord } from '@/object-record/hooks/useCreateNewRecord';
+import { recordGroupDefinitionsComponentSelector } from '@/object-record/record-group/states/selectors/recordGroupDefinitionsComponentSelector';
import { recordIndexGroupFieldMetadataItemComponentState } from '@/object-record/record-index/states/recordIndexGroupFieldMetadataComponentState';
-import { useResolveOpenRecordIn } from '@/object-record/record-index/hooks/useResolveOpenRecordIn';
import { recordIndexRecordIdsByGroupComponentFamilyState } from '@/object-record/record-index/states/recordIndexRecordIdsByGroupComponentFamilyState';
-import { useUpsertRecordsInStore } from '@/object-record/record-store/hooks/useUpsertRecordsInStore';
import { useBuildRecordInputFromFilters } from '@/object-record/record-table/hooks/useBuildRecordInputFromFilters';
-import { newRecordTitleCellToOpenState } from '@/object-record/record-title-cell/states/newRecordTitleCellToOpenState';
import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
-import { useOpenRecordInSidePanel } from '@/side-panel/hooks/useOpenRecordInSidePanel';
-import { useSidePanelMenu } from '@/side-panel/hooks/useSidePanelMenu';
-import { useWorkspaceSurface } from '@/ui/layout/hooks/useWorkspaceSurface';
import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';
import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';
import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';
import { useStore } from 'jotai';
import { useCallback } from 'react';
-import { AppPath, OpenRecordIn } from 'twenty-shared/types';
import { findByProperty, isDefined } from 'twenty-shared/utils';
-import { v4 } from 'uuid';
-import { useNavigateApp } from '~/hooks/useNavigateApp';
type UseCreateNewIndexRecordProps = {
objectMetadataItem: EnrichedObjectMetadataItem;
@@ -51,94 +39,13 @@ export const useCreateNewIndexRecord = ({
instanceId,
);
- const { openRecordInSidePanel } = useOpenRecordInSidePanel();
- const workspaceSurface = useWorkspaceSurface();
-
- const openRecordIn = useResolveOpenRecordIn(objectMetadataItem.nameSingular);
-
- const { closeSidePanelMenu } = useSidePanelMenu();
-
- const { createOneRecord } = useCreateOneRecord({
- objectNameSingular: objectMetadataItem.nameSingular,
- shouldMatchRootQueryFilter: true,
- });
-
- const { upsertRecordsInStore } = useUpsertRecordsInStore();
-
- const { shouldOpenRecordCreationForm, requestRecordCreation } =
- useRecordCreationForm({ objectMetadataItem });
-
- const navigate = useNavigateApp();
-
const { buildRecordInputFromFilters } = useBuildRecordInputFromFilters({
objectMetadataItem,
instanceId,
});
- const { buildRecordInputFromRLSPredicates } =
- useBuildRecordInputFromRLSPredicates({
- objectMetadataItem,
- });
-
- const createIndexRecord = useCallback(
- async (recordInput?: Partial<ObjectRecord>) => {
- const recordId = v4();
- const recordInputFromRLSPredicates = buildRecordInputFromRLSPredicates();
- const recordInputFromFilters = buildRecordInputFromFilters();
-
- const mergedRecordInput = {
- ...recordInputFromRLSPredicates,
- ...recordInputFromFilters,
- ...recordInput,
- };
-
- const createdRecord = await createOneRecord({
- id: recordId,
- ...mergedRecordInput,
- });
-
- const labelIdentifierFieldMetadataItem =
- getLabelIdentifierFieldMetadataItem(objectMetadataItem);
-
- const shouldOpenLabelIdentifierInEditMode =
- !isDefined(labelIdentifierFieldMetadataItem) ||
- !isDefined(
- recordInput?.[
- getFieldMetadataItemGqlFieldName(labelIdentifierFieldMetadataItem)
- ],
- );
-
- if (workspaceSurface.type === 'side-panel') {
- openRecordInSidePanel({
- recordId,
- objectNameSingular: objectMetadataItem.nameSingular,
- isNewRecord: shouldOpenLabelIdentifierInEditMode,
- resetNavigationStack: false,
- });
- } else if (openRecordIn === OpenRecordIn.SIDE_PANEL) {
- openRecordInSidePanel({
- recordId,
- objectNameSingular: objectMetadataItem.nameSingular,
- isNewRecord: shouldOpenLabelIdentifierInEditMode,
- });
- } else {
- if (
- shouldOpenLabelIdentifierInEditMode &&
- isDefined(labelIdentifierFieldMetadataItem)
- ) {
- store.set(newRecordTitleCellToOpenState.atom, {
- recordId,
- fieldName: labelIdentifierFieldMetadataItem.name,
- });
- }
-
- closeSidePanelMenu();
- navigate(AppPath.RecordShowPage, {
- objectNameSingular: objectMetadataItem.nameSingular,
- objectRecordId: recordId,
- });
- }
-
+ const onRecordCreated = useCallback(
+ (createdRecord: ObjectRecord, recordInput?: Partial<ObjectRecord>) => {
if (isDefined(recordIndexGroupFieldMetadataItem)) {
const recordGroup = recordGroupDefinitions.find(
findByProperty(
@@ -173,47 +80,20 @@ export const useCreateNewIndexRecord = ({
}
}
}
-
- upsertRecordsInStore({ partialRecords: [createdRecord] });
-
- return createdRecord;
},
[
store,
- buildRecordInputFromRLSPredicates,
- buildRecordInputFromFilters,
- createOneRecord,
- navigate,
- objectMetadataItem,
- openRecordInSidePanel,
- openRecordIn,
recordGroupDefinitions,
recordIndexGroupFieldMetadataItem,
recordIndexRecordIdsByGroupCallbackState,
- upsertRecordsInStore,
- closeSidePanelMenu,
- workspaceSurface.type,
],
);
- const createNewIndexRecord = useCallback(
- async (recordInput?: Partial<ObjectRecord>) => {
- if (!shouldOpenRecordCreationForm) {
- return createIndexRecord(recordInput);
- }
-
- const createdRecord = await requestRecordCreation({
- initialDraftRecord: recordInput,
- createRecord: (draftRecord) =>
- createIndexRecord({ ...recordInput, ...draftRecord }),
- });
-
- return createdRecord ?? undefined;
- },
- [createIndexRecord, requestRecordCreation, shouldOpenRecordCreationForm],
- );
+ const { createNewRecord } = useCreateNewRecord({
+ objectMetadataItem,
+ buildRecordInput: buildRecordInputFromFilters,
+ onRecordCreated,
+ });
- return {
- createNewIndexRecord,
- };
+ return { createNewIndexRecord: createNewRecord };
};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/__stories__/RecordCreationFlow.stories.tsx b/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/__stories__/RecordCreationFlow.stories.tsx
new file mode 100644
index 00000000000..1aeba45e57c
--- /dev/null
+++ b/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/__stories__/RecordCreationFlow.stories.tsx
@@ -0,0 +1,428 @@
+import { CommandMenuComponentInstanceContext } from '@/command-menu/states/contexts/CommandMenuComponentInstanceContext';
+import { CommandMenuContext } from '@/command-menu-item/contexts/CommandMenuContext';
+import { CommandMenuContextProvider } from '@/command-menu-item/contexts/CommandMenuContextProvider';
+import { CommandMenuItemRenderer } from '@/command-menu-item/display/components/CommandMenuItemRenderer';
+import { CommandRunner } from '@/command-menu-item/engine-command/components/CommandRunner';
+import { CommandMenuItemContainerType } from '@/command-menu-item/types/CommandMenuItemContainerType';
+import { MAIN_CONTEXT_STORE_INSTANCE_ID } from '@/context-store/constants/MainContextStoreInstanceId';
+import { ContextStoreComponentInstanceContext } from '@/context-store/states/contexts/ContextStoreComponentInstanceContext';
+import { contextStoreCurrentObjectMetadataItemIdComponentState } from '@/context-store/states/contextStoreCurrentObjectMetadataItemIdComponentState';
+import { contextStoreCurrentViewIdComponentState } from '@/context-store/states/contextStoreCurrentViewIdComponentState';
+import { SelectableList } from '@/ui/layout/selectable-list/components/SelectableList';
+import { mockedCommandMenuItems } from '~/testing/mock-data/generated/metadata/command-menu-items/mock-command-menu-items-data';
+import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
+import { WorkspaceRouteObjectsContext } from '@/app/routing/components/WorkspaceRouteObjectsProvider';
+import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
+import { useUpdateMetadataStoreDraft } from '@/metadata-store/hooks/useUpdateMetadataStoreDraft';
+import { useObjectMetadataItem } from '@/object-metadata/hooks/useObjectMetadataItem';
+import { useCreateNewRecord } from '@/object-record/hooks/useCreateNewRecord';
+import { RecordCreationFormProvider } from '@/object-record/record-form/components/RecordCreationFormProvider';
+import { recordStoreFamilyState } from '@/object-record/record-store/states/recordStoreFamilyState';
+import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
+import { useSidePanelHistory } from '@/side-panel/hooks/useSidePanelHistory';
+import { SidePanelRecordCreationFormPage } from '@/side-panel/pages/record-creation-form/components/SidePanelRecordCreationFormPage';
+import { SidePanelPageComponentInstanceContext } from '@/side-panel/states/contexts/SidePanelPageComponentInstanceContext';
+import { isSidePanelOpenedState } from '@/side-panel/states/isSidePanelOpenedState';
+import { sidePanelNavigationStackState } from '@/side-panel/states/sidePanelNavigationStackState';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { useStore } from 'jotai';
+import { graphql, HttpResponse } from 'msw';
+import { useContext, useEffect, useState } from 'react';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+import { AppPath, OpenRecordIn, SidePanelPages } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { Button } from 'twenty-ui/primitives/input';
+import { ComponentDecorator, RouterDecorator } from 'twenty-ui/testing';
+import {
+ EngineComponentKey,
+ FeatureFlagKey,
+ PageLayoutTabLayoutMode,
+ PageLayoutType,
+ WidgetConfigurationType,
+ WidgetType,
+} from '~/generated-metadata/graphql';
+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';
+import { ToastDecorator } from '~/testing/decorators/ToastDecorator';
+import { graphqlMocks } from '~/testing/graphqlMocks';
+import { mockedCompanyRecords } from '~/testing/mock-data/generated/data/companies/mock-companies-data';
+import { mockCurrentWorkspace } from '~/testing/mock-data/users';
+
+const createCompanyRequest = fn();
+const onRecordCreated = fn();
+const LAYOUT_ID = 'record-creation-story-layout';
+const TAB_ID = 'record-creation-story-tab';
+
+type RecordCreationFlowProps = {
+ isFormEnabled: boolean;
+ commandOrigin?: 'task' | 'no-object';
+};
+
+const RecordCreationFlow = ({
+ isFormEnabled,
+ commandOrigin,
+}: RecordCreationFlowProps) => {
+ const store = useStore();
+ const { objectMetadataItem } = useObjectMetadataItem({
+ objectNameSingular: 'company',
+ });
+ const { replaceDraft, applyChanges } = useUpdateMetadataStoreDraft();
+ const [isReady, setIsReady] = useState(false);
+
+ useEffect(() => {
+ const nameField = objectMetadataItem.fields.find(
+ (field) => field.name === 'name',
+ );
+ if (!isDefined(nameField)) {
+ throw new Error('Company name field is required for the creation story');
+ }
+ const metadata = {
+ applicationId: '',
+ isSystemSideEffect: false,
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ deletedAt: null,
+ };
+ replaceDraft('pageLayouts', [
+ {
+ ...metadata,
+ id: LAYOUT_ID,
+ universalIdentifier: LAYOUT_ID,
+ name: 'Company creation',
+ type: PageLayoutType.RECORD_FORM,
+ objectMetadataId: objectMetadataItem.id,
+ isFirstTabPinned: false,
+ },
+ ]);
+ replaceDraft('pageLayoutTabs', [
+ {
+ ...metadata,
+ id: TAB_ID,
+ universalIdentifier: TAB_ID,
+ pageLayoutId: LAYOUT_ID,
+ title: 'Fields',
+ isActive: true,
+ position: 0,
+ layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,
+ },
+ ]);
+ replaceDraft('pageLayoutWidgets', [
+ {
+ ...metadata,
+ id: 'company-name-widget',
+ universalIdentifier: 'company-name-widget',
+ pageLayoutTabId: TAB_ID,
+ title: 'Name',
+ isActive: true,
+ type: WidgetType.FORM_FIELD,
+ objectMetadataId: objectMetadataItem.id,
+ configuration: {
+ configurationType: WidgetConfigurationType.FORM_FIELD,
+ fieldMetadataId: nameField.id,
+ },
+ },
+ ]);
+ if (isDefined(commandOrigin)) {
+ const template = mockedCommandMenuItems.find(
+ (item) =>
+ item.engineComponentKey === EngineComponentKey.CREATE_NEW_RECORD &&
+ !isDefined(item.availabilityObjectMetadataId),
+ );
+ if (!isDefined(template)) {
+ throw new Error('Creation command template is required');
+ }
+ replaceDraft('commandMenuItems', [template]);
+ store.set(
+ contextStoreCurrentObjectMetadataItemIdComponentState.atomFamily({
+ instanceId: MAIN_CONTEXT_STORE_INSTANCE_ID,
+ }),
+ commandOrigin === 'task'
+ ? getMockObjectMetadataItemOrThrow('task').id
+ : undefined,
+ );
+ store.set(
+ contextStoreCurrentViewIdComponentState.atomFamily({
+ instanceId: MAIN_CONTEXT_STORE_INSTANCE_ID,
+ }),
+ undefined,
+ );
+ }
+ applyChanges();
+ store.set(currentWorkspaceState.atom, {
+ ...mockCurrentWorkspace,
+ featureFlags: [
+ {
+ key: FeatureFlagKey.IS_RECORD_CREATION_FORM_ENABLED,
+ value: isFormEnabled,
+ },
+ ],
+ });
+ store.set(currentWorkspaceMemberState.atom, (member) =>
+ isDefined(member)
+ ? { ...member, openRecordIn: OpenRecordIn.SIDE_PANEL }
+ : member,
+ );
+ setIsReady(true);
+ }, [
+ applyChanges,
+ commandOrigin,
+ isFormEnabled,
+ objectMetadataItem,
+ replaceDraft,
+ store,
+ ]);
+
+ return isReady ? (
+ <WorkspaceRouteObjectsContext.Provider
+ value={[
+ {
+ path: AppPath.RecordShowPage,
+ handle: { workspaceSurfaces: ['main', 'side-panel'] },
+ },
+ ]}
+ >
+ <RecordCreationFormProvider>
+ <ContextStoreComponentInstanceContext.Provider
+ value={{ instanceId: MAIN_CONTEXT_STORE_INSTANCE_ID }}
+ >
+ <RecordCreationFlowContent commandOrigin={commandOrigin} />
+ <CommandRunner />
+ </ContextStoreComponentInstanceContext.Provider>
+ </RecordCreationFormProvider>
+ </WorkspaceRouteObjectsContext.Provider>
+ ) : null;
+};
+
+const CreationCommandMenu = () => {
+ const { commandMenuItems } = useContext(CommandMenuContext);
+ return (
+ <SelectableList
+ selectableListInstanceId="creation-story-menu"
+ focusId="creation-story-menu"
+ selectableItemIdArray={commandMenuItems.map((item) => item.id)}
+ >
+ {commandMenuItems.map((item) => (
+ <CommandMenuItemRenderer key={item.id} item={item} />
+ ))}
+ </SelectableList>
+ );
+};
+
+const RecordCreationFlowContent = ({
+ commandOrigin,
+}: Pick<RecordCreationFlowProps, 'commandOrigin'>) => {
+ const store = useStore();
+ const { objectMetadataItem } = useObjectMetadataItem({
+ objectNameSingular: 'company',
+ });
+ const { createNewRecord } = useCreateNewRecord({
+ objectMetadataItem,
+ buildRecordInput: () => ({ name: 'Filter default', employees: 10 }),
+ onRecordCreated,
+ });
+ const { goBackFromSidePanel } = useSidePanelHistory();
+ const stack = useAtomStateValue(sidePanelNavigationStackState);
+ const isOpened = useAtomStateValue(isSidePanelOpenedState);
+ const currentPage = stack.at(-1);
+ const [result, setResult] = useState<ObjectRecord | null>();
+
+ const handleCreate = async () => {
+ setResult((await createNewRecord({ position: 'first' })) ?? null);
+ };
+
+ return (
+ <>
+ {isDefined(commandOrigin) ? (
+ <CommandMenuContextProvider
+ displayType="listItem"
+ containerType={CommandMenuItemContainerType.CommandMenuList}
+ >
+ <CommandMenuComponentInstanceContext.Provider
+ value={{ instanceId: 'creation-story-menu' }}
+ >
+ <CreationCommandMenu />
+ </CommandMenuComponentInstanceContext.Provider>
+ </CommandMenuContextProvider>
+ ) : (
+ <Button title="Create company" onClick={handleCreate} />
+ )}
+ {isDefined(commandOrigin) && (
+ <p role="status">Opened: {currentPage?.routedLocation?.pathname}</p>
+ )}
+ {isOpened && currentPage?.page === SidePanelPages.RecordCreationForm && (
+ <SidePanelPageComponentInstanceContext.Provider
+ value={{ instanceId: currentPage.pageId }}
+ >
+ <Button title="Cancel" onClick={goBackFromSidePanel} />
+ <SidePanelRecordCreationFormPage />
+ </SidePanelPageComponentInstanceContext.Provider>
+ )}
+ {result === null && <p>Creation cancelled</p>}
+ {isDefined(result) && (
+ <div role="status">
+ Created {String(result.name)} with {String(result.employees)}{' '}
+ employees
+ <p>
+ Stored:{' '}
+ {String(
+ store.get(recordStoreFamilyState.atomFamily(result.id))?.name,
+ )}
+ </p>
+ <p>Opened: {currentPage?.routedLocation?.pathname}</p>
+ </div>
+ )}
+ </>
+ );
+};
+
+const meta = {
+ title: 'Modules/SidePanel/RecordCreationFlow',
+ component: RecordCreationFlow,
+ decorators: [
+ ObjectMetadataItemsDecorator,
+ ToastDecorator,
+ RouterDecorator,
+ ComponentDecorator,
+ ],
+ args: { isFormEnabled: true },
+ parameters: {
+ container: { width: 420, height: 600 },
+ msw: {
+ handlers: [
+ graphql.mutation('CreateOneCompany', ({ variables }) => {
+ createCompanyRequest(variables.input);
+ return HttpResponse.json({
+ data: {
+ createCompany: {
+ ...mockedCompanyRecords[0],
+ ...variables.input,
+ createdBy: {
+ ...mockedCompanyRecords[0].createdBy,
+ provider: null,
+ },
+ updatedBy: {
+ ...mockedCompanyRecords[0].updatedBy,
+ provider: null,
+ },
+ },
+ },
+ });
+ }),
+ ...graphqlMocks.handlers,
+ ],
+ },
+ },
+ beforeEach: () => {
+ createCompanyRequest.mockClear();
+ onRecordCreated.mockClear();
+ },
+} satisfies Meta<typeof RecordCreationFlow>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+const submitCompany = async (canvasElement: HTMLElement, shortcut?: string) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(
+ await canvas.findByRole('button', { name: /Create company/ }),
+ );
+ const nameInput = await canvas.findByRole('textbox');
+ await expect(nameInput).toHaveTextContent('Filter default');
+ await userEvent.click(nameInput);
+ await userEvent.clear(nameInput);
+ await userEvent.type(nameInput, 'Acme');
+ const createButton = canvas.getByTestId('record-creation-form-create-button');
+ if (isDefined(shortcut)) {
+ await expect(nameInput).toHaveFocus();
+ await userEvent.keyboard(shortcut);
+ } else {
+ await userEvent.click(createButton);
+ }
+ await expect(await canvas.findByRole('status')).toHaveTextContent(
+ 'Created Acme with 10 employees',
+ );
+ await expect(canvas.getByRole('status')).toHaveTextContent('Stored: Acme');
+ await expect(canvas.getByRole('status')).toHaveTextContent(
+ 'Opened: /object/company/',
+ );
+ await expect(createCompanyRequest).toHaveBeenCalledTimes(1);
+ await expect(createCompanyRequest).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'Acme', employees: 10, position: 'first' }),
+ );
+ await expect(onRecordCreated).toHaveBeenCalledTimes(1);
+ await expect(onRecordCreated).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'Acme', employees: 10 }),
+ expect.objectContaining({ name: 'Acme', position: 'first' }),
+ );
+};
+
+export const SubmitWithButton: Story = {
+ play: ({ canvasElement }) => submitCompany(canvasElement),
+};
+export const Cancel: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(
+ await canvas.findByRole('button', { name: /Create company/ }),
+ );
+ await userEvent.click(
+ await canvas.findByRole('button', { name: /Cancel/ }),
+ );
+ await expect(await canvas.findByText('Creation cancelled')).toBeVisible();
+ await expect(createCompanyRequest).not.toHaveBeenCalled();
+ await expect(onRecordCreated).not.toHaveBeenCalled();
+ },
+};
+
+export const FlagDisabled: Story = {
+ args: { isFormEnabled: false },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(
+ await canvas.findByRole('button', { name: /Create company/ }),
+ );
+ await waitFor(() =>
+ expect(canvas.getByRole('status')).toHaveTextContent(
+ 'Created Filter default with 10 employees',
+ ),
+ );
+ await expect(
+ canvas.queryByTestId('record-creation-form-create-button'),
+ ).not.toBeInTheDocument();
+ await expect(createCompanyRequest).toHaveBeenCalledTimes(1);
+ await expect(createCompanyRequest).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'Filter default', employees: 10 }),
+ );
+ },
+};
+
+const createCompanyFromCommandMenu = async (canvasElement: HTMLElement) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(await canvas.findByText('Create Company'));
+ const input = await canvas.findByRole('textbox');
+ await userEvent.type(input, 'Cross-object company');
+ await userEvent.click(
+ canvas.getByTestId('record-creation-form-create-button'),
+ );
+ await waitFor(() => expect(createCompanyRequest).toHaveBeenCalledTimes(1));
+ await expect(createCompanyRequest).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: 'Cross-object company',
+ position: 'first',
+ }),
+ );
+ await waitFor(() =>
+ expect(canvas.getByRole('status')).toHaveTextContent('/object/company/'),
+ );
+};
+
+export const CreateCompanyFromTaskPage: Story = {
+ args: { commandOrigin: 'task' },
+ play: ({ canvasElement }) => createCompanyFromCommandMenu(canvasElement),
+};
+
+export const CreateCompanyWithoutObjectContext: Story = {
+ args: { commandOrigin: 'no-object' },
+ play: ({ canvasElement }) => createCompanyFromCommandMenu(canvasElement),
+};