Skip to content

The open alternative to Salesforce, designed for AI.

Unify CountrySelect shorthand and parts (#28160)

Raphaël Bosibc3f19466176
diff --git a/packages/twenty-docs/snippets/ui/generated/components/input/country-select.mdx b/packages/twenty-docs/snippets/ui/generated/components/input/country-select.mdx
index 9e10af90822..1711e1c22e2 100644
--- a/packages/twenty-docs/snippets/ui/generated/components/input/country-select.mdx
+++ b/packages/twenty-docs/snippets/ui/generated/components/input/country-select.mdx
@@ -11,15 +11,48 @@
* npx nx generate:ui twenty-docs
*/}
+<ParamField body="children" type="ReactNode">
+ Custom trigger content. Replaces the selected country presentation while retaining shared trigger behavior.
+</ParamField>
+
<ParamField body="className" type="string | ((state: PopoverTriggerState) =&gt; string | undefined)">
Class applied to the trigger.
</ParamField>
+<ParamField body="closeDelay" type="number" default="0">
+ How long to wait before closing the popover that was opened on hover.
+ Specified in milliseconds.
+
+ Requires the `openOnHover` prop.
+</ParamField>
+
+<ParamField body="closeOnSelect" type="boolean">
+ Closes the popup after a selection. Defaults to true. Cancelled selection keeps it open.
+</ParamField>
+
<ParamField body="countries" type="readonly CountryChoice[]" required>
- Prepared country choices with unique non-empty values, display labels, and optional decorative flags.
+ Prepared country choices with unique stable string values, caller-owned labels, and optional decorative flags and disabled states. An empty string is a valid choice value.
+</ParamField>
+
+<ParamField body="defaultOpen" type="boolean">
+ Whether the uncontrolled popup is initially open.
+</ParamField>
+
+<ParamField body="defaultPage" type="string">
+ Dropdown page shown when the popup opens. Defaults to root.
+</ParamField>
+
+<ParamField body="defaultValue" type="string | null">
+ Initial uncontrolled selected identifier. Defaults to null.
+</ParamField>
+
+<ParamField body="delay" type="number" default="300">
+ How long to wait before the popover may be opened on hover. Specified in milliseconds.
+
+ Requires the `openOnHover` prop.
</ParamField>
-<ParamField body="disabled" type="boolean" default="false">
+<ParamField body="disabled" type="boolean">
Prevents opening and selection while the trigger stays focusable. An empty country list is also disabled.
</ParamField>
@@ -28,7 +61,7 @@
</ParamField>
<ParamField body="label" type="string">
- Optional visible label that names the trigger and the popup.
+ Optional visible label that names the trigger.
</ParamField>
<ParamField body="nativeButton" type="boolean" default="true">
@@ -37,28 +70,44 @@
Set to `false` if the rendered element is not a button (e.g. `<div>`).
</ParamField>
-<ParamField body="noCountryLabel" type="string" default="No country">
+<ParamField body="noCountryLabel" type="string">
Text of the no-country choice, also displayed when no country is selected.
</ParamField>
-<ParamField body="noResultsLabel" type="string" default="No results">
+<ParamField body="noResultsLabel" type="string">
Text displayed when no choice matches the search.
</ParamField>
+<ParamField body="onEscapeKeyDown" type="((event: DropdownDismissEvent) =&gt; void)">
+ Called before Escape dismisses the popup. Call event.preventDefault() to keep it open.
+</ParamField>
+
+<ParamField body="onInteractOutside" type="((event: DropdownDismissEvent) =&gt; void)">
+ Called before outside interaction or Tab dismisses the popup. Call event.preventDefault() to keep it open.
+</ParamField>
+
<ParamField body="onOpenChange" type="((open: boolean) =&gt; void)">
- Reports popup opening and closing.
+ Reports popup opening and closing with the next boolean state, matching Dropdown.Root.
</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 body="onValueChange" type="((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) =&gt; void)">
+ Reports the selected identifier or null with cancellable event details. Call details.cancel() to preserve selection and keep the popup open.
</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 body="openOnHover" type="boolean" default="false">
+ Whether the popover should also open when the trigger is hovered.
+</ParamField>
+
+<ParamField body="optionsProps" type="Omit&lt;CountrySelectOptionsProps, &quot;closeOnSelect&quot; | &quot;searchLabel&quot; | &quot;noResultsLabel&quot; | &quot;searchProps&quot;&gt;">
+ Native props, ref, and render for the selection group div rendered by CountrySelect.Options.
+</ParamField>
+
+<ParamField body="popupProps" type="Omit&lt;DropdownContentProps, &quot;children&quot;&gt;">
+ Dropdown.Content props, including native popup attributes, ref, render, positioning, portal destination, and keepMounted. Explicit popup accessible names override the trigger name. Children are owned by the picker.
</ParamField>
<ParamField body="ref" type="Ref&lt;HTMLButtonElement&gt;">
@@ -69,15 +118,150 @@
Replaces the trigger element while preserving its behavior and props.
</ParamField>
-<ParamField body="searchLabel" type="string" default="Search">
+<ParamField body="searchLabel" type="string">
Placeholder and accessible name of the search input.
</ParamField>
+<ParamField body="searchProps" type="Omit&lt;DropdownSearchProps, &quot;defaultValue&quot; | &quot;value&quot; | &quot;onValueChange&quot;&gt;">
+ Native search input props, ref, and render. Search value and change handling are owned by the picker.
+</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 body="value" type="string | null">
+ Controlled selected identifier. Null selects no country; undefined leaves selection uncontrolled.
+</ParamField>
+
+<ParamField body="wrapperProps" type="Omit&lt;DetailedHTMLProps&lt;HTMLAttributes&lt;HTMLDivElement&gt;, HTMLDivElement&gt;, &quot;children&quot;&gt;">
+ Native props and ref for the div around the trigger and its visible label. Children are owned by the picker.
+</ParamField>
+
+### CountrySelect.Root
+
+<ParamField body="Root.children" type="ReactNode" required>
+ Picker composition containing Dropdown.Root, CountrySelect.Trigger, and CountrySelect.Options. Root adds no DOM element.
+</ParamField>
+
+<ParamField body="Root.countries" type="readonly CountryChoice[]" required>
+ Prepared country choices with unique stable string values, caller-owned labels, and optional decorative flags and disabled states. An empty string is a valid choice value.
+</ParamField>
+
+<ParamField body="Root.defaultValue" type="string | null" default="null">
+ Initial uncontrolled selected identifier. Defaults to null.
+</ParamField>
+
+<ParamField body="Root.disabled" type="boolean" default="false">
+ Prevents opening and selection. An empty country list is also disabled. The trigger stays focusable with aria-disabled.
+</ParamField>
+
+<ParamField body="Root.noCountryLabel" type="string" default="No country">
+ Text for the null selection and its option. Defaults to No country.
+</ParamField>
+
+<ParamField body="Root.onValueChange" type="((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) =&gt; void)">
+ Reports the selected identifier or null with event, reason, trigger, cancel and isCanceled details. Call cancel() to preserve selection and keep the popup open.
+</ParamField>
+
+<ParamField body="Root.value" type="string | null">
+ Controlled selected identifier. Null selects no country; undefined leaves selection uncontrolled.
+</ParamField>
+
+### CountrySelect.Trigger
+
+<ParamField body="Trigger.children" type="ReactNode">
+ Custom trigger content. Replaces the selected country presentation while retaining shared trigger behavior.
+</ParamField>
+
+<ParamField body="Trigger.className" type="string | ((state: PopoverTriggerState) =&gt; string | undefined)">
+ Class applied to the trigger button.
+</ParamField>
+
+<ParamField body="Trigger.closeDelay" type="number" default="0">
+ How long to wait before closing the popover that was opened on hover.
+ Specified in milliseconds.
+
+ Requires the `openOnHover` prop.
+</ParamField>
+
+<ParamField body="Trigger.delay" type="number" default="300">
+ How long to wait before the popover may be opened on hover. Specified in milliseconds.
+
+ Requires the `openOnHover` prop.
+</ParamField>
+
+<ParamField body="Trigger.id" type="string">
+ ID of the trigger. In addition to being forwarded to the rendered element,
+ it is also used to specify the active trigger for the popover in controlled mode (with the PopoverRoot `triggerId` prop).
+</ParamField>
+
+<ParamField body="Trigger.label" type="string">
+ Optional visible label that names the trigger.
+</ParamField>
+
+<ParamField body="Trigger.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="Trigger.openOnHover" type="boolean" default="false">
+ Whether the popover should also open when the trigger is hovered.
+</ParamField>
+
+<ParamField body="Trigger.ref" type="Ref&lt;HTMLButtonElement&gt;">
+ Ref to the trigger element.
+</ParamField>
+
+<ParamField body="Trigger.render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, PopoverTriggerState&gt;">
+ Replaces the trigger element. Custom components must forward the supplied props and ref.
+</ParamField>
+
+<ParamField body="Trigger.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="Trigger.wrapperProps" type="Omit&lt;DetailedHTMLProps&lt;HTMLAttributes&lt;HTMLDivElement&gt;, HTMLDivElement&gt;, &quot;children&quot;&gt;">
+ Native props and ref for the div around the trigger and its visible label. Children are owned by the picker.
+</ParamField>
+
+### CountrySelect.Options
+
+<ParamField body="Options.aria-label" type="string">
+ Accessible name for the selection listbox. Overrides its default name.
+</ParamField>
+
+<ParamField body="Options.aria-labelledby" type="string">
+ Accessible name references for the selection listbox. Defaults to the registered Dropdown title or trigger element.
+</ParamField>
+
+<ParamField body="Options.className" type="string">
+ Class applied to the selection group div.
+</ParamField>
+
+<ParamField body="Options.closeOnSelect" type="boolean">
+ Closes the popup after a selection. Defaults to true. Cancelled selection keeps it open.
+</ParamField>
+
+<ParamField body="Options.noResultsLabel" type="string">
+ Text displayed when no choice matches the search. Defaults to No results.
+</ParamField>
+
+<ParamField body="Options.ref" type="Ref&lt;HTMLDivElement&gt;">
+ Ref to the selection group element.
+</ParamField>
+
+<ParamField body="Options.render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, CountrySelectOptionsState&gt;">
+ Replaces the selection group div. Functions receive supplied props and &#123; value, multiple: false &#125; state, with the public string or null selection. Custom components must forward the supplied props and ref.
+</ParamField>
+
+<ParamField body="Options.searchLabel" type="string">
+ Search placeholder and accessible name. Defaults to Search.
+</ParamField>
+
+<ParamField body="Options.searchProps" type="Omit&lt;DropdownSearchProps, &quot;defaultValue&quot; | &quot;value&quot; | &quot;onValueChange&quot;&gt;">
+ Native search input props, ref, and render. Search value and change handling are owned by the picker.
</ParamField>
diff --git a/packages/twenty-docs/ui/components/input/country-select.mdx b/packages/twenty-docs/ui/components/input/country-select.mdx
index 2e21a2cd106..22bb6182c87 100644
--- a/packages/twenty-docs/ui/components/input/country-select.mdx
+++ b/packages/twenty-docs/ui/components/input/country-select.mdx
@@ -1,12 +1,12 @@
---
title: CountrySelect
-description: Search prepared country choices and select a country or an explicit empty value.
+description: A complete country picker and shared parts for prepared choices, stable identifiers, and null clearing.
---
import { StoryEmbed } from '/snippets/ui/StoryEmbed.mdx';
import CountrySelectReference from '/snippets/ui/generated/components/input/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.
+`CountrySelect` provides a complete country picker with a labeled trigger, decorative flags, search, and a no-country choice. `CountrySelect.Root`, `CountrySelect.Trigger`, and `CountrySelect.Options` expose the same implementation for composition with [Dropdown](/ui/components/navigation/dropdown). Your application supplies country data and translated text and decides how selected identifiers map to stored values.
<StoryEmbed
storyId="ui-input-countryselect--display"
@@ -16,62 +16,129 @@ import CountrySelectReference from '/snippets/ui/generated/components/input/coun
## Usage
-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.
+Supply prepared choices with unique stable string identifiers and display labels. The picker reports identifiers unchanged, independently of the displayed language. Flags are optional decorative React nodes. A choice can set `disabled: true` to remain visible without allowing selection.
```tsx
-import { useState } from 'react';
import { CountrySelect } from 'twenty-ui/components/input';
-export const ShippingCountry = () => {
- const [country, setCountry] = useState('France');
+const COUNTRIES = [
+ { value: 'FR', label: 'France', flag: '🇫🇷' },
+ { value: 'DE', label: 'Germany', flag: '🇩🇪' },
+ { value: 'JP', label: 'Japan', flag: '🇯🇵' },
+];
+
+export const ShippingCountry = () => (
+ <CountrySelect
+ label="Shipping country"
+ countries={COUNTRIES}
+ defaultValue="FR"
+ searchLabel="Search countries"
+ noCountryLabel="No country"
+ noResultsLabel="No countries found"
+ />
+);
+```
+
+`defaultValue` initializes uncontrolled selection. Use `value` and `onValueChange` for controlled selection. Updating `value` externally updates both the trigger and the selected option, including while the popup is open.
+
+```tsx
+import { useState } from 'react';
+import { CountrySelect, type CountryChoice } from 'twenty-ui/components/input';
+
+export const ControlledCountry = ({
+ countries,
+}: {
+ countries: readonly CountryChoice[];
+}) => {
+ const [country, setCountry] = useState<string | null>('FR');
return (
<CountrySelect
- label="Shipping country"
- countries={[
- { value: 'France', label: 'France', flag: '🇫🇷' },
- { value: 'Germany', label: 'Germany', flag: '🇩🇪' },
- { value: 'Japan', label: 'Japan', flag: '🇯🇵' },
- ]}
+ label="Country"
+ countries={countries}
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.
+## Shared parts
+
+`Root` owns the prepared choices and selected identifier. It adds no DOM element. `Trigger` reads that selection and displays its label and flag. `Options` reads the same data and renders searchable rows inside `Dropdown.SelectionGroup`. Dropdown owns opening, popup placement, pages, navigation, and focus.
+
+```tsx
+import { CountrySelect, type CountryChoice } from 'twenty-ui/components/input';
+import { Dropdown } from 'twenty-ui/components/navigation';
+
+export const ShippingCountryParts = ({
+ countries,
+}: {
+ countries: readonly CountryChoice[];
+}) => (
+ <CountrySelect.Root countries={countries} defaultValue="FR">
+ <Dropdown.Root type="picker">
+ <CountrySelect.Trigger label="Shipping country" />
+ <Dropdown.Content>
+ <CountrySelect.Options
+ aria-label="Shipping country"
+ searchLabel="Search countries"
+ />
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </CountrySelect.Root>
+);
+```
+
+The shorthand assembles these parts internally. Both forms share selection, clearing, disabled behavior, search matching, and selected-option presentation. `closeOnSelect` defaults to `true`. Set it to `false` on the shorthand or `Options` when selection should keep the popup open.
+
+## Clearing and cancellation
-## Empty and unknown values
+`null` represents no country. Selecting the no-country row reports `null`; passing `value={null}` clears a controlled picker. An empty string (`''`) is a valid supplied choice identifier and stays distinct from `null`.
-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.
+`onValueChange` receives the next identifier or `null` and Dropdown selection event details: `event`, `reason`, `trigger`, `cancel`, and `isCanceled`. Call `details.cancel()` before updating controlled state to preserve the current selection and keep the popup open. Repeated selection of the current identifier does not emit another value change.
-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.
+An identifier absent from `countries` displays `noCountryLabel` and the no-country icon. Rendering it does not emit a change or overwrite the host value. The application decides how to handle stored values 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.
+Search matches 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. A query with no matching options displays `noResultsLabel`.
+
+Arrow keys, Home, and End move focus without changing the selected identifier. Enter or Space on an enabled option commits selection through its selection group. Escape and outside interaction use Dropdown dismissal and focus handling. Each picker has independent selection and popup state.
+
+Dropdown search activation and IME protection still need integration work, as do lazy page sessions and inactive-page behavior. Both picker forms reset their own search on reopen, including popups kept mounted. Their shared implementation does not yet complete Dropdown's page and browsing lifecycle.
+
+`disabled` on `Root` or the shorthand prevents opening and selection. A picker with no supplied countries is disabled as well. If either condition occurs while its popup is open, the picker requests closure. Closing returns focus to the trigger. Controlled hosts must accept that close request through `onOpenChange`; the shorthand also suppresses the popup while disabled. After accepting the close request, enabling the picker again does not reopen it automatically. The trigger stays focusable and exposes `aria-disabled`. Disabled triggers skip consumer activation handlers. Function forms of `className`, `style`, and `render` receive `disabled: true` in the trigger state.
+
+## Labels and customization
-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. Referenced labels take precedence over a nonempty `aria-label`, which takes precedence over the visible label. With one of these names, the selected country describes the trigger. Otherwise the selected country names it. The popup inherits the trigger name unless caller-owned popup labels or a Dropdown title name it. The shorthand also names its options listbox from those trigger labels unless `optionsProps` supplies its own accessible name. In composed usage, give `Options` an `aria-label` or `aria-labelledby` for an explicit listbox name. Otherwise it references the registered Dropdown title or trigger content. A tooltip reveals the full selected label when it is truncated.
-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. Custom `Trigger` children replace the selected country display; the caller owns that content and its accessible presentation.
-`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.
+Native trigger attributes, event handlers, `className`, `style`, `ref`, and `render` target the trigger button. `wrapperProps` targets the surrounding div that also contains the visible label. `Options` native props, `ref`, and `render` target its selection group div. Its `render` function receives `{ value, multiple: false }`, where `value` is the public country identifier or `null`, rather than an internal option identifier. `searchProps` targets the search input; search value and change handling remain owned by the picker. The shorthand accepts the same search props directly and group attributes through `optionsProps`. Forward supplied props and refs when replacing an element through `render`.
-`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 and storage
-## Host integration
+The shorthand accepts Dropdown's `open`, `defaultOpen`, `onOpenChange`, `onEscapeKeyDown`, `onInteractOutside`, and `defaultPage`. Composed usage sets them on `Dropdown.Root`. `onOpenChange` currently reports only a boolean, matching Dropdown's public contract. Opening event details and general opening cancellation remain unavailable upstream. Escape and outside dismissal callbacks can call `event.preventDefault()` to keep the popup open.
-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`.
+`popupProps` accepts all `Dropdown.Content` props except `children`, including popup native attributes, `ref`, `render`, positioning, portal destination, accessible names, and `keepMounted`. In composed usage, pass them directly to `Dropdown.Content`.
-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.
+Keep dropdown IDs, focus stacks, field metadata, persistence, and editing lifecycle in the host adapter. Twenty's frontend adapter uses stable country codes for picker identifiers and converts explicit selections back to existing source country-name values. Its stored empty string maps to picker `null`; unmatched legacy values stay stored until an explicit selection changes them. Translated display labels do not become stored country names. Applications with another storage format should make the conversion in their adapter as well.
+
+Native form submission, reset, `required`, `readOnly`, and Field integration for this custom picker remain deferred.
## Front component renderer
-The React and Preact front component sandboxes render the selected country, decorative flag, and disabled trigger. In both sandboxes the trigger opens the popup, but the popup renders into the sandbox document instead of the page, so its content is not visible. Search, selection, popup focus, and closing from the popup are therefore unavailable in those sandboxes for now. Renderer fixtures check the initial presentation and the disabled trigger, then assert that the trigger opens the popup in both runtimes. The UI Storybook exercises these interactions in a regular browser.
+React and Preact front component fixtures verify pointer opening, filtering, and selection through the shorthand and compound APIs, including controlled and uncontrolled values, null clearing and reselection, canceled changes, external controlled updates, disabled interaction, translated labels, and decorative flags. They also verify native trigger and search input props and refs, plus trigger and option-group render targets and refs. Search keyboard activation and IME handling, page-session lifetime, and full renderer portal, geometry, scrolling, outside dismissal, and focus restoration acceptance remain open.
+
+## Migration
+
+Replace the previous empty-string no-country sentinel with `null` in controlled values and selection state. An empty string (`''`) is now a valid choice identifier, so `value=""` no longer means no country. Keep each `CountryChoice.value` stable; existing string identifiers can remain unchanged and display labels can be translated independently.
+
+Update `onValueChange` handlers to accept `string | null`. The callback now also receives `eventDetails` as its second argument, including `cancel()` to reject a selection. Handlers that do not need event details can continue using only the first argument.
+
+If your storage uses `''` for no country, convert it to `null` before passing it to the picker and convert reported `null` back to `''` when persisting. Keep that compatibility conversion in the application adapter, and omit it when `''` is an intentional choice identifier.
## Props
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 2c45fb6d7a5..3c1aa28ef6e 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
@@ -260,7 +260,8 @@ expected-to-fail by the runner.
| Component | Current limitation |
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| Popover, Select, CountrySelect (React and Preact) | Body portal content reaches the host inside the component portal area. These fixtures cover opening and visible content; search, selection, dismissal and focus restoration are not covered yet. |
+| Popover, Select (React and Preact) | Body portal content reaches the host inside the component portal area. These fixtures cover opening and visible content; search, selection, dismissal and focus restoration are not covered yet. |
+| CountrySelect (React and Preact) | Fixtures pass pointer opening, filtering, disabled interaction, translated labels and decorative flags, controlled/uncontrolled shorthand and compound selection, null clearing/reselection, canceled changes, external values, trigger and option-group render/ref targets, and search input props/ref. Search keyboard activation and IME (API-34), page sessions (API-35), and full portal, geometry, scrolling, outside dismissal and focus restoration acceptance (C04-C07) remain open. |
| PhoneCountryPicker (React and Preact) | React interactions and React/Preact trigger cases pass, covering shorthand/compound selection, cancellation, controlled clearing, native refs/render and RTL calling codes. Strict Preact interaction remains failing: typing `"+966"` yields `"966"`, before the clear/replacement assertions run. The input propagation gap remains visible in the active fixture. |
| Slider (React) | Edge-aligned thumbs stay hidden until the value changes. Base UI 1.8 and 1.9 set up the thumb's `ResizeObserver` before React attaches the `Slider.Control` ref, so the thumb never re-measures once the first host geometry arrives ([mui/base-ui#5995](https://github.com/mui/base-ui/issues/5995), fix pending in [mui/base-ui#6000](https://github.com/mui/base-ui/pull/6000)). Preact attaches the ref first, so its thumbs appear. `thumbAlignment="center"` avoids the issue. |
| OverflowingList | Item widths come from the last host layout, because a worker cannot lay out the measuring state synchronously. The truncated last item is measured at its truncated width, so the visible count can differ from a native render when that item's full width decides whether it fits. |
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
index a056f98af09..4d5f815a6fb 100644
--- 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
@@ -1,18 +1,29 @@
import { useState } from 'react';
import { defineFrontComponent } from 'twenty-sdk/define';
+import { isDefined } from 'twenty-shared/utils';
import { CountrySelect } from 'twenty-ui/components/input';
+import { Dropdown } from 'twenty-ui/components/navigation';
+import { Button } from 'twenty-ui/primitives/input';
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: '🇯🇵' },
+ { value: 'FR', label: 'France', flag: '🇫🇷' },
+ { value: 'BR', label: 'Brésil', flag: '🇧🇷' },
+ { value: 'JP', label: 'Japon', flag: '🇯🇵' },
+ { value: 'US', label: 'Unavailable country', flag: '🇺🇸', disabled: true },
];
const CountrySelectExample = () => {
- const [country, setCountry] = useState('France');
- const [shippingCountry, setShippingCountry] = useState('Japan');
+ const [country, setCountry] = useState<string | null>('FR');
+ const [shippingCountry, setShippingCountry] = useState<string | null>('JP');
+ const [defaultCountry, setDefaultCountry] = useState<string | null>('FR');
+ const [cancelableCountry, setCancelableCountry] = useState<string | null>(
+ 'FR',
+ );
+ const [changeDetails, setChangeDetails] = useState('none');
+ const [canceledChangeDetails, setCanceledChangeDetails] = useState('none');
+ const [triggerClickCount, setTriggerClickCount] = useState(0);
return (
<TwentyUiGalleryCard title="Country selection">
@@ -20,23 +31,119 @@ const CountrySelectExample = () => {
countries={COUNTRIES}
label="Billing country"
value={country}
- onValueChange={setCountry}
+ onValueChange={(value, eventDetails) => {
+ setCountry(value);
+ setChangeDetails(
+ `${value ?? 'null'}:${eventDetails.reason}:${eventDetails.event.type}:${eventDetails.trigger?.textContent?.trim()}`,
+ );
+ }}
+ title="Choose a billing country"
+ ref={(element) => {
+ if (isDefined(element)) {
+ element.setAttribute('data-ref-target', 'billing-country');
+ }
+ }}
+ render={<button data-render-target="billing-country" />}
+ onClick={() => setTriggerClickCount((count) => count + 1)}
+ popupProps={{ 'aria-label': 'Billing countries' }}
+ optionsProps={{
+ 'aria-label': 'Billing country choices',
+ render: <section data-render-target="billing-country-choices" />,
+ ref: (element) => {
+ if (isDefined(element)) {
+ element.setAttribute(
+ 'data-ref-target',
+ 'billing-country-choices',
+ );
+ }
+ },
+ }}
+ searchProps={{
+ title: 'Search billing countries',
+ ref: (element) => {
+ if (isDefined(element)) {
+ element.setAttribute('data-ref-target', 'billing-country-search');
+ }
+ },
+ }}
/>
- <CountrySelect
+ <CountrySelect.Root
countries={COUNTRIES}
- label="Shipping country"
value={shippingCountry}
onValueChange={setShippingCountry}
+ >
+ <Dropdown.Root type="picker">
+ <CountrySelect.Trigger label="Shipping country" />
+ <Dropdown.Content aria-label="Shipping countries">
+ <CountrySelect.Options />
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </CountrySelect.Root>
+ <CountrySelect
+ countries={COUNTRIES}
+ label="Default country"
+ defaultValue="FR"
+ onValueChange={setDefaultCountry}
/>
+ <CountrySelect.Root
+ countries={COUNTRIES}
+ defaultValue="FR"
+ onValueChange={(value, eventDetails) => {
+ if (value === 'BR') {
+ eventDetails.cancel();
+ setCanceledChangeDetails(
+ `${value}:${eventDetails.reason}:${eventDetails.isCanceled}`,
+ );
+
+ return;
+ }
+
+ setCancelableCountry(value);
+ }}
+ >
+ <Dropdown.Root type="picker">
+ <CountrySelect.Trigger label="Cancelable country" />
+ <Dropdown.Content aria-label="Cancelable countries">
+ <CountrySelect.Options />
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </CountrySelect.Root>
<CountrySelect
countries={COUNTRIES}
label="Disabled country"
- value="France"
+ value="FR"
onValueChange={setCountry}
disabled
/>
+ <Button
+ onClick={() => {
+ setCountry('BR');
+ setShippingCountry('BR');
+ }}
+ >
+ Set countries externally
+ </Button>
+ <Button
+ onClick={() => {
+ setCountry(null);
+ setShippingCountry(null);
+ }}
+ >
+ Clear countries externally
+ </Button>
<p role="status" aria-label="Saved countries">
- Billing: {country || 'empty'}; Shipping: {shippingCountry || 'empty'}
+ Billing: {country ?? 'null'}; Shipping: {shippingCountry ?? 'null'};
+ Default: {defaultCountry ?? 'null'}; Cancelable:{' '}
+ {cancelableCountry ?? 'null'}
+ </p>
+ <p role="status" aria-label="Country change details">
+ {changeDetails}
+ </p>
+ <p role="status" aria-label="Canceled country change">
+ {canceledChangeDetails}
+ </p>
+ <p role="status" aria-label="Country trigger click count">
+ {triggerClickCount}
</p>
</TwentyUiGalleryCard>
);
@@ -46,6 +153,6 @@ 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',
+ 'Stable country IDs, translated labels, nullable selection and compound picker composition',
component: CountrySelectExample,
});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/countrySelectTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/countrySelectTest.ts
index 3d93a709144..26248147423 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/countrySelectTest.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/countrySelectTest.ts
@@ -1,10 +1,9 @@
-import { expect, userEvent, within } from 'storybook/test';
+import { expect, userEvent, waitFor, within } from 'storybook/test';
import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';
import { waitForSandboxRoundTrip } from '@/__stories__/shared/test-utils/waitForSandboxRoundTrip';
import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
-import { createDropdownOpenTest } from '@/__stories__/twenty-ui-gallery/utils/createDropdownOpenTest';
type Canvas = ReturnType<typeof within>;
@@ -22,6 +21,13 @@ const expectTriggersShowSavedCountriesWithDecorativeFlags = (
expect(billingTrigger).toHaveTextContent('France');
expect(shippingTrigger).toHaveTextContent('Japon');
+ expect(billingTrigger.tagName).toBe('BUTTON');
+ expect(billingTrigger).toHaveAttribute('title', 'Choose a billing country');
+ expect(billingTrigger).toHaveAttribute('data-ref-target', 'billing-country');
+ expect(billingTrigger).toHaveAttribute(
+ 'data-render-target',
+ 'billing-country',
+ );
expect(within(billingTrigger).getByText('🇫🇷')).toHaveAttribute(
'aria-hidden',
'true',
@@ -46,22 +52,213 @@ const expectDisabledTriggerIgnoresClick = async (canvas: Canvas) => {
expect(disabledTrigger).toHaveAttribute('aria-expanded', 'false');
expect(
canvas.getByRole('status', { name: 'Saved countries' }),
- ).toHaveTextContent('Billing: France; Shipping: Japan');
+ ).toHaveTextContent('Billing: FR; Shipping: JP');
};
-const billingCountrySelectOpenTest = createDropdownOpenTest({
- triggerName: BILLING_COUNTRY_TRIGGER_NAME,
- popupText: 'Brésil',
-});
+const selectCountry = async ({
+ canvas,
+ page,
+ triggerName,
+ optionName,
+}: {
+ canvas: Canvas;
+ page: Canvas;
+ triggerName: string;
+ optionName: string;
+}) => {
+ const trigger = canvas.getByRole('button', { name: triggerName });
+
+ await userEvent.click(trigger);
+ await waitFor(() => expect(trigger).toHaveAttribute('aria-expanded', 'true'));
+ await userEvent.click(await page.findByRole('option', { name: optionName }));
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),
+ );
+};
export const countrySelectTest: TwentyUiGalleryPlayFunction = async (
context,
) => {
const canvas = within(context.canvasElement);
+ const page = within(context.canvasElement.ownerDocument.body);
await expectFrontComponentMounted(canvas);
expectTriggersShowSavedCountriesWithDecorativeFlags(canvas);
await expectDisabledTriggerIgnoresClick(canvas);
+
+ const billingTrigger = canvas.getByRole('button', {
+ name: BILLING_COUNTRY_TRIGGER_NAME,
+ });
+ const shippingTrigger = canvas.getByRole('button', {
+ name: 'Shipping country',
+ });
+ const savedCountries = canvas.getByRole('status', {
+ name: 'Saved countries',
+ });
+
+ await userEvent.click(billingTrigger);
+ await waitFor(() => {
+ expect(
+ page.getByRole('dialog', { name: 'Billing countries' }),
+ ).toBeVisible();
+ expect(page.getByRole('option', { name: 'France' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ const choices = page.getByRole('listbox', {
+ name: 'Billing country choices',
+ });
+ expect(choices.tagName).toBe('SECTION');
+ expect(choices).toHaveAttribute(
+ 'data-ref-target',
+ 'billing-country-choices',
+ );
+ expect(choices).toHaveAttribute(
+ 'data-render-target',
+ 'billing-country-choices',
+ );
+ const search = page.getByRole('searchbox', { name: 'Search' });
+ expect(search.tagName).toBe('INPUT');
+ expect(search).toHaveAttribute('title', 'Search billing countries');
+ expect(search).toHaveAttribute('data-ref-target', 'billing-country-search');
+ expect(
+ canvas.getByRole('status', { name: 'Country trigger click count' }),
+ ).toHaveTextContent('1');
+ });
+ const unavailableCountry = page.getByRole('option', {
+ name: 'Unavailable country',
+ });
+ expect(unavailableCountry).toBeDisabled();
+ await userEvent.click(unavailableCountry);
+ await waitForSandboxRoundTrip();
+ expect(savedCountries).toHaveTextContent('Billing: FR; Shipping: JP');
+ expect(billingTrigger).toHaveAttribute('aria-expanded', 'true');
+
+ await userEvent.click(page.getByRole('option', { name: 'Brésil' }));
+ await waitFor(() => {
+ expect(billingTrigger).toHaveTextContent('Brésil');
+ expect(billingTrigger).toHaveAttribute('aria-expanded', 'false');
+ expect(savedCountries).toHaveTextContent('Billing: BR; Shipping: JP');
+ expect(
+ canvas.getByRole('status', { name: 'Country change details' })
+ .textContent,
+ ).toMatch(/^BR:item-press:click:.*Brésil/);
+ });
+
+ await selectCountry({
+ canvas,
+ page,
+ triggerName: BILLING_COUNTRY_TRIGGER_NAME,
+ optionName: 'No country',
+ });
+ await waitFor(() => {
+ expect(billingTrigger).toHaveTextContent('No country');
+ expect(savedCountries).toHaveTextContent('Billing: null; Shipping: JP');
+ expect(
+ canvas.getByRole('status', { name: 'Country change details' }),
+ ).toHaveTextContent('null:item-press:click:No country');
+ });
+
+ await selectCountry({
+ canvas,
+ page,
+ triggerName: BILLING_COUNTRY_TRIGGER_NAME,
+ optionName: 'Japon',
+ });
+ await selectCountry({
+ canvas,
+ page,
+ triggerName: 'Shipping country',
+ optionName: 'No country',
+ });
+ await waitFor(() => {
+ expect(shippingTrigger).toHaveTextContent('No country');
+ expect(savedCountries).toHaveTextContent('Billing: JP; Shipping: null');
+ });
+ await selectCountry({
+ canvas,
+ page,
+ triggerName: 'Shipping country',
+ optionName: 'Brésil',
+ });
+ await waitFor(() => {
+ expect(shippingTrigger).toHaveTextContent('Brésil');
+ expect(savedCountries).toHaveTextContent('Billing: JP; Shipping: BR');
+ });
+
+ await selectCountry({
+ canvas,
+ page,
+ triggerName: 'Default country',
+ optionName: 'No country',
+ });
+ await waitFor(() =>
+ expect(savedCountries).toHaveTextContent('Default: null'),
+ );
+ await selectCountry({
+ canvas,
+ page,
+ triggerName: 'Default country',
+ optionName: 'Japon',
+ });
+ await waitFor(() => expect(savedCountries).toHaveTextContent('Default: JP'));
+
+ const cancelableTrigger = canvas.getByRole('button', {
+ name: 'Cancelable country',
+ });
+ await userEvent.click(cancelableTrigger);
+ await userEvent.click(await page.findByRole('option', { name: 'Brésil' }));
+ await waitFor(() => {
+ expect(cancelableTrigger).toHaveTextContent('France');
+ expect(cancelableTrigger).toHaveAttribute('aria-expanded', 'true');
+ expect(savedCountries).toHaveTextContent('Cancelable: FR');
+ expect(
+ canvas.getByRole('status', { name: 'Canceled country change' }),
+ ).toHaveTextContent('BR:item-press:true');
+ expect(page.getByRole('option', { name: 'France' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ });
+ await userEvent.click(page.getByRole('option', { name: 'Japon' }));
+ await waitFor(() => {
+ expect(cancelableTrigger).toHaveTextContent('Japon');
+ expect(cancelableTrigger).toHaveAttribute('aria-expanded', 'false');
+ expect(savedCountries).toHaveTextContent('Cancelable: JP');
+ });
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Set countries externally' }),
+ );
+ await waitFor(() => {
+ expect(billingTrigger).toHaveTextContent('Brésil');
+ expect(shippingTrigger).toHaveTextContent('Brésil');
+ expect(savedCountries).toHaveTextContent('Billing: BR; Shipping: BR');
+ });
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Clear countries externally' }),
+ );
+ await waitFor(() => {
+ expect(billingTrigger).toHaveTextContent('No country');
+ expect(shippingTrigger).toHaveTextContent('No country');
+ expect(savedCountries).toHaveTextContent('Billing: null; Shipping: null');
+ });
+
+ await userEvent.click(billingTrigger);
+ expect(
+ await page.findByRole('option', { name: 'No country' }),
+ ).toHaveAttribute('aria-selected', 'true');
+ const search = page.getByRole('searchbox', { name: 'Search' });
+ await userEvent.type(search, 'jap');
+ await waitFor(() => {
+ expect(page.getByRole('option', { name: 'Japon' })).toBeVisible();
+ expect(page.queryByRole('option', { name: 'France' })).toBeNull();
+ expect(page.queryByRole('option', { name: 'Brésil' })).toBeNull();
+ });
+ await userEvent.click(page.getByRole('option', { name: 'Japon' }));
+ await waitFor(() => {
+ expect(billingTrigger).toHaveTextContent('Japon');
+ expect(savedCountries).toHaveTextContent('Billing: JP; Shipping: null');
+ });
expect(errorHandler).not.toHaveBeenCalled();
- await billingCountrySelectOpenTest(context);
};
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 9aa11554c9d..0ff98938773 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,8 +1,10 @@
import { t } from '@lingui/core/macro';
-import { createElement, useContext, useMemo } from 'react';
+import { useContext, useMemo } from 'react';
import { Key } from 'ts-key-enum';
import { SELECT_COUNTRY_DROPDOWN_ID } from '@/ui/input/components/internal/country/constants/SelectCountryDropdownId';
+import { getCountrySelectCountryName } from '@/ui/input/components/internal/country/utils/getCountrySelectCountryName';
+import { getCountrySelectValue } from '@/ui/input/components/internal/country/utils/getCountrySelectValue';
import { useCountries } from '@/ui/input/components/internal/hooks/useCountries';
import { DropdownCleanupEffect } from '@/ui/layout/dropdown/components/DropdownCleanupEffect';
import { DropdownClickOutsideListenerExclusion } from '@/ui/layout/dropdown/components/DropdownClickOutsideListenerExclusion';
@@ -10,6 +12,7 @@ import { useHandleDropdownOpenChange } from '@/ui/layout/dropdown/hooks/useHandl
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 { isDefined } from 'twenty-shared/utils';
import {
type CountryChoice,
CountrySelect as SharedCountrySelect,
@@ -38,21 +41,35 @@ export const CountrySelect = ({
const countryChoices = useMemo<CountryChoice[]>(
() =>
- countries.map(({ countryName, Flag }) => ({
- value: countryName,
+ countries.map(({ countryCode, countryName, Flag }) => ({
+ value: countryCode,
label: countryName,
flag: <Flag width="100%" height="100%" />,
})),
[countries],
);
+ const selectedCountryValue = getCountrySelectValue({
+ countries,
+ countryName: selectedCountryName,
+ });
+
+ const handleValueChange = (countryCode: string | null) => {
+ const countryName = getCountrySelectCountryName({ countries, countryCode });
+
+ if (!isDefined(countryName)) {
+ return;
+ }
+
+ onChange(countryName);
+ };
return (
<>
<DropdownCleanupEffect dropdownId={SELECT_COUNTRY_DROPDOWN_ID} />
<SharedCountrySelect
countries={countryChoices}
- value={selectedCountryName}
- onValueChange={onChange}
+ value={selectedCountryValue}
+ onValueChange={handleValueChange}
label={label}
searchLabel={t`Search`}
noCountryLabel={t`No country`}
@@ -65,17 +82,17 @@ export const CountrySelect = ({
}
}}
popupProps={{
- render: (popupProps) =>
- createElement(
- 'div',
- {
- ...popupProps,
- 'data-click-outside-id': parentClickOutsideId,
- },
+ render: (popupProps) => (
+ <div
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...popupProps}
+ data-click-outside-id={parentClickOutsideId}
+ >
<DropdownClickOutsideListenerExclusion>
{popupProps.children}
- </DropdownClickOutsideListenerExclusion>,
- ),
+ </DropdownClickOutsideListenerExclusion>
+ </div>
+ ),
}}
/>
</>
diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__stories__/CountrySelect.stories.tsx b/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__stories__/CountrySelect.stories.tsx
new file mode 100644
index 00000000000..0f0e984a566
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__stories__/CountrySelect.stories.tsx
@@ -0,0 +1,176 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+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';
+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';
+
+import { CountrySelectExample } from './CountrySelectExample';
+
+const onCountryChange = fn<(countryName: string) => void>();
+
+const meta: Meta<typeof CountrySelect> = {
+ title: 'UI/Input/CountrySelect',
+ component: CountrySelect,
+ decorators: [ComponentDecorator],
+ args: {
+ label: 'Country',
+ selectedCountryName: 'France',
+ onChange: onCountryChange,
+ },
+ beforeEach: () => {
+ onCountryChange.mockClear();
+ },
+ render: ({ label, selectedCountryName, onChange }) => (
+ <CountrySelectExample
+ label={label}
+ selectedCountryName={selectedCountryName}
+ onChange={onChange}
+ />
+ ),
+};
+
+export default meta;
+
+type Story = StoryObj<typeof CountrySelect>;
+
+export const ClearAndReselectPreservesCountryNames: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ const trigger = canvas.getByRole('button', { name: 'Country' });
+
+ await userEvent.click(trigger);
+ const popup = await body.findByRole('dialog', { name: 'Country' });
+
+ expect(
+ within(popup).getByRole('option', { name: 'France' }),
+ ).toHaveAttribute('aria-selected', 'true');
+ expect(jotaiStore.get(activeDropdownFocusIdState.atom)).toBe(
+ SELECT_COUNTRY_DROPDOWN_ID,
+ );
+
+ await userEvent.click(
+ within(popup).getByRole('option', { name: 'No country' }),
+ );
+
+ await waitFor(() =>
+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ expect(onCountryChange).toHaveBeenCalledTimes(1);
+ expect(onCountryChange).toHaveBeenCalledWith('');
+ expect(
+ canvas.getByRole('status', { name: 'Stored country' }),
+ ).toHaveTextContent('empty');
+ expect(jotaiStore.get(activeDropdownFocusIdState.atom)).toBeNull();
+ expect(jotaiStore.get(focusStackState.atom)).toEqual([]);
+
+ await userEvent.click(trigger);
+ await userEvent.type(
+ await body.findByRole('searchbox', { name: 'Search' }),
+ 'Brazil',
+ );
+ await userEvent.click(await body.findByRole('option', { name: 'Brazil' }));
+
+ await waitFor(() =>
+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ expect(onCountryChange).toHaveBeenNthCalledWith(2, 'Brazil');
+ expect(onCountryChange).toHaveBeenCalledTimes(2);
+ expect(trigger).toHaveTextContent('Brazil');
+ expect(
+ canvas.getByRole('status', { name: 'Stored country' }),
+ ).toHaveTextContent('Brazil');
+ },
+};
+
+export const ExternalValuesPreserveLegacyCountries: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ const trigger = canvas.getByRole('button', { name: 'Country' });
+
+ await userEvent.click(canvas.getByRole('button', { name: 'Set Brazil' }));
+ expect(trigger).toHaveTextContent('Brazil');
+ expect(onCountryChange).not.toHaveBeenCalled();
+
+ await userEvent.click(trigger);
+ const brazilPopup = await body.findByRole('dialog', { name: 'Country' });
+
+ expect(
+ within(brazilPopup).getByRole('option', { name: 'Brazil' }),
+ ).toHaveAttribute('aria-selected', 'true');
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() =>
+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Set legacy country' }),
+ );
+ expect(trigger).toHaveTextContent('No country');
+ expect(
+ canvas.getByRole('status', { name: 'Stored country' }),
+ ).toHaveTextContent('FR');
+
+ await userEvent.click(trigger);
+ const popup = await body.findByRole('dialog', { name: 'Country' });
+
+ expect(
+ within(popup).queryByRole('option', { selected: true }),
+ ).not.toBeInTheDocument();
+ expect(onCountryChange).not.toHaveBeenCalled();
+ await userEvent.click(
+ within(popup).getByRole('option', { name: 'No country' }),
+ );
+
+ await waitFor(() =>
+ expect(body.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ expect(onCountryChange).toHaveBeenCalledTimes(1);
+ expect(onCountryChange).toHaveBeenCalledWith('');
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Set empty country' }),
+ );
+ await userEvent.click(trigger);
+ const emptyPopup = await body.findByRole('dialog', { name: 'Country' });
+
+ expect(
+ within(emptyPopup).getByRole('option', { name: 'No country' }),
+ ).toHaveAttribute('aria-selected', 'true');
+ expect(onCountryChange).toHaveBeenCalledTimes(1);
+ await userEvent.keyboard('{Escape}');
+ },
+};
+
+export const UnmountCleansDropdownRegistration: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ const dropdownOpenState = isDropdownOpenComponentState.atomFamily({
+ instanceId: SELECT_COUNTRY_DROPDOWN_ID,
+ });
+
+ await userEvent.click(canvas.getByRole('button', { name: 'Country' }));
+ await body.findByRole('dialog', { name: 'Country' });
+
+ expect(jotaiStore.get(dropdownOpenState)).toBe(true);
+ expect(jotaiStore.get(focusStackState.atom)).toEqual([
+ expect.objectContaining({ focusId: SELECT_COUNTRY_DROPDOWN_ID }),
+ ]);
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Unmount country picker' }),
+ );
+
+ await waitFor(() => expect(jotaiStore.get(dropdownOpenState)).toBe(false));
+ expect(jotaiStore.get(activeDropdownFocusIdState.atom)).toBeNull();
+ expect(jotaiStore.get(focusStackState.atom)).toEqual([]);
+ expect(body.queryByRole('dialog')).not.toBeInTheDocument();
+ },
+};
diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__stories__/CountrySelectExample.tsx b/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__stories__/CountrySelectExample.tsx
new file mode 100644
index 00000000000..282b6ef4f3d
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__stories__/CountrySelectExample.tsx
@@ -0,0 +1,37 @@
+import { type ComponentProps, useState } from 'react';
+import { Button } from 'twenty-ui/primitives/input';
+
+import { CountrySelect } from '@/ui/input/components/internal/country/components/CountrySelect';
+
+type CountrySelectExampleProps = ComponentProps<typeof CountrySelect>;
+
+export const CountrySelectExample = ({
+ label,
+ selectedCountryName,
+ onChange,
+}: CountrySelectExampleProps) => {
+ const [countryName, setCountryName] = useState(selectedCountryName);
+ const [showCountrySelect, setShowCountrySelect] = useState(true);
+
+ return (
+ <>
+ {showCountrySelect && (
+ <CountrySelect
+ label={label}
+ selectedCountryName={countryName}
+ onChange={(nextCountryName) => {
+ setCountryName(nextCountryName);
+ onChange(nextCountryName);
+ }}
+ />
+ )}
+ <output aria-label="Stored country">{countryName || 'empty'}</output>
+ <Button onClick={() => setCountryName('Brazil')}>Set Brazil</Button>
+ <Button onClick={() => setCountryName('FR')}>Set legacy country</Button>
+ <Button onClick={() => setCountryName('')}>Set empty country</Button>
+ <Button onClick={() => setShowCountrySelect(false)}>
+ Unmount country picker
+ </Button>
+ </>
+ );
+};
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
deleted file mode 100644
index cef0c3fa07a..00000000000
--- a/packages/twenty-front/src/modules/ui/input/components/internal/country/components/__tests__/CountrySelect.test.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-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();
-
- await waitFor(() => expect(store.get(dropdownOpenState)).toBe(false));
- expect(store.get(activeDropdownFocusIdState.atom)).toBeNull();
- expect(store.get(focusStackState.atom)).toEqual([]);
- });
-});
diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/country/utils/__tests__/getCountrySelectCountryName.test.ts b/packages/twenty-front/src/modules/ui/input/components/internal/country/utils/__tests__/getCountrySelectCountryName.test.ts
new file mode 100644
index 00000000000..bb0e8f8f790
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/input/components/internal/country/utils/__tests__/getCountrySelectCountryName.test.ts
@@ -0,0 +1,27 @@
+import { getCountrySelectCountryName } from '@/ui/input/components/internal/country/utils/getCountrySelectCountryName';
+import { type Country } from '@/ui/input/components/internal/types/Country';
+
+const COUNTRIES: Pick<Country, 'countryCode' | 'countryName'>[] = [
+ { countryCode: 'FR', countryName: 'France' },
+ { countryCode: 'BR', countryName: 'Brazil' },
+];
+
+describe('getCountrySelectCountryName', () => {
+ it('persists the original source country name for a selected identifier', () => {
+ expect(
+ getCountrySelectCountryName({ countries: COUNTRIES, countryCode: 'BR' }),
+ ).toBe('Brazil');
+ });
+
+ it('clears to the existing product empty string when the picker clears to null', () => {
+ expect(
+ getCountrySelectCountryName({ countries: COUNTRIES, countryCode: null }),
+ ).toBe('');
+ });
+
+ it('ignores an identifier absent from the prepared countries', () => {
+ expect(
+ getCountrySelectCountryName({ countries: COUNTRIES, countryCode: 'ZZ' }),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/country/utils/__tests__/getCountrySelectValue.test.ts b/packages/twenty-front/src/modules/ui/input/components/internal/country/utils/__tests__/getCountrySelectValue.test.ts
new file mode 100644
index 00000000000..91073dd87ff
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/input/components/internal/country/utils/__tests__/getCountrySelectValue.test.ts
@@ -0,0 +1,39 @@
+import { getCountrySelectValue } from '@/ui/input/components/internal/country/utils/getCountrySelectValue';
+import { type Country } from '@/ui/input/components/internal/types/Country';
+
+const COUNTRIES: Pick<Country, 'countryCode' | 'countryName'>[] = [
+ { countryCode: 'FR', countryName: 'France' },
+ { countryCode: 'BR', countryName: 'Brazil' },
+];
+
+describe('getCountrySelectValue', () => {
+ it('selects the stable identifier for an existing stored country name', () => {
+ expect(
+ getCountrySelectValue({ countries: COUNTRIES, countryName: 'Brazil' }),
+ ).toBe('BR');
+ });
+
+ it.each(['', null])('treats %p as an empty selection', (countryName) => {
+ expect(
+ getCountrySelectValue({ countries: COUNTRIES, countryName }),
+ ).toBeNull();
+ });
+
+ it.each(['Atlantis', 'FR', ' ', 'france'])(
+ 'keeps legacy stored value %p distinct from an empty or known selection',
+ (countryName) => {
+ const value = getCountrySelectValue({
+ countries: COUNTRIES,
+ countryName,
+ });
+
+ expect(value).not.toBeNull();
+ expect(COUNTRIES.some((country) => country.countryCode === value)).toBe(
+ false,
+ );
+ expect(value).toBe(
+ getCountrySelectValue({ countries: COUNTRIES, countryName }),
+ );
+ },
+ );
+});
diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/country/utils/getCountrySelectCountryName.ts b/packages/twenty-front/src/modules/ui/input/components/internal/country/utils/getCountrySelectCountryName.ts
new file mode 100644
index 00000000000..f1d69f9dec4
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/input/components/internal/country/utils/getCountrySelectCountryName.ts
@@ -0,0 +1,18 @@
+import { isNull } from '@sniptt/guards';
+
+import { type Country } from '@/ui/input/components/internal/types/Country';
+
+export const getCountrySelectCountryName = ({
+ countries,
+ countryCode,
+}: {
+ countries: readonly Pick<Country, 'countryCode' | 'countryName'>[];
+ countryCode: string | null;
+}): string | undefined => {
+ if (isNull(countryCode)) {
+ return '';
+ }
+
+ return countries.find((country) => country.countryCode === countryCode)
+ ?.countryName;
+};
diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/country/utils/getCountrySelectValue.ts b/packages/twenty-front/src/modules/ui/input/components/internal/country/utils/getCountrySelectValue.ts
new file mode 100644
index 00000000000..7dcf30f1a21
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/input/components/internal/country/utils/getCountrySelectValue.ts
@@ -0,0 +1,25 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type Country } from '@/ui/input/components/internal/types/Country';
+
+const UNKNOWN_COUNTRY_VALUE_PREFIX = 'unknown-country:';
+
+export const getCountrySelectValue = ({
+ countries,
+ countryName,
+}: {
+ countries: readonly Pick<Country, 'countryCode' | 'countryName'>[];
+ countryName: string | null;
+}): string | null => {
+ if (!isNonEmptyString(countryName)) {
+ return null;
+ }
+
+ const country = countries.find(
+ (availableCountry) => availableCountry.countryName === countryName,
+ );
+
+ return (
+ country?.countryCode ?? `${UNKNOWN_COUNTRY_VALUE_PREFIX}${countryName}`
+ );
+};
diff --git a/packages/twenty-ui/docs/components.ts b/packages/twenty-ui/docs/components.ts
index a91c4bf2f28..2cfaac22d9e 100644
--- a/packages/twenty-ui/docs/components.ts
+++ b/packages/twenty-ui/docs/components.ts
@@ -5,6 +5,7 @@ import { TEXTAREA_PROP_DESCRIPTIONS } from './textareaPropDescriptions';
import { INPUT_GROUP_PROP_DESCRIPTIONS } from './inputGroupPropDescriptions';
import { INPUT_PROP_DESCRIPTIONS } from './inputPropDescriptions';
import { COUNTRY_SELECT_PROP_DESCRIPTIONS } from './countrySelectPropDescriptions';
+import { COUNTRY_SELECT_PART_PROP_DESCRIPTIONS } from './countrySelectPartPropDescriptions';
import { CURRENCY_PICKER_PART_PROP_DESCRIPTIONS } from './currencyPickerPartPropDescriptions';
import { CURRENCY_PICKER_PROP_DESCRIPTIONS } from './currencyPickerPropDescriptions';
import { OVERFLOWING_LIST_PROP_DESCRIPTIONS } from './overflowingListPropDescriptions';
@@ -103,6 +104,8 @@ export const DOCUMENTED_COMPONENTS = [
entryPoint: 'twenty-ui/components/input',
slug: 'components/input/country-select',
propDescriptions: COUNTRY_SELECT_PROP_DESCRIPTIONS,
+ parts: ['Root', 'Trigger', 'Options'],
+ partPropDescriptions: COUNTRY_SELECT_PART_PROP_DESCRIPTIONS,
},
{
name: 'CurrencyPicker',
diff --git a/packages/twenty-ui/docs/countrySelectPartPropDescriptions.ts b/packages/twenty-ui/docs/countrySelectPartPropDescriptions.ts
new file mode 100644
index 00000000000..1899a7b3c6d
--- /dev/null
+++ b/packages/twenty-ui/docs/countrySelectPartPropDescriptions.ts
@@ -0,0 +1,55 @@
+import { type ComponentProps } from 'react';
+
+import { type CountrySelect } from '../src/components/input/CountrySelect/CountrySelect';
+
+export const COUNTRY_SELECT_PART_PROP_DESCRIPTIONS = {
+ Root: {
+ countries:
+ 'Prepared country choices with unique stable string values, caller-owned labels, and optional decorative flags and disabled states. An empty string is a valid choice value.',
+ value:
+ 'Controlled selected identifier. Null selects no country; undefined leaves selection uncontrolled.',
+ defaultValue: 'Initial uncontrolled selected identifier. Defaults to null.',
+ onValueChange:
+ 'Reports the selected identifier or null with event, reason, trigger, cancel and isCanceled details. Call cancel() to preserve selection and keep the popup open.',
+ noCountryLabel:
+ 'Text for the null selection and its option. Defaults to No country.',
+ disabled:
+ 'Prevents opening and selection. An empty country list is also disabled. The trigger stays focusable with aria-disabled.',
+ children:
+ 'Picker composition containing Dropdown.Root, CountrySelect.Trigger, and CountrySelect.Options. Root adds no DOM element.',
+ } satisfies Partial<
+ Record<keyof ComponentProps<typeof CountrySelect.Root>, string>
+ >,
+ Trigger: {
+ label: 'Optional visible label that names the trigger.',
+ children:
+ 'Custom trigger content. Replaces the selected country presentation while retaining shared trigger behavior.',
+ wrapperProps:
+ 'Native props and ref for the div around the trigger and its visible label. Children are owned by the picker.',
+ className: 'Class applied to the trigger button.',
+ render:
+ 'Replaces the trigger element. Custom components must forward the supplied props and ref.',
+ ref: 'Ref to the trigger element.',
+ } satisfies Partial<
+ Record<keyof ComponentProps<typeof CountrySelect.Trigger>, string>
+ >,
+ Options: {
+ 'aria-label':
+ 'Accessible name for the selection listbox. Overrides its default name.',
+ 'aria-labelledby':
+ 'Accessible name references for the selection listbox. Defaults to the registered Dropdown title or trigger element.',
+ closeOnSelect:
+ 'Closes the popup after a selection. Defaults to true. Cancelled selection keeps it open.',
+ searchLabel: 'Search placeholder and accessible name. Defaults to Search.',
+ noResultsLabel:
+ 'Text displayed when no choice matches the search. Defaults to No results.',
+ searchProps:
+ 'Native search input props, ref, and render. Search value and change handling are owned by the picker.',
+ className: 'Class applied to the selection group div.',
+ render:
+ 'Replaces the selection group div. Functions receive supplied props and { value, multiple: false } state, with the public string or null selection. Custom components must forward the supplied props and ref.',
+ ref: 'Ref to the selection group element.',
+ } satisfies Partial<
+ Record<keyof ComponentProps<typeof CountrySelect.Options>, string>
+ >,
+};
diff --git a/packages/twenty-ui/docs/countrySelectPropDescriptions.ts b/packages/twenty-ui/docs/countrySelectPropDescriptions.ts
index ab967ef020a..353ffae197d 100644
--- a/packages/twenty-ui/docs/countrySelectPropDescriptions.ts
+++ b/packages/twenty-ui/docs/countrySelectPropDescriptions.ts
@@ -2,19 +2,38 @@ import { type CountrySelectProps } from '../src/components/input/CountrySelect/t
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.',
+ 'Prepared country choices with unique stable string values, caller-owned labels, and optional decorative flags and disabled states. An empty string is a valid choice value.',
+ value:
+ 'Controlled selected identifier. Null selects no country; undefined leaves selection uncontrolled.',
+ defaultValue: 'Initial uncontrolled selected identifier. Defaults to null.',
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.',
+ 'Reports the selected identifier or null with cancellable event details. Call details.cancel() to preserve selection and keep the popup open.',
+ label: 'Optional visible label that names the trigger.',
+ children:
+ 'Custom trigger content. Replaces the selected country presentation while retaining shared trigger behavior.',
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.',
+ searchProps:
+ 'Native search input props, ref, and render. Search value and change handling are owned by the picker.',
+ closeOnSelect:
+ 'Closes the popup after a selection. Defaults to true. Cancelled selection keeps it open.',
+ optionsProps:
+ 'Native props, ref, and render for the selection group div rendered by CountrySelect.Options.',
open: 'Controls whether the country popup is open.',
- onOpenChange: 'Reports popup opening and closing.',
+ defaultOpen: 'Whether the uncontrolled popup is initially open.',
+ onOpenChange:
+ 'Reports popup opening and closing with the next boolean state, matching Dropdown.Root.',
+ onEscapeKeyDown:
+ 'Called before Escape dismisses the popup. Call event.preventDefault() to keep it open.',
+ onInteractOutside:
+ 'Called before outside interaction or Tab dismisses the popup. Call event.preventDefault() to keep it open.',
+ defaultPage: 'Dropdown page shown when the popup opens. Defaults to root.',
popupProps:
- 'Dropdown popup positioning, portal, focus, and event options for host integration.',
+ 'Dropdown.Content props, including native popup attributes, ref, render, positioning, portal destination, and keepMounted. Explicit popup accessible names override the trigger name. Children are owned by the picker.',
+ wrapperProps:
+ 'Native props and ref for the div around the trigger and its visible label. Children are owned by the picker.',
id: 'ID of the trigger. Generated when omitted.',
className: 'Class applied to the trigger.',
disabled:
diff --git a/packages/twenty-ui/docs/label-ownership.md b/packages/twenty-ui/docs/label-ownership.md
index 1f454ddaac7..71d3de9dc35 100644
--- a/packages/twenty-ui/docs/label-ownership.md
+++ b/packages/twenty-ui/docs/label-ownership.md
@@ -13,7 +13,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 Badge. 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, native accessible name and action labels. 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. |
+| CountrySelect | Root owns caller-supplied country labels and `noCountryLabel` (default `No country`). Trigger accepts `label`, native accessible names, and custom children. Options owns `searchLabel` (default `Search`) and `noResultsLabel` (default `No results`). The shorthand exposes the same labels. Applications own translations, stable identifiers, and persistence conversions. |
| PhoneCountryPicker | Callers supply country labels and the trigger name. The selected label describes the trigger; the popup uses its trigger name unless named explicitly. Options defaults are `Search` (`searchLabel`), `Countries` (`listLabel`) and `No results` (`emptyLabel`), also available through shorthand `optionsProps`. Calling codes omit the plus sign in caller data and display with LTR isolation. |
| ImageInput | `uploadLabel`, `removeLabel`, and `abortLabel` default to `Upload`, `Remove`, and `Abort`. The upload label names the visible upload button, preview button, and hidden file input. Native accessible attributes can supply names and descriptions for the file input. Applications supply `helperText` and `errorMessage`, including validation instructions and translated strings. |
| Toast and Toaster | Caller-owned children, description, icon, action, and `cancelLabel` nodes (default `Cancel`), plus `iconLabel` and `closeLabel` (default `Close`). Live updates replace only supplied fields. Toaster accepts native accessible attributes over its `Notifications` region default. Multiple Toasters mirror one provider-owned notification lifecycle; each region owns its accessible name. |
diff --git a/packages/twenty-ui/docs/public-exports.json b/packages/twenty-ui/docs/public-exports.json
index 7c6f0cea40c..884b11b46a0 100644
--- a/packages/twenty-ui/docs/public-exports.json
+++ b/packages/twenty-ui/docs/public-exports.json
@@ -102,7 +102,11 @@
},
"types": {
"CountryChoice": "components/input/CountrySelect/types/CountryChoice",
+ "CountrySelectOptionsProps": "components/input/CountrySelect/types/CountrySelectOptionsProps",
+ "CountrySelectOptionsState": "components/input/CountrySelect/types/CountrySelectOptionsState",
"CountrySelectProps": "components/input/CountrySelect/types/CountrySelectProps",
+ "CountrySelectRootProps": "components/input/CountrySelect/types/CountrySelectRootProps",
+ "CountrySelectTriggerProps": "components/input/CountrySelect/types/CountrySelectTriggerProps",
"CurrencyPickerChangeEventDetails": "components/input/CurrencyPicker/types/CurrencyPickerChangeEventDetails",
"CurrencyPickerOption": "components/input/CurrencyPicker/types/CurrencyPickerOption",
"CurrencyPickerOptionsProps": "components/input/CurrencyPicker/types/CurrencyPickerOptionsProps",
diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.json
index ffe37b8c020..1428edd41fd 100644
--- a/packages/twenty-ui/generated/components.docs.json
+++ b/packages/twenty-ui/generated/components.docs.json
@@ -4,6 +4,13 @@
"entryPoint": "twenty-ui/components/input",
"slug": "components/input/country-select",
"props": [
+ {
+ "name": "children",
+ "type": "ReactNode",
+ "required": false,
+ "defaultValue": null,
+ "description": "Custom trigger content. Replaces the selected country presentation while retaining shared trigger behavior."
+ },
{
"name": "className",
"type": "string | ((state: PopoverTriggerState) => string | undefined)",
@@ -11,18 +18,60 @@
"defaultValue": null,
"description": "Class applied to the trigger."
},
+ {
+ "name": "closeDelay",
+ "type": "number",
+ "required": false,
+ "defaultValue": "0",
+ "description": "How long to wait before closing the popover that was opened on hover.\nSpecified in milliseconds.\n\nRequires the `openOnHover` prop."
+ },
+ {
+ "name": "closeOnSelect",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": null,
+ "description": "Closes the popup after a selection. Defaults to true. Cancelled selection keeps it open."
+ },
{
"name": "countries",
"type": "readonly CountryChoice[]",
"required": true,
"defaultValue": null,
- "description": "Prepared country choices with unique non-empty values, display labels, and optional decorative flags."
+ "description": "Prepared country choices with unique stable string values, caller-owned labels, and optional decorative flags and disabled states. An empty string is a valid choice value."
+ },
+ {
+ "name": "defaultOpen",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": null,
+ "description": "Whether the uncontrolled popup is initially open."
+ },
+ {
+ "name": "defaultPage",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Dropdown page shown when the popup opens. Defaults to root."
+ },
+ {
+ "name": "defaultValue",
+ "type": "string | null",
+ "required": false,
+ "defaultValue": null,
+ "description": "Initial uncontrolled selected identifier. Defaults to null."
+ },
+ {
+ "name": "delay",
+ "type": "number",
+ "required": false,
+ "defaultValue": "300",
+ "description": "How long to wait before the popover may be opened on hover. Specified in milliseconds.\n\nRequires the `openOnHover` prop."
},
{
"name": "disabled",
"type": "boolean",
"required": false,
- "defaultValue": "false",
+ "defaultValue": null,
"description": "Prevents opening and selection while the trigger stays focusable. An empty country list is also disabled."
},
{
@@ -37,7 +86,7 @@
"type": "string",
"required": false,
"defaultValue": null,
- "description": "Optional visible label that names the trigger and the popup."
+ "description": "Optional visible label that names the trigger."
},
{
"name": "nativeButton",
@@ -50,29 +99,43 @@
"name": "noCountryLabel",
"type": "string",
"required": false,
- "defaultValue": "No country",
+ "defaultValue": null,
"description": "Text of the no-country choice, also displayed when no country is selected."
},
{
"name": "noResultsLabel",
"type": "string",
"required": false,
- "defaultValue": "No results",
+ "defaultValue": null,
"description": "Text displayed when no choice matches the search."
},
+ {
+ "name": "onEscapeKeyDown",
+ "type": "((event: DropdownDismissEvent) => void)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Called before Escape dismisses the popup. Call event.preventDefault() to keep it open."
+ },
+ {
+ "name": "onInteractOutside",
+ "type": "((event: DropdownDismissEvent) => void)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Called before outside interaction or Tab dismisses the popup. Call event.preventDefault() to keep it open."
+ },
{
"name": "onOpenChange",
"type": "((open: boolean) => void)",
"required": false,
"defaultValue": null,
- "description": "Reports popup opening and closing."
+ "description": "Reports popup opening and closing with the next boolean state, matching Dropdown.Root."
},
{
"name": "onValueChange",
- "type": "(value: string) => void",
- "required": true,
+ "type": "((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) => void)",
+ "required": false,
"defaultValue": null,
- "description": "Reports the selected choice value, or an empty string when no country is selected."
+ "description": "Reports the selected identifier or null with cancellable event details. Call details.cancel() to preserve selection and keep the popup open."
},
{
"name": "open",
@@ -81,12 +144,26 @@
"defaultValue": null,
"description": "Controls whether the country popup is open."
},
+ {
+ "name": "openOnHover",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": "false",
+ "description": "Whether the popover should also open when the trigger is hovered."
+ },
+ {
+ "name": "optionsProps",
+ "type": "Omit<CountrySelectOptionsProps, \"closeOnSelect\" | \"searchLabel\" | \"noResultsLabel\" | \"searchProps\">",
+ "required": false,
+ "defaultValue": null,
+ "description": "Native props, ref, and render for the selection group div rendered by CountrySelect.Options."
+ },
{
"name": "popupProps",
- "type": "Omit<DropdownContentProps, \"children\" | \"aria-label\" | \"aria-labelledby\" | \"keepMounted\">",
+ "type": "Omit<DropdownContentProps, \"children\">",
"required": false,
"defaultValue": null,
- "description": "Dropdown popup positioning, portal, focus, and event options for host integration."
+ "description": "Dropdown.Content props, including native popup attributes, ref, render, positioning, portal destination, and keepMounted. Explicit popup accessible names override the trigger name. Children are owned by the picker."
},
{
"name": "ref",
@@ -106,9 +183,16 @@
"name": "searchLabel",
"type": "string",
"required": false,
- "defaultValue": "Search",
+ "defaultValue": null,
"description": "Placeholder and accessible name of the search input."
},
+ {
+ "name": "searchProps",
+ "type": "Omit<DropdownSearchProps, \"defaultValue\" | \"value\" | \"onValueChange\">",
+ "required": false,
+ "defaultValue": null,
+ "description": "Native search input props, ref, and render. Search value and change handling are owned by the picker."
+ },
{
"name": "style",
"type": "CSSProperties | ((state: PopoverTriggerState) => CSSProperties | undefined)",
@@ -118,10 +202,230 @@
},
{
"name": "value",
- "type": "string",
- "required": true,
+ "type": "string | null",
+ "required": false,
+ "defaultValue": null,
+ "description": "Controlled selected identifier. Null selects no country; undefined leaves selection uncontrolled."
+ },
+ {
+ "name": "wrapperProps",
+ "type": "Omit<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, \"children\">",
+ "required": false,
"defaultValue": null,
- "description": "Selected choice value. An empty string selects no country."
+ "description": "Native props and ref for the div around the trigger and its visible label. Children are owned by the picker."
+ }
+ ],
+ "parts": [
+ {
+ "name": "Root",
+ "props": [
+ {
+ "name": "children",
+ "type": "ReactNode",
+ "required": true,
+ "defaultValue": null,
+ "description": "Picker composition containing Dropdown.Root, CountrySelect.Trigger, and CountrySelect.Options. Root adds no DOM element."
+ },
+ {
+ "name": "countries",
+ "type": "readonly CountryChoice[]",
+ "required": true,
+ "defaultValue": null,
+ "description": "Prepared country choices with unique stable string values, caller-owned labels, and optional decorative flags and disabled states. An empty string is a valid choice value."
+ },
+ {
+ "name": "defaultValue",
+ "type": "string | null",
+ "required": false,
+ "defaultValue": "null",
+ "description": "Initial uncontrolled selected identifier. Defaults to null."
+ },
+ {
+ "name": "disabled",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": "false",
+ "description": "Prevents opening and selection. An empty country list is also disabled. The trigger stays focusable with aria-disabled."
+ },
+ {
+ "name": "noCountryLabel",
+ "type": "string",
+ "required": false,
+ "defaultValue": "No country",
+ "description": "Text for the null selection and its option. Defaults to No country."
+ },
+ {
+ "name": "onValueChange",
+ "type": "((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) => void)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Reports the selected identifier or null with event, reason, trigger, cancel and isCanceled details. Call cancel() to preserve selection and keep the popup open."
+ },
+ {
+ "name": "value",
+ "type": "string | null",
+ "required": false,
+ "defaultValue": null,
+ "description": "Controlled selected identifier. Null selects no country; undefined leaves selection uncontrolled."
+ }
+ ]
+ },
+ {
+ "name": "Trigger",
+ "props": [
+ {
+ "name": "children",
+ "type": "ReactNode",
+ "required": false,
+ "defaultValue": null,
+ "description": "Custom trigger content. Replaces the selected country presentation while retaining shared trigger behavior."
+ },
+ {
+ "name": "className",
+ "type": "string | ((state: PopoverTriggerState) => string | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Class applied to the trigger button."
+ },
+ {
+ "name": "closeDelay",
+ "type": "number",
+ "required": false,
+ "defaultValue": "0",
+ "description": "How long to wait before closing the popover that was opened on hover.\nSpecified in milliseconds.\n\nRequires the `openOnHover` prop."
+ },
+ {
+ "name": "delay",
+ "type": "number",
+ "required": false,
+ "defaultValue": "300",
+ "description": "How long to wait before the popover may be opened on hover. Specified in milliseconds.\n\nRequires the `openOnHover` prop."
+ },
+ {
+ "name": "id",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "ID of the trigger. In addition to being forwarded to the rendered element,\nit is also used to specify the active trigger for the popover in controlled mode (with the PopoverRoot `triggerId` prop)."
+ },
+ {
+ "name": "label",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Optional visible label that names the trigger."
+ },
+ {
+ "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": "openOnHover",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": "false",
+ "description": "Whether the popover should also open when the trigger is hovered."
+ },
+ {
+ "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. Custom components must forward the supplied props and ref."
+ },
+ {
+ "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": "wrapperProps",
+ "type": "Omit<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, \"children\">",
+ "required": false,
+ "defaultValue": null,
+ "description": "Native props and ref for the div around the trigger and its visible label. Children are owned by the picker."
+ }
+ ]
+ },
+ {
+ "name": "Options",
+ "props": [
+ {
+ "name": "aria-label",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Accessible name for the selection listbox. Overrides its default name."
+ },
+ {
+ "name": "aria-labelledby",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Accessible name references for the selection listbox. Defaults to the registered Dropdown title or trigger element."
+ },
+ {
+ "name": "className",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Class applied to the selection group div."
+ },
+ {
+ "name": "closeOnSelect",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": null,
+ "description": "Closes the popup after a selection. Defaults to true. Cancelled selection keeps it open."
+ },
+ {
+ "name": "noResultsLabel",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Text displayed when no choice matches the search. Defaults to No results."
+ },
+ {
+ "name": "ref",
+ "type": "Ref<HTMLDivElement>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Ref to the selection group element."
+ },
+ {
+ "name": "render",
+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, CountrySelectOptionsState>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Replaces the selection group div. Functions receive supplied props and { value, multiple: false } state, with the public string or null selection. Custom components must forward the supplied props and ref."
+ },
+ {
+ "name": "searchLabel",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Search placeholder and accessible name. Defaults to Search."
+ },
+ {
+ "name": "searchProps",
+ "type": "Omit<DropdownSearchProps, \"defaultValue\" | \"value\" | \"onValueChange\">",
+ "required": false,
+ "defaultValue": null,
+ "description": "Native search input props, ref, and render. Search value and change handling are owned by the picker."
+ }
+ ]
}
]
},
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/CountrySelect.tsx b/packages/twenty-ui/src/components/input/CountrySelect/CountrySelect.tsx
index b2e80bdffa4..7c5736b52ca 100644
--- a/packages/twenty-ui/src/components/input/CountrySelect/CountrySelect.tsx
+++ b/packages/twenty-ui/src/components/input/CountrySelect/CountrySelect.tsx
@@ -1,175 +1,10 @@
-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 { CountrySelectComponent } from './internal/CountrySelectComponent';
+import { CountrySelectRoot } from './internal/CountrySelectRoot';
+import { CountrySelectTrigger } from './internal/CountrySelectTrigger';
import { CountrySelectOptions } from './internal/CountrySelectOptions';
-import { getCountrySelectLabelledBy } from './internal/getCountrySelectLabelledBy';
-import { type CountrySelectProps } from './types/CountrySelectProps';
-import { doNotTranslate } from '@ui/utilities/internal/doNotTranslate';
-
-const skipTriggerActivation = (event: { preventBaseUIHandler?: () => void }) =>
- event.preventBaseUIHandler?.();
-
-export const CountrySelect = ({
- countries,
- value,
- onValueChange,
- label,
- searchLabel = doNotTranslate('Search'),
- noCountryLabel = doNotTranslate('No country'),
- noResultsLabel = doNotTranslate('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>
- );
-};
+export const CountrySelect = Object.assign(CountrySelectComponent, {
+ Root: CountrySelectRoot,
+ Trigger: CountrySelectTrigger,
+ Options: CountrySelectOptions,
+});
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
index cc8b323e6b7..0d49adf7b87 100644
--- a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/COUNTRY_CHOICES.ts
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/COUNTRY_CHOICES.ts
@@ -1,7 +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: '🇯🇵' },
+ { value: 'FR', label: 'France', flag: '🇫🇷' },
+ { value: 'BR', label: 'Brésil', flag: '🇧🇷' },
+ { value: 'JP', 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
index 8d069339304..2eb7ce4b19d 100644
--- 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
@@ -1,8 +1,11 @@
import { type Meta, type StoryObj } from '@storybook/react-vite';
import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+import { Dropdown } from '@ui/components/navigation/Dropdown/Dropdown';
import { A11Y_DEFER_COLOR_CONTRAST, ComponentDecorator } from '@ui/testing';
+import { CountrySelect } from '../CountrySelect';
+import { COUNTRY_CHOICES } from './COUNTRY_CHOICES';
import { CountrySelectExample } from './CountrySelectExample';
import { waitForCountryPopup } from './waitForCountryPopup';
@@ -25,6 +28,21 @@ const meta: Meta<typeof CountrySelectExample> = {
export default meta;
type Story = StoryObj<typeof CountrySelectExample>;
+export const VisibleLabelNamesListbox: Story = {
+ play: async ({ canvasElement }) => {
+ await userEvent.click(
+ within(canvasElement).getByRole('button', { name: 'Country' }),
+ );
+ const popup = await waitForCountryPopup({ canvasElement });
+
+ expect(
+ within(popup).getByRole('listbox', { name: 'Country' }),
+ ).toBeVisible();
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ },
+};
+
export const SelectedValueDescription: Story = {
args: { label: '', 'aria-label': 'Shipping country' },
render: (args) => (
@@ -44,7 +62,10 @@ export const SelectedValueDescription: Story = {
canvasElement,
name: 'Shipping country',
});
- const noCountry = within(popup).getByRole('button', { name: 'No country' });
+ expect(
+ within(popup).getByRole('listbox', { name: 'Shipping country' }),
+ ).toBeVisible();
+ const noCountry = within(popup).getByRole('option', { name: 'No country' });
expect(noCountry.querySelector('svg')?.parentElement).toHaveAttribute(
'aria-hidden',
@@ -71,6 +92,10 @@ export const TriggerNameFallback: Story = {
await userEvent.click(trigger);
const popup = await waitForCountryPopup({ canvasElement, name: 'France' });
+ expect(
+ within(popup).getByRole('listbox', { name: 'France' }),
+ ).toBeVisible();
+
await userEvent.keyboard('{Escape}');
await waitFor(() => expect(popup).not.toBeInTheDocument());
},
@@ -96,12 +121,94 @@ export const ExternalLabelledBy: Story = {
name: 'Destination country',
});
+ expect(
+ within(popup).getByRole('listbox', { name: 'Destination country' }),
+ ).toBeVisible();
expect(popup).toHaveAttribute('aria-labelledby', 'country-name');
await userEvent.keyboard('{Escape}');
await waitFor(() => expect(popup).not.toBeInTheDocument());
},
};
+export const PopupAriaLabelOverridesTriggerName: Story = {
+ args: {
+ label: '',
+ popupProps: { 'aria-label': 'Country choices' },
+ optionsProps: { 'aria-label': 'Supported countries' },
+ },
+ render: (args) => (
+ <>
+ <span id="country-name">Destination country</span>
+ <CountrySelectExample
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...args}
+ aria-labelledby="country-name"
+ />
+ </>
+ ),
+ play: async ({ canvasElement }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Destination country',
+ });
+
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({
+ canvasElement,
+ name: 'Country choices',
+ });
+
+ const listbox = within(popup).getByRole('listbox', {
+ name: 'Supported countries',
+ });
+
+ expect(listbox).not.toHaveAttribute('aria-labelledby');
+ expect(popup).toHaveAttribute('aria-label', 'Country choices');
+ expect(popup).not.toHaveAttribute('aria-labelledby');
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ },
+};
+
+export const PopupLabelledByOverridesTriggerName: Story = {
+ args: {
+ label: '',
+ 'aria-label': 'Destination country',
+ popupProps: { 'aria-labelledby': 'country-popup-name' },
+ optionsProps: { 'aria-labelledby': 'country-popup-name' },
+ },
+ render: (args) => (
+ <>
+ <span id="country-popup-name">Country choices</span>
+ <CountrySelectExample
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...args}
+ />
+ </>
+ ),
+ play: async ({ canvasElement }) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Destination country',
+ });
+
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({
+ canvasElement,
+ name: 'Country choices',
+ });
+
+ const listbox = within(popup).getByRole('listbox', {
+ name: 'Country choices',
+ });
+
+ expect(listbox).not.toHaveAttribute('aria-label');
+ expect(listbox).toHaveAttribute('aria-labelledby', 'country-popup-name');
+ expect(popup).toHaveAttribute('aria-labelledby', 'country-popup-name');
+ expect(popup).not.toHaveAttribute('aria-label');
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ },
+};
+
export const AriaLabelOverVisibleLabel: Story = {
args: { label: 'Country', 'aria-label': 'Shipping country' },
play: async ({ canvasElement }) => {
@@ -135,6 +242,9 @@ export const NonButtonTriggerLabel: Story = {
await userEvent.click(trigger);
const popup = await waitForCountryPopup({ canvasElement });
+ expect(
+ within(popup).getByRole('listbox', { name: 'Country' }),
+ ).toBeVisible();
await userEvent.keyboard('{Escape}');
await waitFor(() => expect(popup).not.toBeInTheDocument());
await waitFor(() => expect(trigger).toHaveFocus());
@@ -143,7 +253,7 @@ export const NonButtonTriggerLabel: Story = {
export const TruncatedCountryDisclosure: Story = {
args: {
- countries: [{ value: 'France', label: LONG_COUNTRY_LABEL, flag: '🇫🇷' }],
+ countries: [{ value: 'FR', label: LONG_COUNTRY_LABEL, flag: '🇫🇷' }],
},
play: async ({ canvasElement }) => {
const trigger = within(canvasElement).getByRole('button', {
@@ -165,3 +275,34 @@ export const TruncatedCountryDisclosure: Story = {
await waitFor(() => expect(tooltip).not.toBeInTheDocument());
},
};
+
+export const CompoundTitleNamesListbox: Story = {
+ render: () => (
+ <CountrySelect.Root countries={COUNTRY_CHOICES} defaultValue="FR">
+ <Dropdown.Root type="picker">
+ <CountrySelect.Trigger label="Country" />
+ <Dropdown.Content>
+ <Dropdown.Title>Destination countries</Dropdown.Title>
+ <CountrySelect.Options />
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </CountrySelect.Root>
+ ),
+ play: async ({ canvasElement }) => {
+ await userEvent.click(
+ within(canvasElement).getByRole('button', { name: 'Country' }),
+ );
+ const popup = await waitForCountryPopup({
+ canvasElement,
+ name: 'Destination countries',
+ });
+ const title = within(popup).getByText('Destination countries');
+ const listbox = within(popup).getByRole('listbox', {
+ name: 'Destination countries',
+ });
+
+ expect(listbox).toHaveAttribute('aria-labelledby', title.id);
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ },
+};
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
index 163eb90340b..185409de250 100644
--- 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
@@ -54,13 +54,13 @@ export const PointerSelection: Story = {
const popup = await waitForCountryPopup({ canvasElement });
const choices = within(popup);
- expect(choices.getByRole('button', { name: 'France' })).toHaveAttribute(
- 'aria-pressed',
+ expect(choices.getByRole('option', { name: 'France' })).toHaveAttribute(
+ 'aria-selected',
'true',
);
expect(choices.getByText('🇧🇷')).toHaveAttribute('aria-hidden', 'true');
- await userEvent.click(choices.getByRole('button', { name: 'Brésil' }));
- expect(args.onValueChange).toHaveBeenCalledWith('Brazil');
+ await userEvent.click(choices.getByRole('option', { name: 'Brésil' }));
+ expect(args.onValueChange).toHaveBeenCalledWith('BR', expect.any(Object));
await waitFor(() => expect(popup).not.toBeInTheDocument());
expect(trigger).toHaveTextContent('Brésil');
await waitFor(() => expect(trigger).toHaveFocus());
@@ -86,13 +86,13 @@ export const SearchAndKeyboard: Story = {
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();
+ expect(choices.queryByRole('option', { name: 'France' })).toBeNull();
+ expect(choices.queryByRole('option', { name: 'No country' })).toBeNull();
+ expect(choices.getByRole('option', { name: 'Brésil' })).toBeVisible();
await userEvent.keyboard('{Enter}');
- expect(args.onValueChange).toHaveBeenCalledWith('Brazil');
+ expect(args.onValueChange).toHaveBeenCalledWith('BR', expect.any(Object));
expect(choices.getByRole('searchbox')).toHaveValue('BRESIL');
- expect(choices.queryByRole('button', { name: 'France' })).toBeNull();
+ expect(choices.queryByRole('option', { name: 'France' })).toBeNull();
await waitFor(() => expect(popup).not.toBeInTheDocument());
await waitFor(() => expect(trigger).toHaveFocus());
await userEvent.keyboard('{Enter}');
@@ -102,14 +102,17 @@ export const SearchAndKeyboard: Story = {
expect(reopenedChoices.getByRole('searchbox')).toHaveValue('');
await userEvent.keyboard('{ArrowDown}');
expect(
- reopenedChoices.getByRole('button', { name: 'No country' }),
+ reopenedChoices.getByRole('option', { name: 'No country' }),
).toHaveFocus();
await userEvent.keyboard('{ArrowDown}');
expect(
- reopenedChoices.getByRole('button', { name: 'France' }),
+ reopenedChoices.getByRole('option', { name: 'France' }),
).toHaveFocus();
await userEvent.keyboard('{Enter}');
- expect(args.onValueChange).toHaveBeenLastCalledWith('France');
+ expect(args.onValueChange).toHaveBeenLastCalledWith(
+ 'FR',
+ expect.any(Object),
+ );
await waitFor(() => expect(reopenedPopup).not.toBeInTheDocument());
expect(trigger).toHaveTextContent('France');
},
@@ -126,23 +129,23 @@ export const SearchListsCountriesBeforeNoCountry: Story = {
const choices = within(popup);
const search = choices.getByRole('searchbox');
- expect(choices.getAllByRole('button')[0]).toHaveAccessibleName(
+ expect(choices.getAllByRole('option')[0]).toHaveAccessibleName(
'No country',
);
await userEvent.type(search, ' ');
- const unfilteredChoices = choices.getAllByRole('button');
+ const unfilteredChoices = choices.getAllByRole('option');
expect(unfilteredChoices).toHaveLength(4);
expect(unfilteredChoices[0]).toHaveAccessibleName('No country');
await userEvent.type(search, 'o');
- const matchingChoices = choices.getAllByRole('button');
+ const matchingChoices = choices.getAllByRole('option');
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');
+ expect(args.onValueChange).toHaveBeenCalledWith('JP', expect.any(Object));
await waitFor(() => expect(popup).not.toBeInTheDocument());
expect(trigger).toHaveTextContent('Japon');
},
@@ -159,17 +162,17 @@ export const ClearCountry: Story = {
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('');
+ expect(choices.getAllByRole('option')).toHaveLength(1);
+ await userEvent.click(choices.getByRole('option', { name: 'No country' }));
+ expect(args.onValueChange).toHaveBeenCalledWith(null, expect.any(Object));
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');
+ within(reopenedPopup).getByRole('option', { name: 'No country' }),
+ ).toHaveAttribute('aria-selected', 'true');
await userEvent.keyboard('{Escape}');
await waitFor(() => expect(reopenedPopup).not.toBeInTheDocument());
},
@@ -188,7 +191,7 @@ export const EmptySearchAndEscape: Story = {
await userEvent.type(search, 'Atlantis');
expect(choices.getByRole('status')).toHaveTextContent('No countries found');
- expect(choices.queryAllByRole('button')).toHaveLength(0);
+ expect(choices.queryAllByRole('option')).toHaveLength(0);
await userEvent.keyboard('{ArrowDown}{Enter}');
expect(args.onValueChange).not.toHaveBeenCalled();
expect(popup).toBeVisible();
@@ -228,7 +231,7 @@ export const ReopenDuringExitFade: Story = {
expect(reopenedPopup).toBe(popup);
expect(reopenedChoices.getByRole('searchbox')).toHaveValue('');
- expect(reopenedChoices.getAllByRole('button')).toHaveLength(4);
+ expect(reopenedChoices.getAllByRole('option')).toHaveLength(4);
await userEvent.keyboard('{Escape}');
await waitFor(() => expect(reopenedPopup).not.toBeInTheDocument(), {
timeout: 2000,
@@ -247,8 +250,8 @@ export const UnknownStoredValue: Story = {
await userEvent.click(trigger);
const popup = await waitForCountryPopup({ canvasElement });
- for (const choice of within(popup).getAllByRole('button')) {
- expect(choice).toHaveAttribute('aria-pressed', 'false');
+ for (const choice of within(popup).getAllByRole('option')) {
+ expect(choice).toHaveAttribute('aria-selected', 'false');
}
await userEvent.keyboard('{Escape}');
@@ -266,7 +269,7 @@ export const DisabledAndUnavailable: Story = {
{...args}
label="Unavailable countries"
countries={[]}
- value=""
+ value={null}
/>
</>
),
@@ -371,7 +374,7 @@ export const IndependentInstances: Story = {
render: () => (
<>
<CountrySelectExample label="Billing country" />
- <CountrySelectExample label="Shipping country" value="Japan" />
+ <CountrySelectExample label="Shipping country" value="JP" />
</>
),
play: async ({ canvasElement }) => {
@@ -400,7 +403,7 @@ export const IndependentInstances: Story = {
expect(shippingPopup).toHaveAccessibleName('Shipping country');
expect(within(shippingPopup).getByRole('searchbox')).toHaveValue('');
await userEvent.click(
- within(shippingPopup).getByRole('button', { name: 'No country' }),
+ within(shippingPopup).getByRole('option', { name: 'No country' }),
);
await waitFor(() => expect(shippingPopup).not.toBeInTheDocument());
expect(shipping).toHaveTextContent('No country');
@@ -412,7 +415,7 @@ const ControlledCountryExample = ({
onValueChange,
onOpenChange,
}: Partial<CountrySelectProps>) => {
- const [value, setValue] = useState('France');
+ const [value, setValue] = useState<string | null>('FR');
const [open, setOpen] = useState(false);
return (
@@ -431,7 +434,7 @@ const ControlledCountryExample = ({
onOpenChange?.(nextOpen);
}}
/>
- <Button onClick={() => setValue('Japan')}>Apply Japan</Button>
+ <Button onClick={() => setValue('JP')}>Apply Japan</Button>
<Button onClick={() => setOpen(true)}>Open countries</Button>
</>
);
@@ -449,9 +452,9 @@ export const ControlledUpdates: Story = {
const popup = await waitForCountryPopup({ canvasElement });
await userEvent.click(
- within(popup).getByRole('button', { name: 'Brésil' }),
+ within(popup).getByRole('option', { name: 'Brésil' }),
);
- expect(args.onValueChange).toHaveBeenCalledWith('Brazil');
+ expect(args.onValueChange).toHaveBeenCalledWith('BR', expect.any(Object));
await waitFor(() => expect(popup).not.toBeInTheDocument());
expect(args.onOpenChange).toHaveBeenCalledWith(false);
expect(trigger).toHaveTextContent('France');
@@ -461,12 +464,12 @@ export const ControlledUpdates: Story = {
};
const ArgumentUpdatesExample = (props: Partial<CountrySelectProps>) => {
- const [value, setValue] = useState('France');
+ const [value, setValue] = useState<string | null>('FR');
return (
<>
<CountrySelectExample {...props} value={value} />
- <Button onClick={() => setValue('Japan')}>Apply Japan</Button>
+ <Button onClick={() => setValue('JP')}>Apply Japan</Button>
</>
);
};
@@ -480,7 +483,7 @@ export const ArgumentUpdates: Story = {
const popup = await waitForCountryPopup({ canvasElement });
await userEvent.click(
- within(popup).getByRole('button', { name: 'Brésil' }),
+ within(popup).getByRole('option', { name: 'Brésil' }),
);
await waitFor(() => expect(popup).not.toBeInTheDocument());
expect(canvas.getByRole('button', { name: 'Country' })).toHaveTextContent(
@@ -491,7 +494,7 @@ export const ArgumentUpdates: Story = {
'Japon',
);
expect(args.onValueChange).toHaveBeenCalledTimes(1);
- expect(args.onValueChange).toHaveBeenCalledWith('Brazil');
+ expect(args.onValueChange).toHaveBeenCalledWith('BR', expect.any(Object));
},
};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.parts.stories.tsx b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.parts.stories.tsx
new file mode 100644
index 00000000000..0ca0616f9ed
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.parts.stories.tsx
@@ -0,0 +1,269 @@
+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 { CountrySelectPartsExample } from './CountrySelectPartsExample';
+import { waitForCountryPopup } from './waitForCountryPopup';
+
+const meta: Meta<typeof CountrySelectPartsExample> = {
+ title: 'UI/Components/Input/CountrySelect/Parts',
+ component: CountrySelectPartsExample,
+ decorators: [ComponentDecorator],
+ parameters: {
+ container: { width: 320, height: 420 },
+ a11y: A11Y_DEFER_COLOR_CONTRAST,
+ },
+ args: { onValueChange: fn() },
+};
+
+export default meta;
+type Story = StoryObj<typeof CountrySelectPartsExample>;
+
+const assertSelectionParity: NonNullable<Story['play']> = async ({
+ canvasElement,
+ args,
+}) => {
+ const canvas = within(canvasElement);
+ const trigger = canvas.getByRole('button', { name: 'Country' });
+
+ expect(trigger).toHaveTextContent('France');
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement });
+ const choices = within(popup);
+
+ expect(choices.getByRole('option', { name: 'France' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ expect(choices.getByRole('option', { name: 'Canada' })).toBeDisabled();
+ await userEvent.keyboard('{ArrowDown}{ArrowDown}');
+ expect(args.onValueChange).not.toHaveBeenCalled();
+ await userEvent.click(choices.getByRole('option', { name: 'No country' }));
+ expect(args.onValueChange).toHaveBeenLastCalledWith(
+ null,
+ expect.objectContaining({
+ reason: 'item-press',
+ event: expect.objectContaining({ type: 'click' }),
+ trigger: choices.getByRole('option', { name: 'No country' }),
+ }),
+ );
+ await waitFor(() => expect(trigger).toHaveTextContent('No country'));
+ await waitFor(() => expect(trigger).toHaveFocus());
+
+ await userEvent.click(trigger);
+ const reopened = await waitForCountryPopup({ canvasElement });
+ expect(within(reopened).getByRole('searchbox')).toHaveValue('');
+ expect(
+ within(reopened).getByRole('option', { name: 'No country' }),
+ ).toHaveAttribute('aria-selected', 'true');
+ await userEvent.click(
+ within(reopened).getByRole('option', { name: 'Brésil' }),
+ );
+ await waitFor(() => expect(trigger).toHaveTextContent('Brésil'));
+ expect(args.onValueChange).toHaveBeenLastCalledWith('BR', expect.any(Object));
+ await waitFor(() => expect(trigger).toHaveFocus());
+
+ if (!args.controlled) {
+ return;
+ }
+
+ await userEvent.click(canvas.getByRole('button', { name: 'Apply Japan' }));
+ expect(trigger).toHaveTextContent('Japon');
+ await userEvent.click(trigger);
+ const externalPopup = await waitForCountryPopup({ canvasElement });
+ expect(
+ within(externalPopup).getByRole('option', { name: 'Japon' }),
+ ).toHaveAttribute('aria-selected', 'true');
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),
+ );
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Clear externally' }),
+ );
+ expect(trigger).toHaveTextContent('No country');
+ expect(args.onValueChange).toHaveBeenCalledTimes(2);
+};
+
+export const ShorthandUncontrolled: Story = { play: assertSelectionParity };
+export const CompoundUncontrolled: Story = {
+ args: { compound: true },
+ play: assertSelectionParity,
+};
+export const ShorthandControlled: Story = {
+ args: { controlled: true },
+ play: assertSelectionParity,
+};
+export const CompoundControlled: Story = {
+ args: { compound: true, controlled: true },
+ play: assertSelectionParity,
+};
+
+const assertCancellation: NonNullable<Story['play']> = async ({
+ canvasElement,
+ args,
+}) => {
+ const trigger = within(canvasElement).getByRole('button', {
+ name: 'Country',
+ });
+ await userEvent.click(trigger);
+ const popup = await waitForCountryPopup({ canvasElement });
+ await userEvent.click(
+ within(popup).getByRole('option', { name: 'No country' }),
+ );
+ expect(args.onValueChange).toHaveBeenCalledWith(
+ null,
+ expect.objectContaining({ isCanceled: true }),
+ );
+ expect(trigger).toHaveTextContent('France');
+ expect(popup).toBeVisible();
+ expect(within(popup).getByRole('option', { name: 'France' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),
+ );
+};
+
+export const ShorthandCancellation: Story = {
+ args: { cancelSelection: true },
+ play: assertCancellation,
+};
+export const CompoundCancellation: Story = {
+ args: { compound: true, cancelSelection: true },
+ play: assertCancellation,
+};
+
+export const DistinctEmptyAndReservedIdentifiers: Story = {
+ args: { compound: true, closeOnSelect: false },
+ 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.click(
+ choices.getByRole('option', { name: 'An empty identifier' }),
+ );
+ expect(args.onValueChange).toHaveBeenLastCalledWith('', expect.any(Object));
+ expect(trigger).toHaveTextContent('An empty identifier');
+ expect(choices.getByRole('option', { name: 'No country' })).toHaveAttribute(
+ 'aria-selected',
+ 'false',
+ );
+ await userEvent.click(
+ choices.getByRole('option', { name: 'A reserved-looking identifier' }),
+ );
+ expect(args.onValueChange).toHaveBeenLastCalledWith(
+ 'no-country',
+ expect.any(Object),
+ );
+ expect(trigger).toHaveTextContent('A reserved-looking identifier');
+ await userEvent.click(choices.getByRole('option', { name: 'No country' }));
+ expect(args.onValueChange).toHaveBeenLastCalledWith(
+ null,
+ expect.any(Object),
+ );
+ expect(trigger).toHaveTextContent('No country');
+ expect(popup).toBeVisible();
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),
+ );
+ },
+};
+
+const assertKeptSearchReset: NonNullable<Story['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.type(within(popup).getByRole('searchbox'), 'bresil');
+ expect(within(popup).queryByRole('option', { name: 'France' })).toBeNull();
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),
+ );
+ await userEvent.click(trigger);
+ const reopened = await waitForCountryPopup({ canvasElement });
+ expect(within(reopened).getByRole('searchbox')).toHaveValue('');
+ expect(
+ within(reopened).getByRole('option', { name: 'France' }),
+ ).toHaveAttribute('aria-selected', 'true');
+
+ if (args.compound) {
+ await userEvent.click(
+ within(reopened).getByRole('button', { name: 'Disable country picker' }),
+ );
+ }
+
+ if (!args.compound) {
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),
+ );
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Toggle disabled' }),
+ );
+ }
+
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),
+ );
+ expect(trigger).toHaveAttribute('aria-disabled', 'true');
+};
+
+export const ShorthandKeptSearchReset: Story = {
+ args: { keepMounted: true },
+ play: assertKeptSearchReset,
+};
+export const CompoundKeptSearchReset: Story = {
+ args: { compound: true, keepMounted: true },
+ play: assertKeptSearchReset,
+};
+
+export const CompoundDisabledHover: Story = {
+ args: { compound: true, openOnHover: true, onOpenChange: fn() },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ const trigger = canvas.getByRole('button', { name: 'Country' });
+ const toggleDisabled = canvas.getByRole('button', {
+ name: 'Toggle disabled',
+ });
+
+ await userEvent.hover(trigger);
+ const popup = await body.findByRole('dialog');
+ await waitFor(() => expect(popup).toBeVisible());
+ expect(args.onOpenChange).toHaveBeenCalledTimes(1);
+ expect(args.onOpenChange).toHaveBeenLastCalledWith(true);
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(args.onOpenChange).toHaveBeenCalledTimes(2);
+ expect(args.onOpenChange).toHaveBeenLastCalledWith(false);
+ await userEvent.unhover(trigger);
+ await userEvent.click(toggleDisabled);
+ expect(trigger).toHaveAttribute('aria-disabled', 'true');
+ expect(trigger).not.toBeDisabled();
+ await userEvent.hover(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(args.onOpenChange).toHaveBeenCalledTimes(2);
+ await userEvent.unhover(trigger);
+ await userEvent.click(toggleDisabled);
+ expect(trigger).not.toHaveAttribute('aria-disabled');
+ await userEvent.hover(trigger);
+ const reopenedPopup = await body.findByRole('dialog');
+ await waitFor(() => expect(reopenedPopup).toBeVisible());
+ expect(args.onOpenChange).toHaveBeenCalledTimes(3);
+ expect(args.onOpenChange).toHaveBeenLastCalledWith(true);
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(reopenedPopup).not.toBeInTheDocument());
+ },
+};
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
index 30cf0a9ad5d..8ddf224cccd 100644
--- a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.stories.tsx
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelect.stories.tsx
@@ -24,9 +24,9 @@ export const Display: Story = {
args: {
label: 'Shipping country',
countries: [
- { value: 'France', label: 'France', flag: '🇫🇷' },
- { value: 'Germany', label: 'Germany', flag: '🇩🇪' },
- { value: 'Japan', label: 'Japan', flag: '🇯🇵' },
+ { value: 'FR', label: 'France', flag: '🇫🇷' },
+ { value: 'DE', label: 'Germany', flag: '🇩🇪' },
+ { value: 'JP', label: 'Japan', flag: '🇯🇵' },
],
},
};
@@ -36,11 +36,11 @@ export const Disabled: Story = {
};
export const Empty: Story = {
- args: { value: '' },
+ args: { value: null },
};
export const ScopedTheme: Story = {
- args: { value: 'Japan', label: 'Scoped country' },
+ args: { value: 'JP', label: 'Scoped country' },
render: (args) => (
<ThemeProvider colorScheme="dark" applyToRoot={false}>
<div style={{ background: 'var(--t-background-primary)', padding: 16 }}>
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectAvailabilityExample.tsx b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectAvailabilityExample.tsx
index c951af7b72d..2bf756f0404 100644
--- a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectAvailabilityExample.tsx
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectAvailabilityExample.tsx
@@ -33,7 +33,7 @@ export const CountrySelectAvailabilityExample = ({
searchLabel="Search countries"
noCountryLabel="No country"
noResultsLabel="No countries found"
- value="France"
+ value="FR"
onValueChange={() => undefined}
open={controlled ? open : undefined}
onOpenChange={(nextOpen) => {
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectExample.tsx b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectExample.tsx
index 5b80d3a6a76..a490fb79d24 100644
--- a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectExample.tsx
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectExample.tsx
@@ -5,7 +5,7 @@ import { type CountrySelectProps } from '../types/CountrySelectProps';
import { COUNTRY_CHOICES } from './COUNTRY_CHOICES';
const StatefulCountrySelectExample = ({
- value: initialValue = 'France',
+ value: initialValue = 'FR',
onValueChange,
...props
}: Partial<CountrySelectProps>) => {
@@ -20,14 +20,16 @@ const StatefulCountrySelectExample = ({
noResultsLabel="No countries found"
{...props}
value={value}
- onValueChange={(nextValue) => {
- setValue(nextValue);
- onValueChange?.(nextValue);
+ onValueChange={(nextValue, eventDetails) => {
+ onValueChange?.(nextValue, eventDetails);
+ if (!eventDetails.isCanceled) {
+ setValue(nextValue);
+ }
}}
/>
);
};
export const CountrySelectExample = (props: Partial<CountrySelectProps>) => (
- <StatefulCountrySelectExample key={props.value} {...props} />
+ <StatefulCountrySelectExample key={props.value ?? 'empty'} {...props} />
);
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectPartsExample.tsx b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectPartsExample.tsx
new file mode 100644
index 00000000000..ca9fbf659cc
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__stories__/CountrySelectPartsExample.tsx
@@ -0,0 +1,103 @@
+import { useState } from 'react';
+
+import { Dropdown } from '@ui/components/navigation/Dropdown/Dropdown';
+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 CountrySelectPartsExampleProps = Pick<
+ CountrySelectProps,
+ 'onValueChange' | 'onOpenChange'
+> & {
+ compound?: boolean;
+ controlled?: boolean;
+ cancelSelection?: boolean;
+ closeOnSelect?: boolean;
+ keepMounted?: boolean;
+ openOnHover?: boolean;
+};
+
+export const CountrySelectPartsExample = ({
+ compound = false,
+ controlled = false,
+ cancelSelection = false,
+ closeOnSelect,
+ keepMounted,
+ openOnHover,
+ onValueChange,
+ onOpenChange,
+}: CountrySelectPartsExampleProps) => {
+ const [value, setValue] = useState<string | null>('FR');
+ const [disabled, setDisabled] = useState(false);
+ const handleValueChange: NonNullable<CountrySelectProps['onValueChange']> = (
+ nextValue,
+ eventDetails,
+ ) => {
+ onValueChange?.(nextValue, eventDetails);
+
+ if (cancelSelection) {
+ eventDetails.cancel();
+ return;
+ }
+
+ setValue(nextValue);
+ };
+ const countries = [
+ ...COUNTRY_CHOICES,
+ { value: 'CA', label: 'Canada', disabled: true },
+ { value: '', label: 'An empty identifier' },
+ { value: 'no-country', label: 'A reserved-looking identifier' },
+ ];
+ const rootProps = {
+ countries,
+ value: controlled ? value : undefined,
+ defaultValue: 'FR',
+ disabled,
+ onValueChange: handleValueChange,
+ };
+
+ return (
+ <>
+ {compound ? (
+ <CountrySelect.Root
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...rootProps}
+ >
+ <Dropdown.Root type="picker" onOpenChange={onOpenChange}>
+ <CountrySelect.Trigger
+ label="Country"
+ openOnHover={openOnHover}
+ delay={0}
+ />
+ <Dropdown.Content keepMounted={keepMounted}>
+ <CountrySelect.Options
+ searchLabel="Search countries"
+ closeOnSelect={closeOnSelect}
+ />
+ <Button onClick={() => setDisabled(true)}>
+ Disable country picker
+ </Button>
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </CountrySelect.Root>
+ ) : (
+ <CountrySelect
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...rootProps}
+ label="Country"
+ searchLabel="Search countries"
+ closeOnSelect={closeOnSelect}
+ popupProps={{ keepMounted }}
+ />
+ )}
+ <Button onClick={() => setValue('JP')}>Apply Japan</Button>
+ <Button onClick={() => setValue(null)}>Clear externally</Button>
+ <Button onClick={() => setDisabled(!disabled)}>Toggle disabled</Button>
+ <span role="status" aria-label="Selected identifier">
+ {value ?? 'null'}
+ </span>
+ </>
+ );
+};
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
index 4ad09dcef8b..b502d759e27 100644
--- a/packages/twenty-ui/src/components/input/CountrySelect/__tests__/CountrySelect.test.tsx
+++ b/packages/twenty-ui/src/components/input/CountrySelect/__tests__/CountrySelect.test.tsx
@@ -1,11 +1,21 @@
import { runComponentConformance } from '@test-utilities/conformance/runComponentConformance';
import { render, screen } from '@testing-library/react';
+import { createRef, type ReactNode } from 'react';
import { expect, it } from 'vitest';
+import { Dropdown } from '@ui/components/navigation/Dropdown/Dropdown';
import { ThemeProvider } from '@ui/theme/ThemeProvider';
import { CountrySelect } from '../CountrySelect';
+const FRANCE_CHOICE = { value: 'FR', label: 'France' };
+
+const CountrySelectWrapper = ({ children }: { children: ReactNode }) => (
+ <CountrySelect.Root countries={[FRANCE_CHOICE]} value="FR">
+ <Dropdown.Root type="picker">{children}</Dropdown.Root>
+ </CountrySelect.Root>
+);
+
runComponentConformance({
name: 'CountrySelect',
element: (
@@ -19,7 +29,138 @@ runComponentConformance({
renderPropTagName: 'button',
});
-const FRANCE_CHOICE = { value: 'France', label: 'France' };
+runComponentConformance({
+ name: 'CountrySelect.Trigger',
+ element: <CountrySelect.Trigger aria-label="Country" />,
+ wrapper: CountrySelectWrapper,
+ refInstanceOf: HTMLButtonElement,
+ renderPropTagName: 'button',
+});
+
+runComponentConformance({
+ name: 'CountrySelect.Options',
+ element: <CountrySelect.Options aria-label="Countries" />,
+ wrapper: CountrySelectWrapper,
+ refInstanceOf: HTMLDivElement,
+ renderPropTagName: 'div',
+});
+
+it.each([
+ { value: 'FR', expectedValue: 'FR' },
+ { value: null, expectedValue: 'null' },
+])(
+ 'exposes the public selected identifier $value to Options render',
+ ({ value, expectedValue }) => {
+ render(
+ <ThemeProvider colorScheme="light">
+ <CountrySelect.Root countries={[FRANCE_CHOICE]} value={value}>
+ <Dropdown.Root type="picker">
+ <CountrySelect.Options
+ render={(renderProps, state) => (
+ <div
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...renderProps}
+ data-selected-value={String(state.value)}
+ data-multiple={String(state.multiple)}
+ />
+ )}
+ />
+ </Dropdown.Root>
+ </CountrySelect.Root>
+ </ThemeProvider>,
+ );
+
+ expect(screen.getByRole('listbox')).toHaveAttribute(
+ 'data-selected-value',
+ expectedValue,
+ );
+ expect(screen.getByRole('listbox')).toHaveAttribute(
+ 'data-multiple',
+ 'false',
+ );
+ },
+);
+
+it.each([
+ {
+ value: null,
+ expectedLabel: 'No country',
+ unselectedLabel: 'Empty identifier',
+ },
+ {
+ value: '',
+ expectedLabel: 'Empty identifier',
+ unselectedLabel: 'No country',
+ },
+])(
+ 'distinguishes $value from an actual empty-string country identifier',
+ ({ value, expectedLabel, unselectedLabel }) => {
+ render(
+ <ThemeProvider colorScheme="light">
+ <CountrySelect.Root
+ countries={[FRANCE_CHOICE, { value: '', label: 'Empty identifier' }]}
+ value={value}
+ >
+ <Dropdown.Root type="picker">
+ <CountrySelect.Trigger aria-label="Country" />
+ <CountrySelect.Options />
+ </Dropdown.Root>
+ </CountrySelect.Root>
+ </ThemeProvider>,
+ );
+
+ expect(screen.getByRole('button', { name: 'Country' })).toHaveTextContent(
+ expectedLabel,
+ );
+ expect(screen.getByRole('option', { name: expectedLabel })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ expect(
+ screen.getByRole('option', { name: unselectedLabel }),
+ ).toHaveAttribute('aria-selected', 'false');
+ },
+);
+
+it('keeps wrapper customization and refs separate from the native shorthand trigger', () => {
+ const wrapperRef = createRef<HTMLDivElement>();
+ const triggerRef = createRef<HTMLButtonElement>();
+
+ render(
+ <ThemeProvider colorScheme="light">
+ <CountrySelect
+ countries={[FRANCE_CHOICE]}
+ defaultValue="FR"
+ aria-label="Country"
+ name="country"
+ title="Choose country"
+ className="country-trigger"
+ style={{ minWidth: 200 }}
+ ref={triggerRef}
+ wrapperProps={{
+ id: 'country-wrapper',
+ className: 'country-wrapper',
+ style: { maxWidth: 320 },
+ ref: wrapperRef,
+ }}
+ />
+ </ThemeProvider>,
+ );
+
+ const trigger = screen.getByRole('button', { name: 'Country' });
+
+ expect(triggerRef.current).toBe(trigger);
+ expect(trigger).toHaveAttribute('name', 'country');
+ expect(trigger).toHaveAttribute('title', 'Choose country');
+ expect(trigger).toHaveClass('country-trigger');
+ expect(trigger).toHaveStyle({ minWidth: '200px' });
+ expect(wrapperRef.current).toBe(trigger.parentElement);
+ expect(wrapperRef.current).toHaveAttribute('id', 'country-wrapper');
+ expect(wrapperRef.current).toHaveClass('country-wrapper');
+ expect(wrapperRef.current).toHaveStyle({ maxWidth: '320px' });
+ expect(wrapperRef.current).not.toHaveAttribute('name');
+ expect(wrapperRef.current).not.toHaveAttribute('aria-label');
+});
it.each([
{
@@ -57,6 +198,7 @@ it.each([
style={(state) => ({ opacity: state.disabled ? 0.5 : 1 })}
render={(renderProps, state) => (
<button
+ // oxlint-disable-next-line react/jsx-props-no-spreading
{...renderProps}
data-state-disabled={String(state.disabled)}
/>
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectComponent.tsx b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectComponent.tsx
new file mode 100644
index 00000000000..37981d437d6
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectComponent.tsx
@@ -0,0 +1,27 @@
+import { CountrySelectRoot } from './CountrySelectRoot';
+import { CountrySelectDropdown } from './CountrySelectDropdown';
+import { type CountrySelectProps } from '../types/CountrySelectProps';
+
+export const CountrySelectComponent = ({
+ countries,
+ value,
+ defaultValue,
+ onValueChange,
+ disabled,
+ noCountryLabel,
+ ...props
+}: CountrySelectProps) => (
+ <CountrySelectRoot
+ countries={countries}
+ value={value}
+ defaultValue={defaultValue}
+ onValueChange={onValueChange}
+ disabled={disabled}
+ noCountryLabel={noCountryLabel}
+ >
+ <CountrySelectDropdown
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...props}
+ />
+ </CountrySelectRoot>
+);
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectContext.ts b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectContext.ts
new file mode 100644
index 00000000000..441916a7bcb
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectContext.ts
@@ -0,0 +1,7 @@
+import { createContext } from 'react';
+
+import { type CountrySelectContextValue } from './CountrySelectContextValue';
+
+export const CountrySelectContext = createContext<
+ CountrySelectContextValue | undefined
+>(undefined);
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectContextValue.ts b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectContextValue.ts
new file mode 100644
index 00000000000..b5b2df362d8
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectContextValue.ts
@@ -0,0 +1,12 @@
+import { type CountrySelectRootProps } from '../types/CountrySelectRootProps';
+import { type PreparedCountryChoice } from './PreparedCountryChoice';
+
+export type CountrySelectContextValue = {
+ countries: readonly PreparedCountryChoice[];
+ selectedCountry: PreparedCountryChoice | undefined;
+ value: string | null;
+ disabled: boolean;
+ noCountryLabel: string;
+ selectionGroupId: string;
+ changeValue: NonNullable<CountrySelectRootProps['onValueChange']>;
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectDropdown.tsx b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectDropdown.tsx
new file mode 100644
index 00000000000..071502811d9
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectDropdown.tsx
@@ -0,0 +1,106 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { useState } from 'react';
+
+import { Dropdown } from '@ui/components/navigation/Dropdown/Dropdown';
+import { isDefined } from '@ui/utilities/utils/isDefined';
+
+import { type CountrySelectProps } from '../types/CountrySelectProps';
+import { CountrySelectAvailabilityEffect } from './CountrySelectAvailabilityEffect';
+import { CountrySelectTrigger } from './CountrySelectTrigger';
+import { CountrySelectOptions } from './CountrySelectOptions';
+import { useCountrySelectContextOrThrow } from './useCountrySelectContextOrThrow';
+
+type CountrySelectDropdownProps = Omit<
+ CountrySelectProps,
+ | 'countries'
+ | 'value'
+ | 'defaultValue'
+ | 'onValueChange'
+ | 'disabled'
+ | 'noCountryLabel'
+>;
+
+export const CountrySelectDropdown = ({
+ open: controlledOpen,
+ defaultOpen = false,
+ onOpenChange,
+ onEscapeKeyDown,
+ onInteractOutside,
+ defaultPage,
+ popupProps,
+ optionsProps,
+ searchLabel,
+ noResultsLabel,
+ searchProps,
+ closeOnSelect,
+ ...triggerProps
+}: CountrySelectDropdownProps) => {
+ const { disabled } = useCountrySelectContextOrThrow();
+ const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
+ const requestedOpen = controlledOpen ?? uncontrolledOpen;
+ const open = !disabled && requestedOpen;
+ const handleOpenChange = (nextOpen: boolean) => {
+ if (nextOpen && disabled) {
+ return;
+ }
+
+ setUncontrolledOpen(nextOpen);
+ onOpenChange?.(nextOpen);
+ };
+
+ const popupLabel = [triggerProps['aria-label'], triggerProps.label].find(
+ isNonEmptyString,
+ );
+ const hasPopupAccessibleName =
+ isDefined(popupProps?.['aria-label']) ||
+ isDefined(popupProps?.['aria-labelledby']);
+ const hasOptionsAccessibleName =
+ isDefined(optionsProps?.['aria-label']) ||
+ isDefined(optionsProps?.['aria-labelledby']);
+
+ return (
+ <>
+ <CountrySelectAvailabilityEffect
+ disabled={disabled}
+ open={requestedOpen}
+ onOpenChange={handleOpenChange}
+ />
+ <Dropdown.Root
+ type="picker"
+ open={open}
+ onOpenChange={handleOpenChange}
+ onEscapeKeyDown={onEscapeKeyDown}
+ onInteractOutside={onInteractOutside}
+ defaultPage={defaultPage}
+ >
+ <CountrySelectTrigger
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...triggerProps}
+ />
+ <Dropdown.Content
+ aria-label={hasPopupAccessibleName ? undefined : popupLabel}
+ aria-labelledby={
+ hasPopupAccessibleName ? undefined : triggerProps['aria-labelledby']
+ }
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...popupProps}
+ >
+ <CountrySelectOptions
+ aria-label={hasOptionsAccessibleName ? undefined : popupLabel}
+ aria-labelledby={
+ hasOptionsAccessibleName
+ ? undefined
+ : triggerProps['aria-labelledby']
+ }
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...optionsProps}
+ searchLabel={searchLabel}
+ noResultsLabel={noResultsLabel}
+ searchProps={searchProps}
+ closeOnSelect={closeOnSelect}
+ />
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </>
+ );
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectOptions.tsx b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectOptions.tsx
index 6f4f9007ef8..5c8536785a6 100644
--- a/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectOptions.tsx
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectOptions.tsx
@@ -1,83 +1,28 @@
-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 { useDropdownContext } from '@ui/components/navigation/Dropdown/internal/useDropdownContext';
-import styles from '../CountrySelect.module.scss';
-import { type CountryChoice } from '../types/CountryChoice';
+import { type CountrySelectOptionsProps } from '../types/CountrySelectOptionsProps';
+import { CountrySelectOptionsContent } from './CountrySelectOptionsContent';
-type CountrySelectOptionsProps = {
- countries: readonly CountryChoice[];
- value: string;
- onValueChange: (value: string) => void;
- searchLabel: string;
- noCountryLabel: string;
- noResultsLabel: string;
-};
+export const CountrySelectOptions = (props: CountrySelectOptionsProps) => {
+ const { open } = useDropdownContext();
+ const [previousOpen, setPreviousOpen] = useState(open);
+ const [openingCount, setOpeningCount] = useState(0);
-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>
- );
+ if (previousOpen !== open) {
+ setPreviousOpen(open);
+
+ if (open) {
+ setOpeningCount(openingCount + 1);
+ }
+ }
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>}
- </>
+ <CountrySelectOptionsContent
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...props}
+ key={openingCount}
+ />
);
};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectOptionsContent.tsx b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectOptionsContent.tsx
new file mode 100644
index 00000000000..e7a65a0dcc9
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectOptionsContent.tsx
@@ -0,0 +1,124 @@
+import {
+ isFunction,
+ isNonEmptyArray,
+ isNonEmptyString,
+ isNull,
+} from '@sniptt/guards';
+import { useState } from 'react';
+
+import { Dropdown } from '@ui/components/navigation/Dropdown/Dropdown';
+import { useDropdownContext } from '@ui/components/navigation/Dropdown/internal/useDropdownContext';
+import { IconCircleOff } from '@ui/icon';
+import { doNotTranslate } from '@ui/utilities/internal/doNotTranslate';
+import { normalizeSearchText } from '@ui/utilities/utils/normalizeSearchText';
+import { isDefined } from '@ui/utilities/utils/isDefined';
+
+import styles from '../CountrySelect.module.scss';
+import { type CountrySelectOptionsProps } from '../types/CountrySelectOptionsProps';
+import { getCountrySelectionValue } from './getCountrySelectionValue';
+import { NO_COUNTRY_SELECTION_VALUE } from './NO_COUNTRY_SELECTION_VALUE';
+import { useCountrySelectContextOrThrow } from './useCountrySelectContextOrThrow';
+
+export const CountrySelectOptionsContent = ({
+ searchLabel = doNotTranslate('Search'),
+ noResultsLabel = doNotTranslate('No results'),
+ searchProps,
+ render,
+ ...props
+}: CountrySelectOptionsProps) => {
+ const {
+ countries,
+ value,
+ changeValue,
+ disabled,
+ noCountryLabel,
+ selectionGroupId,
+ } = useCountrySelectContextOrThrow();
+ const { titleId, triggerId } = useDropdownContext();
+ const hasAccessibleName =
+ isDefined(props['aria-label']) || isDefined(props['aria-labelledby']);
+ const defaultAriaLabelledBy = hasAccessibleName
+ ? undefined
+ : (titleId ?? triggerId);
+ const [search, setSearch] = useState('');
+ const normalizedSearch = normalizeSearchText(search.trim());
+ const isSearching = isNonEmptyString(normalizedSearch);
+ const filteredCountries = countries.filter((country) =>
+ country.searchText.includes(normalizedSearch),
+ );
+ const showNoCountry =
+ normalizeSearchText(noCountryLabel).includes(normalizedSearch);
+ const hasResults = showNoCountry || isNonEmptyArray(filteredCountries);
+ const noCountryOption = showNoCountry && (
+ <Dropdown.OptionItem
+ value={NO_COUNTRY_SELECTION_VALUE}
+ disabled={disabled}
+ startIcon={
+ <span className={styles.flag} aria-hidden="true">
+ <IconCircleOff />
+ </span>
+ }
+ >
+ {noCountryLabel}
+ </Dropdown.OptionItem>
+ );
+
+ return (
+ <>
+ <Dropdown.Search
+ placeholder={searchLabel}
+ aria-label={searchLabel}
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...searchProps}
+ value={search}
+ onValueChange={setSearch}
+ disabled={disabled || searchProps?.disabled}
+ />
+ {hasResults && <Dropdown.Separator />}
+ <Dropdown.SelectionGroup
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...props}
+ aria-labelledby={props['aria-labelledby'] ?? defaultAriaLabelledBy}
+ render={
+ isFunction(render)
+ ? (renderProps) => render(renderProps, { value, multiple: false })
+ : render
+ }
+ id={selectionGroupId}
+ value={
+ isNull(value)
+ ? NO_COUNTRY_SELECTION_VALUE
+ : getCountrySelectionValue(value)
+ }
+ onValueChange={(nextValue, eventDetails) => {
+ const country = countries.find(
+ (choice) => choice.selectionValue === nextValue,
+ );
+ changeValue(country?.value ?? null, eventDetails);
+ }}
+ >
+ {hasResults && (
+ <Dropdown.Section scrollable>
+ {!isSearching && noCountryOption}
+ {filteredCountries.map((country) => (
+ <Dropdown.OptionItem
+ key={country.value}
+ value={country.selectionValue}
+ disabled={disabled || country.disabled}
+ startIcon={
+ <span className={styles.flag} aria-hidden="true">
+ {country.flag}
+ </span>
+ }
+ >
+ {country.label}
+ </Dropdown.OptionItem>
+ ))}
+ {isSearching && noCountryOption}
+ </Dropdown.Section>
+ )}
+ {!hasResults && <Dropdown.Empty>{noResultsLabel}</Dropdown.Empty>}
+ </Dropdown.SelectionGroup>
+ </>
+ );
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectRoot.tsx b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectRoot.tsx
new file mode 100644
index 00000000000..ab6d39a8b8f
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectRoot.tsx
@@ -0,0 +1,72 @@
+import { useControlled } from '@base-ui/utils/useControlled';
+import { isNonEmptyArray, isNull } from '@sniptt/guards';
+import { useId, useMemo } from 'react';
+
+import { doNotTranslate } from '@ui/utilities/internal/doNotTranslate';
+import { normalizeSearchText } from '@ui/utilities/utils/normalizeSearchText';
+
+import { type CountrySelectRootProps } from '../types/CountrySelectRootProps';
+import { type PreparedCountryChoice } from './PreparedCountryChoice';
+import { CountrySelectContext } from './CountrySelectContext';
+import { getCountrySelectionValue } from './getCountrySelectionValue';
+
+export const CountrySelectRoot = ({
+ countries,
+ value: controlledValue,
+ defaultValue = null,
+ onValueChange,
+ disabled = false,
+ noCountryLabel = doNotTranslate('No country'),
+ children,
+}: CountrySelectRootProps) => {
+ const selectionGroupId = useId();
+ const [value, setValue] = useControlled({
+ controlled: controlledValue,
+ default: defaultValue,
+ name: doNotTranslate('CountrySelect'),
+ state: 'value',
+ });
+ const preparedCountries = useMemo<PreparedCountryChoice[]>(
+ () =>
+ countries.map((country) => ({
+ ...country,
+ selectionValue: getCountrySelectionValue(country.value),
+ searchText: normalizeSearchText(country.label),
+ })),
+ [countries],
+ );
+ const countriesByValue = useMemo(
+ () => new Map(preparedCountries.map((country) => [country.value, country])),
+ [preparedCountries],
+ );
+ const isDisabled = disabled || !isNonEmptyArray(preparedCountries);
+
+ return (
+ <CountrySelectContext.Provider
+ value={{
+ countries: preparedCountries,
+ selectedCountry: isNull(value)
+ ? undefined
+ : countriesByValue.get(value),
+ value,
+ disabled: isDisabled,
+ noCountryLabel,
+ selectionGroupId,
+ changeValue: (nextValue, eventDetails) => {
+ if (isDisabled) {
+ eventDetails.cancel();
+ return;
+ }
+
+ onValueChange?.(nextValue, eventDetails);
+
+ if (!eventDetails.isCanceled) {
+ setValue(nextValue);
+ }
+ },
+ }}
+ >
+ {children}
+ </CountrySelectContext.Provider>
+ );
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectTrigger.tsx b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectTrigger.tsx
new file mode 100644
index 00000000000..7e6b36b4c61
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/CountrySelectTrigger.tsx
@@ -0,0 +1,140 @@
+import { type Popover as PopoverPrimitive } from '@base-ui/react/popover';
+import { clsx } from 'clsx';
+import { isFunction, isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';
+import { useId } from 'react';
+
+import { useDropdownContext } from '@ui/components/navigation/Dropdown/internal/useDropdownContext';
+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 './CountrySelectAvailabilityEffect';
+import { getCountrySelectLabelledBy } from './getCountrySelectLabelledBy';
+import { useCountrySelectContextOrThrow } from './useCountrySelectContextOrThrow';
+import { type CountrySelectTriggerProps } from '../types/CountrySelectTriggerProps';
+
+const skipTriggerActivation = (event: { preventBaseUIHandler?: () => void }) =>
+ event.preventBaseUIHandler?.();
+
+export const CountrySelectTrigger = ({
+ label,
+ wrapperProps,
+ children,
+ className,
+ style,
+ render,
+ onClick,
+ onMouseDown,
+ onPointerDown,
+ onKeyDown,
+ onKeyUp,
+ openOnHover,
+ id,
+ 'aria-label': ariaLabel,
+ 'aria-labelledby': ariaLabelledBy,
+ 'aria-describedby': ariaDescribedBy,
+ ...props
+}: CountrySelectTriggerProps) => {
+ const {
+ selectedCountry,
+ disabled: isDisabled,
+ noCountryLabel,
+ } = useCountrySelectContextOrThrow();
+ const { open, setOpen } = useDropdownContext();
+ 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 && !isDefined(children) ? selectedValueId : undefined,
+ ].filter(isNonEmptyString);
+ 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,
+ );
+
+ return (
+ <div
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...wrapperProps}
+ className={clsx(styles.root, wrapperProps?.className)}
+ >
+ <CountrySelectAvailabilityEffect
+ disabled={isDisabled}
+ open={open}
+ onOpenChange={setOpen}
+ />
+ {hasVisibleLabel && (
+ <label id={labelId} className={styles.label} htmlFor={triggerId}>
+ {label}
+ </label>
+ )}
+ <Dropdown.Trigger
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...props}
+ id={triggerId}
+ aria-label={nonEmptyAriaLabel}
+ aria-labelledby={labelledBy}
+ aria-describedby={
+ isNonEmptyArray(describedByIds) ? describedByIds.join(' ') : undefined
+ }
+ aria-disabled={isDisabled || undefined}
+ openOnHover={isDisabled ? false : openOnHover}
+ 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
+ }
+ >
+ {children ?? (
+ <>
+ <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>
+ </div>
+ );
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/NO_COUNTRY_SELECTION_VALUE.ts b/packages/twenty-ui/src/components/input/CountrySelect/internal/NO_COUNTRY_SELECTION_VALUE.ts
new file mode 100644
index 00000000000..2163f92d996
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/NO_COUNTRY_SELECTION_VALUE.ts
@@ -0,0 +1 @@
+export const NO_COUNTRY_SELECTION_VALUE = 'no-country';
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/PreparedCountryChoice.ts b/packages/twenty-ui/src/components/input/CountrySelect/internal/PreparedCountryChoice.ts
new file mode 100644
index 00000000000..346a1fbd49c
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/PreparedCountryChoice.ts
@@ -0,0 +1,6 @@
+import { type CountryChoice } from '../types/CountryChoice';
+
+export type PreparedCountryChoice = CountryChoice & {
+ selectionValue: string;
+ searchText: string;
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/getCountrySelectionValue.ts b/packages/twenty-ui/src/components/input/CountrySelect/internal/getCountrySelectionValue.ts
new file mode 100644
index 00000000000..d1e661109c7
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/getCountrySelectionValue.ts
@@ -0,0 +1,4 @@
+const COUNTRY_SELECTION_VALUE_PREFIX = 'country:';
+
+export const getCountrySelectionValue = (value: string) =>
+ `${COUNTRY_SELECTION_VALUE_PREFIX}${value}`;
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/internal/useCountrySelectContextOrThrow.ts b/packages/twenty-ui/src/components/input/CountrySelect/internal/useCountrySelectContextOrThrow.ts
new file mode 100644
index 00000000000..46ce8f5de92
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/internal/useCountrySelectContextOrThrow.ts
@@ -0,0 +1,18 @@
+import { useContext } from 'react';
+
+import { doNotTranslate } from '@ui/utilities/internal/doNotTranslate';
+import { isDefined } from '@ui/utilities/utils/isDefined';
+
+import { CountrySelectContext } from './CountrySelectContext';
+
+export const useCountrySelectContextOrThrow = () => {
+ const context = useContext(CountrySelectContext);
+
+ if (!isDefined(context)) {
+ throw new Error(
+ doNotTranslate('CountrySelect parts must be inside CountrySelect.Root'),
+ );
+ }
+
+ return context;
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/types/CountryChoice.ts b/packages/twenty-ui/src/components/input/CountrySelect/types/CountryChoice.ts
index da23202fd9e..712b74c5889 100644
--- a/packages/twenty-ui/src/components/input/CountrySelect/types/CountryChoice.ts
+++ b/packages/twenty-ui/src/components/input/CountrySelect/types/CountryChoice.ts
@@ -4,4 +4,5 @@ export type CountryChoice = {
value: string;
label: string;
flag?: ReactNode;
+ disabled?: boolean;
};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectOptionsProps.ts b/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectOptionsProps.ts
new file mode 100644
index 00000000000..8e649ae9e0a
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectOptionsProps.ts
@@ -0,0 +1,25 @@
+import { type useRender } from '@base-ui/react/use-render';
+
+import { type DropdownSearchProps } from '@ui/components/navigation/Dropdown/types/DropdownSearchProps';
+import { type DropdownSelectionGroupProps } from '@ui/components/navigation/Dropdown/types/DropdownSelectionGroupProps';
+
+import { type CountrySelectOptionsState } from './CountrySelectOptionsState';
+
+export type CountrySelectOptionsProps = Omit<
+ DropdownSelectionGroupProps,
+ | 'id'
+ | 'children'
+ | 'multiple'
+ | 'value'
+ | 'defaultValue'
+ | 'onValueChange'
+ | 'render'
+> & {
+ render?: useRender.ComponentProps<'div', CountrySelectOptionsState>['render'];
+ searchLabel?: string;
+ noResultsLabel?: string;
+ searchProps?: Omit<
+ DropdownSearchProps,
+ 'value' | 'defaultValue' | 'onValueChange'
+ >;
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectOptionsState.ts b/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectOptionsState.ts
new file mode 100644
index 00000000000..8eeffa2a8ab
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectOptionsState.ts
@@ -0,0 +1,4 @@
+export type CountrySelectOptionsState = {
+ value: string | null;
+ multiple: false;
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectProps.ts b/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectProps.ts
index ea2466d16ee..0076376428a 100644
--- a/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectProps.ts
+++ b/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectProps.ts
@@ -1,29 +1,20 @@
import { type DropdownContentProps } from '@ui/components/navigation/Dropdown/types/DropdownContentProps';
-import { type DropdownTriggerProps } from '@ui/components/navigation/Dropdown/types/DropdownTriggerProps';
+import { type DropdownRootProps } from '@ui/components/navigation/Dropdown/types/DropdownRootProps';
-import { type CountryChoice } from './CountryChoice';
+import { type CountrySelectRootProps } from './CountrySelectRootProps';
+import { type CountrySelectTriggerProps } from './CountrySelectTriggerProps';
+import { type CountrySelectOptionsProps } from './CountrySelectOptionsProps';
-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'
- >;
-};
+export type CountrySelectProps = Omit<CountrySelectRootProps, 'children'> &
+ CountrySelectTriggerProps &
+ Omit<DropdownRootProps, 'children' | 'type' | 'multiple'> &
+ Pick<
+ CountrySelectOptionsProps,
+ 'searchLabel' | 'noResultsLabel' | 'searchProps' | 'closeOnSelect'
+ > & {
+ popupProps?: Omit<DropdownContentProps, 'children'>;
+ optionsProps?: Omit<
+ CountrySelectOptionsProps,
+ 'searchLabel' | 'noResultsLabel' | 'searchProps' | 'closeOnSelect'
+ >;
+ };
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectRootProps.ts b/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectRootProps.ts
new file mode 100644
index 00000000000..9007e33c7c6
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectRootProps.ts
@@ -0,0 +1,18 @@
+import { type ReactNode } from 'react';
+
+import { type DropdownSelectionGroupChangeEventDetails } from '@ui/components/navigation/Dropdown/types/DropdownSelectionGroupChangeEventDetails';
+
+import { type CountryChoice } from './CountryChoice';
+
+export type CountrySelectRootProps = {
+ countries: readonly CountryChoice[];
+ value?: string | null;
+ defaultValue?: string | null;
+ onValueChange?: (
+ value: string | null,
+ eventDetails: DropdownSelectionGroupChangeEventDetails,
+ ) => void;
+ disabled?: boolean;
+ noCountryLabel?: string;
+ children: ReactNode;
+};
diff --git a/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectTriggerProps.ts b/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectTriggerProps.ts
new file mode 100644
index 00000000000..3d339541343
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/CountrySelect/types/CountrySelectTriggerProps.ts
@@ -0,0 +1,11 @@
+import { type ComponentPropsWithRef } from 'react';
+
+import { type DropdownTriggerProps } from '@ui/components/navigation/Dropdown/types/DropdownTriggerProps';
+
+export type CountrySelectTriggerProps = Omit<
+ DropdownTriggerProps,
+ 'value' | 'defaultValue' | 'onChange' | 'disabled'
+> & {
+ label?: string;
+ wrapperProps?: Omit<ComponentPropsWithRef<'div'>, 'children'>;
+};
diff --git a/packages/twenty-ui/src/components/input/index.ts b/packages/twenty-ui/src/components/input/index.ts
index 6f1f35c2719..cbd6be94c88 100644
--- a/packages/twenty-ui/src/components/input/index.ts
+++ b/packages/twenty-ui/src/components/input/index.ts
@@ -9,7 +9,11 @@
export { CountrySelect } from './CountrySelect/CountrySelect';
export type { CountryChoice } from './CountrySelect/types/CountryChoice';
+export type { CountrySelectOptionsProps } from './CountrySelect/types/CountrySelectOptionsProps';
+export type { CountrySelectOptionsState } from './CountrySelect/types/CountrySelectOptionsState';
export type { CountrySelectProps } from './CountrySelect/types/CountrySelectProps';
+export type { CountrySelectRootProps } from './CountrySelect/types/CountrySelectRootProps';
+export type { CountrySelectTriggerProps } from './CountrySelect/types/CountrySelectTriggerProps';
export { CurrencyPicker } from './CurrencyPicker/CurrencyPicker';
export type { CurrencyPickerChangeEventDetails } from './CurrencyPicker/types/CurrencyPickerChangeEventDetails';
export type { CurrencyPickerOption } from './CurrencyPicker/types/CurrencyPickerOption';