The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Migrate address and email autocompletes (#27065)
Raphaël Bosi53996732b408
diff --git a/packages/twenty-docs/snippets/ui/generated/input/autocomplete.mdx b/packages/twenty-docs/snippets/ui/generated/input/autocomplete.mdxnew file mode 100644index 00000000000..bdf9b58d028--- /dev/null+++ b/packages/twenty-docs/snippets/ui/generated/input/autocomplete.mdx@@ -0,0 +1,415 @@+{/*+ * _____ _+ *|_ _|_ _____ _ __ | |_ _ _+ * | | \ \ /\ / / _ \ '_ \| __| | | | Auto-generated file+ * | | \ V V / __/ | | | |_| |_| | DO NOT EDIT - changes will be overwritten+ * |_| \_/\_/ \___|_| |_|\__|\__, | Generated by: npx nx generate:ui twenty-docs+ * |___/+ *+ * This file is generated from the documentation data in packages/twenty-ui/generated.+ * To update it, edit the component prop types or design tokens in twenty-ui and run:+ * npx nx generate:ui twenty-docs+ */}++### Autocomplete.Root++<ParamField body="Root.actionsRef" type="RefObject<AutocompleteRootActions | null>">+ A ref to imperative actions.+ - `unmount`: Manually unmounts the autocomplete.+ Call this after any externally controlled closing animation finishes.+</ParamField>++<ParamField body="Root.autoHighlight" type="boolean | "always"" default="false">+ Whether the first matching item is highlighted automatically.+ - `true`: highlight after the user types and keep the highlight while the query changes.+ - `'always'`: always highlight the first item.+</ParamField>++<ParamField body="Root.defaultOpen" type="boolean" default="false">+ Whether the popup is initially open.++ To render a controlled popup, use the `open` prop instead.+</ParamField>++<ParamField body="Root.defaultValue" type="string | number | readonly string[]">+ The uncontrolled input value of the autocomplete when it's initially rendered.++ To render a controlled autocomplete, use the `value` prop instead.+</ParamField>++<ParamField body="Root.disabled" type="boolean" default="false">+ Whether the component should ignore user interaction.+</ParamField>++<ParamField body="Root.filter" type="((item: TItem, query: string, itemToString?: ((item: TItem) => string) | undefined) => boolean) | null">+ Filter function used to match items against the input query.+</ParamField>++<ParamField body="Root.filteredItems" type="readonly TItem[] | readonly Group<TItem>[]">+ Filtered items to display in the list.+ When provided, the list uses these items instead of filtering the `items` prop internally.+ When `items` is also provided, this array must preserve its flat or grouped structure.+ Nullish entries are not supported, as in `items`.+ Use when you want to control filtering logic externally with the `useFilter()` hook.+</ParamField>++<ParamField body="Root.form" type="string">+ Identifies the form that owns the internal input.+ Useful when the autocomplete is rendered outside the form.+</ParamField>++<ParamField body="Root.grid" type="boolean" default="false">+ Whether list items are presented in a grid layout.+ When enabled, arrow keys navigate across rows and columns inferred from DOM rows.+</ParamField>++<ParamField body="Root.highlightItemOnHover" type="boolean" default="true">+ Whether moving the pointer over items should highlight them.+ Disabling this prop allows CSS `:hover` to be differentiated from the `:focus` (`data-highlighted`) state.+</ParamField>++<ParamField body="Root.id" type="string">+ The id of the component.+</ParamField>++<ParamField body="Root.inline" type="boolean" default="false">+ Whether the list is rendered inline without using the component's own popup.++ Specify `open` unconditionally in conjunction with this prop so the list is considered+ visible: `<Autocomplete.Root inline open>`+</ParamField>++<ParamField body="Root.inputRef" type="Ref<HTMLInputElement>">+ A ref to the hidden input element.+</ParamField>++<ParamField body="Root.items" type="readonly TItem[]">+ Items to display in the list. Nullish entries are not supported.+</ParamField>++<ParamField body="Root.itemToStringValue" type="((itemValue: TItem) => string)">+ When the item values are objects (`<Autocomplete.Item value={object}>`), this function converts the object value to a string representation for both display in the input and form submission.+ If the shape of the object is `{ value, label }`, the label will be used automatically without needing to specify this prop.+</ParamField>++<ParamField body="Root.keepHighlight" type="boolean" default="false">+ Whether the highlighted item should be preserved when the pointer leaves the list.+</ParamField>++<ParamField body="Root.limit" type="number" default="-1">+ The maximum number of items to display in the list.+</ParamField>++<ParamField body="Root.locale" type="LocalesArgument">+ The locale to use for string comparison.+ Defaults to the user's runtime locale.+</ParamField>++<ParamField body="Root.loopFocus" type="boolean" default="true">+ Whether to loop keyboard focus back to the input when the end of the list is reached while using the arrow keys. The first item can then be reached by pressing <kbd>ArrowDown</kbd> again from the input, or the last item can be reached by pressing <kbd>ArrowUp</kbd> from the input.+ The input is always included in the focus loop per [ARIA Authoring Practices](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/).+ When disabled, focus does not move when on the last element and the user presses <kbd>ArrowDown</kbd>, or when on the first element and the user presses <kbd>ArrowUp</kbd>.+</ParamField>++<ParamField body="Root.modal" type="boolean" default="false">+ Determines if the popup enters a modal state when open.+ - `true`: user interaction is limited to the popup: document page scroll is locked and pointer interactions on outside elements are disabled.+ - `false`: user interaction with the rest of the document is allowed.++ On touch devices, a `true` modal blocks outside taps but leaves the page scrollable unless the popup spans nearly the full viewport width, matching native iOS behavior.+</ParamField>++<ParamField body="Root.mode" type=""both" | "inline" | "list" | "none"" default="list">+ Controls how the autocomplete behaves with respect to list filtering and inline autocompletion.+ - `list` (default): items are dynamically filtered based on the input value. The input value does not change based on the active item.+ - `both`: items are dynamically filtered based on the input value, which will temporarily change based on the active item (inline autocompletion).+ - `inline`: items are static (not filtered), and the input value will temporarily change based on the active item (inline autocompletion).+ - `none`: items are static (not filtered), and the input value will not change based on the active item.+</ParamField>++<ParamField body="Root.name" type="string">+ Identifies the field when a form is submitted.+</ParamField>++<ParamField body="Root.onItemHighlighted" type="((highlightedValue: TItem | undefined, eventDetails: HighlightEventDetails) => void)">+ Callback fired when an item is highlighted or unhighlighted.+ Receives the highlighted item value (or `undefined` if no item is highlighted) and event details with a `reason` property describing why the highlight changed.+ The `reason` can be:+ - `'keyboard'`: the highlight changed due to keyboard navigation.+ - `'pointer'`: the highlight changed due to pointer hovering.+ - `'none'`: the highlight changed programmatically.+</ParamField>++<ParamField body="Root.onOpenChange" type="((open: boolean, eventDetails: AutocompleteRootChangeEventDetails) => void)">+ Event handler called when the popup is opened or closed.+</ParamField>++<ParamField body="Root.onOpenChangeComplete" type="((open: boolean) => void)">+ Event handler called after any animations complete when the popup is opened or closed.+</ParamField>++<ParamField body="Root.onValueChange" type="((value: string, eventDetails: AutocompleteRootChangeEventDetails) => void)">+ Event handler called when the input value of the autocomplete changes.+</ParamField>++<ParamField body="Root.open" type="boolean">+ Whether the popup is currently open. Use when controlled.+</ParamField>++<ParamField body="Root.openOnInputClick" type="boolean" default="false">+ Whether the popup opens when clicking the input.+</ParamField>++<ParamField body="Root.readOnly" type="boolean" default="false">+ Whether the user should be unable to choose a different option from the popup.+</ParamField>++<ParamField body="Root.required" type="boolean" default="false">+ Whether the user must choose a value before submitting a form.+</ParamField>++<ParamField body="Root.submitOnItemClick" type="boolean" default="false">+ Whether clicking an item should submit the autocomplete's owning form.+ By default, clicking an item via a pointer or <kbd>Enter</kbd> key does not submit the owning form.+ Useful when the autocomplete is used as a single-field form search input.+</ParamField>++<ParamField body="Root.value" type="string | number | readonly string[]">+ The input value of the autocomplete. Use when controlled.+</ParamField>++<ParamField body="Root.virtualized" type="boolean" default="false">+ Whether the items are being externally virtualized.+</ParamField>++### Autocomplete.InputGroup++<ParamField body="InputGroup.className" type="string | ((state: AutocompleteInputGroupState) => string | undefined)">+ CSS class applied to the element, or a function that+ returns a class based on the component's state.+</ParamField>++<ParamField body="InputGroup.render" type="ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, AutocompleteInputGroupState>">+ Allows you to replace the component's HTML element+ with a different tag, or compose it with another component.++ Accepts a `ReactElement` or a function that returns the element to render.+</ParamField>++<ParamField body="InputGroup.style" type="CSSProperties | ((state: AutocompleteInputGroupState) => CSSProperties | undefined)">+ Style applied to the element, or a function that+ returns a style object based on the component's state.+</ParamField>++### Autocomplete.Input++<ParamField body="Input.className" type="string | ((state: ComboboxInputState) => string | undefined)">+ CSS class applied to the element, or a function that+ returns a class based on the component's state.+</ParamField>++<ParamField body="Input.disabled" type="boolean" default="false">+ Whether the component should ignore user interaction.+</ParamField>++<ParamField body="Input.render" type="ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, ComboboxInputState>">+ Allows you to replace the component's HTML element+ with a different tag, or compose it with another component.++ Accepts a `ReactElement` or a function that returns the element to render.+</ParamField>++<ParamField body="Input.size" type=""md" | "sm"">+ Visual size of the input. Inside an InputGroup, the group size applies.+</ParamField>++<ParamField body="Input.style" type="CSSProperties | ((state: ComboboxInputState) => CSSProperties | undefined)">+ Style applied to the element, or a function that+ returns a style object based on the component's state.+</ParamField>++### Autocomplete.Popup++<ParamField body="Popup.align" type=""center" | "end" | "start"" default="start">+ How to align the popup relative to the specified side.+</ParamField>++<ParamField body="Popup.alignOffset" type="number | OffsetFunction" default="0">+ Additional offset along the alignment axis in pixels.+ Also accepts a function that returns the offset to read the dimensions of the anchor+ and positioner elements, along with its side and alignment.++ The function takes a `data` object parameter with the following properties:+ - `data.anchor`: the dimensions of the anchor element with properties `width` and `height`.+ - `data.positioner`: the dimensions of the positioner element with properties `width` and `height`.+ - `data.side`: which side of the anchor element the positioner is aligned against.+ - `data.align`: how the positioner is aligned relative to the specified side.+</ParamField>++<ParamField body="Popup.anchor" type="Element | VirtualElement | RefObject<Element | null> | (() => Element | VirtualElement | null) | null">+ An element to position the popup against.+ By default, the popup will be positioned against the trigger.+</ParamField>++<ParamField body="Popup.className" type="string | ((state: ComboboxPopupState) => string | undefined)">+ CSS class applied to the element, or a function that+ returns a class based on the component's state.+</ParamField>++<ParamField body="Popup.collisionPadding" type="Padding" default="5">+ Additional space to maintain from the edge of the collision boundary.+</ParamField>++<ParamField body="Popup.container" type="HTMLElement | ShadowRoot | RefObject<HTMLElement | ShadowRoot | null> | null">+ Element the popup is portaled into. Defaults to the theme portal container.+</ParamField>++<ParamField body="Popup.finalFocus" type="boolean | RefObject<HTMLElement | null> | ((closeType: InteractionType) => boolean | void | HTMLElement | null)">+ Determines the element to focus when the popup is closed.++ - `false`: Do not move focus.+ - `true`: Move focus based on the default behavior (trigger or previously focused element).+ - `RefObject`: Move focus to the ref element.+ - `function`: Called with the interaction type (`mouse`, `touch`, `pen`, or `keyboard`).+ Return an element to focus, `true` to use the default behavior, or `false`/`undefined` to do nothing.+</ParamField>++<ParamField body="Popup.initialFocus" type="boolean | RefObject<HTMLElement | null> | ((openType: InteractionType) => boolean | void | HTMLElement | null)">+ Determines the element to focus when the popup is opened.++ - `false`: Do not move focus.+ - `true`: Move focus based on the default behavior (first tabbable element or popup).+ - `RefObject`: Move focus to the ref element.+ - `function`: Called with the interaction type (`mouse`, `touch`, `pen`, or `keyboard`).+ Return an element to focus, `true` to use the default behavior, or `false`/`undefined` to do nothing.+</ParamField>++<ParamField body="Popup.render" type="ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, ComboboxPopupState>">+ Allows you to replace the component's HTML element+ with a different tag, or compose it with another component.++ Accepts a `ReactElement` or a function that returns the element to render.+</ParamField>++<ParamField body="Popup.side" type=""bottom" | "inline-end" | "inline-start" | "left" | "right" | "top"" default="bottom">+ Which side of the anchor element to align the popup against.+ May automatically change to avoid collisions.+</ParamField>++<ParamField body="Popup.sideOffset" type="number | OffsetFunction" default="8">+ Distance between the anchor and the popup in pixels.+ Also accepts a function that returns the distance to read the dimensions of the anchor+ and positioner elements, along with its side and alignment.++ The function takes a `data` object parameter with the following properties:+ - `data.anchor`: the dimensions of the anchor element with properties `width` and `height`.+ - `data.positioner`: the dimensions of the positioner element with properties `width` and `height`.+ - `data.side`: which side of the anchor element the positioner is aligned against.+ - `data.align`: how the positioner is aligned relative to the specified side.+</ParamField>++<ParamField body="Popup.style" type="CSSProperties | ((state: ComboboxPopupState) => CSSProperties | undefined)">+ Style applied to the element, or a function that+ returns a style object based on the component's state.+</ParamField>++<ParamField body="Popup.width" type="string | number">+ Width of the popup. Overrides its default minimum anchor width.+</ParamField>++### Autocomplete.List++<ParamField body="List.className" type="string | ((state: ComboboxListState) => string | undefined)">+ CSS class applied to the element, or a function that+ returns a class based on the component's state.+</ParamField>++<ParamField body="List.render" type="ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, ComboboxListState>">+ Allows you to replace the component's HTML element+ with a different tag, or compose it with another component.++ Accepts a `ReactElement` or a function that returns the element to render.+</ParamField>++<ParamField body="List.style" type="CSSProperties | ((state: ComboboxListState) => CSSProperties | undefined)">+ Style applied to the element, or a function that+ returns a style object based on the component's state.+</ParamField>++### Autocomplete.Item++<ParamField body="Item.className" type="string | ((state: AutocompleteItemState) => string | undefined)">+ CSS class applied to the element, or a function that+ returns a class based on the component's state.+</ParamField>++<ParamField body="Item.description" type="ReactNode">+ Supporting text, placed according to `descriptionPlacement`.+</ParamField>++<ParamField body="Item.descriptionPlacement" type=""end" | "inline"" default="inline">+ Where the description renders: inline after the content or at the end of+ the row.+</ParamField>++<ParamField body="Item.disabled" type="boolean" default="false">+ Whether the component should ignore user interaction.+</ParamField>++<ParamField body="Item.endIcon" type="ReactNode">+ Icon rendered after the content.+</ParamField>++<ParamField body="Item.index" type="number">+ The index of the item in the list. Improves performance when specified by avoiding the need to calculate the index automatically from the DOM.+</ParamField>++<ParamField body="Item.nativeButton" type="boolean" default="false">+ Whether the component renders a native `<button>` element when replacing it+ via the `render` prop.+ Set to `true` if the rendered element is a native button.+</ParamField>++<ParamField body="Item.onClick" type="((event: BaseUIEvent<MouseEvent<HTMLDivElement, MouseEvent>>) => void)">+ An optional click handler for the item when selected.+ It fires when clicking the item with the pointer, as well as when pressing `Enter` with the keyboard if the item is highlighted when the `Input` or `List` element has focus.+</ParamField>++<ParamField body="Item.render" type="ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, AutocompleteItemState>">+ Allows you to replace the component's HTML element+ with a different tag, or compose it with another component.++ Accepts a `ReactElement` or a function that returns the element to render.+</ParamField>++<ParamField body="Item.startIcon" type="ReactNode">+ Icon rendered before the content.+</ParamField>++<ParamField body="Item.style" type="CSSProperties | ((state: AutocompleteItemState) => CSSProperties | undefined)">+ Style applied to the element, or a function that+ returns a style object based on the component's state.+</ParamField>++<ParamField body="Item.value" type="any" default="null">+ A unique value that identifies this item.+</ParamField>++### Autocomplete.Empty++<ParamField body="Empty.className" type="string | ((state: ComboboxEmptyState) => string | undefined)">+ CSS class applied to the element, or a function that+ returns a class based on the component's state.+</ParamField>++<ParamField body="Empty.render" type="ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, ComboboxEmptyState>">+ Allows you to replace the component's HTML element+ with a different tag, or compose it with another component.++ Accepts a `ReactElement` or a function that returns the element to render.+</ParamField>++<ParamField body="Empty.style" type="CSSProperties | ((state: ComboboxEmptyState) => CSSProperties | undefined)">+ Style applied to the element, or a function that+ returns a style object based on the component's state.+</ParamField>diff --git a/packages/twenty-docs/ui/primitives/input/autocomplete.mdx b/packages/twenty-docs/ui/primitives/input/autocomplete.mdxnew file mode 100644index 00000000000..230c5a65f22--- /dev/null+++ b/packages/twenty-docs/ui/primitives/input/autocomplete.mdx@@ -0,0 +1,146 @@+---+title: Autocomplete+description: Suggest values while the user types and keeps focus in the input.+---++import { StoryEmbed } from '/snippets/ui/StoryEmbed.mdx';++import AutocompleteReference from '/snippets/ui/generated/input/autocomplete.mdx';++Use `Autocomplete` for suggestions attached to a text input. The input keeps its caret and keyboard focus while arrow keys highlight suggestions. Use [Select](/ui/primitives/input/select) when the user must choose a value from a fixed list.++<StoryEmbed+ storyId="ui-input-autocomplete--documentation"+ title="Autocomplete example"+ height={360}+/>++## Anatomy++Keep the input and popup inside a mounted `Autocomplete.Root`. `InputGroup` optionally groups the input with adjacent content and anchors the popup to that group.++```text+Autocomplete.Root+├── Autocomplete.InputGroup+│ └── Autocomplete.Input+└── Autocomplete.Popup+ ├── Autocomplete.Empty+ └── Autocomplete.List+ └── Autocomplete.Item+```++| Part | Purpose |+| ------------ | --------------------------------------------------------------- |+| `Root` | Owns the input value, filtering, highlights, and open state. |+| `InputGroup` | Groups the input with adjacent controls or chips. |+| `Input` | Renders the combobox input and retains keyboard focus. |+| `Popup` | Portals and positions the suggestions. |+| `List` | Renders the listbox and its filtered items. |+| `Item` | Renders a suggestion and handles pointer or keyboard selection. |+| `Empty` | Announces when no matching items are available. |++## Local suggestions++Pass `items` to `Root` and render them through `List` so filtering updates the visible suggestions. `autoHighlight="always"` highlights the first result whenever the list opens.++```tsx+import { Autocomplete } from 'twenty-ui/primitives/input';++const CITIES = ['Paris', 'London', 'Lisbon'];++export const CityInput = () => (+ <Autocomplete.Root items={CITIES} autoHighlight="always">+ <Autocomplete.Input aria-label="City" placeholder="Search cities" />+ <Autocomplete.Popup>+ <Autocomplete.Empty>No matching cities</Autocomplete.Empty>+ <Autocomplete.List>+ {(city: string) => (+ <Autocomplete.Item key={city} value={city}>+ {city}+ </Autocomplete.Item>+ )}+ </Autocomplete.List>+ </Autocomplete.Popup>+ </Autocomplete.Root>+);+```++`value` and `onValueChange` control the input text. Use `defaultValue` for an uncontrolled initial value. `Item.onClick` handles both pointer selection and Enter from the input. For object items, provide `itemToStringValue` to determine their input text.++## Server suggestions++Pass `filter={null}` when a server already filters the results. Keep `Root` mounted and control `open` independently so results can arrive while the input remains focused. A loading state can stay outside `List`; render `Empty` when the completed response has no results.++```tsx+import { Autocomplete } from 'twenty-ui/primitives/input';++type LocationSuggestionsProps = {+ query: string;+ locations: string[];+ open: boolean;+ onQueryChange: (query: string) => void;+ onOpenChange: (open: boolean) => void;+ onSelect: (location: string) => void;+};++export const LocationSuggestions = ({+ query,+ locations,+ open,+ onQueryChange,+ onOpenChange,+ onSelect,+}: LocationSuggestionsProps) => (+ <Autocomplete.Root+ items={locations}+ value={query}+ open={open}+ filter={null}+ autoHighlight="always"+ onValueChange={(value, details) => {+ if (details.reason !== 'escape-key') {+ onQueryChange(value);+ }+ }}+ onOpenChange={(nextOpen, details) => {+ if (details.reason !== 'input-change') {+ onOpenChange(nextOpen);+ }+ }}+ >+ <Autocomplete.Input aria-label="Location" />+ <Autocomplete.Popup>+ <Autocomplete.Empty>No matching locations</Autocomplete.Empty>+ <Autocomplete.List>+ {(location: string) => (+ <Autocomplete.Item+ key={location}+ value={location}+ onClick={() => onSelect(location)}+ >+ {location}+ </Autocomplete.Item>+ )}+ </Autocomplete.List>+ </Autocomplete.Popup>+ </Autocomplete.Root>+);+```++The parent owns debounce, request cancellation, and stale response protection. In this example, typing does not open the list until the parent supplies its results and sets `open`. Escape closes the list and preserves the query.++## Input composition and placement++`Input` accepts `size="sm"` or `size="md"` and uses the same styles as [Input](/ui/primitives/input/input). Use its `render` prop to compose an existing input. That input must forward its ref, native input attributes, and event handlers to the actual input element so keyboard navigation and accessible state remain connected.++`InputGroup` provides layout and an anchor without adding input borders. It can contain chips or render an existing wrapper. Use [InputGroup](/ui/primitives/input/input-group) through its `render` prop when the whole group needs input styling.++`Popup` defaults to `side="bottom"`, `align="start"`, and `sideOffset={8}`. It uses the anchor's width as its minimum width and the [theme's portal container](/ui/theming#scope-an-override) unless you provide `container`. Set `width` to override the anchor width with a fixed popup width. Customize placement with `side`, `align`, offsets, `collisionPadding`, or `anchor`.++Use `Item.startIcon`, `Item.endIcon`, and `Item.description` for supporting content. Arrow keys change the highlighted item without moving DOM focus from the input; Enter chooses that item and Escape dismisses the popup. A press outside the input group and popup also dismisses it without activating the element that was pressed. Call `event.preventDefault()` in the input's `onKeyDown` to handle a key yourself and skip this built-in behavior. Give the input an accessible label or compose it with [Field](/ui/primitives/input/field).++## Props++The reference is generated from the public component types. Parts that render an element also accept its native attributes and event handlers.++<AutocompleteReference />diff --git a/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventLocationInput.tsx b/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventLocationInput.tsxindex bfca01a5c45..fb9b4882237 100644--- a/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventLocationInput.tsx+++ b/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventLocationInput.tsx@@ -1,7 +1,8 @@import { StyledComposerTextInput } from '@/activities/components/ComposerTextInput';import { PlaceAutocompleteSelect } from '@/geo-map/components/PlaceAutocompleteSelect';import { usePlaceAutocomplete } from '@/geo-map/hooks/usePlaceAutocomplete';-import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';+import { AutocompleteRoot } from '@/ui/input/components/AutocompleteRoot';+import { Autocomplete } from 'twenty-ui/primitives/input';import { isDefined } from 'twenty-shared/utils';const CALENDAR_EVENT_LOCATION_AUTOCOMPLETE_DROPDOWN_ID =@@ -46,29 +47,29 @@ export const CalendarEventLocationInput = ({};return (- <Dropdown+ <AutocompleteRootdropdownId={CALENDAR_EVENT_LOCATION_AUTOCOMPLETE_DROPDOWN_ID}- dropdownPlacement="bottom-start"- clickableComponentWidth="100%"- disableClickForClickableComponent- onClickOutside={closePlaceAutocomplete}- clickableComponent={- <StyledComposerTextInput- type="text"- autoComplete="off"- aria-label={ariaLabel}- placeholder={placeholder}- value={value}- onChange={(event) => handleLocationChange(event.target.value)}- />- }- dropdownComponents={- <PlaceAutocompleteSelect- list={placeAutocompleteData}- onChange={handlePlaceSelection}- dropdownId={CALENDAR_EVENT_LOCATION_AUTOCOMPLETE_DROPDOWN_ID}- />- }- />+ items={placeAutocompleteData}+ itemToStringValue={(place) => place.text}+ value={value}+ openOnValueChange={false}+ onValueChange={handleLocationChange}+ onClose={closePlaceAutocomplete}+ >+ <Autocomplete.Input+ type="text"+ autoComplete="off"+ aria-label={ariaLabel}+ placeholder={placeholder}+ render={(inputProps) => (+ // oxlint-disable-next-line react/jsx-props-no-spreading+ <StyledComposerTextInput {...inputProps} className={undefined} />+ )}+ />+ <PlaceAutocompleteSelect+ list={placeAutocompleteData}+ onChange={handlePlaceSelection}+ />+ </AutocompleteRoot>);};diff --git a/packages/twenty-front/src/modules/activities/calendar/components/__stories__/CalendarEventLocationInput.stories.tsx b/packages/twenty-front/src/modules/activities/calendar/components/__stories__/CalendarEventLocationInput.stories.tsxindex 41b237d6242..e0d47677a82 100644--- a/packages/twenty-front/src/modules/activities/calendar/components/__stories__/CalendarEventLocationInput.stories.tsx+++ b/packages/twenty-front/src/modules/activities/calendar/components/__stories__/CalendarEventLocationInput.stories.tsx@@ -2,18 +2,25 @@ import { CalendarEventLocationInput } from '@/activities/calendar/components/Calimport { type Meta, type StoryObj } from '@storybook/react-vite';import { HttpResponse, delay, graphql } from 'msw';import { useState } from 'react';-import { expect, userEvent, within } from 'storybook/test';+import { Button } from 'twenty-ui/primitives/input';+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';++const onAutocompleteRequest = fn();+const onAutocompleteResponse = fn();const StatefulCalendarEventLocationInput = () => {const [value, setValue] = useState('');return (- <CalendarEventLocationInput- ariaLabel="Location"- placeholder="Add a location"- value={value}- onChange={setValue}- />+ <>+ <CalendarEventLocationInput+ ariaLabel="Location"+ placeholder="Add a location"+ value={value}+ onChange={setValue}+ />+ <Button>Outside</Button>+ </>);};@@ -21,12 +28,20 @@ const meta: Meta<typeof CalendarEventLocationInput> = {title: 'Modules/Activities/Calendar/CalendarEventLocationInput',component: CalendarEventLocationInput,render: () => <StatefulCalendarEventLocationInput />,+ beforeEach: () => {+ onAutocompleteRequest.mockClear();+ onAutocompleteResponse.mockClear();+ },parameters: {+ mockingDate: null,msw: {handlers: [graphql.query('GetAutoCompleteAddress', async ({ variables }) => {+ onAutocompleteRequest(variables.address);+if (variables.address === 'Paris') {await delay(900);+ onAutocompleteResponse(variables.address);return HttpResponse.json({data: {@@ -37,6 +52,8 @@ const meta: Meta<typeof CalendarEventLocationInput> = {});}+ onAutocompleteResponse(variables.address);+return HttpResponse.json({data: {getAutoCompleteAddress: [@@ -57,17 +74,99 @@ export const IgnoresStaleResponses: Story = {play: async ({ canvasElement }) => {const canvas = within(canvasElement);const screen = within(canvasElement.ownerDocument.body);- const input = canvas.getByRole('textbox', { name: 'Location' });+ const input = canvas.getByRole('combobox', { name: 'Location' });await userEvent.type(input, 'Paris');- await delay(350);+ await waitFor(+ () => expect(onAutocompleteRequest).toHaveBeenCalledWith('Paris'),+ { timeout: 5000 },+ );await userEvent.clear(input);await userEvent.type(input, 'London');- expect(await screen.findByText('London, United Kingdom')).toBeVisible();+ const londonOption = await screen.findByRole(+ 'option',+ { name: 'London, United Kingdom' },+ { timeout: 5000 },+ );++ await waitFor(() => expect(londonOption).toBeVisible());++ await waitFor(+ () => expect(onAutocompleteResponse).toHaveBeenCalledWith('Paris'),+ { timeout: 5000 },+ );++ await waitFor(() => {+ expect(londonOption).toBeVisible();+ expect(screen.queryByText('Paris, France')).not.toBeInTheDocument();+ });+ },+};++export const SelectsWithoutMovingFocus: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const input = canvas.getByRole('combobox', { name: 'Location' });++ await userEvent.type(input, 'London');++ const option = await screen.findByRole(+ 'option',+ { name: 'London, United Kingdom' },+ { timeout: 5000 },+ );++ expect(input).toHaveFocus();+ await userEvent.click(input);+ expect(option).toBeVisible();+ await userEvent.keyboard('{ArrowDown}{Enter}');++ await waitFor(() => {+ expect(input).toHaveValue('London, United Kingdom');+ expect(input).toHaveFocus();+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ });+ },+};++export const DismissesWithoutSelecting: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const input = canvas.getByRole('combobox', { name: 'Location' });+ const outsideButton = canvas.getByRole('button', { name: 'Outside' });++ await userEvent.type(input, 'London');+ await screen.findByRole(+ 'option',+ { name: 'London, United Kingdom' },+ { timeout: 5000 },+ );+ await userEvent.keyboard('{Escape}');++ await waitFor(() => {+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ expect(input).toHaveValue('London');+ expect(input).toHaveFocus();+ });+ await userEvent.keyboard('{ArrowDown}');++ expect(input).toHaveAttribute('aria-expanded', 'false');+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();- await delay(700);+ await userEvent.type(input, ' UK');+ await screen.findByRole(+ 'option',+ { name: 'London, United Kingdom' },+ { timeout: 5000 },+ );+ await userEvent.click(outsideButton);- expect(screen.queryByText('Paris, France')).not.toBeInTheDocument();+ await waitFor(() => {+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ expect(input).toHaveValue('London UK');+ });},};diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientChipMenuContent.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientChipMenuContent.tsxindex af91554cf0f..3e6300f8079 100644--- a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientChipMenuContent.tsx+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientChipMenuContent.tsx@@ -1,22 +1,16 @@import { type EmailRecipientResolution } from '@/activities/emails/recipients/hooks/useEmailRecipientsResolution';import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailRecipient';import { useCreateOneRecord } from '@/object-record/hooks/useCreateOneRecord';-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 { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';import { useLingui } from '@lingui/react/macro';import { isNonEmptyString } from '@sniptt/guards';import { CoreObjectNameSingular } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';-import { MenuItemAvatar, useToast } from 'twenty-ui/components';+import { Dropdown, MenuItemAvatar, useToast } from 'twenty-ui/components';import { IconCopy, IconPencil, IconTrash, IconUserPlus } from 'twenty-ui/icon';-import { ListItem } from 'twenty-ui/primitives/navigation';import { useCopyToClipboard } from '~/hooks/useCopyToClipboard';import { getAbsoluteImageUrl } from '~/utils/image/getAbsoluteImageUrl';type EmailRecipientChipMenuContentProps = {- dropdownId: string;recipient: EmailRecipient;resolution: EmailRecipientResolution | undefined;isInvalid: boolean;@@ -25,7 +19,6 @@ type EmailRecipientChipMenuContentProps = {};export const EmailRecipientChipMenuContent = ({- dropdownId,recipient,resolution,isInvalid,@@ -33,7 +26,6 @@ export const EmailRecipientChipMenuContent = ({onRemove,}: EmailRecipientChipMenuContentProps) => {const { t } = useLingui();- const { closeDropdown } = useCloseDropdown();const { copyToClipboard } = useCopyToClipboard();const { enqueueToast } = useToast();@@ -52,8 +44,6 @@ export const EmailRecipientChipMenuContent = ({: '';const handleAddAsPerson = async () => {- closeDropdown(dropdownId);-const [firstName = '', ...lastNameParts] = (recipient.displayName ?? '').split(' ');@@ -69,28 +59,17 @@ export const EmailRecipientChipMenuContent = ({};const handleCopy = () => {- closeDropdown(dropdownId);copyToClipboard(recipient.address, t`Email copied to clipboard`);};- const handleEdit = () => {- closeDropdown(dropdownId);- onEdit();- };-- const handleRemove = () => {- closeDropdown(dropdownId);- onRemove();- };-const showAddAsPerson =!isDefined(person) && !isDefined(workspaceMember) && !isInvalid;return (- <LegacyDropdownContent widthInPixels={280}>+ <>{(isDefined(person) || isDefined(workspaceMember) || showAddAsPerson) && (<>- <DropdownMenuItemsContainer>+ <Dropdown.Section>{isDefined(workspaceMember) ? (<MenuItemAvataravatar={{@@ -128,30 +107,30 @@ export const EmailRecipientChipMenuContent = ({contextualText={recipient.address}/>) : (- <ListItem+ <Dropdown.ActionItemstartIcon={<IconUserPlus />}onClick={handleAddAsPerson}- >{t`Add as person`}</ListItem>+ >{t`Add as person`}</Dropdown.ActionItem>)}- </DropdownMenuItemsContainer>- <DropdownMenuSeparator />+ </Dropdown.Section>+ <Dropdown.Separator /></>)}- <DropdownMenuItemsContainer>- <ListItem+ <Dropdown.Section>+ <Dropdown.ActionItemstartIcon={<IconCopy />}onClick={handleCopy}- >{t`Copy email`}</ListItem>- <ListItem+ >{t`Copy email`}</Dropdown.ActionItem>+ <Dropdown.ActionItemstartIcon={<IconPencil />}- onClick={handleEdit}- >{t`Edit`}</ListItem>- <ListItem+ onClick={onEdit}+ >{t`Edit`}</Dropdown.ActionItem>+ <Dropdown.ActionItemcolor="danger"startIcon={<IconTrash />}- onClick={handleRemove}- >{t`Remove`}</ListItem>- </DropdownMenuItemsContainer>- </LegacyDropdownContent>+ onClick={onRemove}+ >{t`Remove`}</Dropdown.ActionItem>+ </Dropdown.Section>+ </>);};diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientSuggestionMenuItem.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientSuggestionMenuItem.tsxindex 33634801e5c..8659bd515ed 100644--- a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientSuggestionMenuItem.tsx+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientSuggestionMenuItem.tsx@@ -1,51 +1,32 @@import { Avatar } from 'twenty-ui/primitives/data-display';-import { ListItem } from 'twenty-ui/primitives/navigation';+import { Autocomplete } from 'twenty-ui/primitives/input';import { type EmailRecipientSuggestion } from '@/activities/emails/recipients/types/EmailRecipientSuggestion';-import { SelectableListItem } from '@/ui/layout/selectable-list/components/SelectableListItem';-import { isSelectedItemIdComponentFamilyState } from '@/ui/layout/selectable-list/states/isSelectedItemIdComponentFamilyState';-import { useAtomComponentFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateValue';import { getAbsoluteImageUrl } from '~/utils/image/getAbsoluteImageUrl';type EmailRecipientSuggestionMenuItemProps = {suggestion: EmailRecipientSuggestion;- selectableListInstanceId: string;onPick: (suggestion: EmailRecipientSuggestion) => void;};export const EmailRecipientSuggestionMenuItem = ({suggestion,- selectableListInstanceId,onPick,-}: EmailRecipientSuggestionMenuItemProps) => {- const isSelectedItemId = useAtomComponentFamilyStateValue(- isSelectedItemIdComponentFamilyState,- suggestion.suggestionId,- selectableListInstanceId,- );-- return (- <SelectableListItem itemId={suggestion.suggestionId}>- <ListItem- onClick={() => onPick(suggestion)}- focused={isSelectedItemId}- role="option"- aria-selected={false}- selected={false}- indicator="check"- description={suggestion.secondaryText}- startIcon={- <Avatar- src={getAbsoluteImageUrl(suggestion.avatarUrl)}- name={suggestion.label}- colorSeed={suggestion.avatarColorSeed}- size="md"- shape="circle"- />- }- >- {suggestion.label}- </ListItem>- </SelectableListItem>- );-};+}: EmailRecipientSuggestionMenuItemProps) => (+ <Autocomplete.Item+ value={suggestion.suggestionId}+ onClick={() => onPick(suggestion)}+ description={suggestion.secondaryText}+ startIcon={+ <Avatar+ src={getAbsoluteImageUrl(suggestion.avatarUrl)}+ name={suggestion.label}+ colorSeed={suggestion.avatarColorSeed}+ size="md"+ shape="circle"+ />+ }+ >+ {suggestion.label}+ </Autocomplete.Item>+);diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientSuggestionsDropdownContent.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientSuggestionsDropdownContent.tsxindex 02d82730db9..254afa70e52 100644--- a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientSuggestionsDropdownContent.tsx+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientSuggestionsDropdownContent.tsx@@ -1,53 +1,33 @@-import { ListItem } from 'twenty-ui/primitives/navigation';import { useLingui } from '@lingui/react/macro';+import { Autocomplete } from 'twenty-ui/primitives/input';import { EmailRecipientSuggestionMenuItem } from '@/activities/emails/recipients/components/EmailRecipientSuggestionMenuItem';import { type EmailRecipientSuggestion } from '@/activities/emails/recipients/types/EmailRecipientSuggestion';-import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';-import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';-import { SelectableList } from '@/ui/layout/selectable-list/components/SelectableList';+import { AutocompleteContent } from '@/ui/input/components/AutocompleteContent';type EmailRecipientSuggestionsDropdownContentProps = {suggestions: EmailRecipientSuggestion[];- selectableListInstanceId: string;- focusId: string;onPick: (suggestion: EmailRecipientSuggestion) => void;};export const EmailRecipientSuggestionsDropdownContent = ({suggestions,- selectableListInstanceId,- focusId,onPick,}: EmailRecipientSuggestionsDropdownContentProps) => {const { t } = useLingui();return (- <div onMouseDown={(event) => event.preventDefault()}>- <LegacyDropdownContent widthInPixels={340}>- <DropdownMenuItemsContainer hasMaxHeight>- {suggestions.length === 0 ? (- <ListItem disabled>{t`No results`}</ListItem>- ) : (- <SelectableList- selectableListInstanceId={selectableListInstanceId}- focusId={focusId}- selectableItemIdArray={suggestions.map(- (suggestion) => suggestion.suggestionId,- )}- >- {suggestions.map((suggestion) => (- <EmailRecipientSuggestionMenuItem- key={suggestion.suggestionId}- suggestion={suggestion}- selectableListInstanceId={selectableListInstanceId}- onPick={onPick}- />- ))}- </SelectableList>- )}- </DropdownMenuItemsContainer>- </LegacyDropdownContent>- </div>+ <AutocompleteContent align="start" sideOffset={4} width={340}>+ <Autocomplete.List>+ {suggestions.map((suggestion) => (+ <EmailRecipientSuggestionMenuItem+ key={suggestion.suggestionId}+ suggestion={suggestion}+ onPick={onPick}+ />+ ))}+ </Autocomplete.List>+ <Autocomplete.Empty>{t`No results`}</Autocomplete.Empty>+ </AutocompleteContent>);};diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChip.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChip.tsxindex 44a84fe6692..b3ef348d7a8 100644--- a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChip.tsx+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChip.tsx@@ -1,3 +1,5 @@+import { type RefObject } from 'react';+import { Dropdown } from 'twenty-ui/components';import { useLingui } from '@lingui/react/macro';import { isDefined } from 'twenty-shared/utils';import { Avatar } from 'twenty-ui/primitives/data-display';@@ -8,7 +10,8 @@ import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailRimport { formatEmailRecipient } from '@/activities/emails/recipients/utils/formatEmailRecipient';import { getEmailIdentityDisplayName } from '@/activities/emails/utils/getEmailIdentityDisplayName';import { BaseChip } from '@/ui/input/components/BaseChip';-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 { getAbsoluteImageUrl } from '~/utils/image/getAbsoluteImageUrl';const CHIP_MAX_WIDTH = 240;@@ -16,6 +19,7 @@ const CHIP_MAX_WIDTH = 240;type EmailRecipientsFieldChipProps = {chipId: string;dropdownId: string;+ inputRef: RefObject<HTMLInputElement | null>;recipient: EmailRecipient;resolution: EmailRecipientResolution | undefined;isInvalid: boolean;@@ -28,6 +32,7 @@ type EmailRecipientsFieldChipProps = {export const EmailRecipientsFieldChip = ({chipId,dropdownId,+ inputRef,recipient,resolution,isInvalid,@@ -69,10 +74,8 @@ export const EmailRecipientsFieldChip = ({) : undefined;return (- <Dropdown- dropdownId={dropdownId}- dropdownPlacement="bottom-start"- clickableComponent={+ <DropdownRoot dropdownId={dropdownId} type="menu">+ <Dropdown.Trigger render={<div />} nativeButton={false} tabIndex={-1}><BaseChipchipId={chipId}label={resolvedLabel}@@ -93,17 +96,21 @@ export const EmailRecipientsFieldChip = ({}}removeAriaLabel={t`Remove ${recipient.address}`}/>- }- dropdownComponents={+ </Dropdown.Trigger>+ <DropdownContent+ align="start"+ width={280}+ initialFocus={false}+ finalFocus={inputRef}+ ><EmailRecipientChipMenuContent- dropdownId={dropdownId}recipient={recipient}resolution={resolution}isInvalid={isInvalid}onEdit={onEdit}onRemove={onRemove}/>- }- />+ </DropdownContent>+ </DropdownRoot>);};diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChipCell.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChipCell.tsxindex 2187fc519e8..925fb5eab08 100644--- a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChipCell.tsx+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChipCell.tsx@@ -1,5 +1,5 @@import { styled } from '@linaria/react';-import { type MouseEvent } from 'react';+import { type MouseEvent, type RefObject } from 'react';import { themeCssVariables } from 'twenty-ui/theme';import { EMAIL_RECIPIENT_DND_TYPE } from '@/activities/emails/recipients/constants/EmailRecipientDndType';@@ -10,7 +10,7 @@ import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailRimport { type EmailRecipientsFieldId } from '@/activities/emails/recipients/types/EmailRecipientsFieldId';import { DragDropItemSortableCell } from '@/ui/utilities/drag-and-drop/components/DragDropItemSortableCell';-export type EmailRecipientChipDropEdge = 'before' | 'after' | null;+import { type EmailRecipientChipDropEdge } from '@/activities/emails/recipients/types/EmailRecipientChipDropEdge';const DROP_INDICATOR_WIDTH = '2px';// Centers the bar in the 4px chip gap: half the gap plus half the bar.@@ -52,6 +52,7 @@ type EmailRecipientsFieldChipCellProps = {chipId: string;chipIndex: number;dropdownId: string;+ inputRef: RefObject<HTMLInputElement | null>;dropEdge: EmailRecipientChipDropEdge;fieldId: EmailRecipientsFieldId;isFlashing: boolean;@@ -71,6 +72,7 @@ export const EmailRecipientsFieldChipCell = ({chipId,chipIndex,dropdownId,+ inputRef,dropEdge,fieldId,isFlashing,@@ -126,6 +128,7 @@ export const EmailRecipientsFieldChipCell = ({<EmailRecipientsFieldChipchipId={chipId}dropdownId={dropdownId}+ inputRef={inputRef}recipient={recipient}resolution={resolution}isInvalid={isInvalid}diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsxindex 9c92711b5a6..48d9ea19a71 100644--- a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx@@ -4,7 +4,7 @@ import { pointerIntersection } from '@dnd-kit/collision';import { useDroppable } from '@dnd-kit/react';import { styled } from '@linaria/react';import { isNonEmptyString } from '@sniptt/guards';-import { useStore } from 'jotai';+import { atom, useStore } from 'jotai';import {type ClipboardEvent,type KeyboardEvent,@@ -18,14 +18,13 @@ import {} from 'react';import { flushSync } from 'react-dom';import { isDefined } from 'twenty-shared/utils';+import { Autocomplete } from 'twenty-ui/primitives/input';import { themeCssVariables } from 'twenty-ui/theme';import { useDebouncedCallback } from 'use-debounce';import { EMAIL_RECIPIENT_DND_TYPE } from '@/activities/emails/recipients/constants/EmailRecipientDndType';-import {- type EmailRecipientChipDropEdge,- EmailRecipientsFieldChipCell,-} from '@/activities/emails/recipients/components/EmailRecipientsFieldChipCell';+import { EmailRecipientsFieldChipCell } from '@/activities/emails/recipients/components/EmailRecipientsFieldChipCell';+import { type EmailRecipientChipDropEdge } from '@/activities/emails/recipients/types/EmailRecipientChipDropEdge';import { EmailRecipientSuggestionsDropdownContent } from '@/activities/emails/recipients/components/EmailRecipientSuggestionsDropdownContent';import { useEmailRecipientsField } from '@/activities/emails/recipients/hooks/useEmailRecipientsField';import { useEmailRecipientsResolution } from '@/activities/emails/recipients/hooks/useEmailRecipientsResolution';@@ -38,19 +37,16 @@ import { isValidEmailRecipientAddress } from '@/activities/emails/recipients/utiimport { parseEmailRecipients } from '@/activities/emails/recipients/utils/parseEmailRecipients';import { FormFieldInputContainer } from '@/ui/input/components/FormFieldInputContainer';import { FORM_FIELD_PLACEHOLDER_STYLES } from '@/ui/input/constants/FormFieldPlaceholderStyles';-import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';+import { AutocompleteRoot } from '@/ui/input/components/AutocompleteRoot';import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';import { useOpenDropdown } from '@/ui/layout/dropdown/hooks/useOpenDropdown';import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';-import { useSelectableList } from '@/ui/layout/selectable-list/hooks/useSelectableList';-import { selectedItemIdComponentState } from '@/ui/layout/selectable-list/states/selectedItemIdComponentState';import { DND_KIT_COLLISION_PRIORITY } from '@/ui/utilities/drag-and-drop/constants/DndKitCollisionPriority';import { DragDropItemDndContext } from '@/ui/utilities/drag-and-drop/context/DragDropItemDndContext';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 { useHotkeysOnFocusedElement } from '@/ui/utilities/hotkey/hooks/useHotkeysOnFocusedElement';-import { useAtomComponentStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateCallbackState';import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';const SUGGESTIONS_SEARCH_DEBOUNCE_MS = 300;@@ -132,13 +128,10 @@ export const EmailRecipientsFieldInput = ({useRemoveFocusItemFromFocusStackById();const { openDropdown } = useOpenDropdown();const { closeDropdown } = useCloseDropdown();- const { resetSelectedItem } = useSelectableList(suggestionsDropdownId);-- const store = useStore();- const selectedItemIdAtom = useAtomComponentStateCallbackState(- selectedItemIdComponentState,- suggestionsDropdownId,+ const [highlightedSuggestionIdAtom] = useState(() =>+ atom<string | undefined>(undefined),);+ const store = useStore();const isDropdownOpen = useAtomComponentStateValue(isDropdownOpenComponentState,@@ -229,6 +222,8 @@ export const EmailRecipientsFieldInput = ({};const closeSuggestions = () => {+ store.set(highlightedSuggestionIdAtom, undefined);+if (isDropdownOpen) {closeDropdown(suggestionsDropdownId);}@@ -325,7 +320,7 @@ export const EmailRecipientsFieldInput = ({const handleInputChange = (value: string) => {setInputValue(value);clearChipSelection();- resetSelectedItem();+ store.set(highlightedSuggestionIdAtom, undefined);if (isEditing) {return;@@ -333,9 +328,7 @@ export const EmailRecipientsFieldInput = ({debouncedSetSuggestionsSearchInput(value);- if (value.trim().length > 0) {- openSuggestions();- } else {+ if (value.trim().length === 0) {resetSuggestionsSearchInput();closeSuggestions();}@@ -442,9 +435,11 @@ export const EmailRecipientsFieldInput = ({event.preventDefault();if (!isEditing && isDropdownOpen && suggestions.length > 0) {- const selectedItemId = store.get(selectedItemIdAtom);+ const highlightedSuggestionId = store.get(+ highlightedSuggestionIdAtom,+ );const selectedSuggestion = suggestions.find(- (suggestion) => suggestion.suggestionId === selectedItemId,+ (suggestion) => suggestion.suggestionId === highlightedSuggestionId,);const suggestionsMatchBuffer =suggestionsSearchInput === inputValue.trim();@@ -542,6 +537,8 @@ export const EmailRecipientsFieldInput = ({}case 'Escape': {if (isDropdownOpen) {+ event.preventDefault();+ event.stopPropagation();closeSuggestions();return;}@@ -564,17 +561,17 @@ export const EmailRecipientsFieldInput = ({};const recipientsInput = (- <StyledInput+ <Autocomplete.Inputkey="email-recipients-input"+ render={(inputProps) => (+ // oxlint-disable-next-line react/jsx-props-no-spreading+ <StyledInput {...inputProps} className={undefined} />+ )}ref={inputRef}type="text"autoComplete="off"spellCheck={false}- role="combobox"- aria-expanded={isDropdownOpen}aria-label={label}- value={inputValue}- onChange={(event) => handleInputChange(event.target.value)}onKeyDown={handleInputKeyDown}onPaste={handleInputPaste}onFocus={handleInputFocus}@@ -600,6 +597,7 @@ export const EmailRecipientsFieldInput = ({chipId={getChipId(chipIndex)}chipIndex={chipIndex}dropdownId={`${focusId}-chip-menu-${chipKey}`}+ inputRef={inputRef}dropEdge={getChipDropEdge(chipIndex)}fieldId={fieldId}isFlashing={flashNonce !== null}@@ -625,32 +623,35 @@ export const EmailRecipientsFieldInput = ({<><ToastOnQueryErrorEffect error={error} /><FormFieldInputContainer>- <Dropdown+ <AutocompleteRootdropdownId={suggestionsDropdownId}- dropdownPlacement="bottom-start"- dropdownOffset={{ y: 4 }}- disableClickForClickableComponent- clickableComponentWidth="100%"- onClose={resetSelectedItem}- clickableComponent={- <StyledRowContainer- ref={droppableRef}- $isDropTarget={isActiveDropField}- data-drop-target={isActiveDropField}- onMouseDown={handleRowMouseDown}- >- {rowChildren}- </StyledRowContainer>- }- dropdownComponents={- <EmailRecipientSuggestionsDropdownContent- suggestions={suggestions}- selectableListInstanceId={suggestionsDropdownId}- focusId={suggestionsDropdownId}- onPick={handlePickSuggestion}- />+ enabled={!isEditing}+ items={suggestions.map((suggestion) => suggestion.suggestionId)}+ value={inputValue}+ globalHotkeysConfig={{ enableGlobalHotkeysWithModifiers: true }}+ onValueChange={handleInputChange}+ onItemHighlightedByUser={(suggestionId) =>+ store.set(highlightedSuggestionIdAtom, suggestionId)}- />+ onClose={() => store.set(highlightedSuggestionIdAtom, undefined)}+ >+ <Autocomplete.InputGroup+ render={+ <StyledRowContainer+ ref={droppableRef}+ $isDropTarget={isActiveDropField}+ data-drop-target={isActiveDropField}+ onMouseDown={handleRowMouseDown}+ />+ }+ >+ {rowChildren}+ </Autocomplete.InputGroup>+ <EmailRecipientSuggestionsDropdownContent+ suggestions={suggestions}+ onPick={handlePickSuggestion}+ />+ </AutocompleteRoot></FormFieldInputContainer></>);diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/__stories__/EmailRecipientsFieldInput.stories.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/__stories__/EmailRecipientsFieldInput.stories.tsxnew file mode 100644index 00000000000..6714be3bc26--- /dev/null+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/__stories__/EmailRecipientsFieldInput.stories.tsx@@ -0,0 +1,390 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { HttpResponse, graphql } from 'msw';+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';+import { ComponentDecorator } from 'twenty-ui/testing';++import { StatefulEmailRecipientsFieldInput } from '@/activities/emails/recipients/components/__stories__/StatefulEmailRecipientsFieldInput';+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';+import { ToastDecorator } from '~/testing/decorators/ToastDecorator';+import { WorkspaceDecorator } from '~/testing/decorators/WorkspaceDecorator';+import { graphqlMocks } from '~/testing/graphqlMocks';+import { mockedApolloClient } from '~/testing/mockedApolloClient';+import { mockedPersonRecords } from '~/testing/mock-data/generated/data/people/mock-people-data';++const createPerson = fn();++const meta = {+ title: 'Modules/Activities/Emails/EmailRecipientsFieldInput',+ component: StatefulEmailRecipientsFieldInput,+ args: { onSubmit: fn() },+ beforeEach: async () => {+ createPerson.mockClear();+ await mockedApolloClient.clearStore();+ },+ parameters: {+ mockingDate: null,+ container: { width: 480, height: 240 },+ msw: {+ handlers: [+ graphql.mutation('CreateOnePerson', ({ variables }) => {+ createPerson(variables);++ return HttpResponse.json({+ data: {+ createPerson: {+ ...mockedPersonRecords[0],+ ...variables.input,+ emails: {+ __typename: 'Emails',+ ...variables.input.emails,+ },+ name: {+ __typename: 'FullName',+ ...variables.input.name,+ },+ },+ },+ });+ }),+ ...graphqlMocks.handlers,+ ],+ },+ },+ decorators: [+ ComponentDecorator,+ ObjectMetadataItemsDecorator,+ ToastDecorator,+ MemoryRouterDecorator,+ WorkspaceDecorator,+ ],+} satisfies Meta<typeof StatefulEmailRecipientsFieldInput>;++export default meta;++type Story = StoryObj<typeof meta>;++export const SelectsSuggestionsFromTheInput: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const input = await canvas.findByRole('combobox', { name: 'To' });++ await userEvent.type(input, 'jeff');++ const option = await screen.findByRole('option', {+ name: /Jeffery Griffin/,+ });++ await waitFor(() => expect(option).toHaveAttribute('data-highlighted'));+ expect(input).toHaveFocus();+ expect(input).toHaveAttribute('aria-activedescendant', option.id);++ await userEvent.click(input);++ expect(option).toBeVisible();+ await userEvent.keyboard('{ArrowDown}');++ const secondOption = screen.getByRole('option', {+ name: /Terry Melendez/,+ });++ await waitFor(() =>+ expect(secondOption).toHaveAttribute('data-highlighted'),+ );+ expect(input).toHaveAttribute('aria-activedescendant', secondOption.id);+ await userEvent.keyboard('{Enter}');++ expect(canvas.getByText('Terry Melendez')).toBeVisible();+ expect(canvas.queryByText('Jeffery Griffin')).not.toBeInTheDocument();+ expect(input).toHaveValue('');+ expect(input).toHaveFocus();+ await waitFor(() =>+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument(),+ );+ },+};++export const CommitsBufferWhileSearchIsPending: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const input = await canvas.findByRole('combobox', { name: 'To' });++ await userEvent.type(input, 'jeff');++ const staleSuggestion = await screen.findByRole('option', {+ name: /Jeffery Griffin/,+ });++ await userEvent.type(input, '@example.net');++ expect(input).toHaveAttribute('aria-activedescendant', staleSuggestion.id);+ await userEvent.keyboard('{Enter}');++ expect(canvas.getByText('[email protected]')).toBeVisible();+ expect(canvas.queryByText('Jeffery Griffin')).not.toBeInTheDocument();+ expect(input).toHaveValue('');+ },+};++export const PreservesComposerShortcuts: Story = {+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const input = await canvas.findByRole('combobox', { name: 'To' });++ await userEvent.click(input);+ await userEvent.keyboard('{Control>}{Enter}{/Control}');++ expect(args.onSubmit).toHaveBeenCalledTimes(1);++ await userEvent.type(input, '[email protected]');+ await screen.findByRole('option', { name: /[email protected]/ });+ await userEvent.keyboard('{Meta>}{Enter}{/Meta}');++ expect(canvas.getByText('[email protected]')).toBeVisible();+ expect(args.onSubmit).toHaveBeenCalledTimes(1);+ expect(input).toHaveFocus();++ await userEvent.keyboard('{Meta>}{Enter}{/Meta}');++ expect(args.onSubmit).toHaveBeenCalledTimes(2);+ },+};++export const PastesAndSelectsChipsWithTheKeyboard: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const input = await canvas.findByRole('combobox', { name: 'To' });+ const ccInput = canvas.getByRole('combobox', { name: 'Cc' });++ await userEvent.click(input);+ await userEvent.paste('Ada <[email protected]>; Grace <[email protected]>');++ expect(canvas.getByText('Ada')).toBeVisible();+ expect(canvas.getByText('Grace')).toBeVisible();++ await userEvent.keyboard('{ArrowLeft}{Enter}');++ expect(input).toHaveValue('Grace <[email protected]>');+ await userEvent.keyboard('{Escape}');++ expect(canvas.getByText('Grace')).toBeVisible();+ expect(input).toHaveValue('');++ await userEvent.type(input, 'jeff');+ await screen.findByRole('option', { name: /Jeffery Griffin/ });+ await userEvent.keyboard('{Escape}');++ await waitFor(() =>+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument(),+ );+ expect(input).toHaveValue('jeff');+ expect(input).toHaveFocus();++ await userEvent.clear(input);+ await userEvent.keyboard(+ '{ArrowLeft}{Shift>}{ArrowLeft}{/Shift}{Backspace}',+ );++ expect(canvas.queryByText('Ada')).not.toBeInTheDocument();+ expect(canvas.queryByText('Grace')).not.toBeInTheDocument();++ await userEvent.type(input, '[email protected]');+ await userEvent.click(ccInput);++ expect(canvas.getByText('[email protected]')).toBeVisible();+ },+};++export const ChipMenusReturnFocusToTheInput: Story = {+ args: {+ initialRecipients: [{ address: '[email protected]', displayName: 'Ada' }],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const input = await canvas.findByRole('combobox', { name: 'To' });++ await userEvent.type(input, 'jeff');+ await screen.findByRole('option', { name: /Jeffery Griffin/ });+ await userEvent.click(canvas.getByText('Ada'));++ expect(+ await screen.findByRole('menuitem', { name: 'Add as person' }),+ ).toBeVisible();+ expect(input).toHaveFocus();+ expect(input).toHaveValue('jeff');+ expect(screen.getByRole('menuitem', { name: 'Edit' })).toBeVisible();+ expect(screen.getByRole('menuitem', { name: 'Remove' })).toBeVisible();+ await userEvent.click(screen.getByRole('menuitem', { name: 'Copy email' }));+ await waitFor(() => expect(input).toHaveFocus());++ await userEvent.click(canvas.getByText('Ada'));+ await userEvent.click(+ await screen.findByRole('menuitem', { name: 'Edit' }),+ );++ expect(input).toHaveValue('Ada <[email protected]>');+ expect(input).toHaveFocus();+ await userEvent.keyboard('{Escape}');+ await userEvent.dblClick(canvas.getByText('Ada'));++ expect(input).toHaveValue('Ada <[email protected]>');+ await userEvent.keyboard('{Escape}');+ await userEvent.click(canvas.getByText('Ada'));+ await userEvent.click(+ await screen.findByRole('menuitem', { name: 'Remove' }),+ );++ expect(canvas.queryByText('Ada')).not.toBeInTheDocument();+ await waitFor(() => expect(input).toHaveFocus());+ },+};++export const ModifiedClicksSelectInsteadOfOpeningMenus: Story = {+ args: {+ initialRecipients: [+ { address: '[email protected]', displayName: 'Ada' },+ { address: '[email protected]', displayName: 'Grace' },+ ],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const input = await canvas.findByRole('combobox', { name: 'To' });+ const user = userEvent.setup();++ await user.click(input);+ await user.keyboard('{Meta>}');+ await user.click(canvas.getByText('Ada'));+ await user.keyboard('{/Meta}{Shift>}');+ await user.click(canvas.getByText('Grace'));+ await user.keyboard('{/Shift}');++ expect(canvas.getByText('Ada').closest('[data-selected]')).toHaveAttribute(+ 'data-selected',+ 'true',+ );+ expect(+ canvas.getByText('Grace').closest('[data-selected]'),+ ).toHaveAttribute('data-selected', 'true');++ expect(screen.queryByRole('menu')).not.toBeInTheDocument();+ expect(input).toHaveFocus();+ await user.keyboard('{Backspace}');++ expect(canvas.queryByText('Ada')).not.toBeInTheDocument();+ expect(canvas.queryByText('Grace')).not.toBeInTheDocument();+ },+};++export const AddsRecipientAsPerson: Story = {+ args: {+ initialRecipients: [+ { address: '[email protected]', displayName: 'Ada Lovelace' },+ ],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const input = await canvas.findByRole('combobox', { name: 'To' });++ await userEvent.click(canvas.getByText('Ada Lovelace'));+ await userEvent.click(+ await screen.findByRole('menuitem', { name: 'Add as person' }),+ );++ await waitFor(() => expect(createPerson).toHaveBeenCalledTimes(1));+ expect(createPerson).toHaveBeenCalledWith(+ expect.objectContaining({+ input: expect.objectContaining({+ name: expect.objectContaining({+ firstName: 'Ada',+ lastName: 'Lovelace',+ }),+ emails: expect.objectContaining({+ primaryEmail: '[email protected]',+ }),+ }),+ }),+ );+ expect(screen.queryByRole('menu')).not.toBeInTheDocument();+ await waitFor(() => expect(input).toHaveFocus());+ },+};++export const DragsRecipientsBetweenFields: Story = {+ args: {+ initialRecipients: [{ address: '[email protected]', displayName: 'Ada' }],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const user = userEvent.setup();+ const source = await canvas.findByText('Ada');+ const destination = canvas.getByRole('combobox', { name: 'Cc' });+ const destinationDropTarget = destination.closest('[data-drop-target]');++ await waitFor(() =>+ expect(+ source.closest('[aria-roledescription="draggable"]'),+ ).toHaveAttribute('aria-grabbed', 'false'),+ );+ const sourceBounds = source.getBoundingClientRect();+ const destinationBounds = destination.getBoundingClientRect();+ const sourceCoordinates = {+ clientX: sourceBounds.x + sourceBounds.width / 2,+ clientY: sourceBounds.y + sourceBounds.height / 2,+ };+ const destinationCoordinates = {+ clientX: destinationBounds.x + destinationBounds.width / 2,+ clientY: destinationBounds.y + destinationBounds.height / 2,+ };++ await user.pointer([+ { target: source, keys: '[MouseLeft>]', coords: sourceCoordinates },+ {+ target: source,+ coords: {+ ...sourceCoordinates,+ clientX: sourceCoordinates.clientX + 12,+ },+ },+ ]);++ await screen.findByText(/Picked up draggable item to:[email protected]/);+ await user.pointer({+ target: destination,+ coords: {+ ...destinationCoordinates,+ clientX: destinationCoordinates.clientX - 1,+ },+ });+ await screen.findByText(/was moved over droppable target/);+ await user.pointer({ target: destination, coords: destinationCoordinates });+ await waitFor(() =>+ expect(destinationDropTarget).toHaveAttribute('data-drop-target', 'true'),+ );+ await user.pointer({+ target: destination,+ keys: '[/MouseLeft]',+ coords: destinationCoordinates,+ });++ await waitFor(() =>+ expect(+ within(canvas.getByRole('group', { name: 'cc recipients' })).getByText(+ 'Ada',+ ),+ ).toBeVisible(),+ );+ expect(+ within(canvas.getByRole('group', { name: 'to recipients' })).queryByText(+ 'Ada',+ ),+ ).not.toBeInTheDocument();+ },+};diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/__stories__/StatefulEmailRecipientsFieldInput.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/__stories__/StatefulEmailRecipientsFieldInput.tsxnew file mode 100644index 00000000000..c55ce5e3120--- /dev/null+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/__stories__/StatefulEmailRecipientsFieldInput.tsx@@ -0,0 +1,77 @@+import { DragDropProvider } from '@dnd-kit/react';+import { useState } from 'react';+import { Button } from 'twenty-ui/primitives/input';++import { ComposerFieldRow } from '@/activities/components/ComposerFieldRow';+import { EmailRecipientsFieldInput } from '@/activities/emails/recipients/components/EmailRecipientsFieldInput';+import { useEmailRecipientsDragAndDrop } from '@/activities/emails/recipients/hooks/useEmailRecipientsDragAndDrop';+import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailRecipient';+import { type EmailRecipientDragData } from '@/activities/emails/recipients/types/EmailRecipientDragData';+import { getEmailRecipientKey } from '@/activities/emails/recipients/utils/getEmailRecipientKey';+import { type EmailRecipientsByFieldId } from '@/activities/emails/recipients/utils/moveEmailRecipientsBetweenFields';+import { DND_KIT_PROVIDER_PLUGINS_WITHOUT_DROP_ANIMATION } from '@/ui/utilities/drag-and-drop/constants/DndKitProviderPluginsWithoutDropAnimation';+import { DND_KIT_SENSORS } from '@/ui/utilities/drag-and-drop/constants/DndKitSensors';+import { DragDropItemDndContext } from '@/ui/utilities/drag-and-drop/context/DragDropItemDndContext';++type StatefulEmailRecipientsFieldInputProps = {+ initialRecipients?: EmailRecipient[];+ onSubmit: () => void;+};++export const StatefulEmailRecipientsFieldInput = ({+ initialRecipients = [],+ onSubmit,+}: StatefulEmailRecipientsFieldInputProps) => {+ const [recipientsByFieldId, setRecipientsByFieldId] =+ useState<EmailRecipientsByFieldId>({+ to: initialRecipients,+ cc: [],+ bcc: [],+ });+ const { contextValues, draggedRecipients, handlers } =+ useEmailRecipientsDragAndDrop({+ recipientsByFieldId,+ onRecipientsByFieldIdChange: setRecipientsByFieldId,+ });+ const excludedSuggestionKeys = Object.values(recipientsByFieldId)+ .flat()+ .map((recipient) => getEmailRecipientKey(recipient.address));++ return (+ <DragDropItemDndContext.Provider value={contextValues}>+ <DragDropProvider<EmailRecipientDragData>+ sensors={DND_KIT_SENSORS}+ plugins={DND_KIT_PROVIDER_PLUGINS_WITHOUT_DROP_ANIMATION}+ onDragStart={handlers.onDragStart}+ onDragMove={handlers.onDragMove}+ onDragEnd={handlers.onDragEnd}+ >+ {(['to', 'cc'] as const).map((fieldId) => (+ <div key={fieldId} role="group" aria-label={`${fieldId} recipients`}>+ <ComposerFieldRow label={fieldId === 'to' ? 'To' : 'Cc'}>+ <EmailRecipientsFieldInput+ fieldId={fieldId}+ label={fieldId === 'to' ? 'To' : 'Cc'}+ draggedSourceIndices={+ draggedRecipients?.fieldId === fieldId+ ? draggedRecipients.indices+ : null+ }+ recipients={recipientsByFieldId[fieldId]}+ onChange={(recipients) =>+ setRecipientsByFieldId((currentRecipientsByFieldId) => ({+ ...currentRecipientsByFieldId,+ [fieldId]: recipients,+ }))+ }+ onSubmit={onSubmit}+ excludedSuggestionKeys={excludedSuggestionKeys}+ />+ </ComposerFieldRow>+ </div>+ ))}+ <Button onClick={onSubmit}>Send</Button>+ </DragDropProvider>+ </DragDropItemDndContext.Provider>+ );+};diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/types/EmailRecipientChipDropEdge.ts b/packages/twenty-front/src/modules/activities/emails/recipients/types/EmailRecipientChipDropEdge.tsnew file mode 100644index 00000000000..87c60c18fdb--- /dev/null+++ b/packages/twenty-front/src/modules/activities/emails/recipients/types/EmailRecipientChipDropEdge.ts@@ -0,0 +1 @@+export type EmailRecipientChipDropEdge = 'before' | 'after' | null;diff --git a/packages/twenty-front/src/modules/geo-map/components/PlaceAutocompleteSelect.tsx b/packages/twenty-front/src/modules/geo-map/components/PlaceAutocompleteSelect.tsxindex d3c1c1b6439..da5447ec1a9 100644--- a/packages/twenty-front/src/modules/geo-map/components/PlaceAutocompleteSelect.tsx+++ b/packages/twenty-front/src/modules/geo-map/components/PlaceAutocompleteSelect.tsx@@ -1,82 +1,30 @@import { type PlaceAutocompleteResult } from '@/geo-map/types/PlaceApi';-import { LegacyDropdownContent } from '@/ui/layout/dropdown/components/LegacyDropdownContent';-import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';-import { SelectableList } from '@/ui/layout/selectable-list/components/SelectableList';-import { SelectableListItem } from '@/ui/layout/selectable-list/components/SelectableListItem';-import { styled } from '@linaria/react';-import { useMemo, useRef } from 'react';-import { isDefined } from 'twenty-shared/utils';+import { AutocompleteContent } from '@/ui/input/components/AutocompleteContent';import { Tag } from 'twenty-ui/primitives/data-display';-import { type SelectOption } from 'twenty-ui/primitives/input';-import { ListItem } from 'twenty-ui/primitives/navigation';-const StyledContainer = styled.div<{ fullWidth?: boolean }>`- margin-bottom: 0px !important;- width: ${({ fullWidth }) => (fullWidth ? '100%' : 'auto')};-`;+import { Autocomplete } from 'twenty-ui/primitives/input';-export const PlaceAutocompleteSelect = ({- list,- onChange,- dropdownId,-}: {+type PlaceAutocompleteSelectProps = {list: PlaceAutocompleteResult[];onChange: (placeId: string) => void;- dropdownId: string;-}) => {- const selectContainerRef = useRef<HTMLDivElement>(null);- const options: SelectOption<string>[] = useMemo(() => {- return list?.map<SelectOption<string>>(({ placeId, text }) => ({- label: text,- value: placeId,- }));- }, [list]);-- if (!isDefined(options) || options.length <= 0) return null;-- const selectableItemIdArray = options.map((option) => option.value);+};- return (- <StyledContainer tabIndex={0} ref={selectContainerRef} fullWidth={true}>- <SelectableList- selectableListInstanceId={dropdownId}- selectableItemIdArray={selectableItemIdArray}- focusId={dropdownId}- >- <LegacyDropdownContent- ref={selectContainerRef}- selectDisabled- widthInPixels={345}+export const PlaceAutocompleteSelect = ({+ list,+ onChange,+}: PlaceAutocompleteSelectProps) => (+ <AutocompleteContent width={345}>+ <Autocomplete.List>+ {list.map((place) => (+ <Autocomplete.Item+ key={place.placeId}+ value={place}+ onClick={() => onChange(place.placeId)}>- <DropdownMenuItemsContainer hasMaxHeight>- {options.map((option) => {- return (- <SelectableListItem- key={option.value}- itemId={option.value}- onEnter={() => onChange(option.value)}- >- <ListItem- key={option.value}- onClick={() => onChange(option.value)}- role="option"- aria-selected={false}- selected={false}- indicator="check"- >- <Tag- color={'transparent'}- borderStyle="dashed"- variant={'soft'}- >- {option.label}- </Tag>- </ListItem>- </SelectableListItem>- );- })}- </DropdownMenuItemsContainer>- </LegacyDropdownContent>- </SelectableList>- </StyledContainer>- );-};+ <Tag color="transparent" borderStyle="dashed" variant="soft">+ {place.text}+ </Tag>+ </Autocomplete.Item>+ ))}+ </Autocomplete.List>+ </AutocompleteContent>+);diff --git a/packages/twenty-front/src/modules/geo-map/components/__tests__/PlaceAutocompleteSelect.test.tsx b/packages/twenty-front/src/modules/geo-map/components/__tests__/PlaceAutocompleteSelect.test.tsxdeleted file mode 100644index 97e1d4111ac..00000000000--- a/packages/twenty-front/src/modules/geo-map/components/__tests__/PlaceAutocompleteSelect.test.tsx+++ /dev/null@@ -1,177 +0,0 @@-import { type PlaceAutocompleteResult } from '@/geo-map/types/PlaceApi';--describe('PlaceAutocompleteSelect Component', () => {- describe('component interface', () => {- it('should have correct prop types', () => {- const mockProps = {- list: [] as PlaceAutocompleteResult[],- onChange: jest.fn(),- dropdownId: 'test-dropdown',- };-- expect(mockProps.list).toEqual([]);- expect(typeof mockProps.onChange).toBe('function');- expect(typeof mockProps.dropdownId).toBe('string');- });-- it('should handle empty list prop', () => {- const emptyList: PlaceAutocompleteResult[] = [];- expect(emptyList).toHaveLength(0);- expect(Array.isArray(emptyList)).toBe(true);- });-- it('should handle valid place results', () => {- const validList: PlaceAutocompleteResult[] = [- { placeId: 'place-1', text: 'New York, NY, USA' },- { placeId: 'place-2', text: 'Los Angeles, CA, USA' },- ];-- expect(validList).toHaveLength(2);- expect(validList[0]).toHaveProperty('placeId');- expect(validList[0]).toHaveProperty('text');- expect(typeof validList[0].placeId).toBe('string');- expect(typeof validList[0].text).toBe('string');- });-- it('should handle onChange callback function', () => {- const mockOnChange = jest.fn();- const testPlaceId = 'test-place-id';-- mockOnChange(testPlaceId);-- expect(mockOnChange).toHaveBeenCalledWith(testPlaceId);- expect(mockOnChange).toHaveBeenCalledTimes(1);- });-- it('should handle dropdownId string prop', () => {- const dropdownIds = [- 'test-dropdown',- 'autocomplete-list',- 'place-selector-dropdown',- 'geo-map-dropdown-123',- ];-- dropdownIds.forEach((id) => {- expect(typeof id).toBe('string');- expect(id.length).toBeGreaterThan(0);- });- });- });-- describe('data validation', () => {- it('should validate place result structure', () => {- const validPlaceResult: PlaceAutocompleteResult = {- placeId: 'ChIJD7fiBh9u5kcRYJSMaMOCCwQ',- text: 'Paris, France',- };-- expect(validPlaceResult).toHaveProperty('placeId');- expect(validPlaceResult).toHaveProperty('text');- expect(validPlaceResult.placeId).toBeTruthy();- expect(validPlaceResult.text).toBeTruthy();- });-- it('should handle special characters in place text', () => {- const specialCharacterPlaces: PlaceAutocompleteResult[] = [- { placeId: 'place-1', text: 'São Paulo, Brazil' },- { placeId: 'place-2', text: 'Москва, Россия' },- { placeId: 'place-3', text: '東京, 日本' },- { placeId: 'place-4', text: 'Zürich, Switzerland' },- { placeId: 'place-5', text: "Café de l'Europe, Paris" },- ];-- specialCharacterPlaces.forEach((place) => {- expect(typeof place.text).toBe('string');- expect(place.text.length).toBeGreaterThan(0);- expect(typeof place.placeId).toBe('string');- expect(place.placeId.length).toBeGreaterThan(0);- });- });-- it('should handle empty text values gracefully', () => {- const placesWithEmptyText: PlaceAutocompleteResult[] = [- { placeId: 'place-1', text: '' },- { placeId: 'place-2', text: ' ' },- { placeId: 'place-3', text: 'Valid Location' },- ];-- placesWithEmptyText.forEach((place) => {- expect(typeof place.text).toBe('string');- expect(typeof place.placeId).toBe('string');- expect(place.placeId.length).toBeGreaterThan(0);- });- });-- it('should handle large datasets', () => {- const largeDataset: PlaceAutocompleteResult[] = Array.from(- { length: 1000 },- (_, i) => ({- placeId: `place-${i}`,- text: `Location ${i}`,- }),- );-- expect(largeDataset).toHaveLength(1000);- expect(largeDataset[0].placeId).toBe('place-0');- expect(largeDataset[999].text).toBe('Location 999');- });- });-- describe('callback behavior', () => {- it('should call onChange with correct placeId', () => {- const mockOnChange = jest.fn();- const testPlaceIds = [- 'ChIJD7fiBh9u5kcRYJSMaMOCCwQ',- 'ChIJOwg_06VPwokRYv534QaPC8g',- 'place-with-special-chars-123',- ];-- testPlaceIds.forEach((placeId) => {- mockOnChange(placeId);- });-- expect(mockOnChange).toHaveBeenCalledTimes(3);- testPlaceIds.forEach((placeId) => {- expect(mockOnChange).toHaveBeenCalledWith(placeId);- });- });-- it('should handle multiple onChange calls', () => {- const mockOnChange = jest.fn();- const calls = 10;-- for (let i = 0; i < calls; i++) {- mockOnChange(`place-${i}`);- }-- expect(mockOnChange).toHaveBeenCalledTimes(calls);- });- });-- describe('component requirements', () => {- it('should require all mandatory props', () => {- const requiredProps = ['list', 'onChange', 'dropdownId'];-- requiredProps.forEach((prop) => {- expect(typeof prop).toBe('string');- expect(prop.length).toBeGreaterThan(0);- });- });-- it('should handle dropdown ID formats', () => {- const validDropdownIds = [- 'dropdown-1',- 'place-autocomplete-dropdown',- 'geo-map-selector',- 'test_dropdown_123',- 'dropdown',- ];-- validDropdownIds.forEach((id) => {- expect(typeof id).toBe('string');- expect(id.length).toBeGreaterThan(0);- expect(id).not.toMatch(/\s/);- });- });- });-});diff --git a/packages/twenty-front/src/modules/navigation-menu-item/edit/components/__stories__/NavigationMenuItemEditable.stories.tsx b/packages/twenty-front/src/modules/navigation-menu-item/edit/components/__stories__/NavigationMenuItemEditable.stories.tsxindex 46c480406f6..c128e54fba1 100644--- a/packages/twenty-front/src/modules/navigation-menu-item/edit/components/__stories__/NavigationMenuItemEditable.stories.tsx+++ b/packages/twenty-front/src/modules/navigation-menu-item/edit/components/__stories__/NavigationMenuItemEditable.stories.tsx@@ -174,9 +174,9 @@ export const PreviewInsertion: Story = {await userEvent.click(await body.findByText('Object'));await expect(await canvas.findByText('Select a menu item')).toBeVisible();await userEvent.keyboard('{Escape}');- await expect(- canvas.queryByText('Select a menu item'),- ).not.toBeInTheDocument();+ await waitFor(() =>+ expect(canvas.queryByText('Select a menu item')).not.toBeInTheDocument(),+ );await userEvent.pointer({target: await canvas.findByText('Docs'),keys: '[MouseRight]',@@ -189,9 +189,9 @@ export const PreviewInsertion: Story = {).toEqual(['Select a menu item', 'Docs', 'Status']);await userEvent.click(await body.findByText('Link'));await expect(await body.findByDisplayValue('Twenty')).toBeVisible();- await expect(- canvas.queryByText('Select a menu item'),- ).not.toBeInTheDocument();+ await waitFor(() =>+ expect(canvas.queryByText('Select a menu item')).not.toBeInTheDocument(),+ );await userEvent.keyboard('{Escape}');},};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/AddressFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/AddressFieldInput.tsxindex a61411c0aef..a8fca03d2e0 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/AddressFieldInput.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/AddressFieldInput.tsx@@ -52,10 +52,13 @@ export const AddressFieldInput = () => {onEscape?.({ newValue: convertToAddress(newAddress) });};- const handleClickOutside = (- event: MouseEvent | TouchEvent,- newAddress: FieldAddressDraftValue,- ) => {+ const handleClickOutside = ({+ event,+ newAddress,+ }: {+ event: MouseEvent | TouchEvent;+ newAddress: FieldAddressDraftValue;+ }) => {onClickOutside?.({ newValue: convertToAddress(newAddress), event });};diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/AddressFieldInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/AddressFieldInput.stories.tsxindex 93b89547e54..0f9fcfc5503 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/AddressFieldInput.stories.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/AddressFieldInput.stories.tsx@@ -5,19 +5,28 @@ import {} from '@storybook/react-vite';import { expect, fn, userEvent, waitFor, within } from 'storybook/test';+import { MAIN_CONTEXT_STORE_INSTANCE_ID } from '@/context-store/constants/MainContextStoreInstanceId';import { FieldContext } from '@/object-record/record-field/ui/contexts/FieldContext';import { useAddressField } from '@/object-record/record-field/ui/meta-types/hooks/useAddressField';import { RecordFieldComponentInstanceContext } from '@/object-record/record-field/ui/states/contexts/RecordFieldComponentInstanceContext';import { type FieldAddressDraftValue } from '@/object-record/record-field/ui/types/FieldInputDraftValue';import { RECORD_TABLE_CELL_INPUT_ID_PREFIX } from '@/object-record/record-table/constants/RecordTableCellInputIdPrefix';import { getRecordFieldInputInstanceId } from '@/object-record/utils/getRecordFieldInputId';+import { AddressFieldInput } from '@/object-record/record-field/ui/meta-types/input/components/AddressFieldInput';import {- AddressInput,- type AddressInputProps,-} from '@/ui/field/input/components/AddressInput';+ FieldInputEventContext,+ type FieldInputEventContextType,+} from '@/object-record/record-field/ui/contexts/FieldInputEventContext';+import {+ WorkspaceSurfaceContext,+ type WorkspaceSurfaceContextValue,+} from '@/ui/layout/contexts/WorkspaceSurfaceContext';+import { Button } from 'twenty-ui/primitives/input';+import { delay, graphql, HttpResponse } from 'msw';import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePushFocusItemToFocusStack';import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';import { useEffect } from 'react';+import { isDefined } from 'twenty-shared/utils';import { FieldMetadataType } from '~/generated-metadata/graphql';const AddressValueSetterEffect = ({@@ -25,18 +34,30 @@ const AddressValueSetterEffect = ({}: {value: FieldAddressDraftValue;}) => {- const { setFieldValue } = useAddressField();+ const { setFieldValue, setDraftValue } = useAddressField();useEffect(() => {setFieldValue(value);- }, [setFieldValue, value]);+ setDraftValue(value);+ }, [setDraftValue, setFieldValue, value]);return <></>;};-type AddressInputWithContextProps = AddressInputProps & {- value: string;+const InitializedAddressFieldInput = () => {+ const { draftValue } = useAddressField();++ if (!isDefined(draftValue)) {+ return null;+ }++ return <AddressFieldInput />;+};++type AddressInputWithContextProps = FieldInputEventContextType & {+ value: FieldAddressDraftValue;recordId?: string;+ surface?: WorkspaceSurfaceContextValue;};const AddressInputWithContext = ({@@ -47,6 +68,11 @@ const AddressInputWithContext = ({onClickOutside,onTab,onShiftTab,+ surface = {+ type: 'main',+ instanceId: MAIN_CONTEXT_STORE_INSTANCE_ID,+ ownsRouteLocation: true,+ },}: AddressInputWithContextProps) => {const { pushFocusItemToFocusStack } = usePushFocusItemToFocusStack();@@ -67,7 +93,7 @@ const AddressInputWithContext = ({}, [instanceId, pushFocusItemToFocusStack]);return (- <div>+ <WorkspaceSurfaceContext.Provider value={surface}><RecordFieldComponentInstanceContext.Providervalue={{instanceId: instanceId,@@ -92,19 +118,15 @@ const AddressInputWithContext = ({}}><AddressValueSetterEffect value={value} />- <AddressInput- instanceId={instanceId}- onEnter={onEnter}- onEscape={onEscape}- onClickOutside={onClickOutside}- value={value}- onTab={onTab}- onShiftTab={onShiftTab}- />+ <FieldInputEventContext.Provider+ value={{ onEnter, onEscape, onClickOutside, onTab, onShiftTab }}+ >+ <InitializedAddressFieldInput />+ </FieldInputEventContext.Provider></FieldContext.Provider>- <div data-testid="data-field-input-click-outside-div" />+ <Button onClick={outsideButtonClickJestFn}>Outside</Button></RecordFieldComponentInstanceContext.Provider>- </div>+ </WorkspaceSurfaceContext.Provider>);};@@ -113,6 +135,8 @@ const escapeJestfn = fn();const clickOutsideJestFn = fn();const tabJestFn = fn();const shiftTabJestFn = fn();+const autocompleteResponseJestFn = fn();+const outsideButtonClickJestFn = fn();const clearMocksDecorator: Decorator = (Story, context) => {if (context.parameters.clearMocks === true) {@@ -121,6 +145,8 @@ const clearMocksDecorator: Decorator = (Story, context) => {clickOutsideJestFn.mockClear();tabJestFn.mockClear();shiftTabJestFn.mockClear();+ autocompleteResponseJestFn.mockClear();+ outsideButtonClickJestFn.mockClear();}return <Story />;};@@ -155,6 +181,46 @@ const meta: Meta = {decorators: [clearMocksDecorator],parameters: {clearMocks: true,+ mockingDate: null,+ msw: {+ handlers: [+ graphql.query('GetAutoCompleteAddress', ({ variables }) => {+ autocompleteResponseJestFn(variables.address);++ if (variables.address.includes('Nowhere')) {+ return HttpResponse.json({ data: { getAutoCompleteAddress: [] } });+ }++ return HttpResponse.json({+ data: {+ getAutoCompleteAddress: [+ {+ text: variables.isFieldCity+ ? 'Paris, France'+ : '10 Rue de Rivoli, Paris',+ placeId: variables.isFieldCity ? 'paris' : 'rivoli',+ },+ ],+ },+ });+ }),+ graphql.query('GetAddressDetails', ({ variables }) =>+ HttpResponse.json({+ data: {+ getAddressDetails: {+ street:+ variables.placeId === 'paris' ? null : '10 Rue de Rivoli',+ state: 'Île-de-France',+ postcode: '75001',+ city: 'Paris',+ country: 'FR',+ location: { lat: 48.8566, lng: 2.3522 },+ },+ },+ }),+ ),+ ],+ },},};@@ -170,7 +236,9 @@ export const Enter: Story = {expect(enterJestFn).toHaveBeenCalledTimes(0);- const addressInput = await canvas.findByDisplayValue('Address 1');+ const addressInput = await canvas.findByRole('combobox', {+ name: 'Address 1',+ });await userEvent.click(addressInput);@@ -181,3 +249,260 @@ export const Enter: Story = {});},};++export const AutofillsAndPersistsAddress: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const input = canvas.getByRole('combobox', { name: 'Address 1' });++ await userEvent.clear(input);+ await userEvent.type(input, '10 Rue');+ await screen.findByRole('option', { name: '10 Rue de Rivoli, Paris' });+ expect(input).toHaveFocus();+ await userEvent.click(input);+ expect(screen.getByRole('listbox')).toBeVisible();+ await userEvent.keyboard('{Enter}');++ await waitFor(() => {+ expect(input).toHaveValue('10 Rue de Rivoli');+ expect(canvas.getByRole('combobox', { name: 'City' })).toHaveValue(+ 'Paris',+ );+ expect(canvas.getByRole('textbox', { name: 'State' })).toHaveValue(+ 'Île-de-France',+ );+ expect(canvas.getByRole('textbox', { name: 'Post Code' })).toHaveValue(+ '75001',+ );+ expect(input).toHaveFocus();+ expect(enterJestFn).not.toHaveBeenCalled();+ });++ await userEvent.keyboard('{Enter}');++ await waitFor(() => {+ expect(enterJestFn).toHaveBeenCalledWith({+ newValue: {+ addressStreet1: '10 Rue de Rivoli',+ addressStreet2: null,+ addressCity: 'Paris',+ addressState: 'Île-de-France',+ addressPostcode: '75001',+ addressCountry: 'France',+ addressLat: 48.8566,+ addressLng: 2.3522,+ },+ });+ });+ },+};++export const SelectsCityWithoutReplacingStreet: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const cityInput = canvas.getByRole('combobox', { name: 'City' });++ await userEvent.type(cityInput, 'Par');+ await userEvent.click(+ await screen.findByRole('option', { name: 'Paris, France' }),+ );++ await waitFor(() => {+ expect(cityInput).toHaveValue('Paris');+ expect(cityInput).toHaveFocus();+ expect(canvas.getByRole('combobox', { name: 'Address 1' })).toHaveValue(+ 'Address 1',+ );+ expect(clickOutsideJestFn).not.toHaveBeenCalled();+ });+ },+};++export const KeepsSelectionWhileDetailsLoad: Story = {+ parameters: {+ msw: {+ handlers: [+ graphql.query('GetAddressDetails', async () => {+ await delay(800);++ return HttpResponse.json({+ data: {+ getAddressDetails: {+ street: '10 Rue de Rivoli',+ state: 'Île-de-France',+ postcode: '75001',+ city: 'Paris',+ country: 'FR',+ location: { lat: 48.8566, lng: 2.3522 },+ },+ },+ });+ }),+ ...(meta.parameters?.msw?.handlers ?? []),+ ],+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const input = canvas.getByRole('combobox', { name: 'Address 1' });+ const outsideButton = canvas.getByRole('button', { name: 'Outside' });++ await userEvent.type(input, ' Rue');+ await userEvent.click(+ await screen.findByRole('option', { name: '10 Rue de Rivoli, Paris' }),+ );++ expect(screen.getByRole('listbox')).toBeVisible();++ await userEvent.click(outsideButton);++ await waitFor(() => {+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ expect(clickOutsideJestFn).not.toHaveBeenCalled();+ expect(outsideButtonClickJestFn).not.toHaveBeenCalled();+ });++ await waitFor(+ () => {+ expect(input).toHaveValue('10 Rue de Rivoli');+ expect(canvas.getByRole('combobox', { name: 'City' })).toHaveValue(+ 'Paris',+ );+ },+ { timeout: 3000 },+ );++ await userEvent.click(outsideButton);++ await waitFor(() => {+ expect(clickOutsideJestFn).toHaveBeenCalledWith(+ expect.objectContaining({+ newValue: expect.objectContaining({+ addressStreet1: '10 Rue de Rivoli',+ addressCity: 'Paris',+ addressPostcode: '75001',+ }),+ }),+ );+ });+ },+};++export const CancelsSuggestionsBeforePersisting: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const input = canvas.getByRole('combobox', { name: 'Address 1' });+ const outsideButton = canvas.getByRole('button', { name: 'Outside' });++ await userEvent.type(input, ' Rue');+ await screen.findByRole('option', { name: '10 Rue de Rivoli, Paris' });+ await userEvent.click(outsideButton);++ await waitFor(() => {+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ expect(input).toHaveValue('Address 1 Rue');+ expect(clickOutsideJestFn).not.toHaveBeenCalled();+ expect(outsideButtonClickJestFn).not.toHaveBeenCalled();+ });++ await userEvent.click(outsideButton);++ await waitFor(() => {+ expect(clickOutsideJestFn).toHaveBeenCalledWith(+ expect.objectContaining({+ newValue: expect.objectContaining({+ addressStreet1: 'Address 1 Rue',+ }),+ }),+ );+ });+ },+};++export const IgnoresArrowKeysWithoutSuggestions: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const input = canvas.getByRole('combobox', { name: 'Address 1' });++ await userEvent.type(input, ' Nowhere');+ await waitFor(() =>+ expect(autocompleteResponseJestFn).toHaveBeenCalledWith(+ 'Address 1 Nowhere',+ ),+ );+ await userEvent.keyboard('{ArrowDown}');++ expect(input).toHaveAttribute('aria-expanded', 'false');+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();++ await userEvent.keyboard('{Escape}');++ await waitFor(() =>+ expect(escapeJestfn).toHaveBeenCalledWith({+ newValue: expect.objectContaining({+ addressStreet1: 'Address 1 Nowhere',+ }),+ }),+ );+ },+};++export const CountryOnMainSurface: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);++ await userEvent.click(canvas.getByText('No country'));+ await userEvent.type(screen.getByPlaceholderText('Search'), 'France');+ await userEvent.click(await screen.findByText('France'));++ await waitFor(() => {+ expect(canvas.getByText('France')).toBeVisible();+ expect(clickOutsideJestFn).not.toHaveBeenCalled();+ });+ },+};++export const CountryOnSidePanelSurface: Story = {+ args: {+ surface: {+ type: 'side-panel',+ instanceId: 'side-panel-page',+ ownsRouteLocation: true,+ },+ },+ play: CountryOnMainSurface.play,+};++export const CountryOpensWithEnter: Story = {+ args: CountryOnSidePanelSurface.args,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);+ const trigger = canvas.getByRole('button', { name: 'Country' });++ trigger.focus();+ await userEvent.keyboard('{Enter}');++ expect(enterJestFn).not.toHaveBeenCalled();++ const countryDialog = await screen.findByRole('dialog', {+ name: 'Country',+ });++ await waitFor(() => expect(countryDialog).toBeVisible());+ await userEvent.type(screen.getByPlaceholderText('Search'), 'France');+ await userEvent.keyboard('{Enter}');++ await waitFor(() => {+ expect(canvas.getByText('France')).toBeVisible();+ expect(enterJestFn).not.toHaveBeenCalled();+ expect(clickOutsideJestFn).not.toHaveBeenCalled();+ });+ },+};diff --git a/packages/twenty-front/src/modules/side-panel/pages/__stories__/SidePanelComposerPages.stories.tsx b/packages/twenty-front/src/modules/side-panel/pages/__stories__/SidePanelComposerPages.stories.tsxindex b9095f98a09..c37652f0922 100644--- a/packages/twenty-front/src/modules/side-panel/pages/__stories__/SidePanelComposerPages.stories.tsx+++ b/packages/twenty-front/src/modules/side-panel/pages/__stories__/SidePanelComposerPages.stories.tsx@@ -2,7 +2,7 @@ import { type Meta, type StoryObj } from '@storybook/react-vite';import { useStore } from 'jotai';import { HttpResponse, graphql } from 'msw';import { useEffect, useState } from 'react';-import { expect, userEvent, within } from 'storybook/test';+import { expect, userEvent, waitFor, within } from 'storybook/test';import { CoreObjectNameSingular } from 'twenty-shared/types';import { ComponentDecorator } from 'twenty-ui/testing';@@ -164,6 +164,7 @@ const meta = {await mockedApolloClient.clearStore();},parameters: {+ mockingDate: null,container: { width: 480, height: 720 },msw: {handlers: [@@ -227,8 +228,25 @@ type Story = StoryObj<typeof meta>;export const CalendarEvent: Story = {args: { composer: 'calendar-event' },+ parameters: {+ msw: {+ handlers: [+ graphql.query('GetAutoCompleteAddress', () =>+ HttpResponse.json({+ data: {+ getAutoCompleteAddress: [+ { text: 'Apple Park, Cupertino', placeId: 'apple-park' },+ ],+ },+ }),+ ),+ ...meta.parameters.msw.handlers,+ ],+ },+ },play: async ({ canvasElement }) => {const canvas = within(canvasElement);+ const screen = within(canvasElement.ownerDocument.body);expect(await canvas.findByText('Kimberly Gordon')).toBeVisible();expect(canvas.getByText('[email protected]')).toBeVisible();@@ -242,6 +260,21 @@ export const CalendarEvent: Story = {'Apple Park',);+ const locationSuggestion = await screen.findByRole(+ 'option',+ { name: 'Apple Park, Cupertino' },+ { timeout: 5000 },+ );++ await waitFor(() => expect(locationSuggestion).toBeVisible());+ await userEvent.keyboard('{Escape}');+ await waitFor(() =>+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument(),+ );++ expect(canvas.getByPlaceholderText('Add a location')).toHaveValue(+ 'Apple Park',+ );expect(canvas.getByRole('button', { name: /^Create event/ })).toBeEnabled();},};@@ -308,5 +341,32 @@ export const Email: Story = {canvas.getByDisplayValue('Follow-up from our meeting'),).toBeVisible();expect(canvas.getByRole('button', { name: /^Send/ })).toBeEnabled();++ const screen = within(canvasElement.ownerDocument.body);+ const input = canvas.getByRole('combobox', { name: 'To' });++ await userEvent.type(input, '[email protected]');++ const suggestion = await screen.findByRole(+ 'option',+ { name: /[email protected]/ },+ { timeout: 5000 },+ );++ expect(input).toHaveFocus();+ await userEvent.click(suggestion);++ expect(canvas.getByText('[email protected]')).toBeVisible();+ expect(input).toHaveFocus();+ await userEvent.click(canvas.getByText('[email protected]'));+ await userEvent.click(+ await screen.findByRole('menuitem', { name: 'Remove' }),+ );++ expect(+ canvas.queryByText('[email protected]'),+ ).not.toBeInTheDocument();+ await waitFor(() => expect(input).toHaveFocus());+ expect(canvas.getByText('Kimberly Gordon')).toBeVisible();},};diff --git a/packages/twenty-front/src/modules/ui/field/input/components/AddressInput.tsx b/packages/twenty-front/src/modules/ui/field/input/components/AddressInput.tsxindex 717743e5e85..7e686a4ab22 100644--- a/packages/twenty-front/src/modules/ui/field/input/components/AddressInput.tsx+++ b/packages/twenty-front/src/modules/ui/field/input/components/AddressInput.tsx@@ -1,25 +1,24 @@import { styled } from '@linaria/react';+import { atom, useAtomValue, useStore } from 'jotai';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { PlaceAutocompleteSelect } from '@/geo-map/components/PlaceAutocompleteSelect';import { SELECT_AUTOCOMPLETE_LIST_DROPDOWN_ID } from '@/geo-map/constants/SelectAutocompleteListDropDownId';import { useRegisterInputEvents } from '@/object-record/record-field/ui/meta-types/input/hooks/useRegisterInputEvents';import { type FieldAddressDraftValue } from '@/object-record/record-field/ui/types/FieldInputDraftValue';-import { type FieldAddressValue } from '@/object-record/record-field/ui/types/FieldMetadata';import { TextInput } from '@/ui/input/components/TextInput';-import { TEXT_INPUT_CLICK_OUTSIDE_ID } from '@/ui/input/components/constants/TextInputClickOutsideId';+import { AutocompleteRoot } from '@/ui/input/components/AutocompleteRoot';+import { type AddressInputProps } from '@/ui/field/input/types/AddressInputProps';import { CountrySelect } from '@/ui/input/components/internal/country/components/CountrySelect';-import { SELECT_COUNTRY_DROPDOWN_ID } from '@/ui/input/components/internal/country/constants/SelectCountryDropdownId';-import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';-import { activeDropdownFocusIdState } from '@/ui/layout/dropdown/states/activeDropdownFocusIdState';-import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';-import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';+import { Autocomplete } from 'twenty-ui/primitives/input';+import { isDefined } from 'twenty-shared/utils';import { MOBILE_VIEWPORT } from 'twenty-ui/theme';+import { turnIntoEmptyStringIfWhitespacesOnly } from '~/utils/string/turnIntoEmptyStringIfWhitespacesOnly';import { t } from '@lingui/core/macro';import { type AllowedAddressSubField } from 'twenty-shared/types';import { useAddressAutocomplete } from '@/ui/field/input/hooks/useAddressAutocomplete';+import { useAddressInputClickOutside } from '@/ui/field/input/hooks/useAddressInputClickOutside';import { useCountryUtils } from '@/ui/field/input/hooks/useCountryUtils';import { useFocusManagement } from '@/ui/field/input/hooks/useFocusManagement';@@ -60,22 +59,6 @@ const StyledInputWithDropdownContainer = styled.div`width: 100%;`;-export type AddressInputProps = {- instanceId: string;- value: FieldAddressValue;- onTab: (newAddress: FieldAddressDraftValue) => void;- onShiftTab: (newAddress: FieldAddressDraftValue) => void;- onEnter: (newAddress: FieldAddressDraftValue) => void;- onEscape: (newAddress: FieldAddressDraftValue) => void;- onClickOutside: (- event: MouseEvent | TouchEvent,- newAddress: FieldAddressDraftValue,- ) => void;- clearable?: boolean;- onChange?: (updatedValue: FieldAddressDraftValue) => void;- subFields?: AllowedAddressSubField[] | null;-};-export const AddressInput = ({instanceId,value,@@ -87,7 +70,16 @@ export const AddressInput = ({onChange,subFields,}: AddressInputProps) => {- const [internalValue, setInternalValue] = useState(value);+ const store = useStore();+ const [internalValueAtom] = useState(() =>+ atom<FieldAddressDraftValue>(value),+ );+ const internalValue = useAtomValue(internalValueAtom);+ const setInternalValue = useCallback(+ (updatedValue: FieldAddressDraftValue) =>+ store.set(internalValueAtom, updatedValue),+ [internalValueAtom, store],+ );const addressStreet1InputRef = useRef<HTMLInputElement>(null);const addressStreet2InputRef = useRef<HTMLInputElement>(null);@@ -162,6 +154,7 @@ export const AddressInput = ({},[internalValue,+ setInternalValue,onChange,findCountryCodeByCountryName,typeOfAddressForAutocomplete,@@ -172,7 +165,7 @@ export const AddressInput = ({);const handlePlaceSelection = useCallback(- (placeId: string) => {+ async (placeId: string) => {const placeAutocomplete = placeAutocompleteData?.find((place) => place.placeId === placeId,);@@ -184,21 +177,30 @@ export const AddressInput = ({? placeAutocomplete.text: undefined;- autoFillInputsFromPlaceDetails(placeId, token, text, internalValue);+ const updatedAddress = await autoFillInputsFromPlaceDetails({+ placeId,+ token,+ addressStreet1: text,+ getInternalValue: () => store.get(internalValueAtom),+ });++ if (!isDefined(updatedAddress)) {+ return;+ }++ setInternalValue(updatedAddress);},[placeAutocompleteData,tokenForPlaceApi,typeOfAddressForAutocomplete,autoFillInputsFromPlaceDetails,- internalValue,+ internalValueAtom,+ setInternalValue,+ store,],);- const handleClickOutside = useCallback(() => {- closeDropdownOfAutocomplete();- }, [closeDropdownOfAutocomplete]);-const handleEnter = useCallback(() => {onEnter(internalValue);closeDropdownOfAutocomplete();@@ -211,7 +213,7 @@ export const AddressInput = ({const handleOutsideClick = useCallback((event: MouseEvent | TouchEvent) => {- onClickOutside?.(event, internalValue);+ onClickOutside?.({ event, newAddress: internalValue });closeDropdownOfAutocomplete();},[onClickOutside, internalValue, closeDropdownOfAutocomplete],@@ -227,91 +229,69 @@ export const AddressInput = ({onShiftTab: handleShiftTab,});- const activeDropdownFocusId = useAtomStateValue(activeDropdownFocusIdState);-- useListenClickOutside({- refs: [wrapperRef],- callback: (event) => {- if (- activeDropdownFocusId === SELECT_COUNTRY_DROPDOWN_ID ||- activeDropdownFocusId === SELECT_AUTOCOMPLETE_LIST_DROPDOWN_ID- ) {- return;- }-- event.stopImmediatePropagation();- handleOutsideClick(event);- },- enabled: isDefined(onClickOutside),- listenerId: 'address-input',+ useAddressInputClickOutside({+ inputRef: wrapperRef,+ onClickOutside: handleOutsideClick,});useEffect(() => {setInternalValue(value);- }, [value]);-- const validAutocompleteData = useMemo(- () =>- isNonEmptyArray(placeAutocompleteData) ? placeAutocompleteData : null,- [placeAutocompleteData],- );-- const renderInputWithAutocomplete = (- inputElement: React.ReactNode | null,- fieldType: 'addressStreet1' | 'addressCity',- ) => {- const shouldShowDropdown =- validAutocompleteData && typeOfAddressForAutocomplete === fieldType;-- if (!shouldShowDropdown) {- return inputElement;- }-- return (- <StyledInputWithDropdownContainer>- <Dropdown- dropdownId={SELECT_AUTOCOMPLETE_LIST_DROPDOWN_ID}- dropdownPlacement="bottom-start"- excludedClickOutsideIds={[- TEXT_INPUT_CLICK_OUTSIDE_ID,- SELECT_AUTOCOMPLETE_LIST_DROPDOWN_ID,- ]}- disableClickForClickableComponent={true}- onClickOutside={handleClickOutside}- clickableComponent={inputElement}- dropdownComponents={- <PlaceAutocompleteSelect- list={validAutocompleteData}- onChange={handlePlaceSelection}- dropdownId={SELECT_AUTOCOMPLETE_LIST_DROPDOWN_ID}+ }, [setInternalValue, value]);++ const renderInputWithAutocomplete = ({+ fieldType,+ label,+ autoFocus = false,+ }: {+ fieldType: 'addressStreet1' | 'addressCity';+ label: string;+ autoFocus?: boolean;+ }) => (+ <StyledInputWithDropdownContainer>+ <AutocompleteRoot+ dropdownId={SELECT_AUTOCOMPLETE_LIST_DROPDOWN_ID}+ enabled={typeOfAddressForAutocomplete === fieldType}+ items={placeAutocompleteData}+ itemToStringValue={(place) => place.text}+ value={internalValue[fieldType] ?? ''}+ openOnValueChange={false}+ closeOnItemPress={false}+ onValueChange={(updatedValue) =>+ getChangeHandler(fieldType)(+ turnIntoEmptyStringIfWhitespacesOnly(updatedValue),+ )+ }+ onClose={closeDropdownOfAutocomplete}+ >+ <Autocomplete.Input+ aria-label={label}+ render={(inputProps) => (+ <TextInput+ inputProps={{ ...inputProps, className: undefined }}+ autoFocus={autoFocus}+ ref={inputRefs[fieldType]}+ label={label}+ fullWidth+ onFocus={getFocusHandler(fieldType)}/>- }+ )}+ />+ <PlaceAutocompleteSelect+ list={placeAutocompleteData}+ onChange={handlePlaceSelection}/>- </StyledInputWithDropdownContainer>- );- };+ </AutocompleteRoot>+ </StyledInputWithDropdownContainer>+ );return (<StyledAddressContainer ref={wrapperRef}>{isFieldInputInSubFieldsAddress('addressStreet1') &&- renderInputWithAutocomplete(- <TextInput- autoFocus- value={internalValue.addressStreet1 ?? ''}- ref={inputRefs.addressStreet1}- label={t`Address 1`}- fullWidth- onChange={getChangeHandler('addressStreet1')}- onFocus={getFocusHandler('addressStreet1')}- textClickOutsideId={- validAutocompleteData &&- typeOfAddressForAutocomplete === 'addressStreet1'- ? TEXT_INPUT_CLICK_OUTSIDE_ID- : undefined- }- />,- 'addressStreet1',- )}+ renderInputWithAutocomplete({+ fieldType: 'addressStreet1',+ label: t`Address 1`,+ autoFocus: true,+ })}{isFieldInputInSubFieldsAddress('addressStreet2') && (<TextInputvalue={internalValue.addressStreet2 ?? ''}@@ -324,23 +304,10 @@ export const AddressInput = ({)}<StyledHalfRowContainer>{isFieldInputInSubFieldsAddress('addressCity') &&- renderInputWithAutocomplete(- <TextInput- value={internalValue.addressCity ?? ''}- ref={inputRefs.addressCity}- label={t`City`}- fullWidth- onChange={getChangeHandler('addressCity')}- onFocus={getFocusHandler('addressCity')}- textClickOutsideId={- validAutocompleteData &&- typeOfAddressForAutocomplete === 'addressCity'- ? TEXT_INPUT_CLICK_OUTSIDE_ID- : undefined- }- />,- 'addressCity',- )}+ renderInputWithAutocomplete({+ fieldType: 'addressCity',+ label: t`City`,+ })}{isFieldInputInSubFieldsAddress('addressState') && (<TextInputvalue={internalValue.addressState ?? ''}diff --git a/packages/twenty-front/src/modules/ui/field/input/components/__tests__/AddressInput.surfaceScope.test.tsx b/packages/twenty-front/src/modules/ui/field/input/components/__tests__/AddressInput.surfaceScope.test.tsxdeleted file mode 100644index a5435705605..00000000000--- a/packages/twenty-front/src/modules/ui/field/input/components/__tests__/AddressInput.surfaceScope.test.tsx+++ /dev/null@@ -1,127 +0,0 @@-import { act, render, screen } from '@testing-library/react';-import userEvent from '@testing-library/user-event';-import { i18n } from '@lingui/core';-import { I18nProvider } from '@lingui/react';-import { type ReactNode } from 'react';--import { AddressInput } from '@/ui/field/input/components/AddressInput';-import {- WorkspaceSurfaceContext,- type WorkspaceSurfaceContextValue,-} from '@/ui/layout/contexts/WorkspaceSurfaceContext';-import { focusStackState } from '@/ui/utilities/focus/states/focusStackState';-import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';-import { DEFAULT_GLOBAL_HOTKEYS_CONFIG } from '@/ui/utilities/hotkey/constants/DefaultGlobalHotkeysConfig';-import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';--const ADDRESS_INPUT_INSTANCE_ID = 'address-input';--const SIDE_PANEL_SURFACE: WorkspaceSurfaceContextValue = {- type: 'side-panel',- instanceId: 'side-panel-page',- ownsRouteLocation: true,-};--const EMPTY_ADDRESS = {- addressStreet1: '',- addressStreet2: null,- addressCity: null,- addressState: null,- addressCountry: null,- addressPostcode: null,- addressLat: null,- addressLng: null,-};--const renderAddressInput = (surface?: WorkspaceSurfaceContextValue) => {- const onChange = jest.fn();- const onClickOutside = jest.fn();- const onEnter = jest.fn();- const BaseWrapper = getJestMetadataAndApolloMocksWrapper({- onInitializeJotaiStore: (store) => {- store.set(focusStackState.atom, [- {- focusId: ADDRESS_INPUT_INSTANCE_ID,- componentInstance: {- componentType: FocusComponentType.OPENED_FIELD_INPUT,- componentInstanceId: ADDRESS_INPUT_INSTANCE_ID,- },- globalHotkeysConfig: DEFAULT_GLOBAL_HOTKEYS_CONFIG,- },- ]);- },- });-- const Wrapper = ({ children }: { children: ReactNode }) => (- <I18nProvider i18n={i18n}>- <BaseWrapper>- {surface ? (- <WorkspaceSurfaceContext.Provider value={surface}>- {children}- </WorkspaceSurfaceContext.Provider>- ) : (- children- )}- </BaseWrapper>- </I18nProvider>- );-- render(- <AddressInput- instanceId={ADDRESS_INPUT_INSTANCE_ID}- value={EMPTY_ADDRESS}- onTab={jest.fn()}- onShiftTab={jest.fn()}- onEnter={onEnter}- onEscape={jest.fn()}- onClickOutside={onClickOutside}- onChange={onChange}- />,- { wrapper: Wrapper },- );-- return { onChange, onClickOutside, onEnter };-};--describe('AddressInput country picker on a side panel surface', () => {- it.each([- ['main', undefined],- ['side-panel', SIDE_PANEL_SURFACE],- ])('selects a country with a click on %s', async (_, surface) => {- const user = userEvent.setup();- const { onChange, onClickOutside } = renderAddressInput(surface);-- await user.click(screen.getByText('No country'));- await user.type(screen.getByPlaceholderText('Search'), 'France');- await user.click(await screen.findByText('France'));-- expect(onChange).toHaveBeenCalledWith(- expect.objectContaining({ addressCountry: 'France' }),- );- expect(onClickOutside).not.toHaveBeenCalled();- });-- it('opens the country picker with Enter without submitting the address editor', async () => {- const user = userEvent.setup();- const { onChange, onClickOutside, onEnter } =- renderAddressInput(SIDE_PANEL_SURFACE);- const trigger = screen.getByRole('button', { name: 'Country' });-- act(() => trigger.focus());- await user.keyboard('{Enter}');-- expect(onEnter).not.toHaveBeenCalled();- expect(- await screen.findByRole('dialog', { name: 'Country' }),- ).toBeVisible();-- await user.type(screen.getByPlaceholderText('Search'), 'France');- await user.keyboard('{Enter}');-- expect(onChange).toHaveBeenCalledWith(- expect.objectContaining({ addressCountry: 'France' }),- );- expect(onEnter).not.toHaveBeenCalled();- expect(onClickOutside).not.toHaveBeenCalled();- });-});diff --git a/packages/twenty-front/src/modules/ui/field/input/hooks/__tests__/useAddressAutocomplete.test.tsx b/packages/twenty-front/src/modules/ui/field/input/hooks/__tests__/useAddressAutocomplete.test.tsxindex 2019394f334..b1215e153a7 100644--- a/packages/twenty-front/src/modules/ui/field/input/hooks/__tests__/useAddressAutocomplete.test.tsx+++ b/packages/twenty-front/src/modules/ui/field/input/hooks/__tests__/useAddressAutocomplete.test.tsx@@ -1,4 +1,5 @@import { useGetPlaceApiData } from '@/geo-map/hooks/useGetPlaceApiData';+import { type PlaceDetailsResult } from '@/geo-map/types/PlaceApi';import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';import { useOpenDropdown } from '@/ui/layout/dropdown/hooks/useOpenDropdown';import { act, renderHook } from '@testing-library/react';@@ -95,6 +96,82 @@ describe('useAddressAutocomplete', () => {expect(mockCloseDropdown).toHaveBeenCalled();});+ it('should keep edits made while place details are loading', async () => {+ const mockOnChange = jest.fn();+ let internalValue = {+ addressStreet1: '10 Rue',+ addressStreet2: null as string | null,+ addressCity: null,+ addressState: null,+ addressCountry: null,+ addressPostcode: null,+ addressLat: null,+ addressLng: null,+ };++ mockGetPlaceDetailsData.mockImplementation(async () => {+ internalValue = { ...internalValue, addressStreet2: 'Suite 5' };++ return { street: '10 Rue de Rivoli', city: 'Paris' };+ });++ const { result } = renderHook(() => useAddressAutocomplete(mockOnChange));++ await act(async () => {+ await result.current.autoFillInputsFromPlaceDetails({+ placeId: 'rivoli',+ token: 'token123',+ getInternalValue: () => internalValue,+ });+ });++ expect(mockOnChange).toHaveBeenCalledWith(+ expect.objectContaining({+ addressStreet1: '10 Rue de Rivoli',+ addressStreet2: 'Suite 5',+ addressCity: 'Paris',+ }),+ );+ });++ it('should keep a city edited while place details are loading', async () => {+ const mockOnChange = jest.fn();+ let internalValue = {+ addressStreet1: '10 Rue',+ addressStreet2: null,+ addressCity: null as string | null,+ addressState: null,+ addressCountry: null,+ addressPostcode: null,+ addressLat: null,+ addressLng: null,+ };++ mockGetPlaceDetailsData.mockImplementation(async () => {+ internalValue = { ...internalValue, addressCity: 'Lyon' };++ return { street: '10 Rue de Rivoli', city: 'Paris', postcode: '75001' };+ });++ const { result } = renderHook(() => useAddressAutocomplete(mockOnChange));++ await act(async () => {+ await result.current.autoFillInputsFromPlaceDetails({+ placeId: 'rivoli',+ token: 'token123',+ getInternalValue: () => internalValue,+ });+ });++ expect(mockOnChange).toHaveBeenCalledWith(+ expect.objectContaining({+ addressStreet1: '10 Rue de Rivoli',+ addressCity: 'Lyon',+ addressPostcode: '75001',+ }),+ );+ });+it('should autofill inputs from place details', async () => {const mockOnChange = jest.fn();const mockPlaceData = {@@ -122,12 +199,12 @@ describe('useAddressAutocomplete', () => {};await act(async () => {- await result.current.autoFillInputsFromPlaceDetails(- 'place123',- 'token123',- '123 Main St',- internalValue,- );+ await result.current.autoFillInputsFromPlaceDetails({+ placeId: 'place123',+ token: 'token123',+ addressStreet1: '123 Main St',+ getInternalValue: () => internalValue,+ });});expect(mockOnChange).toHaveBeenCalledWith({@@ -157,11 +234,11 @@ describe('useAddressAutocomplete', () => {const { result } = renderHook(() => useAddressAutocomplete(mockOnChange));await act(async () => {- await result.current.autoFillInputsFromPlaceDetails(- 'place123',- 'token123',- '123 Main St, Springfield, IL 62704, USA',- {+ await result.current.autoFillInputsFromPlaceDetails({+ placeId: 'place123',+ token: 'token123',+ addressStreet1: '123 Main St, Springfield, IL 62704, USA',+ getInternalValue: () => ({addressStreet1: '',addressStreet2: null,addressCity: null,@@ -170,8 +247,8 @@ describe('useAddressAutocomplete', () => {addressPostcode: null,addressLat: null,addressLng: null,- },- );+ }),+ });});expect(mockOnChange).toHaveBeenCalledWith(@@ -208,12 +285,12 @@ describe('useAddressAutocomplete', () => {};await act(async () => {- await result.current.autoFillInputsFromPlaceDetails(- 'place123',- 'token123',- '123 Main St',- internalValue,- );+ await result.current.autoFillInputsFromPlaceDetails({+ placeId: 'place123',+ token: 'token123',+ addressStreet1: '123 Main St',+ getInternalValue: () => internalValue,+ });});expect(mockOnChange).toHaveBeenCalledWith({@@ -236,13 +313,108 @@ describe('useAddressAutocomplete', () => {const { result } = renderHook(() => useAddressAutocomplete(mockOnChange));await act(async () => {- await result.current.autoFillInputsFromPlaceDetails(- 'place123',- 'token123',- );+ await result.current.autoFillInputsFromPlaceDetails({+ placeId: 'place123',+ token: 'token123',+ });+ });++ expect(mockCloseDropdown).toHaveBeenCalled();+ });++ it('should ignore place details of a superseded selection', async () => {+ const mockOnChange = jest.fn();+ const resolvePlaceDetailsRequests: Array<+ (placeDetails: PlaceDetailsResult) => void+ > = [];++ mockGetPlaceDetailsData.mockImplementation(+ () =>+ new Promise<PlaceDetailsResult>((resolve) => {+ resolvePlaceDetailsRequests.push(resolve);+ }),+ );++ const internalValue = {+ addressStreet1: 'Place',+ addressStreet2: null,+ addressCity: null,+ addressState: null,+ addressCountry: null,+ addressPostcode: null,+ addressLat: null,+ addressLng: null,+ };++ const { result } = renderHook(() => useAddressAutocomplete(mockOnChange));++ let firstSelection: Promise<unknown> = Promise.resolve();+ let secondSelection: Promise<unknown> = Promise.resolve();++ act(() => {+ firstSelection = result.current.autoFillInputsFromPlaceDetails({+ placeId: 'bellecour',+ token: 'token123',+ getInternalValue: () => internalValue,+ });+ secondSelection = result.current.autoFillInputsFromPlaceDetails({+ placeId: 'concorde',+ token: 'token123',+ getInternalValue: () => internalValue,+ });+ });++ await act(async () => {+ resolvePlaceDetailsRequests[0]({+ street: 'Place Bellecour',+ city: 'Lyon',+ });+ await expect(firstSelection).resolves.toBeUndefined();+ });++ expect(mockOnChange).not.toHaveBeenCalled();+ expect(mockCloseDropdown).not.toHaveBeenCalled();++ await act(async () => {+ resolvePlaceDetailsRequests[1]({+ street: 'Place de la Concorde',+ city: 'Paris',+ });+ await secondSelection;+ });++ expect(mockOnChange).toHaveBeenCalledTimes(1);+ expect(mockOnChange).toHaveBeenCalledWith(+ expect.objectContaining({+ addressStreet1: 'Place de la Concorde',+ addressCity: 'Paris',+ }),+ );+ expect(mockCloseDropdown).toHaveBeenCalled();+ });++ it('should close dropdown when place details fail to load', async () => {+ const mockOnChange = jest.fn();+ mockGetPlaceDetailsData.mockRejectedValue(new Error('Network error'));++ const { result } = renderHook(() => useAddressAutocomplete(mockOnChange));++ act(() => {+ result.current.setTypeOfAddressForAutocomplete('addressStreet1');});+ await act(async () => {+ await expect(+ result.current.autoFillInputsFromPlaceDetails({+ placeId: 'place123',+ token: 'token123',+ }),+ ).rejects.toThrow('Network error');+ });++ expect(mockOnChange).not.toHaveBeenCalled();expect(mockCloseDropdown).toHaveBeenCalled();+ expect(result.current.typeOfAddressForAutocomplete).toBeNull();});it('should set token to null after autofilling', async () => {@@ -263,10 +435,10 @@ describe('useAddressAutocomplete', () => {expect(result.current.tokenForPlaceApi).not.toBeNull();await act(async () => {- await result.current.autoFillInputsFromPlaceDetails(- 'place123',- 'token123',- );+ await result.current.autoFillInputsFromPlaceDetails({+ placeId: 'place123',+ token: 'token123',+ });});expect(result.current.tokenForPlaceApi).toBeNull();@@ -305,10 +477,10 @@ describe('useAddressAutocomplete', () => {const { result } = renderHook(() => useAddressAutocomplete(mockOnChange));await act(async () => {- await result.current.autoFillInputsFromPlaceDetails(- 'place123',- 'token123',- );+ await result.current.autoFillInputsFromPlaceDetails({+ placeId: 'place123',+ token: 'token123',+ });});expect(mockFindCountryNameByCountryCode).toHaveBeenCalledWith('US');diff --git a/packages/twenty-front/src/modules/ui/field/input/hooks/useAddressAutocomplete.ts b/packages/twenty-front/src/modules/ui/field/input/hooks/useAddressAutocomplete.tsindex 0540b7c43b5..2f4576e8783 100644--- a/packages/twenty-front/src/modules/ui/field/input/hooks/useAddressAutocomplete.ts+++ b/packages/twenty-front/src/modules/ui/field/input/hooks/useAddressAutocomplete.ts@@ -1,9 +1,11 @@+import { atom, useStore } from 'jotai';import { useCallback, useState } from 'react';import { SELECT_AUTOCOMPLETE_LIST_DROPDOWN_ID } from '@/geo-map/constants/SelectAutocompleteListDropDownId';import { useGetPlaceApiData } from '@/geo-map/hooks/useGetPlaceApiData';import { usePlaceAutocomplete } from '@/geo-map/hooks/usePlaceAutocomplete';import { type FieldAddressDraftValue } from '@/object-record/record-field/ui/types/FieldInputDraftValue';+import { keepAddressFieldsEditedDuringAutofill } from '@/ui/field/input/utils/keepAddressFieldsEditedDuringAutofill';import { useCountryUtils } from './useCountryUtils';@@ -12,6 +14,8 @@ export const useAddressAutocomplete = () => {const [typeOfAddressForAutocomplete, setTypeOfAddressForAutocomplete] =useState<string | null>(null);+ const [latestPlaceSelectionIdAtom] = useState(() => atom(0));+ const store = useStore();const { getPlaceDetailsData } = useGetPlaceApiData();const { findCountryNameByCountryCode } = useCountryUtils();@@ -30,16 +34,43 @@ export const useAddressAutocomplete = (}, [closePlaceAutocomplete]);const autoFillInputsFromPlaceDetails = useCallback(- async (- placeId: string,- token: string,- addressStreet1?: string,- internalValue?: FieldAddressDraftValue,- ) => {- const placeData = await getPlaceDetailsData(placeId, token);+ async ({+ placeId,+ token,+ addressStreet1,+ getInternalValue,+ }: {+ placeId: string;+ token: string;+ addressStreet1?: string;+ getInternalValue?: () => FieldAddressDraftValue;+ }): Promise<FieldAddressDraftValue | undefined> => {+ const placeSelectionId = store.get(latestPlaceSelectionIdAtom) + 1;+ store.set(latestPlaceSelectionIdAtom, placeSelectionId);++ const isLatestPlaceSelection = () =>+ placeSelectionId === store.get(latestPlaceSelectionIdAtom);++ const internalValueAtSelection = getInternalValue?.();+ const placeData = await getPlaceDetailsData(placeId, token).finally(+ () => {+ if (!isLatestPlaceSelection()) {+ return;+ }++ resetPlaceAutocomplete();+ setTypeOfAddressForAutocomplete(null);+ },+ );++ if (!isLatestPlaceSelection()) {+ return undefined;+ }+const countryName = findCountryNameByCountryCode(placeData?.country);+ const internalValue = getInternalValue?.();- const updatedAddress = {+ const autofilledAddress = {addressStreet1:placeData?.street ||addressStreet1 ||@@ -56,13 +87,19 @@ export const useAddressAutocomplete = (placeData?.location?.lng ?? internalValue?.addressLng ?? null,};- resetPlaceAutocomplete();- setTypeOfAddressForAutocomplete(null);+ const updatedAddress = keepAddressFieldsEditedDuringAutofill({+ autofilledAddress,+ addressAtSelection: internalValueAtSelection,+ currentAddress: internalValue,+ });+onChange?.(updatedAddress);return updatedAddress;},[+ store,+ latestPlaceSelectionIdAtom,getPlaceDetailsData,findCountryNameByCountryCode,resetPlaceAutocomplete,diff --git a/packages/twenty-front/src/modules/ui/field/input/hooks/useAddressInputClickOutside.ts b/packages/twenty-front/src/modules/ui/field/input/hooks/useAddressInputClickOutside.tsnew file mode 100644index 00000000000..2f26b38cbf3--- /dev/null+++ b/packages/twenty-front/src/modules/ui/field/input/hooks/useAddressInputClickOutside.ts@@ -0,0 +1,45 @@+import { useStore } from 'jotai';+import { type RefObject } from 'react';++import { SELECT_AUTOCOMPLETE_LIST_DROPDOWN_ID } from '@/geo-map/constants/SelectAutocompleteListDropDownId';+import { SELECT_COUNTRY_DROPDOWN_ID } from '@/ui/input/components/internal/country/constants/SelectCountryDropdownId';+import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';+import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';++const ADDRESS_CLICK_OUTSIDE_LISTENER_ID = 'address-input';++const ADDRESS_DROPDOWN_IDS = [+ SELECT_AUTOCOMPLETE_LIST_DROPDOWN_ID,+ SELECT_COUNTRY_DROPDOWN_ID,+];++type UseAddressInputClickOutsideArgs = {+ inputRef: RefObject<HTMLDivElement | null>;+ onClickOutside: (event: MouseEvent | TouchEvent) => void;+};++export const useAddressInputClickOutside = ({+ inputRef,+ onClickOutside,+}: UseAddressInputClickOutsideArgs) => {+ const store = useStore();++ useListenClickOutside({+ refs: [inputRef],+ callback: (event) => {+ const isAddressDropdownOpen = ADDRESS_DROPDOWN_IDS.some((dropdownId) =>+ store.get(+ isDropdownOpenComponentState.atomFamily({ instanceId: dropdownId }),+ ),+ );++ if (isAddressDropdownOpen) {+ return;+ }++ event.stopImmediatePropagation();+ onClickOutside(event);+ },+ listenerId: ADDRESS_CLICK_OUTSIDE_LISTENER_ID,+ });+};diff --git a/packages/twenty-front/src/modules/ui/field/input/types/AddressInputProps.ts b/packages/twenty-front/src/modules/ui/field/input/types/AddressInputProps.tsnew file mode 100644index 00000000000..a240f720941--- /dev/null+++ b/packages/twenty-front/src/modules/ui/field/input/types/AddressInputProps.ts@@ -0,0 +1,19 @@+import { type FieldAddressDraftValue } from '@/object-record/record-field/ui/types/FieldInputDraftValue';+import { type FieldAddressValue } from '@/object-record/record-field/ui/types/FieldMetadata';+import { type AllowedAddressSubField } from 'twenty-shared/types';++export type AddressInputProps = {+ instanceId: string;+ value: FieldAddressValue;+ onTab: (newAddress: FieldAddressDraftValue) => void;+ onShiftTab: (newAddress: FieldAddressDraftValue) => void;+ onEnter: (newAddress: FieldAddressDraftValue) => void;+ onEscape: (newAddress: FieldAddressDraftValue) => void;+ onClickOutside: (args: {+ event: MouseEvent | TouchEvent;+ newAddress: FieldAddressDraftValue;+ }) => void;+ clearable?: boolean;+ onChange?: (updatedValue: FieldAddressDraftValue) => void;+ subFields?: AllowedAddressSubField[] | null;+};diff --git a/packages/twenty-front/src/modules/ui/field/input/utils/__tests__/keepAddressFieldsEditedDuringAutofill.test.ts b/packages/twenty-front/src/modules/ui/field/input/utils/__tests__/keepAddressFieldsEditedDuringAutofill.test.tsnew file mode 100644index 00000000000..29ed0aaf293--- /dev/null+++ b/packages/twenty-front/src/modules/ui/field/input/utils/__tests__/keepAddressFieldsEditedDuringAutofill.test.ts@@ -0,0 +1,87 @@+import { type FieldAddressDraftValue } from '@/object-record/record-field/ui/types/FieldInputDraftValue';+import { keepAddressFieldsEditedDuringAutofill } from '@/ui/field/input/utils/keepAddressFieldsEditedDuringAutofill';++const ADDRESS_AT_SELECTION: FieldAddressDraftValue = {+ addressStreet1: '10 Rue',+ addressStreet2: null,+ addressCity: null,+ addressState: null,+ addressPostcode: null,+ addressCountry: null,+ addressLat: null,+ addressLng: null,+};++const AUTOFILLED_ADDRESS: FieldAddressDraftValue = {+ addressStreet1: '10 Rue de Rivoli',+ addressStreet2: null,+ addressCity: 'Paris',+ addressState: 'Île-de-France',+ addressPostcode: '75001',+ addressCountry: 'France',+ addressLat: 48.8566,+ addressLng: 2.3522,+};++describe('keepAddressFieldsEditedDuringAutofill', () => {+ it('keeps the autofilled address when nothing changed while loading', () => {+ expect(+ keepAddressFieldsEditedDuringAutofill({+ autofilledAddress: AUTOFILLED_ADDRESS,+ addressAtSelection: ADDRESS_AT_SELECTION,+ currentAddress: ADDRESS_AT_SELECTION,+ }),+ ).toEqual(AUTOFILLED_ADDRESS);+ });++ it('keeps fields edited while the place details were loading', () => {+ expect(+ keepAddressFieldsEditedDuringAutofill({+ autofilledAddress: AUTOFILLED_ADDRESS,+ addressAtSelection: ADDRESS_AT_SELECTION,+ currentAddress: {+ ...ADDRESS_AT_SELECTION,+ addressCity: 'Lyon',+ addressPostcode: '69001',+ },+ }),+ ).toEqual({+ ...AUTOFILLED_ADDRESS,+ addressCity: 'Lyon',+ addressPostcode: '69001',+ });+ });++ it('keeps a field cleared while the place details were loading', () => {+ expect(+ keepAddressFieldsEditedDuringAutofill({+ autofilledAddress: AUTOFILLED_ADDRESS,+ addressAtSelection: {+ ...ADDRESS_AT_SELECTION,+ addressPostcode: '69001',+ },+ currentAddress: { ...ADDRESS_AT_SELECTION, addressPostcode: null },+ }),+ ).toEqual({ ...AUTOFILLED_ADDRESS, addressPostcode: null });+ });++ it('keeps a field replaced while the place details were loading', () => {+ expect(+ keepAddressFieldsEditedDuringAutofill({+ autofilledAddress: AUTOFILLED_ADDRESS,+ addressAtSelection: { ...ADDRESS_AT_SELECTION, addressCity: 'Lyon' },+ currentAddress: { ...ADDRESS_AT_SELECTION, addressCity: 'Marseille' },+ }),+ ).toEqual({ ...AUTOFILLED_ADDRESS, addressCity: 'Marseille' });+ });++ it('keeps the autofilled address when no current value is known', () => {+ expect(+ keepAddressFieldsEditedDuringAutofill({+ autofilledAddress: AUTOFILLED_ADDRESS,+ addressAtSelection: undefined,+ currentAddress: undefined,+ }),+ ).toEqual(AUTOFILLED_ADDRESS);+ });+});diff --git a/packages/twenty-front/src/modules/ui/field/input/utils/keepAddressFieldsEditedDuringAutofill.ts b/packages/twenty-front/src/modules/ui/field/input/utils/keepAddressFieldsEditedDuringAutofill.tsnew file mode 100644index 00000000000..a62d1c3eb93--- /dev/null+++ b/packages/twenty-front/src/modules/ui/field/input/utils/keepAddressFieldsEditedDuringAutofill.ts@@ -0,0 +1,36 @@+import { isUndefined } from '@sniptt/guards';++import { type FieldAddressDraftValue } from '@/object-record/record-field/ui/types/FieldInputDraftValue';++export const keepAddressFieldsEditedDuringAutofill = ({+ autofilledAddress,+ addressAtSelection,+ currentAddress,+}: {+ autofilledAddress: FieldAddressDraftValue;+ addressAtSelection: FieldAddressDraftValue | undefined;+ currentAddress: FieldAddressDraftValue | undefined;+}): FieldAddressDraftValue => {+ const pickField = <TField extends keyof FieldAddressDraftValue>(+ field: TField,+ ): FieldAddressDraftValue[TField] => {+ const currentFieldValue = currentAddress?.[field];+ const isEditedDuringAutofill =+ currentFieldValue !== addressAtSelection?.[field];++ return isEditedDuringAutofill && !isUndefined(currentFieldValue)+ ? currentFieldValue+ : autofilledAddress[field];+ };++ return {+ addressStreet1: pickField('addressStreet1'),+ addressStreet2: pickField('addressStreet2'),+ addressCity: pickField('addressCity'),+ addressState: pickField('addressState'),+ addressPostcode: pickField('addressPostcode'),+ addressCountry: pickField('addressCountry'),+ addressLat: pickField('addressLat'),+ addressLng: pickField('addressLng'),+ };+};diff --git a/packages/twenty-front/src/modules/ui/input/components/AutocompleteContent.tsx b/packages/twenty-front/src/modules/ui/input/components/AutocompleteContent.tsxnew file mode 100644index 00000000000..d708c475579--- /dev/null+++ b/packages/twenty-front/src/modules/ui/input/components/AutocompleteContent.tsx@@ -0,0 +1,37 @@+import { type ComponentProps, type MouseEvent, useContext } from 'react';+import { Autocomplete } from 'twenty-ui/primitives/input';++import { DropdownClickOutsideListenerExclusion } from '@/ui/layout/dropdown/components/DropdownClickOutsideListenerExclusion';+import { ParentClickOutsideIdContext } from '@/ui/utilities/pointer-event/contexts/ParentClickOutsideIdContext';++type AutocompleteContentProps = Pick<+ ComponentProps<typeof Autocomplete.Popup>,+ 'children' | 'align' | 'sideOffset' | 'width'+>;++export const AutocompleteContent = ({+ children,+ align,+ sideOffset,+ width,+}: AutocompleteContentProps) => {+ const parentClickOutsideId = useContext(ParentClickOutsideIdContext);++ const keepFocusInInput = (event: MouseEvent<HTMLDivElement>) => {+ event.preventDefault();+ };++ return (+ <Autocomplete.Popup+ data-click-outside-id={parentClickOutsideId}+ align={align}+ sideOffset={sideOffset}+ width={width}+ onMouseDown={keepFocusInInput}+ >+ <DropdownClickOutsideListenerExclusion>+ {children}+ </DropdownClickOutsideListenerExclusion>+ </Autocomplete.Popup>+ );+};diff --git a/packages/twenty-front/src/modules/ui/input/components/AutocompleteRoot.tsx b/packages/twenty-front/src/modules/ui/input/components/AutocompleteRoot.tsxnew file mode 100644index 00000000000..2ad6069db21--- /dev/null+++ b/packages/twenty-front/src/modules/ui/input/components/AutocompleteRoot.tsx@@ -0,0 +1,116 @@+import { type ReactNode } from 'react';+import { isNonEmptyArray } from 'twenty-shared/utils';+import {+ type AutocompleteRootProps as AutocompletePrimitiveRootProps,+ Autocomplete,+} from 'twenty-ui/primitives/input';++import { DropdownCleanupEffect } from '@/ui/layout/dropdown/components/DropdownCleanupEffect';+import { DropdownComponentInstanceContext } from '@/ui/layout/dropdown/contexts/DropdownComponentInstanceContext';+import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';+import { useOpenDropdown } from '@/ui/layout/dropdown/hooks/useOpenDropdown';+import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';+import { type GlobalHotkeysConfig } from '@/ui/utilities/hotkey/types/GlobalHotkeysConfig';+import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';++type AutocompleteRootProps<TItem> = {+ children: ReactNode;+ dropdownId: string;+ items: readonly TItem[];+ value: string;+ onValueChange: (value: string) => void;+ itemToStringValue?: (item: TItem) => string;+ enabled?: boolean;+ openOnValueChange?: boolean;+ closeOnItemPress?: boolean;+ onClose?: () => void;+ onItemHighlightedByUser?: (item: TItem | undefined) => void;+ globalHotkeysConfig?: Partial<GlobalHotkeysConfig>;+};++export const AutocompleteRoot = <TItem,>({+ children,+ dropdownId,+ items,+ value,+ onValueChange,+ itemToStringValue,+ enabled = true,+ openOnValueChange = true,+ closeOnItemPress = true,+ onClose,+ onItemHighlightedByUser,+ globalHotkeysConfig,+}: AutocompleteRootProps<TItem>) => {+ const isDropdownOpen = useAtomComponentStateValue(+ isDropdownOpenComponentState,+ dropdownId,+ );+ const { openDropdown } = useOpenDropdown();+ const { closeDropdown } = useCloseDropdown();++ const handleValueChange: AutocompletePrimitiveRootProps<TItem>['onValueChange'] =+ (nextValue, details) => {+ if (details.reason === 'item-press' || details.reason === 'escape-key') {+ return;+ }++ onValueChange(nextValue);+ };++ const handleOpenChange: AutocompletePrimitiveRootProps<TItem>['onOpenChange'] =+ (open, details) => {+ const isOpeningOnValueChange =+ details.reason === 'input-change' && !openOnValueChange;+ const isOpeningEmptyList =+ details.reason === 'list-navigation' && !isNonEmptyArray(items);+ const isClosingOnItemPress =+ details.reason === 'item-press' && !closeOnItemPress;++ if (+ !enabled ||+ (open && (isOpeningOnValueChange || isOpeningEmptyList)) ||+ (!open && isClosingOnItemPress)+ ) {+ details.cancel();+ return;+ }++ if (!open) {+ closeDropdown(dropdownId);+ onClose?.();+ return;+ }++ openDropdown({+ dropdownComponentInstanceIdFromProps: dropdownId,+ globalHotkeysConfig,+ });+ };++ const handleItemHighlighted: AutocompletePrimitiveRootProps<TItem>['onItemHighlighted'] =+ (item, details) => {+ onItemHighlightedByUser?.(details.reason === 'none' ? undefined : item);+ };++ return (+ <DropdownComponentInstanceContext.Provider+ value={{ instanceId: dropdownId }}+ >+ <Autocomplete.Root<TItem>+ items={items}+ filter={null}+ autoHighlight="always"+ value={value}+ open={enabled && isDropdownOpen}+ itemToStringValue={itemToStringValue}+ onValueChange={handleValueChange}+ onOpenChange={handleOpenChange}+ onItemHighlighted={handleItemHighlighted}+ >+ <DropdownCleanupEffect dropdownId={dropdownId} />+ {children}+ </Autocomplete.Root>+ </DropdownComponentInstanceContext.Provider>+ );+};diff --git a/packages/twenty-front/src/modules/ui/input/components/SettingsTextInput.tsx b/packages/twenty-front/src/modules/ui/input/components/SettingsTextInput.tsxindex 28fa7679839..de884b3badb 100644--- a/packages/twenty-front/src/modules/ui/input/components/SettingsTextInput.tsx+++ b/packages/twenty-front/src/modules/ui/input/components/SettingsTextInput.tsx@@ -1,10 +1,8 @@import { type FocusEventHandler, useEffect, useRef, useState } from 'react';import { Key } from 'ts-key-enum';-import {- TextInput,- type TextInputComponentProps,-} from '@/ui/input/components/TextInput';+import { TextInput } from '@/ui/input/components/TextInput';+import { type TextInputComponentProps } from '@/ui/input/types/TextInputComponentProps';import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePushFocusItemToFocusStack';import { useRemoveFocusItemFromFocusStackById } from '@/ui/utilities/focus/hooks/useRemoveFocusItemFromFocusStackById';import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';diff --git a/packages/twenty-front/src/modules/ui/input/components/TextInput.tsx b/packages/twenty-front/src/modules/ui/input/components/TextInput.tsxindex 7772dfd5a51..e86427cc3f3 100644--- a/packages/twenty-front/src/modules/ui/input/components/TextInput.tsx+++ b/packages/twenty-front/src/modules/ui/input/components/TextInput.tsx@@ -1,3 +1,6 @@+import { mergeProps } from '@base-ui/react/merge-props';+import { type TextInputComponentProps } from '@/ui/input/types/TextInputComponentProps';+import { type TextInputSize } from '@/ui/input/types/TextInputSize';import { AutogrowWrapper } from '@/ui/input/components/internal/AutogrowWrapper/AutogrowWrapper';import { css } from '@linaria/core';import { styled } from '@linaria/react';@@ -5,14 +8,13 @@ import { isNonEmptyString } from '@sniptt/guards';import React, {type ChangeEvent,type FocusEventHandler,- type InputHTMLAttributes,forwardRef,useId,useRef,useState,} from 'react';import { isDefined } from 'twenty-shared/utils';-import { type IconComponent, IconEye, IconEyeOff } from 'twenty-ui/icon';+import { IconEye, IconEyeOff } from 'twenty-ui/icon';import { Field } from 'twenty-ui/primitives/input';import { useTheme, themeCssVariables } from 'twenty-ui/theme';import { useCombinedRefs } from '~/hooks/useCombinedRefs';@@ -236,33 +238,6 @@ const StyledTrailingIcon = styled.div<{const INPUT_TYPE_PASSWORD = 'password';-export type TextInputSize = 'xs' | 'sm' | 'md' | 'lg';--export type TextInputComponentProps = Omit<- InputHTMLAttributes<HTMLInputElement>,- 'onChange' | 'onKeyDown'-> & {- className?: string;- label?: string;- onChange?: (text: string) => void;- fullWidth?: boolean;- error?: string;- noErrorHelper?: boolean;- RightIcon?: IconComponent;- onRightIconClick?: () => void;- LeftIcon?: IconComponent;- autoGrow?: boolean;- onKeyDown?: (event: React.KeyboardEvent<HTMLInputElement>) => void;- onBlur?: FocusEventHandler<HTMLInputElement>;- dataTestId?: string;- sizeVariant?: TextInputSize;- inheritFontStyles?: boolean;- rightAdornment?: string;- leftAdornment?: string;- textClickOutsideId?: string;- ignorePasswordManagers?: boolean;-};-type TextInputWithAutoGrowWrapperProps = TextInputComponentProps;const TextInputComponent = forwardRef<@@ -303,12 +278,13 @@ const TextInputComponent = forwardRef<leftAdornment,textClickOutsideId,ignorePasswordManagers = false,+ inputProps,},ref,) => {const theme = useTheme();const inputRef = useRef<HTMLInputElement>(null);- const combinedRef = useCombinedRefs(ref, inputRef);+ const combinedRef = useCombinedRefs(ref, inputRef, inputProps?.ref);const [passwordVisible, setPasswordVisible] = useState(false);const [isFocused, setIsFocused] = useState(false);@@ -327,7 +303,19 @@ const TextInputComponent = forwardRef<onBlur?.(event);};- const instanceId = useId();+ const handleChange = (event: ChangeEvent<HTMLInputElement>) => {+ onChange?.(turnIntoEmptyStringIfWhitespacesOnly(event.target.value));+ };++ const mergedInputProps = mergeProps<'input'>(inputProps, {+ onFocus: handleFocus,+ onBlur: handleBlur,+ onKeyDown,+ onChange: handleChange,+ });++ const generatedId = useId();+ const instanceId = inputProps?.id ?? generatedId;return (<Field.Root className={fieldRootClassName}>@@ -368,34 +356,26 @@ const TextInputComponent = forwardRef<// oxlint-disable-next-line react/jsx-props-no-spreading{...(ignorePasswordManagers &&PASSWORD_MANAGER_IGNORE_ATTRIBUTES)}- ref={combinedRef}tabIndex={tabIndex ?? 0}- onFocus={handleFocus}- onBlur={handleBlur}type={passwordVisible ? 'text' : type}- onChange={(event: ChangeEvent<HTMLInputElement>) => {- onChange?.(- turnIntoEmptyStringIfWhitespacesOnly(event.target.value),- );- }}- onKeyDown={onKeyDown}- {...{- autoFocus,- disabled,- readOnly,- placeholder,- required,- value,- LeftIcon,- RightIcon,- maxLength,- error,- sizeVariant,- inheritFontStyles,- autoGrow,- leftAdornment,- rightAdornment,- }}+ autoFocus={autoFocus}+ disabled={disabled}+ readOnly={readOnly}+ placeholder={placeholder}+ required={required}+ value={value}+ LeftIcon={LeftIcon}+ RightIcon={RightIcon}+ maxLength={maxLength}+ error={error}+ sizeVariant={sizeVariant}+ inheritFontStyles={inheritFontStyles}+ autoGrow={autoGrow}+ leftAdornment={leftAdornment}+ rightAdornment={rightAdornment}+ // oxlint-disable-next-line react/jsx-props-no-spreading+ {...mergedInputProps}+ ref={combinedRef}/>{rightAdornment && (<StyledAdornmentContainerdiff --git a/packages/twenty-front/src/modules/ui/input/components/TitleInput.tsx b/packages/twenty-front/src/modules/ui/input/components/TitleInput.tsxindex 2efffca1eb3..58e195792df 100644--- a/packages/twenty-front/src/modules/ui/input/components/TitleInput.tsx+++ b/packages/twenty-front/src/modules/ui/input/components/TitleInput.tsx@@ -1,4 +1,5 @@-import { TextInput, type TextInputSize } from '@/ui/input/components/TextInput';+import { TextInput } from '@/ui/input/components/TextInput';+import { type TextInputSize } from '@/ui/input/types/TextInputSize';import { useRef, useState } from 'react';import { isDefined } from 'twenty-shared/utils';diff --git a/packages/twenty-front/src/modules/ui/input/components/__stories__/TextInput.stories.tsx b/packages/twenty-front/src/modules/ui/input/components/__stories__/TextInput.stories.tsxindex e5fd92b1a3e..f71756c5ba0 100644--- a/packages/twenty-front/src/modules/ui/input/components/__stories__/TextInput.stories.tsx+++ b/packages/twenty-front/src/modules/ui/input/components/__stories__/TextInput.stories.tsx@@ -1,10 +1,9 @@import { type Meta, type StoryObj } from '@storybook/react-vite';import { useState } from 'react';+import { expect, fn, userEvent, within } from 'storybook/test';-import {- TextInput,- type TextInputComponentProps,-} from '@/ui/input/components/TextInput';+import { TextInput } from '@/ui/input/components/TextInput';+import { type TextInputComponentProps } from '@/ui/input/types/TextInputComponentProps';import { ComponentDecorator } from 'twenty-ui/testing';type RenderProps = TextInputComponentProps;@@ -68,3 +67,48 @@ export const WithRightAdornment: Story = {rightAdornment: '@twenty.com',},};++export const ForwardsNativeInputProps: Story = {+ args: {+ label: 'Address',+ value: '',+ onChange: fn(),+ onFocus: fn(),+ onKeyDown: fn(),+ inputProps: {+ id: 'native-address-input',+ role: 'combobox',+ 'aria-controls': 'address-options',+ onChange: fn(),+ onFocus: fn(),+ onKeyDown: fn(),+ },+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole('combobox', { name: 'Address' });++ expect(input).toHaveAttribute('id', 'native-address-input');+ expect(input).toHaveAttribute('aria-controls', 'address-options');++ await userEvent.click(canvas.getByText('Address'));++ expect(input).toHaveFocus();+ expect(args.onFocus).toHaveBeenCalledTimes(1);+ expect(args.inputProps?.onFocus).toHaveBeenCalledTimes(1);++ await userEvent.type(input, 'Paris');++ expect(input).toHaveValue('Paris');+ expect(args.onChange).toHaveBeenLastCalledWith('Paris');+ expect(args.inputProps?.onChange).toHaveBeenLastCalledWith(+ expect.objectContaining({ target: input }),+ );+ expect(args.onKeyDown).toHaveBeenLastCalledWith(+ expect.objectContaining({ key: 's' }),+ );+ expect(args.inputProps?.onKeyDown).toHaveBeenLastCalledWith(+ expect.objectContaining({ key: 's' }),+ );+ },+};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.tsxnew file mode 100644index 00000000000..f7681ecd71c--- /dev/null+++ b/packages/twenty-front/src/modules/ui/input/components/__tests__/AutocompleteRoot.test.tsx@@ -0,0 +1,298 @@+import { AutocompleteContent } from '@/ui/input/components/AutocompleteContent';+import { AutocompleteRoot } from '@/ui/input/components/AutocompleteRoot';+import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';+import { useOpenDropdown } from '@/ui/layout/dropdown/hooks/useOpenDropdown';+import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';+import { focusStackState } from '@/ui/utilities/focus/states/focusStackState';+import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';+import { ParentClickOutsideIdContext } from '@/ui/utilities/pointer-event/contexts/ParentClickOutsideIdContext';+import {+ act,+ fireEvent,+ render,+ renderHook,+ screen,+ waitFor,+} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { createStore, Provider as JotaiProvider } from 'jotai';+import { StrictMode, useState } from 'react';+import { Autocomplete } from 'twenty-ui/primitives/input';++const OPTIONS = ['Paris', 'London'];+const DROPDOWN_ID = 'autocomplete';++type AutocompleteExampleProps = {+ enabled?: boolean;+ label?: string;+ items?: string[];+ openOnValueChange?: boolean;+ onItemHighlightedByUser?: (item: string | undefined) => void;+};++const AutocompleteExample = ({+ enabled = true,+ label = 'City',+ items = OPTIONS,+ openOnValueChange,+ onItemHighlightedByUser,+}: AutocompleteExampleProps) => {+ const [value, setValue] = useState('');++ return (+ <AutocompleteRoot+ dropdownId={DROPDOWN_ID}+ enabled={enabled}+ items={items}+ value={value}+ openOnValueChange={openOnValueChange}+ onValueChange={setValue}+ onItemHighlightedByUser={onItemHighlightedByUser}+ >+ <Autocomplete.InputGroup>+ <Autocomplete.Input aria-label={label} />+ </Autocomplete.InputGroup>+ <AutocompleteContent>+ <Autocomplete.List>+ {items.map((option) => (+ <Autocomplete.Item key={option} value={option}>+ {option}+ </Autocomplete.Item>+ ))}+ </Autocomplete.List>+ </AutocompleteContent>+ </AutocompleteRoot>+ );+};++describe('AutocompleteRoot', () => {+ it('keeps input focus while navigating and restores the focus stack on Escape', async () => {+ const user = userEvent.setup();+ const store = createStore();++ render(+ <JotaiProvider store={store}>+ <AutocompleteExample />+ </JotaiProvider>,+ );++ const input = screen.getByRole('combobox', { name: 'City' });+ await user.type(input, 'Pa');++ expect(screen.getAllByRole('option')).toHaveLength(2);+ expect(input).toHaveFocus();+ expect(store.get(focusStackState.atom).at(-1)?.componentInstance).toEqual({+ componentType: FocusComponentType.DROPDOWN,+ componentInstanceId: DROPDOWN_ID,+ });++ await user.keyboard('{ArrowDown}');+ expect(input).toHaveFocus();+ expect(input).toHaveAttribute(+ 'aria-activedescendant',+ screen.getByRole('option', { name: 'London' }).id,+ );++ await user.keyboard('{Escape}');+ await waitFor(() =>+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument(),+ );+ expect(input).toHaveFocus();+ expect(input).toHaveValue('Pa');+ expect(store.get(focusStackState.atom)).toEqual([]);+ });++ it('waits for results before opening when openOnValueChange is false', async () => {+ const user = userEvent.setup();+ const store = createStore();++ render(+ <JotaiProvider store={store}>+ <AutocompleteExample openOnValueChange={false} />+ </JotaiProvider>,+ );++ await user.type(screen.getByRole('combobox'), 'Pa');++ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ expect(store.get(focusStackState.atom)).toEqual([]);+ });++ it('opens from the arrow keys once results arrive when openOnValueChange is false', async () => {+ const user = userEvent.setup();+ const store = createStore();++ const { rerender } = render(+ <JotaiProvider store={store}>+ <AutocompleteExample items={[]} openOnValueChange={false} />+ </JotaiProvider>,+ );++ const input = screen.getByRole('combobox');+ await user.type(input, 'Pa');+ await user.keyboard('{ArrowDown}');++ expect(input).toHaveAttribute('aria-expanded', 'false');++ rerender(+ <JotaiProvider store={store}>+ <AutocompleteExample items={OPTIONS} openOnValueChange={false} />+ </JotaiProvider>,+ );+ await user.keyboard('{ArrowDown}');++ expect(screen.getByRole('listbox')).toBeVisible();+ expect(input).toHaveValue('Pa');+ expect(store.get(focusStackState.atom).at(-1)?.componentInstance).toEqual({+ componentType: FocusComponentType.DROPDOWN,+ componentInstanceId: DROPDOWN_ID,+ });+ });++ it('does not open an empty list from the arrow keys', async () => {+ const user = userEvent.setup();+ const store = createStore();++ render(+ <JotaiProvider store={store}>+ <AutocompleteExample items={[]} />+ </JotaiProvider>,+ );++ await user.click(screen.getByRole('combobox'));+ await user.keyboard('{ArrowDown}');++ expect(screen.getByRole('combobox')).toHaveAttribute(+ 'aria-expanded',+ 'false',+ );+ expect(store.get(focusStackState.atom)).toEqual([]);+ });++ it('keeps the highlighted item when the same items are passed again', async () => {+ const user = userEvent.setup();+ const store = createStore();+ const onItemHighlightedByUser = jest.fn();++ const { rerender } = render(+ <JotaiProvider store={store}>+ <AutocompleteExample+ items={[...OPTIONS]}+ onItemHighlightedByUser={onItemHighlightedByUser}+ />+ </JotaiProvider>,+ );++ const input = screen.getByRole('combobox');+ await user.type(input, 'Pa');+ await user.keyboard('{ArrowDown}');++ expect(onItemHighlightedByUser).toHaveBeenLastCalledWith('London');++ onItemHighlightedByUser.mockClear();++ rerender(+ <JotaiProvider store={store}>+ <AutocompleteExample+ items={[...OPTIONS]}+ onItemHighlightedByUser={onItemHighlightedByUser}+ />+ </JotaiProvider>,+ );++ expect(onItemHighlightedByUser).not.toHaveBeenCalled();+ expect(input).toHaveAttribute(+ 'aria-activedescendant',+ screen.getByRole('option', { name: 'London' }).id,+ );+ });++ it('opens only the active input for a shared dropdown id and supports external close', async () => {+ const store = createStore();+ const { result } = renderHook(+ () => ({ ...useOpenDropdown(), ...useCloseDropdown() }),+ {+ wrapper: ({ children }) => (+ <JotaiProvider store={store}>{children}</JotaiProvider>+ ),+ },+ );++ render(+ <JotaiProvider store={store}>+ <AutocompleteExample label="Address" />+ <AutocompleteExample label="City" enabled={false} />+ </JotaiProvider>,+ );++ const inactiveInput = screen.getByRole('combobox', { name: 'City' });++ act(() =>+ result.current.openDropdown({+ dropdownComponentInstanceIdFromProps: DROPDOWN_ID,+ }),+ );++ await waitFor(() =>+ expect(screen.getByRole('combobox', { name: 'Address' })).toHaveAttribute(+ 'aria-expanded',+ 'true',+ ),+ );+ expect(inactiveInput).toHaveAttribute('aria-expanded', 'false');+ expect(screen.getAllByRole('listbox')).toHaveLength(1);++ act(() => result.current.closeDropdown(DROPDOWN_ID));++ await waitFor(() =>+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument(),+ );+ expect(store.get(focusStackState.atom)).toEqual([]);+ });++ it('marks the popup as inside its parent surface and keeps the input focused on press', async () => {+ const user = userEvent.setup();+ const store = createStore();++ render(+ <JotaiProvider store={store}>+ <ParentClickOutsideIdContext.Provider value="side-panel">+ <AutocompleteExample />+ </ParentClickOutsideIdContext.Provider>+ </JotaiProvider>,+ );++ const input = screen.getByRole('combobox');+ await user.type(input, 'Pa');++ const listbox = screen.getByRole('listbox');++ expect(+ listbox.closest('[data-click-outside-id="side-panel"]'),+ ).not.toBeNull();+ expect(fireEvent.mouseDown(listbox)).toBe(false);+ });++ it('cleans up an open autocomplete when its mounted owner leaves StrictMode', async () => {+ const user = userEvent.setup();+ const store = createStore();+ const { unmount } = render(+ <StrictMode>+ <JotaiProvider store={store}>+ <AutocompleteExample />+ </JotaiProvider>+ </StrictMode>,+ );++ await user.type(screen.getByRole('combobox'), 'Pa');+ expect(screen.getByRole('listbox')).toBeVisible();+ unmount();++ 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/constants/TextInputClickOutsideId.ts b/packages/twenty-front/src/modules/ui/input/components/constants/TextInputClickOutsideId.tsdeleted file mode 100644index 80138670213..00000000000--- a/packages/twenty-front/src/modules/ui/input/components/constants/TextInputClickOutsideId.ts+++ /dev/null@@ -1 +0,0 @@-export const TEXT_INPUT_CLICK_OUTSIDE_ID = 'text-input-click-outside-id';diff --git a/packages/twenty-front/src/modules/ui/input/types/TextInputComponentProps.ts b/packages/twenty-front/src/modules/ui/input/types/TextInputComponentProps.tsnew file mode 100644index 00000000000..db686937158--- /dev/null+++ b/packages/twenty-front/src/modules/ui/input/types/TextInputComponentProps.ts@@ -0,0 +1,26 @@+import { type ComponentPropsWithRef, type InputHTMLAttributes } from 'react';+import { type IconComponent } from 'twenty-ui/icon';+import { type TextInputSize } from '@/ui/input/types/TextInputSize';++export type TextInputComponentProps = Omit<+ InputHTMLAttributes<HTMLInputElement>,+ 'onChange'+> & {+ label?: string;+ onChange?: (text: string) => void;+ inputProps?: ComponentPropsWithRef<'input'>;+ fullWidth?: boolean;+ error?: string;+ noErrorHelper?: boolean;+ RightIcon?: IconComponent;+ onRightIconClick?: () => void;+ LeftIcon?: IconComponent;+ autoGrow?: boolean;+ dataTestId?: string;+ sizeVariant?: TextInputSize;+ inheritFontStyles?: boolean;+ rightAdornment?: string;+ leftAdornment?: string;+ textClickOutsideId?: string;+ ignorePasswordManagers?: boolean;+};diff --git a/packages/twenty-front/src/modules/ui/input/types/TextInputSize.ts b/packages/twenty-front/src/modules/ui/input/types/TextInputSize.tsnew file mode 100644index 00000000000..bfd2790ba64--- /dev/null+++ b/packages/twenty-front/src/modules/ui/input/types/TextInputSize.ts@@ -0,0 +1 @@+export type TextInputSize = 'xs' | 'sm' | 'md' | 'lg';diff --git a/packages/twenty-ui/docs/components.ts b/packages/twenty-ui/docs/components.tsindex 45469ac880f..834627e8c08 100644--- a/packages/twenty-ui/docs/components.ts+++ b/packages/twenty-ui/docs/components.ts@@ -298,6 +298,27 @@ export const DOCUMENTED_COMPONENTS = [entryPoint: 'twenty-ui/primitives/input',slug: 'input/radio-group',},+ {+ name: 'Autocomplete',+ source: 'primitives/input/Autocomplete/Autocomplete.tsx',+ entryPoint: 'twenty-ui/primitives/input',+ slug: 'input/autocomplete',+ partPropDescriptions: {+ Root: {+ items:+ 'Items to display in the list. Nullish entries are not supported.',+ },+ Input: {+ size: 'Visual size of the input. Inside an InputGroup, the group size applies.',+ },+ Popup: {+ width:+ 'Width of the popup. Overrides its default minimum anchor width.',+ container:+ 'Element the popup is portaled into. Defaults to the theme portal container.',+ },+ },+ },{name: 'Select',source: 'primitives/input/Select/Select.tsx',diff --git a/packages/twenty-ui/docs/module-ownership.json b/packages/twenty-ui/docs/module-ownership.jsonindex 9b4a125c38e..aa508dc930d 100644--- a/packages/twenty-ui/docs/module-ownership.json+++ b/packages/twenty-ui/docs/module-ownership.json@@ -1,6 +1,7 @@{"primitives": ["AlertDialog",+ "Autocomplete","Avatar","Banner","Breadcrumb",diff --git a/packages/twenty-ui/docs/public-exports.json b/packages/twenty-ui/docs/public-exports.jsonindex 90c835ee41b..4b538330bf0 100644--- a/packages/twenty-ui/docs/public-exports.json+++ b/packages/twenty-ui/docs/public-exports.json@@ -700,6 +700,7 @@"primitives/input": {"reExports": [],"values": {+ "Autocomplete": "primitives/input/Autocomplete/Autocomplete","Button": "primitives/input/Button/Button","ButtonGroup": "primitives/input/ButtonGroup/ButtonGroup","Checkbox": "primitives/input/Checkbox/Checkbox",@@ -716,6 +717,13 @@"Textarea": "primitives/input/Textarea/Textarea"},"types": {+ "AutocompleteEmptyProps": "primitives/input/Autocomplete/types/AutocompleteEmptyProps",+ "AutocompleteInputGroupProps": "primitives/input/Autocomplete/types/AutocompleteInputGroupProps",+ "AutocompleteInputProps": "primitives/input/Autocomplete/types/AutocompleteInputProps",+ "AutocompleteItemProps": "primitives/input/Autocomplete/types/AutocompleteItemProps",+ "AutocompleteListProps": "primitives/input/Autocomplete/types/AutocompleteListProps",+ "AutocompletePopupProps": "primitives/input/Autocomplete/types/AutocompletePopupProps",+ "AutocompleteRootProps": "primitives/input/Autocomplete/types/AutocompleteRootProps","ButtonColor": "primitives/input/Button/types/ButtonColor","ButtonGroupProps": "primitives/input/ButtonGroup/types/ButtonGroupProps","ButtonProps": "primitives/input/Button/types/ButtonProps",diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.jsonindex 6fe93cb901a..74ff70fde96 100644--- a/packages/twenty-ui/generated/components.docs.json+++ b/packages/twenty-ui/generated/components.docs.json@@ -2575,6 +2575,553 @@}]},+ {+ "name": "Autocomplete",+ "entryPoint": "twenty-ui/primitives/input",+ "slug": "input/autocomplete",+ "props": [],+ "parts": [+ {+ "name": "Root",+ "props": [+ {+ "name": "actionsRef",+ "type": "RefObject<AutocompleteRootActions | null>",+ "required": false,+ "defaultValue": null,+ "description": "A ref to imperative actions.\n- `unmount`: Manually unmounts the autocomplete.\nCall this after any externally controlled closing animation finishes."+ },+ {+ "name": "autoHighlight",+ "type": "boolean | \"always\"",+ "required": false,+ "defaultValue": "false",+ "description": "Whether the first matching item is highlighted automatically.\n- `true`: highlight after the user types and keep the highlight while the query changes.\n- `'always'`: always highlight the first item."+ },+ {+ "name": "defaultOpen",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Whether the popup is initially open.\n\nTo render a controlled popup, use the `open` prop instead."+ },+ {+ "name": "defaultValue",+ "type": "string | number | readonly string[]",+ "required": false,+ "defaultValue": null,+ "description": "The uncontrolled input value of the autocomplete when it's initially rendered.\n\nTo render a controlled autocomplete, use the `value` prop instead."+ },+ {+ "name": "disabled",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Whether the component should ignore user interaction."+ },+ {+ "name": "filter",+ "type": "((item: TItem, query: string, itemToString?: ((item: TItem) => string) | undefined) => boolean) | null",+ "required": false,+ "defaultValue": null,+ "description": "Filter function used to match items against the input query."+ },+ {+ "name": "filteredItems",+ "type": "readonly TItem[] | readonly Group<TItem>[]",+ "required": false,+ "defaultValue": null,+ "description": "Filtered items to display in the list.\nWhen provided, the list uses these items instead of filtering the `items` prop internally.\nWhen `items` is also provided, this array must preserve its flat or grouped structure.\nNullish entries are not supported, as in `items`.\nUse when you want to control filtering logic externally with the `useFilter()` hook."+ },+ {+ "name": "form",+ "type": "string",+ "required": false,+ "defaultValue": null,+ "description": "Identifies the form that owns the internal input.\nUseful when the autocomplete is rendered outside the form."+ },+ {+ "name": "grid",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Whether list items are presented in a grid layout.\nWhen enabled, arrow keys navigate across rows and columns inferred from DOM rows."+ },+ {+ "name": "highlightItemOnHover",+ "type": "boolean",+ "required": false,+ "defaultValue": "true",+ "description": "Whether moving the pointer over items should highlight them.\nDisabling this prop allows CSS `:hover` to be differentiated from the `:focus` (`data-highlighted`) state."+ },+ {+ "name": "id",+ "type": "string",+ "required": false,+ "defaultValue": null,+ "description": "The id of the component."+ },+ {+ "name": "inline",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Whether the list is rendered inline without using the component's own popup.\n\nSpecify `open` unconditionally in conjunction with this prop so the list is considered\nvisible: `<Autocomplete.Root inline open>`"+ },+ {+ "name": "inputRef",+ "type": "Ref<HTMLInputElement>",+ "required": false,+ "defaultValue": null,+ "description": "A ref to the hidden input element."+ },+ {+ "name": "items",+ "type": "readonly TItem[]",+ "required": false,+ "defaultValue": null,+ "description": "Items to display in the list. Nullish entries are not supported."+ },+ {+ "name": "itemToStringValue",+ "type": "((itemValue: TItem) => string)",+ "required": false,+ "defaultValue": null,+ "description": "When the item values are objects (`<Autocomplete.Item value={object}>`), this function converts the object value to a string representation for both display in the input and form submission.\nIf the shape of the object is `{ value, label }`, the label will be used automatically without needing to specify this prop."+ },+ {+ "name": "keepHighlight",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Whether the highlighted item should be preserved when the pointer leaves the list."+ },+ {+ "name": "limit",+ "type": "number",+ "required": false,+ "defaultValue": "-1",+ "description": "The maximum number of items to display in the list."+ },+ {+ "name": "locale",+ "type": "LocalesArgument",+ "required": false,+ "defaultValue": null,+ "description": "The locale to use for string comparison.\nDefaults to the user's runtime locale."+ },+ {+ "name": "loopFocus",+ "type": "boolean",+ "required": false,+ "defaultValue": "true",+ "description": "Whether to loop keyboard focus back to the input when the end of the list is reached while using the arrow keys. The first item can then be reached by pressing <kbd>ArrowDown</kbd> again from the input, or the last item can be reached by pressing <kbd>ArrowUp</kbd> from the input.\nThe input is always included in the focus loop per [ARIA Authoring Practices](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/).\nWhen disabled, focus does not move when on the last element and the user presses <kbd>ArrowDown</kbd>, or when on the first element and the user presses <kbd>ArrowUp</kbd>."+ },+ {+ "name": "modal",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Determines if the popup enters a modal state when open.\n- `true`: user interaction is limited to the popup: document page scroll is locked and pointer interactions on outside elements are disabled.\n- `false`: user interaction with the rest of the document is allowed.\n\nOn touch devices, a `true` modal blocks outside taps but leaves the page scrollable unless the popup spans nearly the full viewport width, matching native iOS behavior."+ },+ {+ "name": "mode",+ "type": "\"both\" | \"inline\" | \"list\" | \"none\"",+ "required": false,+ "defaultValue": "list",+ "description": "Controls how the autocomplete behaves with respect to list filtering and inline autocompletion.\n- `list` (default): items are dynamically filtered based on the input value. The input value does not change based on the active item.\n- `both`: items are dynamically filtered based on the input value, which will temporarily change based on the active item (inline autocompletion).\n- `inline`: items are static (not filtered), and the input value will temporarily change based on the active item (inline autocompletion).\n- `none`: items are static (not filtered), and the input value will not change based on the active item."+ },+ {+ "name": "name",+ "type": "string",+ "required": false,+ "defaultValue": null,+ "description": "Identifies the field when a form is submitted."+ },+ {+ "name": "onItemHighlighted",+ "type": "((highlightedValue: TItem | undefined, eventDetails: HighlightEventDetails) => void)",+ "required": false,+ "defaultValue": null,+ "description": "Callback fired when an item is highlighted or unhighlighted.\nReceives the highlighted item value (or `undefined` if no item is highlighted) and event details with a `reason` property describing why the highlight changed.\nThe `reason` can be:\n- `'keyboard'`: the highlight changed due to keyboard navigation.\n- `'pointer'`: the highlight changed due to pointer hovering.\n- `'none'`: the highlight changed programmatically."+ },+ {+ "name": "onOpenChange",+ "type": "((open: boolean, eventDetails: AutocompleteRootChangeEventDetails) => void)",+ "required": false,+ "defaultValue": null,+ "description": "Event handler called when the popup is opened or closed."+ },+ {+ "name": "onOpenChangeComplete",+ "type": "((open: boolean) => void)",+ "required": false,+ "defaultValue": null,+ "description": "Event handler called after any animations complete when the popup is opened or closed."+ },+ {+ "name": "onValueChange",+ "type": "((value: string, eventDetails: AutocompleteRootChangeEventDetails) => void)",+ "required": false,+ "defaultValue": null,+ "description": "Event handler called when the input value of the autocomplete changes."+ },+ {+ "name": "open",+ "type": "boolean",+ "required": false,+ "defaultValue": null,+ "description": "Whether the popup is currently open. Use when controlled."+ },+ {+ "name": "openOnInputClick",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Whether the popup opens when clicking the input."+ },+ {+ "name": "readOnly",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Whether the user should be unable to choose a different option from the popup."+ },+ {+ "name": "required",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Whether the user must choose a value before submitting a form."+ },+ {+ "name": "submitOnItemClick",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Whether clicking an item should submit the autocomplete's owning form.\nBy default, clicking an item via a pointer or <kbd>Enter</kbd> key does not submit the owning form.\nUseful when the autocomplete is used as a single-field form search input."+ },+ {+ "name": "value",+ "type": "string | number | readonly string[]",+ "required": false,+ "defaultValue": null,+ "description": "The input value of the autocomplete. Use when controlled."+ },+ {+ "name": "virtualized",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Whether the items are being externally virtualized."+ }+ ]+ },+ {+ "name": "InputGroup",+ "props": [+ {+ "name": "className",+ "type": "string | ((state: AutocompleteInputGroupState) => string | undefined)",+ "required": false,+ "defaultValue": null,+ "description": "CSS class applied to the element, or a function that\nreturns a class based on the component's state."+ },+ {+ "name": "render",+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, AutocompleteInputGroupState>",+ "required": false,+ "defaultValue": null,+ "description": "Allows you to replace the component's HTML element\nwith a different tag, or compose it with another component.\n\nAccepts a `ReactElement` or a function that returns the element to render."+ },+ {+ "name": "style",+ "type": "CSSProperties | ((state: AutocompleteInputGroupState) => CSSProperties | undefined)",+ "required": false,+ "defaultValue": null,+ "description": "Style applied to the element, or a function that\nreturns a style object based on the component's state."+ }+ ]+ },+ {+ "name": "Input",+ "props": [+ {+ "name": "className",+ "type": "string | ((state: ComboboxInputState) => string | undefined)",+ "required": false,+ "defaultValue": null,+ "description": "CSS class applied to the element, or a function that\nreturns a class based on the component's state."+ },+ {+ "name": "disabled",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Whether the component should ignore user interaction."+ },+ {+ "name": "render",+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, ComboboxInputState>",+ "required": false,+ "defaultValue": null,+ "description": "Allows you to replace the component's HTML element\nwith a different tag, or compose it with another component.\n\nAccepts a `ReactElement` or a function that returns the element to render."+ },+ {+ "name": "size",+ "type": "\"md\" | \"sm\"",+ "required": false,+ "defaultValue": null,+ "description": "Visual size of the input. Inside an InputGroup, the group size applies."+ },+ {+ "name": "style",+ "type": "CSSProperties | ((state: ComboboxInputState) => CSSProperties | undefined)",+ "required": false,+ "defaultValue": null,+ "description": "Style applied to the element, or a function that\nreturns a style object based on the component's state."+ }+ ]+ },+ {+ "name": "Popup",+ "props": [+ {+ "name": "align",+ "type": "\"center\" | \"end\" | \"start\"",+ "required": false,+ "defaultValue": "start",+ "description": "How to align the popup relative to the specified side."+ },+ {+ "name": "alignOffset",+ "type": "number | OffsetFunction",+ "required": false,+ "defaultValue": "0",+ "description": "Additional offset along the alignment axis in pixels.\nAlso accepts a function that returns the offset to read the dimensions of the anchor\nand positioner elements, along with its side and alignment.\n\nThe function takes a `data` object parameter with the following properties:\n- `data.anchor`: the dimensions of the anchor element with properties `width` and `height`.\n- `data.positioner`: the dimensions of the positioner element with properties `width` and `height`.\n- `data.side`: which side of the anchor element the positioner is aligned against.\n- `data.align`: how the positioner is aligned relative to the specified side."+ },+ {+ "name": "anchor",+ "type": "Element | VirtualElement | RefObject<Element | null> | (() => Element | VirtualElement | null) | null",+ "required": false,+ "defaultValue": null,+ "description": "An element to position the popup against.\nBy default, the popup will be positioned against the trigger."+ },+ {+ "name": "className",+ "type": "string | ((state: ComboboxPopupState) => string | undefined)",+ "required": false,+ "defaultValue": null,+ "description": "CSS class applied to the element, or a function that\nreturns a class based on the component's state."+ },+ {+ "name": "collisionPadding",+ "type": "Padding",+ "required": false,+ "defaultValue": "5",+ "description": "Additional space to maintain from the edge of the collision boundary."+ },+ {+ "name": "container",+ "type": "HTMLElement | ShadowRoot | RefObject<HTMLElement | ShadowRoot | null> | null",+ "required": false,+ "defaultValue": null,+ "description": "Element the popup is portaled into. Defaults to the theme portal container."+ },+ {+ "name": "finalFocus",+ "type": "boolean | RefObject<HTMLElement | null> | ((closeType: InteractionType) => boolean | void | HTMLElement | null)",+ "required": false,+ "defaultValue": null,+ "description": "Determines the element to focus when the popup is closed.\n\n- `false`: Do not move focus.\n- `true`: Move focus based on the default behavior (trigger or previously focused element).\n- `RefObject`: Move focus to the ref element.\n- `function`: Called with the interaction type (`mouse`, `touch`, `pen`, or `keyboard`).\n Return an element to focus, `true` to use the default behavior, or `false`/`undefined` to do nothing."+ },+ {+ "name": "initialFocus",+ "type": "boolean | RefObject<HTMLElement | null> | ((openType: InteractionType) => boolean | void | HTMLElement | null)",+ "required": false,+ "defaultValue": null,+ "description": "Determines the element to focus when the popup is opened.\n\n- `false`: Do not move focus.\n- `true`: Move focus based on the default behavior (first tabbable element or popup).\n- `RefObject`: Move focus to the ref element.\n- `function`: Called with the interaction type (`mouse`, `touch`, `pen`, or `keyboard`).\n Return an element to focus, `true` to use the default behavior, or `false`/`undefined` to do nothing."+ },+ {+ "name": "render",+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, ComboboxPopupState>",+ "required": false,+ "defaultValue": null,+ "description": "Allows you to replace the component's HTML element\nwith a different tag, or compose it with another component.\n\nAccepts a `ReactElement` or a function that returns the element to render."+ },+ {+ "name": "side",+ "type": "\"bottom\" | \"inline-end\" | \"inline-start\" | \"left\" | \"right\" | \"top\"",+ "required": false,+ "defaultValue": "bottom",+ "description": "Which side of the anchor element to align the popup against.\nMay automatically change to avoid collisions."+ },+ {+ "name": "sideOffset",+ "type": "number | OffsetFunction",+ "required": false,+ "defaultValue": "8",+ "description": "Distance between the anchor and the popup in pixels.\nAlso accepts a function that returns the distance to read the dimensions of the anchor\nand positioner elements, along with its side and alignment.\n\nThe function takes a `data` object parameter with the following properties:\n- `data.anchor`: the dimensions of the anchor element with properties `width` and `height`.\n- `data.positioner`: the dimensions of the positioner element with properties `width` and `height`.\n- `data.side`: which side of the anchor element the positioner is aligned against.\n- `data.align`: how the positioner is aligned relative to the specified side."+ },+ {+ "name": "style",+ "type": "CSSProperties | ((state: ComboboxPopupState) => CSSProperties | undefined)",+ "required": false,+ "defaultValue": null,+ "description": "Style applied to the element, or a function that\nreturns a style object based on the component's state."+ },+ {+ "name": "width",+ "type": "string | number",+ "required": false,+ "defaultValue": null,+ "description": "Width of the popup. Overrides its default minimum anchor width."+ }+ ]+ },+ {+ "name": "List",+ "props": [+ {+ "name": "className",+ "type": "string | ((state: ComboboxListState) => string | undefined)",+ "required": false,+ "defaultValue": null,+ "description": "CSS class applied to the element, or a function that\nreturns a class based on the component's state."+ },+ {+ "name": "render",+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, ComboboxListState>",+ "required": false,+ "defaultValue": null,+ "description": "Allows you to replace the component's HTML element\nwith a different tag, or compose it with another component.\n\nAccepts a `ReactElement` or a function that returns the element to render."+ },+ {+ "name": "style",+ "type": "CSSProperties | ((state: ComboboxListState) => CSSProperties | undefined)",+ "required": false,+ "defaultValue": null,+ "description": "Style applied to the element, or a function that\nreturns a style object based on the component's state."+ }+ ]+ },+ {+ "name": "Item",+ "props": [+ {+ "name": "className",+ "type": "string | ((state: AutocompleteItemState) => string | undefined)",+ "required": false,+ "defaultValue": null,+ "description": "CSS class applied to the element, or a function that\nreturns a class based on the component's state."+ },+ {+ "name": "description",+ "type": "ReactNode",+ "required": false,+ "defaultValue": null,+ "description": "Supporting text, placed according to `descriptionPlacement`."+ },+ {+ "name": "descriptionPlacement",+ "type": "\"end\" | \"inline\"",+ "required": false,+ "defaultValue": "inline",+ "description": "Where the description renders: inline after the content or at the end of\nthe row."+ },+ {+ "name": "disabled",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Whether the component should ignore user interaction."+ },+ {+ "name": "endIcon",+ "type": "ReactNode",+ "required": false,+ "defaultValue": null,+ "description": "Icon rendered after the content."+ },+ {+ "name": "index",+ "type": "number",+ "required": false,+ "defaultValue": null,+ "description": "The index of the item in the list. Improves performance when specified by avoiding the need to calculate the index automatically from the DOM."+ },+ {+ "name": "nativeButton",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Whether the component renders a native `<button>` element when replacing it\nvia the `render` prop.\nSet to `true` if the rendered element is a native button."+ },+ {+ "name": "onClick",+ "type": "((event: BaseUIEvent<MouseEvent<HTMLDivElement, MouseEvent>>) => void)",+ "required": false,+ "defaultValue": null,+ "description": "An optional click handler for the item when selected.\nIt fires when clicking the item with the pointer, as well as when pressing `Enter` with the keyboard if the item is highlighted when the `Input` or `List` element has focus."+ },+ {+ "name": "render",+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, AutocompleteItemState>",+ "required": false,+ "defaultValue": null,+ "description": "Allows you to replace the component's HTML element\nwith a different tag, or compose it with another component.\n\nAccepts a `ReactElement` or a function that returns the element to render."+ },+ {+ "name": "startIcon",+ "type": "ReactNode",+ "required": false,+ "defaultValue": null,+ "description": "Icon rendered before the content."+ },+ {+ "name": "style",+ "type": "CSSProperties | ((state: AutocompleteItemState) => CSSProperties | undefined)",+ "required": false,+ "defaultValue": null,+ "description": "Style applied to the element, or a function that\nreturns a style object based on the component's state."+ },+ {+ "name": "value",+ "type": "any",+ "required": false,+ "defaultValue": "null",+ "description": "A unique value that identifies this item."+ }+ ]+ },+ {+ "name": "Empty",+ "props": [+ {+ "name": "className",+ "type": "string | ((state: ComboboxEmptyState) => string | undefined)",+ "required": false,+ "defaultValue": null,+ "description": "CSS class applied to the element, or a function that\nreturns a class based on the component's state."+ },+ {+ "name": "render",+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, ComboboxEmptyState>",+ "required": false,+ "defaultValue": null,+ "description": "Allows you to replace the component's HTML element\nwith a different tag, or compose it with another component.\n\nAccepts a `ReactElement` or a function that returns the element to render."+ },+ {+ "name": "style",+ "type": "CSSProperties | ((state: ComboboxEmptyState) => CSSProperties | undefined)",+ "required": false,+ "defaultValue": null,+ "description": "Style applied to the element, or a function that\nreturns a style object based on the component's state."+ }+ ]+ }+ ]+ },{"name": "Select","entryPoint": "twenty-ui/primitives/input",diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownRoot.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownRoot.tsxindex 7cbe8f9b018..1c6fb89fd55 100644--- a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownRoot.tsx+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownRoot.tsx@@ -1,6 +1,7 @@import { useCallback, useContext, useRef, useState } from 'react';import { Popover } from '@ui/primitives/surfaces/Popover/Popover';+import { preventDismissingClickActivation } from '@ui/utilities/internal/preventDismissingClickActivation';import { isDefined } from '@ui/utilities/utils/isDefined';import { type DropdownRootProps } from '../types/DropdownRootProps';@@ -10,7 +11,6 @@ import { type DropdownFocusTarget } from './DropdownFocusTarget';import { type DropdownPageFocusRequest } from './DropdownPageFocusRequest';import { DropdownNestedRootEffect } from './DropdownNestedRootEffect';import { isDropdownDismissPrevented } from './isDropdownDismissPrevented';-import { preventDismissingClickActivation } from './preventDismissingClickActivation';import { useRegisteredElementId } from './useRegisteredElementId';type PageHistoryEntry = { id?: string; trigger?: DropdownFocusTarget };diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/Autocomplete.module.scss b/packages/twenty-ui/src/primitives/input/Autocomplete/Autocomplete.module.scssnew file mode 100644index 00000000000..b1f71cd5eee--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/Autocomplete.module.scss@@ -0,0 +1,56 @@+.inputGroup {+ align-items: center;+ display: flex;+ min-inline-size: 0;+ position: relative;+}++.positioner {+ z-index: var(--t-last-layer-z-index);+}++.popup {+ backdrop-filter: var(--t-blur-medium);+ background: var(--t-background-transparent-primary);+ border: 1px solid var(--t-border-color-medium);+ border-radius: var(--t-border-radius-md);+ box-shadow: var(--t-box-shadow-strong);+ box-sizing: border-box;+ color: var(--t-font-color-primary);+ display: flex;+ flex-direction: column;+ min-inline-size: var(--anchor-width);+ max-inline-size: var(--available-width);+ max-block-size: var(--available-height);+ outline: none;+ overflow: auto;+ overscroll-behavior: contain;+ padding: var(--t-spacing-1);+ transition: opacity duration(fast) ease-out;++ &[data-starting-style],+ &[data-ending-style] {+ opacity: 0;+ }++ &[data-ending-style] {+ transition-timing-function: ease-in;+ }+}++.list {+ max-block-size: 176px;+ outline: none;+ overflow-y: auto;+ overscroll-behavior: contain;+}++.empty {+ color: var(--t-font-color-secondary);+ font-family: var(--t-font-family);+ font-size: var(--t-font-size-md);++ &:not(:empty) {+ padding: var(--t-spacing-2);+ }+}diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/Autocomplete.module.scss.d.ts b/packages/twenty-ui/src/primitives/input/Autocomplete/Autocomplete.module.scss.d.tsnew file mode 100644index 00000000000..154524e3c5d--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/Autocomplete.module.scss.d.ts@@ -0,0 +1,8 @@+declare const classNames: {+ readonly inputGroup: 'inputGroup';+ readonly positioner: 'positioner';+ readonly popup: 'popup';+ readonly list: 'list';+ readonly empty: 'empty';+};+export default classNames;diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/Autocomplete.tsx b/packages/twenty-ui/src/primitives/input/Autocomplete/Autocomplete.tsxnew file mode 100644index 00000000000..1b29d98ccc1--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/Autocomplete.tsx@@ -0,0 +1,19 @@+import { AutocompleteEmpty } from './internal/AutocompleteEmpty';+import { AutocompleteInput } from './internal/AutocompleteInput';+import { AutocompleteInputGroup } from './internal/AutocompleteInputGroup';+import { AutocompleteItem } from './internal/AutocompleteItem';+import { AutocompleteList } from './internal/AutocompleteList';+import { AutocompletePopup } from './internal/AutocompletePopup';+import { AutocompleteRoot } from './internal/AutocompleteRoot';++const createAutocomplete = () => ({+ Root: AutocompleteRoot,+ InputGroup: AutocompleteInputGroup,+ Input: AutocompleteInput,+ Popup: AutocompletePopup,+ List: AutocompleteList,+ Item: AutocompleteItem,+ Empty: AutocompleteEmpty,+});++export const Autocomplete = /* @__PURE__ */ createAutocomplete();diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/__stories__/Autocomplete.interactions.stories.tsx b/packages/twenty-ui/src/primitives/input/Autocomplete/__stories__/Autocomplete.interactions.stories.tsxnew file mode 100644index 00000000000..8dc4d2200af--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/__stories__/Autocomplete.interactions.stories.tsx@@ -0,0 +1,211 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { useState } from 'react';+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';++import { Button } from '@ui/primitives/input/Button/Button';+import { ComponentDecorator } from '@ui/testing';++import { Autocomplete } from '../Autocomplete';+import { AutocompleteExample } from './AutocompleteExample';++const meta: Meta<typeof AutocompleteExample> = {+ title: 'UI/Input/Autocomplete/Interactions',+ component: AutocompleteExample,+ decorators: [ComponentDecorator],+ parameters: { container: { width: 280, height: 260 } },+};++export default meta;+type Story = StoryObj<typeof AutocompleteExample>;++export const KeyboardFocus: Story = {+ args: { filter: null, onValueChange: fn() },+ play: async ({ canvasElement }) => {+ const input = within(canvasElement).getByRole('combobox');+ await userEvent.type(input, 'fruit');+ const body = within(canvasElement.ownerDocument.body);+ const apple = await body.findByRole('option', { name: 'Apple' });+ await waitFor(() =>+ expect(input).toHaveAttribute('aria-activedescendant', apple.id),+ );+ await userEvent.keyboard('{ArrowDown}');+ const banana = body.getByRole('option', { name: 'Banana' });+ await expect(input).toHaveAttribute('aria-activedescendant', banana.id);+ await expect(input).toHaveFocus();+ await expect(input).toHaveValue('fruit');+ await userEvent.click(input);+ await expect(banana).toBeVisible();+ await userEvent.keyboard('{Enter}');+ await expect(input).toHaveValue('Banana');+ await expect(input).toHaveFocus();+ await userEvent.type(input, 'x');+ await body.findByRole('listbox');+ await userEvent.keyboard('{Escape}');+ await waitFor(() =>+ expect(input).toHaveAttribute('aria-expanded', 'false'),+ );+ await expect(input).toHaveFocus();+ },+};++export const EmptyResults: Story = {+ play: async ({ canvasElement }) => {+ const input = within(canvasElement).getByRole('combobox');+ await userEvent.type(input, 'Kiwi');+ const empty = await within(canvasElement.ownerDocument.body).findByText(+ 'No fruits found',+ );+ await expect(empty).toBeVisible();+ await expect(input).toHaveFocus();+ await userEvent.clear(input);+ await userEvent.type(input, 'Cherry');+ await within(canvasElement.ownerDocument.body).findByRole('option', {+ name: 'Cherry',+ });+ await expect(+ within(canvasElement.ownerDocument.body).queryByText('No fruits found'),+ ).not.toBeInTheDocument();+ },+};++const ControlledResultsExample = () => {+ const [open, setOpen] = useState(false);+ const [value, setValue] = useState('');+ const [items, setItems] = useState<string[]>([]);+ const [outsideClickCount, setOutsideClickCount] = useState(0);++ return (+ <>+ <Autocomplete.Root+ items={items}+ filter={null}+ autoHighlight="always"+ value={value}+ open={open}+ onValueChange={(nextValue, details) => {+ if (details.reason !== 'escape-key') {+ setValue(nextValue);+ }+ }}+ onOpenChange={(nextOpen, details) => {+ if (details.reason !== 'input-change') {+ setOpen(nextOpen);+ }+ }}+ >+ <Autocomplete.Input render={<input aria-label="Location" />} />+ <Autocomplete.Popup width={200} style={{ maxInlineSize: 180 }}>+ <Autocomplete.List>+ {(item: string) => (+ <Autocomplete.Item key={item} value={item}>+ {item}+ </Autocomplete.Item>+ )}+ </Autocomplete.List>+ </Autocomplete.Popup>+ </Autocomplete.Root>+ <Button+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => {+ setItems(['Paris, France', 'Paris, Texas']);+ setOpen(true);+ }}+ >+ Receive results+ </Button>+ <Button onClick={() => setOutsideClickCount((count) => count + 1)}>+ Outside+ </Button>+ <span>{`Outside clicks: ${outsideClickCount}`}</span>+ </>+ );+};++export const ControlledResults: Story = {+ render: () => <ControlledResultsExample />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole('combobox', { name: 'Location' });+ const outsideButton = canvas.getByRole('button', { name: 'Outside' });+ await userEvent.type(input, 'Paris');+ await expect(input).toHaveAttribute('aria-expanded', 'false');+ await userEvent.click(+ canvas.getByRole('button', { name: 'Receive results' }),+ );+ const option = await within(canvasElement.ownerDocument.body).findByRole(+ 'option',+ { name: 'Paris, France' },+ );+ await expect(input).toHaveFocus();+ const listbox = within(canvasElement.ownerDocument.body).getByRole(+ 'listbox',+ );+ await expect(listbox.getBoundingClientRect().width).toBeLessThan(180);+ await waitFor(() =>+ expect(input).toHaveAttribute('aria-activedescendant', option.id),+ );+ await userEvent.keyboard('{Escape}');+ await expect(input).toHaveValue('Paris');+ await expect(input).toHaveFocus();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Receive results' }),+ );+ await within(canvasElement.ownerDocument.body).findByRole('listbox');+ await userEvent.click(outsideButton);+ await waitFor(() =>+ expect(input).toHaveAttribute('aria-expanded', 'false'),+ );+ await expect(input).toHaveValue('Paris');+ await expect(canvas.getByText('Outside clicks: 0')).toBeVisible();+ await userEvent.click(outsideButton);+ await expect(canvas.getByText('Outside clicks: 1')).toBeVisible();+ },+};++const PreventedEnterExample = () => {+ const [enterCount, setEnterCount] = useState(0);++ return (+ <>+ <Autocomplete.Root items={['Apple', 'Banana']} autoHighlight="always">+ <Autocomplete.Input+ aria-label="Fruit"+ onKeyDown={(event) => {+ if (event.key === 'Enter') {+ event.preventDefault();+ setEnterCount((count) => count + 1);+ }+ }}+ />+ <Autocomplete.Popup>+ <Autocomplete.List>+ {(fruit: string) => (+ <Autocomplete.Item key={fruit} value={fruit}>+ {fruit}+ </Autocomplete.Item>+ )}+ </Autocomplete.List>+ </Autocomplete.Popup>+ </Autocomplete.Root>+ <span>{`Enter count: ${enterCount}`}</span>+ </>+ );+};++export const PreventedKeyDown: Story = {+ render: () => <PreventedEnterExample />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const input = canvas.getByRole('combobox', { name: 'Fruit' });+ await userEvent.type(input, 'a');+ const apple = await body.findByRole('option', { name: 'Apple' });+ await waitFor(() =>+ expect(input).toHaveAttribute('aria-activedescendant', apple.id),+ );+ await userEvent.keyboard('{Enter}');+ await expect(canvas.getByText('Enter count: 1')).toBeVisible();+ await expect(input).toHaveValue('a');+ await expect(input).toHaveAttribute('aria-expanded', 'true');+ },+};diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/__stories__/Autocomplete.stories.tsx b/packages/twenty-ui/src/primitives/input/Autocomplete/__stories__/Autocomplete.stories.tsxnew file mode 100644index 00000000000..007c2d6b164--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/__stories__/Autocomplete.stories.tsx@@ -0,0 +1,41 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { expect, userEvent, waitFor, within } from 'storybook/test';++import { ComponentDecorator } from '@ui/testing';++import { AutocompleteExample } from './AutocompleteExample';++const meta: Meta<typeof AutocompleteExample> = {+ title: 'UI/Input/Autocomplete',+ component: AutocompleteExample,+ decorators: [ComponentDecorator],+ parameters: { container: { width: 280, height: 240 } },+};++export default meta;+type Story = StoryObj<typeof AutocompleteExample>;++export const Default: Story = {+ play: async ({ canvasElement }) => {+ const input = within(canvasElement).getByRole('combobox', {+ name: 'Fruit',+ });+ await userEvent.type(input, 'Ch');+ const option = await within(canvasElement.ownerDocument.body).findByRole(+ 'option',+ { name: 'Cherry' },+ );+ await expect(input).toHaveFocus();+ await waitFor(() =>+ expect(input).toHaveAttribute('aria-activedescendant', option.id),+ );+ await userEvent.keyboard('{Enter}');+ await expect(input).toHaveValue('Cherry');+ await expect(input).toHaveFocus();+ await waitFor(() =>+ expect(input).toHaveAttribute('aria-expanded', 'false'),+ );+ },+};++export const Documentation: Story = {};diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/__stories__/AutocompleteExample.tsx b/packages/twenty-ui/src/primitives/input/Autocomplete/__stories__/AutocompleteExample.tsxnew file mode 100644index 00000000000..0adac489559--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/__stories__/AutocompleteExample.tsx@@ -0,0 +1,26 @@+import { Autocomplete } from '../Autocomplete';+import { type AutocompleteRootProps } from '../types/AutocompleteRootProps';++const FRUITS = ['Apple', 'Banana', 'Cherry'];++export const AutocompleteExample = (+ props: Omit<AutocompleteRootProps<string>, 'items'> & {+ items?: readonly string[];+ },+) => (+ <Autocomplete.Root items={FRUITS} autoHighlight="always" {...props}>+ <Autocomplete.InputGroup>+ <Autocomplete.Input aria-label="Fruit" placeholder="Search fruits" />+ </Autocomplete.InputGroup>+ <Autocomplete.Popup>+ <Autocomplete.Empty>No fruits found</Autocomplete.Empty>+ <Autocomplete.List>+ {(fruit: string) => (+ <Autocomplete.Item key={fruit} value={fruit}>+ {fruit}+ </Autocomplete.Item>+ )}+ </Autocomplete.List>+ </Autocomplete.Popup>+ </Autocomplete.Root>+);diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/__tests__/Autocomplete.test.tsx b/packages/twenty-ui/src/primitives/input/Autocomplete/__tests__/Autocomplete.test.tsxnew file mode 100644index 00000000000..a1fe7b1b812--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/__tests__/Autocomplete.test.tsx@@ -0,0 +1,72 @@+import { type ReactNode } from 'react';++import { runComponentConformance } from '@test-utilities/conformance/runComponentConformance';+import inputStyles from '@ui/primitives/input/Input/Input.module.scss';+import listItemStyles from '@ui/primitives/navigation/ListItem/ListItem.module.scss';++import { Autocomplete } from '../Autocomplete';+import styles from '../Autocomplete.module.scss';++const RootWrapper = ({ children }: { children: ReactNode }) => (+ <Autocomplete.Root>{children}</Autocomplete.Root>+);+const OpenWrapper = ({ children }: { children: ReactNode }) => (+ <Autocomplete.Root open items={[]}>+ <Autocomplete.Input aria-label="Search" />+ {children}+ </Autocomplete.Root>+);+const PopupWrapper = ({ children }: { children: ReactNode }) => (+ <OpenWrapper>+ <Autocomplete.Popup>{children}</Autocomplete.Popup>+ </OpenWrapper>+);+const ListWrapper = ({ children }: { children: ReactNode }) => (+ <PopupWrapper>+ <Autocomplete.List>{children}</Autocomplete.List>+ </PopupWrapper>+);++runComponentConformance({+ name: 'Autocomplete.InputGroup',+ element: <Autocomplete.InputGroup />,+ refInstanceOf: HTMLDivElement,+ wrapper: RootWrapper,+ ownClassName: styles.inputGroup,+});+runComponentConformance({+ name: 'Autocomplete.Input',+ element: <Autocomplete.Input aria-label="Search" />,+ refInstanceOf: HTMLInputElement,+ wrapper: RootWrapper,+ ownClassName: inputStyles.input,+ renderPropTagName: 'input',+});+runComponentConformance({+ name: 'Autocomplete.Popup',+ element: <Autocomplete.Popup />,+ refInstanceOf: HTMLDivElement,+ wrapper: OpenWrapper,+ ownClassName: styles.popup,+});+runComponentConformance({+ name: 'Autocomplete.List',+ element: <Autocomplete.List />,+ refInstanceOf: HTMLDivElement,+ wrapper: PopupWrapper,+ ownClassName: styles.list,+});+runComponentConformance({+ name: 'Autocomplete.Item',+ element: <Autocomplete.Item value="first">First</Autocomplete.Item>,+ refInstanceOf: HTMLDivElement,+ wrapper: ListWrapper,+ ownClassName: listItemStyles.root,+});+runComponentConformance({+ name: 'Autocomplete.Empty',+ element: <Autocomplete.Empty>No results</Autocomplete.Empty>,+ refInstanceOf: HTMLDivElement,+ wrapper: PopupWrapper,+ ownClassName: styles.empty,+});diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteEmpty.tsx b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteEmpty.tsxnew file mode 100644index 00000000000..41edff740ef--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteEmpty.tsx@@ -0,0 +1,16 @@+import { Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';++import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';++import styles from '../Autocomplete.module.scss';+import { type AutocompleteEmptyProps } from '../types/AutocompleteEmptyProps';++export const AutocompleteEmpty = ({+ className,+ ...props+}: AutocompleteEmptyProps) => (+ <AutocompletePrimitive.Empty+ {...props}+ className={mergeClassNames(styles.empty, className)}+ />+);diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteInput.tsx b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteInput.tsxnew file mode 100644index 00000000000..67884841f0f--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteInput.tsx@@ -0,0 +1,38 @@+import { Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';+import { clsx } from 'clsx';+import { useContext } from 'react';++import inputStyles from '@ui/primitives/input/Input/Input.module.scss';+import { InputGroupContext } from '@ui/primitives/input/InputGroup/internal/InputGroupContext';+import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';+import { isDefined } from '@ui/utilities/utils/isDefined';++import { type AutocompleteInputProps } from '../types/AutocompleteInputProps';++export const AutocompleteInput = ({+ size,+ className,+ onKeyDown,+ ...props+}: AutocompleteInputProps) => {+ const inputGroup = useContext(InputGroupContext);+ const resolvedSize = size ?? inputGroup?.size ?? 'md';++ return (+ <AutocompletePrimitive.Input+ {...props}+ className={mergeClassNames(+ clsx(inputStyles.input, inputStyles[resolvedSize]),+ className,+ )}+ data-grouped={isDefined(inputGroup) || undefined}+ onKeyDown={(event) => {+ onKeyDown?.(event);++ if (event.defaultPrevented) {+ event.preventBaseUIHandler();+ }+ }}+ />+ );+};diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteInputGroup.tsx b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteInputGroup.tsxnew file mode 100644index 00000000000..714b8bf9ad5--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteInputGroup.tsx@@ -0,0 +1,16 @@+import { Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';++import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';++import styles from '../Autocomplete.module.scss';+import { type AutocompleteInputGroupProps } from '../types/AutocompleteInputGroupProps';++export const AutocompleteInputGroup = ({+ className,+ ...props+}: AutocompleteInputGroupProps) => (+ <AutocompletePrimitive.InputGroup+ {...props}+ className={mergeClassNames(styles.inputGroup, className)}+ />+);diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteItem.tsx b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteItem.tsxnew file mode 100644index 00000000000..dc83f5bb448--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteItem.tsx@@ -0,0 +1,58 @@+import { Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';+import { clsx } from 'clsx';++import { isRenderableSlot } from '@ui/utilities/internal/isRenderableSlot';+import listItemStyles from '@ui/primitives/navigation/ListItem/ListItem.module.scss';+import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';++import { type AutocompleteItemProps } from '../types/AutocompleteItemProps';++export const AutocompleteItem = ({+ className,+ children,+ startIcon,+ endIcon,+ description,+ descriptionPlacement = 'inline',+ ...props+}: AutocompleteItemProps) => (+ <AutocompletePrimitive.Item+ {...props}+ className={mergeClassNames(listItemStyles.root, className)}+ data-color="neutral"+ >+ {isRenderableSlot(startIcon) && (+ <div className={listItemStyles.startIcon} aria-hidden>+ {startIcon}+ </div>+ )}+ <div className={listItemStyles.label}>+ <div className={listItemStyles.text}>{children}</div>+ {isRenderableSlot(description) && descriptionPlacement === 'inline' && (+ <div+ className={clsx(+ listItemStyles.description,+ listItemStyles.inlineDescription,+ )}+ >+ {description}+ </div>+ )}+ </div>+ {isRenderableSlot(description) && descriptionPlacement === 'end' && (+ <div+ className={clsx(+ listItemStyles.description,+ listItemStyles.endDescription,+ )}+ >+ {description}+ </div>+ )}+ {isRenderableSlot(endIcon) && (+ <div className={listItemStyles.endIcon} aria-hidden>+ {endIcon}+ </div>+ )}+ </AutocompletePrimitive.Item>+);diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteList.tsx b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteList.tsxnew file mode 100644index 00000000000..155f7ae96be--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteList.tsx@@ -0,0 +1,16 @@+import { Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';++import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';++import styles from '../Autocomplete.module.scss';+import { type AutocompleteListProps } from '../types/AutocompleteListProps';++export const AutocompleteList = ({+ className,+ ...props+}: AutocompleteListProps) => (+ <AutocompletePrimitive.List+ {...props}+ className={mergeClassNames(styles.list, className)}+ />+);diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompletePopup.tsx b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompletePopup.tsxnew file mode 100644index 00000000000..6933bbf602a--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompletePopup.tsx@@ -0,0 +1,56 @@+import { Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';+import { isFunction } from '@sniptt/guards';++import { useProvidedTextDirection } from '@ui/primitives/layout/TextDirectionProvider/internal/useProvidedTextDirection';+import { useThemeContainer } from '@ui/theme';+import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';+import { isDefined } from '@ui/utilities/utils/isDefined';++import styles from '../Autocomplete.module.scss';+import { type AutocompletePopupProps } from '../types/AutocompletePopupProps';++export const AutocompletePopup = ({+ side = 'bottom',+ align = 'start',+ sideOffset = 8,+ alignOffset,+ anchor,+ collisionPadding,+ width,+ style,+ container,+ className,+ ...props+}: AutocompletePopupProps) => {+ const themeContainer = useThemeContainer();+ const direction = useProvidedTextDirection();++ return (+ <AutocompletePrimitive.Portal+ container={+ container === undefined ? (themeContainer ?? undefined) : container+ }+ >+ <AutocompletePrimitive.Positioner+ dir={direction}+ side={side}+ align={align}+ sideOffset={sideOffset}+ alignOffset={alignOffset}+ anchor={anchor}+ collisionPadding={collisionPadding}+ className={styles.positioner}+ >+ <AutocompletePrimitive.Popup+ {...props}+ className={mergeClassNames(styles.popup, className)}+ style={(state) => ({+ width,+ minInlineSize: isDefined(width) ? 0 : undefined,+ ...(isFunction(style) ? style(state) : style),+ })}+ />+ </AutocompletePrimitive.Positioner>+ </AutocompletePrimitive.Portal>+ );+};diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteRoot.tsx b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteRoot.tsxnew file mode 100644index 00000000000..2e8010c641b--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/internal/AutocompleteRoot.tsx@@ -0,0 +1,27 @@+import { Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';++import { preventDismissingClickActivation } from '@ui/utilities/internal/preventDismissingClickActivation';++import { type AutocompleteRootProps } from '../types/AutocompleteRootProps';++export const AutocompleteRoot = <TItem,>({+ onOpenChange,+ ...props+}: AutocompleteRootProps<TItem>) => (+ <AutocompletePrimitive.Root+ {...props}+ onOpenChange={(open, eventDetails) => {+ onOpenChange?.(open, eventDetails);++ if (+ open ||+ eventDetails.isCanceled ||+ eventDetails.reason !== 'outside-press'+ ) {+ return;+ }++ preventDismissingClickActivation(eventDetails.event);+ }}+ />+);diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteEmptyProps.ts b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteEmptyProps.tsnew file mode 100644index 00000000000..71b08ab68cf--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteEmptyProps.ts@@ -0,0 +1,3 @@+import { type Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';++export type AutocompleteEmptyProps = AutocompletePrimitive.Empty.Props;diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteInputGroupProps.ts b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteInputGroupProps.tsnew file mode 100644index 00000000000..d744e8eaa85--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteInputGroupProps.ts@@ -0,0 +1,4 @@+import { type Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';++export type AutocompleteInputGroupProps =+ AutocompletePrimitive.InputGroup.Props;diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteInputProps.ts b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteInputProps.tsnew file mode 100644index 00000000000..42653ffa82d--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteInputProps.ts@@ -0,0 +1,10 @@+import { type Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';++import { type InputSize } from '@ui/primitives/input/types/InputSize';++export type AutocompleteInputProps = Omit<+ AutocompletePrimitive.Input.Props,+ 'size'+> & {+ size?: InputSize;+};diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteItemProps.ts b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteItemProps.tsnew file mode 100644index 00000000000..66f309efe4b--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteItemProps.ts@@ -0,0 +1,9 @@+import { type Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';++import { type ListItemProps } from '@ui/primitives/navigation/ListItem/types/ListItemProps';++export type AutocompleteItemProps = AutocompletePrimitive.Item.Props &+ Pick<+ ListItemProps,+ 'startIcon' | 'endIcon' | 'description' | 'descriptionPlacement'+ >;diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteListProps.ts b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteListProps.tsnew file mode 100644index 00000000000..fd07e477290--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteListProps.ts@@ -0,0 +1,3 @@+import { type Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';++export type AutocompleteListProps = AutocompletePrimitive.List.Props;diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompletePopupProps.ts b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompletePopupProps.tsnew file mode 100644index 00000000000..9310f9b0e67--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompletePopupProps.ts@@ -0,0 +1,15 @@+import { type Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';++export type AutocompletePopupProps = AutocompletePrimitive.Popup.Props &+ Pick<+ AutocompletePrimitive.Positioner.Props,+ | 'side'+ | 'align'+ | 'sideOffset'+ | 'alignOffset'+ | 'anchor'+ | 'collisionPadding'+ > & {+ width?: number | string;+ container?: AutocompletePrimitive.Portal.Props['container'];+ };diff --git a/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteRootProps.ts b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteRootProps.tsnew file mode 100644index 00000000000..5a25b2df083--- /dev/null+++ b/packages/twenty-ui/src/primitives/input/Autocomplete/types/AutocompleteRootProps.ts@@ -0,0 +1,8 @@+import { type Autocomplete as AutocompletePrimitive } from '@base-ui/react/autocomplete';++export type AutocompleteRootProps<TItem> = Omit<+ AutocompletePrimitive.Root.Props<TItem>,+ 'items'+> & {+ items?: readonly TItem[];+};diff --git a/packages/twenty-ui/src/primitives/input/index.ts b/packages/twenty-ui/src/primitives/input/index.tsindex f18d70d4492..fb13c6755f9 100644--- a/packages/twenty-ui/src/primitives/input/index.ts+++ b/packages/twenty-ui/src/primitives/input/index.ts@@ -7,6 +7,14 @@* |___/*/+export { Autocomplete } from './Autocomplete/Autocomplete';+export type { AutocompleteEmptyProps } from './Autocomplete/types/AutocompleteEmptyProps';+export type { AutocompleteInputGroupProps } from './Autocomplete/types/AutocompleteInputGroupProps';+export type { AutocompleteInputProps } from './Autocomplete/types/AutocompleteInputProps';+export type { AutocompleteItemProps } from './Autocomplete/types/AutocompleteItemProps';+export type { AutocompleteListProps } from './Autocomplete/types/AutocompleteListProps';+export type { AutocompletePopupProps } from './Autocomplete/types/AutocompletePopupProps';+export type { AutocompleteRootProps } from './Autocomplete/types/AutocompleteRootProps';export { Button } from './Button/Button';export type { ButtonColor } from './Button/types/ButtonColor';export type { ButtonProps } from './Button/types/ButtonProps';diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/preventDismissingClickActivation.ts b/packages/twenty-ui/src/utilities/internal/preventDismissingClickActivation.tssimilarity index 98%rename from packages/twenty-ui/src/components/navigation/Dropdown/internal/preventDismissingClickActivation.tsrename to packages/twenty-ui/src/utilities/internal/preventDismissingClickActivation.tsindex a78a345b607..4e4639d9555 100644--- a/packages/twenty-ui/src/components/navigation/Dropdown/internal/preventDismissingClickActivation.ts+++ b/packages/twenty-ui/src/utilities/internal/preventDismissingClickActivation.ts@@ -1,4 +1,5 @@const DISMISSING_EVENT_TYPES_FOLLOWED_BY_CLICK = [+ 'pointerdown','mousedown','touchend','focusout',