Skip to content

The open alternative to Salesforce, designed for AI.

Replace the generic multi-item field inputs with composable bricks (#28708)

Charles Bochet99d3f780c49e
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormArrayFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormArrayFieldInput.tsx
index d825d520e63..f7fad95e758 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormArrayFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormArrayFieldInput.tsx
@@ -5,7 +5,8 @@ import { FormFieldPlaceholder } from '@/object-record/record-field/ui/form-types
import { VariableChipStandalone } from '@/object-record/record-field/ui/form-types/components/VariableChipStandalone';
import { type VariablePickerComponent } from '@/ui/input/types/VariablePickerComponent';
import { ArrayFieldMenuItem } from '@/object-record/record-field/ui/meta-types/input/components/ArrayFieldMenuItem';
-import { MultiItemBaseInput } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemBaseInput';
+import { MultiItemFieldInputRow } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInputRow';
+import { MultiItemFieldTextInput } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldTextInput';
import { type FieldArrayValue } from '@/object-record/record-field/ui/types/FieldMetadata';
import { ArrayDisplay } from '@/ui/field/display/components/ArrayDisplay';
import { StyledTextInput } from '@/ui/field/input/components/TextInput';
@@ -414,17 +415,18 @@ export const FormArrayFieldInput = ({
<Dropdown.Separator />
{isInputDisplayed ? (
- <MultiItemBaseInput
- instanceId={newItemInputInstanceId}
- autoFocus
- placeholder={placeholder}
- value={inputValue}
- onFocus={handleNewItemInputFocus}
- onBlur={handleNewItemInputBlur}
- onEscape={handleNewItemInputEscape}
- onChange={handleNewItemInputChange}
- onEnter={handleNewItemInputSubmit}
- />
+ <MultiItemFieldInputRow>
+ <MultiItemFieldTextInput
+ autoFocus
+ placeholder={placeholder}
+ value={inputValue}
+ onFocus={handleNewItemInputFocus}
+ onBlur={handleNewItemInputBlur}
+ onEscape={handleNewItemInputEscape}
+ onChange={handleNewItemInputChange}
+ onEnter={handleNewItemInputSubmit}
+ />
+ </MultiItemFieldInputRow>
) : !isLimitReached ? (
<Dropdown.Section>
<Dropdown.ActionItem
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/ArrayFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/ArrayFieldInput.tsx
index 66961f7ff2e..100041b1bf6 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/ArrayFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/ArrayFieldInput.tsx
@@ -1,14 +1,26 @@
-import { t } from '@lingui/core/macro';
import { FieldInputEventContext } from '@/object-record/record-field/ui/contexts/FieldInputEventContext';
import { useArrayField } from '@/object-record/record-field/ui/meta-types/hooks/useArrayField';
import { ArrayFieldMenuItem } from '@/object-record/record-field/ui/meta-types/input/components/ArrayFieldMenuItem';
-import { MultiItemFieldInput } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInput';
+import { MultiItemFieldAddButton } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldAddButton';
+import { MultiItemFieldInputRow } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInputRow';
+import { MultiItemFieldSaveButton } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSaveButton';
+import { MultiItemFieldSearchHeader } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSearchHeader';
+import { MultiItemFieldTextInput } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldTextInput';
import { MULTI_ITEM_FIELD_INPUT_DROPDOWN_ID_PREFIX } from '@/object-record/record-field/ui/meta-types/input/constants/MultiItemFieldInputDropdownClickOutsideId';
+import { useMultiItemDraft } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemDraft';
+import { useMultiItemFieldDismiss } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemFieldDismiss';
+import { useMultiItemSearch } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemSearch';
import { arrayFieldValueSchema } from '@/object-record/record-field/ui/validation-schemas/arrayFieldValueSchema';
-import { useContext, useMemo } from 'react';
+import { OverlayMenuList } from '@/ui/layout/overlay/components/OverlayMenuList';
+import { OverlayMenuListSeparator } from '@/ui/layout/overlay/components/OverlayMenuListSeparator';
+import { t } from '@lingui/core/macro';
+import { useContext, useMemo, useRef } from 'react';
import { MULTI_ITEM_FIELD_DEFAULT_MAX_VALUES } from 'twenty-shared/constants';
-import { isDefined } from 'twenty-shared/utils';
-import { FieldMetadataType } from '~/generated-metadata/graphql';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { toSpliced } from '~/utils/array/toSpliced';
+import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
+
+const getArrayItemText = (item: string) => item;
export const ArrayFieldInput = () => {
const { setDraftValue, draftValue, fieldDefinition } = useArrayField();
@@ -17,10 +29,13 @@ export const ArrayFieldInput = () => {
FieldInputEventContext,
);
+ const containerRef = useRef<HTMLDivElement>(null);
+
const arrayItems = useMemo<Array<string>>(
() => (Array.isArray(draftValue) ? draftValue : []),
[draftValue],
);
+
const parseStringArrayToArrayValue = (arrayItems: string[]) => {
const parseResponse = arrayFieldValueSchema.safeParse(arrayItems);
@@ -29,66 +44,150 @@ export const ArrayFieldInput = () => {
}
};
- const handleChange = (newValue: string[]) => {
- if (!isDefined(newValue)) setDraftValue(null);
-
- const nextValue = parseStringArrayToArrayValue(newValue);
+ const handleChange = (updatedItems: string[]) => {
+ const nextValue = parseStringArrayToArrayValue(updatedItems);
if (isDefined(nextValue)) {
setDraftValue(nextValue);
}
};
- const handleClickOutside = (
- newValue: string[],
- event: MouseEvent | TouchEvent,
- ) => {
- onClickOutside?.({
- newValue: parseStringArrayToArrayValue(newValue),
- event,
+ const handleSubmit = (updatedItems: string[]) => {
+ onSubmit?.({
+ newValue: parseStringArrayToArrayValue(updatedItems),
+ skipClose: true,
});
};
- const handleEscape = (newValue: string[]) => {
- onEscape?.({ newValue: parseStringArrayToArrayValue(newValue) });
+ const maxNumberOfValues =
+ fieldDefinition.metadata.settings?.maxNumberOfValues ??
+ MULTI_ITEM_FIELD_DEFAULT_MAX_VALUES;
+
+ const draft = useMultiItemDraft({
+ items: arrayItems,
+ onItemsChange: handleChange,
+ getItemText: getArrayItemText,
+ maxItemCount: maxNumberOfValues,
+ });
+
+ const {
+ searchFilter,
+ setSearchFilter,
+ shouldShowSearch,
+ filteredItemEntries,
+ } = useMultiItemSearch({ items: arrayItems, getItemText: getArrayItemText });
+
+ const handleInputEnter = () => {
+ const updatedItems = draft.commitInput();
+
+ if (!isDefined(updatedItems)) {
+ return;
+ }
+
+ if (draft.isSingleItemMode) {
+ onEnter?.({ newValue: parseStringArrayToArrayValue(updatedItems) });
+ } else if (!isDeeplyEqual(arrayItems, updatedItems)) {
+ handleSubmit(updatedItems);
+ }
+
+ draft.closeInput();
};
- const handleEnter = (newValue: string[]) => {
- onEnter?.({ newValue: parseStringArrayToArrayValue(newValue) });
+ const handleEscape = () => {
+ onEscape?.({ newValue: parseStringArrayToArrayValue(arrayItems) });
};
- const handleSubmit = (newValue: string[]) => {
- onSubmit?.({
- newValue: parseStringArrayToArrayValue(newValue),
- skipClose: true,
- });
+ useMultiItemFieldDismiss({
+ containerRef,
+ onEscape: handleEscape,
+ onClickOutside: (event) => {
+ const updatedItems = draft.isInputDisplayed
+ ? draft.commitInput()
+ : arrayItems;
+
+ if (!isDefined(updatedItems)) {
+ return;
+ }
+
+ onClickOutside?.({
+ newValue: parseStringArrayToArrayValue(updatedItems),
+ event,
+ });
+ },
+ });
+
+ const handleDelete = (index: number) => {
+ const updatedItems = toSpliced(arrayItems, index, 1);
+
+ handleChange(updatedItems);
+ handleSubmit(updatedItems);
+ draft.resetInputForItems(updatedItems);
};
- const maxNumberOfValues =
- fieldDefinition.metadata.settings?.maxNumberOfValues ??
- MULTI_ITEM_FIELD_DEFAULT_MAX_VALUES;
+ const shouldShowItems =
+ isNonEmptyArray(filteredItemEntries) &&
+ (!draft.isSingleItemMode || !draft.isInputDisplayed);
+ const visibleItemEntries = shouldShowItems ? filteredItemEntries : undefined;
+ const shouldShowAddButton = !draft.isInputDisplayed && !draft.isLimitReached;
return (
- <MultiItemFieldInput
- newItemLabel={t`Add Item`}
- items={arrayItems}
- onChange={handleChange}
- onEnter={handleEnter}
- onSubmit={handleSubmit}
- onEscape={handleEscape}
- onClickOutside={handleClickOutside}
- placeholder={t`Enter value`}
- fieldMetadataType={FieldMetadataType.ARRAY}
- renderItem={({ value, index, handleEdit, handleDelete }) => (
+ <OverlayMenuList
+ ref={containerRef}
+ header={
+ shouldShowSearch && !draft.isInputDisplayed ? (
+ <MultiItemFieldSearchHeader
+ value={searchFilter}
+ onChange={setSearchFilter}
+ />
+ ) : undefined
+ }
+ footer={
+ <>
+ {shouldShowItems &&
+ (draft.isInputDisplayed || shouldShowAddButton) && (
+ <OverlayMenuListSeparator />
+ )}
+ {draft.isInputDisplayed && (
+ <MultiItemFieldInputRow
+ rightComponent={
+ isNonEmptyArray(arrayItems) ? (
+ <MultiItemFieldSaveButton
+ isAddingNewItem={draft.isAddingNewItem}
+ onClick={handleInputEnter}
+ />
+ ) : undefined
+ }
+ >
+ <MultiItemFieldTextInput
+ autoFocus={!shouldShowSearch}
+ placeholder={t`Enter value`}
+ value={draft.inputValue}
+ hasError={draft.hasError}
+ onChange={draft.handleInputChange}
+ onEnter={handleInputEnter}
+ onEscape={handleEscape}
+ shouldPreventTabNavigation
+ />
+ </MultiItemFieldInputRow>
+ )}
+ {shouldShowAddButton && (
+ <MultiItemFieldAddButton
+ label={t`Add Item`}
+ onClick={draft.startAdding}
+ />
+ )}
+ </>
+ }
+ >
+ {visibleItemEntries?.map(({ item, index }) => (
<ArrayFieldMenuItem
key={index}
dropdownId={`${MULTI_ITEM_FIELD_INPUT_DROPDOWN_ID_PREFIX}-${fieldDefinition.metadata.fieldName}-${index}`}
- value={value}
- onEdit={handleEdit}
- onDelete={handleDelete}
+ value={item}
+ onEdit={() => draft.startEditing(index)}
+ onDelete={() => handleDelete(index)}
/>
- )}
- maxItemCount={maxNumberOfValues}
- ></MultiItemFieldInput>
+ ))}
+ </OverlayMenuList>
);
};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/EmailsFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/EmailsFieldInput.tsx
index 240ff5c96bf..0f75bdaac6e 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/EmailsFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/EmailsFieldInput.tsx
@@ -1,18 +1,36 @@
import { FieldInputEventContext } from '@/object-record/record-field/ui/contexts/FieldInputEventContext';
import { useEmailsField } from '@/object-record/record-field/ui/meta-types/hooks/useEmailsField';
import { EmailsFieldMenuItem } from '@/object-record/record-field/ui/meta-types/input/components/EmailsFieldMenuItem';
+import { MultiItemFieldAddButton } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldAddButton';
+import { MultiItemFieldInputRow } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInputRow';
+import { MultiItemFieldSaveButton } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSaveButton';
+import { MultiItemFieldSearchHeader } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSearchHeader';
+import { MultiItemFieldTextInput } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldTextInput';
import { MULTI_ITEM_FIELD_INPUT_DROPDOWN_ID_PREFIX } from '@/object-record/record-field/ui/meta-types/input/constants/MultiItemFieldInputDropdownClickOutsideId';
+import { useMultiItemDraft } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemDraft';
+import { useMultiItemFieldDismiss } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemFieldDismiss';
+import { useMultiItemSearch } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemSearch';
import { recordFieldInputIsFieldInErrorComponentState } from '@/object-record/record-field/ui/states/recordFieldInputIsFieldInErrorComponentState';
import { type FieldEmailsValue } from '@/object-record/record-field/ui/types/FieldMetadata';
import { emailsFieldValueSchema } from '@/object-record/record-field/ui/validation-schemas/emailsFieldValueSchema';
+import { OverlayMenuList } from '@/ui/layout/overlay/components/OverlayMenuList';
+import { OverlayMenuListSeparator } from '@/ui/layout/overlay/components/OverlayMenuListSeparator';
import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
import { useLingui } from '@lingui/react/macro';
-import { useCallback, useContext, useMemo } from 'react';
+import { useContext, useMemo, useRef } from 'react';
import { MULTI_ITEM_FIELD_DEFAULT_MAX_VALUES } from 'twenty-shared/constants';
-import { emailSchema, isDefined } from 'twenty-shared/utils';
-import { FieldMetadataType } from '~/generated-metadata/graphql';
+import { emailSchema, isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { moveArrayItem } from '~/utils/array/moveArrayItem';
+import { toSpliced } from '~/utils/array/toSpliced';
import { useCopyToClipboard } from '~/hooks/useCopyToClipboard';
-import { MultiItemFieldInput } from './MultiItemFieldInput';
+import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
+
+const getEmailText = (email: string) => email;
+
+const validateEmail = (input: string) => ({
+ isValid: emailSchema.safeParse(input).success,
+ errorMessage: '',
+});
export const EmailsFieldInput = () => {
const { setDraftValue, draftValue, fieldDefinition } = useEmailsField();
@@ -23,6 +41,8 @@ export const EmailsFieldInput = () => {
FieldInputEventContext,
);
+ const containerRef = useRef<HTMLDivElement>(null);
+
const emails = useMemo<string[]>(
() =>
[
@@ -55,92 +75,168 @@ export const EmailsFieldInput = () => {
}
};
- const validateInput = useCallback(
- (input: string) => ({
- isValid: emailSchema.safeParse(input).success,
- errorMessage: '',
- }),
- [],
- );
-
- const getShowPrimaryIcon = (index: number) =>
- index === 0 && emails.length > 1;
- const getShowSetAsPrimaryButton = (index: number) => index > 0;
+ const handleSubmit = (updatedEmails: string[]) => {
+ onSubmit?.({
+ newValue: parseStringArrayToEmailsValue(updatedEmails),
+ skipClose: true,
+ });
+ };
const setRecordFieldInputIsFieldInError = useSetAtomComponentState(
recordFieldInputIsFieldInErrorComponentState,
);
- const handleError = (hasError: boolean, values: any[]) => {
- setRecordFieldInputIsFieldInError(hasError && values.length === 0);
+ const maxNumberOfValues =
+ fieldDefinition.metadata.settings?.maxNumberOfValues ??
+ MULTI_ITEM_FIELD_DEFAULT_MAX_VALUES;
+
+ const draft = useMultiItemDraft({
+ items: emails,
+ onItemsChange: handleChange,
+ getItemText: getEmailText,
+ validateInput: validateEmail,
+ maxItemCount: maxNumberOfValues,
+ onError: (hasError) =>
+ setRecordFieldInputIsFieldInError(hasError && emails.length === 0),
+ });
+
+ const {
+ searchFilter,
+ setSearchFilter,
+ shouldShowSearch,
+ filteredItemEntries,
+ } = useMultiItemSearch({ items: emails, getItemText: getEmailText });
+
+ const handleInputEnter = () => {
+ const updatedItems = draft.commitInput();
+
+ if (!isDefined(updatedItems)) {
+ return;
+ }
+
+ if (draft.isSingleItemMode) {
+ onEnter?.({ newValue: parseStringArrayToEmailsValue(updatedItems) });
+ } else if (!isDeeplyEqual(emails, updatedItems)) {
+ handleSubmit(updatedItems);
+ }
+
+ draft.closeInput();
};
- const handleCopy = (email: string) => {
- copyToClipboard(email, t`Email copied to clipboard`);
+ const handleEscape = () => {
+ onEscape?.({ newValue: parseStringArrayToEmailsValue(emails) });
};
- const handleClickOutside = (
- updatedEmails: string[],
- event: MouseEvent | TouchEvent,
- ) => {
- onClickOutside?.({
- newValue: parseStringArrayToEmailsValue(updatedEmails),
- event,
+ useMultiItemFieldDismiss({
+ containerRef,
+ onEscape: handleEscape,
+ onClickOutside: (event) => {
+ const updatedItems = draft.isInputDisplayed
+ ? draft.commitInput()
+ : emails;
+
+ if (!isDefined(updatedItems)) {
+ return;
+ }
+
+ onClickOutside?.({
+ newValue: parseStringArrayToEmailsValue(updatedItems),
+ event,
+ });
+ },
+ });
+
+ const handleSetAsPrimary = (index: number) => {
+ const updatedEmails = moveArrayItem(emails, {
+ fromIndex: index,
+ toIndex: 0,
});
- };
- const handleEscape = (updatedEmails: string[]) => {
- onEscape?.({ newValue: parseStringArrayToEmailsValue(updatedEmails) });
+ handleChange(updatedEmails);
+ handleSubmit(updatedEmails);
};
- const handleEnter = (updatedEmails: string[]) => {
- onEnter?.({ newValue: parseStringArrayToEmailsValue(updatedEmails) });
+ const handleDelete = (index: number) => {
+ const updatedEmails = toSpliced(emails, index, 1);
+
+ handleChange(updatedEmails);
+ handleSubmit(updatedEmails);
+ draft.resetInputForItems(updatedEmails);
};
- const handleSubmit = (updatedEmails: string[]) => {
- onSubmit?.({
- newValue: parseStringArrayToEmailsValue(updatedEmails),
- skipClose: true,
- });
+ const handleCopy = (email: string) => {
+ copyToClipboard(email, t`Email copied to clipboard`);
};
- const maxNumberOfValues =
- fieldDefinition.metadata.settings?.maxNumberOfValues ??
- MULTI_ITEM_FIELD_DEFAULT_MAX_VALUES;
+ const shouldShowItems =
+ isNonEmptyArray(filteredItemEntries) &&
+ (!draft.isSingleItemMode || !draft.isInputDisplayed);
+ const visibleItemEntries = shouldShowItems ? filteredItemEntries : undefined;
+ const shouldShowAddButton = !draft.isInputDisplayed && !draft.isLimitReached;
return (
- <MultiItemFieldInput
- items={emails}
- onChange={handleChange}
- onEnter={handleEnter}
- onSubmit={handleSubmit}
- onEscape={handleEscape}
- onClickOutside={handleClickOutside}
- placeholder={t`Email`}
- fieldMetadataType={FieldMetadataType.EMAILS}
- validateInput={validateInput}
- renderItem={({
- value: email,
- index,
- handleEdit,
- handleSetPrimary,
- handleDelete,
- }) => (
+ <OverlayMenuList
+ ref={containerRef}
+ header={
+ shouldShowSearch && !draft.isInputDisplayed ? (
+ <MultiItemFieldSearchHeader
+ value={searchFilter}
+ onChange={setSearchFilter}
+ />
+ ) : undefined
+ }
+ footer={
+ <>
+ {shouldShowItems &&
+ (draft.isInputDisplayed || shouldShowAddButton) && (
+ <OverlayMenuListSeparator />
+ )}
+ {draft.isInputDisplayed && (
+ <MultiItemFieldInputRow
+ rightComponent={
+ isNonEmptyArray(emails) ? (
+ <MultiItemFieldSaveButton
+ isAddingNewItem={draft.isAddingNewItem}
+ onClick={handleInputEnter}
+ />
+ ) : undefined
+ }
+ >
+ <MultiItemFieldTextInput
+ autoFocus={!shouldShowSearch}
+ placeholder={t`Email`}
+ value={draft.inputValue}
+ hasError={draft.hasError}
+ onChange={draft.handleInputChange}
+ onEnter={handleInputEnter}
+ onEscape={handleEscape}
+ shouldPreventTabNavigation
+ />
+ </MultiItemFieldInputRow>
+ )}
+ {shouldShowAddButton && (
+ <MultiItemFieldAddButton
+ label={t`Add Email`}
+ onClick={draft.startAdding}
+ />
+ )}
+ </>
+ }
+ >
+ {visibleItemEntries?.map(({ item: email, index }) => (
<EmailsFieldMenuItem
key={index}
dropdownId={`${MULTI_ITEM_FIELD_INPUT_DROPDOWN_ID_PREFIX}-${fieldDefinition.metadata.fieldName}-${index}`}
- showPrimaryIcon={getShowPrimaryIcon(index)}
- showSetAsPrimaryButton={getShowSetAsPrimaryButton(index)}
+ showPrimaryIcon={index === 0 && emails.length > 1}
+ showSetAsPrimaryButton={index > 0}
showCopyButton={true}
email={email}
- onEdit={handleEdit}
- onSetAsPrimary={handleSetPrimary}
- onDelete={handleDelete}
+ onEdit={() => draft.startEditing(index)}
+ onSetAsPrimary={() => handleSetAsPrimary(index)}
+ onDelete={() => handleDelete(index)}
onCopy={handleCopy}
/>
- )}
- onError={handleError}
- maxItemCount={maxNumberOfValues}
- />
+ ))}
+ </OverlayMenuList>
);
};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FilesFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FilesFieldInput.tsx
index ca4284139a7..1a53de5250c 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FilesFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FilesFieldInput.tsx
@@ -4,23 +4,47 @@ import { FieldInputEventContext } from '@/object-record/record-field/ui/contexts
import { useFilesField } from '@/object-record/record-field/ui/meta-types/hooks/useFilesField';
import { useUploadFilesFieldFile } from '@/object-record/record-field/ui/meta-types/hooks/useUploadFilesFieldFile';
import { FilesFieldMenuItem } from '@/object-record/record-field/ui/meta-types/input/components/FilesFieldMenuItem';
-import { MultiItemFieldInput } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInput';
+import { MultiItemFieldAddButton } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldAddButton';
+import { MultiItemFieldInputRow } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInputRow';
+import { MultiItemFieldSaveButton } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSaveButton';
+import { MultiItemFieldSearchHeader } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSearchHeader';
+import { MultiItemFieldTextInput } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldTextInput';
import { MULTI_ITEM_FIELD_INPUT_DROPDOWN_ID_PREFIX } from '@/object-record/record-field/ui/meta-types/input/constants/MultiItemFieldInputDropdownClickOutsideId';
+import { useMultiItemDraft } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemDraft';
+import { useMultiItemFieldDismiss } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemFieldDismiss';
+import { useMultiItemSearch } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemSearch';
import { uploadMultipleFiles } from '@/object-record/record-field/ui/meta-types/utils/uploadMultipleFiles';
import { recordFieldInputIsFieldInErrorComponentState } from '@/object-record/record-field/ui/states/recordFieldInputIsFieldInErrorComponentState';
import { type FieldFilesValue } from '@/object-record/record-field/ui/types/FieldMetadata';
import { filesFieldValueSchema } from '@/object-record/record-field/ui/validation-schemas/filesFieldValueSchema';
import { filePreviewState } from '@/ui/field/display/states/filePreviewState';
+import { OverlayMenuList } from '@/ui/layout/overlay/components/OverlayMenuList';
+import { OverlayMenuListSeparator } from '@/ui/layout/overlay/components/OverlayMenuListSeparator';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
import { useLingui } from '@lingui/react/macro';
-import { useCallback, useContext, useMemo, useState } from 'react';
+import { isNonEmptyString } from '@sniptt/guards';
+import { useContext, useMemo, useRef, useState } from 'react';
import { MULTI_ITEM_FIELD_DEFAULT_MAX_VALUES } from 'twenty-shared/constants';
-import { isDefined } from 'twenty-shared/utils';
import { doNotTranslate } from 'twenty-shared/i18n';
+import { CustomError, isDefined, isNonEmptyArray } from 'twenty-shared/utils';
import { useToast } from 'twenty-ui/components/feedback';
-import { FieldMetadataType } from '~/generated-metadata/graphql';
+import { toSpliced } from '~/utils/array/toSpliced';
+import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
+
+const getFileText = (file: FieldFilesValue) => file.label;
+
+const validateFileLabel = (input: string) => ({
+ isValid: isNonEmptyString(input.trim()),
+ errorMessage: '',
+});
+
+const parseFilesArrayToFilesValue = (filesArray: FieldFilesValue[]) => {
+ const parseResponse = filesFieldValueSchema.safeParse(filesArray);
+
+ return parseResponse.success ? parseResponse.data : [];
+};
export const FilesFieldInput = () => {
const { setDraftValue, draftValue, fieldDefinition } = useFilesField();
@@ -38,16 +62,7 @@ export const FilesFieldInput = () => {
FieldInputEventContext,
);
- const parseFilesArrayToFilesValue = useCallback(
- (filesArray: FieldFilesValue[]) => {
- const parseResponse = filesFieldValueSchema.safeParse(filesArray);
- if (parseResponse.success) {
- return parseResponse.data;
- }
- return [];
- },
- [],
- );
+ const containerRef = useRef<HTMLDivElement>(null);
const files = useMemo(
() => (draftValue ?? []) as FieldFilesValue[],
@@ -58,22 +73,25 @@ export const FilesFieldInput = () => {
fieldDefinition.metadata.settings?.maxNumberOfValues ??
MULTI_ITEM_FIELD_DEFAULT_MAX_VALUES;
- const handleChange = useCallback(
- (updatedFiles: FieldFilesValue[]) => {
- const nextValue = parseFilesArrayToFilesValue(updatedFiles);
- if (isDefined(nextValue)) {
- setDraftValue(nextValue);
+ const handleChange = (updatedFiles: FieldFilesValue[]) => {
+ const nextValue = parseFilesArrayToFilesValue(updatedFiles);
- // This input renders nothing without files, so close it once the last is gone; persisting is left to onSubmit.
- if (nextValue.length === 0) {
- onEnter?.({ newValue: nextValue, skipPersist: true });
- }
- }
- },
- [parseFilesArrayToFilesValue, setDraftValue, onEnter],
- );
+ setDraftValue(nextValue);
+
+ // This input renders nothing without files, so close it once the last is gone; persisting is left to onSubmit.
+ if (nextValue.length === 0) {
+ onEnter?.({ newValue: nextValue, skipPersist: true });
+ }
+ };
+
+ const handleSubmit = (updatedFiles: FieldFilesValue[]) => {
+ onSubmit?.({
+ newValue: parseFilesArrayToFilesValue(updatedFiles),
+ skipClose: true,
+ });
+ };
- const handleUploadClick = useCallback(() => {
+ const handleUploadClick = () => {
if (isUploading) {
return;
}
@@ -111,51 +129,91 @@ export const FilesFieldInput = () => {
}
},
});
- }, [
- isUploading,
- openFileUpload,
- files,
- maxNumberOfValues,
- enqueueToast,
- t,
- uploadFile,
- handleChange,
- onEnter,
- parseFilesArrayToFilesValue,
- fieldDefinition,
- ]);
+ };
const setRecordFieldInputIsFieldInError = useSetAtomComponentState(
recordFieldInputIsFieldInErrorComponentState,
);
- const handleError = (hasError: boolean, values: FieldFilesValue[]) => {
- setRecordFieldInputIsFieldInError(hasError && values.length === 0);
- };
+ const formatFileLabelInputOrThrow = ({
+ input,
+ itemIndex,
+ }: {
+ input: string;
+ itemIndex?: number;
+ }): FieldFilesValue => {
+ if (isDefined(itemIndex) && itemIndex >= 0 && itemIndex < files.length) {
+ return { ...files[itemIndex], label: input.trim() };
+ }
- const handleClickOutside = (
- updatedFiles: FieldFilesValue[],
- event: MouseEvent | TouchEvent,
- ) => {
- onClickOutside?.({
- newValue: parseFilesArrayToFilesValue(updatedFiles),
- event,
- });
+ throw new CustomError(
+ doNotTranslate('Cannot create file from text input'),
+ 'FILES_FIELD_INPUT_CANNOT_CREATE_FILE',
+ );
};
- const handleEscape = (updatedFiles: FieldFilesValue[]) => {
- onEscape?.({ newValue: parseFilesArrayToFilesValue(updatedFiles) });
+ const draft = useMultiItemDraft({
+ items: files,
+ onItemsChange: handleChange,
+ getItemText: getFileText,
+ validateInput: validateFileLabel,
+ formatInput: formatFileLabelInputOrThrow,
+ maxItemCount: maxNumberOfValues,
+ shouldOpenInputWhenEmpty: false,
+ onError: (hasError) =>
+ setRecordFieldInputIsFieldInError(hasError && files.length === 0),
+ });
+
+ const {
+ searchFilter,
+ setSearchFilter,
+ shouldShowSearch,
+ filteredItemEntries,
+ } = useMultiItemSearch({ items: files, getItemText: getFileText });
+
+ const handleInputEnter = () => {
+ const updatedItems = draft.commitInput();
+
+ if (!isDefined(updatedItems)) {
+ return;
+ }
+
+ if (draft.isSingleItemMode) {
+ onEnter?.({ newValue: parseFilesArrayToFilesValue(updatedItems) });
+ } else if (!isDeeplyEqual(files, updatedItems)) {
+ handleSubmit(updatedItems);
+ }
+
+ draft.closeInput();
};
- const handleEnter = (updatedFiles: FieldFilesValue[]) => {
- onEnter?.({ newValue: parseFilesArrayToFilesValue(updatedFiles) });
+ const handleEscape = () => {
+ onEscape?.({ newValue: parseFilesArrayToFilesValue(files) });
};
- const handleSubmit = (updatedFiles: FieldFilesValue[]) => {
- onSubmit?.({
- newValue: parseFilesArrayToFilesValue(updatedFiles),
- skipClose: true,
- });
+ useMultiItemFieldDismiss({
+ containerRef,
+ onEscape: handleEscape,
+ onClickOutside: (event) => {
+ const updatedItems = draft.isInputDisplayed ? draft.commitInput() : files;
+
+ if (!isDefined(updatedItems)) {
+ return;
+ }
+
+ onClickOutside?.({
+ newValue: parseFilesArrayToFilesValue(updatedItems),
+ event,
+ });
+ },
+ });
+
+ const handleDelete = (index: number) => {
+ const updatedFiles = toSpliced(files, index, 1);
+
+ handleChange(updatedFiles);
+ handleSubmit(updatedFiles);
+ draft.resetInputForItems(updatedFiles);
};
const handlePreview = (file: FieldFilesValue) => {
@@ -163,63 +221,74 @@ export const FilesFieldInput = () => {
setFilePreview(file);
};
- const validateInput = useCallback(
- (input: string) => ({
- isValid: input.trim().length > 0,
- errorMessage: '',
- }),
- [],
- );
-
- const formatInput = useCallback(
- (_input: string, index?: number): FieldFilesValue => {
- if (
- index !== undefined &&
- index >= 0 &&
- index < files.length &&
- isDefined(files)
- ) {
- const fileToEdit = files[index];
- return {
- ...fileToEdit,
- label: _input.trim(),
- };
- }
- throw new Error(doNotTranslate('Cannot create file from text input'));
- },
- [files],
- );
-
if (files.length === 0) {
return null;
}
+ const shouldShowItems =
+ isNonEmptyArray(filteredItemEntries) &&
+ (!draft.isSingleItemMode || !draft.isInputDisplayed);
+ const visibleItemEntries = shouldShowItems ? filteredItemEntries : undefined;
+ const shouldShowUploadButton =
+ !draft.isInputDisplayed && !draft.isLimitReached;
+
return (
- <MultiItemFieldInput
- items={files}
- onChange={handleChange}
- onEnter={handleEnter}
- onSubmit={handleSubmit}
- onEscape={handleEscape}
- onClickOutside={handleClickOutside}
- placeholder={t`File label`}
- fieldMetadataType={FieldMetadataType.FILES}
- validateInput={validateInput}
- formatInput={formatInput}
- renderItem={({ value: file, index, handleEdit, handleDelete }) => (
+ <OverlayMenuList
+ ref={containerRef}
+ header={
+ shouldShowSearch && !draft.isInputDisplayed ? (
+ <MultiItemFieldSearchHeader
+ value={searchFilter}
+ onChange={setSearchFilter}
+ />
+ ) : undefined
+ }
+ footer={
+ <>
+ {shouldShowItems &&
+ (draft.isInputDisplayed || shouldShowUploadButton) && (
+ <OverlayMenuListSeparator />
+ )}
+ {draft.isInputDisplayed && (
+ <MultiItemFieldInputRow
+ rightComponent={
+ <MultiItemFieldSaveButton
+ isAddingNewItem={draft.isAddingNewItem}
+ onClick={handleInputEnter}
+ />
+ }
+ >
+ <MultiItemFieldTextInput
+ autoFocus={!shouldShowSearch}
+ placeholder={t`File label`}
+ value={draft.inputValue}
+ hasError={draft.hasError}
+ onChange={draft.handleInputChange}
+ onEnter={handleInputEnter}
+ onEscape={handleEscape}
+ shouldPreventTabNavigation
+ />
+ </MultiItemFieldInputRow>
+ )}
+ {shouldShowUploadButton && (
+ <MultiItemFieldAddButton
+ label={isUploading ? t`Uploading...` : t`Upload file`}
+ onClick={handleUploadClick}
+ />
+ )}
+ </>
+ }
+ >
+ {visibleItemEntries?.map(({ item: file, index }) => (
<FilesFieldMenuItem
key={file.fileId}
dropdownId={`${MULTI_ITEM_FIELD_INPUT_DROPDOWN_ID_PREFIX}-${fieldDefinition.metadata.fieldName}-${index}`}
file={file}
- onEdit={handleEdit}
- onDelete={handleDelete}
+ onEdit={() => draft.startEditing(index)}
+ onDelete={() => handleDelete(index)}
onClick={() => handlePreview(file)}
/>
- )}
- newItemLabel={isUploading ? t`Uploading...` : t`Upload file`}
- onAddClick={handleUploadClick}
- onError={handleError}
- maxItemCount={maxNumberOfValues}
- />
+ ))}
+ </OverlayMenuList>
);
};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/LinksFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/LinksFieldInput.tsx
index 632730407a2..4a45b863501 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/LinksFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/LinksFieldInput.tsx
@@ -2,28 +2,48 @@ import { getLinksVariant } from '@/object-record/spreadsheet-import/utils/getLin
import { FieldInputEventContext } from '@/object-record/record-field/ui/contexts/FieldInputEventContext';
import { useLinksField } from '@/object-record/record-field/ui/meta-types/hooks/useLinksField';
import { LinksFieldMenuItem } from '@/object-record/record-field/ui/meta-types/input/components/LinksFieldMenuItem';
+import { MultiItemFieldAddButton } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldAddButton';
+import { MultiItemFieldInputRow } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInputRow';
+import { MultiItemFieldSaveButton } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSaveButton';
+import { MultiItemFieldSearchHeader } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSearchHeader';
+import { MultiItemFieldTextInput } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldTextInput';
import { MULTI_ITEM_FIELD_INPUT_DROPDOWN_ID_PREFIX } from '@/object-record/record-field/ui/meta-types/input/constants/MultiItemFieldInputDropdownClickOutsideId';
+import { useMultiItemDraft } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemDraft';
+import { useMultiItemFieldDismiss } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemFieldDismiss';
+import { useMultiItemSearch } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemSearch';
import { getFieldLinkDefinedLinks } from '@/object-record/record-field/ui/meta-types/input/utils/getFieldLinkDefinedLinks';
import { recordFieldInputIsFieldInErrorComponentState } from '@/object-record/record-field/ui/states/recordFieldInputIsFieldInErrorComponentState';
import { type FieldLinksValue } from '@/object-record/record-field/ui/types/FieldMetadata';
import { linksFieldValueSchema } from '@/object-record/record-field/ui/validation-schemas/linksFieldValueSchema';
+import { OverlayMenuList } from '@/ui/layout/overlay/components/OverlayMenuList';
+import { OverlayMenuListSeparator } from '@/ui/layout/overlay/components/OverlayMenuListSeparator';
import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
import { useLingui } from '@lingui/react/macro';
-import { useContext, useMemo } from 'react';
+import { useContext, useMemo, useRef } from 'react';
import { MULTI_ITEM_FIELD_DEFAULT_MAX_VALUES } from 'twenty-shared/constants';
import {
absoluteUrlSchema,
isDefined,
+ isNonEmptyArray,
isValidDomain,
} from 'twenty-shared/utils';
import { FieldMetadataType } from '~/generated-metadata/graphql';
-import { MultiItemFieldInput } from './MultiItemFieldInput';
+import { moveArrayItem } from '~/utils/array/moveArrayItem';
+import { toSpliced } from '~/utils/array/toSpliced';
+import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
type LinkRecord = {
- url: string | null;
+ url: string;
label: string | null;
};
+const getLinkText = (link: LinkRecord) => link.url;
+
+const formatLinkInput = ({ input }: { input: string }): LinkRecord => ({
+ url: input,
+ label: null,
+});
+
export const LinksFieldInput = () => {
const { t } = useLingui();
const { draftValue, fieldDefinition, setDraftValue } = useLinksField();
@@ -32,7 +52,9 @@ export const LinksFieldInput = () => {
FieldInputEventContext,
);
- const links = useMemo<{ url: string; label: string | null }[]>(
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ const links = useMemo<LinkRecord[]>(
() => getFieldLinkDefinedLinks(draftValue),
[draftValue],
);
@@ -51,9 +73,7 @@ export const LinksFieldInput = () => {
}
};
- const handleChange = (
- updatedLinks: { url: string | null; label: string | null }[],
- ) => {
+ const handleChange = (updatedLinks: LinkRecord[]) => {
const nextValue = parseArrayToLinksValue(updatedLinks);
if (isDefined(nextValue)) {
@@ -61,32 +81,6 @@ export const LinksFieldInput = () => {
}
};
- const getShowPrimaryIcon = (index: number) => index === 0 && links.length > 1;
- const getShowSetAsPrimaryButton = (index: number) => index > 0;
-
- const setRecordFieldInputIsFieldInError = useSetAtomComponentState(
- recordFieldInputIsFieldInErrorComponentState,
- );
-
- const handleError = (hasError: boolean, values: any[]) => {
- setRecordFieldInputIsFieldInError(hasError && values.length === 0);
- };
-
- const handleClickOutside = (
- updatedLinks: LinkRecord[],
- event: MouseEvent | TouchEvent,
- ) => {
- onClickOutside?.({ newValue: parseArrayToLinksValue(updatedLinks), event });
- };
-
- const handleEscape = (updatedLinks: LinkRecord[]) => {
- onEscape?.({ newValue: parseArrayToLinksValue(updatedLinks) });
- };
-
- const handleEnter = (updatedLinks: LinkRecord[]) => {
- onEnter?.({ newValue: parseArrayToLinksValue(updatedLinks) });
- };
-
const handleSubmit = (updatedLinks: LinkRecord[]) => {
onSubmit?.({
newValue: parseArrayToLinksValue(updatedLinks),
@@ -94,6 +88,10 @@ export const LinksFieldInput = () => {
});
};
+ const setRecordFieldInputIsFieldInError = useSetAtomComponentState(
+ recordFieldInputIsFieldInErrorComponentState,
+ );
+
const maxNumberOfValues =
fieldDefinition.metadata.settings?.maxNumberOfValues ??
MULTI_ITEM_FIELD_DEFAULT_MAX_VALUES;
@@ -104,47 +102,153 @@ export const LinksFieldInput = () => {
settings: fieldDefinition.metadata.settings,
}) === 'domain';
- const validateInput = (input: string) =>
- isDomainField
+ const validateLink = (input: string) => ({
+ isValid: isDomainField
? isValidDomain(input)
- : absoluteUrlSchema.safeParse(input).success;
+ : absoluteUrlSchema.safeParse(input).success,
+ errorMessage: '',
+ });
+
+ const draft = useMultiItemDraft({
+ items: links,
+ onItemsChange: handleChange,
+ getItemText: getLinkText,
+ validateInput: validateLink,
+ formatInput: formatLinkInput,
+ maxItemCount: maxNumberOfValues,
+ onError: (hasError) =>
+ setRecordFieldInputIsFieldInError(hasError && links.length === 0),
+ });
+
+ const {
+ searchFilter,
+ setSearchFilter,
+ shouldShowSearch,
+ filteredItemEntries,
+ } = useMultiItemSearch({ items: links, getItemText: getLinkText });
+
+ const handleInputEnter = () => {
+ const updatedItems = draft.commitInput();
+
+ if (!isDefined(updatedItems)) {
+ return;
+ }
+
+ if (draft.isSingleItemMode) {
+ onEnter?.({ newValue: parseArrayToLinksValue(updatedItems) });
+ } else if (!isDeeplyEqual(links, updatedItems)) {
+ handleSubmit(updatedItems);
+ }
+
+ draft.closeInput();
+ };
+
+ const handleEscape = () => {
+ onEscape?.({ newValue: parseArrayToLinksValue(links) });
+ };
+
+ useMultiItemFieldDismiss({
+ containerRef,
+ onEscape: handleEscape,
+ onClickOutside: (event) => {
+ const updatedItems = draft.isInputDisplayed ? draft.commitInput() : links;
+
+ if (!isDefined(updatedItems)) {
+ return;
+ }
+
+ onClickOutside?.({
+ newValue: parseArrayToLinksValue(updatedItems),
+ event,
+ });
+ },
+ });
+
+ const handleSetAsPrimary = (index: number) => {
+ const updatedLinks = moveArrayItem(links, { fromIndex: index, toIndex: 0 });
+
+ handleChange(updatedLinks);
+ handleSubmit(updatedLinks);
+ };
+
+ const handleDelete = (index: number) => {
+ const updatedLinks = toSpliced(links, index, 1);
+
+ handleChange(updatedLinks);
+ handleSubmit(updatedLinks);
+ draft.resetInputForItems(updatedLinks);
+ };
+
+ const placeholder = isDomainField ? t`Domain` : t`URL`;
+
+ const shouldShowItems =
+ isNonEmptyArray(filteredItemEntries) &&
+ (!draft.isSingleItemMode || !draft.isInputDisplayed);
+ const visibleItemEntries = shouldShowItems ? filteredItemEntries : undefined;
+ const shouldShowAddButton = !draft.isInputDisplayed && !draft.isLimitReached;
return (
- <MultiItemFieldInput
- items={links}
- onChange={handleChange}
- onEscape={handleEscape}
- onEnter={handleEnter}
- onSubmit={handleSubmit}
- onClickOutside={handleClickOutside}
- placeholder={isDomainField ? t`Domain` : t`URL`}
- fieldMetadataType={FieldMetadataType.LINKS}
- validateInput={(input) => ({
- isValid: validateInput(input),
- errorMessage: '',
- })}
- onError={handleError}
- formatInput={(input) => ({ url: input, label: null })}
- renderItem={({
- value: link,
- index,
- handleEdit,
- handleSetPrimary,
- handleDelete,
- }) => (
+ <OverlayMenuList
+ ref={containerRef}
+ header={
+ shouldShowSearch && !draft.isInputDisplayed ? (
+ <MultiItemFieldSearchHeader
+ value={searchFilter}
+ onChange={setSearchFilter}
+ />
+ ) : undefined
+ }
+ footer={
+ <>
+ {shouldShowItems &&
+ (draft.isInputDisplayed || shouldShowAddButton) && (
+ <OverlayMenuListSeparator />
+ )}
+ {draft.isInputDisplayed && (
+ <MultiItemFieldInputRow
+ rightComponent={
+ isNonEmptyArray(links) ? (
+ <MultiItemFieldSaveButton
+ isAddingNewItem={draft.isAddingNewItem}
+ onClick={handleInputEnter}
+ />
+ ) : undefined
+ }
+ >
+ <MultiItemFieldTextInput
+ autoFocus={!shouldShowSearch}
+ placeholder={placeholder}
+ value={draft.inputValue}
+ hasError={draft.hasError}
+ onChange={draft.handleInputChange}
+ onEnter={handleInputEnter}
+ onEscape={handleEscape}
+ shouldPreventTabNavigation
+ />
+ </MultiItemFieldInputRow>
+ )}
+ {shouldShowAddButton && (
+ <MultiItemFieldAddButton
+ label={t`Add ${placeholder}`}
+ onClick={draft.startAdding}
+ />
+ )}
+ </>
+ }
+ >
+ {visibleItemEntries?.map(({ item: link, index }) => (
<LinksFieldMenuItem
key={index}
dropdownId={`${MULTI_ITEM_FIELD_INPUT_DROPDOWN_ID_PREFIX}-${fieldDefinition.metadata.fieldName}-${index}`}
- showPrimaryIcon={getShowPrimaryIcon(index)}
- showSetAsPrimaryButton={getShowSetAsPrimaryButton(index)}
+ showPrimaryIcon={index === 0 && links.length > 1}
+ showSetAsPrimaryButton={index > 0}
label={link.label}
- onEdit={handleEdit}
- onSetAsPrimary={handleSetPrimary}
- onDelete={handleDelete}
+ onEdit={() => draft.startEditing(index)}
+ onSetAsPrimary={() => handleSetAsPrimary(index)}
+ onDelete={() => handleDelete(index)}
url={link.url}
/>
- )}
- maxItemCount={maxNumberOfValues}
- />
+ ))}
+ </OverlayMenuList>
);
};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemBaseInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemBaseInput.tsx
deleted file mode 100644
index 8845c7ef271..00000000000
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemBaseInput.tsx
+++ /dev/null
@@ -1,153 +0,0 @@
-import { styled } from '@linaria/react';
-import { useRef, type KeyboardEvent, type Ref } from 'react';
-import { type MultiItemBaseInputProps } from '@/object-record/record-field/ui/meta-types/input/types/MultiItemBaseInputProps';
-import { isKeyboardEventComposing } from '@/ui/utilities/hotkey/utils/isKeyboardEventComposing';
-import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';
-import { Key } from 'ts-key-enum';
-import { isNonEmptyString } from '@sniptt/guards';
-import { themeCssVariables } from 'twenty-ui/theme';
-import { isDefined } from 'twenty-shared/utils';
-import { Input } from 'twenty-ui/primitives/input';
-import { combineRefs } from '~/utils/combineRefs';
-
-const StyledInputContent = styled.div<{ hasRightComponent: boolean }>`
- align-items: center;
- box-sizing: border-box;
- display: flex;
- min-height: ${themeCssVariables.spacing[8]};
- padding-inline-end: ${({ hasRightComponent }) =>
- hasRightComponent ? themeCssVariables.spacing[8] : '0'};
- padding-inline-start: ${themeCssVariables.spacing[2]};
-`;
-
-const StyledInputContainer = styled.div`
- background-color: transparent;
- box-sizing: border-box;
- position: relative;
- width: 100%;
-
- &:not(:first-of-type) {
- padding: ${themeCssVariables.spacing[1]};
- }
-`;
-
-const StyledRightContainer = styled.div`
- position: absolute;
- right: ${themeCssVariables.spacing[2]};
- top: 50%;
- transform: translateY(-50%);
-`;
-
-const StyledErrorDiv = styled.div`
- color: ${themeCssVariables.color.red};
- padding: 0 ${themeCssVariables.spacing[2]};
-`;
-
-export const MultiItemBaseInput = ({
- autoFocus,
- className,
- value,
- placeholder,
- onChange,
- onClickOutside,
- onEnter,
- onEscape,
- onShiftTab,
- onTab,
- preventTabNavigation = false,
- onFocus,
- onBlur,
- rightComponent,
- renderInput,
- error = '',
- hasError = false,
- instanceId,
- ref,
-}: MultiItemBaseInputProps & { ref?: Ref<HTMLInputElement> }) => {
- const inputRef = useRef<HTMLInputElement>(null);
- const combinedRef = combineRefs(ref, inputRef);
-
- useListenClickOutside({
- refs: [inputRef],
- callback: () => onClickOutside?.(),
- listenerId: instanceId,
- enabled: isDefined(onClickOutside),
- });
-
- const getKeyDownHandler = (event: KeyboardEvent<HTMLInputElement>) => {
- switch (event.key) {
- case Key.Enter:
- return onEnter;
- case Key.Escape:
- return onEscape;
- case Key.Tab:
- return event.shiftKey ? onShiftTab : onTab;
- default:
- return undefined;
- }
- };
-
- const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
- const hasUnsupportedModifier =
- event.altKey ||
- event.ctrlKey ||
- event.metaKey ||
- (event.shiftKey && event.key !== Key.Tab);
-
- if (isKeyboardEventComposing(event.nativeEvent) || hasUnsupportedModifier) {
- return;
- }
-
- if (event.key === Key.Tab && preventTabNavigation) {
- event.preventDefault();
- }
-
- const handler = getKeyDownHandler(event);
-
- if (!isDefined(handler)) {
- return;
- }
-
- event.preventDefault();
- event.stopPropagation();
- handler();
- };
-
- return (
- <>
- <StyledInputContainer className={className}>
- {isDefined(renderInput) ? (
- renderInput({
- value,
- onChange,
- autoFocus,
- placeholder,
- hasError,
- onKeyDown: handleKeyDown,
- onFocus,
- onBlur,
- })
- ) : (
- <StyledInputContent hasRightComponent={isDefined(rightComponent)}>
- <Input
- variant="plain"
- aria-invalid={hasError || undefined}
- autoFocus={autoFocus}
- value={value}
- placeholder={placeholder}
- onChange={(event) => onChange(event.target.value)}
- ref={combinedRef}
- onFocus={onFocus}
- onBlur={onBlur}
- onKeyDown={handleKeyDown}
- />
- </StyledInputContent>
- )}
- {isDefined(rightComponent) && (
- <StyledRightContainer>{rightComponent}</StyledRightContainer>
- )}
- </StyledInputContainer>
- {isNonEmptyString(error) && <StyledErrorDiv>{error}</StyledErrorDiv>}
- </>
- );
-};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldAddButton.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldAddButton.tsx
new file mode 100644
index 00000000000..e9eb63e30c5
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldAddButton.tsx
@@ -0,0 +1,25 @@
+import { styled } from '@linaria/react';
+import { ListItemButton } from 'twenty-ui/components/navigation';
+import { IconPlus } from 'twenty-ui/icon';
+import { OverflowingTextWithTooltip } from 'twenty-ui/primitives/typography';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+const StyledAddItemContainer = styled.div`
+ padding: ${themeCssVariables.spacing[1]};
+`;
+
+type MultiItemFieldAddButtonProps = {
+ label: string;
+ onClick: () => void;
+};
+
+export const MultiItemFieldAddButton = ({
+ label,
+ onClick,
+}: MultiItemFieldAddButtonProps) => (
+ <StyledAddItemContainer>
+ <ListItemButton onClick={onClick} startIcon={<IconPlus />}>
+ <OverflowingTextWithTooltip text={label} />
+ </ListItemButton>
+ </StyledAddItemContainer>
+);
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInput.tsx
deleted file mode 100644
index d667cbe9dc1..00000000000
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInput.tsx
+++ /dev/null
@@ -1,406 +0,0 @@
-import { ListItemButton } from 'twenty-ui/components/navigation';
-import { MultiItemBaseInput } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemBaseInput';
-import { type MultiItemBaseInputProps } from '@/object-record/record-field/ui/meta-types/input/types/MultiItemBaseInputProps';
-import { computeUpdatedMultiItemFieldItems } from '@/object-record/record-field/ui/meta-types/input/utils/computeUpdatedMultiItemFieldItems';
-import { sanitizeAndValidateInput } from '@/object-record/record-field/ui/meta-types/input/utils/sanitizeAndValidateInput';
-import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';
-import { type PhoneRecord } from '@/object-record/record-field/ui/types/FieldMetadata';
-import { OverlayMenuList } from '@/ui/layout/overlay/components/OverlayMenuList';
-import { OverlayMenuListSearchRow } from '@/ui/layout/overlay/components/OverlayMenuListSearchRow';
-import { OverlayMenuListSeparator } from '@/ui/layout/overlay/components/OverlayMenuListSeparator';
-import { currentFocusedItemSelector } from '@/ui/utilities/focus/states/currentFocusedItemSelector';
-import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';
-import { useHotkeysOnFocusedElement } from '@/ui/utilities/hotkey/hooks/useHotkeysOnFocusedElement';
-import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';
-import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';
-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-import { styled } from '@linaria/react';
-import { t } from '@lingui/core/macro';
-import { isNonEmptyString } from '@sniptt/guards';
-import React, { useCallback, useMemo, useRef, useState } from 'react';
-import { Key } from 'ts-key-enum';
-import { CustomError, isDefined, isNonEmptyArray } from 'twenty-shared/utils';
-import { doNotTranslate } from 'twenty-shared/i18n';
-import { LightIconButton } from 'twenty-ui/components/input';
-import { OverflowingTextWithTooltip } from 'twenty-ui/primitives/typography';
-import { IconCheck, IconPlus } from 'twenty-ui/icon';
-import { themeCssVariables } from 'twenty-ui/theme';
-import { useDebounce } from 'use-debounce';
-import { FieldMetadataType } from '~/generated-metadata/graphql';
-import { moveArrayItem } from '~/utils/array/moveArrayItem';
-import { toSpliced } from '~/utils/array/toSpliced';
-import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
-import { turnIntoEmptyStringIfWhitespacesOnly } from '~/utils/string/turnIntoEmptyStringIfWhitespacesOnly';
-import { normalizeSearchText } from 'twenty-ui/utilities';
-
-const StyledAddItemContainer = styled.div`
- padding: ${themeCssVariables.spacing[1]};
-`;
-
-type MultiItemFieldInputProps<T> = {
- items: T[];
- onChange: (newItemsValue: T[]) => void;
- onEscape: (newItemsValue: T[]) => void;
- onEnter: (newItemsValue: T[]) => void;
- onSubmit: (newItemsValue: T[]) => void;
- onClickOutside: (newItemsValue: T[], event: MouseEvent | TouchEvent) => void;
- onError?: (hasError: boolean, values: any[]) => void;
- placeholder: string;
- validateInput?: (input: string) => { isValid: boolean; errorMessage: string };
- formatInput?: (input: string, itemIndex?: number) => T;
- renderItem: (props: {
- value: T;
- index: number;
- handleEdit: () => void;
- handleSetPrimary: () => void;
- handleDelete: () => void;
- }) => React.ReactNode;
- newItemLabel?: string;
- onAddClick?: () => void;
- fieldMetadataType: FieldMetadataType;
- renderInput?: MultiItemBaseInputProps['renderInput'];
- maxItemCount?: number;
-};
-
-// TODO: replace renderInput/renderItem/formatInput with a hook exposing them through context.
-export const MultiItemFieldInput = <T,>({
- items,
- onChange,
- onEscape,
- onEnter,
- onSubmit,
- onError,
- placeholder,
- validateInput,
- formatInput,
- renderItem,
- newItemLabel,
- onAddClick,
- fieldMetadataType,
- renderInput,
- onClickOutside,
- maxItemCount,
-}: MultiItemFieldInputProps<T>) => {
- const containerRef = useRef<HTMLDivElement>(null);
-
- const instanceId = useAvailableComponentInstanceIdOrThrow(
- RecordFieldComponentInstanceContext,
- );
-
- const currentFocusedItem = useAtomStateValue(currentFocusedItemSelector);
-
- useListenClickOutside({
- refs: [containerRef],
- callback: (event) => {
- if (
- currentFocusedItem?.componentInstance.componentType !==
- FocusComponentType.OPENED_FIELD_INPUT
- ) {
- return;
- }
-
- if (isInputDisplayed) {
- const { isValid, updatedItems } = validateInputAndComputeUpdatedItems();
-
- if (!isValid) {
- return;
- }
-
- onChange(updatedItems);
- onClickOutside(updatedItems, event);
-
- return;
- }
-
- onClickOutside(items, event);
- },
- listenerId: instanceId,
- });
-
- const getItemValueAsString = useCallback(
- (index: number): string => {
- if (index >= items.length) {
- return '';
- }
-
- let item;
- switch (fieldMetadataType) {
- case FieldMetadataType.LINKS:
- item = items[index] as { label: string; url: string };
- return item.url || '';
- case FieldMetadataType.PHONES:
- item = items[index] as PhoneRecord;
- return item.callingCode + item.number;
- case FieldMetadataType.EMAILS:
- item = items[index] as string;
- return item;
- case FieldMetadataType.ARRAY:
- item = items[index] as string;
- return item;
- case FieldMetadataType.FILES:
- item = items[index] as { label: string };
- return item.label || '';
- default:
- throw new CustomError(
- doNotTranslate(`Unsupported field type: ${fieldMetadataType}`),
- 'UNSUPPORTED_FIELD_TYPE',
- );
- }
- },
- [items, fieldMetadataType],
- );
-
- const shouldAutoEnterBecauseOnlyOneItemIsAllowed = maxItemCount === 1;
- const shouldAutoEditFirstItemOnOpen =
- items.length === 0 || maxItemCount === 1;
-
- const [isInputDisplayed, setIsInputDisplayed] = useState(
- shouldAutoEditFirstItemOnOpen && !isDefined(onAddClick),
- );
-
- const [inputValue, setInputValue] = useState(
- shouldAutoEditFirstItemOnOpen && !isDefined(onAddClick)
- ? getItemValueAsString(0)
- : '',
- );
-
- const [itemToEditIndex, setItemToEditIndex] = useState(0);
- const [isAddingNewItem, setIsAddingNewItem] = useState(false);
-
- const [errorData, setErrorData] = useState({
- isValid: true,
- errorMessage: '',
- });
-
- const [searchFilter, setSearchFilter] = useState('');
- const [debouncedSearchFilter] = useDebounce(searchFilter, 150);
-
- const shouldShowSearch = items.length > 3;
-
- const filteredItems = useMemo(() => {
- if (!shouldShowSearch || !debouncedSearchFilter) {
- return items;
- }
- const searchTerm = normalizeSearchText(debouncedSearchFilter);
- return items.filter((_item, index) => {
- const itemText = getItemValueAsString(index);
- return normalizeSearchText(itemText).includes(searchTerm);
- });
- }, [items, debouncedSearchFilter, shouldShowSearch, getItemValueAsString]);
-
- const isLimitReached =
- typeof maxItemCount === 'number' && items.length >= maxItemCount;
-
- const handleInputChange = (value: string) => {
- setInputValue(value);
-
- if (!validateInput) return;
-
- setErrorData(
- errorData.isValid ? errorData : { isValid: true, errorMessage: '' },
- );
-
- onError?.(false, items);
- };
-
- const handleAddButtonClick = () => {
- if (isLimitReached) {
- return;
- }
-
- if (isDefined(onAddClick)) {
- onAddClick();
- return;
- }
-
- setIsAddingNewItem(true);
- setInputValue('');
- setIsInputDisplayed(true);
- };
-
- const handleEditButtonClick = (index: number) => {
- setItemToEditIndex(index);
- setInputValue(getItemValueAsString(index));
- setIsAddingNewItem(false);
- setIsInputDisplayed(true);
- };
-
- const handleEnter = () => {
- const { isValid, updatedItems } = validateInputAndComputeUpdatedItems();
- if (!isValid) {
- return;
- }
-
- onChange(updatedItems);
-
- if (shouldAutoEnterBecauseOnlyOneItemIsAllowed) {
- onEnter(updatedItems);
- } else if (!isDeeplyEqual(items, updatedItems)) {
- onSubmit(updatedItems);
- }
-
- setIsInputDisplayed(false);
- setIsAddingNewItem(false);
- setInputValue('');
- };
-
- const showInputIfNoItemsRemain = (remainingItems: T[]) => {
- const shouldShowInput =
- remainingItems.length === 0 && !isDefined(onAddClick);
- setIsInputDisplayed(shouldShowInput);
- setIsAddingNewItem(false);
- if (shouldShowInput) {
- setInputValue('');
- }
- };
-
- const validateInputAndComputeUpdatedItems = (): {
- isValid: boolean;
- updatedItems: T[];
- } => {
- const { sanitizedInput, isValid, errorMessage } = sanitizeAndValidateInput(
- inputValue,
- validateInput,
- );
-
- if (!isValid) {
- onError?.(true, items);
- setErrorData({ isValid: false, errorMessage });
- return { isValid: false, updatedItems: items };
- }
-
- const editingIndex = isAddingNewItem ? null : itemToEditIndex;
-
- const updatedItems = computeUpdatedMultiItemFieldItems({
- sanitizedInput,
- items,
- editingIndex,
- singleItemMode: shouldAutoEnterBecauseOnlyOneItemIsAllowed,
- formatInput,
- });
-
- const isItemDeletion =
- !isNonEmptyString(sanitizedInput) &&
- isDefined(editingIndex) &&
- !shouldAutoEnterBecauseOnlyOneItemIsAllowed;
-
- if (isItemDeletion) {
- showInputIfNoItemsRemain(updatedItems);
- }
-
- return { isValid: true, updatedItems };
- };
-
- const handleSetPrimaryItem = (index: number) => {
- const updatedItems = moveArrayItem(items, { fromIndex: index, toIndex: 0 });
- onChange(updatedItems);
- onSubmit(updatedItems);
- };
-
- const handleDeleteItem = (index: number) => {
- const updatedItems = toSpliced(items, index, 1);
- onChange(updatedItems);
- onSubmit(updatedItems);
- showInputIfNoItemsRemain(updatedItems);
- };
-
- const handleEscape = () => {
- onEscape(items);
- };
-
- useHotkeysOnFocusedElement({
- focusId: instanceId,
- keys: [Key.Escape],
- callback: handleEscape,
- dependencies: [handleEscape],
- });
-
- const shouldShowItems =
- isNonEmptyArray(filteredItems) &&
- (!shouldAutoEnterBecauseOnlyOneItemIsAllowed || !isInputDisplayed);
-
- return (
- <OverlayMenuList
- ref={containerRef}
- header={
- shouldShowSearch && !isInputDisplayed ? (
- <>
- <OverlayMenuListSearchRow
- value={searchFilter}
- onChange={(event) =>
- setSearchFilter(
- turnIntoEmptyStringIfWhitespacesOnly(
- event.currentTarget.value,
- ),
- )
- }
- />
- <OverlayMenuListSeparator />
- </>
- ) : undefined
- }
- footer={
- <>
- {shouldShowItems && (isInputDisplayed || !isLimitReached) && (
- <OverlayMenuListSeparator />
- )}
- {isInputDisplayed ? (
- <MultiItemBaseInput
- instanceId={instanceId}
- autoFocus={!shouldShowSearch}
- placeholder={placeholder}
- value={inputValue}
- hasError={!errorData.isValid}
- renderInput={renderInput}
- onEscape={handleEscape}
- onChange={(value) => {
- value
- ? handleInputChange(
- turnIntoEmptyStringIfWhitespacesOnly(value),
- )
- : handleInputChange('');
- }}
- onEnter={handleEnter}
- preventTabNavigation
- rightComponent={
- isNonEmptyArray(items) ? (
- <LightIconButton
- onClick={handleEnter}
- aria-label={isAddingNewItem ? t`Add item` : t`Save item`}
- >
- {isAddingNewItem ? <IconPlus /> : <IconCheck />}
- </LightIconButton>
- ) : null
- }
- />
- ) : !isLimitReached ? (
- <StyledAddItemContainer>
- <ListItemButton
- onClick={handleAddButtonClick}
- startIcon={<IconPlus />}
- >
- <OverflowingTextWithTooltip
- text={newItemLabel || t`Add ${placeholder}`}
- />
- </ListItemButton>
- </StyledAddItemContainer>
- ) : null}
- </>
- }
- >
- {shouldShowItems
- ? filteredItems.map((item) => {
- const originalIndex = items.indexOf(item);
-
- return renderItem({
- value: item,
- index: originalIndex,
- handleEdit: () => handleEditButtonClick(originalIndex),
- handleSetPrimary: () => handleSetPrimaryItem(originalIndex),
- handleDelete: () => handleDeleteItem(originalIndex),
- });
- })
- : undefined}
- </OverlayMenuList>
- );
-};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInputRow.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInputRow.tsx
new file mode 100644
index 00000000000..9e290bbbecd
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInputRow.tsx
@@ -0,0 +1,41 @@
+import { styled } from '@linaria/react';
+import { type ReactNode } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+const StyledInputRow = styled.div`
+ align-items: center;
+ box-sizing: border-box;
+ display: flex;
+ min-height: ${themeCssVariables.spacing[8]};
+ width: 100%;
+
+ &:not(:first-of-type) {
+ padding: ${themeCssVariables.spacing[1]};
+ }
+`;
+
+const StyledRightContainer = styled.div`
+ display: flex;
+ flex-shrink: 0;
+ padding-inline-end: ${themeCssVariables.spacing[2]};
+`;
+
+type MultiItemFieldInputRowProps = {
+ children: ReactNode;
+ rightComponent?: ReactNode;
+ className?: string;
+};
+
+export const MultiItemFieldInputRow = ({
+ children,
+ rightComponent,
+ className,
+}: MultiItemFieldInputRowProps) => (
+ <StyledInputRow className={className}>
+ {children}
+ {isDefined(rightComponent) && (
+ <StyledRightContainer>{rightComponent}</StyledRightContainer>
+ )}
+ </StyledInputRow>
+);
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSaveButton.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSaveButton.tsx
new file mode 100644
index 00000000000..004029bd92c
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSaveButton.tsx
@@ -0,0 +1,20 @@
+import { t } from '@lingui/core/macro';
+import { LightIconButton } from 'twenty-ui/components/input';
+import { IconCheck, IconPlus } from 'twenty-ui/icon';
+
+type MultiItemFieldSaveButtonProps = {
+ isAddingNewItem: boolean;
+ onClick: () => void;
+};
+
+export const MultiItemFieldSaveButton = ({
+ isAddingNewItem,
+ onClick,
+}: MultiItemFieldSaveButtonProps) => (
+ <LightIconButton
+ onClick={onClick}
+ aria-label={isAddingNewItem ? t`Add item` : t`Save item`}
+ >
+ {isAddingNewItem ? <IconPlus /> : <IconCheck />}
+ </LightIconButton>
+);
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSearchHeader.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSearchHeader.tsx
new file mode 100644
index 00000000000..6b93682fb37
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSearchHeader.tsx
@@ -0,0 +1,25 @@
+import { OverlayMenuListSearchRow } from '@/ui/layout/overlay/components/OverlayMenuListSearchRow';
+import { OverlayMenuListSeparator } from '@/ui/layout/overlay/components/OverlayMenuListSeparator';
+import { turnIntoEmptyStringIfWhitespacesOnly } from '~/utils/string/turnIntoEmptyStringIfWhitespacesOnly';
+
+type MultiItemFieldSearchHeaderProps = {
+ value: string;
+ onChange: (value: string) => void;
+};
+
+export const MultiItemFieldSearchHeader = ({
+ value,
+ onChange,
+}: MultiItemFieldSearchHeaderProps) => (
+ <>
+ <OverlayMenuListSearchRow
+ value={value}
+ onChange={(event) =>
+ onChange(
+ turnIntoEmptyStringIfWhitespacesOnly(event.currentTarget.value),
+ )
+ }
+ />
+ <OverlayMenuListSeparator />
+ </>
+);
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldTextInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldTextInput.tsx
new file mode 100644
index 00000000000..066c2519d2d
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldTextInput.tsx
@@ -0,0 +1,68 @@
+import { getMultiItemInputKeyDownHandler } from '@/object-record/record-field/ui/meta-types/input/utils/getMultiItemInputKeyDownHandler';
+import { styled } from '@linaria/react';
+import { type FocusEvent, type Ref } from 'react';
+import { Input } from 'twenty-ui/primitives/input';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+const StyledInputContent = styled.div`
+ align-items: center;
+ box-sizing: border-box;
+ display: flex;
+ flex: 1;
+ min-width: 0;
+ padding-inline-start: ${themeCssVariables.spacing[2]};
+`;
+
+type MultiItemFieldTextInputProps = {
+ value: string;
+ onChange: (value: string) => void;
+ placeholder?: string;
+ autoFocus?: boolean;
+ hasError?: boolean;
+ onEnter?: () => void;
+ onEscape?: () => void;
+ onTab?: () => void;
+ onShiftTab?: () => void;
+ shouldPreventTabNavigation?: boolean;
+ onFocus?: (event: FocusEvent<HTMLInputElement>) => void;
+ onBlur?: (event: FocusEvent<HTMLInputElement>) => void;
+ ref?: Ref<HTMLInputElement>;
+};
+
+export const MultiItemFieldTextInput = ({
+ value,
+ onChange,
+ placeholder,
+ autoFocus,
+ hasError = false,
+ onEnter,
+ onEscape,
+ onTab,
+ onShiftTab,
+ shouldPreventTabNavigation,
+ onFocus,
+ onBlur,
+ ref,
+}: MultiItemFieldTextInputProps) => (
+ <StyledInputContent>
+ <Input
+ variant="plain"
+ hasFocusRing={false}
+ aria-invalid={hasError || undefined}
+ autoFocus={autoFocus}
+ value={value}
+ placeholder={placeholder}
+ onChange={(event) => onChange(event.target.value)}
+ ref={ref}
+ onFocus={onFocus}
+ onBlur={onBlur}
+ onKeyDown={getMultiItemInputKeyDownHandler({
+ onEnter,
+ onEscape,
+ onTab,
+ onShiftTab,
+ shouldPreventTabNavigation,
+ })}
+ />
+ </StyledInputContent>
+);
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/PhonesFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/PhonesFieldInput.tsx
index 12207db5a25..06336b6d285 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/PhonesFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/PhonesFieldInput.tsx
@@ -1,30 +1,39 @@
-import { t } from '@lingui/core/macro';
+import { FieldInputEventContext } from '@/object-record/record-field/ui/contexts/FieldInputEventContext';
import { usePhonesField } from '@/object-record/record-field/ui/meta-types/hooks/usePhonesField';
+import { MultiItemFieldAddButton } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldAddButton';
+import { MultiItemFieldInputRow } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInputRow';
+import { MultiItemFieldSaveButton } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSaveButton';
+import { MultiItemFieldSearchHeader } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldSearchHeader';
import { PhonesFieldMenuItem } from '@/object-record/record-field/ui/meta-types/input/components/PhonesFieldMenuItem';
-import { recordFieldInputIsFieldInErrorComponentState } from '@/object-record/record-field/ui/states/recordFieldInputIsFieldInErrorComponentState';
-import { phoneSchema } from '@/object-record/record-field/ui/validation-schemas/phoneSchema';
-import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
-import { styled } from '@linaria/react';
-import { parsePhoneNumber, type E164Number } from 'libphonenumber-js';
-import ReactPhoneNumberInput from 'react-phone-number-input';
-import 'react-phone-number-input/style.css';
-
-import { MultiItemFieldInput } from './MultiItemFieldInput';
-
-import { FieldInputEventContext } from '@/object-record/record-field/ui/contexts/FieldInputEventContext';
import { MULTI_ITEM_FIELD_INPUT_DROPDOWN_ID_PREFIX } from '@/object-record/record-field/ui/meta-types/input/constants/MultiItemFieldInputDropdownClickOutsideId';
+import { useMultiItemDraft } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemDraft';
+import { useMultiItemFieldDismiss } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemFieldDismiss';
+import { useMultiItemSearch } from '@/object-record/record-field/ui/meta-types/input/hooks/useMultiItemSearch';
+import { getMultiItemInputKeyDownHandler } from '@/object-record/record-field/ui/meta-types/input/utils/getMultiItemInputKeyDownHandler';
import { createPhonesFromFieldValue } from '@/object-record/record-field/ui/meta-types/input/utils/phonesUtils';
+import { recordFieldInputIsFieldInErrorComponentState } from '@/object-record/record-field/ui/states/recordFieldInputIsFieldInErrorComponentState';
import {
type FieldPhonesValue,
type PhoneRecord,
} from '@/object-record/record-field/ui/types/FieldMetadata';
+import { phoneSchema } from '@/object-record/record-field/ui/validation-schemas/phoneSchema';
import { phonesFieldValueSchema } from '@/object-record/record-field/ui/validation-schemas/phonesFieldValueSchema';
import { PhoneCountryPickerDropdownButton } from '@/ui/input/components/internal/phone/components/PhoneCountryPickerDropdownButton';
-import { useContext } from 'react';
+import { OverlayMenuList } from '@/ui/layout/overlay/components/OverlayMenuList';
+import { OverlayMenuListSeparator } from '@/ui/layout/overlay/components/OverlayMenuListSeparator';
+import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
+import { styled } from '@linaria/react';
+import { t } from '@lingui/core/macro';
+import { parsePhoneNumber, type E164Number } from 'libphonenumber-js';
+import { useContext, useRef } from 'react';
+import ReactPhoneNumberInput from 'react-phone-number-input';
+import 'react-phone-number-input/style.css';
import { MULTI_ITEM_FIELD_DEFAULT_MAX_VALUES } from 'twenty-shared/constants';
-import { isDefined } from 'twenty-shared/utils';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
import { themeCssVariables } from 'twenty-ui/theme';
-import { FieldMetadataType } from '~/generated-metadata/graphql';
+import { moveArrayItem } from '~/utils/array/moveArrayItem';
+import { toSpliced } from '~/utils/array/toSpliced';
+import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
import { stripSimpleQuotesFromString } from '~/utils/string/stripSimpleQuotesFromString';
const StyledCustomPhoneInputContainer = styled.div<{
@@ -40,7 +49,9 @@ const StyledCustomPhoneInputContainer = styled.div<{
: `1px solid ${themeCssVariables.border.color.medium}`
: 'none'};
border-radius: ${({ hasItem }) => (hasItem ? '4px' : '0')};
+ flex: 1;
height: ${({ hasItem }) => (hasItem ? '30px' : 'auto')};
+ min-width: 0;
`;
const StyledCustomPhoneInputWrapper = styled.div`
@@ -51,7 +62,7 @@ const StyledCustomPhoneInputWrapper = styled.div`
font-size: inherit;
font-weight: inherit;
height: 100%;
- width: calc(100% - ${themeCssVariables.spacing[8]});
+ width: 100%;
.PhoneInput {
height: 100%;
@@ -78,6 +89,40 @@ const StyledCustomPhoneInputWrapper = styled.div`
}
`;
+const EMPTY_PHONE: PhoneRecord = {
+ number: '',
+ callingCode: '',
+ countryCode: '',
+};
+
+const getPhoneText = ({
+ callingCode,
+ number,
+}: Pick<PhoneRecord, 'callingCode' | 'number'>) => callingCode + number;
+
+const validatePhone = (input: string) => ({
+ isValid: phoneSchema.safeParse(input).success,
+ errorMessage: '',
+});
+
+const formatPhoneInput = ({ input }: { input: string }): PhoneRecord => {
+ if (input === '') {
+ return EMPTY_PHONE;
+ }
+
+ const phone = parsePhoneNumber(input);
+
+ if (!isDefined(phone)) {
+ return EMPTY_PHONE;
+ }
+
+ return {
+ number: phone.nationalNumber,
+ callingCode: `+${phone.countryCallingCode}`,
+ countryCode: phone.country ?? '',
+ };
+};
+
export const PhonesFieldInput = () => {
const { fieldDefinition, setDraftValue, draftValue } = usePhonesField();
@@ -85,6 +130,8 @@ export const PhonesFieldInput = () => {
FieldInputEventContext,
);
+ const containerRef = useRef<HTMLDivElement>(null);
+
const phones = createPhonesFromFieldValue(draftValue);
const defaultCountry = stripSimpleQuotesFromString(
@@ -110,7 +157,7 @@ export const PhonesFieldInput = () => {
}
};
- const handlePhonesChange = (updatedPhones: PhoneRecord[]) => {
+ const handleChange = (updatedPhones: PhoneRecord[]) => {
const nextValue = parseArrayToPhonesValue(updatedPhones);
if (isDefined(nextValue)) {
@@ -118,136 +165,173 @@ export const PhonesFieldInput = () => {
}
};
- const validateInput = (input: string) => ({
- isValid: phoneSchema.safeParse(input).success,
- errorMessage: '',
- });
-
- const getShowPrimaryIcon = (index: number) =>
- index === 0 && phones.length > 1;
- const getShowSetAsPrimaryButton = (index: number) => index > 0;
+ const handleSubmit = (updatedPhones: PhoneRecord[]) => {
+ onSubmit?.({
+ newValue: parseArrayToPhonesValue(updatedPhones),
+ skipClose: true,
+ });
+ };
const setRecordFieldInputIsFieldInError = useSetAtomComponentState(
recordFieldInputIsFieldInErrorComponentState,
);
- const handleError = (hasError: boolean, values: any[]) => {
- setRecordFieldInputIsFieldInError(hasError && values.length === 0);
- };
+ const draft = useMultiItemDraft({
+ items: phones,
+ onItemsChange: handleChange,
+ getItemText: getPhoneText,
+ validateInput: validatePhone,
+ formatInput: formatPhoneInput,
+ maxItemCount: maxNumberOfValues,
+ onError: (hasError) =>
+ setRecordFieldInputIsFieldInError(hasError && phones.length === 0),
+ });
- const handleClickOutside = (
- updatedPhones: PhoneRecord[],
- event: MouseEvent | TouchEvent,
- ) => {
- onClickOutside?.({
- newValue: parseArrayToPhonesValue(updatedPhones),
- event,
- });
- };
+ const {
+ searchFilter,
+ setSearchFilter,
+ shouldShowSearch,
+ filteredItemEntries,
+ } = useMultiItemSearch({ items: phones, getItemText: getPhoneText });
+
+ const handleInputEnter = () => {
+ const updatedItems = draft.commitInput();
+
+ if (!isDefined(updatedItems)) {
+ return;
+ }
+
+ if (draft.isSingleItemMode) {
+ onEnter?.({ newValue: parseArrayToPhonesValue(updatedItems) });
+ } else if (!isDeeplyEqual(phones, updatedItems)) {
+ handleSubmit(updatedItems);
+ }
- const handleEscape = (updatedPhones: PhoneRecord[]) => {
- onEscape?.({ newValue: parseArrayToPhonesValue(updatedPhones) });
+ draft.closeInput();
};
- const handleEnter = (updatedPhones: PhoneRecord[]) => {
- onEnter?.({ newValue: parseArrayToPhonesValue(updatedPhones) });
+ const handleEscape = () => {
+ onEscape?.({ newValue: parseArrayToPhonesValue(phones) });
};
- const handleSubmit = (updatedPhones: PhoneRecord[]) => {
- onSubmit?.({
- newValue: parseArrayToPhonesValue(updatedPhones),
- skipClose: true,
+ useMultiItemFieldDismiss({
+ containerRef,
+ onEscape: handleEscape,
+ onClickOutside: (event) => {
+ const updatedItems = draft.isInputDisplayed
+ ? draft.commitInput()
+ : phones;
+
+ if (!isDefined(updatedItems)) {
+ return;
+ }
+
+ onClickOutside?.({
+ newValue: parseArrayToPhonesValue(updatedItems),
+ event,
+ });
+ },
+ });
+
+ const handleSetAsPrimary = (index: number) => {
+ const updatedPhones = moveArrayItem(phones, {
+ fromIndex: index,
+ toIndex: 0,
});
+
+ handleChange(updatedPhones);
+ handleSubmit(updatedPhones);
};
+ const handleDelete = (index: number) => {
+ const updatedPhones = toSpliced(phones, index, 1);
+
+ handleChange(updatedPhones);
+ handleSubmit(updatedPhones);
+ draft.resetInputForItems(updatedPhones);
+ };
+
+ const shouldShowItems =
+ isNonEmptyArray(filteredItemEntries) &&
+ (!draft.isSingleItemMode || !draft.isInputDisplayed);
+ const visibleItemEntries = shouldShowItems ? filteredItemEntries : undefined;
+ const shouldShowAddButton = !draft.isInputDisplayed && !draft.isLimitReached;
+
return (
- <MultiItemFieldInput
- items={phones}
- onChange={handlePhonesChange}
- onClickOutside={handleClickOutside}
- onEscape={handleEscape}
- onEnter={handleEnter}
- onSubmit={handleSubmit}
- placeholder={t`Phone`}
- fieldMetadataType={FieldMetadataType.PHONES}
- validateInput={validateInput}
- formatInput={(input) => {
- if (input === '') {
- return {
- number: '',
- callingCode: '',
- countryCode: '',
- };
- }
-
- const phone = parsePhoneNumber(input);
- if (phone !== undefined) {
- return {
- number: phone.nationalNumber,
- callingCode: `+${phone.countryCallingCode}`,
- countryCode: phone.country as string,
- };
- }
-
- return {
- number: '',
- callingCode: '',
- countryCode: '',
- };
- }}
- renderItem={({
- value: phone,
- index,
- handleEdit,
- handleSetPrimary,
- handleDelete,
- }) => (
+ <OverlayMenuList
+ ref={containerRef}
+ header={
+ shouldShowSearch && !draft.isInputDisplayed ? (
+ <MultiItemFieldSearchHeader
+ value={searchFilter}
+ onChange={setSearchFilter}
+ />
+ ) : undefined
+ }
+ footer={
+ <>
+ {shouldShowItems &&
+ (draft.isInputDisplayed || shouldShowAddButton) && (
+ <OverlayMenuListSeparator />
+ )}
+ {draft.isInputDisplayed && (
+ <MultiItemFieldInputRow
+ rightComponent={
+ isNonEmptyArray(phones) ? (
+ <MultiItemFieldSaveButton
+ isAddingNewItem={draft.isAddingNewItem}
+ onClick={handleInputEnter}
+ />
+ ) : undefined
+ }
+ >
+ <StyledCustomPhoneInputContainer
+ hasItem={isNonEmptyArray(phones)}
+ hasError={draft.hasError}
+ >
+ <StyledCustomPhoneInputWrapper>
+ <ReactPhoneNumberInput
+ autoFocus={!shouldShowSearch}
+ placeholder={t`Phone`}
+ value={draft.inputValue as E164Number}
+ onChange={(value?: E164Number) =>
+ draft.handleInputChange(value ?? '')
+ }
+ onKeyDown={getMultiItemInputKeyDownHandler({
+ onEnter: handleInputEnter,
+ onEscape: handleEscape,
+ shouldPreventTabNavigation: true,
+ })}
+ international={true}
+ withCountryCallingCode={true}
+ countrySelectComponent={PhoneCountryPickerDropdownButton}
+ defaultCountry={defaultCountry}
+ />
+ </StyledCustomPhoneInputWrapper>
+ </StyledCustomPhoneInputContainer>
+ </MultiItemFieldInputRow>
+ )}
+ {shouldShowAddButton && (
+ <MultiItemFieldAddButton
+ label={t`Add Phone`}
+ onClick={draft.startAdding}
+ />
+ )}
+ </>
+ }
+ >
+ {visibleItemEntries?.map(({ item: phone, index }) => (
<PhonesFieldMenuItem
key={index}
dropdownId={`${MULTI_ITEM_FIELD_INPUT_DROPDOWN_ID_PREFIX}-${fieldDefinition.metadata.fieldName}-${index}`}
- showPrimaryIcon={getShowPrimaryIcon(index)}
- showSetAsPrimaryButton={getShowSetAsPrimaryButton(index)}
+ showPrimaryIcon={index === 0 && phones.length > 1}
+ showSetAsPrimaryButton={index > 0}
phone={phone}
- onEdit={handleEdit}
- onSetAsPrimary={handleSetPrimary}
- onDelete={handleDelete}
+ onEdit={() => draft.startEditing(index)}
+ onSetAsPrimary={() => handleSetAsPrimary(index)}
+ onDelete={() => handleDelete(index)}
/>
- )}
- renderInput={({
- value,
- onChange,
- onKeyDown,
- onFocus,
- onBlur,
- autoFocus,
- placeholder,
- hasError,
- }) => {
- return (
- <StyledCustomPhoneInputContainer
- hasItem={!!phones.length}
- hasError={hasError}
- >
- <StyledCustomPhoneInputWrapper>
- <ReactPhoneNumberInput
- autoFocus={autoFocus}
- placeholder={placeholder}
- value={value as E164Number}
- onChange={onChange as unknown as (newValue: E164Number) => void}
- onKeyDown={onKeyDown}
- onFocus={onFocus}
- onBlur={onBlur}
- international={true}
- withCountryCallingCode={true}
- countrySelectComponent={PhoneCountryPickerDropdownButton}
- defaultCountry={defaultCountry}
- />
- </StyledCustomPhoneInputWrapper>
- </StyledCustomPhoneInputContainer>
- );
- }}
- onError={handleError}
- maxItemCount={maxNumberOfValues}
- />
+ ))}
+ </OverlayMenuList>
);
};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/MultiItemBaseInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/MultiItemFieldTextInput.stories.tsx
similarity index 62%
rename from packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/MultiItemBaseInput.stories.tsx
rename to packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/MultiItemFieldTextInput.stories.tsx
index 87f39599e15..f88328e3fcd 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/MultiItemBaseInput.stories.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/MultiItemFieldTextInput.stories.tsx
@@ -1,18 +1,18 @@
import { expect, fn, userEvent, within } from 'storybook/test';
import { type Meta, type StoryObj } from '@storybook/react-vite';
-import { MultiItemBaseInput } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemBaseInput';
+import { MultiItemFieldTextInput } from '@/object-record/record-field/ui/meta-types/input/components/MultiItemFieldTextInput';
import { ComponentDecorator } from 'twenty-ui/testing';
-const meta: Meta<typeof MultiItemBaseInput> = {
- title: 'UI/Data/Field/Input/BaseFieldInput',
- component: MultiItemBaseInput,
+const meta: Meta<typeof MultiItemFieldTextInput> = {
+ title: 'UI/Data/Field/Input/MultiItemFieldTextInput',
+ component: MultiItemFieldTextInput,
decorators: [ComponentDecorator],
- args: { value: 'Lorem ipsum', instanceId: 'multi-item-base-input' },
+ args: { value: 'Lorem ipsum', onChange: fn() },
};
export default meta;
-type Story = StoryObj<typeof MultiItemBaseInput>;
+type Story = StoryObj<typeof MultiItemFieldTextInput>;
export const Default: Story = {};
@@ -20,11 +20,9 @@ export const Focused: Story = {
args: { autoFocus: true },
};
-export const InvalidPlainInput: Story = {
+export const Invalid: Story = {
args: {
hasError: true,
- error: 'Enter a valid value',
- onChange: fn(),
onEnter: fn(),
},
play: async ({ canvasElement, args }) => {
@@ -32,7 +30,6 @@ export const InvalidPlainInput: Story = {
const input = canvas.getByRole('textbox');
await expect(input).toHaveAttribute('aria-invalid', 'true');
- await expect(canvas.getByText('Enter a valid value')).toBeVisible();
await expect(getComputedStyle(input).borderWidth).toBe('0px');
await expect(getComputedStyle(input).outlineWidth).toBe('2px');
await userEvent.click(input);
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/hooks/useMultiItemDraft.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/hooks/useMultiItemDraft.ts
new file mode 100644
index 00000000000..7707e16194d
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/hooks/useMultiItemDraft.ts
@@ -0,0 +1,146 @@
+import { computeUpdatedMultiItemFieldItems } from '@/object-record/record-field/ui/meta-types/input/utils/computeUpdatedMultiItemFieldItems';
+import { sanitizeAndValidateInput } from '@/object-record/record-field/ui/meta-types/input/utils/sanitizeAndValidateInput';
+import { isNonEmptyString } from '@sniptt/guards';
+import { useState } from 'react';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { turnIntoEmptyStringIfWhitespacesOnly } from '~/utils/string/turnIntoEmptyStringIfWhitespacesOnly';
+
+type UseMultiItemDraftParams<TItem> = {
+ items: TItem[];
+ getItemText: (item: TItem) => string;
+ onItemsChange: (items: TItem[]) => void;
+ validateInput?: (input: string) => { isValid: boolean; errorMessage: string };
+ formatInput?: (params: { input: string; itemIndex?: number }) => TItem;
+ maxItemCount?: number;
+ shouldOpenInputWhenEmpty?: boolean;
+ onError?: (hasError: boolean) => void;
+};
+
+export const useMultiItemDraft = <TItem>({
+ items,
+ getItemText,
+ onItemsChange,
+ validateInput,
+ formatInput,
+ maxItemCount,
+ shouldOpenInputWhenEmpty = true,
+ onError,
+}: UseMultiItemDraftParams<TItem>) => {
+ const isSingleItemMode = maxItemCount === 1;
+ const isLimitReached =
+ isDefined(maxItemCount) && items.length >= maxItemCount;
+
+ const shouldOpenInputOnMount =
+ shouldOpenInputWhenEmpty && (items.length === 0 || isSingleItemMode);
+
+ const [isInputDisplayed, setIsInputDisplayed] = useState(
+ shouldOpenInputOnMount,
+ );
+ const [inputValue, setInputValue] = useState(
+ shouldOpenInputOnMount && isNonEmptyArray(items)
+ ? getItemText(items[0])
+ : '',
+ );
+ const [editedItemIndex, setEditedItemIndex] = useState(0);
+ const [isAddingNewItem, setIsAddingNewItem] = useState(false);
+ const [hasError, setHasError] = useState(false);
+
+ const handleInputChange = (value: string) => {
+ setInputValue(turnIntoEmptyStringIfWhitespacesOnly(value));
+
+ if (!isDefined(validateInput)) {
+ return;
+ }
+
+ setHasError(false);
+ onError?.(false);
+ };
+
+ const startAdding = () => {
+ if (isLimitReached) {
+ return;
+ }
+
+ setIsAddingNewItem(true);
+ setInputValue('');
+ setIsInputDisplayed(true);
+ };
+
+ const startEditing = (index: number) => {
+ setEditedItemIndex(index);
+ setInputValue(getItemText(items[index]));
+ setIsAddingNewItem(false);
+ setIsInputDisplayed(true);
+ };
+
+ const closeInput = () => {
+ setIsInputDisplayed(false);
+ setIsAddingNewItem(false);
+ setInputValue('');
+ };
+
+ const resetInputForItems = (remainingItems: TItem[]) => {
+ const shouldShowInput =
+ remainingItems.length === 0 && shouldOpenInputWhenEmpty;
+
+ setIsInputDisplayed(shouldShowInput);
+ setIsAddingNewItem(false);
+
+ if (shouldShowInput) {
+ setInputValue('');
+ }
+ };
+
+ const commitInput = (): TItem[] | null => {
+ const { sanitizedInput, isValid } = sanitizeAndValidateInput(
+ inputValue,
+ validateInput,
+ );
+
+ if (!isValid) {
+ setHasError(true);
+ onError?.(true);
+
+ return null;
+ }
+
+ const editingIndex = isAddingNewItem ? null : editedItemIndex;
+
+ const updatedItems = computeUpdatedMultiItemFieldItems({
+ sanitizedInput,
+ items,
+ editingIndex,
+ singleItemMode: isSingleItemMode,
+ formatInput,
+ });
+
+ const isItemDeletion =
+ !isNonEmptyString(sanitizedInput) &&
+ isDefined(editingIndex) &&
+ !isSingleItemMode;
+
+ if (isItemDeletion) {
+ resetInputForItems(updatedItems);
+ }
+
+ onItemsChange(updatedItems);
+
+ return updatedItems;
+ };
+
+ return {
+ isInputDisplayed,
+ inputValue,
+ isAddingNewItem,
+ editedItemIndex,
+ hasError,
+ isSingleItemMode,
+ isLimitReached,
+ handleInputChange,
+ startAdding,
+ startEditing,
+ closeInput,
+ resetInputForItems,
+ commitInput,
+ };
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/hooks/useMultiItemFieldDismiss.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/hooks/useMultiItemFieldDismiss.ts
new file mode 100644
index 00000000000..3c47235c71c
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/hooks/useMultiItemFieldDismiss.ts
@@ -0,0 +1,47 @@
+import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';
+import { currentFocusedItemSelector } from '@/ui/utilities/focus/states/currentFocusedItemSelector';
+import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';
+import { useHotkeysOnFocusedElement } from '@/ui/utilities/hotkey/hooks/useHotkeysOnFocusedElement';
+import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';
+import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { type RefObject } from 'react';
+import { Key } from 'ts-key-enum';
+
+export const useMultiItemFieldDismiss = ({
+ containerRef,
+ onClickOutside,
+ onEscape,
+}: {
+ containerRef: RefObject<HTMLDivElement | null>;
+ onClickOutside: (event: MouseEvent | TouchEvent) => void;
+ onEscape: () => void;
+}) => {
+ const instanceId = useAvailableComponentInstanceIdOrThrow(
+ RecordFieldComponentInstanceContext,
+ );
+
+ const currentFocusedItem = useAtomStateValue(currentFocusedItemSelector);
+
+ useListenClickOutside({
+ refs: [containerRef],
+ callback: (event) => {
+ if (
+ currentFocusedItem?.componentInstance.componentType !==
+ FocusComponentType.OPENED_FIELD_INPUT
+ ) {
+ return;
+ }
+
+ onClickOutside(event);
+ },
+ listenerId: instanceId,
+ });
+
+ useHotkeysOnFocusedElement({
+ focusId: instanceId,
+ keys: [Key.Escape],
+ callback: onEscape,
+ dependencies: [onEscape],
+ });
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/hooks/useMultiItemSearch.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/hooks/useMultiItemSearch.ts
new file mode 100644
index 00000000000..b76f182255d
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/hooks/useMultiItemSearch.ts
@@ -0,0 +1,36 @@
+import { filterMultiItemsBySearch } from '@/object-record/record-field/ui/meta-types/input/utils/filterMultiItemsBySearch';
+import { useMemo, useState } from 'react';
+import { useDebounce } from 'use-debounce';
+
+const SEARCH_DEBOUNCE_MS = 150;
+const MIN_ITEM_COUNT_FOR_SEARCH = 4;
+
+export const useMultiItemSearch = <TItem>({
+ items,
+ getItemText,
+}: {
+ items: TItem[];
+ getItemText: (item: TItem) => string;
+}) => {
+ const [searchFilter, setSearchFilter] = useState('');
+ const [debouncedSearchFilter] = useDebounce(searchFilter, SEARCH_DEBOUNCE_MS);
+
+ const shouldShowSearch = items.length >= MIN_ITEM_COUNT_FOR_SEARCH;
+
+ const filteredItemEntries = useMemo(
+ () =>
+ filterMultiItemsBySearch({
+ items,
+ searchFilter: shouldShowSearch ? debouncedSearchFilter : '',
+ getItemText,
+ }),
+ [items, debouncedSearchFilter, shouldShowSearch, getItemText],
+ );
+
+ return {
+ searchFilter,
+ setSearchFilter,
+ shouldShowSearch,
+ filteredItemEntries,
+ };
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/types/MultiItemBaseInputProps.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/types/MultiItemBaseInputProps.ts
deleted file mode 100644
index 5559b67c1ec..00000000000
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/types/MultiItemBaseInputProps.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { type InputHTMLAttributes, type ReactNode } from 'react';
-
-type HTMLInputProps = InputHTMLAttributes<HTMLInputElement>;
-
-export type MultiItemBaseInputProps = Pick<
- HTMLInputProps,
- 'autoFocus' | 'className' | 'value' | 'placeholder' | 'onFocus' | 'onBlur'
-> & {
- onClickOutside?: () => void;
- onEnter?: () => void;
- onEscape?: () => void;
- onShiftTab?: () => void;
- onTab?: () => void;
- preventTabNavigation?: boolean;
- rightComponent?: ReactNode;
- renderInput?: (
- props: Pick<
- HTMLInputProps,
- 'value' | 'autoFocus' | 'placeholder' | 'onKeyDown' | 'onFocus' | 'onBlur'
- > & {
- onChange: (value: string) => void;
- hasError?: boolean;
- },
- ) => ReactNode;
- error?: string | null;
- hasError?: boolean;
- onChange: (value: string) => void;
- instanceId: string;
-};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/__tests__/computeUpdatedMultiItemFieldItems.test.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/__tests__/computeUpdatedMultiItemFieldItems.test.ts
index 1cab1a564cf..e5ef877ec78 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/__tests__/computeUpdatedMultiItemFieldItems.test.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/__tests__/computeUpdatedMultiItemFieldItems.test.ts
@@ -52,7 +52,7 @@ describe('computeUpdatedMultiItemFieldItems', () => {
it('should use formatInput to transform the value', () => {
type Link = { url: string; label: string };
- const formatInput = jest.fn((input: string) => ({
+ const formatInput = jest.fn(({ input }: { input: string }) => ({
url: input,
label: input,
}));
@@ -65,7 +65,10 @@ describe('computeUpdatedMultiItemFieldItems', () => {
formatInput,
});
- expect(formatInput).toHaveBeenCalledWith('example.com', undefined);
+ expect(formatInput).toHaveBeenCalledWith({
+ input: 'example.com',
+ itemIndex: undefined,
+ });
expect(result).toEqual([{ url: 'example.com', label: 'example.com' }]);
});
});
@@ -83,7 +86,7 @@ describe('computeUpdatedMultiItemFieldItems', () => {
});
it('should pass editingIndex to formatInput', () => {
- const formatInput = jest.fn((input: string) => input);
+ const formatInput = jest.fn(({ input }: { input: string }) => input);
computeUpdatedMultiItemFieldItems({
sanitizedInput: 'edited',
@@ -93,7 +96,10 @@ describe('computeUpdatedMultiItemFieldItems', () => {
formatInput,
});
- expect(formatInput).toHaveBeenCalledWith('edited', 2);
+ expect(formatInput).toHaveBeenCalledWith({
+ input: 'edited',
+ itemIndex: 2,
+ });
});
});
});
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/__tests__/filterMultiItemsBySearch.test.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/__tests__/filterMultiItemsBySearch.test.ts
new file mode 100644
index 00000000000..b9af1fa479e
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/__tests__/filterMultiItemsBySearch.test.ts
@@ -0,0 +1,32 @@
+import { filterMultiItemsBySearch } from '@/object-record/record-field/ui/meta-types/input/utils/filterMultiItemsBySearch';
+
+describe('filterMultiItemsBySearch', () => {
+ const items = ['alpha', 'Beta', 'alpha'];
+
+ it('keeps every item with its original index when the filter is empty', () => {
+ expect(
+ filterMultiItemsBySearch({
+ items,
+ searchFilter: '',
+ getItemText: (item) => item,
+ }),
+ ).toEqual([
+ { item: 'alpha', index: 0 },
+ { item: 'Beta', index: 1 },
+ { item: 'alpha', index: 2 },
+ ]);
+ });
+
+ it('matches case-insensitively and keeps original indexes for duplicates', () => {
+ expect(
+ filterMultiItemsBySearch({
+ items,
+ searchFilter: 'ALPHA',
+ getItemText: (item) => item,
+ }),
+ ).toEqual([
+ { item: 'alpha', index: 0 },
+ { item: 'alpha', index: 2 },
+ ]);
+ });
+});
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/__tests__/getMultiItemInputKeyDownHandler.test.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/__tests__/getMultiItemInputKeyDownHandler.test.tsx
new file mode 100644
index 00000000000..65c33a9493b
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/__tests__/getMultiItemInputKeyDownHandler.test.tsx
@@ -0,0 +1,67 @@
+import { getMultiItemInputKeyDownHandler } from '@/object-record/record-field/ui/meta-types/input/utils/getMultiItemInputKeyDownHandler';
+import { fireEvent, render, screen } from '@testing-library/react';
+
+const renderInput = ({
+ handlers,
+ onParentKeyDown = jest.fn(),
+}: {
+ handlers: Parameters<typeof getMultiItemInputKeyDownHandler>[0];
+ onParentKeyDown?: jest.Mock;
+}) => {
+ render(
+ <div onKeyDown={onParentKeyDown}>
+ <input
+ aria-label="value"
+ onKeyDown={getMultiItemInputKeyDownHandler(handlers)}
+ />
+ </div>,
+ );
+
+ return { input: screen.getByLabelText('value'), onParentKeyDown };
+};
+
+describe('getMultiItemInputKeyDownHandler', () => {
+ it('calls onEnter on Enter and stops the event', () => {
+ const onEnter = jest.fn();
+ const { input, onParentKeyDown } = renderInput({ handlers: { onEnter } });
+
+ const isDefaultAllowed = fireEvent.keyDown(input, { key: 'Enter' });
+
+ expect(onEnter).toHaveBeenCalledTimes(1);
+ expect(isDefaultAllowed).toBe(false);
+ expect(onParentKeyDown).not.toHaveBeenCalled();
+ });
+
+ it('routes Tab and Shift+Tab to their handlers', () => {
+ const onTab = jest.fn();
+ const onShiftTab = jest.fn();
+ const { input } = renderInput({ handlers: { onTab, onShiftTab } });
+
+ fireEvent.keyDown(input, { key: 'Tab' });
+ fireEvent.keyDown(input, { key: 'Tab', shiftKey: true });
+
+ expect(onTab).toHaveBeenCalledTimes(1);
+ expect(onShiftTab).toHaveBeenCalledTimes(1);
+ });
+
+ it('prevents the default Tab navigation when asked, even without a handler', () => {
+ const { input, onParentKeyDown } = renderInput({
+ handlers: { shouldPreventTabNavigation: true },
+ });
+
+ const isDefaultAllowed = fireEvent.keyDown(input, { key: 'Tab' });
+
+ expect(isDefaultAllowed).toBe(false);
+ expect(onParentKeyDown).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores composing input and modifier combinations', () => {
+ const onEnter = jest.fn();
+ const { input } = renderInput({ handlers: { onEnter } });
+
+ fireEvent.keyDown(input, { key: 'Enter', isComposing: true });
+ fireEvent.keyDown(input, { key: 'Enter', metaKey: true });
+
+ expect(onEnter).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/computeUpdatedMultiItemFieldItems.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/computeUpdatedMultiItemFieldItems.ts
index 5b776aac2f7..e5fb995938f 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/computeUpdatedMultiItemFieldItems.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/computeUpdatedMultiItemFieldItems.ts
@@ -13,7 +13,7 @@ export const computeUpdatedMultiItemFieldItems = <T>({
items: T[];
editingIndex: number | null;
singleItemMode: boolean;
- formatInput?: (input: string, itemIndex?: number) => T;
+ formatInput?: (params: { input: string; itemIndex?: number }) => T;
}): T[] => {
const isAdding = !isDefined(editingIndex);
@@ -28,7 +28,10 @@ export const computeUpdatedMultiItemFieldItems = <T>({
}
const newItem = isDefined(formatInput)
- ? formatInput(sanitizedInput, isAdding ? undefined : editingIndex)
+ ? formatInput({
+ input: sanitizedInput,
+ itemIndex: isAdding ? undefined : editingIndex,
+ })
: (sanitizedInput as unknown as T);
return isAdding
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/filterMultiItemsBySearch.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/filterMultiItemsBySearch.ts
new file mode 100644
index 00000000000..7d3cdb8e842
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/filterMultiItemsBySearch.ts
@@ -0,0 +1,26 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { normalizeSearchText } from 'twenty-ui/utilities';
+
+export type MultiItemEntry<TItem> = { item: TItem; index: number };
+
+export const filterMultiItemsBySearch = <TItem>({
+ items,
+ searchFilter,
+ getItemText,
+}: {
+ items: TItem[];
+ searchFilter: string;
+ getItemText: (item: TItem) => string;
+}): MultiItemEntry<TItem>[] => {
+ const itemEntries = items.map((item, index) => ({ item, index }));
+
+ if (!isNonEmptyString(searchFilter)) {
+ return itemEntries;
+ }
+
+ const searchTerm = normalizeSearchText(searchFilter);
+
+ return itemEntries.filter(({ item }) =>
+ normalizeSearchText(getItemText(item)).includes(searchTerm),
+ );
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/getMultiItemInputKeyDownHandler.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/getMultiItemInputKeyDownHandler.ts
new file mode 100644
index 00000000000..9f2a08fa1c9
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/utils/getMultiItemInputKeyDownHandler.ts
@@ -0,0 +1,52 @@
+import { isKeyboardEventComposing } from '@/ui/utilities/hotkey/utils/isKeyboardEventComposing';
+import { type KeyboardEvent } from 'react';
+import { Key } from 'ts-key-enum';
+import { isDefined } from 'twenty-shared/utils';
+
+type MultiItemInputKeyHandlers = {
+ onEnter?: () => void;
+ onEscape?: () => void;
+ onTab?: () => void;
+ onShiftTab?: () => void;
+ shouldPreventTabNavigation?: boolean;
+};
+
+export const getMultiItemInputKeyDownHandler =
+ ({
+ onEnter,
+ onEscape,
+ onTab,
+ onShiftTab,
+ shouldPreventTabNavigation,
+ }: MultiItemInputKeyHandlers) =>
+ (event: KeyboardEvent<HTMLInputElement>) => {
+ const hasUnsupportedModifier =
+ event.altKey ||
+ event.ctrlKey ||
+ event.metaKey ||
+ (event.shiftKey && event.key !== Key.Tab);
+
+ if (isKeyboardEventComposing(event.nativeEvent) || hasUnsupportedModifier) {
+ return;
+ }
+
+ if (event.key === Key.Tab && shouldPreventTabNavigation) {
+ event.preventDefault();
+ }
+
+ const handlersByKey: Partial<Record<string, () => void>> = {
+ [Key.Enter]: onEnter,
+ [Key.Escape]: onEscape,
+ [Key.Tab]: event.shiftKey ? onShiftTab : onTab,
+ };
+
+ const handler = handlersByKey[event.key];
+
+ if (!isDefined(handler)) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ handler();
+ };