The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Migrate field input pickers and row menus (#27061)
Raphaël Bosi5762d3c548c8
diff --git a/packages/twenty-docs/snippets/ui/generated/components/navigation/dropdown.mdx b/packages/twenty-docs/snippets/ui/generated/components/navigation/dropdown.mdxindex fcd5fa9be7a..a6ed0c9031a 100644--- a/packages/twenty-docs/snippets/ui/generated/components/navigation/dropdown.mdx+++ b/packages/twenty-docs/snippets/ui/generated/components/navigation/dropdown.mdx@@ -98,7 +98,7 @@Alignment of the popup along the anchor.</ParamField>-<ParamField body="Content.alignOffset" type="number">+<ParamField body="Content.alignOffset" type="number | OffsetFunction">Offset in pixels along the alignment axis.</ParamField>@@ -158,7 +158,7 @@Side of the anchor the popup is placed on.</ParamField>-<ParamField body="Content.sideOffset" type="number" default="0">+<ParamField body="Content.sideOffset" type="number | OffsetFunction" default="0">Distance in pixels between the anchor and the popup.</ParamField>diff --git a/packages/twenty-docs/snippets/ui/generated/surfaces/popover.mdx b/packages/twenty-docs/snippets/ui/generated/surfaces/popover.mdxindex 093d9f7ae42..d4349ac3316 100644--- a/packages/twenty-docs/snippets/ui/generated/surfaces/popover.mdx+++ b/packages/twenty-docs/snippets/ui/generated/surfaces/popover.mdx@@ -136,7 +136,7 @@Alignment of the popup along the anchor.</ParamField>-<ParamField body="Popup.alignOffset" type="number">+<ParamField body="Popup.alignOffset" type="number | OffsetFunction">Offset in pixels along the alignment axis.</ParamField>@@ -200,7 +200,7 @@Side of the anchor the popup is placed on.</ParamField>-<ParamField body="Popup.sideOffset" type="number" default="8">+<ParamField body="Popup.sideOffset" type="number | OffsetFunction" default="8">Distance in pixels between the anchor and the popup.</ParamField>diff --git a/packages/twenty-docs/ui/components/navigation/dropdown.mdx b/packages/twenty-docs/ui/components/navigation/dropdown.mdxindex 3b154bf4f82..f194f5185fe 100644--- a/packages/twenty-docs/ui/components/navigation/dropdown.mdx+++ b/packages/twenty-docs/ui/components/navigation/dropdown.mdx@@ -14,6 +14,8 @@ import DropdownReference from '/snippets/ui/generated/components/navigation/dropheight={380}/>+Dropdown.Content accepts numeric offsets or functions for `sideOffset` and `alignOffset`. Offset functions receive the anchor and popup dimensions, side, and alignment. Use them to preserve an anchored field picker’s overlap when the cell is scaled.+## Choose an interaction typeSet `type` on `Dropdown.Root` to match the popup's contents.diff --git a/packages/twenty-e2e-testing/tests/create-record.spec.ts b/packages/twenty-e2e-testing/tests/create-record.spec.tsindex 545776415c1..0aae534924c 100644--- a/packages/twenty-e2e-testing/tests/create-record.spec.ts+++ b/packages/twenty-e2e-testing/tests/create-record.spec.ts@@ -137,8 +137,8 @@ test('Create and update record', async ({ page }) => {.getByText('Work Preference', { exact: true }).nth(1).click({ force: true });- const options = page.getByRole('listbox');- await options.getByText('Hybrid').first().click({ force: true });+ const options = page.getByRole('dialog', { name: 'Work Preference' });+ await options.getByRole('button', { name: 'Hybrid', exact: true }).click();await recordFieldList.getByText('Work Preference', { exact: true }).first()diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/contexts/FieldInputAnchorContext.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/contexts/FieldInputAnchorContext.tsnew file mode 100644index 00000000000..3005d353cc9--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/contexts/FieldInputAnchorContext.ts@@ -0,0 +1,7 @@+import { type FieldInputAnchorPosition } from '@/object-record/record-field/ui/types/FieldInputAnchorPosition';+import { createRequiredContext } from '~/utils/createRequiredContext';++export const [+ FieldInputAnchorContextProvider,+ useFieldInputAnchorContextOrThrow,+] = createRequiredContext<FieldInputAnchorPosition>('FieldInputAnchorContext');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.tsxindex f11a57c2873..d0d92094bff 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@@ -1,4 +1,3 @@-import { ListItem } from 'twenty-ui/primitives/navigation';import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';import { FormFieldInputInnerContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputInnerContainer';import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/form-types/components/FormFieldInputRowContainer';@@ -11,10 +10,8 @@ import { type FieldArrayValue } from '@/object-record/record-field/ui/types/Fielimport { ArrayDisplay } from '@/ui/field/display/components/ArrayDisplay';import { StyledTextInput } from '@/ui/field/input/components/TextInput';import { Field } from 'twenty-ui/primitives/input';-import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';-import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';-import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';-import { DropdownMenuSeparator } from '@/ui/layout/dropdown/components/DropdownMenuSeparator';+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';+import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';import { useOpenDropdown } from '@/ui/layout/dropdown/hooks/useOpenDropdown';import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';@@ -26,16 +23,11 @@ import { isStandaloneVariableString } from 'twenty-shared/workflow';import { styled } from '@linaria/react';import { useLingui } from '@lingui/react/macro';import { isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';-import {- type FocusEvent,- type KeyboardEvent,- useId,- useRef,- useState,-} from 'react';+import { type FocusEvent, type KeyboardEvent, useId, useState } from 'react';import { Key } from 'ts-key-enum';import { isDefined } from 'twenty-shared/utils';import { IconPlus } from 'twenty-ui/icon';+import { Dropdown } from 'twenty-ui/components/navigation';import { useTheme, themeCssVariables } from 'twenty-ui/theme';import { toSpliced } from '~/utils/array/toSpliced';@@ -86,10 +78,6 @@ const StyledPlaceholderContainer = styled.div`width: 100%;`;-const parseSpacingValueAsNumber = (value: string) => {- return Number(value.replace('px', ''));-};-export const FormArrayFieldInput = ({label,defaultValue,@@ -140,14 +128,14 @@ export const FormArrayFieldInput = ({const [itemToEditIndex, setItemToEditIndex] = useState(-1);const isAddingNewItem = itemToEditIndex === -1;- const containerRef = useRef<HTMLDivElement>(null);-const dropdownId = `dropdown-${instanceId}`;const isDropdownOpen = useAtomComponentStateValue(isDropdownOpenComponentState,dropdownId,);+ const accessibleLabel = isNonEmptyString(label) ? label : t`Items`;+const preventContainerFocusStackUpdate =draftValue.type === 'static' && draftValue.value.length >= 1;@@ -393,63 +381,65 @@ export const FormArrayFieldInput = ({/></StyledInputContainer>) : (- <Dropdown- dropdownId={dropdownId}- dropdownPlacement="bottom-start"- dropdownOffset={{- y: parseSpacingValueAsNumber(theme.spacing[1]),- }}- clickableComponent={- <StyledDisplayModeContainer data-open={isDropdownOpen}>- <ArrayDisplay value={draftValue.value} />- </StyledDisplayModeContainer>- }- clickableComponentWidth="100%"- dropdownComponents={- <LegacyDropdownContent ref={containerRef}>- <DropdownMenuItemsContainer hasMaxHeight>- {draftValue.type === 'static' &&- draftValue.value.map((value, index) => (- <ArrayFieldMenuItem- key={index}- dropdownId={`array-field-input-${instanceId}-${index}`}- value={value}- onEdit={() => {- handleEditItem(index);- }}- onDelete={() => {- handleDeleteItem(index);- }}- />- ))}- </DropdownMenuItemsContainer>-- <DropdownMenuSeparator />-- {isInputDisplayed ? (- <MultiItemBaseInput- instanceId={newItemInputInstanceId}- autoFocus- placeholder={placeholder}- value={inputValue}- onFocus={handleNewItemInputFocus}- onBlur={handleNewItemInputBlur}- onEscape={handleNewItemInputEscape}- onChange={handleNewItemInputChange}- onEnter={handleNewItemInputSubmit}- hasItem- />- ) : !isLimitReached ? (- <DropdownMenuItemsContainer>- <ListItem- onClick={handleAddItemButtonClick}- startIcon={<IconPlus />}- >{t`Add item`}</ListItem>- </DropdownMenuItemsContainer>- ) : null}- </LegacyDropdownContent>- }- />+ <DropdownRoot dropdownId={dropdownId} type="panel">+ <Dropdown.Trigger+ render={+ <StyledDisplayModeContainer data-open={isDropdownOpen} />+ }+ nativeButton={false}+ aria-label={accessibleLabel}+ >+ <ArrayDisplay value={draftValue.value} />+ </Dropdown.Trigger>+ <DropdownContent+ side="bottom"+ align="start"+ sideOffset={parseInt(theme.spacing[1], 10)}+ aria-label={accessibleLabel}+ >+ <Dropdown.Section scrollable>+ {draftValue.type === 'static' &&+ draftValue.value.map((value, index) => (+ <ArrayFieldMenuItem+ key={index}+ dropdownId={`array-field-input-${instanceId}-${index}`}+ value={value}+ onEdit={() => {+ handleEditItem(index);+ }}+ onDelete={() => {+ handleDeleteItem(index);+ }}+ />+ ))}+ </Dropdown.Section>++ <Dropdown.Separator />++ {isInputDisplayed ? (+ <MultiItemBaseInput+ instanceId={newItemInputInstanceId}+ autoFocus+ placeholder={placeholder}+ value={inputValue}+ onFocus={handleNewItemInputFocus}+ onBlur={handleNewItemInputBlur}+ onEscape={handleNewItemInputEscape}+ onChange={handleNewItemInputChange}+ onEnter={handleNewItemInputSubmit}+ hasItem+ />+ ) : !isLimitReached ? (+ <Dropdown.Section>+ <Dropdown.ActionItem+ onClick={handleAddItemButtonClick}+ startIcon={<IconPlus />}+ closeOnClick={false}+ >{t`Add item`}</Dropdown.ActionItem>+ </Dropdown.Section>+ ) : null}+ </DropdownContent>+ </DropdownRoot>)) : (<VariableChipStandalonediff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiSelectFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiSelectFieldInput.tsxindex bcc8d5a2813..b524e05a23c 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiSelectFieldInput.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormMultiSelectFieldInput.tsx@@ -7,21 +7,20 @@ import { FormFieldInputRowContainer } from '@/object-record/record-field/ui/formimport { FormFieldPlaceholder } from '@/object-record/record-field/ui/form-types/components/FormFieldPlaceholder';import { VariableChipStandalone } from '@/object-record/record-field/ui/form-types/components/VariableChipStandalone';import { type VariablePickerComponent } from '@/object-record/record-field/ui/form-types/types/VariablePickerComponent';-import { SELECT_FIELD_INPUT_SELECTABLE_LIST_COMPONENT_INSTANCE_ID } from '@/object-record/record-field/ui/meta-types/input/constants/SelectFieldInputSelectableListComponentInstanceId';import { type FieldMultiSelectValue } from '@/object-record/record-field/ui/types/FieldMetadata';import { MultiSelectDisplay } from '@/ui/field/display/components/MultiSelectDisplay';import { MultiSelectInput } from '@/ui/field/input/components/MultiSelectInput';import { Field, type SelectOption } from 'twenty-ui/primitives/input';import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';-import { OverlayContainer } from '@/ui/layout/overlay/components/OverlayContainer';-import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePushFocusItemToFocusStack';-import { useRemoveFocusItemFromFocusStackById } from '@/ui/utilities/focus/hooks/useRemoveFocusItemFromFocusStackById';-import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';import { isStandaloneVariableString } from 'twenty-shared/workflow';-import { isArray } from '@sniptt/guards';+import { isArray, isNonEmptyString } from '@sniptt/guards';import { useId, useState } from 'react';-import { isDefined } from 'twenty-shared/utils';-import { VisibilityHidden } from 'twenty-ui/primitives/accessibility';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';+import { Dropdown } from 'twenty-ui/components/navigation';+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';+import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';+import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';+import { preventDropdownDismissOnInputElement } from '@/ui/layout/dropdown/utils/preventDropdownDismissOnInputElement';import { IconChevronDown } from 'twenty-ui/icon';import { useTheme, themeCssVariables } from 'twenty-ui/theme';@@ -68,12 +67,6 @@ const StyledDisplayModeContainer = styled.div`width: 100%;`;-const StyledSelectInputContainer = styled.div`- position: absolute;- top: calc(100% + ${themeCssVariables.spacing[1]});- z-index: 1;-`;-const StyledPlaceholderContainer = styled.div`width: 100%;`;@@ -100,16 +93,12 @@ export const FormMultiSelectFieldInput = ({}: FormMultiSelectFieldInputProps) => {const theme = useTheme();const instanceId = useId();-- const { pushFocusItemToFocusStack } = usePushFocusItemToFocusStack();- const { removeFocusItemFromFocusStackById } =- useRemoveFocusItemFromFocusStackById();+ const { closeDropdown } = useCloseDropdown();const [draftValue, setDraftValue] = useState<| {type: 'static';value: FieldMultiSelectValue | string;- editingMode: 'view' | 'edit';}| {type: 'variable';@@ -124,34 +113,9 @@ export const FormMultiSelectFieldInput = ({: {type: 'static',value: isDefined(defaultValue) ? defaultValue : [],- editingMode: 'view',},);- const handleDisplayModeClick = () => {- if (draftValue.type !== 'static') {- throw new Error(- 'This function can only be called when editing a static value.',- );- }-- setDraftValue({- ...draftValue,- editingMode: 'edit',- });-- pushFocusItemToFocusStack({- focusId: instanceId,- component: {- type: FocusComponentType.FORM_FIELD_INPUT,- instanceId,- },- globalHotkeysConfig: {- enableGlobalHotkeysConflictingWithKeyboard: false,- },- });- };-const onOptionSelected = (value: FieldMultiSelectValue) => {if (draftValue.type !== 'static') {throw new Error('Can only be called when editing a static value');@@ -160,25 +124,11 @@ export const FormMultiSelectFieldInput = ({setDraftValue({type: 'static',value,- editingMode: 'edit',});onChange(value);};- const onCancel = () => {- if (draftValue.type !== 'static') {- throw new Error('Can only be called when editing a static value');- }-- setDraftValue({- ...draftValue,- editingMode: 'view',- });-- removeFocusItemFromFocusStackById({ focusId: instanceId });- };-const handleVariableTagInsert = (variableName: string) => {setDraftValue({type: 'variable',@@ -192,7 +142,6 @@ export const FormMultiSelectFieldInput = ({setDraftValue({type: 'static',value: [],- editingMode: 'view',});onChange([]);@@ -213,6 +162,8 @@ export const FormMultiSelectFieldInput = ({: undefined;const placeholderText = placeholder ?? label;+ const accessibleLabel =+ [label, placeholder].find(isNonEmptyString) ?? t`Select options`;return (<FormFieldInputContainer data-testid={testId}>@@ -223,11 +174,12 @@ export const FormMultiSelectFieldInput = ({formFieldInputInstanceId={instanceId}hasRightElement={isDefined(VariablePicker) && !readonly}hoverable={!readonly}+ preventFocusStackUpdate={draftValue.type === 'static' && !readonly}>{draftValue.type === 'static' ? (readonly ? (<StyledDisplayModeReadonlyContainer>- {isDefined(selectedOptions) && selectedOptions.length > 0 ? (+ {isNonEmptyArray(selectedOptions) ? (<StyledMultiSelectDisplayvalues={selectedNames}options={selectedOptions}@@ -243,29 +195,50 @@ export const FormMultiSelectFieldInput = ({/></StyledDisplayModeReadonlyContainer>) : (- <StyledDisplayModeContainer- data-open={draftValue.editingMode === 'edit'}- onClick={handleDisplayModeClick}+ <DropdownRoot+ dropdownId={instanceId}+ type="picker"+ multiple+ onInteractOutside={preventDropdownDismissOnInputElement}>- <VisibilityHidden>{t`Edit`}</VisibilityHidden>-- {isDefined(selectedOptions) && selectedOptions.length > 0 ? (- <StyledMultiSelectDisplay+ <Dropdown.Trigger+ render={<StyledDisplayModeContainer />}+ nativeButton={false}+ aria-label={accessibleLabel}+ >+ {isNonEmptyArray(selectedOptions) ? (+ <StyledMultiSelectDisplay+ values={selectedNames}+ options={selectedOptions}+ />+ ) : (+ <StyledPlaceholderContainer>+ <FormFieldPlaceholder>+ {placeholderText}+ </FormFieldPlaceholder>+ </StyledPlaceholderContainer>+ )}+ <IconChevronDown+ size={theme.icon.size.md}+ color={theme.font.color.tertiary}+ />+ </Dropdown.Trigger>+ <DropdownContent+ align="start"+ sideOffset={parseInt(theme.spacing[1], 10)}+ width={+ dropdownWidth ?? GenericDropdownContentWidth.ExtraLarge+ }+ aria-label={accessibleLabel}+ >+ <MultiSelectInput+ options={options}+ onOptionSelected={onOptionSelected}+ onEnter={() => closeDropdown(instanceId)}values={selectedNames}- options={selectedOptions}/>- ) : (- <StyledPlaceholderContainer>- <FormFieldPlaceholder>- {placeholderText}- </FormFieldPlaceholder>- </StyledPlaceholderContainer>- )}- <IconChevronDown- size={theme.icon.size.md}- color={theme.font.color.tertiary}- />- </StyledDisplayModeContainer>+ </DropdownContent>+ </DropdownRoot>)) : (<VariableChipStandalone@@ -274,28 +247,8 @@ export const FormMultiSelectFieldInput = ({/>)}</FormFieldInputInnerContainer>- <StyledSelectInputContainer>- {draftValue.type === 'static' &&- draftValue.editingMode === 'edit' && (- <OverlayContainer>- <MultiSelectInput- selectableListComponentInstanceId={- SELECT_FIELD_INPUT_SELECTABLE_LIST_COMPONENT_INSTANCE_ID- }- focusId={instanceId}- options={options}- onCancel={onCancel}- onOptionSelected={onOptionSelected}- values={selectedNames}- dropdownWidth={- dropdownWidth ?? GenericDropdownContentWidth.ExtraLarge- }- />- </OverlayContainer>- )}- </StyledSelectInputContainer>- {VariablePicker && !readonly && (+ {isDefined(VariablePicker) && !readonly && (<VariablePickerinstanceId={instanceId}onVariableSelect={handleVariableTagInsert}diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__stories__/FormArrayFieldInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__stories__/FormArrayFieldInput.stories.tsxindex 3febf28539f..f2797c46938 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__stories__/FormArrayFieldInput.stories.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__stories__/FormArrayFieldInput.stories.tsx@@ -1,7 +1,10 @@import { FormArrayFieldInput } from '@/object-record/record-field/ui/form-types/components/FormArrayFieldInput';+import { focusStackState } from '@/ui/utilities/focus/states/focusStackState';+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';import { type Meta, type StoryObj } from '@storybook/react-vite';import { expect, fn, userEvent, waitFor, within } from 'storybook/test';-import { isDefined } from 'twenty-shared/utils';+import { StrictMode } from 'react';+import { Button } from 'twenty-ui/primitives/input';import { WorkflowStepDecorator } from '~/testing/decorators/WorkflowStepDecorator';import { MOCKED_STEP_ID } from '~/testing/mock-data/workflow';@@ -18,6 +21,13 @@ export default meta;type Story = StoryObj<typeof FormArrayFieldInput>;export const AddTwoItems: Story = {+ decorators: [+ (Story) => (+ <StrictMode>+ <Story />+ </StrictMode>+ ),+ ],args: {label: 'Items',defaultValue: undefined,@@ -93,31 +103,29 @@ export const EditExistingItem: Story = {await userEvent.click(firstItemChip);- const openSecondItemMenuButton = await waitFor(() => {- const button = canvasElement.ownerDocument.body.querySelector(- '[aria-controls$="-1-options"] > button',- );-- if (!isDefined(button)) {- throw new Error('Button not found');- }-- return button;- });+ const body = within(canvasElement.ownerDocument.body);+ const panel = await body.findByRole('dialog', { name: 'Items' });+ await userEvent.click(within(panel).getByText('Second item'));+ expect(body.queryByRole('menu')).not.toBeInTheDocument();+ const openSecondItemMenuButton = within(panel).getAllByRole('button', {+ name: 'More options',+ })[1];await userEvent.click(openSecondItemMenuButton);- const editSecondItemButton = await within(- canvasElement.ownerDocument.body,- ).findByText('Edit');+ const editSecondItemButton = await body.findByRole('menuitem', {+ name: 'Edit',+ });await userEvent.click(editSecondItemButton);+ expect(panel).toBeVisible();const editSecondItemInput = await within(canvasElement.ownerDocument.body,).findByRole('textbox');expect(editSecondItemInput).toHaveValue('Second item');+ await waitFor(() => expect(editSecondItemInput).toHaveFocus());await userEvent.clear(editSecondItemInput);await userEvent.type(editSecondItemInput, 'Updated second item{enter}');@@ -128,6 +136,8 @@ export const EditExistingItem: Story = {'Updated second item',]);});+ expect(panel).toBeVisible();+ expect(within(panel).queryByRole('textbox')).not.toBeInTheDocument();const updatedSecondItemChip = await canvas.findByText('Updated second item',@@ -150,23 +160,17 @@ export const DeleteExistingItem: Story = {await userEvent.click(firstItemChip);- const openSecondItemMenuButton = await waitFor(() => {- const button = canvasElement.ownerDocument.body.querySelector(- '[aria-controls$="-1-options"] > button',- );-- if (!isDefined(button)) {- throw new Error('Button not found');- }-- return button;- });+ const body = within(canvasElement.ownerDocument.body);+ const panel = await body.findByRole('dialog', { name: 'Items' });+ const openSecondItemMenuButton = within(panel).getAllByRole('button', {+ name: 'More options',+ })[1];await userEvent.click(openSecondItemMenuButton);- const deleteSecondItemButton = await within(- canvasElement.ownerDocument.body,- ).findByText('Delete');+ const deleteSecondItemButton = await body.findByRole('menuitem', {+ name: 'Delete',+ });await userEvent.click(deleteSecondItemButton);@@ -175,6 +179,148 @@ export const DeleteExistingItem: Story = {});expect(canvas.queryByText('Second item')).not.toBeInTheDocument();+ expect(panel).toBeVisible();+ },+};++export const ItemLimit: Story = {+ args: {+ label: 'Items',+ defaultValue: ['First item'],+ maxItemCount: 2,+ onChange: fn(),+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ await userEvent.click(await canvas.findByRole('button', { name: 'Items' }));+ await userEvent.click(+ await body.findByRole('button', { name: 'Add item' }),+ );+ await userEvent.type(body.getByRole('textbox'), 'Second item{enter}');++ expect(args.onChange).toHaveBeenLastCalledWith([+ 'First item',+ 'Second item',+ ]);+ expect(+ body.queryByRole('button', { name: 'Add item' }),+ ).not.toBeInTheDocument();++ const panel = body.getByRole('dialog', { name: 'Items' });++ await userEvent.click(+ within(panel).getAllByRole('button', { name: 'More options' })[1],+ );+ await userEvent.click(+ await body.findByRole('menuitem', { name: 'Delete' }),+ );++ expect(args.onChange).toHaveBeenLastCalledWith(['First item']);+ expect(panel).toBeVisible();+ expect(+ within(panel).getByRole('button', { name: 'Add item' }),+ ).toBeVisible();+ },+};++export const EscapeDismissesOneLayer: Story = {+ args: {+ label: 'Items',+ defaultValue: ['First item'],+ onChange: fn(),+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const initialFocusStack = jotaiStore.get(focusStackState.atom);++ await userEvent.click(await canvas.findByRole('button', { name: 'Items' }));++ const panel = await body.findByRole('dialog', { name: 'Items' });+ const menuTrigger = within(panel).getByRole('button', {+ name: 'More options',+ });+ const panelFocusStack = jotaiStore.get(focusStackState.atom);++ await userEvent.click(menuTrigger);+ await userEvent.keyboard('{escape}');++ await waitFor(() =>+ expect(body.queryByRole('menu')).not.toBeInTheDocument(),+ );+ expect(panel).toBeVisible();+ expect(jotaiStore.get(focusStackState.atom)).toEqual(panelFocusStack);+ await waitFor(() => expect(menuTrigger).toHaveFocus());++ await userEvent.keyboard('{escape}');++ await waitFor(() =>+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),+ );+ expect(jotaiStore.get(focusStackState.atom)).toEqual(initialFocusStack);+ },+};++export const EscapeClearsUncommittedItem: Story = {+ args: {+ label: 'Items',+ defaultValue: ['First item'],+ onChange: fn(),+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const trigger = await canvas.findByRole('button', { name: 'Items' });++ await userEvent.click(trigger);+ await userEvent.click(+ await body.findByRole('button', { name: 'Add item' }),+ );+ await userEvent.type(body.getByRole('textbox'), 'Uncommitted{escape}');++ await waitFor(() =>+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),+ );+ expect(args.onChange).not.toHaveBeenCalled();++ await userEvent.click(trigger);+ await userEvent.click(+ await body.findByRole('button', { name: 'Add item' }),+ );++ expect(body.getByRole('textbox')).toHaveValue('');+ },+};++export const TabOrderIncludesTrigger: Story = {+ decorators: [+ (Story) => (+ <>+ <Button>Before</Button>+ <Story />+ <Button>After</Button>+ </>+ ),+ ],+ args: {+ label: 'Items',+ defaultValue: ['First item'],+ onChange: fn(),+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByRole('button', { name: 'Before' }),+ );+ await userEvent.tab();++ expect(canvas.getByRole('button', { name: 'Items' })).toHaveFocus();++ await userEvent.tab();++ expect(canvas.getByRole('button', { name: 'After' })).toHaveFocus();},};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__stories__/FormMultiSelectFieldInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__stories__/FormMultiSelectFieldInput.stories.tsxindex 98f17324edb..2ed773551fb 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__stories__/FormMultiSelectFieldInput.stories.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__stories__/FormMultiSelectFieldInput.stories.tsx@@ -1,13 +1,14 @@import { FormMultiSelectFieldInput } from '@/object-record/record-field/ui/form-types/components/FormMultiSelectFieldInput';import { type Meta, type StoryObj } from '@storybook/react-vite';-import { expect, fn, userEvent, within } from 'storybook/test';+import { Input } from 'twenty-ui/primitives/input';+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';import { WorkflowStepDecorator } from '~/testing/decorators/WorkflowStepDecorator';import { MOCKED_STEP_ID } from '~/testing/mock-data/workflow';const meta: Meta<typeof FormMultiSelectFieldInput> = {title: 'UI/Data/Field/Form/Input/FormMultiSelectFieldInput',component: FormMultiSelectFieldInput,- args: {},+ args: { onChange: fn() },argTypes: {},decorators: [WorkflowStepDecorator],};@@ -16,33 +17,35 @@ export default meta;type Story = StoryObj<typeof FormMultiSelectFieldInput>;+const WORK_POLICY_ARGS: Story['args'] = {+ label: 'Work Policy',+ defaultValue: ['WORK_POLICY_1', 'WORK_POLICY_2'],+ options: [+ {+ label: 'Work Policy 1',+ value: 'WORK_POLICY_1',+ color: 'blue',+ },+ {+ label: 'Work Policy 2',+ value: 'WORK_POLICY_2',+ color: 'green',+ },+ {+ label: 'Work Policy 3',+ value: 'WORK_POLICY_3',+ color: 'red',+ },+ {+ label: 'Work Policy 4',+ value: 'WORK_POLICY_4',+ color: 'yellow',+ },+ ],+};+export const Default: Story = {- args: {- label: 'Work Policy',- defaultValue: ['WORK_POLICY_1', 'WORK_POLICY_2'],- options: [- {- label: 'Work Policy 1',- value: 'WORK_POLICY_1',- color: 'blue',- },- {- label: 'Work Policy 2',- value: 'WORK_POLICY_2',- color: 'green',- },- {- label: 'Work Policy 3',- value: 'WORK_POLICY_3',- color: 'red',- },- {- label: 'Work Policy 4',- value: 'WORK_POLICY_4',- color: 'yellow',- },- ],- },+ args: WORK_POLICY_ARGS,play: async ({ canvasElement }) => {const canvas = within(canvasElement);@@ -135,3 +138,86 @@ export const DisabledWithVariable: Story = {expect(searchInputInModal).not.toBeInTheDocument();},};++export const ToggleAndDismiss: Story = {+ args: WORK_POLICY_ARGS,+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const trigger = await canvas.findByRole('button', { name: 'Work Policy' });++ await userEvent.click(trigger);+ const popup = await body.findByRole('dialog', { name: 'Work Policy' });+ const picker = within(popup);++ await userEvent.type(picker.getByRole('searchbox'), 'Policy 3{Enter}');+ await waitFor(() => {+ expect(args.onChange).toHaveBeenCalledWith([+ 'WORK_POLICY_3',+ 'WORK_POLICY_1',+ 'WORK_POLICY_2',+ ]);+ });+ expect(popup).toBeVisible();++ await userEvent.keyboard('{Escape}');+ await waitFor(() => {+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();+ });+ await waitFor(() => {+ expect(trigger).toHaveFocus();+ });+ await userEvent.keyboard('{Enter}');+ expect(+ await body.findByRole('dialog', { name: 'Work Policy' }),+ ).toBeVisible();+ expect(body.getByRole('searchbox')).toHaveValue('');+ expect(+ within(body.getByRole('dialog')).getByRole('button', {+ name: 'Work Policy 3',+ }),+ ).toHaveAttribute('aria-pressed', 'true');+ },+};++export const OutsideInputKeepsPickerOpen: Story = {+ args: WORK_POLICY_ARGS,+ decorators: [+ (Story) => (+ <>+ <Story />+ <Input aria-label="Outside input" />+ </>+ ),+ ],+ play: async ({ canvasElement }) => {+ const body = within(canvasElement.ownerDocument.body);++ await userEvent.click(+ await body.findByRole('button', { name: 'Work Policy' }),+ );+ const popup = await body.findByRole('dialog', { name: 'Work Policy' });+ await userEvent.click(body.getByRole('textbox', { name: 'Outside input' }));+ expect(popup).toBeVisible();+ },+};++export const EmptyLabelUsesPlaceholderAsName: Story = {+ args: {+ ...WORK_POLICY_ARGS,+ label: '',+ placeholder: 'Choose policies',+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await userEvent.click(+ await canvas.findByRole('button', { name: 'Choose policies' }),+ );++ expect(+ await body.findByRole('dialog', { name: 'Choose policies' }),+ ).toBeVisible();+ },+};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__tests__/FormArrayFieldInput.test.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__tests__/FormArrayFieldInput.test.tsxindex d26d09e4bd3..9dda4b84712 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__tests__/FormArrayFieldInput.test.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/__tests__/FormArrayFieldInput.test.tsx@@ -2,10 +2,10 @@ import { FormArrayFieldInput } from '@/object-record/record-field/ui/form-types/import { FormLinksFieldInput } from '@/object-record/record-field/ui/form-types/components/FormLinksFieldInput';import { i18n } from '@lingui/core';import { I18nProvider } from '@lingui/react';-import { render, screen } from '@testing-library/react';+import { render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { createStore, Provider } from 'jotai';-import { type ReactNode } from 'react';+import { type ReactNode, StrictMode } from 'react';const renderWithProviders = (children: ReactNode) => {const store = createStore();@@ -13,7 +13,9 @@ const renderWithProviders = (children: ReactNode) => {return render(children, {wrapper: ({ children: wrappedChildren }) => (<I18nProvider i18n={i18n}>- <Provider store={store}>{wrappedChildren}</Provider>+ <Provider store={store}>+ <StrictMode>{wrappedChildren}</StrictMode>+ </Provider></I18nProvider>),});@@ -26,7 +28,11 @@ const renderArrayField = ({renderWithProviders(<><button>Before</button>- <FormArrayFieldInput defaultValue={defaultValue} onChange={onChange} />+ <FormArrayFieldInput+ label="Items"+ defaultValue={defaultValue}+ onChange={onChange}+ /><button>After</button></>,);@@ -55,7 +61,7 @@ it.each([},);-it('trims the first item added with Enter', async () => {+it('commits the trimmed first item on Enter and opens its panel with the row menu focused under StrictMode', async () => {const user = userEvent.setup();const { onChange } = renderArrayField();const itemInput = screen.getByPlaceholderText('Enter an item');@@ -66,6 +72,13 @@ it('trims the first item added with Enter', async () => {expect(onChange).toHaveBeenCalledTimes(1);expect(onChange).toHaveBeenCalledWith(['Draft item']);+ const panel = await screen.findByRole('dialog', { name: 'Items' });+ expect(panel).toBeVisible();+ await waitFor(() =>+ expect(+ within(panel).getByRole('button', { name: 'More options' }),+ ).toHaveFocus(),+ );});it('adds the typed first item when focus moves to another element', async () => {diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FieldInputDropdown.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FieldInputDropdown.tsxnew file mode 100644index 00000000000..25e72dd1ff1--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FieldInputDropdown.tsx@@ -0,0 +1,73 @@+import { FieldContext } from '@/object-record/record-field/ui/contexts/FieldContext';+import { useFieldInputAnchorContextOrThrow } from '@/object-record/record-field/ui/contexts/FieldInputAnchorContext';+import { FieldInputEventContext } from '@/object-record/record-field/ui/contexts/FieldInputEventContext';+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';+import { preventDropdownDismissOnInputElement } from '@/ui/layout/dropdown/utils/preventDropdownDismissOnInputElement';+import { type KeyboardEvent, type ReactNode, useContext } from 'react';+import { Key } from 'ts-key-enum';+import { isDefined } from 'twenty-shared/utils';+import { Dropdown } from 'twenty-ui/components/navigation';++type FieldInputDropdownProps<TValue> = {+ children: ReactNode;+ value: TValue;+ onDismiss: () => void;+ multiple?: boolean;+};++export const FieldInputDropdown = <TValue,>({+ children,+ value,+ onDismiss,+ multiple,+}: FieldInputDropdownProps<TValue>) => {+ const { fieldDefinition } = useContext(FieldContext);+ const { onTab, onShiftTab } = useContext(FieldInputEventContext);+ const { anchorRef, align, sideOffset, alignOffset, collisionPadding } =+ useFieldInputAnchorContextOrThrow();++ const handleOpenChange = (open: boolean) => {+ if (!open) {+ onDismiss();+ }+ };++ const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.key !== Key.Tab) {+ return;+ }++ const handleTab = event.shiftKey ? onShiftTab : onTab;++ if (!isDefined(handleTab)) {+ onDismiss();+ return;+ }++ event.preventDefault();+ handleTab({ newValue: value });+ };++ return (+ <Dropdown.Root+ type="picker"+ multiple={multiple}+ open+ onOpenChange={handleOpenChange}+ onInteractOutside={preventDropdownDismissOnInputElement}+ >+ <DropdownContent+ anchor={anchorRef}+ align={align}+ sideOffset={sideOffset}+ alignOffset={alignOffset}+ collisionPadding={collisionPadding}+ aria-label={fieldDefinition.label}+ finalFocus={false}+ onKeyDown={handleKeyDown}+ >+ {children}+ </DropdownContent>+ </Dropdown.Root>+ );+};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.tsxindex 98c63e18cc2..c1d248f6af6 100644--- 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@@ -1,11 +1,10 @@import { styled } from '@linaria/react';-import {- forwardRef,- useRef,- type InputHTMLAttributes,- type ReactNode,-} from 'react';-import { useRegisterInputEvents } from '@/object-record/record-field/ui/meta-types/input/hooks/useRegisterInputEvents';+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 { useCombinedRefs } from '~/hooks/useCombinedRefs';@@ -73,104 +72,111 @@ const StyledErrorDiv = styled.div`padding: 0 ${themeCssVariables.spacing[2]};`;-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;- rightComponent?: ReactNode;- renderInput?: (props: {- value: HTMLInputProps['value'];- onChange: (value: string) => void;- autoFocus: HTMLInputProps['autoFocus'];- placeholder: HTMLInputProps['placeholder'];- hasError?: boolean;- }) => React.ReactNode;- error?: string | null;- hasError?: boolean;- hasItem: boolean;- onChange: (value: string) => void;- instanceId: string;-};+export const MultiItemBaseInput = ({+ autoFocus,+ className,+ value,+ placeholder,+ onChange,+ onClickOutside,+ onEnter,+ onEscape,+ onShiftTab,+ onTab,+ preventTabNavigation = false,+ onFocus,+ onBlur,+ rightComponent,+ renderInput,+ error = '',+ hasError = false,+ hasItem,+ instanceId,+ ref,+}: MultiItemBaseInputProps & { ref?: Ref<HTMLInputElement> }) => {+ const inputRef = useRef<HTMLInputElement>(null);+ const combinedRef = useCombinedRefs(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);-export const MultiItemBaseInput = forwardRef<- HTMLInputElement,- MultiItemBaseInputProps->(- (- {- autoFocus,- className,- value,- placeholder,- onChange,- onClickOutside,- onEnter = () => {},- onEscape = () => {},- onShiftTab,- onTab,- onFocus,- onBlur,- rightComponent,- renderInput,- error = '',- hasError = false,- hasItem,- instanceId,- },- ref,- ) => {- const inputRef = useRef<HTMLInputElement>(null);- const combinedRef = useCombinedRefs(ref, inputRef);-- useRegisterInputEvents({- focusId: instanceId,- inputRef,- inputValue: value,- onEnter,- onEscape,- onClickOutside,- onTab,- onShiftTab,- });-- return (- <>- <StyledInputContainer className={className}>- {renderInput ? (- renderInput({- value,- onChange,- autoFocus,- placeholder,- hasError,- })- ) : (- <StyledInput- hasError={hasError}- autoFocus={autoFocus}- value={value}- placeholder={placeholder}- onChange={(event) => onChange(event.target.value)}- ref={combinedRef}- withRightComponent={isDefined(rightComponent)}- hasItem={hasItem}- onFocus={onFocus}- onBlur={onBlur}- />- )}- {isDefined(rightComponent) && (- <StyledRightContainer>{rightComponent}</StyledRightContainer>- )}- </StyledInputContainer>- {error && <StyledErrorDiv>{error}</StyledErrorDiv>}- </>- );- },-);+ 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,+ })+ ) : (+ <StyledInput+ hasError={hasError}+ autoFocus={autoFocus}+ value={value}+ placeholder={placeholder}+ onChange={(event) => onChange(event.target.value)}+ ref={combinedRef}+ withRightComponent={isDefined(rightComponent)}+ hasItem={hasItem}+ onFocus={onFocus}+ onBlur={onBlur}+ onKeyDown={handleKeyDown}+ />+ )}+ {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/MultiItemFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInput.tsxindex bb209be2ef6..f1aa9de9170 100644--- 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@@ -1,30 +1,29 @@-import {- MultiItemBaseInput,- type MultiItemBaseInputProps,-} from '@/object-record/record-field/ui/meta-types/input/components/MultiItemBaseInput';+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 { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';-import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';-import { DropdownMenuSearchInput } from '@/ui/layout/dropdown/components/DropdownMenuSearchInput';-import { DropdownMenuSeparator } from '@/ui/layout/dropdown/components/DropdownMenuSeparator';+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 } from 'twenty-shared/utils';+import { CustomError, isDefined, isNonEmptyArray } from 'twenty-shared/utils';import { LightIconButton } from 'twenty-ui/components/input';import { OverflowingTextWithTooltip } from 'twenty-ui/primitives/typography';import { IconCheck, IconPlus } from 'twenty-ui/icon';import { ListItem } from 'twenty-ui/primitives/navigation';+import { themeCssVariables } from 'twenty-ui/theme';import { useDebounce } from 'use-debounce';import { FieldMetadataType } from '~/generated-metadata/graphql';import { moveArrayItem } from '~/utils/array/moveArrayItem';@@ -33,6 +32,10 @@ import { isDeeplyEqual } from '~/utils/isDeeplyEqual';import { normalizeSearchText } from '~/utils/normalizeSearchText';import { turnIntoEmptyStringIfWhitespacesOnly } from '~/utils/string/turnIntoEmptyStringIfWhitespacesOnly';+const StyledAddItemContainer = styled.div`+ padding: ${themeCssVariables.spacing[1]};+`;+type MultiItemFieldInputProps<T> = {items: T[];onChange: (newItemsValue: T[]) => void;@@ -311,80 +314,90 @@ export const MultiItemFieldInput = <T,>({dependencies: [handleEscape],});+ const shouldShowItems =+ isNonEmptyArray(filteredItems) &&+ (!shouldAutoEnterBecauseOnlyOneItemIsAllowed || !isInputDisplayed);+return (- <LegacyDropdownContent ref={containerRef}>- {shouldShowSearch && !isInputDisplayed && (- <>- <DropdownMenuSearchInput- value={searchFilter}- onChange={(event) =>- setSearchFilter(- turnIntoEmptyStringIfWhitespacesOnly(event.currentTarget.value),- )- }- autoFocus- />- <DropdownMenuSeparator />- </>- )}- {!!filteredItems.length &&- (!shouldAutoEnterBecauseOnlyOneItemIsAllowed || !isInputDisplayed) && (+ <OverlayMenuList+ ref={containerRef}+ header={+ shouldShowSearch && !isInputDisplayed ? (<>- <DropdownMenuItemsContainer hasMaxHeight>- {filteredItems.map((item) => {- const originalIndex = items.indexOf(item);- return renderItem({- value: item,- index: originalIndex,- handleEdit: () => handleEditButtonClick(originalIndex),- handleSetPrimary: () => handleSetPrimaryItem(originalIndex),- handleDelete: () => {- handleDeleteItem(originalIndex);- },- });- })}- </DropdownMenuItemsContainer>- {isInputDisplayed || !isLimitReached ? (- <DropdownMenuSeparator />- ) : null}+ <OverlayMenuListSearchRow+ value={searchFilter}+ onChange={(event) =>+ setSearchFilter(+ turnIntoEmptyStringIfWhitespacesOnly(+ event.currentTarget.value,+ ),+ )+ }+ />+ <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}- hasItem={!!items.length}- rightComponent={- items.length ? (- <LightIconButton- onClick={handleEnter}- aria-label={isAddingNewItem ? t`Add item` : t`Save item`}- >- {isAddingNewItem ? <IconPlus /> : <IconCheck />}- </LightIconButton>- ) : null- }- />- ) : !isLimitReached ? (- <DropdownMenuItemsContainer>- <ListItem onClick={handleAddButtonClick} startIcon={<IconPlus />}>- <OverflowingTextWithTooltip- text={newItemLabel || `Add ${placeholder}`}+ ) : 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+ hasItem={isNonEmptyArray(items)}+ rightComponent={+ isNonEmptyArray(items) ? (+ <LightIconButton+ onClick={handleEnter}+ aria-label={isAddingNewItem ? t`Add item` : t`Save item`}+ >+ {isAddingNewItem ? <IconPlus /> : <IconCheck />}+ </LightIconButton>+ ) : null+ }/>- </ListItem>- </DropdownMenuItemsContainer>- ) : null}- </LegacyDropdownContent>+ ) : !isLimitReached ? (+ <StyledAddItemContainer>+ <ListItem onClick={handleAddButtonClick} startIcon={<IconPlus />}>+ <OverflowingTextWithTooltip+ text={newItemLabel || `Add ${placeholder}`}+ />+ </ListItem>+ </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/MultiItemFieldMenuItem.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldMenuItem.tsxindex 76ebb12ac07..a150ae65136 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldMenuItem.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldMenuItem.tsx@@ -1,12 +1,7 @@-import { ListItem } from 'twenty-ui/primitives/navigation';import { t } from '@lingui/core/macro';-import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';-import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';-import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';-import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';import { MenuItemWithOptionDropdown } from '@/ui/navigation/menu-item/components/MenuItemWithOptionDropdown';-import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';import React, { useState } from 'react';+import { Dropdown } from 'twenty-ui/components/navigation';import {IconBookmark,IconBookmarkPlus,@@ -15,21 +10,21 @@ import {IconTrash,} from 'twenty-ui/icon';-type MultiItemFieldMenuItemProps<T> = {+type MultiItemFieldMenuItemProps<TValue> = {dropdownId: string;- value: T;+ value: TValue;onEdit?: () => void;onSetAsPrimary?: () => void;onDelete?: () => void;- onCopy?: (value: T) => void;+ onCopy?: (value: TValue) => void;onClick?: () => void;- DisplayComponent: React.ComponentType<{ value: T }>;+ DisplayComponent: React.ComponentType<{ value: TValue }>;showPrimaryIcon: boolean;showSetAsPrimaryButton: boolean;showCopyButton?: boolean;};-export const MultiItemFieldMenuItem = <T,>({+export const MultiItemFieldMenuItem = <TValue,>({dropdownId,value,onEdit,@@ -41,13 +36,8 @@ export const MultiItemFieldMenuItem = <T,>({showSetAsPrimaryButton,showCopyButton,onCopy,-}: MultiItemFieldMenuItemProps<T>) => {+}: MultiItemFieldMenuItemProps<TValue>) => {const [isHovered, setIsHovered] = useState(false);- const { closeDropdown } = useCloseDropdown();- const isDropdownOpen = useAtomComponentStateValue(- isDropdownOpenComponentState,- dropdownId,- );const handleMouseEnter = () => setIsHovered(true);const handleMouseLeave = () => {@@ -55,23 +45,11 @@ export const MultiItemFieldMenuItem = <T,>({};const handleDeleteClick = () => {- closeDropdown(dropdownId);setIsHovered(false);onDelete?.();};- const handleSetAsPrimaryClick = () => {- closeDropdown(dropdownId);- onSetAsPrimary?.();- };-- const handleEditClick = () => {- closeDropdown(dropdownId);- onEdit?.();- };-const handleCopyClick = () => {- closeDropdown(dropdownId);onCopy?.(value);};@@ -81,35 +59,33 @@ export const MultiItemFieldMenuItem = <T,>({onMouseLeave={handleMouseLeave}onClick={onClick}text={<DisplayComponent value={value} />}- isIconDisplayedOnHoverOnly={!showPrimaryIcon && !isDropdownOpen}+ isIconDisplayedOnHoverOnly={!showPrimaryIcon}RightIcon={!isHovered && showPrimaryIcon ? IconBookmark : null}dropdownId={dropdownId}dropdownContent={- <LegacyDropdownContent>- <DropdownMenuItemsContainer>- {showSetAsPrimaryButton && (- <ListItem- startIcon={<IconBookmarkPlus />}- onClick={handleSetAsPrimaryClick}- >{t`Set as Primary`}</ListItem>- )}- <ListItem- startIcon={<IconPencil />}- onClick={handleEditClick}- >{t`Edit`}</ListItem>- <ListItem- color="danger"- startIcon={<IconTrash />}- onClick={handleDeleteClick}- >{t`Delete`}</ListItem>- {showCopyButton && (- <ListItem- startIcon={<IconCopy />}- onClick={handleCopyClick}- >{t`Copy`}</ListItem>- )}- </DropdownMenuItemsContainer>- </LegacyDropdownContent>+ <Dropdown.Section>+ {showSetAsPrimaryButton && (+ <Dropdown.ActionItem+ startIcon={<IconBookmarkPlus />}+ onClick={onSetAsPrimary}+ >{t`Set as Primary`}</Dropdown.ActionItem>+ )}+ <Dropdown.ActionItem+ startIcon={<IconPencil />}+ onClick={onEdit}+ >{t`Edit`}</Dropdown.ActionItem>+ <Dropdown.ActionItem+ color="danger"+ startIcon={<IconTrash />}+ onClick={handleDeleteClick}+ >{t`Delete`}</Dropdown.ActionItem>+ {showCopyButton && (+ <Dropdown.ActionItem+ startIcon={<IconCopy />}+ onClick={handleCopyClick}+ >{t`Copy`}</Dropdown.ActionItem>+ )}+ </Dropdown.Section>}/>);diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiSelectFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiSelectFieldInput.tsxindex 4b229656cf0..4848ec62d42 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiSelectFieldInput.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiSelectFieldInput.tsx@@ -3,12 +3,11 @@ import { useAddSelectOption } from '@/object-record/record-field/ui/meta-types/himport { useCanAddSelectOption } from '@/object-record/record-field/ui/meta-types/hooks/useCanAddSelectOption';import { useFilteredSelectOptionsFromRLSPredicates } from '@/object-record/record-field/ui/meta-types/hooks/useFilteredSelectOptionsFromRLSPredicates';import { useMultiSelectField } from '@/object-record/record-field/ui/meta-types/hooks/useMultiSelectField';-import { SELECT_FIELD_INPUT_SELECTABLE_LIST_COMPONENT_INSTANCE_ID } from '@/object-record/record-field/ui/meta-types/input/constants/SelectFieldInputSelectableListComponentInstanceId';-import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';+import { FieldInputDropdown } from '@/object-record/record-field/ui/meta-types/input/components/FieldInputDropdown';import { type FieldMultiSelectValue } from '@/object-record/record-field/ui/types/FieldMetadata';import { MultiSelectInput } from '@/ui/field/input/components/MultiSelectInput';-import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';import { useContext } from 'react';+import { isDefined } from 'twenty-shared/utils';export const MultiSelectFieldInput = () => {const { fieldDefinition, draftValue, setDraftValue } = useMultiSelectField();@@ -19,7 +18,7 @@ export const MultiSelectFieldInput = () => {fieldDefinition.fieldMetadataId,);- const { onSubmit } = useContext(FieldInputEventContext);+ const { onSubmit, onEnter } = useContext(FieldInputEventContext);const { filteredOptions: selectOptions } =useFilteredSelectOptionsFromRLSPredicates({@@ -33,25 +32,28 @@ export const MultiSelectFieldInput = () => {setDraftValue(newDraftValue);};- const instanceId = useAvailableComponentInstanceIdOrThrow(- RecordFieldComponentInstanceContext,- );-const handleCancel = () => {onSubmit?.({ newValue: draftValue });};+ const handleEnter = () => {+ if (!isDefined(onEnter)) {+ handleCancel();+ return;+ }++ onEnter({ newValue: draftValue });+ };+return (- <MultiSelectInput- selectableListComponentInstanceId={- SELECT_FIELD_INPUT_SELECTABLE_LIST_COMPONENT_INSTANCE_ID- }- focusId={instanceId}- options={selectOptions}- onCancel={handleCancel}- onOptionSelected={handleOptionSelected}- values={draftValue}- onAddSelectOption={canAddSelectOption ? addSelectOption : undefined}- />+ <FieldInputDropdown value={draftValue} onDismiss={handleCancel} multiple>+ <MultiSelectInput+ onEnter={handleEnter}+ options={selectOptions}+ onOptionSelected={handleOptionSelected}+ values={draftValue}+ onAddSelectOption={canAddSelectOption ? addSelectOption : undefined}+ />+ </FieldInputDropdown>);};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.tsxindex cb055b7cdfa..869bea31bcc 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@@ -218,7 +218,16 @@ export const PhonesFieldInput = () => {onDelete={handleDelete}/>)}- renderInput={({ value, onChange, autoFocus, placeholder, hasError }) => {+ renderInput={({+ value,+ onChange,+ onKeyDown,+ onFocus,+ onBlur,+ autoFocus,+ placeholder,+ hasError,+ }) => {return (<StyledCustomPhoneInputContainerhasItem={!!phones.length}@@ -230,6 +239,9 @@ export const PhonesFieldInput = () => {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}diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/SelectFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/SelectFieldInput.tsxindex 8f314d277e6..2de9e5e9e59 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/SelectFieldInput.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/SelectFieldInput.tsx@@ -1,19 +1,12 @@-import { t } from '@lingui/core/macro';import { FieldInputEventContext } from '@/object-record/record-field/ui/contexts/FieldInputEventContext';import { useClearField } from '@/object-record/record-field/ui/hooks/useClearField';import { useAddSelectOption } from '@/object-record/record-field/ui/meta-types/hooks/useAddSelectOption';import { useCanAddSelectOption } from '@/object-record/record-field/ui/meta-types/hooks/useCanAddSelectOption';import { useFilteredSelectOptionsFromRLSPredicates } from '@/object-record/record-field/ui/meta-types/hooks/useFilteredSelectOptionsFromRLSPredicates';import { useSelectField } from '@/object-record/record-field/ui/meta-types/hooks/useSelectField';-import { SELECT_FIELD_INPUT_SELECTABLE_LIST_COMPONENT_INSTANCE_ID } from '@/object-record/record-field/ui/meta-types/input/constants/SelectFieldInputSelectableListComponentInstanceId';-import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';-import { SelectInput } from '@/ui/field/input/components/SelectInput';-import { useSelectableList } from '@/ui/layout/selectable-list/hooks/useSelectableList';-import { useHotkeysOnFocusedElement } from '@/ui/utilities/hotkey/hooks/useHotkeysOnFocusedElement';-import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';-import { useContext, useState } from 'react';-import { Key } from 'ts-key-enum';-import { isDefined } from 'twenty-shared/utils';+import { FieldInputDropdown } from '@/object-record/record-field/ui/meta-types/input/components/FieldInputDropdown';+import { SelectInput } from '@/ui/input/components/SelectInput';+import { useContext } from 'react';import { type SelectOption } from 'twenty-ui/primitives/input';export const SelectFieldInput = () => {@@ -35,20 +28,12 @@ export const SelectFieldInput = () => {options: fieldDefinition.metadata.options,});- const instanceId = useAvailableComponentInstanceIdOrThrow(- RecordFieldComponentInstanceContext,- );-- const [filteredOptions, setFilteredOptions] = useState<SelectOption[]>([]);-- const { resetSelectedItem } = useSelectableList(- SELECT_FIELD_INPUT_SELECTABLE_LIST_COMPONENT_INSTANCE_ID,- );const clearField = useClearField();- const selectedOption = selectOptions.find(- (option) => option.value === fieldValue,- );+ const handleCancel = () => {+ onCancel?.();+ };+const handleClearField = () => {clearField();onCancel?.();@@ -56,53 +41,22 @@ export const SelectFieldInput = () => {const handleSubmit = (option: SelectOption) => {onSubmit?.({ newValue: option.value });-- resetSelectedItem();};- useHotkeysOnFocusedElement({- keys: [Key.Escape],- callback: () => {- onCancel?.();- resetSelectedItem();- },- focusId: instanceId,- dependencies: [onCancel, resetSelectedItem],- });-- const fieldLabel = fieldDefinition.label;- const optionIds = [- t`No ${fieldLabel}`,- ...filteredOptions.map((option) => option.value),- ];-return (- <SelectInput- selectableListComponentInstanceId={- SELECT_FIELD_INPUT_SELECTABLE_LIST_COMPONENT_INSTANCE_ID- }- selectableItemIdArray={optionIds}- focusId={instanceId}- onEnter={(itemId) => {- const option = filteredOptions.find(- (option) => option.value === itemId,- );- if (isDefined(option)) {- handleSubmit(option);+ <FieldInputDropdown value={fieldValue} onDismiss={handleCancel}>+ <SelectInput+ onOptionSelected={handleSubmit}+ options={selectOptions}+ value={fieldValue}+ onClear={+ fieldDefinition.metadata.isNullable && canSelectEmpty+ ? handleClearField+ : undefined}- }}- onOptionSelected={handleSubmit}- options={selectOptions}- onCancel={onCancel}- defaultOption={selectedOption}- onFilterChange={setFilteredOptions}- onClear={- fieldDefinition.metadata.isNullable && canSelectEmpty- ? handleClearField- : undefined- }- clearLabel={fieldDefinition.label}- onAddSelectOption={canAddSelectOption ? addSelectOption : undefined}- />+ clearLabel={fieldDefinition.label}+ onAddSelectOption={canAddSelectOption ? addSelectOption : undefined}+ />+ </FieldInputDropdown>);};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/ArrayFieldInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/ArrayFieldInput.stories.tsxindex 3541bbea23f..f35be7d88dd 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/ArrayFieldInput.stories.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/ArrayFieldInput.stories.tsx@@ -14,8 +14,11 @@ import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentTypimport { ArrayFieldInput } from '@/object-record/record-field/ui/meta-types/input/components/ArrayFieldInput';import { FieldMetadataType } from '~/generated-metadata/graphql';-const { FieldInputEventContextProviderWithJestMocks } =- getFieldInputEventContextProviderWithJestMocks();+const {+ FieldInputEventContextProviderWithJestMocks,+ handleEscapeMocked,+ handleClickoutsideMocked,+} = getFieldInputEventContextProviderWithJestMocks();const ArrayValueSetterEffect = ({ value }: { value: string[] }) => {const { setFieldValue, setDraftValue } = useArrayField();@@ -101,6 +104,7 @@ const ArrayInputWithContext = ({const meta: Meta<typeof ArrayInputWithContext> = {title: 'UI/Input/ArrayFieldInput',component: ArrayInputWithContext,+ parameters: { mockingDate: null },decorators: [],};@@ -144,3 +148,52 @@ export const TrimInput: Story = {});},};++export const SearchAndEditItem: Story = {+ args: {+ value: ['tag1', 'tag2', 'tag3', 'tag4'],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const searchInput = await canvas.findByPlaceholderText('Search');++ await userEvent.type(searchInput, 'tag3');+ await waitFor(() => {+ expect(canvas.queryByText('tag1')).not.toBeInTheDocument();+ });++ const item = await canvas.findByText('tag3');++ await userEvent.click(item);+ expect(body.queryByRole('menu')).not.toBeInTheDocument();++ const optionsButton = await canvas.findByRole('button', {+ name: 'More options',+ });++ await userEvent.click(optionsButton);+ expect(optionsButton).toBeVisible();+ await body.findByRole('menuitem', { name: 'Edit' });+ await userEvent.keyboard('{Escape}');++ await waitFor(() => {+ expect(body.queryByRole('menu')).not.toBeInTheDocument();+ });+ expect(handleEscapeMocked).not.toHaveBeenCalled();+ expect(handleClickoutsideMocked).not.toHaveBeenCalled();+ await waitFor(() => expect(optionsButton).toHaveFocus());++ await userEvent.click(optionsButton);+ await userEvent.click(await body.findByRole('menuitem', { name: 'Edit' }));++ const input = await canvas.findByPlaceholderText('Enter value');++ expect(input).toHaveValue('tag3');+ await userEvent.clear(input);+ await userEvent.type(input, 'tag3-edited{Enter}');++ expect(await canvas.findByText('tag3-edited')).toBeVisible();+ expect(handleClickoutsideMocked).not.toHaveBeenCalled();+ },+};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/EmailsFieldInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/EmailsFieldInput.stories.tsxindex f7af1e48913..28d9bda552a 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/EmailsFieldInput.stories.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/EmailsFieldInput.stories.tsx@@ -17,8 +17,10 @@ import { ToastDecorator } from '~/testing/decorators/ToastDecorator';const updateRecord = fn();-const { FieldInputEventContextProviderWithJestMocks } =- getFieldInputEventContextProviderWithJestMocks();+const {+ FieldInputEventContextProviderWithJestMocks,+ handleClickoutsideMocked,+} = getFieldInputEventContextProviderWithJestMocks();const EmailValueSetterEffect = ({ value }: { value: FieldEmailsValue }) => {const { setFieldValue, setDraftValue } = useEmailsField();@@ -127,6 +129,31 @@ export const Default: Story = {},};+export const TabKeepsFocusInEditor: Story = {+ args: {+ value: {+ primaryEmail: '[email protected]',+ additionalEmails: [],+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(await canvas.findByText('Add Email'));++ const input = await canvas.findByPlaceholderText('Email');+ await userEvent.type(input, '[email protected]');++ await userEvent.tab();+ expect(input).toHaveFocus();+ expect(input).toHaveValue('[email protected]');++ await userEvent.tab({ shift: true });+ expect(input).toHaveFocus();+ expect(input).toHaveValue('[email protected]');+ },+};+export const TrimInput: Story = {args: {value: {@@ -164,20 +191,53 @@ export const CanNotSetPrimaryLinkAsPrimaryLink: Story = {await userEvent.hover(primaryEmail);const openDropdownButtons = await canvas.findAllByRole('button', {+ name: 'More options',expanded: false,});await userEvent.click(openDropdownButtons[0]);const editOption = await within(canvasElement.ownerDocument.body,- ).findByText('Edit');+ ).findByRole('menuitem', { name: 'Edit' });expect(editOption).toBeVisible();const setPrimaryOption = within(canvasElement.ownerDocument.body,- ).queryByText('Set as Primary');+ ).queryByRole('menuitem', { name: 'Set as Primary' });expect(setPrimaryOption).not.toBeInTheDocument();},};++export const InvalidEmailKeepsEditorOpen: Story = {+ args: {+ value: {+ primaryEmail: '',+ additionalEmails: [],+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = await canvas.findByPlaceholderText('Email');++ await userEvent.type(input, 'invalid-email');+ await userEvent.click(canvasElement.ownerDocument.body);++ expect(handleClickoutsideMocked).not.toHaveBeenCalled();+ expect(input).toBeVisible();+ expect(input).toHaveValue('invalid-email');++ await userEvent.clear(input);+ await userEvent.type(input, '[email protected]');+ await userEvent.click(canvasElement.ownerDocument.body);++ expect(handleClickoutsideMocked).toHaveBeenCalledWith({+ newValue: {+ primaryEmail: '[email protected]',+ additionalEmails: [],+ },+ event: expect.anything(),+ });+ },+};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/LinksFieldInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/LinksFieldInput.stories.tsxindex c19117bcd00..1415f64c7bd 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/LinksFieldInput.stories.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/LinksFieldInput.stories.tsx@@ -297,13 +297,14 @@ export const DeletePrimaryLink: Story = {expect(getPrimaryLinkBookmarkIcon(canvasElement)).not.toBeInTheDocument();const openDropdownButton = await canvas.findByRole('button', {+ name: 'More options',expanded: false,});await userEvent.click(openDropdownButton);const deleteOption = await within(canvasElement.ownerDocument.body,- ).findByText('Delete');+ ).findByRole('menuitem', { name: 'Delete' });await userEvent.click(deleteOption);const input = await canvas.findByPlaceholderText('URL');@@ -324,13 +325,14 @@ export const DeletePrimaryLinkPersistsEmptyValue: Story = {const canvas = within(canvasElement);const openDropdownButton = await canvas.findByRole('button', {+ name: 'More options',expanded: false,});await userEvent.click(openDropdownButton);const deleteOption = await within(canvasElement.ownerDocument.body,- ).findByText('Delete');+ ).findByRole('menuitem', { name: 'Delete' });await userEvent.click(deleteOption);expect(handleSubmitMocked).toHaveBeenCalledWith({@@ -352,13 +354,14 @@ export const ClearPrimaryLinkAndPressEnter: Story = {const canvas = within(canvasElement);const openDropdownButton = await canvas.findByRole('button', {+ name: 'More options',expanded: false,});await userEvent.click(openDropdownButton);const editOption = await within(canvasElement.ownerDocument.body,- ).findByText('Edit');+ ).findByRole('menuitem', { name: 'Edit' });await userEvent.click(editOption);const input = await canvas.findByPlaceholderText('URL');@@ -396,13 +399,14 @@ export const DeletePrimaryLinkAndUseSecondaryLinkAsTheNewPrimaryLink: Story = {});const openDropdownButtons = await canvas.findAllByRole('button', {+ name: 'More options',expanded: false,});await userEvent.click(openDropdownButtons[0]);const deleteOption = await within(canvasElement.ownerDocument.body,- ).findByText('Delete');+ ).findByRole('menuitem', { name: 'Delete' });await userEvent.click(deleteOption);const newPrimaryLink = await canvas.findByText('Documentation');@@ -438,13 +442,14 @@ export const DeleteSecondaryLink: Story = {await userEvent.hover(listItemToDelete);const openDropdownButtons = await canvas.findAllByRole('button', {+ name: 'More options',expanded: false,});await userEvent.click(openDropdownButtons[1]);const deleteOption = await within(canvasElement.ownerDocument.body,- ).findByText('Delete');+ ).findByRole('menuitem', { name: 'Delete' });await userEvent.click(deleteOption);const primaryLink = await canvas.findByText('Twenty Website');@@ -546,13 +551,14 @@ export const MakeSecondaryLinkPrimary: Story = {await userEvent.hover(secondaryLink);const openDropdownButtons = await canvas.findAllByRole('button', {+ name: 'More options',expanded: false,});await userEvent.click(openDropdownButtons[1]);const setPrimaryOption = await within(canvasElement.ownerDocument.body,- ).findByText('Set as Primary');+ ).findByRole('menuitem', { name: 'Set as Primary' });await userEvent.click(setPrimaryOption);expect(handleSubmitMocked).toHaveBeenCalledWith({@@ -585,13 +591,14 @@ export const CanNotSetPrimaryLinkAsPrimaryLink: Story = {expect(getPrimaryLinkBookmarkIcon(canvasElement)).not.toBeInTheDocument();const openDropdownButton = await canvas.findByRole('button', {+ name: 'More options',expanded: false,});await userEvent.click(openDropdownButton);const setPrimaryOption = within(canvasElement.ownerDocument.body,- ).queryByText('Set as Primary');+ ).queryByRole('menuitem', { name: 'Set as Primary' });expect(setPrimaryOption).not.toBeInTheDocument();},};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/MultiSelectFieldInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/MultiSelectFieldInput.stories.tsxnew file mode 100644index 00000000000..2bb8c2af121--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/MultiSelectFieldInput.stories.tsx@@ -0,0 +1,146 @@+import {+ FieldInputEventContext,+ type FieldInputEvent,+} from '@/object-record/record-field/ui/contexts/FieldInputEventContext';+import { useMultiSelectField } from '@/object-record/record-field/ui/meta-types/hooks/useMultiSelectField';+import { MultiSelectFieldInput } from '@/object-record/record-field/ui/meta-types/input/components/MultiSelectFieldInput';+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { useEffect, useState } from 'react';+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';+import { Button, Input } from 'twenty-ui/primitives/input';+import { FieldInputAnchorDecorator } from '~/testing/decorators/FieldInputAnchorDecorator';+import { getFieldDecorator } from '~/testing/decorators/getFieldDecorator';+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';++type MultiSelectFieldInputExampleProps = {+ onSubmit: FieldInputEvent;+ onEnter: FieldInputEvent;+ onShiftTab: FieldInputEvent;+};++const MultiSelectFieldInputExample = ({+ onSubmit,+ onEnter,+ onShiftTab,+}: MultiSelectFieldInputExampleProps) => {+ const [isOpen, setIsOpen] = useState(true);+ const { setDraftValue } = useMultiSelectField();++ useEffect(() => {+ setDraftValue(['ON_SITE']);+ }, [setDraftValue]);++ return (+ <FieldInputEventContext.Provider+ value={{+ onSubmit: (args) => {+ onSubmit(args);+ setIsOpen(false);+ },+ onEnter: (args) => {+ onEnter(args);+ setIsOpen(false);+ },+ onShiftTab: (args) => {+ onShiftTab(args);+ setIsOpen(false);+ },+ }}+ >+ {isOpen && <MultiSelectFieldInput />}+ <Input aria-label="Outside input" />+ <Button>Outside picker</Button>+ </FieldInputEventContext.Provider>+ );+};++const meta: Meta<typeof MultiSelectFieldInputExample> = {+ title: 'UI/Data/Field/Input/MultiSelectFieldInput',+ component: MultiSelectFieldInputExample,+ decorators: [+ getFieldDecorator('company', 'workPolicy', ['ON_SITE']),+ ObjectMetadataItemsDecorator,+ MemoryRouterDecorator,+ FieldInputAnchorDecorator,+ ],+ args: { onSubmit: fn(), onEnter: fn(), onShiftTab: fn() },+};++export default meta;+type Story = StoryObj<typeof MultiSelectFieldInputExample>;++export const ToggleThenEscape: Story = {+ play: async ({ canvasElement, args }) => {+ const body = within(canvasElement.ownerDocument.body);+ const popup = await body.findByRole('dialog', { name: 'Work Policy' });+ const picker = within(popup);++ await userEvent.type(picker.getByRole('searchbox'), 'hybrid{Enter}');+ await waitFor(() => {+ expect(picker.getByRole('button', { name: 'Hybrid' })).toHaveAttribute(+ 'aria-pressed',+ 'true',+ );+ });+ expect(popup).toBeVisible();+ expect(args.onSubmit).not.toHaveBeenCalled();+ await userEvent.keyboard('{Escape}');++ await waitFor(() => {+ expect(args.onSubmit).toHaveBeenCalledWith({+ newValue: ['HYBRID', 'ON_SITE'],+ });+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();+ });+ },+};++export const EmptySearchEnter: Story = {+ play: async ({ canvasElement, args }) => {+ const body = within(canvasElement.ownerDocument.body);+ const popup = await body.findByRole('dialog', { name: 'Work Policy' });+ const picker = within(popup);++ await userEvent.click(picker.getByRole('button', { name: 'Hybrid' }));+ await userEvent.click(picker.getByRole('searchbox'));+ await userEvent.keyboard('{Enter}');++ await waitFor(() => {+ expect(args.onEnter).toHaveBeenCalledWith({+ newValue: ['HYBRID', 'ON_SITE'],+ });+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();+ });+ },+};++export const OutsideInputThenPress: Story = {+ play: async ({ canvasElement, args }) => {+ const body = within(canvasElement.ownerDocument.body);+ const popup = await body.findByRole('dialog', { name: 'Work Policy' });++ await userEvent.click(body.getByRole('textbox', { name: 'Outside input' }));+ expect(popup).toBeVisible();+ expect(args.onSubmit).not.toHaveBeenCalled();+ await userEvent.click(body.getByRole('button', { name: 'Outside picker' }));++ await waitFor(() => {+ expect(args.onSubmit).toHaveBeenCalledWith({ newValue: ['ON_SITE'] });+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();+ });+ },+};++export const ShiftTab: Story = {+ play: async ({ canvasElement, args }) => {+ const body = within(canvasElement.ownerDocument.body);+ await body.findByRole('dialog', { name: 'Work Policy' });+ await userEvent.tab({ shift: true });++ await waitFor(() => {+ expect(args.onShiftTab).toHaveBeenCalledWith({ newValue: ['ON_SITE'] });+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();+ });+ },+};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/PhonesFieldInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/PhonesFieldInput.stories.tsxindex 08b6934b79d..7562e04d203 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/PhonesFieldInput.stories.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/PhonesFieldInput.stories.tsx@@ -210,19 +210,20 @@ export const CanNotSetPrimaryLinkAsPrimaryLink: Story = {await userEvent.hover(primaryPhone);const openDropdownButtons = await canvas.findAllByRole('button', {+ name: 'More options',expanded: false,});await userEvent.click(openDropdownButtons[0]);const editOption = await within(canvasElement.ownerDocument.body,- ).findByText('Edit');+ ).findByRole('menuitem', { name: 'Edit' });expect(editOption).toBeVisible();const setPrimaryOption = within(canvasElement.ownerDocument.body,- ).queryByText('Set as Primary');+ ).queryByRole('menuitem', { name: 'Set as Primary' });expect(setPrimaryOption).not.toBeInTheDocument();},diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/SelectFieldInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/SelectFieldInput.stories.tsxnew file mode 100644index 00000000000..8c3a3b010ce--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/SelectFieldInput.stories.tsx@@ -0,0 +1,193 @@+import {+ FieldInputEventContext,+ type FieldInputEvent,+} from '@/object-record/record-field/ui/contexts/FieldInputEventContext';+import { SelectFieldInput } from '@/object-record/record-field/ui/meta-types/input/components/SelectFieldInput';+import { RecordInlineCellEditMode } from '@/object-record/record-inline-cell/components/RecordInlineCellEditMode';+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { useState } from 'react';+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';+import { Button, Input } from 'twenty-ui/primitives/input';+import { FieldInputAnchorDecorator } from '~/testing/decorators/FieldInputAnchorDecorator';+import { getFieldDecorator } from '~/testing/decorators/getFieldDecorator';+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';++type SelectFieldInputExampleProps = {+ onSubmit: FieldInputEvent;+ onCancel: () => void;+ onTab: FieldInputEvent;+ inline?: boolean;+ scale?: number;+};++const SelectFieldInputExample = ({+ onSubmit,+ onCancel,+ onTab,+ inline = false,+ scale = 1,+}: SelectFieldInputExampleProps) => {+ const [isOpen, setIsOpen] = useState(true);++ const picker = isOpen ? <SelectFieldInput /> : null;++ return (+ <FieldInputEventContext.Provider+ value={{+ onSubmit: (args) => {+ onSubmit(args);+ setIsOpen(false);+ },+ onCancel: () => {+ onCancel();+ setIsOpen(false);+ },+ onTab: (args) => {+ onTab(args);+ setIsOpen(false);+ },+ }}+ >+ {inline ? (+ <div+ style={{ position: 'relative', width: 200, height: 80, zoom: scale }}+ >+ <RecordInlineCellEditMode>{picker}</RecordInlineCellEditMode>+ </div>+ ) : (+ picker+ )}+ <Input aria-label="Outside input" />+ <Button>Outside picker</Button>+ </FieldInputEventContext.Provider>+ );+};++const meta: Meta<typeof SelectFieldInputExample> = {+ title: 'UI/Data/Field/Input/SelectFieldInput',+ component: SelectFieldInputExample,+ decorators: [+ getFieldDecorator('task', 'status', 'TODO'),+ ObjectMetadataItemsDecorator,+ MemoryRouterDecorator,+ FieldInputAnchorDecorator,+ ],+ args: {+ onSubmit: fn(),+ onCancel: fn(),+ onTab: fn(),+ },+};++export default meta;+type Story = StoryObj<typeof SelectFieldInputExample>;++export const SearchThenEnter: Story = {+ play: async ({ canvasElement, args }) => {+ const body = within(canvasElement.ownerDocument.body);+ const popup = await body.findByRole('dialog', { name: 'Status' });+ const picker = within(popup);++ await userEvent.type(picker.getByRole('searchbox'), 'done');+ expect(+ picker.queryByRole('button', { name: 'No Status' }),+ ).not.toBeInTheDocument();+ expect(+ picker.queryByRole('button', { name: 'To do' }),+ ).not.toBeInTheDocument();+ await userEvent.keyboard('{Enter}');++ await waitFor(() => {+ expect(args.onSubmit).toHaveBeenCalledWith({ newValue: 'DONE' });+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();+ });+ expect(args.onCancel).not.toHaveBeenCalled();+ },+};++export const SearchMatchingClearOptionThenEnter: Story = {+ play: async ({ canvasElement, args }) => {+ const body = within(canvasElement.ownerDocument.body);+ const popup = await body.findByRole('dialog', { name: 'Status' });+ const picker = within(popup);++ await userEvent.type(picker.getByRole('searchbox'), 's');+ expect(+ picker.getByRole('button', { name: 'No Status' }),+ ).toBeInTheDocument();+ await userEvent.keyboard('{Enter}');++ await waitFor(() => {+ expect(args.onSubmit).toHaveBeenCalledWith({ newValue: 'IN_PROGRESS' });+ });+ expect(args.onCancel).not.toHaveBeenCalled();+ },+};++export const OutsideInputThenEscape: Story = {+ play: async ({ canvasElement, args }) => {+ const body = within(canvasElement.ownerDocument.body);+ const popup = await body.findByRole('dialog', { name: 'Status' });++ await userEvent.click(body.getByRole('textbox', { name: 'Outside input' }));+ expect(popup).toBeVisible();+ expect(args.onCancel).not.toHaveBeenCalled();+ await userEvent.click(within(popup).getByRole('searchbox'));+ await userEvent.keyboard('{Escape}');++ await waitFor(() => {+ expect(args.onCancel).toHaveBeenCalledTimes(1);+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();+ });+ expect(args.onSubmit).not.toHaveBeenCalled();+ },+};++export const OutsidePress: Story = {+ play: async ({ canvasElement, args }) => {+ const body = within(canvasElement.ownerDocument.body);+ await body.findByRole('dialog', { name: 'Status' });+ await userEvent.click(body.getByRole('button', { name: 'Outside picker' }));++ await waitFor(() => {+ expect(args.onCancel).toHaveBeenCalledTimes(1);+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();+ });+ },+};++export const Tab: Story = {+ play: async ({ canvasElement, args }) => {+ const body = within(canvasElement.ownerDocument.body);+ await body.findByRole('dialog', { name: 'Status' });+ await userEvent.tab();++ await waitFor(() => {+ expect(args.onTab).toHaveBeenCalledWith({ newValue: 'TODO' });+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();+ });+ },+};++export const InlineAnchor: Story = {+ args: { inline: true, scale: 1.25 },+ play: async ({ canvasElement }) => {+ const body = within(canvasElement.ownerDocument.body);+ const popup = await body.findByRole('dialog', { name: 'Status' });+ const anchor = within(canvasElement).getByTestId(+ 'inline-cell-edit-mode-container',+ );++ await waitFor(() => {+ const anchorBounds = anchor.getBoundingClientRect();+ const popupBounds = popup.getBoundingClientRect();+ expect(+ Math.abs(popupBounds.top - (anchorBounds.bottom - 29 * 1.25)),+ ).toBeLessThan(2);+ expect(+ Math.abs(popupBounds.left - (anchorBounds.left - 5 * 1.25)),+ ).toBeLessThan(2);+ });+ },+};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/constants/SelectFieldInputSelectableListComponentInstanceId.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/constants/SelectFieldInputSelectableListComponentInstanceId.tsdeleted file mode 100644index 400b8a99b7e..00000000000--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/constants/SelectFieldInputSelectableListComponentInstanceId.ts+++ /dev/null@@ -1,2 +0,0 @@-export const SELECT_FIELD_INPUT_SELECTABLE_LIST_COMPONENT_INSTANCE_ID =- 'select-field-input-selectable-list-component-instance-id';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.tsnew file mode 100644index 00000000000..91b561749fb--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/types/MultiItemBaseInputProps.ts@@ -0,0 +1,30 @@+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;+ hasItem: boolean;+ onChange: (value: string) => void;+ instanceId: string;+};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/types/FieldInputAnchorPosition.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/types/FieldInputAnchorPosition.tsnew file mode 100644index 00000000000..e0b9737132f--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/types/FieldInputAnchorPosition.ts@@ -0,0 +1,9 @@+import { type ComponentProps, type RefObject } from 'react';+import { type Dropdown } from 'twenty-ui/components/navigation';++export type FieldInputAnchorPosition = Pick<+ ComponentProps<typeof Dropdown.Content>,+ 'align' | 'sideOffset' | 'alignOffset' | 'collisionPadding'+> & {+ anchorRef: RefObject<Element | null>;+};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/getFieldInputAnchorPosition.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/getFieldInputAnchorPosition.tsnew file mode 100644index 00000000000..ac0056d3c7b--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/getFieldInputAnchorPosition.ts@@ -0,0 +1,29 @@+import { type FieldInputAnchorPosition } from '@/object-record/record-field/ui/types/FieldInputAnchorPosition';+import { getFloatingReferenceScale } from '@/ui/layout/overlay/utils/getFloatingReferenceScale';++export const getFieldInputAnchorPosition = ({+ anchorRef,+ sideOffset,+ alignOffset,+ align = 'start',+ collisionPadding,+}: Omit<FieldInputAnchorPosition, 'sideOffset' | 'alignOffset'> & {+ sideOffset: number;+ alignOffset: number;+}): FieldInputAnchorPosition => ({+ anchorRef,+ align,+ collisionPadding,+ sideOffset: ({ anchor }) =>+ sideOffset *+ getFloatingReferenceScale({+ rects: { reference: anchor },+ elements: { reference: anchorRef.current },+ }),+ alignOffset: ({ anchor }) =>+ alignOffset *+ getFloatingReferenceScale({+ rects: { reference: anchor },+ elements: { reference: anchorRef.current },+ }),+});diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/isFieldInputRenderedAsDropdown.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/isFieldInputRenderedAsDropdown.tsnew file mode 100644index 00000000000..fd44dba94a9--- /dev/null+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/isFieldInputRenderedAsDropdown.ts@@ -0,0 +1,9 @@+import { type FieldDefinition } from '@/object-record/record-field/ui/types/FieldDefinition';+import { type FieldMetadata } from '@/object-record/record-field/ui/types/FieldMetadata';+import { isFieldMultiSelect } from '@/object-record/record-field/ui/types/guards/isFieldMultiSelect';+import { isFieldSelect } from '@/object-record/record-field/ui/types/guards/isFieldSelect';++export const isFieldInputRenderedAsDropdown = (+ fieldDefinition: Pick<FieldDefinition<FieldMetadata>, 'type'>,+): boolean =>+ isFieldSelect(fieldDefinition) || isFieldMultiSelect(fieldDefinition);diff --git a/packages/twenty-front/src/modules/object-record/record-inline-cell/components/RecordInlineCellEditMode.tsx b/packages/twenty-front/src/modules/object-record/record-inline-cell/components/RecordInlineCellEditMode.tsxindex 6c2d1545cb8..44c4f33a96d 100644--- a/packages/twenty-front/src/modules/object-record/record-inline-cell/components/RecordInlineCellEditMode.tsx+++ b/packages/twenty-front/src/modules/object-record/record-inline-cell/components/RecordInlineCellEditMode.tsx@@ -1,3 +1,7 @@+import { FieldContext } from '@/object-record/record-field/ui/contexts/FieldContext';+import { FieldInputAnchorContextProvider } from '@/object-record/record-field/ui/contexts/FieldInputAnchorContext';+import { getFieldInputAnchorPosition } from '@/object-record/record-field/ui/utils/getFieldInputAnchorPosition';+import { isFieldInputRenderedAsDropdown } from '@/object-record/record-field/ui/utils/isFieldInputRenderedAsDropdown';import { getFloatingReferenceScale } from '@/ui/layout/overlay/utils/getFloatingReferenceScale';import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';import { recordFieldInputIsFieldInErrorComponentState } from '@/object-record/record-field/ui/states/recordFieldInputIsFieldInErrorComponentState';@@ -23,6 +27,11 @@ import {import { useContext } from 'react';import { createPortal } from 'react-dom';+const INLINE_FIELD_INPUT_SIDE_OFFSET = -29;+const INLINE_FIELD_INPUT_CENTERED_SIDE_OFFSET = -26;+const INLINE_FIELD_INPUT_ALIGN_OFFSET = -5;+const INLINE_FIELD_INPUT_COLLISION_PADDING = 8;+const StyledInlineCellEditModeContainer = styled.div`align-items: center;@@ -42,6 +51,10 @@ export const RecordInlineCellEditMode = ({children,}: RecordInlineCellEditModeProps) => {const { isCentered } = useContext(RecordInlineCellContext);+ const sideOffset = isCentered+ ? INLINE_FIELD_INPUT_CENTERED_SIDE_OFFSET+ : INLINE_FIELD_INPUT_SIDE_OFFSET;+ const alignOffset = isCentered ? 0 : INLINE_FIELD_INPUT_ALIGN_OFFSET;const recordFieldComponentInstanceId = useAvailableComponentInstanceIdOrThrow(RecordFieldComponentInstanceContext,@@ -72,6 +85,9 @@ export const RecordInlineCellEditMode = ({recordFieldInputIsFieldInErrorComponentState,);+ const { fieldDefinition } = useContext(FieldContext);+ const isDropdownFieldInput = isFieldInputRenderedAsDropdown(fieldDefinition);+const { refs, floatingStyles } = useFloating({placement: isCentered ? 'bottom' : 'bottom-start',strategy: 'fixed',@@ -81,11 +97,11 @@ export const RecordInlineCellEditMode = ({const referenceScale = getFloatingReferenceScale(state);return {- mainAxis: (isCentered ? -26 : -29) * referenceScale,- crossAxis: (isCentered ? 0 : -5) * referenceScale,+ mainAxis: sideOffset * referenceScale,+ crossAxis: alignOffset * referenceScale,};}),- shift({ padding: 8 }),+ shift({ padding: INLINE_FIELD_INPUT_COLLISION_PADDING }),size({apply: ({ rects, elements }) => {elements.floating.style.setProperty(@@ -104,8 +120,20 @@ export const RecordInlineCellEditMode = ({ref={refs.setReference}data-testid="inline-cell-edit-mode-container">- <>- {createPortal(+ {isDropdownFieldInput ? (+ <FieldInputAnchorContextProvider+ value={getFieldInputAnchorPosition({+ anchorRef: refs.domReference,+ sideOffset,+ alignOffset,+ align: isCentered ? 'center' : 'start',+ collisionPadding: INLINE_FIELD_INPUT_COLLISION_PADDING,+ })}+ >+ {children}+ </FieldInputAnchorContextProvider>+ ) : (+ createPortal(<StyledOverlayPortalLayerdata-floating-ui-viewportref={refs.setFloating}@@ -119,8 +147,8 @@ export const RecordInlineCellEditMode = ({</OverlayContainer></StyledOverlayPortalLayer>,document.body,- )}- </>+ )+ )}</StyledInlineCellEditModeContainer>);};diff --git a/packages/twenty-front/src/modules/object-record/record-table/__stories__/RecordTable.stories.tsx b/packages/twenty-front/src/modules/object-record/record-table/__stories__/RecordTable.stories.tsxindex 5b0dd72d635..a6b62e28ba1 100644--- a/packages/twenty-front/src/modules/object-record/record-table/__stories__/RecordTable.stories.tsx+++ b/packages/twenty-front/src/modules/object-record/record-table/__stories__/RecordTable.stories.tsx@@ -1,4 +1,5 @@import { type Meta, type StoryObj } from '@storybook/react-vite';+import { graphql, HttpResponse } from 'msw';import { RecordTableWithWrappers } from '@/object-record/record-table/components/RecordTableWithWrappers';import { expect, fireEvent, userEvent, waitFor, within } from 'storybook/test';@@ -13,6 +14,7 @@ import { ToastDecorator } from '~/testing/decorators/ToastDecorator';import { graphqlMocks } from '~/testing/graphqlMocks';import { mockedCompanyRecords } from '~/testing/mock-data/generated/data/companies/mock-companies-data';import { mockedViews } from '~/testing/mock-data/generated/metadata/views/mock-views-data';+import { mockedWorkspaceMemberRecords } from '~/testing/mock-data/generated/data/workspaceMembers/mock-workspaceMembers-data';import { getMockFieldMetadataItemOrThrow } from '~/testing/utils/getMockFieldMetadataItemOrThrow';import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';import { sleep } from '~/utils/sleep';@@ -226,3 +228,95 @@ export const ScrolledBottom: Story = {await canvas.findByText(mockedCompanyRecords[1].name);},};++export const MultiSelectPickerAnchorsToTableCell: Story = {+ parameters: {+ msw: {+ handlers: [+ ...graphqlMocks.handlers,+ graphql.query('FindOneWorkspaceMember', ({ variables }) =>+ HttpResponse.json({+ data: {+ workspaceMember:+ mockedWorkspaceMemberRecords.find(+ (workspaceMemberRecord) =>+ workspaceMemberRecord.id === variables.objectRecordId,+ ) ?? null,+ },+ }),+ ),+ ],+ },+ },+ beforeEach: () => {+ const originalViewFields = companyView.viewFields;+ const originalWorkPolicy = mockedCompanyRecords[0].workPolicy;+ const workPolicyField = getMockFieldMetadataItemOrThrow({+ objectMetadataItem: getMockObjectMetadataItemOrThrow('company'),+ fieldName: 'workPolicy',+ });++ companyView.viewFields = [+ ...originalViewFields.map((viewField) => ({+ ...viewField,+ position: viewField.position === 0 ? 0 : viewField.position + 1,+ })),+ {+ ...originalViewFields[0],+ id: 'work-policy-anchor-story-field',+ fieldMetadataId: workPolicyField.id,+ position: 1,+ },+ ];+ mockedCompanyRecords[0].workPolicy = ['ON_SITE'];++ return () => {+ companyView.viewFields = originalViewFields;+ mockedCompanyRecords[0].workPolicy = originalWorkPolicy;+ };+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await canvas.findByText(+ mockedCompanyRecords[0].name,+ {},+ { timeout: 3000 },+ );+ await userEvent.click((await canvas.findAllByText('On-Site'))[0]);++ const picker = await body.findByRole('dialog', { name: 'Work Policy' });+ const anchor = canvas.getByTestId('editable-cell-edit-mode-container');++ await waitFor(() => {+ const anchorBounds = anchor.getBoundingClientRect();+ const pickerBounds = picker.getBoundingClientRect();++ expect(+ Math.abs(pickerBounds.left - (anchorBounds.left - 3)),+ ).toBeLessThan(2);+ expect(+ Math.abs(pickerBounds.top - (anchorBounds.bottom - 33)),+ ).toBeLessThan(2);+ });++ const search = within(picker).getByRole('searchbox', { name: 'Search' });++ await userEvent.type(search, 'Remote');+ await userEvent.keyboard('{Enter}');++ await expect(+ within(picker).getByRole('button', { name: 'Remote Work' }),+ ).toHaveAttribute('aria-pressed', 'true');++ await userEvent.keyboard('{Enter}');++ await expect(+ within(picker).getByRole('button', { name: 'Remote Work' }),+ ).toHaveAttribute('aria-pressed', 'false');+ await expect(picker).toBeVisible();+ await userEvent.keyboard('{Escape}');+ await waitFor(() => expect(picker).not.toBeInTheDocument());+ },+};diff --git a/packages/twenty-front/src/modules/object-record/record-table/record-table-cell/components/RecordTableCellEditMode.tsx b/packages/twenty-front/src/modules/object-record/record-table/record-table-cell/components/RecordTableCellEditMode.tsxindex 1050f3b5978..e7a70f28a9e 100644--- a/packages/twenty-front/src/modules/object-record/record-table/record-table-cell/components/RecordTableCellEditMode.tsx+++ b/packages/twenty-front/src/modules/object-record/record-table/record-table-cell/components/RecordTableCellEditMode.tsx@@ -1,3 +1,7 @@+import { FieldContext } from '@/object-record/record-field/ui/contexts/FieldContext';+import { FieldInputAnchorContextProvider } from '@/object-record/record-field/ui/contexts/FieldInputAnchorContext';+import { getFieldInputAnchorPosition } from '@/object-record/record-field/ui/utils/getFieldInputAnchorPosition';+import { isFieldInputRenderedAsDropdown } from '@/object-record/record-field/ui/utils/isFieldInputRenderedAsDropdown';import { getFloatingReferenceScale } from '@/ui/layout/overlay/utils/getFloatingReferenceScale';import { useIsFieldInputOnly } from '@/object-record/record-field/ui/hooks/useIsFieldInputOnly';import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';@@ -22,6 +26,9 @@ import {} from '@floating-ui/react';import { useContext, type ReactElement } from 'react';+const TABLE_FIELD_INPUT_SIDE_OFFSET = -33;+const TABLE_FIELD_INPUT_ALIGN_OFFSET = -3;+const StyledEditableCellEditModeContainer = styled.div<{isFieldInputOnly: boolean;}>`@@ -76,6 +83,9 @@ export const RecordTableCellEditMode = ({},};+ const { fieldDefinition } = useContext(FieldContext);+ const isDropdownFieldInput = isFieldInputRenderedAsDropdown(fieldDefinition);+const { refs, floatingStyles } = useFloating({placement: 'bottom-start',strategy: 'fixed',@@ -85,8 +95,8 @@ export const RecordTableCellEditMode = ({const referenceScale = getFloatingReferenceScale(state);return {- mainAxis: -33 * referenceScale,- crossAxis: -3 * referenceScale,+ mainAxis: TABLE_FIELD_INPUT_SIDE_OFFSET * referenceScale,+ crossAxis: TABLE_FIELD_INPUT_ALIGN_OFFSET * referenceScale,};}),setFieldInputLayoutDirectionMiddleware,@@ -101,13 +111,9 @@ export const RecordTableCellEditMode = ({const { focusRecordTableCell } = useFocusRecordTableCell();- return (- <StyledEditableCellEditModeContainer- ref={refs.setReference}- data-testid="editable-cell-edit-mode-container"- isFieldInputOnly={isFieldInputOnly}- >- {isFieldInputOnly ? (+ const renderEditModeContent = () => {+ if (isFieldInputOnly) {+ return (<StyledInputModeOnlyContaineronClick={() => {focusRecordTableCell(cellPosition);@@ -115,22 +121,49 @@ export const RecordTableCellEditMode = ({>{children}</StyledInputModeOnlyContainer>- ) : (- <FloatingPortal>- <StyledOverlayPortalLayer- data-floating-ui-viewport- ref={refs.setFloating}- style={floatingStyles}+ );+ }++ if (isDropdownFieldInput) {+ return (+ <FieldInputAnchorContextProvider+ value={getFieldInputAnchorPosition({+ anchorRef: refs.domReference,+ sideOffset: TABLE_FIELD_INPUT_SIDE_OFFSET,+ alignOffset: TABLE_FIELD_INPUT_ALIGN_OFFSET,+ collisionPadding: 0,+ })}+ >+ {children}+ </FieldInputAnchorContextProvider>+ );+ }++ return (+ <FloatingPortal>+ <StyledOverlayPortalLayer+ data-floating-ui-viewport+ ref={refs.setFloating}+ style={floatingStyles}+ >+ <OverlayContainer+ borderRadius="sm"+ hasDangerBorder={recordFieldInputIsFieldInError}>- <OverlayContainer- borderRadius="sm"- hasDangerBorder={recordFieldInputIsFieldInError}- >- {children}- </OverlayContainer>- </StyledOverlayPortalLayer>- </FloatingPortal>- )}+ {children}+ </OverlayContainer>+ </StyledOverlayPortalLayer>+ </FloatingPortal>+ );+ };++ return (+ <StyledEditableCellEditModeContainer+ ref={refs.setReference}+ data-testid="editable-cell-edit-mode-container"+ isFieldInputOnly={isFieldInputOnly}+ >+ {renderEditModeContent()}</StyledEditableCellEditModeContainer>);};diff --git a/packages/twenty-front/src/modules/settings/data-model/fields/forms/select/components/AddSelectOptionMenuItem.tsx b/packages/twenty-front/src/modules/settings/data-model/fields/forms/select/components/AddSelectOptionMenuItem.tsxdeleted file mode 100644index 986deb27571..00000000000--- a/packages/twenty-front/src/modules/settings/data-model/fields/forms/select/components/AddSelectOptionMenuItem.tsx+++ /dev/null@@ -1,36 +0,0 @@-import { t } from '@lingui/core/macro';-import { isNonEmptyString } from '@sniptt/guards';-import { isDefined } from 'twenty-shared/utils';-import { OverflowingTextWithTooltip } from 'twenty-ui/primitives/typography';-import { IconPlus } from 'twenty-ui/icon';-import { ListItem } from 'twenty-ui/primitives/navigation';--type AddSelectOptionMenuItemProps = {- name: string;- onAddSelectOption?: (optionName: string) => void;-};--export const AddSelectOptionMenuItem = ({- name,- onAddSelectOption,-}: AddSelectOptionMenuItemProps) => {- const trimmedName = name.trim();- const showAddOption =- isNonEmptyString(trimmedName) && isDefined(onAddSelectOption);-- const handleClick = () => {- if (isDefined(onAddSelectOption)) {- onAddSelectOption(trimmedName);- }- };-- if (!showAddOption) {- return null;- }-- return (- <ListItem onClick={handleClick} startIcon={<IconPlus />}>- <OverflowingTextWithTooltip text={t`Add "${trimmedName}" to options`} />- </ListItem>- );-};diff --git a/packages/twenty-front/src/modules/ui/field/input/components/MultiSelectInput.tsx b/packages/twenty-front/src/modules/ui/field/input/components/MultiSelectInput.tsxindex 273d7c4dd0d..aec8ad0775a 100644--- a/packages/twenty-front/src/modules/ui/field/input/components/MultiSelectInput.tsx+++ b/packages/twenty-front/src/modules/ui/field/input/components/MultiSelectInput.tsx@@ -1,193 +1,100 @@-import { ListItem } from 'twenty-ui/primitives/navigation';-import { Tag } from 'twenty-ui/primitives/data-display';-import { isNonEmptyString } from '@sniptt/guards';-import { useRef, useState, createElement } from 'react';-import { Key } from 'ts-key-enum';-import { type FieldMultiSelectValue } from '@/object-record/record-field/ui/types/FieldMetadata';-import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';-import { DropdownMenuSearchInput } from '@/ui/layout/dropdown/components/DropdownMenuSearchInput';-import { DropdownMenuSeparator } from '@/ui/layout/dropdown/components/DropdownMenuSeparator';-import { SelectableList } from '@/ui/layout/selectable-list/components/SelectableList';--import { AddSelectOptionMenuItem } from '@/settings/data-model/fields/forms/select/components/AddSelectOptionMenuItem';-import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';-import { SelectableListItem } from '@/ui/layout/selectable-list/components/SelectableListItem';-import { useSelectableList } from '@/ui/layout/selectable-list/hooks/useSelectableList';-import { selectedItemIdComponentState } from '@/ui/layout/selectable-list/states/selectedItemIdComponentState';-import { useHotkeysOnFocusedElement } from '@/ui/utilities/hotkey/hooks/useHotkeysOnFocusedElement';-import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';-import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';+import { AddSelectOptionDropdownSection } from '@/ui/input/components/AddSelectOptionDropdownSection';+import { filterSelectOptionsBySearch } from '@/ui/input/utils/filterSelectOptionsBySearch';+import { isKeyboardEventComposing } from '@/ui/utilities/hotkey/utils/isKeyboardEventComposing';import { t } from '@lingui/core/macro';-import { isDefined } from 'twenty-shared/utils';+import { isNonEmptyString } from '@sniptt/guards';+import { createElement, useState } from 'react';+import { Key } from 'ts-key-enum';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';+import { Dropdown } from 'twenty-ui/components/navigation';+import { Tag } from 'twenty-ui/primitives/data-display';import { type SelectOption } from 'twenty-ui/primitives/input';-import { normalizeSearchText } from '~/utils/normalizeSearchText';import { turnIntoEmptyStringIfWhitespacesOnly } from '~/utils/string/turnIntoEmptyStringIfWhitespacesOnly';type MultiSelectInputProps = {- selectableListComponentInstanceId: string;values: FieldMultiSelectValue;- focusId: string;- onCancel?: () => void;options: SelectOption[];onOptionSelected: (value: FieldMultiSelectValue) => void;- dropdownWidth?: number;+ onEnter?: () => void;onAddSelectOption?: (optionName: string) => void;};export const MultiSelectInput = ({- selectableListComponentInstanceId,values,options,- focusId,- onCancel,onOptionSelected,- dropdownWidth,onAddSelectOption,+ onEnter,}: MultiSelectInputProps) => {- const { resetSelectedItem } = useSelectableList(- selectableListComponentInstanceId,- );-- const selectedItemId = useAtomComponentStateValue(- selectedItemIdComponentState,- selectableListComponentInstanceId,- );-const [searchFilter, setSearchFilter] = useState('');- const containerRef = useRef<HTMLDivElement>(null);-- const selectedOptions = options.filter((option) =>- values?.includes(option.value),- );-- const filterOptions = (searchText: string) => {- const searchTerm = normalizeSearchText(searchText);- return options.filter((option) => {- return normalizeSearchText(option.label).includes(searchTerm);- });- };-- const filteredOptionsInDropDown = filterOptions(searchFilter);-- const formatNewSelectedOptions = (value: string) => {- const selectedOptionsValues = selectedOptions.map(- (selectedOption) => selectedOption.value,- );- if (!selectedOptionsValues.includes(value)) {- return [value, ...selectedOptionsValues];- } else {- return selectedOptionsValues.filter(- (selectedOptionsValue) => selectedOptionsValue !== value,- );- }- };-- useHotkeysOnFocusedElement({- keys: Key.Escape,- callback: () => {- onCancel?.();- resetSelectedItem();- },- focusId,- dependencies: [onCancel, resetSelectedItem],+ const filteredOptions = filterSelectOptionsBySearch({+ options,+ searchFilter,});+ const selectedValues = options+ .filter((option) => values?.includes(option.value))+ .map((option) => option.value);- useListenClickOutside({- refs: [containerRef],- callback: (event) => {- event.stopImmediatePropagation();- event.preventDefault();- const weAreNotInAnHTMLInput = !(- event.target instanceof HTMLInputElement &&- event.target.tagName === 'INPUT'- );- if (weAreNotInAnHTMLInput && isDefined(onCancel)) {- onCancel();- }- resetSelectedItem();- },- listenerId: 'MultiSelectFieldInput',- });+ const toggleOption = (value: string) => {+ const newValues = selectedValues.includes(value)+ ? selectedValues.filter((selectedValue) => selectedValue !== value)+ : [value, ...selectedValues];- const optionIds = filteredOptionsInDropDown.map((option) => option.value);+ onOptionSelected(newValues);+ };return (- <SelectableList- selectableListInstanceId={selectableListComponentInstanceId}- selectableItemIdArray={optionIds}- focusId={focusId}- shouldPreselectFirstItem={isNonEmptyString(searchFilter)}- >- <LegacyDropdownContent- ref={containerRef}- selectDisabled- widthInPixels={dropdownWidth}- >- <DropdownMenuSearchInput- value={searchFilter}- onChange={(event) =>- setSearchFilter(- turnIntoEmptyStringIfWhitespacesOnly(event.currentTarget.value),- )+ <>+ <Dropdown.Search+ value={searchFilter}+ onValueChange={(value) =>+ setSearchFilter(turnIntoEmptyStringIfWhitespacesOnly(value))+ }+ onKeyDown={(event) => {+ const shouldSubmit =+ event.key === Key.Enter &&+ !isKeyboardEventComposing(event.nativeEvent) &&+ !isNonEmptyString(searchFilter) &&+ isDefined(onEnter);++ if (shouldSubmit) {+ event.preventDefault();+ onEnter();}- autoFocus- />- <DropdownMenuSeparator />- <DropdownMenuItemsContainer isMultiSelect hasMaxHeight>- {filteredOptionsInDropDown.length === 0 ? (- <ListItem disabled>{t`No option found`}</ListItem>- ) : (- filteredOptionsInDropDown.map((option) => {- return (- <SelectableListItem- key={option.value}- itemId={option.value}- onEnter={() => {- onOptionSelected(formatNewSelectedOptions(option.value));- }}- >- <ListItem- key={option.value}- onClick={() =>- onOptionSelected(formatNewSelectedOptions(option.value))- }- focused={selectedItemId === option.value}- role="option"- aria-selected={values?.includes(option.value) || false}- selected={values?.includes(option.value) || false}- indicator="checkbox"- >- <Tag- color={option.color ?? 'transparent'}- startIcon={- isDefined(option.Icon)- ? createElement(option.Icon)- : undefined- }- >- {option.label}- </Tag>- </ListItem>- </SelectableListItem>- );- })- )}- </DropdownMenuItemsContainer>- {onAddSelectOption &&- searchFilter &&- filteredOptionsInDropDown.length === 0 && (- <>- <DropdownMenuSeparator />- <DropdownMenuItemsContainer scrollable={false}>- <AddSelectOptionMenuItem- name={searchFilter}- onAddSelectOption={onAddSelectOption}- />- </DropdownMenuItemsContainer>- </>- )}- </LegacyDropdownContent>- </SelectableList>+ }}+ placeholder={t`Search`}+ aria-label={t`Search`}+ />+ <Dropdown.Separator />+ <Dropdown.Section scrollable>+ {filteredOptions.map((option) => (+ <Dropdown.OptionItem+ key={option.value}+ onSelect={() => toggleOption(option.value)}+ selected={values?.includes(option.value) ?? false}+ closeOnSelect={false}+ indicator="checkbox"+ >+ <Tag+ color={option.color ?? 'transparent'}+ startIcon={+ isDefined(option.Icon) ? createElement(option.Icon) : undefined+ }+ >+ {option.label}+ </Tag>+ </Dropdown.OptionItem>+ ))}+ {!isNonEmptyArray(filteredOptions) && (+ <Dropdown.Empty>{t`No option found`}</Dropdown.Empty>+ )}+ </Dropdown.Section>+ <AddSelectOptionDropdownSection+ searchFilter={searchFilter}+ filteredOptions={filteredOptions}+ onAddSelectOption={onAddSelectOption}+ />+ </>);};diff --git a/packages/twenty-front/src/modules/ui/field/input/components/SelectInput.tsx b/packages/twenty-front/src/modules/ui/field/input/components/SelectInput.tsxdeleted file mode 100644index 8fd9182e5cc..00000000000--- a/packages/twenty-front/src/modules/ui/field/input/components/SelectInput.tsx+++ /dev/null@@ -1,52 +0,0 @@-import { SelectInput as SelectBaseInput } from '@/ui/input/components/SelectInput';-import { SelectableList } from '@/ui/layout/selectable-list/components/SelectableList';-import { type SelectOption } from 'twenty-ui/primitives/input';--type SelectInputProps = {- selectableListComponentInstanceId: string;- selectableItemIdArray: string[];- focusId: string;- onEnter: (itemId: string) => void;- onOptionSelected: (selectedOption: SelectOption) => void;- options: SelectOption[];- onCancel?: () => void;- defaultOption?: SelectOption | undefined;- onFilterChange?: ((filteredOptions: SelectOption[]) => void) | undefined;- onClear?: (() => void) | undefined;- clearLabel?: string;- onAddSelectOption?: (optionName: string) => void;-};--export const SelectInput = ({- selectableListComponentInstanceId,- selectableItemIdArray,- focusId,- onOptionSelected,- options,- onCancel,- defaultOption,- onFilterChange,- onClear,- clearLabel,- onAddSelectOption,-}: SelectInputProps) => {- return (- <SelectableList- selectableListInstanceId={selectableListComponentInstanceId}- selectableItemIdArray={selectableItemIdArray}- focusId={focusId}- >- <SelectBaseInput- onOptionSelected={onOptionSelected}- options={options}- onCancel={onCancel}- defaultOption={defaultOption}- onFilterChange={onFilterChange}- onClear={onClear}- clearLabel={clearLabel}- focusId={focusId}- onAddSelectOption={onAddSelectOption}- />- </SelectableList>- );-};diff --git a/packages/twenty-front/src/modules/ui/field/input/components/__stories__/MultiSelectInput.stories.tsx b/packages/twenty-front/src/modules/ui/field/input/components/__stories__/MultiSelectInput.stories.tsxindex 9f548ff7f02..b32923a2b62 100644--- a/packages/twenty-front/src/modules/ui/field/input/components/__stories__/MultiSelectInput.stories.tsx+++ b/packages/twenty-front/src/modules/ui/field/input/components/__stories__/MultiSelectInput.stories.tsx@@ -1,10 +1,9 @@import { type FieldMultiSelectValue } from '@/object-record/record-field/ui/types/FieldMetadata';-import { getRecordFieldInputInstanceId } from '@/object-record/utils/getRecordFieldInputId';import { MultiSelectInput } from '@/ui/field/input/components/MultiSelectInput';-import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePushFocusItemToFocusStack';-import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';import { type Meta, type StoryObj } from '@storybook/react-vite';-import { useEffect, useState } from 'react';+import { type ComponentProps, useRef, useState } from 'react';+import { Dropdown } from 'twenty-ui/components/navigation';+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';import { expect, fn, userEvent, waitFor, within } from 'storybook/test';import {IconBolt,@@ -19,14 +18,6 @@ import {import { type SelectOption } from 'twenty-ui/primitives/input';import { ComponentDecorator } from 'twenty-ui/testing';-type RenderProps = {- values: FieldMultiSelectValue;- options: SelectOption[];- onOptionSelected: (value: FieldMultiSelectValue) => void;- onCancel?: () => void;- dropdownWidth?: number;-};-const sampleOptions: SelectOption[] = [{value: 'social-media',@@ -76,33 +67,15 @@ const priorityOptions: SelectOption[] = [{ value: 'urgent', label: 'Urgent', color: 'red' },];-const instanceId = getRecordFieldInputInstanceId({- recordId: '123',- fieldName: 'Relation',- prefix: 'multi-select-story',-});-const Render = ({values,options,onOptionSelected,- onCancel,- dropdownWidth,-}: RenderProps) => {+ onAddSelectOption,+}: ComponentProps<typeof MultiSelectInput>) => {const [currentValues, setCurrentValues] =useState<FieldMultiSelectValue>(values);-- const { pushFocusItemToFocusStack } = usePushFocusItemToFocusStack();-- useEffect(() => {- pushFocusItemToFocusStack({- focusId: instanceId,- component: {- type: FocusComponentType.DROPDOWN,- instanceId,- },- });- }, [pushFocusItemToFocusStack]);+ const anchorRef = useRef<HTMLDivElement>(null);const handleOptionSelected = (newValues: FieldMultiSelectValue) => {setCurrentValues(newValues);@@ -111,15 +84,17 @@ const Render = ({return (<div style={{ height: '400px', padding: '20px' }}>- <MultiSelectInput- selectableListComponentInstanceId="multi-select-story"- values={currentValues}- options={options}- focusId={instanceId}- onCancel={onCancel}- onOptionSelected={handleOptionSelected}- dropdownWidth={dropdownWidth}- />+ <div ref={anchorRef} />+ <Dropdown.Root type="picker" multiple open>+ <DropdownContent anchor={anchorRef} aria-label="Options">+ <MultiSelectInput+ values={currentValues}+ options={options}+ onOptionSelected={handleOptionSelected}+ onAddSelectOption={onAddSelectOption}+ />+ </DropdownContent>+ </Dropdown.Root></div>);};@@ -145,10 +120,10 @@ export const Default: Story = {options: sampleOptions,},play: async ({ canvasElement }) => {- const canvas = within(canvasElement);+ const canvas = within(canvasElement.ownerDocument.body);await waitFor(() => {- expect(canvas.getByRole('textbox')).toBeVisible();+ expect(canvas.getByRole('searchbox')).toBeVisible();});for (const option of sampleOptions) {@@ -163,14 +138,14 @@ export const WithPreselectedValues: Story = {options: sampleOptions,},play: async ({ canvasElement }) => {- const canvas = within(canvasElement);+ const canvas = within(canvasElement.ownerDocument.body);await waitFor(() => {- expect(canvas.getByRole('textbox')).toBeVisible();+ expect(canvas.getByRole('searchbox')).toBeVisible();});await waitFor(() => {- const selectedOptions = canvas.getAllByRole('option', { selected: true });+ const selectedOptions = canvas.getAllByRole('button', { pressed: true });expect(selectedOptions).toHaveLength(2);});@@ -187,14 +162,14 @@ export const SingleSelection: Story = {options: sampleOptions,},play: async ({ canvasElement }) => {- const canvas = within(canvasElement);+ const canvas = within(canvasElement.ownerDocument.body);await waitFor(() => {- expect(canvas.getByRole('textbox')).toBeVisible();+ expect(canvas.getByRole('searchbox')).toBeVisible();});await waitFor(() => {- const selectedOptions = canvas.getAllByRole('option', { selected: true });+ const selectedOptions = canvas.getAllByRole('button', { pressed: true });expect(selectedOptions).toHaveLength(1);});@@ -206,8 +181,8 @@ export const SingleSelection: Story = {await userEvent.click(canvas.getByText('Professional Network'));await waitFor(() => {- const selectedOptions = canvas.queryAllByRole('option', {- selected: true,+ const selectedOptions = canvas.queryAllByRole('button', {+ pressed: true,});expect(selectedOptions).toHaveLength(0);@@ -227,10 +202,10 @@ export const EmptyOptions: Story = {options: [],},play: async ({ canvasElement }) => {- const canvas = within(canvasElement);+ const canvas = within(canvasElement.ownerDocument.body);await waitFor(() => {- expect(canvas.getByRole('textbox')).toBeVisible();+ expect(canvas.getByRole('searchbox')).toBeVisible();});expect(canvas.getByText('No option found')).toBeVisible();@@ -261,10 +236,10 @@ export const LongLabels: Story = {],},play: async ({ canvasElement }) => {- const canvas = within(canvasElement);+ const canvas = within(canvasElement.ownerDocument.body);await waitFor(() => {- expect(canvas.getByRole('textbox')).toBeVisible();+ expect(canvas.getByRole('searchbox')).toBeVisible();});expect(@@ -282,9 +257,9 @@ export const SearchFiltering: Story = {options: sampleOptions,},play: async ({ canvasElement }) => {- const canvas = within(canvasElement);+ const canvas = within(canvasElement.ownerDocument.body);- const searchInput = canvas.getByRole('textbox');+ const searchInput = canvas.getByRole('searchbox');await userEvent.type(searchInput, 'marketing');@@ -294,7 +269,11 @@ export const SearchFiltering: Story = {});expect(canvas.queryByText('Social Media')).not.toBeInTheDocument();- expect(canvas.getAllByRole('option')).toHaveLength(2);+ expect(+ within(canvas.getByRole('dialog', { name: 'Options' })).getAllByRole(+ 'button',+ ),+ ).toHaveLength(2);},};@@ -304,9 +283,9 @@ export const NoResultsFound: Story = {options: sampleOptions,},play: async ({ canvasElement }) => {- const canvas = within(canvasElement);+ const canvas = within(canvasElement.ownerDocument.body);- const searchInput = canvas.getByRole('textbox');+ const searchInput = canvas.getByRole('searchbox');await userEvent.type(searchInput, 'xyz123');@@ -322,9 +301,9 @@ export const KeyboardNavigation: Story = {options: priorityOptions,},play: async ({ canvasElement, args }) => {- const canvas = within(canvasElement);+ const canvas = within(canvasElement.ownerDocument.body);- const searchInput = await canvas.findByRole('textbox');+ const searchInput = await canvas.findByRole('searchbox');await userEvent.click(searchInput);@@ -345,3 +324,43 @@ export const KeyboardNavigation: Story = {});},};++export const SearchThenEnter: Story = {+ args: {+ values: [],+ options: priorityOptions,+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement.ownerDocument.body);+ const searchInput = await canvas.findByRole('searchbox');++ await userEvent.type(searchInput, 'high{Enter}');++ await waitFor(() => {+ expect(args.onOptionSelected).toHaveBeenCalledWith(['high']);+ });+ expect(canvas.getByRole('dialog', { name: 'Options' })).toBeVisible();+ expect(+ canvas.getByRole('button', { name: 'High Priority' }),+ ).toHaveAttribute('aria-pressed', 'true');+ },+};++export const AddOption: Story = {+ args: {+ values: [],+ options: priorityOptions,+ onAddSelectOption: fn(),+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement.ownerDocument.body);+ const searchInput = await canvas.findByRole('searchbox');++ await userEvent.type(searchInput, 'New priority{Enter}');+ expect(args.onAddSelectOption).not.toHaveBeenCalled();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Add "New priority" to options' }),+ );+ expect(args.onAddSelectOption).toHaveBeenCalledWith('New priority');+ },+};diff --git a/packages/twenty-front/src/modules/ui/input/components/AddSelectOptionDropdownSection.tsx b/packages/twenty-front/src/modules/ui/input/components/AddSelectOptionDropdownSection.tsxnew file mode 100644index 00000000000..099aa5e5287--- /dev/null+++ b/packages/twenty-front/src/modules/ui/input/components/AddSelectOptionDropdownSection.tsx@@ -0,0 +1,43 @@+import { t } from '@lingui/core/macro';+import { isNonEmptyString } from '@sniptt/guards';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';+import { Dropdown } from 'twenty-ui/components/navigation';+import { IconPlus } from 'twenty-ui/icon';+import { type SelectOption } from 'twenty-ui/primitives/input';++type AddSelectOptionDropdownSectionProps = {+ searchFilter: string;+ filteredOptions: SelectOption[];+ onAddSelectOption?: (optionName: string) => void;+};++export const AddSelectOptionDropdownSection = ({+ searchFilter,+ filteredOptions,+ onAddSelectOption,+}: AddSelectOptionDropdownSectionProps) => {+ const optionName = searchFilter.trim();++ if (+ !isDefined(onAddSelectOption) ||+ !isNonEmptyString(optionName) ||+ isNonEmptyArray(filteredOptions)+ ) {+ return null;+ }++ return (+ <>+ <Dropdown.Separator />+ <Dropdown.Section>+ <Dropdown.ActionItem+ onClick={() => onAddSelectOption(optionName)}+ closeOnClick={false}+ startIcon={<IconPlus />}+ >+ {t`Add "${optionName}" to options`}+ </Dropdown.ActionItem>+ </Dropdown.Section>+ </>+ );+};diff --git a/packages/twenty-front/src/modules/ui/input/components/SelectInput.tsx b/packages/twenty-front/src/modules/ui/input/components/SelectInput.tsxindex 09954734813..e92eab99817 100644--- a/packages/twenty-front/src/modules/ui/input/components/SelectInput.tsx+++ b/packages/twenty-front/src/modules/ui/input/components/SelectInput.tsx@@ -1,181 +1,106 @@-import { AddSelectOptionMenuItem } from '@/settings/data-model/fields/forms/select/components/AddSelectOptionMenuItem';-import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';-import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';-import { DropdownMenuSearchInput } from '@/ui/layout/dropdown/components/DropdownMenuSearchInput';-import { DropdownMenuSeparator } from '@/ui/layout/dropdown/components/DropdownMenuSeparator';-import { SelectableListItem } from '@/ui/layout/selectable-list/components/SelectableListItem';-import { SelectableListComponentInstanceContext } from '@/ui/layout/selectable-list/states/contexts/SelectableListComponentInstanceContext';-import { selectedItemIdComponentState } from '@/ui/layout/selectable-list/states/selectedItemIdComponentState';-import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';-import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';-import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';import { t } from '@lingui/core/macro';-import { createElement, useEffect, useMemo, useRef, useState } from 'react';-import { isDefined } from 'twenty-shared/utils';-import { type TagColor, Tag } from 'twenty-ui/primitives/data-display';+import { isNonEmptyString } from '@sniptt/guards';+import { createElement, useState } from 'react';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';+import { Dropdown } from 'twenty-ui/components/navigation';+import { Tag } from 'twenty-ui/primitives/data-display';import { type SelectOption } from 'twenty-ui/primitives/input';-import { ListItem } from 'twenty-ui/primitives/navigation';+import { AddSelectOptionDropdownSection } from '@/ui/input/components/AddSelectOptionDropdownSection';+import { filterSelectOptionsBySearch } from '@/ui/input/utils/filterSelectOptionsBySearch';import { normalizeSearchText } from '~/utils/normalizeSearchText';-interface SelectInputProps {+type SelectInputProps = {onOptionSelected: (selectedOption: SelectOption) => void;options: SelectOption[];- onCancel?: () => void;- defaultOption?: SelectOption;- onFilterChange?: (filteredOptions: SelectOption[]) => void;+ value?: string | null;onClear?: () => void;clearLabel?: string;- focusId: string;onAddSelectOption?: (optionName: string) => void;-}+};export const SelectInput = ({onOptionSelected,onClear,clearLabel,options,- onCancel,- defaultOption,- onFilterChange,+ value,onAddSelectOption,}: SelectInputProps) => {- const containerRef = useRef<HTMLDivElement>(null);-- const selectableListInstanceId = useAvailableComponentInstanceIdOrThrow(- SelectableListComponentInstanceContext,- );-- const selectedItemId = useAtomComponentStateValue(- selectedItemIdComponentState,- selectableListInstanceId,- );-const [searchFilter, setSearchFilter] = useState('');- const [selectedOption, setSelectedOption] = useState<- SelectOption | undefined- >(defaultOption);-- const optionsToSelect = useMemo(() => {- const searchTerm = normalizeSearchText(searchFilter);- return options.filter((option) => {- return (- option.value !== selectedOption?.value &&- normalizeSearchText(option.label).includes(searchTerm)- );- });- }, [options, searchFilter, selectedOption?.value]);-- const optionsInDropDown = useMemo(- () =>- selectedOption ? [selectedOption, ...optionsToSelect] : optionsToSelect,- [optionsToSelect, selectedOption],+ const isSearching = isNonEmptyString(searchFilter.trim());+ const filteredOptions = filterSelectOptionsBySearch({+ options,+ searchFilter,+ });+ const selectedOption = filteredOptions.find(+ (option) => option.value === value,);+ const optionsInDropdown = isDefined(selectedOption)+ ? [+ selectedOption,+ ...filteredOptions.filter(+ (option) => option.value !== selectedOption.value,+ ),+ ]+ : filteredOptions;+ const emptyLabel = isNonEmptyString(clearLabel) ? t`No ${clearLabel}` : '';+ const shouldShowClearOption =+ isDefined(onClear) &&+ isNonEmptyString(clearLabel) &&+ normalizeSearchText(emptyLabel).includes(normalizeSearchText(searchFilter));- const handleOptionChange = (option: SelectOption) => {- setSelectedOption(option);- onOptionSelected(option);- };-- const handleClearOption = () => {- setSelectedOption(undefined);- onClear?.();- };-- useEffect(() => {- onFilterChange?.(optionsInDropDown);- }, [onFilterChange, optionsInDropDown]);-- useListenClickOutside({- refs: [containerRef],- callback: (event) => {- event.stopImmediatePropagation();- event.preventDefault();- const weAreNotInAnHTMLInput = !(- event.target instanceof HTMLInputElement &&- event.target.tagName === 'INPUT'- );- if (weAreNotInAnHTMLInput && isDefined(onCancel)) {- onCancel();- }- },- listenerId: 'select-input',- });+ const clearOptionItem = shouldShowClearOption ? (+ <Dropdown.OptionItem+ onSelect={onClear}+ selected={!isNonEmptyString(value)}+ closeOnSelect={false}+ >+ <Tag color="transparent" borderStyle="dashed" variant="outline">+ {emptyLabel}+ </Tag>+ </Dropdown.OptionItem>+ ) : null;return (- <LegacyDropdownContent ref={containerRef} selectDisabled>- <DropdownMenuSearchInput+ <>+ <Dropdown.Searchvalue={searchFilter}- onChange={(e) => setSearchFilter(e.target.value)}- autoFocus+ onValueChange={setSearchFilter}+ placeholder={t`Search`}+ aria-label={t`Search`}/>- <DropdownMenuSeparator />- <DropdownMenuItemsContainer hasMaxHeight>- {onClear && clearLabel && (- <SelectableListItem- itemId={t`No ${clearLabel}`}- onEnter={handleClearOption}+ <Dropdown.Separator />+ <Dropdown.Section scrollable>+ {!isSearching && clearOptionItem}+ {optionsInDropdown.map((option) => (+ <Dropdown.OptionItem+ key={option.value}+ onSelect={() => onOptionSelected(option)}+ selected={option.value === value}+ closeOnSelect={false}>- <ListItem- key={t`No ${clearLabel}`}- onClick={handleClearOption}- focused={selectedItemId === t`No ${clearLabel}`}- role="option"- aria-selected={false}- selected={false}- indicator="check"+ <Tag+ color={option.color ?? 'transparent'}+ borderStyle="dashed"+ variant="soft"+ startIcon={+ isDefined(option.Icon) ? createElement(option.Icon) : undefined+ }>- <Tag- color={'transparent'}- borderStyle="dashed"- variant={'outline'}- >{t`No ${clearLabel}`}</Tag>- </ListItem>- </SelectableListItem>+ {option.label}+ </Tag>+ </Dropdown.OptionItem>+ ))}+ {isSearching && clearOptionItem}+ {!shouldShowClearOption && !isNonEmptyArray(optionsInDropdown) && (+ <Dropdown.Empty>{t`No option found`}</Dropdown.Empty>)}- {optionsInDropDown.map((option) => {- return (- <SelectableListItem- key={option.value}- itemId={option.value}- onEnter={() => handleOptionChange(option)}- >- <ListItem- key={option.value}- onClick={() => handleOptionChange(option)}- focused={selectedItemId === option.value}- role="option"- aria-selected={selectedOption?.value === option.value}- selected={selectedOption?.value === option.value}- indicator="check"- >- <Tag- color={(option.color as TagColor) ?? 'transparent'}- borderStyle="dashed"- variant={'soft'}- startIcon={- isDefined(option.Icon)- ? createElement(option.Icon)- : undefined- }- >- {option.label}- </Tag>- </ListItem>- </SelectableListItem>- );- })}- </DropdownMenuItemsContainer>- {onAddSelectOption && searchFilter && optionsToSelect.length === 0 && (- <>- <DropdownMenuSeparator />- <DropdownMenuItemsContainer scrollable={false}>- <AddSelectOptionMenuItem- name={searchFilter}- onAddSelectOption={onAddSelectOption}- />- </DropdownMenuItemsContainer>- </>- )}- </LegacyDropdownContent>+ </Dropdown.Section>+ <AddSelectOptionDropdownSection+ searchFilter={searchFilter}+ filteredOptions={filteredOptions}+ onAddSelectOption={onAddSelectOption}+ />+ </>);};diff --git a/packages/twenty-front/src/modules/ui/input/components/__stories__/SelectInput.stories.tsx b/packages/twenty-front/src/modules/ui/input/components/__stories__/SelectInput.stories.tsxnew file mode 100644index 00000000000..c17df25fb22--- /dev/null+++ b/packages/twenty-front/src/modules/ui/input/components/__stories__/SelectInput.stories.tsx@@ -0,0 +1,106 @@+import { SelectInput } from '@/ui/input/components/SelectInput';+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { type ComponentProps, useRef } from 'react';+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';+import { Dropdown } from 'twenty-ui/components/navigation';+import { type SelectOption } from 'twenty-ui/primitives/input';+import { ComponentDecorator } from 'twenty-ui/testing';++const STATUS_OPTIONS: SelectOption[] = [+ { label: 'To do', value: 'TODO', color: 'blue' },+ { label: 'In progress', value: 'IN_PROGRESS', color: 'purple' },+ { label: 'Done', value: 'DONE', color: 'green' },+];++const SelectInputInDropdown = ({+ options,+ value,+ onOptionSelected,+ onClear,+ clearLabel,+}: ComponentProps<typeof SelectInput>) => {+ const anchorRef = useRef<HTMLDivElement>(null);++ return (+ <div style={{ height: '300px', padding: '20px' }}>+ <div ref={anchorRef} />+ <Dropdown.Root type="picker" open>+ <DropdownContent anchor={anchorRef} aria-label="Status">+ <SelectInput+ options={options}+ value={value}+ onOptionSelected={onOptionSelected}+ onClear={onClear}+ clearLabel={clearLabel}+ />+ </DropdownContent>+ </Dropdown.Root>+ </div>+ );+};++const meta: Meta<typeof SelectInput> = {+ title: 'UI/Input/SelectInput',+ component: SelectInput,+ decorators: [ComponentDecorator],+ args: {+ options: STATUS_OPTIONS,+ value: 'TODO',+ clearLabel: 'Status',+ onOptionSelected: fn(),+ onClear: fn(),+ },+ render: SelectInputInDropdown,+};++export default meta;+type Story = StoryObj<typeof SelectInput>;++export const SearchListsMatchingOptionsBeforeClearOption: Story = {+ play: async ({ canvasElement, args }) => {+ const body = within(canvasElement.ownerDocument.body);+ const popup = await body.findByRole('dialog', { name: 'Status' });+ const picker = within(popup);++ await userEvent.type(+ picker.getByRole('searchbox', { name: 'Search' }),+ 's',+ );++ expect(+ picker.getAllByRole('button').map((option) => option.textContent),+ ).toEqual(['In progress', 'No Status']);++ await userEvent.keyboard('{Enter}');++ await waitFor(() =>+ expect(args.onOptionSelected).toHaveBeenCalledWith(STATUS_OPTIONS[1]),+ );+ expect(args.onClear).not.toHaveBeenCalled();+ },+};++export const EmptyValueSelectsClearOption: Story = {+ args: { value: null },+ play: async ({ canvasElement }) => {+ const body = within(canvasElement.ownerDocument.body);+ const popup = await body.findByRole('dialog', { name: 'Status' });++ expect(+ within(popup).getByRole('button', { name: 'No Status' }),+ ).toHaveAttribute('aria-pressed', 'true');+ },+};++export const UnavailableValueLeavesClearOptionUnselected: Story = {+ args: { value: 'ARCHIVED' },+ play: async ({ canvasElement }) => {+ const body = within(canvasElement.ownerDocument.body);+ const popup = await body.findByRole('dialog', { name: 'Status' });++ expect(+ within(popup).getByRole('button', { name: 'No Status' }),+ ).toHaveAttribute('aria-pressed', 'false');+ },+};diff --git a/packages/twenty-front/src/modules/ui/input/components/__tests__/AutocompleteRoot.test.tsx b/packages/twenty-front/src/modules/ui/input/components/__tests__/AutocompleteRoot.test.tsxindex f7681ecd71c..ec4a66b56ac 100644--- a/packages/twenty-front/src/modules/ui/input/components/__tests__/AutocompleteRoot.test.tsx+++ b/packages/twenty-front/src/modules/ui/input/components/__tests__/AutocompleteRoot.test.tsx@@ -288,11 +288,13 @@ describe('AutocompleteRoot', () => {expect(screen.getByRole('listbox')).toBeVisible();unmount();- expect(- store.get(- isDropdownOpenComponentState.atomFamily({ instanceId: DROPDOWN_ID }),- ),- ).toBe(false);+ await waitFor(() =>+ expect(+ store.get(+ isDropdownOpenComponentState.atomFamily({ instanceId: DROPDOWN_ID }),+ ),+ ).toBe(false),+ );expect(store.get(focusStackState.atom)).toEqual([]);});});diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__tests__/CountrySelect.test.tsx b/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__tests__/CountrySelect.test.tsxindex b3ece8df592..cef0c3fa07a 100644--- a/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__tests__/CountrySelect.test.tsx+++ b/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__tests__/CountrySelect.test.tsx@@ -68,7 +68,7 @@ describe('CountrySelect frontend adapter', () => {unmount();- expect(store.get(dropdownOpenState)).toBe(false);+ await waitFor(() => expect(store.get(dropdownOpenState)).toBe(false));expect(store.get(activeDropdownFocusIdState.atom)).toBeNull();expect(store.get(focusStackState.atom)).toEqual([]);});diff --git a/packages/twenty-front/src/modules/ui/input/utils/filterSelectOptionsBySearch.ts b/packages/twenty-front/src/modules/ui/input/utils/filterSelectOptionsBySearch.tsnew file mode 100644index 00000000000..55579e06ae1--- /dev/null+++ b/packages/twenty-front/src/modules/ui/input/utils/filterSelectOptionsBySearch.ts@@ -0,0 +1,16 @@+import { type SelectOption } from 'twenty-ui/primitives/input';+import { normalizeSearchText } from '~/utils/normalizeSearchText';++export const filterSelectOptionsBySearch = ({+ options,+ searchFilter,+}: {+ options: SelectOption[];+ searchFilter: string;+}) => {+ const searchTerm = normalizeSearchText(searchFilter);++ return options.filter((option) =>+ normalizeSearchText(option.label).includes(searchTerm),+ );+};diff --git a/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownCleanupEffect.tsx b/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownCleanupEffect.tsxindex d8f4828ac33..db0f9ff84dd 100644--- a/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownCleanupEffect.tsx+++ b/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownCleanupEffect.tsx@@ -1,6 +1,8 @@+import { useStore } from 'jotai';import { useEffect } from 'react';import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';+import { mountedDropdownRootCountComponentState } from '@/ui/layout/dropdown/states/internal/mountedDropdownRootCountComponentState';type DropdownCleanupEffectProps = {dropdownId: string;@@ -10,8 +12,26 @@ export const DropdownCleanupEffect = ({dropdownId,}: DropdownCleanupEffectProps) => {const { closeDropdown } = useCloseDropdown();+ const store = useStore();- useEffect(() => () => closeDropdown(dropdownId), [closeDropdown, dropdownId]);+ useEffect(() => {+ const mountedDropdownRootCountAtom =+ mountedDropdownRootCountComponentState.atomFamily({+ instanceId: dropdownId,+ });++ store.set(mountedDropdownRootCountAtom, (count) => count + 1);++ return () => {+ store.set(mountedDropdownRootCountAtom, (count) => count - 1);++ queueMicrotask(() => {+ if (store.get(mountedDropdownRootCountAtom) === 0) {+ closeDropdown(dropdownId);+ }+ });+ };+ }, [closeDropdown, dropdownId, store]);return null;};diff --git a/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownContent.tsx b/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownContent.tsxindex c263f517195..b6779b69f02 100644--- a/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownContent.tsx+++ b/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownContent.tsx@@ -14,6 +14,7 @@ type DropdownContentProps = Pick<| 'anchor'| 'collisionPadding'| 'width'+ | 'onKeyDown'| 'initialFocus'| 'finalFocus'| 'className'@@ -30,6 +31,7 @@ export const DropdownContent = ({anchor,collisionPadding,width,+ onKeyDown,initialFocus,finalFocus,className,@@ -49,6 +51,7 @@ export const DropdownContent = ({anchor={anchor}collisionPadding={collisionPadding}width={width}+ onKeyDown={onKeyDown}initialFocus={initialFocus}finalFocus={finalFocus}className={className}diff --git a/packages/twenty-front/src/modules/ui/layout/dropdown/components/__stories__/DropdownRoot.stories.tsx b/packages/twenty-front/src/modules/ui/layout/dropdown/components/__stories__/DropdownRoot.stories.tsxindex 10a6deddcd4..b2e57c8d8f5 100644--- a/packages/twenty-front/src/modules/ui/layout/dropdown/components/__stories__/DropdownRoot.stories.tsx+++ b/packages/twenty-front/src/modules/ui/layout/dropdown/components/__stories__/DropdownRoot.stories.tsx@@ -4,7 +4,7 @@ import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropimport { useGlobalHotkeys } from '@/ui/utilities/hotkey/hooks/useGlobalHotkeys';import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';import { type Meta, type StoryObj } from '@storybook/react-vite';-import { useRef } from 'react';+import { useRef, useState } from 'react';import { expect, fn, userEvent, waitFor, within } from 'storybook/test';import { Dropdown } from 'twenty-ui/components/navigation';import { Button } from 'twenty-ui/primitives/input';@@ -38,6 +38,27 @@ const GroupRenamePanel = () => {);};+const ReplaceableOwnerDropdown = () => {+ const [ownerKey, setOwnerKey] = useState('first-owner');++ return (+ <>+ <DropdownRoot+ key={ownerKey}+ dropdownId="replaced-owner-dropdown"+ type="menu"+ onInteractOutside={(event) => event.preventDefault()}+ >+ <Dropdown.Trigger render={<Button>Actions</Button>} />+ <Dropdown.Content>+ <Dropdown.ActionItem>Archive</Dropdown.ActionItem>+ </Dropdown.Content>+ </DropdownRoot>+ <Button onClick={() => setOwnerKey('second-owner')}>Replace owner</Button>+ </>+ );+};+const meta: Meta<typeof DropdownRoot> = {title: 'UI/Layout/Dropdown/DropdownRoot',component: DropdownRoot,@@ -142,3 +163,33 @@ export const OpenedBeforeMount: Story = {);},};++export const ReplacedOwnerKeepsItOpen: Story = {+ render: () => <ReplaceableOwnerDropdown />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const isReplacedOwnerDropdownOpen = () =>+ jotaiStore.get(+ isDropdownOpenComponentState.atomFamily({+ instanceId: 'replaced-owner-dropdown',+ }),+ );++ await userEvent.click(canvas.getByRole('button', { name: 'Actions' }));+ await body.findByRole('menu', { name: 'Actions' });++ await userEvent.click(+ canvas.getByRole('button', { name: 'Replace owner' }),+ );++ expect(isReplacedOwnerDropdownOpen()).toBe(true);+ await waitFor(() =>+ expect(body.getByRole('menu', { name: 'Actions' })).toBeVisible(),+ );++ await userEvent.keyboard('{Escape}');++ await waitFor(() => expect(isReplacedOwnerDropdownOpen()).toBe(false));+ },+};diff --git a/packages/twenty-front/src/modules/ui/layout/dropdown/components/__tests__/DropdownRoot.test.tsx b/packages/twenty-front/src/modules/ui/layout/dropdown/components/__tests__/DropdownRoot.test.tsxindex cac15150169..e6a100d2375 100644--- a/packages/twenty-front/src/modules/ui/layout/dropdown/components/__tests__/DropdownRoot.test.tsx+++ b/packages/twenty-front/src/modules/ui/layout/dropdown/components/__tests__/DropdownRoot.test.tsx@@ -19,7 +19,7 @@ import {} from '@testing-library/react';import userEvent from '@testing-library/user-event';import { createStore, Provider as JotaiProvider } from 'jotai';-import { useRef } from 'react';+import { StrictMode, useRef } from 'react';import { Dropdown } from 'twenty-ui/components/navigation';const BACKGROUND_FOCUS_ITEM: FocusStackItem = {@@ -532,7 +532,7 @@ describe('DropdownRoot', () => {expect(store.get(focusStackState.atom)).toHaveLength(2);});- it('keeps a dropdown opened before its root mounts open', async () => {+ it('keeps a dropdown opened before its root mounts open in StrictMode', async () => {const user = userEvent.setup();const store = createTestStore();const { result } = renderHook(() => useOpenDropdown(), {@@ -549,7 +549,9 @@ describe('DropdownRoot', () => {render(<JotaiProvider store={store}>- <GroupRenamePanel />+ <StrictMode>+ <GroupRenamePanel />+ </StrictMode></JotaiProvider>,);diff --git a/packages/twenty-front/src/modules/ui/layout/dropdown/states/internal/mountedDropdownRootCountComponentState.ts b/packages/twenty-front/src/modules/ui/layout/dropdown/states/internal/mountedDropdownRootCountComponentState.tsnew file mode 100644index 00000000000..dbd51f916f2--- /dev/null+++ b/packages/twenty-front/src/modules/ui/layout/dropdown/states/internal/mountedDropdownRootCountComponentState.ts@@ -0,0 +1,9 @@+import { DropdownComponentInstanceContext } from '@/ui/layout/dropdown/contexts/DropdownComponentInstanceContext';+import { createAtomComponentState } from '@/ui/utilities/state/jotai/utils/createAtomComponentState';++export const mountedDropdownRootCountComponentState =+ createAtomComponentState<number>({+ key: 'mountedDropdownRootCountComponentState',+ componentInstanceContext: DropdownComponentInstanceContext,+ defaultValue: 0,+ });diff --git a/packages/twenty-front/src/modules/ui/layout/dropdown/utils/preventDropdownDismissOnInputElement.ts b/packages/twenty-front/src/modules/ui/layout/dropdown/utils/preventDropdownDismissOnInputElement.tsnew file mode 100644index 00000000000..558ddd13cad--- /dev/null+++ b/packages/twenty-front/src/modules/ui/layout/dropdown/utils/preventDropdownDismissOnInputElement.ts@@ -0,0 +1,9 @@+import { type DropdownDismissEvent } from 'twenty-ui/components/navigation';++export const preventDropdownDismissOnInputElement = (+ event: DropdownDismissEvent,+) => {+ if (event.target instanceof HTMLInputElement) {+ event.preventDefault();+ }+};diff --git a/packages/twenty-front/src/modules/ui/layout/overlay/components/OverlayMenuList.tsx b/packages/twenty-front/src/modules/ui/layout/overlay/components/OverlayMenuList.tsxindex 3b22de446b5..77b4cb402f0 100644--- a/packages/twenty-front/src/modules/ui/layout/overlay/components/OverlayMenuList.tsx+++ b/packages/twenty-front/src/modules/ui/layout/overlay/components/OverlayMenuList.tsx@@ -3,6 +3,7 @@ import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/Geneimport { styled } from '@linaria/react';import { type ReactNode, type Ref } from 'react';import { themeCssVariables } from 'twenty-ui/theme';+import { isDefined } from 'twenty-shared/utils';const StyledContainer = styled.div<{ widthInPixels: number }>`display: flex;@@ -36,19 +37,27 @@ const StyledItems = styled.div``;type OverlayMenuListProps = {- children: ReactNode;+ children?: ReactNode;+ header?: ReactNode;+ footer?: ReactNode;width?: number;ref?: Ref<HTMLDivElement>;};export const OverlayMenuList = ({children,+ header,+ footer,width = GenericDropdownContentWidth.Medium,ref,}: OverlayMenuListProps) => (<StyledContainer ref={ref} widthInPixels={width}>- <StyledScrollableContainer>- <StyledItems>{children}</StyledItems>- </StyledScrollableContainer>+ {header}+ {isDefined(children) && (+ <StyledScrollableContainer>+ <StyledItems>{children}</StyledItems>+ </StyledScrollableContainer>+ )}+ {footer}</StyledContainer>);diff --git a/packages/twenty-front/src/modules/ui/layout/overlay/components/OverlayMenuListSearchRow.tsx b/packages/twenty-front/src/modules/ui/layout/overlay/components/OverlayMenuListSearchRow.tsxnew file mode 100644index 00000000000..911979ca065--- /dev/null+++ b/packages/twenty-front/src/modules/ui/layout/overlay/components/OverlayMenuListSearchRow.tsx@@ -0,0 +1,59 @@+import { t } from '@lingui/core/macro';+import { styled } from '@linaria/react';+import { type InputHTMLAttributes } from 'react';+import { themeCssVariables } from 'twenty-ui/theme';++const StyledSearchRow = styled.div`+ align-items: center;+ box-sizing: content-box;+ display: flex;+ min-height: 20px;+ padding: ${themeCssVariables.spacing[2]} 0;+ width: 100%;+`;++const StyledInput = styled.input`+ background-color: transparent;+ border: none;+ color: ${themeCssVariables.font.color.primary};+ font-family: ${themeCssVariables.font.family};+ font-size: inherit;+ font-weight: inherit;+ outline: none;+ padding: ${themeCssVariables.spacing[0]} ${themeCssVariables.spacing[2]};+ width: 100%;++ &::placeholder {+ color: ${themeCssVariables.font.color.light};+ font-family: ${themeCssVariables.font.family};+ font-weight: ${themeCssVariables.font.weight.medium};+ }+`;++type OverlayMenuListSearchRowProps = Pick<+ InputHTMLAttributes<HTMLInputElement>,+ 'value' | 'onChange' | 'placeholder'+>;++const focusSearchInput = (input: HTMLInputElement | null) => {+ input?.focus({ preventScroll: true });+};++export const OverlayMenuListSearchRow = ({+ value,+ onChange,+ placeholder = t`Search`,+}: OverlayMenuListSearchRowProps) => {+ return (+ <StyledSearchRow>+ <StyledInput+ ref={focusSearchInput}+ autoComplete="off"+ value={value}+ onChange={onChange}+ placeholder={placeholder}+ aria-label={placeholder}+ />+ </StyledSearchRow>+ );+};diff --git a/packages/twenty-front/src/modules/ui/layout/overlay/components/OverlayMenuListSeparator.tsx b/packages/twenty-front/src/modules/ui/layout/overlay/components/OverlayMenuListSeparator.tsxnew file mode 100644index 00000000000..1eabe11f1ae--- /dev/null+++ b/packages/twenty-front/src/modules/ui/layout/overlay/components/OverlayMenuListSeparator.tsx@@ -0,0 +1,12 @@+import { styled } from '@linaria/react';+import { themeCssVariables } from 'twenty-ui/theme';++const StyledSeparator = styled.div`+ background-color: ${themeCssVariables.border.color.light};+ min-height: 1px;+ width: 100%;+`;++export const OverlayMenuListSeparator = () => (+ <StyledSeparator role="separator" />+);diff --git a/packages/twenty-front/src/modules/ui/layout/overlay/utils/getFloatingReferenceScale.ts b/packages/twenty-front/src/modules/ui/layout/overlay/utils/getFloatingReferenceScale.tsindex e23054f1093..2f935e28d4f 100644--- a/packages/twenty-front/src/modules/ui/layout/overlay/utils/getFloatingReferenceScale.ts+++ b/packages/twenty-front/src/modules/ui/layout/overlay/utils/getFloatingReferenceScale.ts@@ -3,7 +3,11 @@ import { type MiddlewareState } from '@floating-ui/react';export const getFloatingReferenceScale = ({rects,elements,-}: Pick<MiddlewareState, 'rects' | 'elements'>) =>- elements.reference instanceof HTMLElement+}: {+ rects: { reference: Pick<MiddlewareState['rects']['reference'], 'width'> };+ elements: { reference: MiddlewareState['elements']['reference'] | null };+}) =>+ elements.reference instanceof HTMLElement &&+ elements.reference.offsetWidth > 0? rects.reference.width / elements.reference.offsetWidth: 1;diff --git a/packages/twenty-front/src/modules/ui/navigation/menu-item/components/MenuItemWithOptionDropdown.tsx b/packages/twenty-front/src/modules/ui/navigation/menu-item/components/MenuItemWithOptionDropdown.tsxindex 96b79cc5e96..1fc1240200b 100644--- a/packages/twenty-front/src/modules/ui/navigation/menu-item/components/MenuItemWithOptionDropdown.tsx+++ b/packages/twenty-front/src/modules/ui/navigation/menu-item/components/MenuItemWithOptionDropdown.tsx@@ -1,14 +1,17 @@-import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';+import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';+import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';+import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';import { t } from '@lingui/core/macro';import { type MouseEvent } from 'react';import { isDefined } from 'twenty-shared/utils';import { LightIconButton } from 'twenty-ui/components/input';+import { Dropdown } from 'twenty-ui/components/navigation';import { IconDotsVertical } from 'twenty-ui/icon';import { ListItem } from 'twenty-ui/primitives/navigation';import { useTheme } from 'twenty-ui/theme';import { type MenuItemWithOptionDropdownProps } from './types/MenuItemWithOptionDropdownProps';-// TODO: refactor thisexport const MenuItemWithOptionDropdown = ({accent = 'default',className,@@ -23,16 +26,24 @@ export const MenuItemWithOptionDropdown = ({testId,text,hasSubMenu = false,- dropdownPlacement = 'bottom-end',+ dropdownSide = 'bottom',+ dropdownAlign = 'end',selected = false,}: MenuItemWithOptionDropdownProps) => {const theme = useTheme();+ const isDropdownOpen = useAtomComponentStateValue(+ isDropdownOpenComponentState,+ dropdownId,+ );const handleMenuItemClick = (event: MouseEvent<HTMLDivElement>) => {- if (!onClick) return;+ if (!isDefined(onClick)) {+ return;+ }+event.preventDefault();event.stopPropagation();- onClick?.(event);+ onClick(event);};return (@@ -44,25 +55,29 @@ export const MenuItemWithOptionDropdown = ({onMouseEnter={onMouseEnter}onMouseLeave={onMouseLeave}focused={selected}- startIcon={LeftIcon && <LeftIcon size={theme.icon.size.md} />}+ startIcon={isDefined(LeftIcon) && <LeftIcon size={theme.icon.size.md} />}hasSubmenu={hasSubMenu}- actionsVisibility={isIconDisplayedOnHoverOnly ? 'hover' : 'always'}+ actionsVisibility={+ isIconDisplayedOnHoverOnly && !isDropdownOpen ? 'hover' : 'always'+ }actions={<div className="hoverable-buttons">- <Dropdown- clickableComponent={- <LightIconButton- size="sm"- emphasis="subtle"- aria-label={t`More options`}- >- {isDefined(RightIcon) ? <RightIcon /> : <IconDotsVertical />}- </LightIconButton>- }- dropdownPlacement={dropdownPlacement}- dropdownComponents={dropdownContent}- dropdownId={dropdownId}- />+ <DropdownRoot dropdownId={dropdownId} type="menu">+ <Dropdown.Trigger+ render={+ <LightIconButton+ size="sm"+ emphasis="subtle"+ aria-label={t`More options`}+ >+ {isDefined(RightIcon) ? <RightIcon /> : <IconDotsVertical />}+ </LightIconButton>+ }+ />+ <DropdownContent side={dropdownSide} align={dropdownAlign}>+ {dropdownContent}+ </DropdownContent>+ </DropdownRoot></div>}>diff --git a/packages/twenty-front/src/modules/ui/navigation/menu-item/components/types/MenuItemWithOptionDropdownProps.ts b/packages/twenty-front/src/modules/ui/navigation/menu-item/components/types/MenuItemWithOptionDropdownProps.tsindex 0c905e0a949..0b17cfae116 100644--- a/packages/twenty-front/src/modules/ui/navigation/menu-item/components/types/MenuItemWithOptionDropdownProps.ts+++ b/packages/twenty-front/src/modules/ui/navigation/menu-item/components/types/MenuItemWithOptionDropdownProps.ts@@ -1,6 +1,8 @@-import { type Placement } from '@floating-ui/react';-import { type MouseEvent, type ReactNode } from 'react';-import { type MenuItemAccent } from 'twenty-ui/components/navigation';+import { type ComponentProps, type MouseEvent, type ReactNode } from 'react';+import {+ type Dropdown,+ type MenuItemAccent,+} from 'twenty-ui/components/navigation';import { type IconComponent } from 'twenty-ui/icon';export type MenuItemWithOptionDropdownProps = {@@ -18,6 +20,7 @@ export type MenuItemWithOptionDropdownProps = {testId?: string;text: ReactNode;hasSubMenu?: boolean;- dropdownPlacement?: Placement;+ dropdownSide?: ComponentProps<typeof Dropdown.Content>['side'];+ dropdownAlign?: ComponentProps<typeof Dropdown.Content>['align'];selected?: boolean;};diff --git a/packages/twenty-front/src/modules/views/view-picker/components/ViewPickerOptionDropdown.tsx b/packages/twenty-front/src/modules/views/view-picker/components/ViewPickerOptionDropdown.tsxindex 37c91a801c0..fec9cc04a8c 100644--- a/packages/twenty-front/src/modules/views/view-picker/components/ViewPickerOptionDropdown.tsx+++ b/packages/twenty-front/src/modules/views/view-picker/components/ViewPickerOptionDropdown.tsx@@ -1,11 +1,8 @@-import { ListItem } from 'twenty-ui/primitives/navigation';+import { Dropdown } from 'twenty-ui/components/navigation';import { useCreateManyNavigationMenuItems } from '@/navigation-menu-item/common/hooks/useCreateManyNavigationMenuItems';import { useDeleteManyNavigationMenuItems } from '@/navigation-menu-item/common/hooks/useDeleteManyNavigationMenuItems';import { useNavigationMenuItemsData } from '@/navigation-menu-item/display/hooks/useNavigationMenuItemsData';import { useHasPermissionFlag } from '@/settings/roles/hooks/useHasPermissionFlag';-import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';-import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';-import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';import { MenuItemWithOptionDropdown } from '@/ui/navigation/menu-item/components/MenuItemWithOptionDropdown';import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';import { type View } from '@/views/types/View';@@ -51,7 +48,6 @@ export const ViewPickerOptionDropdown = ({const dropdownId = `view-picker-options-${view.id}`;const { t } = useLingui();- const { closeDropdown } = useCloseDropdown();const { getIcon } = useIcons();const { destroyViewFromCurrentState } = useDestroyViewFromCurrentState();const setViewPickerReferenceViewId = useSetAtomComponentState(@@ -79,33 +75,32 @@ export const ViewPickerOptionDropdown = ({const handleDelete = () => {setViewPickerReferenceViewId(view.id);destroyViewFromCurrentState();- closeDropdown(dropdownId);};const handleToggleFavorite = () => {- if (!isFavorite) {- const relevantItems = navigationMenuItems.filter(- (item) => !isDefined(item.folderId) && isDefined(item.userWorkspaceId),- );-- const maxPosition = Math.max(- ...relevantItems.map((item) => item.position),- 0,- );-- createManyNavigationMenuItems([- {- id: uuidv4(),- type: NavigationMenuItemType.VIEW,- viewId: view.id,- userWorkspaceId: currentUserWorkspaceId,- position: maxPosition + 1,- },- ]);- } else {+ if (isFavorite) {deleteManyNavigationMenuItems([currentNavigationMenuItem.id]);+ return;}- closeDropdown(dropdownId);++ const relevantItems = navigationMenuItems.filter(+ (item) => !isDefined(item.folderId) && isDefined(item.userWorkspaceId),+ );++ const maxPosition = Math.max(+ ...relevantItems.map((item) => item.position),+ 0,+ );++ createManyNavigationMenuItems([+ {+ id: uuidv4(),+ type: NavigationMenuItemType.VIEW,+ viewId: view.id,+ userWorkspaceId: currentUserWorkspaceId,+ position: maxPosition + 1,+ },+ ]);};const getVisibilityIcon = () => {@@ -126,38 +121,35 @@ export const ViewPickerOptionDropdown = ({onClick={() => handleViewSelect(view.id)}isIconDisplayedOnHoverOnly={!shouldShowIconAlways}RightIcon={getVisibilityIcon()}- dropdownPlacement="bottom-start"- dropdownId={`view-picker-options-${view.id}`}+ dropdownAlign="start"+ dropdownId={dropdownId}selected={isCurrentView}dropdownContent={- <LegacyDropdownContent>- <DropdownMenuItemsContainer>- <ListItem- startIcon={isFavorite ? <IconHeartOff /> : <IconHeart />}- onClick={handleToggleFavorite}- >- {isFavorite ? t`Remove Favorite` : t`Add to Favorite`}- </ListItem>- {!isIndexView && canEditView && (- <>- <ListItem- startIcon={<IconPencil />}- onClick={(event) => {- onEdit(event, view.id);- closeDropdown(dropdownId);- }}- >{t`Edit`}</ListItem>- {!isLastView && (- <ListItem- startIcon={<IconTrash />}- onClick={handleDelete}- color="danger"- >{t`Delete`}</ListItem>- )}- </>- )}- </DropdownMenuItemsContainer>- </LegacyDropdownContent>+ <Dropdown.Section>+ <Dropdown.ActionItem+ startIcon={isFavorite ? <IconHeartOff /> : <IconHeart />}+ onClick={handleToggleFavorite}+ >+ {isFavorite ? t`Remove Favorite` : t`Add to Favorite`}+ </Dropdown.ActionItem>+ {!isIndexView && canEditView && (+ <>+ <Dropdown.ActionItem+ startIcon={<IconPencil />}+ onClick={(event) => {+ onEdit(event, view.id);+ }}+ >{t`Edit`}</Dropdown.ActionItem>+ {!isLastView && (+ <Dropdown.ActionItem+ startIcon={<IconTrash />}+ onClick={handleDelete}+ color="danger"+ >{t`Delete`}</Dropdown.ActionItem>+ )}+ </>+ )}+ </Dropdown.Section>}/></>diff --git a/packages/twenty-front/src/testing/decorators/FieldInputAnchorDecorator.tsx b/packages/twenty-front/src/testing/decorators/FieldInputAnchorDecorator.tsxnew file mode 100644index 00000000000..3101112bb6c--- /dev/null+++ b/packages/twenty-front/src/testing/decorators/FieldInputAnchorDecorator.tsx@@ -0,0 +1,24 @@+import { FieldInputAnchorContextProvider } from '@/object-record/record-field/ui/contexts/FieldInputAnchorContext';+import { getFieldInputAnchorPosition } from '@/object-record/record-field/ui/utils/getFieldInputAnchorPosition';+import { type Decorator } from '@storybook/react-vite';+import { useRef } from 'react';++export const FieldInputAnchorDecorator: Decorator = (Story) => {+ const anchorRef = useRef<HTMLDivElement>(null);++ return (+ <FieldInputAnchorContextProvider+ value={getFieldInputAnchorPosition({+ anchorRef,+ sideOffset: -33,+ alignOffset: -3,+ collisionPadding: 0,+ })}+ >+ <div style={{ height: 400, padding: 40 }}>+ <div ref={anchorRef} style={{ height: 32, width: 200 }} />+ <Story />+ </div>+ </FieldInputAnchorContextProvider>+ );+};diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.jsonindex 852d3989bcc..7d506e8e650 100644--- a/packages/twenty-ui/generated/components.docs.json+++ b/packages/twenty-ui/generated/components.docs.json@@ -6453,7 +6453,7 @@},{"name": "alignOffset",- "type": "number",+ "type": "number | OffsetFunction","required": false,"defaultValue": null,"description": "Offset in pixels along the alignment axis."@@ -6530,7 +6530,7 @@},{"name": "sideOffset",- "type": "number",+ "type": "number | OffsetFunction","required": false,"defaultValue": "8","description": "Distance in pixels between the anchor and the popup."@@ -8167,7 +8167,7 @@},{"name": "alignOffset",- "type": "number",+ "type": "number | OffsetFunction","required": false,"defaultValue": null,"description": "Offset in pixels along the alignment axis."@@ -8237,7 +8237,7 @@},{"name": "sideOffset",- "type": "number",+ "type": "number | OffsetFunction","required": false,"defaultValue": "0","description": "Distance in pixels between the anchor and the popup."diff --git a/packages/twenty-ui/src/primitives/surfaces/Popover/types/PopoverPopupProps.ts b/packages/twenty-ui/src/primitives/surfaces/Popover/types/PopoverPopupProps.tsindex e2e4541eebf..67d59058298 100644--- a/packages/twenty-ui/src/primitives/surfaces/Popover/types/PopoverPopupProps.ts+++ b/packages/twenty-ui/src/primitives/surfaces/Popover/types/PopoverPopupProps.ts@@ -9,9 +9,9 @@ export type PopoverPopupProps = PopoverPrimitive.Popup.Props & {/** Alignment of the popup along the anchor. */align?: PopoverAlign;/** Distance in pixels between the anchor and the popup. */- sideOffset?: number;+ sideOffset?: PopoverPrimitive.Positioner.Props['sideOffset'];/** Offset in pixels along the alignment axis. */- alignOffset?: number;+ alignOffset?: PopoverPrimitive.Positioner.Props['alignOffset'];/** Shows an arrow pointing at the anchor. */arrow?: boolean;/** Element or position the popup is anchored to. Defaults to the trigger. */