Skip to content

The open alternative to Salesforce, designed for AI.

Migrate country selection in Twenty UI (#27128)

Raphaël Bosi1fdf149afb27
diff --git a/packages/twenty-docs/docs.json b/packages/twenty-docs/docs.json
index e6d18690ff3..a521749b9bb 100644
--- a/packages/twenty-docs/docs.json
+++ b/packages/twenty-docs/docs.json
@@ -638,6 +638,7 @@
"ui/components/avatar-group",
"ui/components/callout",
"ui/components/command-block",
+ "ui/components/country-select",
"ui/components/currency-picker",
"ui/components/image-input",
"ui/components/inline-banner",
diff --git a/packages/twenty-docs/navigation/base-structure.json b/packages/twenty-docs/navigation/base-structure.json
index be917f6106f..49f7f9da136 100644
--- a/packages/twenty-docs/navigation/base-structure.json
+++ b/packages/twenty-docs/navigation/base-structure.json
@@ -656,6 +656,7 @@
"ui/components/avatar-group",
"ui/components/callout",
"ui/components/command-block",
+ "ui/components/country-select",
"ui/components/currency-picker",
"ui/components/image-input",
"ui/components/inline-banner",
diff --git a/packages/twenty-docs/snippets/ui/generated/components/country-select.mdx b/packages/twenty-docs/snippets/ui/generated/components/country-select.mdx
new file mode 100644
index 00000000000..9e10af90822
--- /dev/null
+++ b/packages/twenty-docs/snippets/ui/generated/components/country-select.mdx
@@ -0,0 +1,83 @@
+{/*
+ * _____ _
+ *|_ _|_ _____ _ __ | |_ _ _
+ * | | \ \ /\ / / _ \ '_ \| __| | | | 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
+ */}
+
+<ParamField body="className" type="string | ((state: PopoverTriggerState) =&gt; string | undefined)">
+ Class applied to the trigger.
+</ParamField>
+
+<ParamField body="countries" type="readonly CountryChoice[]" required>
+ Prepared country choices with unique non-empty values, display labels, and optional decorative flags.
+</ParamField>
+
+<ParamField body="disabled" type="boolean" default="false">
+ Prevents opening and selection while the trigger stays focusable. An empty country list is also disabled.
+</ParamField>
+
+<ParamField body="id" type="string">
+ ID of the trigger. Generated when omitted.
+</ParamField>
+
+<ParamField body="label" type="string">
+ Optional visible label that names the trigger and the popup.
+</ParamField>
+
+<ParamField body="nativeButton" type="boolean" default="true">
+ Whether the component renders a native `<button>` element when replacing it
+ via the `render` prop.
+ Set to `false` if the rendered element is not a button (e.g. `<div>`).
+</ParamField>
+
+<ParamField body="noCountryLabel" type="string" default="No country">
+ Text of the no-country choice, also displayed when no country is selected.
+</ParamField>
+
+<ParamField body="noResultsLabel" type="string" default="No results">
+ Text displayed when no choice matches the search.
+</ParamField>
+
+<ParamField body="onOpenChange" type="((open: boolean) =&gt; void)">
+ Reports popup opening and closing.
+</ParamField>
+
+<ParamField body="onValueChange" type="(value: string) =&gt; void" required>
+ Reports the selected choice value, or an empty string when no country is selected.
+</ParamField>
+
+<ParamField body="open" type="boolean">
+ Controls whether the country popup is open.
+</ParamField>
+
+<ParamField body="popupProps" type="Omit&lt;DropdownContentProps, &quot;children&quot; | &quot;aria-label&quot; | &quot;aria-labelledby&quot; | &quot;keepMounted&quot;&gt;">
+ Dropdown popup positioning, portal, focus, and event options for host integration.
+</ParamField>
+
+<ParamField body="ref" type="Ref&lt;HTMLButtonElement&gt;">
+ Ref to the trigger element.
+</ParamField>
+
+<ParamField body="render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, PopoverTriggerState&gt;">
+ Replaces the trigger element while preserving its behavior and props.
+</ParamField>
+
+<ParamField body="searchLabel" type="string" default="Search">
+ Placeholder and accessible name of the search input.
+</ParamField>
+
+<ParamField body="style" type="CSSProperties | ((state: PopoverTriggerState) =&gt; CSSProperties | undefined)">
+ Style applied to the element, or a function that
+ returns a style object based on the component's state.
+</ParamField>
+
+<ParamField body="value" type="string" required>
+ Selected choice value. An empty string selects no country.
+</ParamField>
diff --git a/packages/twenty-docs/ui/components/country-select.mdx b/packages/twenty-docs/ui/components/country-select.mdx
new file mode 100644
index 00000000000..4d184135c37
--- /dev/null
+++ b/packages/twenty-docs/ui/components/country-select.mdx
@@ -0,0 +1,78 @@
+---
+title: CountrySelect
+description: Search prepared country choices and select a country or an explicit empty value.
+---
+
+import { StoryEmbed } from '/snippets/ui/StoryEmbed.mdx';
+import CountrySelectReference from '/snippets/ui/generated/components/country-select.mdx';
+
+`CountrySelect` combines a labeled trigger, decorative flags, country search, selected options, and an explicit no-country choice. It uses the shared Dropdown picker behavior. Your application supplies country data and translated text and decides how selected values are stored.
+
+<StoryEmbed
+ storyId="ui-input-countryselect--default"
+ title="Country selection"
+ height={340}
+/>
+
+## Prepared choices
+
+Each choice has a unique, non-empty `value`, a display `label`, and an optional `flag`. Values are opaque strings. They can be country names, identifiers, or codes according to your application's existing storage format. Selecting a choice reports its value unchanged.
+
+```tsx
+import { useState } from 'react';
+import { CountrySelect } from 'twenty-ui/components';
+
+export const ShippingCountry = () => {
+ const [country, setCountry] = useState('France');
+
+ return (
+ <CountrySelect
+ label="Shipping country"
+ countries={[
+ { value: 'France', label: 'France', flag: '🇫🇷' },
+ { value: 'Germany', label: 'Germany', flag: '🇩🇪' },
+ { value: 'Japan', label: 'Japan', flag: '🇯🇵' },
+ ]}
+ value={country}
+ onValueChange={setCountry}
+ searchLabel="Search countries"
+ noCountryLabel="No country"
+ noResultsLabel="No countries found"
+ />
+ );
+};
+```
+
+`flag` accepts a React node and is decorative. The country label supplies the accessible option name. Country lists, flag assets, locale selection, and translations remain in the host application.
+
+## Empty and unknown values
+
+The empty string (`''`) represents no country. The no-country option appears beside the supplied choices and reports that empty string when selected. Reserve it for the empty selection instead of using it as a country value.
+
+An unknown value displays `noCountryLabel` and the no-country icon. It does not call `onValueChange` or overwrite the host value. This lets the application decide how to handle a stored value that is absent from the current choices.
+
+## Search and interaction
+
+Search matches the prepared display labels. It ignores letter case, optional accents in Latin, Greek, Arabic, and Hebrew text, and Cyrillic stress marks, treats the Cyrillic `ё` as `е`, and folds letters such as `ø`, `æ`, and `ß` into `o`, `ae`, and `ss`. It also ignores standalone accent characters such as `^`, `` ` ``, `´`, `¨`, and `ˇ`, so a pending dead key does not hide matches. Marks that form distinct letters remain significant, such as Japanese voicing marks, Indic vowel signs, and the Cyrillic `й`. A partly typed Korean syllable, such as ㅎ or 하, matches syllables that start with it, such as 한. `noCountryLabel` participates in the same search. While a search is active, matching countries are listed before the no-country choice, so Enter picks the first matching country. When only the no-country choice matches, Enter selects it. A query with no matching options displays `noResultsLabel`. Closing and reopening the picker clears its search.
+
+The picker handles pointer selection, keyboard movement, selected-option presentation, focus, and closing. Selecting an option closes the popup. Escape closes it and restores trigger focus. Each instance has independent popup and search state.
+
+Provide a visible `label`, or use `aria-label` or `aria-labelledby` on the trigger. `aria-labelledby` takes precedence over a non-empty `aria-label`, which takes precedence over the visible label, and the popup takes the same name as the trigger. The visible label also names a trigger that `render` replaces with a non-button element. When the trigger is named this way, the selected country is its accessible description. Without any of them, the selected country names the trigger and the popup. A tooltip reveals the full selected label when it is truncated.
+
+`searchLabel` supplies the search input's placeholder and accessible name, `noCountryLabel` the no-country text, and `noResultsLabel` the empty-result text. They default to `Search`, `No country`, and `No results`. Pass translated strings when your application is localized. Native trigger attributes, event handlers, `className`, `style`, and `ref` apply to its button.
+
+`disabled` prevents opening and selection. A picker with no supplied countries is disabled as well. If either condition occurs while the popup is open, the popup closes, reports `onOpenChange(false)`, and returns focus to the trigger. Enabling the picker again does not reopen it automatically. While disabled, the trigger stays focusable, is marked with `aria-disabled`, and never opens. Like a native disabled button, it skips consumer `onClick`, `onMouseDown`, `onPointerDown`, `onKeyDown`, and `onKeyUp` handlers. Function forms of `className`, `style`, and `render` receive `disabled: true` in the trigger state.
+
+## Host integration
+
+Use `open` and `onOpenChange` when the application needs to register or control the popup. Without `open`, the picker manages its own open state. `popupProps` accepts Dropdown popup options for positioning, portal placement, and focus handling. The popup takes its name from the trigger, so `popupProps` does not accept `aria-label` or `aria-labelledby`.
+
+Keep application dropdown IDs, focus stacks, field metadata, persistence, and editing lifecycle in the host adapter. Changing the display label or flag does not require changing the stored value.
+
+## Front component renderer
+
+The React and Preact front component sandboxes render the selected country, decorative flag, and disabled trigger. Opening the popup is currently unsupported. Base UI reads pointer contact data from the `nativeEvent` of the forwarded event, which the sandbox does not provide. When the popup content still mounts, the Dropdown reads the popup element's `dataset`, which worker elements do not provide. Search, selection, popup focus, and closing are therefore unavailable in those sandboxes for now. Renderer fixtures check the initial presentation and the disabled trigger, then assert the known opening errors. The UI Storybook exercises these interactions in a regular browser.
+
+## Props
+
+<CountrySelectReference />
diff --git a/packages/twenty-docs/ui/components/overview.mdx b/packages/twenty-docs/ui/components/overview.mdx
index d7e28e41a76..c534a11a47a 100644
--- a/packages/twenty-docs/ui/components/overview.mdx
+++ b/packages/twenty-docs/ui/components/overview.mdx
@@ -35,6 +35,7 @@ Import shared components from `twenty-ui/components`. The code editor has its ow
| [SearchInput](/ui/components/search-input) | Search text and optional filter controls. |
| [AnimatedIconCrossfade](/ui/components/animated-icon-crossfade) | State-driven icon transitions. |
| [Menu rows](/ui/components/menu-items) | MenuItem, MenuItemAvatar, MenuItemDraggable, and MenuItemSuggestion. |
+| [CountrySelect](/ui/components/country-select) | Searchable country choices, flags, and an explicit empty selection. |
| [MenuPicker](/ui/components/menu-picker) | Compact icon toggles with tooltips. |
Routing, record formatting, product placeholders, and application state belong to the host application. Shared components expose data, callback, and render props for those integrations.
diff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiCountrySelect.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiCountrySelect.stories.tsx
new file mode 100644
index 00000000000..54b12cceb2b
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiCountrySelect.stories.tsx
@@ -0,0 +1,31 @@
+import { type Meta } from '@storybook/react-vite';
+
+import {
+ FRONT_COMPONENT_STORY_DEFAULT_ARGS,
+ resetFrontComponentStoryMocks,
+} from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
+import { type TwentyUiGalleryStory as Story } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryStory';
+import { countrySelectSandboxTest } from '@/__stories__/twenty-ui-gallery/utils/countrySelectSandboxTest';
+import { createGalleryStory } from '@/__stories__/twenty-ui-gallery/utils/createGalleryStory';
+import { FrontComponentRenderer } from '@/host/components/FrontComponentRenderer';
+
+const meta: Meta<typeof FrontComponentRenderer> = {
+ title: 'FrontComponent/Twenty UI Country Select',
+ component: FrontComponentRenderer,
+ args: FRONT_COMPONENT_STORY_DEFAULT_ARGS,
+ beforeEach: resetFrontComponentStoryMocks,
+};
+
+export default meta;
+
+export const CountrySelectReactUnsupportedPopup: Story = createGalleryStory({
+ frontComponentBundleName: 'twenty-ui-country-select',
+ runtime: 'react',
+ play: countrySelectSandboxTest,
+});
+
+export const CountrySelectPreactUnsupportedPopup: Story = createGalleryStory({
+ frontComponentBundleName: 'twenty-ui-country-select',
+ runtime: 'preact',
+ play: countrySelectSandboxTest,
+});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
index a44f833f1a5..091277a6499 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
@@ -32,6 +32,7 @@ requiring them to occur.
| `twenty-ui-tooltip` | Tooltip (convenience and compound APIs) |
| `twenty-ui-responsive-hooks` | useIsMobile, useIsTouchDevice, Button hotkeys |
| `twenty-ui-reading-directions` | Callout, ButtonGroup, Button, AvatarGroup, ListItem, JsonTree in LTR and RTL side by side (`TwentyUiReadingDirections.stories.tsx`) |
+| `twenty-ui-country-select` | CountrySelect (`TwentyUiCountrySelect.stories.tsx`) |
The focused fixtures import public twenty-ui entry points and use
`TwentyUiGalleryCard` for the light theme, mount marker, and `twenty-ui/style.css`.
@@ -63,6 +64,7 @@ No stories are skipped or marked as expected-to-fail by the runner.
| PhoneCountryPicker | Both runtimes render the triggers, flags, and disabled state. Opening fails while reading pointer contact data from the missing `nativeEvent`. In React the popup still mounts, and the Dropdown search effect then reads `dataset`, which sandbox elements lack; the uncaught error unmounts the React tree, so the React story requires that error and keeps the pointer error optional. See the [PhoneCountryPicker documentation](../../../../twenty-docs/ui/components/phone-country-picker.mdx). |
| Menu | Opening fails on the missing `nativeEvent.pointerType` and pointer contact data. |
| Select | Opening fails on missing native event data and focus support. Preact can report only the last of these failures when the host coalesces sandbox errors. |
+| CountrySelect | Opening fails while reading pointer contact data from the missing `nativeEvent`. React still mounts the popup, and the Dropdown search target then reads `dataset`, which worker elements do not provide, so that error is allowed without being required; Preact stops at the opening error. The fixture checks the selected values and decorative flags, then clicks the disabled trigger and, after a settle delay, requires the opening error alone, so a popup mounted by React fails the story. Clicking an enabled trigger then asserts the opening error. |
| Switch, Checkbox, Radio (standard and card), SegmentedControl | Activation attempts to construct an unavailable `PointerEvent`. `RadioCardReact` never gets that far: React drops the click handler Base UI adds through `React.cloneElement`, so only the group's focus handling fails on the missing `nativeEvent` for `composedPath`. |
| Slider | Thumbs stay hidden because the sandbox has no `ResizeObserver` to re-measure after the first geometry batch. |
| Tooltip | `TooltipReact` opens on hover but remains open after Escape because React drops the handlers Base UI adds through `React.cloneElement`. |
@@ -98,3 +100,11 @@ Then, from `packages/twenty-front-component-renderer`, run:
```sh
npx vitest run --config vitest.storybook.config.ts TwentyUiGallery.stories.tsx
```
+
+The CountrySelect and reading-directions fixtures live in their own story
+files, so run them separately:
+
+```sh
+npx vitest run --config vitest.storybook.config.ts TwentyUiCountrySelect.stories.tsx
+npx vitest run --config vitest.storybook.config.ts TwentyUiReadingDirections.stories.tsx
+```
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-country-select.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-country-select.front-component.tsx
new file mode 100644
index 00000000000..9aca05d6910
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-country-select.front-component.tsx
@@ -0,0 +1,51 @@
+import { useState } from 'react';
+import { defineFrontComponent } from 'twenty-sdk/define';
+import { CountrySelect } from 'twenty-ui/components';
+
+import { TwentyUiGalleryCard } from '@/__stories__/shared/front-components/twenty-ui-gallery-card';
+
+const COUNTRIES = [
+ { value: 'France', label: 'France', flag: '🇫🇷' },
+ { value: 'Brazil', label: 'Brésil', flag: '🇧🇷' },
+ { value: 'Japan', label: 'Japon', flag: '🇯🇵' },
+];
+
+const CountrySelectExample = () => {
+ const [country, setCountry] = useState('France');
+ const [shippingCountry, setShippingCountry] = useState('Japan');
+
+ return (
+ <TwentyUiGalleryCard title="Country selection">
+ <CountrySelect
+ countries={COUNTRIES}
+ label="Billing country"
+ value={country}
+ onValueChange={setCountry}
+ />
+ <CountrySelect
+ countries={COUNTRIES}
+ label="Shipping country"
+ value={shippingCountry}
+ onValueChange={setShippingCountry}
+ />
+ <CountrySelect
+ countries={COUNTRIES}
+ label="Disabled country"
+ value="France"
+ onValueChange={setCountry}
+ disabled
+ />
+ <p role="status" aria-label="Saved countries">
+ Billing: {country || 'empty'}; Shipping: {shippingCountry || 'empty'}
+ </p>
+ </TwentyUiGalleryCard>
+ );
+};
+
+export default defineFrontComponent({
+ universalIdentifier: 'fa3c0858-7f45-48aa-8406-8dd4e2aa24c9',
+ name: 'twenty-ui-country-select',
+ description:
+ 'Country labels and flags rendered in the sandbox, with popup interaction unsupported',
+ component: CountrySelectExample,
+});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/countrySelectSandboxTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/countrySelectSandboxTest.ts
new file mode 100644
index 00000000000..97dec4d30da
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/countrySelectSandboxTest.ts
@@ -0,0 +1,53 @@
+import { expect, userEvent, within } from 'storybook/test';
+
+import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
+import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';
+import { SANDBOX_ROUND_TRIP_SETTLE_DELAY } from '@/__stories__/shared/test-utils/timeouts';
+import { SANDBOX_ERROR_PATTERNS } from '@/__stories__/twenty-ui-gallery/constants/SANDBOX_ERROR_PATTERNS';
+import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
+import { expectSandboxErrors } from '@/__stories__/twenty-ui-gallery/utils/expectSandboxErrors';
+
+export const countrySelectSandboxTest: TwentyUiGalleryPlayFunction = async ({
+ canvasElement,
+}) => {
+ const canvas = within(canvasElement);
+
+ await expectFrontComponentMounted(canvas);
+ const billing = canvas.getByRole('button', { name: 'Billing country' });
+ const shipping = canvas.getByRole('button', { name: 'Shipping country' });
+ const disabled = canvas.getByRole('button', { name: 'Disabled country' });
+
+ expect(billing).toHaveTextContent('France');
+ expect(shipping).toHaveTextContent('Japon');
+ expect(within(billing).getByText('🇫🇷')).toHaveAttribute(
+ 'aria-hidden',
+ 'true',
+ );
+ expect(within(shipping).getByText('🇯🇵')).toHaveAttribute(
+ 'aria-hidden',
+ 'true',
+ );
+ expect(disabled).toHaveAttribute('aria-disabled', 'true');
+ expect(disabled).not.toBeDisabled();
+ expect(disabled).toHaveTextContent('France');
+ expect(errorHandler).not.toHaveBeenCalled();
+
+ await userEvent.click(disabled);
+ await new Promise((resolve) =>
+ setTimeout(resolve, SANDBOX_ROUND_TRIP_SETTLE_DELAY),
+ );
+ await expectSandboxErrors({
+ requiredErrors: [SANDBOX_ERROR_PATTERNS.VIEWPORT_WIDTH],
+ });
+ expect(disabled).toHaveAttribute('aria-expanded', 'false');
+ expect(
+ canvas.getByRole('status', { name: 'Saved countries' }),
+ ).toHaveTextContent('Billing: France; Shipping: Japan');
+ errorHandler.mockClear();
+
+ await userEvent.click(billing);
+ await expectSandboxErrors({
+ requiredErrors: [SANDBOX_ERROR_PATTERNS.VIEWPORT_WIDTH],
+ allowedAdditionalErrors: [SANDBOX_ERROR_PATTERNS.ELEMENT_DATASET],
+ });
+};
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.tsx
index cdbe1dc7a8a..a5435705605 100644
--- 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.tsx
@@ -1,4 +1,4 @@
-import { render, screen } from '@testing-library/react';
+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';
@@ -9,8 +9,13 @@ 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',
@@ -31,7 +36,21 @@ const EMPTY_ADDRESS = {
const renderAddressInput = (surface?: WorkspaceSurfaceContextValue) => {
const onChange = jest.fn();
const onClickOutside = jest.fn();
- const BaseWrapper = getJestMetadataAndApolloMocksWrapper({});
+ 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}>
@@ -49,11 +68,11 @@ const renderAddressInput = (surface?: WorkspaceSurfaceContextValue) => {
render(
<AddressInput
- instanceId="address-input"
+ instanceId={ADDRESS_INPUT_INSTANCE_ID}
value={EMPTY_ADDRESS}
onTab={jest.fn()}
onShiftTab={jest.fn()}
- onEnter={jest.fn()}
+ onEnter={onEnter}
onEscape={jest.fn()}
onClickOutside={onClickOutside}
onChange={onChange}
@@ -61,7 +80,7 @@ const renderAddressInput = (surface?: WorkspaceSurfaceContextValue) => {
{ wrapper: Wrapper },
);
- return { onChange, onClickOutside };
+ return { onChange, onClickOutside, onEnter };
};
describe('AddressInput country picker on a side panel surface', () => {
@@ -81,4 +100,28 @@ describe('AddressInput country picker on a side panel surface', () => {
);
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/input/components/internal/country/components/CountrySelect.tsx b/packages/twenty-front/src/modules/ui/input/components/internal/country/components/CountrySelect.tsx
index 756d41578cb..88d4b055072 100644
--- a/packages/twenty-front/src/modules/ui/input/components/internal/country/components/CountrySelect.tsx
+++ b/packages/twenty-front/src/modules/ui/input/components/internal/country/components/CountrySelect.tsx
@@ -1,49 +1,83 @@
import { t } from '@lingui/core/macro';
-import { useMemo } from 'react';
+import { createElement, useContext, useMemo } from 'react';
+import { Key } from 'ts-key-enum';
import { SELECT_COUNTRY_DROPDOWN_ID } from '@/ui/input/components/internal/country/constants/SelectCountryDropdownId';
import { useCountries } from '@/ui/input/components/internal/hooks/useCountries';
-import { Select } from '@/ui/input/components/Select';
-import { IconCircleOff, type IconComponentProps } from 'twenty-ui/icon';
-import { type SelectOption } from 'twenty-ui/primitives/input';
+import { DropdownCleanupEffect } from '@/ui/layout/dropdown/components/DropdownCleanupEffect';
+import { DropdownClickOutsideListenerExclusion } from '@/ui/layout/dropdown/components/DropdownClickOutsideListenerExclusion';
+import { useHandleDropdownOpenChange } from '@/ui/layout/dropdown/hooks/useHandleDropdownOpenChange';
+import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';
+import { ParentClickOutsideIdContext } from '@/ui/utilities/pointer-event/contexts/ParentClickOutsideIdContext';
+import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';
+import {
+ type CountryChoice,
+ CountrySelect as SharedCountrySelect,
+} from 'twenty-ui/components';
+
+type CountrySelectProps = {
+ label: string;
+ selectedCountryName: string;
+ onChange: (countryName: string) => void;
+};
export const CountrySelect = ({
label,
selectedCountryName,
onChange,
-}: {
- label: string;
- selectedCountryName: string;
- onChange: (countryCode: string) => void;
-}) => {
+}: CountrySelectProps) => {
const countries = useCountries();
+ const parentClickOutsideId = useContext(ParentClickOutsideIdContext);
+ const isDropdownOpen = useAtomComponentStateValue(
+ isDropdownOpenComponentState,
+ SELECT_COUNTRY_DROPDOWN_ID,
+ );
+ const { handleDropdownOpenChange } = useHandleDropdownOpenChange({
+ dropdownId: SELECT_COUNTRY_DROPDOWN_ID,
+ });
- const options: SelectOption<string>[] = useMemo(() => {
- const countryList = countries.map<SelectOption<string>>(
- ({ countryName, Flag }) => ({
- label: countryName,
+ const countryChoices = useMemo<CountryChoice[]>(
+ () =>
+ countries.map(({ countryName, Flag }) => ({
value: countryName,
- Icon: (props: IconComponentProps) =>
- Flag({ width: props.size, height: props.size }), // TODO : improve this ?
- }),
- );
- countryList.unshift({
- label: t`No country`,
- value: '',
- Icon: IconCircleOff,
- });
- return countryList;
- }, [countries]);
+ label: countryName,
+ flag: <Flag width="100%" height="100%" />,
+ })),
+ [countries],
+ );
return (
- <Select
- fullWidth
- dropdownId={SELECT_COUNTRY_DROPDOWN_ID}
- options={options}
- label={label}
- withSearchInput
- onChange={onChange}
- value={selectedCountryName}
- />
+ <>
+ <DropdownCleanupEffect dropdownId={SELECT_COUNTRY_DROPDOWN_ID} />
+ <SharedCountrySelect
+ countries={countryChoices}
+ value={selectedCountryName}
+ onValueChange={onChange}
+ label={label}
+ searchLabel={t`Search`}
+ noCountryLabel={t`No country`}
+ noResultsLabel={t`No results`}
+ open={isDropdownOpen}
+ onOpenChange={handleDropdownOpenChange}
+ onKeyDown={(event) => {
+ if (event.key === Key.Enter) {
+ event.stopPropagation();
+ }
+ }}
+ popupProps={{
+ render: (popupProps) =>
+ createElement(
+ 'div',
+ {
+ ...popupProps,
+ 'data-click-outside-id': parentClickOutsideId,
+ },
+ <DropdownClickOutsideListenerExclusion>
+ {popupProps.children}
+ </DropdownClickOutsideListenerExclusion>,
+ ),
+ }}
+ />
+ </>
);
};
diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__tests__/CountrySelect.test.tsx b/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__tests__/CountrySelect.test.tsx
new file mode 100644
index 00000000000..b3ece8df592
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__tests__/CountrySelect.test.tsx
@@ -0,0 +1,75 @@
+import { render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { createStore, Provider as JotaiProvider } from 'jotai';
+
+import { CountrySelect } from '@/ui/input/components/internal/country/components/CountrySelect';
+import { SELECT_COUNTRY_DROPDOWN_ID } from '@/ui/input/components/internal/country/constants/SelectCountryDropdownId';
+import { activeDropdownFocusIdState } from '@/ui/layout/dropdown/states/activeDropdownFocusIdState';
+import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';
+import { focusStackState } from '@/ui/utilities/focus/states/focusStackState';
+
+const renderCountrySelect = () => {
+ const store = createStore();
+ const onChange = jest.fn();
+ const { unmount } = render(
+ <JotaiProvider store={store}>
+ <CountrySelect
+ label="Country"
+ selectedCountryName="France"
+ onChange={onChange}
+ />
+ </JotaiProvider>,
+ );
+
+ return { store, onChange, unmount };
+};
+
+describe('CountrySelect frontend adapter', () => {
+ it('keeps a stored country name selected and clears it to an empty string', async () => {
+ const user = userEvent.setup();
+ const { store, onChange } = renderCountrySelect();
+
+ await user.click(screen.getByText('France'));
+
+ const popup = await screen.findByRole('dialog', { name: 'Country' });
+
+ expect(
+ within(popup).getByRole('button', { name: 'France' }),
+ ).toHaveAttribute('aria-pressed', 'true');
+ expect(store.get(activeDropdownFocusIdState.atom)).toBe(
+ SELECT_COUNTRY_DROPDOWN_ID,
+ );
+
+ await user.click(within(popup).getByRole('button', { name: 'No country' }));
+
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith('');
+ expect(store.get(activeDropdownFocusIdState.atom)).toBeNull();
+ expect(store.get(focusStackState.atom)).toEqual([]);
+
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ });
+
+ it('removes its dropdown registration when the address editor unmounts', async () => {
+ const user = userEvent.setup();
+ const { store, unmount } = renderCountrySelect();
+ const dropdownOpenState = isDropdownOpenComponentState.atomFamily({
+ instanceId: SELECT_COUNTRY_DROPDOWN_ID,
+ });
+
+ await user.click(screen.getByText('France'));
+
+ expect(store.get(dropdownOpenState)).toBe(true);
+ expect(store.get(focusStackState.atom)).toEqual([
+ expect.objectContaining({ focusId: SELECT_COUNTRY_DROPDOWN_ID }),
+ ]);
+
+ unmount();
+
+ expect(store.get(dropdownOpenState)).toBe(false);
+ expect(store.get(activeDropdownFocusIdState.atom)).toBeNull();
+ expect(store.get(focusStackState.atom)).toEqual([]);
+ });
+});
diff --git a/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownClickOutsideListenerExclusion.tsx b/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownClickOutsideListenerExclusion.tsx
new file mode 100644
index 00000000000..01c8126f3f1
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownClickOutsideListenerExclusion.tsx
@@ -0,0 +1,31 @@
+import { styled } from '@linaria/react';
+import { type ReactNode, useContext } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+
+import { ClickOutsideListenerContext } from '@/ui/utilities/pointer-event/contexts/ClickOutsideListenerContext';
+
+const StyledClickOutsideListenerExclusion = styled.div`
+ display: contents;
+`;
+
+type DropdownClickOutsideListenerExclusionProps = {
+ children: ReactNode;
+};
+
+export const DropdownClickOutsideListenerExclusion = ({
+ children,
+}: DropdownClickOutsideListenerExclusionProps) => {
+ const { excludedClickOutsideId } = useContext(ClickOutsideListenerContext);
+
+ if (!isDefined(excludedClickOutsideId)) {
+ return children;
+ }
+
+ return (
+ <StyledClickOutsideListenerExclusion
+ data-click-outside-id={excludedClickOutsideId}
+ >
+ {children}
+ </StyledClickOutsideListenerExclusion>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownContent.tsx b/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownContent.tsx
index 34821d921cc..0538fe6ba91 100644
--- a/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownContent.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownContent.tsx
@@ -1,15 +1,9 @@
-import { styled } from '@linaria/react';
import { type ComponentProps, useContext } from 'react';
-import { isDefined } from 'twenty-shared/utils';
import { Dropdown } from 'twenty-ui/components';
-import { ClickOutsideListenerContext } from '@/ui/utilities/pointer-event/contexts/ClickOutsideListenerContext';
+import { DropdownClickOutsideListenerExclusion } from '@/ui/layout/dropdown/components/DropdownClickOutsideListenerExclusion';
import { ParentClickOutsideIdContext } from '@/ui/utilities/pointer-event/contexts/ParentClickOutsideIdContext';
-const StyledClickOutsideListenerExclusion = styled.div`
- display: contents;
-`;
-
type DropdownContentProps = Pick<
ComponentProps<typeof Dropdown.Content>,
| 'children'
@@ -43,7 +37,6 @@ export const DropdownContent = ({
ref,
}: DropdownContentProps) => {
const parentClickOutsideId = useContext(ParentClickOutsideIdContext);
- const { excludedClickOutsideId } = useContext(ClickOutsideListenerContext);
return (
<Dropdown.Content
@@ -61,15 +54,9 @@ export const DropdownContent = ({
className={className}
aria-label={ariaLabel}
>
- {isDefined(excludedClickOutsideId) ? (
- <StyledClickOutsideListenerExclusion
- data-click-outside-id={excludedClickOutsideId}
- >
- {children}
- </StyledClickOutsideListenerExclusion>
- ) : (
- children
- )}
+ <DropdownClickOutsideListenerExclusion>
+ {children}
+ </DropdownClickOutsideListenerExclusion>
</Dropdown.Content>
);
};
diff --git a/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownRoot.tsx b/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownRoot.tsx
index 31972fcf3d8..f30fcbabe25 100644
--- a/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownRoot.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/dropdown/components/DropdownRoot.tsx
@@ -4,8 +4,7 @@ import { Dropdown } from 'twenty-ui/components';
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 { useHandleDropdownOpenChange } from '@/ui/layout/dropdown/hooks/useHandleDropdownOpenChange';
import { type GlobalHotkeysConfig } from '@/ui/utilities/hotkey/types/GlobalHotkeysConfig';
import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';
@@ -55,20 +54,10 @@ export const DropdownRoot = ({
getIsDropdownOpen,
getIsDropdownOpen,
);
- const { openDropdown } = useOpenDropdown();
- const { closeDropdown } = useCloseDropdown();
-
- const handleOpenChange = (open: boolean) => {
- if (!open) {
- closeDropdown(dropdownId);
- return;
- }
-
- openDropdown({
- dropdownComponentInstanceIdFromProps: dropdownId,
- globalHotkeysConfig,
- });
- };
+ const { handleDropdownOpenChange } = useHandleDropdownOpenChange({
+ dropdownId,
+ globalHotkeysConfig,
+ });
return (
<DropdownComponentInstanceContext.Provider
@@ -79,7 +68,7 @@ export const DropdownRoot = ({
multiple={multiple}
defaultPage={defaultPage}
open={isDropdownOpen}
- onOpenChange={handleOpenChange}
+ onOpenChange={handleDropdownOpenChange}
onEscapeKeyDown={onEscapeKeyDown}
onInteractOutside={onInteractOutside}
>
diff --git a/packages/twenty-front/src/modules/ui/layout/dropdown/hooks/useHandleDropdownOpenChange.ts b/packages/twenty-front/src/modules/ui/layout/dropdown/hooks/useHandleDropdownOpenChange.ts
new file mode 100644
index 00000000000..08e608f3a7e
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/layout/dropdown/hooks/useHandleDropdownOpenChange.ts
@@ -0,0 +1,30 @@
+import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
+import { useOpenDropdown } from '@/ui/layout/dropdown/hooks/useOpenDropdown';
+import { type GlobalHotkeysConfig } from '@/ui/utilities/hotkey/types/GlobalHotkeysConfig';
+
+type UseHandleDropdownOpenChangeArgs = {
+ dropdownId: string;
+ globalHotkeysConfig?: Partial<GlobalHotkeysConfig>;
+};
+
+export const useHandleDropdownOpenChange = ({
+ dropdownId,
+ globalHotkeysConfig,
+}: UseHandleDropdownOpenChangeArgs) => {
+ const { openDropdown } = useOpenDropdown();
+ const { closeDropdown } = useCloseDropdown();
+
+ const handleDropdownOpenChange = (open: boolean) => {
+ if (!open) {
+ closeDropdown(dropdownId);
+ return;
+ }
+
+ openDropdown({
+ dropdownComponentInstanceIdFromProps: dropdownId,
+ globalHotkeysConfig,
+ });
+ };
+
+ return { handleDropdownOpenChange };
+};
diff --git a/packages/twenty-front/src/utils/__tests__/normalizeSearchText.test.ts b/packages/twenty-front/src/utils/__tests__/normalizeSearchText.test.ts
deleted file mode 100644
index 69ed9a008f1..00000000000
--- a/packages/twenty-front/src/utils/__tests__/normalizeSearchText.test.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { normalizeSearchText } from '~/utils/normalizeSearchText';
-
-describe('normalizeSearchText', () => {
- it('should handle basic ASCII text', () => {
- expect(normalizeSearchText('Hello World')).toBe('hello world');
- expect(normalizeSearchText('TEST')).toBe('test');
- expect(normalizeSearchText('MixedCase123')).toBe('mixedcase123');
- });
-
- it('should remove accents from various languages', () => {
- expect(normalizeSearchText('café')).toBe('cafe');
- expect(normalizeSearchText('naïve')).toBe('naive');
- expect(normalizeSearchText('résumé')).toBe('resume');
- expect(normalizeSearchText('Zürich')).toBe('zurich');
- expect(normalizeSearchText('Müller')).toBe('muller');
- expect(normalizeSearchText('niño')).toBe('nino');
- expect(normalizeSearchText('España')).toBe('espana');
- expect(normalizeSearchText('São Paulo')).toBe('sao paulo');
- expect(normalizeSearchText('João')).toBe('joao');
- expect(normalizeSearchText('Åse')).toBe('ase');
- expect(normalizeSearchText('Øyvind')).toBe('oyvind');
- });
-
- it('should handle Nordic and Germanic special characters', () => {
- expect(normalizeSearchText('Øyvind')).toBe('oyvind');
- expect(normalizeSearchText('Åse')).toBe('ase');
- expect(normalizeSearchText('Æther')).toBe('aether');
- expect(normalizeSearchText('Straße')).toBe('strasse');
- expect(normalizeSearchText('Łódź')).toBe('lodz');
- expect(normalizeSearchText('Œuvre')).toBe('oeuvre');
- });
-
- it('should handle mixed case with accents', () => {
- expect(normalizeSearchText('CAFÉ')).toBe('cafe');
- expect(normalizeSearchText('NaÏvE')).toBe('naive');
- expect(normalizeSearchText('ZÜRICH')).toBe('zurich');
- });
-
- it('should handle null and undefined gracefully', () => {
- expect(normalizeSearchText(null)).toBe('');
- expect(normalizeSearchText(undefined)).toBe('');
- });
-
- it('should handle empty strings', () => {
- expect(normalizeSearchText('')).toBe('');
- expect(normalizeSearchText(' ')).toBe(' ');
- });
-
- it('should handle special characters and numbers', () => {
- expect(normalizeSearchText('[email protected]')).toBe('[email protected]');
- expect(normalizeSearchText('123-456-7890')).toBe('123-456-7890');
- expect(normalizeSearchText('Café #1')).toBe('cafe #1');
- });
-
- it('should handle complex Unicode combinations', () => {
- expect(normalizeSearchText('e\u0301')).toBe('e');
- expect(normalizeSearchText('a\u0300\u0301')).toBe('a');
- expect(normalizeSearchText('é')).toBe('e');
- expect(normalizeSearchText('e\u0301')).toBe('e');
- });
-
- it('should be consistent for search matching', () => {
- const searchTerm = 'cafe';
- const names = ['Café', 'CAFE', 'cafe', 'Cafe'];
-
- names.forEach((name) => {
- expect(normalizeSearchText(name)).toContain(searchTerm);
- });
- });
-});
diff --git a/packages/twenty-front/src/utils/normalizeSearchText.ts b/packages/twenty-front/src/utils/normalizeSearchText.ts
index fa723f41192..895e35c9f93 100644
--- a/packages/twenty-front/src/utils/normalizeSearchText.ts
+++ b/packages/twenty-front/src/utils/normalizeSearchText.ts
@@ -1,17 +1 @@
-export const normalizeSearchText = (
- text: string | null | undefined,
-): string => {
- if (!text) return '';
- return text
- .normalize('NFD')
- .replace(/\p{Diacritic}/gu, '')
- .replace(/[øØ]/g, 'o')
- .replace(/[åÅ]/g, 'a')
- .replace(/[æÆ]/g, 'ae')
- .replace(/[ßẞ]/g, 'ss')
- .replace(/[ðÐ]/g, 'd')
- .replace(/[þÞ]/g, 'th')
- .replace(/[łŁ]/g, 'l')
- .replace(/[œŒ]/g, 'oe')
- .toLowerCase();
-};
+export { normalizeSearchText } from 'twenty-ui/utilities';
diff --git a/packages/twenty-shared/src/constants/DocumentationPaths.ts b/packages/twenty-shared/src/constants/DocumentationPaths.ts
index 820c30b391a..ebbcb727ff3 100644
--- a/packages/twenty-shared/src/constants/DocumentationPaths.ts
+++ b/packages/twenty-shared/src/constants/DocumentationPaths.ts
@@ -134,6 +134,7 @@ export const DOCUMENTATION_PATHS = {
UI_COMPONENTS_CALLOUT: '/ui/components/callout',
UI_COMPONENTS_CODE_EDITOR: '/ui/components/code-editor',
UI_COMPONENTS_COMMAND_BLOCK: '/ui/components/command-block',
+ UI_COMPONENTS_COUNTRY_SELECT: '/ui/components/country-select',
UI_COMPONENTS_CURRENCY_PICKER: '/ui/components/currency-picker',
UI_COMPONENTS_DROPDOWN: '/ui/components/dropdown',
UI_COMPONENTS_IMAGE_INPUT: '/ui/components/image-input',
diff --git a/packages/twenty-ui/docs/components.ts b/packages/twenty-ui/docs/components.ts
index 384193b5347..45469ac880f 100644
--- a/packages/twenty-ui/docs/components.ts
+++ b/packages/twenty-ui/docs/components.ts
@@ -1,3 +1,4 @@
+import { COUNTRY_SELECT_PROP_DESCRIPTIONS } from './countrySelectPropDescriptions';
import { CURRENCY_PICKER_PART_PROP_DESCRIPTIONS } from './currencyPickerPartPropDescriptions';
import { OVERFLOWING_LIST_PROP_DESCRIPTIONS } from './overflowingListPropDescriptions';
import { METRIC_ROW_PROP_DESCRIPTIONS } from './metricRowPropDescriptions';
@@ -67,6 +68,13 @@ import { TOOLTIP_PROP_DESCRIPTIONS } from './tooltipPropDescriptions';
import { VISIBILITY_HIDDEN_PROP_DESCRIPTIONS } from './visibilityHiddenPropDescriptions';
export const DOCUMENTED_COMPONENTS = [
+ {
+ name: 'CountrySelect',
+ source: 'components/input/CountrySelect/CountrySelect.tsx',
+ entryPoint: 'twenty-ui/components',
+ slug: 'components/country-select',
+ propDescriptions: COUNTRY_SELECT_PROP_DESCRIPTIONS,
+ },
{
name: 'CurrencyPicker',
source: 'components/input/CurrencyPicker/CurrencyPicker.tsx',
diff --git a/packages/twenty-ui/docs/countrySelectPropDescriptions.ts b/packages/twenty-ui/docs/countrySelectPropDescriptions.ts
new file mode 100644
index 00000000000..ab967ef020a
--- /dev/null
+++ b/packages/twenty-ui/docs/countrySelectPropDescriptions.ts
@@ -0,0 +1,25 @@
+import { type CountrySelectProps } from '../src/components/input/CountrySelect/types/CountrySelectProps';
+
+export const COUNTRY_SELECT_PROP_DESCRIPTIONS = {
+ countries:
+ 'Prepared country choices with unique non-empty values, display labels, and optional decorative flags.',
+ value: 'Selected choice value. An empty string selects no country.',
+ onValueChange:
+ 'Reports the selected choice value, or an empty string when no country is selected.',
+ label: 'Optional visible label that names the trigger and the popup.',
+ searchLabel: 'Placeholder and accessible name of the search input.',
+ noCountryLabel:
+ 'Text of the no-country choice, also displayed when no country is selected.',
+ noResultsLabel: 'Text displayed when no choice matches the search.',
+ open: 'Controls whether the country popup is open.',
+ onOpenChange: 'Reports popup opening and closing.',
+ popupProps:
+ 'Dropdown popup positioning, portal, focus, and event options for host integration.',
+ id: 'ID of the trigger. Generated when omitted.',
+ className: 'Class applied to the trigger.',
+ disabled:
+ 'Prevents opening and selection while the trigger stays focusable. An empty country list is also disabled.',
+ render:
+ 'Replaces the trigger element while preserving its behavior and props.',
+ ref: 'Ref to the trigger element.',
+} satisfies Partial<Record<keyof CountrySelectProps, string>>;
diff --git a/packages/twenty-ui/docs/label-ownership.md b/packages/twenty-ui/docs/label-ownership.md
index f81abe31fca..738fb50cc19 100644
--- a/packages/twenty-ui/docs/label-ownership.md
+++ b/packages/twenty-ui/docs/label-ownership.md
@@ -12,6 +12,7 @@ This covers production exports under components, primitives, and icons, includin
| Button, MainButton, LightButton | Children and native accessible attributes. Applications compose upcoming-feature labels with Pill. Loading preserves the supplied name and marks the button busy; its spinner is decorative. Button hints use the shared Shortcut presentation and remain decorative. `shortcutJoinLabel` supplies the sequence join label. |
| IconButton and LightIconButton | Caller-supplied accessible label and optional tooltip. Native `aria-labelledby` remains available and takes precedence. |
| SearchInput | Caller-owned placeholder and native accessible name; `filterButtonAriaLabel` defaults to `Filter`. Referenced labels take precedence over explicit labels and placeholder fallback. |
+| CountrySelect | `searchLabel`, `noCountryLabel`, and `noResultsLabel` default to `Search`, `No country`, and `No results`. The search label names the search input and is its placeholder. Applications supply `label` or native accessible names and the country labels, including translated strings. |
| PhoneCountryPicker | Callers supply country labels and the trigger accessible name. The popup takes the trigger name unless a `Dropdown.Title` or an explicit `Dropdown.Content` label names it, and the selected country label describes the trigger. `searchLabel` defaults to `Search`; `emptyLabel` defaults to `No results`. Calling codes are supplied as data without a leading plus sign. |
| ImageInput | `uploadLabel`, `removeLabel`, and `abortLabel` default to `Upload`, `Remove`, and `Abort`. The upload label names the visible upload button and the preview button. Applications supply `helperText` and `errorMessage`, including validation instructions and translated strings. |
| Toast and Toaster | Children, description and action slots, `iconLabel`, `cancelLabel` (default `Cancel`), and `closeLabel` (default `Close`). Toaster accepts native accessible attributes over its `Notifications` region default. |
diff --git a/packages/twenty-ui/docs/module-ownership.json b/packages/twenty-ui/docs/module-ownership.json
index 8c27b096e04..9b4a125c38e 100644
--- a/packages/twenty-ui/docs/module-ownership.json
+++ b/packages/twenty-ui/docs/module-ownership.json
@@ -50,6 +50,7 @@
"CodeEditor",
"CodeEditorHeader",
"CommandBlock",
+ "CountrySelect",
"CurrencyPicker",
"Dropdown",
"IconButton",
diff --git a/packages/twenty-ui/docs/public-exports.json b/packages/twenty-ui/docs/public-exports.json
index 6b97c612d1c..90c835ee41b 100644
--- a/packages/twenty-ui/docs/public-exports.json
+++ b/packages/twenty-ui/docs/public-exports.json
@@ -16,6 +16,7 @@
"AvatarGroup": "components/data-display/AvatarGroup/AvatarGroup",
"Callout": "components/feedback/Callout/Callout",
"CommandBlock": "components/data-display/CommandBlock/CommandBlock",
+ "CountrySelect": "components/input/CountrySelect/CountrySelect",
"CurrencyPicker": "components/input/CurrencyPicker/CurrencyPicker",
"DEFAULT_COLOR_LABELS": "components/navigation/MenuItem/constants/DefaultColorLabels",
"Dropdown": "components/navigation/Dropdown/Dropdown",
@@ -52,6 +53,8 @@
"CalloutProps": "components/feedback/Callout/types/CalloutProps",
"CalloutVariant": "components/feedback/Callout/types/CalloutVariant",
"ColorLabels": "components/navigation/MenuItem/types/ColorLabels",
+ "CountryChoice": "components/input/CountrySelect/types/CountryChoice",
+ "CountrySelectProps": "components/input/CountrySelect/types/CountrySelectProps",
"CurrencyPickerOption": "components/input/CurrencyPicker/types/CurrencyPickerOption",
"CurrencyPickerOptionsProps": "components/input/CurrencyPicker/types/CurrencyPickerOptionsProps",
"CurrencyPickerTriggerProps": "components/input/CurrencyPicker/types/CurrencyPickerTriggerProps",
@@ -927,6 +930,7 @@
"getUserDevice": "utilities/device/getUserDevice",
"isDefined": "utilities/utils/isDefined",
"MOBILE_MEDIA_QUERY": "utilities/responsive/constants/MobileMediaQuery",
+ "normalizeSearchText": "utilities/utils/normalizeSearchText",
"parseThemeColor": "utilities/color/utils/parseThemeColor",
"stringToThemeColor": "utilities/color/utils/stringToThemeColorP3String",
"stringToThemeColorP3String": "utilities/color/utils/stringToThemeColorP3String",
diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.json
index cf1c5fde16b..28b0bc4f343 100644
--- a/packages/twenty-ui/generated/components.docs.json
+++ b/packages/twenty-ui/generated/components.docs.json
@@ -1,4 +1,130 @@
[
+ {
+ "name": "CountrySelect",
+ "entryPoint": "twenty-ui/components",
+ "slug": "components/country-select",
+ "props": [
+ {
+ "name": "className",
+ "type": "string | ((state: PopoverTriggerState) => string | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Class applied to the trigger."
+ },
+ {
+ "name": "countries",
+ "type": "readonly CountryChoice[]",
+ "required": true,
+ "defaultValue": null,
+ "description": "Prepared country choices with unique non-empty values, display labels, and optional decorative flags."
+ },
+ {
+ "name": "disabled",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": "false",
+ "description": "Prevents opening and selection while the trigger stays focusable. An empty country list is also disabled."
+ },
+ {
+ "name": "id",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "ID of the trigger. Generated when omitted."
+ },
+ {
+ "name": "label",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Optional visible label that names the trigger and the popup."
+ },
+ {
+ "name": "nativeButton",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": "true",
+ "description": "Whether the component renders a native `<button>` element when replacing it\nvia the `render` prop.\nSet to `false` if the rendered element is not a button (e.g. `<div>`)."
+ },
+ {
+ "name": "noCountryLabel",
+ "type": "string",
+ "required": false,
+ "defaultValue": "No country",
+ "description": "Text of the no-country choice, also displayed when no country is selected."
+ },
+ {
+ "name": "noResultsLabel",
+ "type": "string",
+ "required": false,
+ "defaultValue": "No results",
+ "description": "Text displayed when no choice matches the search."
+ },
+ {
+ "name": "onOpenChange",
+ "type": "((open: boolean) => void)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Reports popup opening and closing."
+ },
+ {
+ "name": "onValueChange",
+ "type": "(value: string) => void",
+ "required": true,
+ "defaultValue": null,
+ "description": "Reports the selected choice value, or an empty string when no country is selected."
+ },
+ {
+ "name": "open",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": null,
+ "description": "Controls whether the country popup is open."
+ },
+ {
+ "name": "popupProps",
+ "type": "Omit<DropdownContentProps, \"children\" | \"aria-label\" | \"aria-labelledby\" | \"keepMounted\">",
+ "required": false,
+ "defaultValue": null,
+ "description": "Dropdown popup positioning, portal, focus, and event options for host integration."
+ },
+ {
+ "name": "ref",
+ "type": "Ref<HTMLButtonElement>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Ref to the trigger element."
+ },
+ {
+ "name": "render",
+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, PopoverTriggerState>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Replaces the trigger element while preserving its behavior and props."
+ },
+ {
+ "name": "searchLabel",
+ "type": "string",
+ "required": false,
+ "defaultValue": "Search",
+ "description": "Placeholder and accessible name of the search input."
+ },
+ {
+ "name": "style",
+ "type": "CSSProperties | ((state: PopoverTriggerState) => 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": "string",
+ "required": true,
+ "defaultValue": null,
+ "description": "Selected choice value. An empty string selects no country."
+ }
+ ]
+ },
{
"name": "CurrencyPicker",
"entryPoint": "twenty-ui/components",
diff --git a/packages/twenty-ui/src/components/index.ts b/packages/twenty-ui/src/components/index.ts
index 5196f6bd692..e803f7551d1 100644
--- a/packages/twenty-ui/src/components/index.ts
+++ b/packages/twenty-ui/src/components/index.ts
@@ -39,6 +39,9 @@ export type { ToastProviderProps } from './feedback/Toast/types/ToastProviderPro
export type { ToastVariant } from './feedback/Toast/types/ToastVariant';
export { Toaster } from './feedback/Toaster/Toaster';
export type { ToasterProps } from './feedback/Toaster/types/ToasterProps';
+export { CountrySelect } from './input/CountrySelect/CountrySelect';
+export type { CountryChoice } from './input/CountrySelect/types/CountryChoice';
+export type { CountrySelectProps } from './input/CountrySelect/types/CountrySelectProps';
export { CurrencyPicker } from './input/CurrencyPicker/CurrencyPicker';
export type { CurrencyPickerOption } from './input/CurrencyPicker/types/CurrencyPickerOption';
export type { CurrencyPickerOptionsProps } from './input/CurrencyPicker/types/CurrencyPickerOptionsProps';
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/CountrySelect.module.scss b/packages/twenty-ui/src/components/input/CountrySelect/CountrySelect.module.scss
new file mode 100644
index 00000000000..416107ebb13
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/CountrySelect.module.scss
@@ -0,0 +1,26 @@
+.root {
+ inline-size: 100%;
+ min-inline-size: 0;
+}
+
+.label {
+ color: var(--t-font-color-light);
+ display: block;
+ font-size: var(--t-font-size-xs);
+ font-weight: var(--t-font-weight-semi-bold);
+ margin-block-end: var(--t-spacing-1);
+}
+
+.flag {
+ align-items: center;
+ display: inline-flex;
+ flex: none;
+ justify-content: center;
+ inline-size: calc(var(--t-icon-size-md) * 1px);
+ block-size: calc(var(--t-icon-size-md) * 1px);
+
+ > svg {
+ max-inline-size: 100%;
+ max-block-size: 100%;
+ }
+}
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/CountrySelect.module.scss.d.ts b/packages/twenty-ui/src/components/input/CountrySelect/CountrySelect.module.scss.d.ts
new file mode 100644
index 00000000000..c4563bf6117
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/CountrySelect.module.scss.d.ts
@@ -0,0 +1,6 @@
+declare const classNames: {
+ readonly root: 'root';
+ readonly label: 'label';
+ readonly flag: 'flag';
+};
+export default classNames;
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/CountrySelect.tsx b/packages/twenty-ui/src/components/input/CountrySelect/CountrySelect.tsx
new file mode 100644
index 00000000000..1058e101288
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/CountrySelect.tsx
@@ -0,0 +1,174 @@
+import { type Popover as PopoverPrimitive } from '@base-ui/react/popover';
+import { clsx } from 'clsx';
+import { isFunction, isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';
+import { useId, useState } from 'react';
+
+import { Dropdown } from '@ui/components/navigation/Dropdown/Dropdown';
+import { IconChevronDown, IconCircleOff } from '@ui/icon';
+import inputStyles from '@ui/primitives/input/Input/Input.module.scss';
+import selectStyles from '@ui/primitives/input/Select/Select.module.scss';
+import { OverflowingTextWithTooltip } from '@ui/primitives/typography/OverflowingTextWithTooltip/OverflowingTextWithTooltip';
+import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';
+import { isDefined } from '@ui/utilities/utils/isDefined';
+
+import styles from './CountrySelect.module.scss';
+import { CountrySelectAvailabilityEffect } from './internal/CountrySelectAvailabilityEffect';
+import { CountrySelectOptions } from './internal/CountrySelectOptions';
+import { getCountrySelectLabelledBy } from './internal/getCountrySelectLabelledBy';
+import { type CountrySelectProps } from './types/CountrySelectProps';
+
+const skipTriggerActivation = (event: { preventBaseUIHandler?: () => void }) =>
+ event.preventBaseUIHandler?.();
+
+export const CountrySelect = ({
+ countries,
+ value,
+ onValueChange,
+ label,
+ searchLabel = 'Search',
+ noCountryLabel = 'No country',
+ noResultsLabel = 'No results',
+ open: controlledOpen,
+ onOpenChange,
+ popupProps,
+ disabled = false,
+ className,
+ style,
+ render,
+ onClick,
+ onMouseDown,
+ onPointerDown,
+ onKeyDown,
+ onKeyUp,
+ id,
+ 'aria-label': ariaLabel,
+ 'aria-labelledby': ariaLabelledBy,
+ 'aria-describedby': ariaDescribedBy,
+ ...props
+}: CountrySelectProps) => {
+ const generatedId = useId();
+ const triggerId = id ?? generatedId;
+ const labelId = `${generatedId}-label`;
+ const selectedValueId = `${generatedId}-value`;
+ const hasVisibleLabel = isNonEmptyString(label);
+ const nonEmptyAriaLabel = isNonEmptyString(ariaLabel) ? ariaLabel : undefined;
+ const labelledBy = getCountrySelectLabelledBy({
+ ariaLabelledBy,
+ ariaLabel: nonEmptyAriaLabel,
+ visibleLabelId: hasVisibleLabel ? labelId : undefined,
+ });
+ const hasExternalName = isDefined(labelledBy) || isDefined(nonEmptyAriaLabel);
+ const describedByIds = [
+ ariaDescribedBy,
+ hasExternalName ? selectedValueId : undefined,
+ ].filter(isNonEmptyString);
+ const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
+ const isDisabled = disabled || !isNonEmptyArray(countries);
+ const requestedOpen = controlledOpen ?? uncontrolledOpen;
+ const open = !isDisabled && requestedOpen;
+ const [previousOpen, setPreviousOpen] = useState(open);
+ const [openingCount, setOpeningCount] = useState(0);
+
+ if (previousOpen !== open) {
+ setPreviousOpen(open);
+
+ if (open) {
+ setOpeningCount(openingCount + 1);
+ }
+ }
+
+ const selectedCountry = countries.find((country) => country.value === value);
+ const selectedLabel = selectedCountry?.label ?? noCountryLabel;
+ const selectedFlag = isDefined(selectedCountry) ? (
+ selectedCountry.flag
+ ) : (
+ <IconCircleOff />
+ );
+
+ const getTriggerState = (
+ state: PopoverPrimitive.Trigger.State,
+ ): PopoverPrimitive.Trigger.State => ({ ...state, disabled: isDisabled });
+ const triggerClassName = mergeClassNames<PopoverPrimitive.Trigger.State>(
+ clsx(inputStyles.input, inputStyles.md, selectStyles.trigger),
+ className,
+ );
+
+ const handleOpenChange = (nextOpen: boolean) => {
+ if (nextOpen && isDisabled) {
+ return;
+ }
+
+ setUncontrolledOpen(nextOpen);
+ onOpenChange?.(nextOpen);
+ };
+
+ return (
+ <div className={styles.root}>
+ <CountrySelectAvailabilityEffect
+ disabled={isDisabled}
+ open={requestedOpen}
+ onOpenChange={handleOpenChange}
+ />
+ {hasVisibleLabel && (
+ <label id={labelId} className={styles.label} htmlFor={triggerId}>
+ {label}
+ </label>
+ )}
+ <Dropdown.Root type="picker" open={open} onOpenChange={handleOpenChange}>
+ <Dropdown.Trigger
+ {...props}
+ id={triggerId}
+ aria-label={nonEmptyAriaLabel}
+ aria-labelledby={labelledBy}
+ aria-describedby={
+ isNonEmptyArray(describedByIds)
+ ? describedByIds.join(' ')
+ : undefined
+ }
+ aria-disabled={isDisabled || undefined}
+ data-disabled={isDisabled ? '' : undefined}
+ onClick={isDisabled ? skipTriggerActivation : onClick}
+ onMouseDown={isDisabled ? skipTriggerActivation : onMouseDown}
+ onPointerDown={isDisabled ? skipTriggerActivation : onPointerDown}
+ onKeyDown={isDisabled ? skipTriggerActivation : onKeyDown}
+ onKeyUp={isDisabled ? skipTriggerActivation : onKeyUp}
+ className={(state) => triggerClassName(getTriggerState(state))}
+ style={
+ isFunction(style) ? (state) => style(getTriggerState(state)) : style
+ }
+ render={
+ isFunction(render)
+ ? (renderProps, state) =>
+ render(renderProps, getTriggerState(state))
+ : render
+ }
+ >
+ <span className={styles.flag} aria-hidden="true">
+ {selectedFlag}
+ </span>
+ <span className={selectStyles.value} id={selectedValueId}>
+ <OverflowingTextWithTooltip text={selectedLabel} />
+ </span>
+ <span className={selectStyles.icon} aria-hidden="true">
+ <IconChevronDown />
+ </span>
+ </Dropdown.Trigger>
+ <Dropdown.Content
+ {...popupProps}
+ aria-label={nonEmptyAriaLabel}
+ aria-labelledby={labelledBy}
+ >
+ <CountrySelectOptions
+ key={openingCount}
+ countries={countries}
+ value={value}
+ onValueChange={onValueChange}
+ searchLabel={searchLabel}
+ noCountryLabel={noCountryLabel}
+ noResultsLabel={noResultsLabel}
+ />
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </div>
+ );
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/COUNTRY_CHOICES.ts b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/COUNTRY_CHOICES.ts
new file mode 100644
index 00000000000..cc8b323e6b7
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/COUNTRY_CHOICES.ts
@@ -0,0 +1,7 @@
+import { type CountryChoice } from '../types/CountryChoice';
+
+export const COUNTRY_CHOICES = [
+ { value: 'France', label: 'France', flag: '🇫🇷' },
+ { value: 'Brazil', label: 'Brésil', flag: '🇧🇷' },
+ { value: 'Japan', label: 'Japon', flag: '🇯🇵' },
+] satisfies CountryChoice[];
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.accessibility.stories.tsx b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.accessibility.stories.tsx
new file mode 100644
index 00000000000..fb1624d35dc
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.accessibility.stories.tsx
@@ -0,0 +1,166 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+
+import { A11Y_DEFER_COLOR_CONTRAST, ComponentDecorator } from '@ui/testing';
+
+import { CountrySelectExample } from './CountrySelectExample';
+import { waitForCountryPopup } from './waitForCountryPopup';
+
+const LONG_COUNTRY_LABEL =
+ 'A country with a long localized name that exceeds the trigger width';
+
+const meta: Meta<typeof CountrySelectExample> = {
+ title: 'UI/Input/CountrySelect/Accessibility',
+ component: CountrySelectExample,
+ tags: ['!autodocs'],
+ decorators: [ComponentDecorator],
+ parameters: {
+ container: { width: 240, height: 320 },
+ a11y: A11Y_DEFER_COLOR_CONTRAST,
+ },
+ args: { onValueChange: fn(), onOpenChange: fn() },
+};
+
+export default meta;
+type Story = StoryObj<typeof CountrySelectExample>;
+
+export const SelectedValueDescription: Story = {
+ args: { label: '', 'aria-label': 'Shipping country' },
+ render: (args) => (
+ <>
+ <span id="country-help">Delivery destination</span>
+ <CountrySelectExample {...args} aria-describedby="country-help" />
+ </>
+ ),
+ play: async ({ canvasElement }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Shipping country',
+ });
+
+ expect(trigger).toHaveAccessibleDescription('Delivery destination France');
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({
+ canvasElement,
+ name: 'Shipping country',
+ });
+ const noCountry = within(popup).getByRole('button', { name: 'No country' });
+
+ expect(noCountry.querySelector('svg')?.parentElement).toHaveAttribute(
+ 'aria-hidden',
+ 'true',
+ );
+ await userEvent.click(noCountry);
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(trigger).toHaveAccessibleName('Shipping country');
+ expect(trigger).toHaveAccessibleDescription(
+ 'Delivery destination No country',
+ );
+ },
+};
+
+export const TriggerNameFallback: Story = {
+ args: { label: '', 'aria-label': '' },
+ play: async ({ canvasElement }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'France',
+ });
+
+ expect(trigger).not.toHaveAttribute('aria-describedby');
+ expect(trigger).toHaveAccessibleDescription('');
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement, name: 'France' });
+
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ },
+};
+
+export const ExternalLabelledBy: Story = {
+ args: { label: '' },
+ render: (args) => (
+ <>
+ <span id="country-name">Destination country</span>
+ <CountrySelectExample {...args} aria-labelledby="country-name" />
+ </>
+ ),
+ play: async ({ canvasElement }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Destination country',
+ });
+
+ expect(trigger).toHaveAccessibleDescription('France');
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({
+ canvasElement,
+ name: 'Destination country',
+ });
+
+ expect(popup).toHaveAttribute('aria-labelledby', 'country-name');
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ },
+};
+
+export const AriaLabelOverVisibleLabel: Story = {
+ args: { label: 'Country', 'aria-label': 'Shipping country' },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const trigger = canvas.getByRole('button', { name: 'Shipping country' });
+
+ expect(canvas.getByText('Country')).toBeVisible();
+ expect(trigger).toHaveAccessibleDescription('France');
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({
+ canvasElement,
+ name: 'Shipping country',
+ });
+
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ },
+};
+
+export const NonButtonTriggerLabel: Story = {
+ render: (args) => (
+ <CountrySelectExample {...args} render={<div />} nativeButton={false} />
+ ),
+ play: async ({ canvasElement }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Country',
+ });
+
+ expect(trigger.tagName).toBe('DIV');
+ expect(trigger).toHaveAccessibleDescription('France');
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement });
+
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ await waitFor(() => expect(trigger).toHaveFocus());
+ },
+};
+
+export const TruncatedCountryDisclosure: Story = {
+ args: {
+ countries: [{ value: 'France', label: LONG_COUNTRY_LABEL, flag: '🇫🇷' }],
+ },
+ play: async ({ canvasElement }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Country',
+ });
+ const selectedText = within(trigger).getByText(LONG_COUNTRY_LABEL);
+
+ expect(trigger).toHaveAccessibleDescription(LONG_COUNTRY_LABEL);
+ expect(selectedText.scrollWidth).toBeGreaterThan(selectedText.clientWidth);
+ await userEvent.hover(selectedText);
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ 'tooltip',
+ { name: LONG_COUNTRY_LABEL },
+ );
+
+ await waitFor(() => expect(tooltip).toBeVisible());
+ expect(tooltip).toHaveTextContent(LONG_COUNTRY_LABEL);
+ await userEvent.unhover(selectedText);
+ await waitFor(() => expect(tooltip).not.toBeInTheDocument());
+ },
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.availability.stories.tsx b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.availability.stories.tsx
new file mode 100644
index 00000000000..7f085c1047b
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.availability.stories.tsx
@@ -0,0 +1,65 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+
+import { A11Y_DEFER_COLOR_CONTRAST, ComponentDecorator } from '@ui/testing';
+
+import { assertCountryAvailabilityReset } from './assertCountryAvailabilityReset';
+import { CountrySelectAvailabilityExample } from './CountrySelectAvailabilityExample';
+import { waitForCountryPopup } from './waitForCountryPopup';
+
+const meta: Meta<typeof CountrySelectAvailabilityExample> = {
+ title: 'UI/Input/CountrySelect/Availability',
+ component: CountrySelectAvailabilityExample,
+ tags: ['!autodocs'],
+ decorators: [ComponentDecorator],
+ parameters: {
+ container: { width: 320, height: 320 },
+ a11y: A11Y_DEFER_COLOR_CONTRAST,
+ },
+ args: { onOpenChange: fn(), availability: 'disabled' },
+};
+
+export default meta;
+type Story = StoryObj<typeof CountrySelectAvailabilityExample>;
+
+export const DisableAndEnable: Story = {
+ play: assertCountryAvailabilityReset,
+};
+
+export const ControlledDisableAndEnable: Story = {
+ args: { controlled: true },
+ play: assertCountryAvailabilityReset,
+};
+
+export const RemoveAndRestoreCountries: Story = {
+ args: { availability: 'countries' },
+ play: assertCountryAvailabilityReset,
+};
+
+export const ControlledRemoveAndRestoreCountries: Story = {
+ args: { controlled: true, availability: 'countries' },
+ play: assertCountryAvailabilityReset,
+};
+
+export const NotifyControlledHostOnce: Story = {
+ args: { controlled: true, ignoreCloseRequests: true },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const trigger = canvas.getByRole('button', { name: 'Country' });
+
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement });
+
+ await userEvent.click(
+ within(popup).getByRole('button', { name: 'Make countries unavailable' }),
+ );
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(trigger).toHaveAttribute('aria-disabled', 'true');
+ await waitFor(() => expect(trigger).toHaveFocus());
+ expect(args.onOpenChange).toHaveBeenLastCalledWith(false);
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Refresh host 0' }),
+ );
+ expect(args.onOpenChange).toHaveBeenCalledTimes(2);
+ },
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.interactions.stories.tsx b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.interactions.stories.tsx
new file mode 100644
index 00000000000..04d41ae6597
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.interactions.stories.tsx
@@ -0,0 +1,534 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { type CSSProperties, useState } from 'react';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+
+import { Button } from '@ui/primitives/input/Button/Button';
+import { TextDirectionProvider } from '@ui/primitives/layout/TextDirectionProvider/TextDirectionProvider';
+import { A11Y_DEFER_COLOR_CONTRAST, ComponentDecorator } from '@ui/testing';
+import { ThemeProvider } from '@ui/theme/ThemeProvider';
+
+import { CountrySelect } from '../CountrySelect';
+import { type CountrySelectProps } from '../types/CountrySelectProps';
+import { COUNTRY_CHOICES } from './COUNTRY_CHOICES';
+import { CountrySelectExample } from './CountrySelectExample';
+import { waitForCountryPopup } from './waitForCountryPopup';
+
+const meta: Meta<typeof CountrySelectExample> = {
+ title: 'UI/Input/CountrySelect/Interactions',
+ component: CountrySelectExample,
+ tags: ['!autodocs'],
+ decorators: [ComponentDecorator],
+ parameters: {
+ container: { width: 320, height: 320 },
+ a11y: {
+ config: {
+ rules: [
+ ...A11Y_DEFER_COLOR_CONTRAST.config.rules,
+ {
+ id: 'aria-hidden-focus',
+ selector: '[aria-hidden="true"]:not([data-base-ui-focus-guard])',
+ },
+ ],
+ },
+ },
+ },
+ args: { onValueChange: fn(), onOpenChange: fn() },
+};
+
+export default meta;
+type Story = StoryObj<typeof CountrySelectExample>;
+
+export const PointerSelection: Story = {
+ play: async ({ canvasElement, args }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Country',
+ });
+
+ expect(trigger).toHaveTextContent('France');
+ expect(within(trigger).getByText('🇫🇷')).toHaveAttribute(
+ 'aria-hidden',
+ 'true',
+ );
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement });
+ const choices = within(popup);
+
+ expect(choices.getByRole('button', { name: 'France' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ expect(choices.getByText('🇧🇷')).toHaveAttribute('aria-hidden', 'true');
+ await userEvent.click(choices.getByRole('button', { name: 'Brésil' }));
+ expect(args.onValueChange).toHaveBeenCalledWith('Brazil');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(trigger).toHaveTextContent('Brésil');
+ await waitFor(() => expect(trigger).toHaveFocus());
+ expect(args.onOpenChange).toHaveBeenLastCalledWith(false);
+ },
+};
+
+export const SearchAndKeyboard: Story = {
+ play: async ({ canvasElement, args }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Country',
+ });
+
+ await userEvent.tab();
+ expect(trigger).toHaveFocus();
+ await userEvent.keyboard('{Enter}');
+ const popup = await waitForCountryPopup({ canvasElement });
+ const choices = within(popup);
+ const search = choices.getByRole('searchbox', {
+ name: 'Search countries',
+ });
+
+ await userEvent.keyboard('{Enter}');
+ expect(args.onValueChange).not.toHaveBeenCalled();
+ await userEvent.type(search, 'BRESIL');
+ expect(choices.queryByRole('button', { name: 'France' })).toBeNull();
+ expect(choices.queryByRole('button', { name: 'No country' })).toBeNull();
+ expect(choices.getByRole('button', { name: 'Brésil' })).toBeVisible();
+ await userEvent.keyboard('{Enter}');
+ expect(args.onValueChange).toHaveBeenCalledWith('Brazil');
+ expect(choices.getByRole('searchbox')).toHaveValue('BRESIL');
+ expect(choices.queryByRole('button', { name: 'France' })).toBeNull();
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ await waitFor(() => expect(trigger).toHaveFocus());
+ await userEvent.keyboard('{Enter}');
+ const reopenedPopup = await waitForCountryPopup({ canvasElement });
+ const reopenedChoices = within(reopenedPopup);
+
+ expect(reopenedChoices.getByRole('searchbox')).toHaveValue('');
+ await userEvent.keyboard('{ArrowDown}');
+ expect(
+ reopenedChoices.getByRole('button', { name: 'No country' }),
+ ).toHaveFocus();
+ await userEvent.keyboard('{ArrowDown}');
+ expect(
+ reopenedChoices.getByRole('button', { name: 'France' }),
+ ).toHaveFocus();
+ await userEvent.keyboard('{Enter}');
+ expect(args.onValueChange).toHaveBeenLastCalledWith('France');
+ await waitFor(() => expect(reopenedPopup).not.toBeInTheDocument());
+ expect(trigger).toHaveTextContent('France');
+ },
+};
+
+export const SearchListsCountriesBeforeNoCountry: Story = {
+ play: async ({ canvasElement, args }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Country',
+ });
+
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement });
+ const choices = within(popup);
+ const search = choices.getByRole('searchbox');
+
+ expect(choices.getAllByRole('button')[0]).toHaveAccessibleName(
+ 'No country',
+ );
+ await userEvent.type(search, ' ');
+ const unfilteredChoices = choices.getAllByRole('button');
+
+ expect(unfilteredChoices).toHaveLength(4);
+ expect(unfilteredChoices[0]).toHaveAccessibleName('No country');
+ await userEvent.type(search, 'o');
+ const matchingChoices = choices.getAllByRole('button');
+
+ expect(matchingChoices).toHaveLength(2);
+ expect(matchingChoices[0]).toHaveAccessibleName('Japon');
+ expect(matchingChoices[1]).toHaveAccessibleName('No country');
+ await userEvent.keyboard('{Enter}');
+ expect(args.onValueChange).toHaveBeenCalledTimes(1);
+ expect(args.onValueChange).toHaveBeenCalledWith('Japan');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(trigger).toHaveTextContent('Japon');
+ },
+};
+
+export const ClearCountry: Story = {
+ play: async ({ canvasElement, args }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Country',
+ });
+
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement });
+ const choices = within(popup);
+
+ await userEvent.type(choices.getByRole('searchbox'), 'NO COUNTRY');
+ expect(choices.getAllByRole('button')).toHaveLength(1);
+ await userEvent.click(choices.getByRole('button', { name: 'No country' }));
+ expect(args.onValueChange).toHaveBeenCalledWith('');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(trigger).toHaveTextContent('No country');
+ await userEvent.click(trigger);
+ const reopenedPopup = await waitForCountryPopup({ canvasElement });
+
+ expect(
+ within(reopenedPopup).getByRole('button', { name: 'No country' }),
+ ).toHaveAttribute('aria-pressed', 'true');
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(reopenedPopup).not.toBeInTheDocument());
+ },
+};
+
+export const EmptySearchAndEscape: Story = {
+ play: async ({ canvasElement, args }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Country',
+ });
+
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement });
+ const choices = within(popup);
+ const search = choices.getByRole('searchbox');
+
+ await userEvent.type(search, 'Atlantis');
+ expect(choices.getByRole('status')).toHaveTextContent('No countries found');
+ expect(choices.queryAllByRole('button')).toHaveLength(0);
+ await userEvent.keyboard('{ArrowDown}{Enter}');
+ expect(args.onValueChange).not.toHaveBeenCalled();
+ expect(popup).toBeVisible();
+ expect(search).toHaveFocus();
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ await waitFor(() => expect(trigger).toHaveFocus());
+ expect(trigger).toHaveTextContent('France');
+ expect(args.onOpenChange).toHaveBeenLastCalledWith(false);
+ },
+};
+
+export const ReopenDuringExitFade: Story = {
+ args: {
+ popupProps: {
+ style: { '--t-animation-duration-fast': '1' } as CSSProperties,
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Country',
+ });
+
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement });
+
+ await userEvent.type(within(popup).getByRole('searchbox'), 'bresil');
+ await waitFor(() => expect(getComputedStyle(popup).opacity).toBe('1'), {
+ timeout: 2000,
+ });
+ await userEvent.keyboard('{Escape}');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(popup).toBeInTheDocument();
+ await userEvent.click(trigger);
+ const reopenedPopup = await waitForCountryPopup({ canvasElement });
+ const reopenedChoices = within(reopenedPopup);
+
+ expect(reopenedPopup).toBe(popup);
+ expect(reopenedChoices.getByRole('searchbox')).toHaveValue('');
+ expect(reopenedChoices.getAllByRole('button')).toHaveLength(4);
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(reopenedPopup).not.toBeInTheDocument(), {
+ timeout: 2000,
+ });
+ },
+};
+
+export const UnknownStoredValue: Story = {
+ args: { value: 'Previously stored country' },
+ play: async ({ canvasElement, args }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Country',
+ });
+
+ expect(trigger).toHaveTextContent('No country');
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement });
+
+ for (const choice of within(popup).getAllByRole('button')) {
+ expect(choice).toHaveAttribute('aria-pressed', 'false');
+ }
+
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(args.onValueChange).not.toHaveBeenCalled();
+ await waitFor(() => expect(trigger).toHaveFocus());
+ },
+};
+
+export const DisabledAndUnavailable: Story = {
+ render: (args) => (
+ <>
+ <CountrySelectExample {...args} label="Disabled country" disabled />
+ <CountrySelectExample
+ {...args}
+ label="Unavailable countries"
+ countries={[]}
+ value=""
+ />
+ </>
+ ),
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+
+ for (const name of ['Disabled country', 'Unavailable countries']) {
+ const trigger = canvas.getByRole('button', { name });
+
+ expect(trigger).toHaveAttribute('aria-disabled', 'true');
+ expect(trigger).toHaveAttribute('data-disabled');
+ await userEvent.tab();
+ expect(trigger).toHaveFocus();
+ await userEvent.keyboard('{ArrowDown}');
+ await userEvent.keyboard('{Enter}');
+ await userEvent.keyboard(' ');
+ await userEvent.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(body.queryByRole('dialog')).toBeNull();
+ await userEvent.click(canvas.getByText(name, { selector: 'label' }));
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(body.queryByRole('dialog')).toBeNull();
+ }
+
+ expect(args.onOpenChange).not.toHaveBeenCalled();
+ expect(args.onValueChange).not.toHaveBeenCalled();
+ },
+};
+
+export const DisabledSkipsTriggerHandlers: Story = {
+ args: {
+ disabled: true,
+ onClick: fn(),
+ onPointerDown: fn(),
+ onKeyDown: fn(),
+ },
+ play: async ({ canvasElement, args }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Country',
+ });
+
+ const defaultPreventedKeys: string[] = [];
+ const recordDefaultPreventedKey = (event: KeyboardEvent) => {
+ if (event.defaultPrevented) {
+ defaultPreventedKeys.push(event.key);
+ }
+ };
+
+ canvasElement.ownerDocument.addEventListener(
+ 'keydown',
+ recordDefaultPreventedKey,
+ );
+
+ try {
+ await userEvent.tab();
+ expect(trigger).toHaveFocus();
+ await userEvent.keyboard('{Shift}{ArrowDown}{ArrowUp}');
+ await userEvent.click(trigger);
+ } finally {
+ canvasElement.ownerDocument.removeEventListener(
+ 'keydown',
+ recordDefaultPreventedKey,
+ );
+ }
+
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(defaultPreventedKeys).toEqual([]);
+ expect(args.onKeyDown).not.toHaveBeenCalled();
+ expect(args.onPointerDown).not.toHaveBeenCalled();
+ expect(args.onClick).not.toHaveBeenCalled();
+ expect(args.onOpenChange).not.toHaveBeenCalled();
+ },
+};
+
+export const EnabledRunsTriggerHandlers: Story = {
+ args: {
+ onClick: fn(),
+ onPointerDown: fn(),
+ onKeyDown: fn(),
+ },
+ play: async ({ canvasElement, args }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Country',
+ });
+
+ await userEvent.tab();
+ expect(trigger).toHaveFocus();
+ await userEvent.keyboard('{Shift}');
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement });
+
+ expect(args.onKeyDown).toHaveBeenCalledTimes(1);
+ expect(args.onPointerDown).toHaveBeenCalledTimes(1);
+ expect(args.onClick).toHaveBeenCalledTimes(1);
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ },
+};
+
+export const IndependentInstances: Story = {
+ render: () => (
+ <>
+ <CountrySelectExample label="Billing country" />
+ <CountrySelectExample label="Shipping country" value="Japan" />
+ </>
+ ),
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const billing = canvas.getByRole('button', { name: 'Billing country' });
+ const shipping = canvas.getByRole('button', { name: 'Shipping country' });
+
+ expect(billing.id).not.toBe(shipping.id);
+ await userEvent.click(billing);
+ const popup = await waitForCountryPopup({
+ canvasElement,
+ name: 'Billing country',
+ });
+
+ await userEvent.type(within(popup).getByRole('searchbox'), 'bresil');
+ await userEvent.keyboard('{Enter}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(billing).toHaveTextContent('Brésil');
+ expect(shipping).toHaveTextContent('Japon');
+ await userEvent.click(shipping);
+ const shippingPopup = await waitForCountryPopup({
+ canvasElement,
+ name: 'Shipping country',
+ });
+
+ expect(shippingPopup).toHaveAccessibleName('Shipping country');
+ expect(within(shippingPopup).getByRole('searchbox')).toHaveValue('');
+ await userEvent.click(
+ within(shippingPopup).getByRole('button', { name: 'No country' }),
+ );
+ await waitFor(() => expect(shippingPopup).not.toBeInTheDocument());
+ expect(shipping).toHaveTextContent('No country');
+ expect(billing).toHaveTextContent('Brésil');
+ },
+};
+
+const ControlledCountryExample = ({
+ onValueChange,
+ onOpenChange,
+}: Partial<CountrySelectProps>) => {
+ const [value, setValue] = useState('France');
+ const [open, setOpen] = useState(false);
+
+ return (
+ <>
+ <CountrySelect
+ countries={COUNTRY_CHOICES}
+ label="Country"
+ searchLabel="Search countries"
+ noCountryLabel="No country"
+ noResultsLabel="No countries found"
+ value={value}
+ onValueChange={onValueChange ?? (() => undefined)}
+ open={open}
+ onOpenChange={(nextOpen) => {
+ setOpen(nextOpen);
+ onOpenChange?.(nextOpen);
+ }}
+ />
+ <Button onClick={() => setValue('Japan')}>Apply Japan</Button>
+ <Button onClick={() => setOpen(true)}>Open countries</Button>
+ </>
+ );
+};
+
+export const ControlledUpdates: Story = {
+ render: (args) => <ControlledCountryExample {...args} />,
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const trigger = canvas.getByRole('button', { name: 'Country' });
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Open countries' }),
+ );
+ const popup = await waitForCountryPopup({ canvasElement });
+
+ await userEvent.click(
+ within(popup).getByRole('button', { name: 'Brésil' }),
+ );
+ expect(args.onValueChange).toHaveBeenCalledWith('Brazil');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(args.onOpenChange).toHaveBeenCalledWith(false);
+ expect(trigger).toHaveTextContent('France');
+ await userEvent.click(canvas.getByRole('button', { name: 'Apply Japan' }));
+ expect(trigger).toHaveTextContent('Japon');
+ },
+};
+
+const ArgumentUpdatesExample = (props: Partial<CountrySelectProps>) => {
+ const [value, setValue] = useState('France');
+
+ return (
+ <>
+ <CountrySelectExample {...props} value={value} />
+ <Button onClick={() => setValue('Japan')}>Apply Japan</Button>
+ </>
+ );
+};
+
+export const ArgumentUpdates: Story = {
+ render: (args) => <ArgumentUpdatesExample {...args} />,
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+
+ await userEvent.click(canvas.getByRole('button', { name: 'Country' }));
+ const popup = await waitForCountryPopup({ canvasElement });
+
+ await userEvent.click(
+ within(popup).getByRole('button', { name: 'Brésil' }),
+ );
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(canvas.getByRole('button', { name: 'Country' })).toHaveTextContent(
+ 'Brésil',
+ );
+ await userEvent.click(canvas.getByRole('button', { name: 'Apply Japan' }));
+ expect(canvas.getByRole('button', { name: 'Country' })).toHaveTextContent(
+ 'Japon',
+ );
+ expect(args.onValueChange).toHaveBeenCalledTimes(1);
+ expect(args.onValueChange).toHaveBeenCalledWith('Brazil');
+ },
+};
+
+const ScopedCountryExample = (props: Partial<CountrySelectProps>) => {
+ const [container, setContainer] = useState<HTMLDivElement | null>(null);
+
+ return (
+ <ThemeProvider colorScheme="dark" applyToRoot={false}>
+ <TextDirectionProvider direction="rtl">
+ <div dir="rtl">
+ <CountrySelectExample
+ {...props}
+ popupProps={{ ...props.popupProps, container, align: 'start' }}
+ />
+ <div ref={setContainer} role="region" aria-label="Country portal" />
+ </div>
+ </TextDirectionProvider>
+ </ThemeProvider>
+ );
+};
+
+export const ScopedThemeAndContainer: Story = {
+ render: (args) => <ScopedCountryExample {...args} />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const trigger = canvas.getByRole('button', { name: 'Country' });
+
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement });
+
+ expect(
+ canvas.getByRole('region', { name: 'Country portal' }),
+ ).toContainElement(popup);
+ expect(popup.closest('.dark')).not.toBeNull();
+ expect(getComputedStyle(popup).direction).toBe('rtl');
+ await userEvent.type(within(popup).getByRole('searchbox'), 'japon');
+ await userEvent.keyboard('{Enter}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(trigger).toHaveTextContent('Japon');
+ },
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.stories.tsx b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.stories.tsx
new file mode 100644
index 00000000000..c4c47cab867
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.stories.tsx
@@ -0,0 +1,48 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, within } from 'storybook/test';
+
+import { A11Y_DEFER_COLOR_CONTRAST, ComponentDecorator } from '@ui/testing';
+import { ThemeProvider } from '@ui/theme/ThemeProvider';
+
+import { CountrySelectExample } from './CountrySelectExample';
+
+const meta: Meta<typeof CountrySelectExample> = {
+ title: 'UI/Input/CountrySelect',
+ component: CountrySelectExample,
+ decorators: [ComponentDecorator],
+ parameters: {
+ container: { width: 280, height: 220 },
+ a11y: A11Y_DEFER_COLOR_CONTRAST,
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof CountrySelectExample>;
+
+export const Default: Story = {};
+
+export const Disabled: Story = {
+ args: { disabled: true },
+};
+
+export const Empty: Story = {
+ args: { value: '' },
+};
+
+export const ScopedTheme: Story = {
+ args: { value: 'Japan', label: 'Scoped country' },
+ render: (args) => (
+ <ThemeProvider colorScheme="dark" applyToRoot={false}>
+ <div style={{ background: 'var(--t-background-primary)', padding: 16 }}>
+ <CountrySelectExample {...args} />
+ </div>
+ </ThemeProvider>
+ ),
+ play: async ({ canvasElement }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Scoped country',
+ });
+
+ expect(trigger).toHaveTextContent('Japon');
+ },
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectAvailabilityExample.tsx b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectAvailabilityExample.tsx
new file mode 100644
index 00000000000..c951af7b72d
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectAvailabilityExample.tsx
@@ -0,0 +1,69 @@
+import { useState } from 'react';
+
+import { Button } from '@ui/primitives/input/Button/Button';
+
+import { CountrySelect } from '../CountrySelect';
+import { type CountrySelectProps } from '../types/CountrySelectProps';
+import { COUNTRY_CHOICES } from './COUNTRY_CHOICES';
+
+type CountrySelectAvailabilityExampleProps = Partial<CountrySelectProps> & {
+ controlled?: boolean;
+ availability: 'disabled' | 'countries';
+ ignoreCloseRequests?: boolean;
+};
+
+export const CountrySelectAvailabilityExample = ({
+ controlled = false,
+ availability,
+ ignoreCloseRequests = false,
+ onOpenChange,
+}: CountrySelectAvailabilityExampleProps) => {
+ const [unavailable, setUnavailable] = useState(false);
+ const [open, setOpen] = useState(false);
+ const [revision, setRevision] = useState(0);
+
+ return (
+ <>
+ <CountrySelect
+ countries={
+ unavailable && availability === 'countries' ? [] : COUNTRY_CHOICES
+ }
+ disabled={unavailable && availability === 'disabled'}
+ label="Country"
+ searchLabel="Search countries"
+ noCountryLabel="No country"
+ noResultsLabel="No countries found"
+ value="France"
+ onValueChange={() => undefined}
+ open={controlled ? open : undefined}
+ onOpenChange={(nextOpen) => {
+ onOpenChange?.(nextOpen);
+
+ if (!ignoreCloseRequests || nextOpen) {
+ setOpen(nextOpen);
+ }
+ }}
+ popupProps={{
+ render: (popupProps) => (
+ <div {...popupProps}>
+ {popupProps.children}
+ <Button onClick={() => setUnavailable(true)}>
+ Make countries unavailable
+ </Button>
+ </div>
+ ),
+ }}
+ />
+ {unavailable && (
+ <>
+ <Button onClick={() => setUnavailable(false)}>
+ Restore countries
+ </Button>
+ <Button onClick={() => setRevision(revision + 1)}>
+ Refresh host {revision}
+ </Button>
+ </>
+ )}
+ </>
+ );
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectExample.tsx b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectExample.tsx
new file mode 100644
index 00000000000..5b80d3a6a76
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectExample.tsx
@@ -0,0 +1,33 @@
+import { useState } from 'react';
+
+import { CountrySelect } from '../CountrySelect';
+import { type CountrySelectProps } from '../types/CountrySelectProps';
+import { COUNTRY_CHOICES } from './COUNTRY_CHOICES';
+
+const StatefulCountrySelectExample = ({
+ value: initialValue = 'France',
+ onValueChange,
+ ...props
+}: Partial<CountrySelectProps>) => {
+ const [value, setValue] = useState(initialValue);
+
+ return (
+ <CountrySelect
+ countries={COUNTRY_CHOICES}
+ label="Country"
+ searchLabel="Search countries"
+ noCountryLabel="No country"
+ noResultsLabel="No countries found"
+ {...props}
+ value={value}
+ onValueChange={(nextValue) => {
+ setValue(nextValue);
+ onValueChange?.(nextValue);
+ }}
+ />
+ );
+};
+
+export const CountrySelectExample = (props: Partial<CountrySelectProps>) => (
+ <StatefulCountrySelectExample key={props.value} {...props} />
+);
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/assertCountryAvailabilityReset.ts b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/assertCountryAvailabilityReset.ts
new file mode 100644
index 00000000000..03c9ba7ff7f
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/assertCountryAvailabilityReset.ts
@@ -0,0 +1,46 @@
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+
+import { type CountrySelectProps } from '../types/CountrySelectProps';
+import { waitForCountryPopup } from './waitForCountryPopup';
+
+export const assertCountryAvailabilityReset = async ({
+ canvasElement,
+ args,
+}: {
+ canvasElement: HTMLElement;
+ args: Partial<CountrySelectProps>;
+}) => {
+ const canvas = within(canvasElement);
+ const trigger = canvas.getByRole('button', { name: 'Country' });
+
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement });
+
+ await userEvent.type(within(popup).getByRole('searchbox'), 'bresil');
+ await userEvent.click(
+ within(popup).getByRole('button', { name: 'Make countries unavailable' }),
+ );
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(trigger).toHaveAttribute('aria-disabled', 'true');
+ await waitFor(() => expect(trigger).toHaveFocus());
+ expect(args.onOpenChange).toHaveBeenLastCalledWith(false);
+ expect(args.onOpenChange).toHaveBeenCalledTimes(2);
+ await userEvent.keyboard('{Enter}');
+ await userEvent.click(trigger);
+ expect(
+ within(canvasElement.ownerDocument.body).queryByRole('dialog'),
+ ).toBeNull();
+ expect(args.onOpenChange).toHaveBeenCalledTimes(2);
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Restore countries' }),
+ );
+ expect(trigger).not.toHaveAttribute('aria-disabled');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(args.onOpenChange).toHaveBeenCalledTimes(2);
+ await userEvent.click(trigger);
+ const reopenedPopup = await waitForCountryPopup({ canvasElement });
+
+ expect(within(reopenedPopup).getByRole('searchbox')).toHaveValue('');
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(reopenedPopup).not.toBeInTheDocument());
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/waitForCountryPopup.ts b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/waitForCountryPopup.ts
new file mode 100644
index 00000000000..c670670ebfa
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/waitForCountryPopup.ts
@@ -0,0 +1,21 @@
+import { expect, waitFor, within } from 'storybook/test';
+
+export const waitForCountryPopup = async ({
+ canvasElement,
+ name = 'Country',
+}: {
+ canvasElement: HTMLElement;
+ name?: string;
+}) => {
+ const popup = await within(canvasElement.ownerDocument.body).findByRole(
+ 'dialog',
+ { name },
+ );
+
+ await waitFor(() => expect(popup).toBeVisible());
+ await waitFor(() =>
+ expect(within(popup).getByRole('searchbox')).toHaveFocus(),
+ );
+
+ return popup;
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__tests__/CountrySelect.test.tsx b/packages/twenty-ui/src/components/input/CountrySelect/__tests__/CountrySelect.test.tsx
new file mode 100644
index 00000000000..4ad09dcef8b
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__tests__/CountrySelect.test.tsx
@@ -0,0 +1,79 @@
+import { runComponentConformance } from '@test-utilities/conformance/runComponentConformance';
+import { render, screen } from '@testing-library/react';
+import { expect, it } from 'vitest';
+
+import { ThemeProvider } from '@ui/theme/ThemeProvider';
+
+import { CountrySelect } from '../CountrySelect';
+
+runComponentConformance({
+ name: 'CountrySelect',
+ element: (
+ <CountrySelect
+ countries={[{ value: 'France', label: 'France' }]}
+ value="France"
+ onValueChange={() => undefined}
+ />
+ ),
+ refInstanceOf: HTMLButtonElement,
+ renderPropTagName: 'button',
+});
+
+const FRANCE_CHOICE = { value: 'France', label: 'France' };
+
+it.each([
+ {
+ availability: 'enabled',
+ disabled: false,
+ countries: [FRANCE_CHOICE],
+ expectedDisabled: false,
+ },
+ {
+ availability: 'disabled',
+ disabled: true,
+ countries: [FRANCE_CHOICE],
+ expectedDisabled: true,
+ },
+ {
+ availability: 'unavailable',
+ disabled: false,
+ countries: [],
+ expectedDisabled: true,
+ },
+])(
+ 'passes the $availability state to trigger state callbacks',
+ ({ disabled, countries, expectedDisabled }) => {
+ render(
+ <ThemeProvider colorScheme="light">
+ <CountrySelect
+ countries={countries}
+ value=""
+ onValueChange={() => undefined}
+ aria-label="Country"
+ disabled={disabled}
+ className={(state) =>
+ state.disabled ? 'trigger-disabled' : 'trigger-enabled'
+ }
+ style={(state) => ({ opacity: state.disabled ? 0.5 : 1 })}
+ render={(renderProps, state) => (
+ <button
+ {...renderProps}
+ data-state-disabled={String(state.disabled)}
+ />
+ )}
+ />
+ </ThemeProvider>,
+ );
+
+ const trigger = screen.getByRole('button', { name: 'Country' });
+
+ expect(trigger).toHaveClass(
+ expectedDisabled ? 'trigger-disabled' : 'trigger-enabled',
+ );
+ expect(trigger).toHaveStyle({ opacity: expectedDisabled ? '0.5' : '1' });
+ expect(trigger).toHaveAttribute(
+ 'data-state-disabled',
+ String(expectedDisabled),
+ );
+ },
+);
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectAvailabilityEffect.tsx b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectAvailabilityEffect.tsx
new file mode 100644
index 00000000000..c26480c0041
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectAvailabilityEffect.tsx
@@ -0,0 +1,26 @@
+import { useStableCallback } from '@base-ui/utils/useStableCallback';
+import { useEffect } from 'react';
+
+type CountrySelectAvailabilityEffectProps = {
+ disabled: boolean;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+};
+
+export const CountrySelectAvailabilityEffect = ({
+ disabled,
+ open,
+ onOpenChange,
+}: CountrySelectAvailabilityEffectProps) => {
+ const changeOpen = useStableCallback(onOpenChange);
+
+ useEffect(() => {
+ if (!disabled || !open) {
+ return;
+ }
+
+ changeOpen(false);
+ }, [disabled, open, changeOpen]);
+
+ return null;
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectOptions.tsx b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectOptions.tsx
new file mode 100644
index 00000000000..6f4f9007ef8
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectOptions.tsx
@@ -0,0 +1,83 @@
+import { isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';
+import { useState } from 'react';
+
+import { Dropdown } from '@ui/components/navigation/Dropdown/Dropdown';
+import { IconCircleOff } from '@ui/icon';
+import { normalizeSearchText } from '@ui/utilities/utils/normalizeSearchText';
+
+import styles from '../CountrySelect.module.scss';
+import { type CountryChoice } from '../types/CountryChoice';
+
+type CountrySelectOptionsProps = {
+ countries: readonly CountryChoice[];
+ value: string;
+ onValueChange: (value: string) => void;
+ searchLabel: string;
+ noCountryLabel: string;
+ noResultsLabel: string;
+};
+
+export const CountrySelectOptions = ({
+ countries,
+ value,
+ onValueChange,
+ searchLabel,
+ noCountryLabel,
+ noResultsLabel,
+}: CountrySelectOptionsProps) => {
+ const [search, setSearch] = useState('');
+ const normalizedSearch = normalizeSearchText(search.trim());
+ const isSearching = isNonEmptyString(normalizedSearch);
+ const filteredCountries = countries.filter((country) =>
+ normalizeSearchText(country.label).includes(normalizedSearch),
+ );
+ const showNoCountry =
+ normalizeSearchText(noCountryLabel).includes(normalizedSearch);
+ const hasResults = showNoCountry || isNonEmptyArray(filteredCountries);
+ const noCountryOption = showNoCountry && (
+ <Dropdown.OptionItem
+ selected={!isNonEmptyString(value)}
+ startIcon={
+ <span className={styles.flag} aria-hidden="true">
+ <IconCircleOff />
+ </span>
+ }
+ onSelect={() => onValueChange('')}
+ >
+ {noCountryLabel}
+ </Dropdown.OptionItem>
+ );
+
+ return (
+ <>
+ <Dropdown.Search
+ value={search}
+ onValueChange={setSearch}
+ placeholder={searchLabel}
+ aria-label={searchLabel}
+ />
+ {hasResults && <Dropdown.Separator />}
+ {hasResults && (
+ <Dropdown.Section scrollable>
+ {!isSearching && noCountryOption}
+ {filteredCountries.map((country) => (
+ <Dropdown.OptionItem
+ key={country.value}
+ selected={country.value === value}
+ startIcon={
+ <span className={styles.flag} aria-hidden="true">
+ {country.flag}
+ </span>
+ }
+ onSelect={() => onValueChange(country.value)}
+ >
+ {country.label}
+ </Dropdown.OptionItem>
+ ))}
+ {isSearching && noCountryOption}
+ </Dropdown.Section>
+ )}
+ {!hasResults && <Dropdown.Empty>{noResultsLabel}</Dropdown.Empty>}
+ </>
+ );
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/getCountrySelectLabelledBy.ts b/packages/twenty-ui/src/components/input/CountrySelect/internal/getCountrySelectLabelledBy.ts
new file mode 100644
index 00000000000..41ead07eabb
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/getCountrySelectLabelledBy.ts
@@ -0,0 +1,21 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+export const getCountrySelectLabelledBy = ({
+ ariaLabelledBy,
+ ariaLabel,
+ visibleLabelId,
+}: {
+ ariaLabelledBy?: string;
+ ariaLabel?: string;
+ visibleLabelId?: string;
+}) => {
+ if (isNonEmptyString(ariaLabelledBy)) {
+ return ariaLabelledBy;
+ }
+
+ if (isNonEmptyString(ariaLabel)) {
+ return undefined;
+ }
+
+ return visibleLabelId;
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/types/CountryChoice.ts b/packages/twenty-ui/src/components/input/CountrySelect/types/CountryChoice.ts
new file mode 100644
index 00000000000..da23202fd9e
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/types/CountryChoice.ts
@@ -0,0 +1,7 @@
+import { type ReactNode } from 'react';
+
+export type CountryChoice = {
+ value: string;
+ label: string;
+ flag?: ReactNode;
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectProps.ts b/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectProps.ts
new file mode 100644
index 00000000000..ea2466d16ee
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectProps.ts
@@ -0,0 +1,29 @@
+import { type DropdownContentProps } from '@ui/components/navigation/Dropdown/types/DropdownContentProps';
+import { type DropdownTriggerProps } from '@ui/components/navigation/Dropdown/types/DropdownTriggerProps';
+
+import { type CountryChoice } from './CountryChoice';
+
+export type CountrySelectProps = Omit<
+ DropdownTriggerProps,
+ | 'children'
+ | 'value'
+ | 'defaultValue'
+ | 'onChange'
+ | 'openOnHover'
+ | 'delay'
+ | 'closeDelay'
+> & {
+ countries: readonly CountryChoice[];
+ value: string;
+ onValueChange: (value: string) => void;
+ label?: string;
+ searchLabel?: string;
+ noCountryLabel?: string;
+ noResultsLabel?: string;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ popupProps?: Omit<
+ DropdownContentProps,
+ 'children' | 'aria-label' | 'aria-labelledby' | 'keepMounted'
+ >;
+};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerOptions.tsx b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerOptions.tsx
index 9b06b6c46b2..95647bd8e87 100644
--- a/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerOptions.tsx
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerOptions.tsx
@@ -3,7 +3,7 @@ import { useState } from 'react';
import { Dropdown } from '@ui/components/navigation/Dropdown/Dropdown';
import { OverflowingTextWithTooltip } from '@ui/primitives/typography/OverflowingTextWithTooltip/OverflowingTextWithTooltip';
-import { normalizeSearchText } from '@ui/utilities/internal/normalizeSearchText';
+import { normalizeSearchText } from '@ui/utilities/utils/normalizeSearchText';
import { isDefined } from '@ui/utilities/utils/isDefined';
import styles from '../PhoneCountryPicker.module.scss';
diff --git a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownTrigger.tsx b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownTrigger.tsx
index 580725d49e6..4aec5586fa0 100644
--- a/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownTrigger.tsx
+++ b/packages/twenty-ui/src/components/navigation/Dropdown/internal/DropdownTrigger.tsx
@@ -36,7 +36,12 @@ export const DropdownTrigger = ({
onKeyDown={(event) => {
onKeyDown?.(event);
- if (event.defaultPrevented || props.disabled || type === 'panel') {
+ if (
+ event.defaultPrevented ||
+ event.baseUIHandlerPrevented ||
+ props.disabled ||
+ type === 'panel'
+ ) {
return;
}
diff --git a/packages/twenty-ui/src/utilities/index.ts b/packages/twenty-ui/src/utilities/index.ts
index b2fb083df25..08c9a96ee2a 100644
--- a/packages/twenty-ui/src/utilities/index.ts
+++ b/packages/twenty-ui/src/utilities/index.ts
@@ -24,3 +24,4 @@ export { useMediaQuery } from './responsive/hooks/useMediaQuery';
export type { Nullable } from './types/Nullable';
export { getSafeUrl } from './utils/getSafeUrl';
export { isDefined } from './utils/isDefined';
+export { normalizeSearchText } from './utils/normalizeSearchText';
diff --git a/packages/twenty-ui/src/utilities/internal/__tests__/normalizeSearchText.test.ts b/packages/twenty-ui/src/utilities/internal/__tests__/normalizeSearchText.test.ts
deleted file mode 100644
index d0d84aefe4b..00000000000
--- a/packages/twenty-ui/src/utilities/internal/__tests__/normalizeSearchText.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { normalizeSearchText } from '../normalizeSearchText';
-
-describe('normalizeSearchText', () => {
- it('lowercases without depending on the default locale', () => {
- expect(normalizeSearchText('United Kingdom')).toBe('united kingdom');
- expect(normalizeSearchText('India')).toBe('india');
- expect(normalizeSearchText('İtalya')).toBe('italya');
- });
-
- it('removes accents', () => {
- expect(normalizeSearchText("Côte d'Ivoire")).toBe("cote d'ivoire");
- expect(normalizeSearchText('Curaçao')).toBe('curacao');
- expect(normalizeSearchText('RÉUNION')).toBe('reunion');
- expect(normalizeSearchText('Türkiye')).toBe('turkiye');
- expect(normalizeSearchText('Åland Islands')).toBe('aland islands');
- });
-
- it('replaces letters that have no accent decomposition', () => {
- expect(normalizeSearchText('Øresund')).toBe('oresund');
- expect(normalizeSearchText('Æther')).toBe('aether');
- expect(normalizeSearchText('Straße')).toBe('strasse');
- expect(normalizeSearchText('Ðakovo')).toBe('dakovo');
- expect(normalizeSearchText('Þingvellir')).toBe('thingvellir');
- expect(normalizeSearchText('Łódź')).toBe('lodz');
- expect(normalizeSearchText('Œuvre')).toBe('oeuvre');
- });
-
- it('keeps whitespace, digits, and punctuation', () => {
- expect(normalizeSearchText(' France ')).toBe(' france ');
- expect(normalizeSearchText('+44')).toBe('+44');
- });
-});
diff --git a/packages/twenty-ui/src/utilities/internal/normalizeSearchText.ts b/packages/twenty-ui/src/utilities/internal/normalizeSearchText.ts
deleted file mode 100644
index 771ac4d9cf2..00000000000
--- a/packages/twenty-ui/src/utilities/internal/normalizeSearchText.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-export const normalizeSearchText = (text: string) =>
- text
- .normalize('NFD')
- .replace(/\p{Diacritic}/gu, '')
- .replace(/[øØ]/g, 'o')
- .replace(/[åÅ]/g, 'a')
- .replace(/[æÆ]/g, 'ae')
- .replace(/[ßẞ]/g, 'ss')
- .replace(/[ðÐ]/g, 'd')
- .replace(/[þÞ]/g, 'th')
- .replace(/[łŁ]/g, 'l')
- .replace(/[œŒ]/g, 'oe')
- .toLowerCase();
diff --git a/packages/twenty-ui/src/utilities/utils/__tests__/normalizeSearchText.test.ts b/packages/twenty-ui/src/utilities/utils/__tests__/normalizeSearchText.test.ts
new file mode 100644
index 00000000000..b8cc0da3316
--- /dev/null
+++ b/packages/twenty-ui/src/utilities/utils/__tests__/normalizeSearchText.test.ts
@@ -0,0 +1,252 @@
+import { normalizeSearchText } from '../normalizeSearchText';
+
+describe('normalizeSearchText', () => {
+ it.each([
+ { text: 'Hello World', expected: 'hello world' },
+ { text: 'MixedCase123', expected: 'mixedcase123' },
+ { text: 'İtalya', expected: 'italya' },
+ ])('folds case in $text', ({ text, expected }) => {
+ expect(normalizeSearchText(text)).toBe(expected);
+ });
+
+ it.each([
+ { text: 'café', expected: 'cafe' },
+ { text: 'naïve', expected: 'naive' },
+ { text: 'résumé', expected: 'resume' },
+ { text: 'Zürich', expected: 'zurich' },
+ { text: 'Müller', expected: 'muller' },
+ { text: 'niño', expected: 'nino' },
+ { text: 'España', expected: 'espana' },
+ { text: 'São Paulo', expected: 'sao paulo' },
+ { text: 'João', expected: 'joao' },
+ { text: 'CAFÉ', expected: 'cafe' },
+ { text: 'NaÏvE', expected: 'naive' },
+ { text: 'ZÜRICH', expected: 'zurich' },
+ { text: 'Côte d’Ivoire', expected: 'cote d’ivoire' },
+ { text: "Côte d'Ivoire", expected: "cote d'ivoire" },
+ { text: 'Curaçao', expected: 'curacao' },
+ { text: 'RÉUNION', expected: 'reunion' },
+ { text: 'Türkiye', expected: 'turkiye' },
+ { text: 'Việt Nam', expected: 'viet nam' },
+ { text: 'Åland å', expected: 'aland a' },
+ { text: 'e\u0301', expected: 'e' },
+ { text: 'A\u0300\u0301', expected: 'a' },
+ ])('folds Latin accents in $text', ({ text, expected }) => {
+ expect(normalizeSearchText(text)).toBe(expected);
+ });
+
+ it.each([
+ { text: 'Straße', expected: 'strasse' },
+ { text: 'Œuvre', expected: 'oeuvre' },
+ { text: 'Æther', expected: 'aether' },
+ { text: 'Łódź', expected: 'lodz' },
+ { text: 'Øyvind', expected: 'oyvind' },
+ { text: 'Đan Mạch', expected: 'dan mach' },
+ { text: 'Ðakovo', expected: 'dakovo' },
+ { text: 'Þingvellir', expected: 'thingvellir' },
+ { text: 'Kıbrıs', expected: 'kibris' },
+ { text: 'Ŋaŋ', expected: 'ngang' },
+ { text: 'ÆØÐÞŁŒẞ', expected: 'aeodthloess' },
+ ])('folds special Latin letters in $text', ({ text, expected }) => {
+ expect(normalizeSearchText(text)).toBe(expected);
+ });
+
+ it.each(['Café', 'CAFE', 'cafe', 'Cafe'])(
+ 'matches a cafe search in %s',
+ (text) => {
+ expect(normalizeSearchText(text)).toContain(normalizeSearchText('cafe'));
+ },
+ );
+
+ it('folds Greek accents', () => {
+ expect(normalizeSearchText('Ελλάδα')).toBe('ελλαδα');
+ });
+
+ it.each(['ρυθμισεις', 'ΡΥΘΜΙΣΕΙΣ'])(
+ 'matches the Greek search %s regardless of accents and final sigma',
+ (search) => {
+ expect(normalizeSearchText('Μετάβαση στις Ρυθμίσεις')).toContain(
+ normalizeSearchText(search),
+ );
+ },
+ );
+
+ it.each(['\u0385', '\u1FED', '\u1FEE', '\u1FC1'])(
+ 'removes the Greek spacing accent %s without moving its mark onto the previous letter',
+ (greekSpacingAccent) => {
+ expect(normalizeSearchText(`α${greekSpacingAccent}β`)).toBe('αβ');
+ },
+ );
+
+ it('matches an uppercase Greek search ending with a sigma inside a word', () => {
+ expect(normalizeSearchText('Ινδονησία')).toContain(
+ normalizeSearchText('ΙΝΔΟΝΗΣ'),
+ );
+ });
+
+ it('normalizes uppercase and lowercase Greek to the same text', () => {
+ expect(normalizeSearchText('ΠΡΩΤΕΪ\u0301ΝΗ')).toBe(
+ normalizeSearchText('πρωτεΐνη'),
+ );
+ });
+
+ it('matches Arabic text written without harakat', () => {
+ expect(normalizeSearchText('نهائيًا')).toContain(
+ normalizeSearchText('نهائيا'),
+ );
+ });
+
+ it.each([
+ { text: 'أ', expected: 'ا' },
+ { text: 'إ', expected: 'ا' },
+ { text: 'آ', expected: 'ا' },
+ { text: 'أحمد', expected: 'احمد' },
+ ])('folds the Arabic hamza form in $text', ({ text, expected }) => {
+ expect(normalizeSearchText(text)).toBe(expected);
+ });
+
+ it('removes harakat drawn on a tatweel', () => {
+ expect(normalizeSearchText('نـَـا')).toBe('نــا');
+ });
+
+ it('removes Hebrew niqqud', () => {
+ expect(normalizeSearchText('שָׁלוֹם')).toBe('שלום');
+ });
+
+ it.each(['Королёв', 'КОРОЛЁВ'])('folds Cyrillic ё to е in %s', (text) => {
+ expect(normalizeSearchText(text)).toContain(normalizeSearchText('королев'));
+ });
+
+ it('preserves the Ukrainian ї', () => {
+ expect(normalizeSearchText('Україна')).toBe('україна');
+ });
+
+ it('keeps Cyrillic й distinct from и', () => {
+ expect(normalizeSearchText('Нью-Йорк')).toBe('нью-йорк');
+ expect(normalizeSearchText('и\u0306')).toBe('й');
+ expect(normalizeSearchText('й')).not.toBe(normalizeSearchText('и'));
+ });
+
+ it.each([
+ { text: 'за\u0301мок', expected: 'замок' },
+ { text: 'ЗА\u0300МОК', expected: 'замок' },
+ { text: 'ѐ', expected: 'е' },
+ { text: 'Ѐ', expected: 'е' },
+ { text: 'ѝ', expected: 'и' },
+ { text: 'Украї\u0301на', expected: 'україна' },
+ ])('removes the Cyrillic stress accent in $text', ({ text, expected }) => {
+ expect(normalizeSearchText(text)).toBe(expected);
+ });
+
+ it.each([
+ { text: 'ў', expected: 'ў' },
+ { text: 'у\u0306', expected: 'ў' },
+ { text: 'і\u0308', expected: 'ї' },
+ { text: 'ѓ', expected: 'ѓ' },
+ { text: 'г\u0301', expected: 'ѓ' },
+ { text: 'ќ', expected: 'ќ' },
+ ])(
+ 'keeps the letter-forming Cyrillic mark in $text',
+ ({ text, expected }) => {
+ expect(normalizeSearchText(text)).toBe(expected);
+ },
+ );
+
+ it.each(['ガボン', 'カ\u3099ホ\u3099ン'])(
+ 'preserves Japanese voiced consonants in %s',
+ (text) => {
+ const normalizedText = normalizeSearchText(text);
+
+ expect(normalizedText).toBe('ガボン');
+ expect(normalizedText).not.toContain(normalizeSearchText('カ'));
+ expect(normalizedText).toContain(normalizeSearchText('カ\u3099'));
+ },
+ );
+
+ it('preserves Devanagari signs', () => {
+ expect(normalizeSearchText('भारत')).toBe('भारत');
+ });
+
+ it.each([
+ { text: '한국', search: '하' },
+ { text: '한국', search: '한' },
+ { text: '설정', search: '서' },
+ { text: '설정', search: '설저' },
+ { text: '한국', search: 'ㅎ' },
+ { text: '한국', search: '한ㄱ' },
+ { text: '설정', search: '설ㅈ' },
+ ])('matches the partly typed Hangul $search in $text', ({ text, search }) => {
+ expect(normalizeSearchText(text)).toContain(normalizeSearchText(search));
+ });
+
+ it.each([
+ { text: 'Cancel·la', search: 'cancella' },
+ { text: 'oʻchirish', search: 'ochirish' },
+ ])('matches $search in $text', ({ text, search }) => {
+ expect(normalizeSearchText(text)).toContain(normalizeSearchText(search));
+ });
+
+ it.each([
+ '·',
+ 'ʻ',
+ 'ʼ',
+ '´',
+ '¨',
+ 'ˆ',
+ '˜',
+ '΄',
+ 'ˇ',
+ '˘',
+ '˙',
+ '˚',
+ '˛',
+ '˝',
+ '¯',
+ '¸',
+ '^',
+ '`',
+ ])('removes the spacing diacritic %s', (spacingDiacritic) => {
+ expect(normalizeSearchText(`a${spacingDiacritic}b`)).toBe('ab');
+ });
+
+ it.each([
+ { text: 'Crêpe', search: 'crˆ' },
+ { text: 'España', search: 'espa˜' },
+ { text: 'Ελλάδα', search: 'ελλ΄' },
+ { text: 'Crêpe', search: 'cr^' },
+ { text: 'Crème', search: 'cr`' },
+ { text: 'Dvořák', search: 'dvoˇ' },
+ ])(
+ 'matches $search typed with a pending dead key in $text',
+ ({ text, search }) => {
+ expect(normalizeSearchText(text)).toContain(normalizeSearchText(search));
+ },
+ );
+
+ it('preserves tildes', () => {
+ expect(normalizeSearchText('a~b')).toBe('a~b');
+ });
+
+ it('keeps long combining mark runs in linear time', () => {
+ const combiningAcute = String.fromCodePoint(0x0301);
+ const longMarkRun = combiningAcute.repeat(20000);
+
+ expect(normalizeSearchText(`ж${longMarkRun}`)).toBe('ж');
+ expect(normalizeSearchText(`1${longMarkRun}`)).toBe(`1${longMarkRun}`);
+ });
+
+ it.each([
+ { text: ' Country #123 ', expected: ' country #123 ' },
+ { text: ' ', expected: ' ' },
+ { text: '[email protected]', expected: '[email protected]' },
+ { text: '123-456-7890', expected: '123-456-7890' },
+ { text: '+44', expected: '+44' },
+ { text: 'Café #1', expected: 'cafe #1' },
+ ])('preserves whitespace and punctuation in $text', ({ text, expected }) => {
+ expect(normalizeSearchText(text)).toBe(expected);
+ });
+
+ it.each([null, undefined, ''])('accepts missing text %s', (text) => {
+ expect(normalizeSearchText(text)).toBe('');
+ });
+});
diff --git a/packages/twenty-ui/src/utilities/utils/normalizeSearchText.ts b/packages/twenty-ui/src/utilities/utils/normalizeSearchText.ts
new file mode 100644
index 00000000000..1c00bf15734
--- /dev/null
+++ b/packages/twenty-ui/src/utilities/utils/normalizeSearchText.ts
@@ -0,0 +1,59 @@
+import { isDefined } from './isDefined';
+
+const SPACING_DIACRITICS = /[·ʻʼ´¨ˆ˜΄ˇ˘˙˚˛˝¯¸^`]/g;
+const MARKS_AFTER_LATIN_GREEK_ARABIC_OR_HEBREW_LETTER =
+ /([\p{Script=Latin}\p{Script=Greek}\p{Script_Extensions=Arabic}\p{Script=Hebrew}])\p{Mark}+/gu;
+const CYRILLIC_LETTER_WITH_MARKS = /(\p{Script=Cyrillic})(\p{Mark}+)/gu;
+const CYRILLIC_STRESS_ACCENTS = /[\u0300\u0301]/g;
+const CYRILLIC_LETTERS_FORMED_WITH_ACUTE = ['г', 'к'];
+const HANGUL_SYLLABLES = /[가-힣]+/g;
+const HANGUL_COMPATIBILITY_JAMO = /[ㄱ-ㆎ]/g;
+const SEARCH_LETTER_REPLACEMENTS: Record<string, string> = {
+ ø: 'o',
+ æ: 'ae',
+ ß: 'ss',
+ ð: 'd',
+ þ: 'th',
+ ł: 'l',
+ œ: 'oe',
+ đ: 'd',
+ ı: 'i',
+ ŋ: 'ng',
+ ς: 'σ',
+ ё: 'е',
+};
+const LETTERS_WITH_SEARCH_REPLACEMENT = new RegExp(
+ `[${Object.keys(SEARCH_LETTER_REPLACEMENTS).join('')}]`,
+ 'g',
+);
+
+const removeCyrillicStressAccents = (
+ _match: string,
+ letter: string,
+ marks: string,
+) =>
+ CYRILLIC_LETTERS_FORMED_WITH_ACUTE.includes(letter)
+ ? `${letter}${marks}`
+ : `${letter}${marks.replace(CYRILLIC_STRESS_ACCENTS, '')}`;
+
+export const normalizeSearchText = (
+ text: string | null | undefined,
+): string => {
+ if (!isDefined(text)) {
+ return '';
+ }
+
+ return text
+ .toLowerCase()
+ .normalize('NFD')
+ .replace(SPACING_DIACRITICS, '')
+ .replace(MARKS_AFTER_LATIN_GREEK_ARABIC_OR_HEBREW_LETTER, '$1')
+ .replace(CYRILLIC_LETTER_WITH_MARKS, removeCyrillicStressAccents)
+ .normalize('NFC')
+ .replace(HANGUL_SYLLABLES, (syllables) => syllables.normalize('NFD'))
+ .replace(HANGUL_COMPATIBILITY_JAMO, (jamo) => jamo.normalize('NFKD'))
+ .replace(
+ LETTERS_WITH_SEARCH_REPLACEMENT,
+ (letter) => SEARCH_LETTER_REPLACEMENTS[letter] ?? letter,
+ );
+};