The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Record creation form: Create another (#27937)
Thomas Trompette72c4265adfc9
diff --git a/packages/twenty-front/src/modules/object-record/hooks/useCreateNewRecord.ts b/packages/twenty-front/src/modules/object-record/hooks/useCreateNewRecord.tsindex ee5c9761096..5b08866e306 100644--- a/packages/twenty-front/src/modules/object-record/hooks/useCreateNewRecord.ts+++ b/packages/twenty-front/src/modules/object-record/hooks/useCreateNewRecord.ts@@ -80,6 +80,18 @@ export const useCreateNewRecord = ({[buildRecordInputFromRLSPredicates, buildRecordInput, createOneRecord],);+ const createAndStoreRecord = useCallback(+ async (recordInput?: Partial<ObjectRecord>) => {+ const createdRecord = await createRecord(recordInput);++ onRecordCreated?.({ record: createdRecord, recordInput });+ upsertRecordsInStore({ partialRecords: [createdRecord] });++ return createdRecord;+ },+ [createRecord, onRecordCreated, upsertRecordsInStore],+ );+const createNewRecord = useCallback(async (recordInput?: Partial<ObjectRecord>) => {let submittedRecordInput = recordInput;@@ -93,10 +105,10 @@ export const useCreateNewRecord = ({},createRecord: (draftRecord) => {submittedRecordInput = { ...recordInput, ...draftRecord };- return createRecord(submittedRecordInput);+ return createAndStoreRecord(submittedRecordInput);},})- : await createRecord(recordInput);+ : await createAndStoreRecord(recordInput);if (!isDefined(createdRecord)) {return;@@ -146,18 +158,12 @@ export const useCreateNewRecord = ({});}- onRecordCreated?.({- record: createdRecord,- recordInput: submittedRecordInput,- });- upsertRecordsInStore({ partialRecords: [createdRecord] });-return createdRecord;},[buildRecordInputFromRLSPredicates,buildRecordInput,- createRecord,+ createAndStoreRecord,store,navigate,objectMetadataItem,@@ -167,8 +173,6 @@ export const useCreateNewRecord = ({workspaceSurface.type,isRecordCreationFormEnabled,requestRecordCreation,- onRecordCreated,- upsertRecordsInStore,],);diff --git a/packages/twenty-front/src/modules/object-record/record-form/components/RecordCreationFormProvider.tsx b/packages/twenty-front/src/modules/object-record/record-form/components/RecordCreationFormProvider.tsxindex 20571acf5f1..41e268d775e 100644--- a/packages/twenty-front/src/modules/object-record/record-form/components/RecordCreationFormProvider.tsx+++ b/packages/twenty-front/src/modules/object-record/record-form/components/RecordCreationFormProvider.tsx@@ -44,9 +44,11 @@ export const RecordCreationFormProvider = ({async ({requestId,draftRecord,+ shouldKeepOpen = false,}: {requestId: string;draftRecord: Partial<ObjectRecord> | null;+ shouldKeepOpen?: boolean;}) => {const pendingRecordCreation = pendingRecordCreations.find((candidate) => candidate.requestId === requestId,@@ -79,11 +81,26 @@ export const RecordCreationFormProvider = ({),);- let createdRecord: ObjectRecord;-try {- createdRecord = await pendingRecordCreation.createRecord(draftRecord);+ const createdRecord =+ await pendingRecordCreation.createRecord(draftRecord);++ if (!shouldKeepOpen) {+ removePageFromSidePanelHistory(requestId);++ pendingRecordCreation.resolve(createdRecord);++ setPendingRecordCreations((previousPendingRecordCreations) =>+ previousPendingRecordCreations.filter(+ (candidate) => candidate.requestId !== requestId,+ ),+ );+ }++ return {};} catch (error) {+ return { error };+ } finally {setPendingRecordCreations((previousPendingRecordCreations) =>previousPendingRecordCreations.map((candidate) =>candidate.requestId === requestId@@ -91,21 +108,7 @@ export const RecordCreationFormProvider = ({: candidate,),);-- return { error };}-- removePageFromSidePanelHistory(requestId);-- pendingRecordCreation.resolve(createdRecord);-- setPendingRecordCreations((previousPendingRecordCreations) =>- previousPendingRecordCreations.filter(- (candidate) => candidate.requestId !== requestId,- ),- );-- return {};},[pendingRecordCreations, removePageFromSidePanelHistory],);diff --git a/packages/twenty-front/src/modules/object-record/record-form/components/__tests__/RecordCreationFormProvider.test.tsx b/packages/twenty-front/src/modules/object-record/record-form/components/__tests__/RecordCreationFormProvider.test.tsxindex 6a1122e7c16..aec2e2f400f 100644--- a/packages/twenty-front/src/modules/object-record/record-form/components/__tests__/RecordCreationFormProvider.test.tsx+++ b/packages/twenty-front/src/modules/object-record/record-form/components/__tests__/RecordCreationFormProvider.test.tsx@@ -129,6 +129,45 @@ it('resolves with the error the server rejected the draft with and keeps the forexpect(store.get(sidePanelNavigationStackState.atom)).toEqual([formPage]);});+it('creates the record and keeps the request open when asked to keep the form open', async () => {+ const { result, store } = setup();+ const createdRecord = { id: 'created-company', __typename: 'Company' };+ const createRecord = jest.fn(() => Promise.resolve(createdRecord));+ let requestResult: unknown = 'pending';+ act(() => {+ void result.current+ .requestRecordCreation({+ objectMetadataItem: getMockObjectMetadataItemOrThrow('company'),+ createRecord,+ })+ .then((record) => {+ requestResult = record;+ });+ });+ const [formPage] = store.get(sidePanelNavigationStackState.atom);++ await act(async () => {+ await result.current.settleRecordCreationDraft({+ requestId: formPage.pageId,+ draftRecord: { name: 'First' },+ shouldKeepOpen: true,+ });+ });++ await act(async () => {+ await result.current.settleRecordCreationDraft({+ requestId: formPage.pageId,+ draftRecord: { name: 'Second' },+ shouldKeepOpen: true,+ });+ });++ expect(createRecord).toHaveBeenNthCalledWith(1, { name: 'First' });+ expect(createRecord).toHaveBeenNthCalledWith(2, { name: 'Second' });+ expect(requestResult).toBe('pending');+ expect(store.get(sidePanelNavigationStackState.atom)).toEqual([formPage]);+});+it('keeps the open creation form of the same object instead of stacking another', async () => {const { result, store } = setup();act(() => {diff --git a/packages/twenty-front/src/modules/object-record/record-form/contexts/RecordCreationFormContext.ts b/packages/twenty-front/src/modules/object-record/record-form/contexts/RecordCreationFormContext.tsindex 370b86a7464..9acba3f0e14 100644--- a/packages/twenty-front/src/modules/object-record/record-form/contexts/RecordCreationFormContext.ts+++ b/packages/twenty-front/src/modules/object-record/record-form/contexts/RecordCreationFormContext.ts@@ -11,6 +11,7 @@ export type RecordCreationFormContextValue = {settleRecordCreationDraft: (params: {requestId: string;draftRecord: Partial<ObjectRecord> | null;+ shouldKeepOpen?: boolean;}) => Promise<{ error?: unknown }>;};diff --git a/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/SidePanelRecordCreationFormPage.tsx b/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/SidePanelRecordCreationFormPage.tsxindex 98c04b3fac7..bb2fc48bacb 100644--- a/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/SidePanelRecordCreationFormPage.tsx+++ b/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/SidePanelRecordCreationFormPage.tsx@@ -127,6 +127,7 @@ const SidePanelRecordCreationForm = ({);const [isSubmitting, setIsSubmitting] = useState(false);+ const [formResetCount, setFormResetCount] = useState(0);const optionsDropdownId = useId();const [draftValidationRuleViolations, setDraftValidationRuleViolations] =useState<ValidationRuleViolation[]>([]);@@ -227,7 +228,11 @@ const SidePanelRecordCreationForm = ({}};- const handleCreateClick = async () => {+ const submitDraftRecord = async ({+ shouldKeepOpen,+ }: {+ shouldKeepOpen: boolean;+ }) => {if (isSubmitting) {return;}@@ -257,9 +262,22 @@ const SidePanelRecordCreationForm = ({fieldMetadataItems: objectMetadataItem.fields,objectMetadataItems,}),+ shouldKeepOpen,});if (!isDefined(error)) {+ if (shouldKeepOpen) {+ setRecordCreationFormDraft(null);+ setDraftValidationRuleViolations([]);+ setFormResetCount(+ (previousFormResetCount) => previousFormResetCount + 1,+ );+ enqueueToast({+ status: 'success',+ children: t`${objectMetadataItem.labelSingular} created`,+ });+ }+return;}@@ -280,11 +298,21 @@ const SidePanelRecordCreationForm = ({}};+ const handleCreateClick = () => submitDraftRecord({ shouldKeepOpen: false });++ const handleCreateAnotherClick = () =>+ submitDraftRecord({ shouldKeepOpen: true });+const containerRef = useHotkeysOnFocusedElement({- keys: [`${Key.Meta}+${Key.Enter}`, `${Key.Control}+${Key.Enter}`],+ keys: [+ `${Key.Meta}+${Key.Enter}`,+ `${Key.Control}+${Key.Enter}`,+ `${Key.Alt}+${Key.Enter}`,+ ],focusId: currentFocusId ?? SIDE_PANEL_FOCUS_ID,- callback: handleCreateClick,- dependencies: [currentFocusId, handleCreateClick],+ callback: (keyboardEvent) =>+ keyboardEvent.altKey ? handleCreateAnotherClick() : handleCreateClick(),+ dependencies: [currentFocusId, handleCreateClick, handleCreateAnotherClick],});return (@@ -303,7 +331,7 @@ const SidePanelRecordCreationForm = ({/>}/>- <StyledContent>+ <StyledContent key={formResetCount}><RecordFormFieldInputsobjectMetadataItem={objectMetadataItem}fieldMetadataItems={visibleFieldMetadataItems}@@ -360,23 +388,25 @@ const SidePanelRecordCreationForm = ({)}<SidePanelFooteractions={[- ...(hasLayoutsPermission- ? [- <SidePanelOptionsDropdown- key="options"- dropdownId={optionsDropdownId}- >- <Dropdown.ActionItem- startIcon={<IconEdit />}- onClick={() =>- openRecordCreationFormSettingsInSidePanel(- objectMetadataItem,- )- }- >{t`Edit form`}</Dropdown.ActionItem>- </SidePanelOptionsDropdown>,- ]- : []),+ <SidePanelOptionsDropdown+ key="options"+ dropdownId={optionsDropdownId}+ >+ <Dropdown.ActionItem+ startIcon={<IconPlus />}+ shortcut={['Alt', 'Enter']}+ disabled={isSubmitting}+ onClick={handleCreateAnotherClick}+ >{t`Create another`}</Dropdown.ActionItem>+ {hasLayoutsPermission && (+ <Dropdown.ActionItem+ startIcon={<IconEdit />}+ onClick={() =>+ openRecordCreationFormSettingsInSidePanel(objectMetadataItem)+ }+ >{t`Edit form`}</Dropdown.ActionItem>+ )}+ </SidePanelOptionsDropdown>,<Buttonkey="create-record"startIcon={<IconPlus />}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.tsxindex ff9dfa786f2..8c42ef3c39a 100644--- 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@@ -481,6 +481,34 @@ export const SubmitWithControlEnter: Story = {submitCompany(canvasElement, '{Control>}{Enter}{/Control}'),};+export const CreateAnotherWithOptionEnter: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(+ await canvas.findByRole('button', { name: /Create company/ }),+ );+ const nameInput = await canvas.findByRole('textbox');+ await userEvent.click(nameInput);+ await userEvent.clear(nameInput);+ await userEvent.type(nameInput, 'Acme');+ await userEvent.keyboard('{Alt>}{Enter}{/Alt}');+ await waitFor(() => expect(createCompanyRequest).toHaveBeenCalledTimes(1));+ await expect(createCompanyRequest).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'Acme', position: 'first' }),+ );+ await waitFor(() =>+ expect(canvas.getByRole('textbox')).not.toHaveTextContent('Acme'),+ );+ await expect(onRecordCreated).toHaveBeenCalledWith({+ record: expect.objectContaining({ name: 'Acme' }),+ recordInput: expect.objectContaining({ name: 'Acme', position: 'first' }),+ });+ await expect(+ canvas.getByTestId('record-creation-form-create-button'),+ ).toBeVisible();+ },+};+export const IgnoreNonSubmitKeys: Story = {play: async ({ canvasElement }) => {const canvas = within(canvasElement);diff --git a/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/__tests__/SidePanelRecordCreationFormPage.test.tsx b/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/__tests__/SidePanelRecordCreationFormPage.test.tsxindex 560b9220574..949f88ee84e 100644--- a/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/__tests__/SidePanelRecordCreationFormPage.test.tsx+++ b/packages/twenty-front/src/modules/side-panel/pages/record-creation-form/components/__tests__/SidePanelRecordCreationFormPage.test.tsx@@ -346,6 +346,7 @@ describe('SidePanelRecordCreationFormPage', () => {expect(settleRecordCreationDraft).toHaveBeenCalledWith({requestId: REQUEST_ID,draftRecord: { nickname: 'Apple' },+ shouldKeepOpen: false,});});@@ -414,6 +415,7 @@ describe('SidePanelRecordCreationFormPage', () => {expect(settleRecordCreationDraft).toHaveBeenCalledWith({requestId: REQUEST_ID,draftRecord: {},+ shouldKeepOpen: false,});expect(screen.getByLabelText('Nickname')).toBeInTheDocument();expect(@@ -480,6 +482,7 @@ describe('SidePanelRecordCreationFormPage', () => {expect(settleRecordCreationDraft).toHaveBeenCalledWith({requestId: REQUEST_ID,draftRecord: {},+ shouldKeepOpen: false,});expect(screen.queryByLabelText('Nickname')).not.toBeInTheDocument();});@@ -499,13 +502,42 @@ describe('SidePanelRecordCreationFormPage', () => {);});- it('hides the options menu from members without the layouts permission', () => {+ it('leaves the form configuration out of the options menu for members without the layouts permission', async () => {+ const user = userEvent.setup();+mockHasPermissionFlag.mockReturnValue(false);renderPage();+ await user.click(screen.getByRole('button', { name: 'Options' }));++ expect(+ await screen.findByRole('menuitem', { name: /Create another/ }),+ ).toBeInTheDocument();expect(- screen.queryByRole('button', { name: 'Options' }),+ screen.queryByRole('menuitem', { name: 'Edit form' }),).not.toBeInTheDocument();});++ it('creates another record from the options menu and keeps an empty form open', async () => {+ const user = userEvent.setup();++ renderPage();++ await user.type(screen.getByLabelText('Name'), 'Apple');+ await user.click(screen.getByRole('button', { name: 'Options' }));+ await user.click(+ await screen.findByRole('menuitem', { name: /Create another/ }),+ );++ expect(settleRecordCreationDraft).toHaveBeenCalledWith({+ requestId: REQUEST_ID,+ draftRecord: { name: 'Apple' },+ shouldKeepOpen: true,+ });+ expect(await screen.findByLabelText('Name')).toHaveValue('');+ expect(mockEnqueueToast).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'success' }),+ );+ });});