Skip to content

The open alternative to Salesforce, designed for AI.

Unify PhoneCountryPicker composition (#28169)

Raphaël Bosi07d4f8425298
diff --git a/packages/twenty-docs/snippets/ui/generated/components/input/phone-country-picker.mdx b/packages/twenty-docs/snippets/ui/generated/components/input/phone-country-picker.mdx
index 6e56dedda55..7ff701db0d9 100644
--- a/packages/twenty-docs/snippets/ui/generated/components/input/phone-country-picker.mdx
+++ b/packages/twenty-docs/snippets/ui/generated/components/input/phone-country-picker.mdx
@@ -11,12 +11,136 @@
* npx nx generate:ui twenty-docs
*/}
+<ParamField body="aria-label" type="string" required>
+ Required accessible name for the country selector trigger.
+</ParamField>
+
+<ParamField body="children" type="ReactNode">
+ Optional trigger content replacing the default country flag or world icon and chevron.
+</ParamField>
+
+<ParamField body="className" type="string | ((state: PopoverTriggerState) =&gt; string | undefined)">
+ CSS class applied to the element, or a function that
+ returns a class based on the component's state.
+</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 dropdown after an accepted selection. Defaults to true.
+</ParamField>
+
+<ParamField body="contentProps" type="Omit&lt;DropdownContentProps, &quot;children&quot;&gt;">
+ Props for the internally assembled Dropdown.Content, including its accessible name, placement, width and popup ref.
+</ParamField>
+
+<ParamField body="countries" type="readonly PhoneCountryOption[]" required>
+ Prepared choices with a unique stable value, localized label, digits-only calling code without a plus sign, decorative flag node and optional disabled state. Matching choices retain their supplied order after the selected country.
+</ParamField>
+
+<ParamField body="defaultValue" type="string | null">
+ Initial uncontrolled country identifier. Omit it or use null to start empty.
+</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">
+ Disables the trigger, search and country selection.
+</ParamField>
+
+<ParamField body="dropdownProps" type="Omit&lt;DropdownRootProps, &quot;children&quot; | &quot;type&quot; | &quot;multiple&quot;&gt;">
+ Props for the internally assembled Dropdown.Root, including controlled open state and open-change events. The picker fixes its type to picker.
+</ParamField>
+
+<ParamField body="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="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="onValueChange" type="((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) =&gt; void)">
+ Receives the requested country identifier or null and Dropdown.SelectionGroup event details, including reason, event, trigger and cancel(). Cancel before updating controlled state to reject a selection.
+</ParamField>
+
+<ParamField body="openOnHover" type="boolean" default="false">
+ Whether the popover should also open when the trigger is hovered.
+</ParamField>
+
+<ParamField body="optionsProps" type="PhoneCountryPickerOptionsProps">
+ Props for the options root div, including native attributes, ref, render, searchLabel, listLabel and emptyLabel. Search matches normalized labels and identifiers, or calling codes with an optional leading plus sign. Surrounding query whitespace is trimmed.
+</ParamField>
+
+<ParamField body="ref" type="Ref&lt;HTMLButtonElement&gt;">
+ Ref to the trigger button, or the element composed through render.
+</ParamField>
+
+<ParamField body="render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, PopoverTriggerState&gt;">
+ Composes the trigger with an element or render callback. Native attributes, handlers, className, style and ref target the trigger.
+</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 | null">
+ Controlled country identifier. Use null to clear the selection. Labels and calling codes do not replace this value.
+</ParamField>
+
+### PhoneCountryPicker.Root
+
+<ParamField body="Root.children" type="ReactNode" required>
+ A Dropdown.Root with type="picker", its Trigger, Content and Options. Root shares prepared data and selection and renders no DOM node.
+</ParamField>
+
+<ParamField body="Root.closeOnSelect" type="boolean" default="true">
+ Closes the composed Dropdown after an accepted selection. Defaults to true.
+</ParamField>
+
+<ParamField body="Root.countries" type="readonly PhoneCountryOption[]" required>
+ Prepared choices shared by Trigger and Options, with unique stable values, localized labels, digits-only calling codes without a plus sign, decorative flag nodes and optional disabled states.
+</ParamField>
+
+<ParamField body="Root.defaultValue" type="string | null" default="null">
+ Initial uncontrolled country identifier. Omit it or use null to start empty.
+</ParamField>
+
+<ParamField body="Root.disabled" type="boolean" default="false">
+ Disables the composed trigger, search and country selection.
+</ParamField>
+
+<ParamField body="Root.onValueChange" type="((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) =&gt; void)">
+ Receives the requested identifier or null and Dropdown.SelectionGroup event details, including reason, event, trigger and cancel(). Cancel before updating controlled state to reject a selection.
+</ParamField>
+
+<ParamField body="Root.value" type="string | null">
+ Controlled country identifier shared by the parts. Use null to clear the selection.
+</ParamField>
+
### PhoneCountryPicker.Trigger
<ParamField body="Trigger.aria-label" type="string" required>
Required accessible name for the country selector button.
</ParamField>
+<ParamField body="Trigger.children" type="ReactNode">
+ Optional trigger content replacing the selected country flag or empty world icon and chevron. The selected label comes from Root.
+</ParamField>
+
<ParamField body="Trigger.className" type="string | ((state: PopoverTriggerState) =&gt; string | undefined)">
CSS class applied to the element, or a function that
returns a class based on the component's state.
@@ -29,10 +153,6 @@
Requires the `openOnHover` prop.
</ParamField>
-<ParamField body="Trigger.country" type="PhoneCountryOption">
- Prepared country whose flag is displayed and whose label describes the trigger. Omit it to show a world icon.
-</ParamField>
-
<ParamField body="Trigger.delay" type="number" default="300">
How long to wait before the popover may be opened on hover. Specified in milliseconds.
@@ -40,7 +160,7 @@
</ParamField>
<ParamField body="Trigger.disabled" type="boolean">
- Disables the native trigger button.
+ Disables the native trigger button in addition to Root.disabled.
</ParamField>
<ParamField body="Trigger.id" type="string">
@@ -48,10 +168,24 @@
it is also used to specify the active trigger for the popover in controlled mode (with the PopoverRoot `triggerId` prop).
</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 button, or the element composed through render.
+</ParamField>
+
+<ParamField body="Trigger.render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, PopoverTriggerState&gt;">
+ Composes the Dropdown trigger with an element or render callback. Native attributes, handlers, className, style and ref target this element.
+</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.
@@ -59,22 +193,26 @@
### PhoneCountryPicker.Options
-<ParamField body="Options.countries" type="readonly PhoneCountryOption[]" required>
- Prepared choices with a unique value, localized label, calling code without a plus sign, and flag node. The supplied order is preserved after the matching selected country.
+<ParamField body="Options.disabled" type="boolean">
+ Disables search and selection in addition to Root.disabled.
</ParamField>
<ParamField body="Options.emptyLabel" type="string" default="No results">
- Status message shown when no country names match. Defaults to No results.
+ Status message shown when no country label, identifier or calling code matches. Defaults to No results.
</ParamField>
-<ParamField body="Options.onValueChange" type="(value: string) =&gt; void" required>
- Called with the chosen country value. The host owns the selected country and phone number.
+<ParamField body="Options.listLabel" type="string" default="Countries">
+ Accessible name of the country listbox, separate from the search field. Defaults to Countries.
</ParamField>
-<ParamField body="Options.searchLabel" type="string" default="Search">
- Accessible name and placeholder of the country search field. Defaults to Search.
+<ParamField body="Options.ref" type="Ref&lt;HTMLDivElement&gt;">
+ Ref to the options root div, or the element composed through render.
</ParamField>
-<ParamField body="Options.value" type="string">
- Selected country value. Its row appears first only while it matches the search.
+<ParamField body="Options.render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, {}&gt;">
+ Composes the non-interactive options root with an element or render callback. Native attributes, handlers, className, style and ref target this element. searchLabel names the internal search input.
+</ParamField>
+
+<ParamField body="Options.searchLabel" type="string" default="Search">
+ Accessible name and placeholder of the country search field. Defaults to Search. Search matches normalized labels and identifiers, or calling codes with an optional leading plus sign. Surrounding query whitespace is trimmed.
</ParamField>
diff --git a/packages/twenty-docs/ui/components/input/phone-country-picker.mdx b/packages/twenty-docs/ui/components/input/phone-country-picker.mdx
index 5fe6614363f..278cc77e884 100644
--- a/packages/twenty-docs/ui/components/input/phone-country-picker.mdx
+++ b/packages/twenty-docs/ui/components/input/phone-country-picker.mdx
@@ -1,12 +1,12 @@
---
title: PhoneCountryPicker
-description: Country flags, calling codes, search, and selection for phone inputs.
+description: A complete phone country picker and composable parts sharing country data and selection.
---
import { StoryEmbed } from '/snippets/ui/StoryEmbed.mdx';
import PhoneCountryPickerReference from '/snippets/ui/generated/components/input/phone-country-picker.mdx';
-`PhoneCountryPicker` displays a country flag trigger and searchable calling-code choices. Compose its two parts inside [Dropdown](/ui/components/navigation/dropdown). Your application supplies country data, owns the selected value, and handles the phone number.
+`PhoneCountryPicker` combines a country flag trigger, popup, search and calling-code choices. Use the complete component for ordinary selection, or compose `Root`, `Trigger` and `Options` with [Dropdown](/ui/components/navigation/dropdown) when you need a custom popup. Both forms share the same prepared countries and selection.
<StoryEmbed
storyId="ui-input-phonecountrypicker--display"
@@ -16,7 +16,7 @@ import PhoneCountryPickerReference from '/snippets/ui/generated/components/input
## Usage
-Each `PhoneCountryOption` has a unique `value`, a localized country `label`, a `callingCode` without the leading plus sign, and a `flag` node. Supply the country list in the order you want it displayed. The picker adds the plus sign to calling-code labels and keeps calling codes left to right next to right-to-left country names.
+Supply your own country data and a trigger accessible name. Use `value` with `onValueChange` for controlled selection, or `defaultValue` for uncontrolled selection. `null` represents no selected country.
```tsx
import { useState } from 'react';
@@ -24,7 +24,6 @@ import {
PhoneCountryPicker,
type PhoneCountryOption,
} from 'twenty-ui/components/input';
-import { Dropdown } from 'twenty-ui/components/navigation';
const COUNTRIES: PhoneCountryOption[] = [
{ value: 'FR', label: 'France', callingCode: '33', flag: '🇫🇷' },
@@ -33,53 +32,90 @@ const COUNTRIES: PhoneCountryOption[] = [
];
export const PhoneCountryExample = () => {
- const [value, setValue] = useState('FR');
+ const [value, setValue] = useState<string | null>('FR');
return (
- <Dropdown.Root type="picker">
- <PhoneCountryPicker.Trigger
- aria-label="Phone country"
- country={COUNTRIES.find((country) => country.value === value)}
- />
- <Dropdown.Content width={280}>
- <PhoneCountryPicker.Options
- countries={COUNTRIES}
- value={value}
- onValueChange={setValue}
- searchLabel="Search countries"
- emptyLabel="No countries found"
- />
- </Dropdown.Content>
- </Dropdown.Root>
+ <PhoneCountryPicker
+ aria-label="Phone country"
+ countries={COUNTRIES}
+ value={value}
+ onValueChange={setValue}
+ contentProps={{ width: 280 }}
+ optionsProps={{
+ searchLabel: 'Search countries',
+ listLabel: 'Phone countries',
+ emptyLabel: 'No countries found',
+ }}
+ />
);
};
```
-The picker ships without a country catalog, flag asset package, or phone-input runtime. Full phone-number parsing, validation, formatting, drafts, and submission belong to the host application.
+Each `PhoneCountryOption` has a unique stable `value`, a localized country `label`, a digits-only `callingCode` without the leading plus sign, and a decorative `flag` node. It may also be `disabled`. Values are caller-owned identifiers, such as ISO country codes, and are returned unchanged. Labels, flags and calling codes are presentation data and do not become the selected identifier.
+
+The picker adds the plus sign and isolates calling codes left to right in option rows and overflow tooltips, including in right-to-left interfaces. Supply countries in the order you want them displayed. The selected country appears first while it matches the query; the remaining matches retain their supplied order.
+
+## Compound composition
+
+This is a breaking API change for existing compound callers. Add `PhoneCountryPicker.Root` around `Dropdown.Root`, move `countries`, `value` and `onValueChange` from `Options` to `Root`, and remove `Trigger.country`. Both parts now require `Root` and derive the selected country from it.
+
+`Root` owns countries and the controlled or uncontrolled selection. Put the shared `Dropdown.Root` inside it and compose the trigger, content and options. `Trigger` derives its selected flag and accessible description from `Root`; `Options` reads the same data and selection. Do not supply another country or selected value to those parts.
+
+```tsx
+import {
+ PhoneCountryPicker,
+ type PhoneCountryOption,
+} from 'twenty-ui/components/input';
+import { Dropdown } from 'twenty-ui/components/navigation';
+import { Button } from 'twenty-ui/primitives/input';
+
+const COUNTRIES: PhoneCountryOption[] = [
+ { value: 'FR', label: 'France', callingCode: '33', flag: '🇫🇷' },
+ { value: 'GB', label: 'United Kingdom', callingCode: '44', flag: '🇬🇧' },
+];
+
+<PhoneCountryPicker.Root countries={COUNTRIES} defaultValue="FR">
+ <Dropdown.Root type="picker">
+ <PhoneCountryPicker.Trigger
+ aria-label="Phone country"
+ render={<Button variant="outline" />}
+ />
+ <Dropdown.Content width={320}>
+ <PhoneCountryPicker.Options
+ searchLabel="Search countries"
+ listLabel="Phone countries"
+ emptyLabel="No countries found"
+ />
+ </Dropdown.Content>
+ </Dropdown.Root>
+</PhoneCountryPicker.Root>;
+```
+
+Keep one root per selector. The shared Dropdown owns opening, popup placement, pages, focus and search navigation. Use `dropdownProps` and `contentProps` on the complete picker, or configure the Dropdown parts directly in compound usage.
## Search and selection
-Search matches a substring of the country name, ignoring case and accents. It does not trim whitespace or match country values or calling codes. For example, `united` matches United Kingdom and United States, `reunion` matches Réunion, and `+44` does not match a calling code.
+Search matches substrings of the supplied country labels, stable identifiers and calling codes. Labels and identifiers use the shared `normalizeSearchText` normalization: lowercase text, Unicode NFD decomposition and script-aware accent handling. For example, `reunion` matches `Réunion` and `gb` matches a `GB` identifier. Meaningful distinctions in scripts are preserved according to that helper. Surrounding query whitespace is trimmed; internal whitespace is preserved. For calling-code search, one leading plus sign is optional, so `44`, `+44` and `" +44 "` match the supplied calling code `44`. Search does not parse a full phone number or infer a country from it.
-The selected country appears first when it matches the query. Remaining matches retain their supplied order. A query that excludes the current selection also removes its row. Empty results show the supplied status message.
+`onValueChange(value, eventDetails)` receives the requested identifier and the shared `Dropdown.SelectionGroup` details: `reason`, the native `event`, the selected option `trigger`, `cancel()` and `isCanceled`. Call `cancel()` before updating controlled state to reject the request. A canceled request preserves uncontrolled selection and leaves the popup open. Set `closeOnSelect={false}` to keep it open after an accepted selection. Selection changes do not modify any phone input value.
-The search field receives focus when the popup opens. Arrow keys and typed letters navigate options. Enter chooses the highlighted matching result after typing, or the focused option. Enter with an empty query does not select a country while focus remains in the search field. Pointer selection calls `onValueChange` with the country value. The dropdown closes after selection and returns focus according to its focus settings. Search clears when the popup content unmounts.
+Set `disabled` on the complete picker or `Root` to disable its trigger, search and selection. A disabled country stays visible and cannot be selected. `Trigger.disabled` and `Options.disabled` can additionally disable those individual parts.
-## Trigger and host integration
+## Native targets and labels
-`Trigger` is a native button with a required accessible name. Its flag and chevron are decorative, and the selected country label becomes its accessible description. Pass the selected `country` to display its flag, or omit it for a world icon. Native attributes, event handlers, `disabled`, and the button ref reach the trigger.
+The complete picker's native attributes, event handlers, `className`, `style`, `ref`, `render` and optional `children` target its trigger. `children` replaces the default flag or world icon and chevron. `contentProps` targets `Dropdown.Content`; `optionsProps` targets the options root div and supplies `searchLabel`, `listLabel` and `emptyLabel`. In compound usage, native props, refs and render composition target the corresponding `Trigger` button or `Options` div. `Root` renders no DOM node.
-Keep `Dropdown.Root` and `Dropdown.Content` in the host when coordinating controlled open state, popup placement, an explicit return-focus target, or application editing lifecycle. The shared parts use the root's picker behavior. Use one root per selector to keep instances independent.
+Supply localized country labels and the required trigger `aria-label`. The selected country label describes the trigger, while its flag and chevron are decorative. An empty selection shows a world icon. The popup takes the trigger name unless a `Dropdown.Title` or an explicit content label names it. `searchLabel` defaults to `Search` and names both the search field and its placeholder. `listLabel` defaults to `Countries` and names the listbox independently. `emptyLabel` defaults to `No results`.
-A phone library adapter maps the library's country value, country-change callback, and disabled or read-only state onto this composition, and supplies its own translated trigger label. The adapter owns the library-specific country values and any subsequent focus on the phone input.
+## Phone input integration
-## Labels
+The picker ships without a country catalog, flag asset package or phone-input runtime. The frontend adapter owns phone parsing, validation, formatting, editing drafts and persistence. Map the phone library's selected country to `Root.value` or the complete picker's `value`, and map country changes back through one callback. Keep the phone text in its existing owner when changing or clearing a country, or applying an external selected-country update.
-Supply localized country labels in `countries` and an accessible name on `Trigger`. The popup takes the trigger name unless a `Dropdown.Title` or an explicit label on `Dropdown.Content` names it. `searchLabel` defaults to `Search` and names both the search field and its placeholder. `emptyLabel` defaults to `No results`.
+Native form submission, reset, required, read-only and Field integration for this custom picker are deferred. The complete picker forwards native trigger attributes according to the Dropdown button contract.
## Front component renderer
-In [front components](/developers/extend/apps/layout/front-components), the React and Preact renderers display the trigger, its flag, and its disabled state. In both renderers the trigger opens the popup, but the popup renders into the sandbox document instead of the page, so its search and options are not visible yet. These limitations do not affect normal React rendering.
+The React and Preact gallery fixtures include the complete picker and compound composition. Portal placement, geometry, scrolling, dismissal and focus belong to the shared Dropdown and renderer integration. The picker does not introduce a separate renderer runtime.
## 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 35ef8b745dc..2c45fb6d7a5 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, PhoneCountryPicker, 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, 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. |
+| 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. |
| Responsive hooks | The sandbox `window.matchMedia` answers for the widget's own box, so `useIsMobile` follows the widget width rather than the browser viewport: a widget 768px wide or narrower gets the mobile layout, and Button drops its hotkey hint, on any screen. `useIsTouchDevice` follows the primary input of the host device, so it is `false` under the desktop Chromium that runs these stories. The fixture asserts both at a 1024px and a 400px widget width. |
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-phone-country-picker.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-phone-country-picker.front-component.tsx
index fe35da20ba5..0c101656c7a 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-phone-country-picker.front-component.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-phone-country-picker.front-component.tsx
@@ -1,10 +1,11 @@
-import { useState } from 'react';
+import { useRef, useState } from 'react';
import { defineFrontComponent } from 'twenty-sdk/define';
import {
PhoneCountryPicker,
type PhoneCountryOption,
} from 'twenty-ui/components/input';
import { Dropdown } from 'twenty-ui/components/navigation';
+import { Button } from 'twenty-ui/primitives/input';
import { Text } from 'twenty-ui/primitives/typography';
import { TwentyUiGalleryCard } from '@/__stories__/shared/front-components/twenty-ui-gallery-card';
@@ -13,56 +14,124 @@ const COUNTRIES: PhoneCountryOption[] = [
{ value: 'FR', label: 'France', callingCode: '33', flag: '🇫🇷' },
{ value: 'GB', label: 'United Kingdom', callingCode: '44', flag: '🇬🇧' },
{ value: 'US', label: 'United States', callingCode: '1', flag: '🇺🇸' },
+ { value: 'RE', label: 'Réunion', callingCode: '262', flag: '🇷🇪' },
+ {
+ value: 'SA',
+ label: 'المملكة العربية السعودية',
+ callingCode: '966',
+ flag: '🇸🇦',
+ },
+ {
+ value: 'JP',
+ label: 'Japan',
+ callingCode: '81',
+ flag: '🇯🇵',
+ disabled: true,
+ },
];
-const PhoneCountrySelector = ({
- label,
- initialValue,
- disabled = false,
-}: {
- label: string;
- initialValue?: string;
- disabled?: boolean;
-}) => {
- const [value, setValue] = useState(initialValue);
+const PhoneCountryPickerExample = () => {
+ const [primaryCountry, setPrimaryCountry] = useState<string | null>('US');
+ const [secondaryCountry, setSecondaryCountry] = useState<string | null>('FR');
+ const [primaryChanges, setPrimaryChanges] = useState(0);
+ const [secondaryChanges, setSecondaryChanges] = useState(0);
+ const [primaryEvent, setPrimaryEvent] = useState('none');
+ const [secondaryEvent, setSecondaryEvent] = useState('none');
+ const [referenceTargets, setReferenceTargets] = useState('unread');
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const optionsRef = useRef<HTMLDivElement>(null);
return (
- <>
- <Dropdown.Root type="picker">
- <PhoneCountryPicker.Trigger
- aria-label={label}
- country={COUNTRIES.find((country) => country.value === value)}
- disabled={disabled}
- />
- <Dropdown.Content aria-label={`Choose ${label}`} width={280}>
- <PhoneCountryPicker.Options
- countries={COUNTRIES}
- value={value}
- onValueChange={setValue}
- searchLabel={`Search ${label}`}
- emptyLabel="No countries found"
- />
- </Dropdown.Content>
- </Dropdown.Root>
- <Text role="status" aria-label={`${label} selection`}>
- Country: {value ?? 'none'}
+ <TwentyUiGalleryCard title="PhoneCountryPicker">
+ <PhoneCountryPicker
+ ref={triggerRef}
+ aria-label="Primary phone country"
+ data-phone-trigger="primary"
+ countries={COUNTRIES}
+ value={primaryCountry}
+ onValueChange={(value, eventDetails) => {
+ setPrimaryCountry(value);
+ setPrimaryChanges((count) => count + 1);
+ setPrimaryEvent(`${eventDetails.reason}/${eventDetails.event.type}`);
+ setReferenceTargets(
+ `${triggerRef.current?.getAttribute('data-phone-trigger') ?? 'missing'}/${optionsRef.current?.getAttribute('data-phone-options') ?? 'missing'}`,
+ );
+ }}
+ render={<Button variant="ghost" />}
+ contentProps={{
+ 'aria-label': 'Choose primary phone country',
+ width: 280,
+ }}
+ optionsProps={{
+ ref: optionsRef,
+ dir: 'rtl',
+ render: <section data-phone-options="primary" />,
+ searchLabel: 'Search primary phone country',
+ listLabel: 'Primary phone countries',
+ emptyLabel: 'No countries found',
+ }}
+ />
+ <PhoneCountryPicker.Root
+ countries={COUNTRIES}
+ defaultValue="FR"
+ onValueChange={(value, eventDetails) => {
+ if (value === 'GB') {
+ eventDetails.cancel();
+ setSecondaryEvent(`canceled/${eventDetails.reason}`);
+ return;
+ }
+
+ setSecondaryCountry(value);
+ setSecondaryChanges((count) => count + 1);
+ setSecondaryEvent(
+ `${eventDetails.reason}/${eventDetails.event.type}`,
+ );
+ }}
+ >
+ <Dropdown.Root type="picker">
+ <PhoneCountryPicker.Trigger aria-label="Secondary phone country" />
+ <Dropdown.Content
+ aria-label="Choose secondary phone country"
+ width={280}
+ >
+ <PhoneCountryPicker.Options
+ searchLabel="Search secondary phone country"
+ listLabel="Secondary phone countries"
+ emptyLabel="No countries found"
+ />
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </PhoneCountryPicker.Root>
+ <PhoneCountryPicker
+ aria-label="Disabled phone country"
+ countries={COUNTRIES}
+ disabled
+ />
+ <Button onClick={() => setPrimaryCountry(null)}>
+ Clear primary country
+ </Button>
+ <Button onClick={() => setPrimaryCountry('FR')}>
+ Set primary country to France
+ </Button>
+ <Text role="status" aria-label="Primary phone country selection">
+ Country: {primaryCountry ?? 'none'}; Changes: {primaryChanges}; Event:{' '}
+ {primaryEvent}; Refs: {referenceTargets}
+ </Text>
+ <Text role="status" aria-label="Secondary phone country selection">
+ Country: {secondaryCountry ?? 'none'}; Changes: {secondaryChanges};
+ Event: {secondaryEvent}
</Text>
- </>
+ <Text role="status" aria-label="Disabled phone country selection">
+ Country: none
+ </Text>
+ </TwentyUiGalleryCard>
);
};
-const PhoneCountryPickerExample = () => (
- <TwentyUiGalleryCard title="PhoneCountryPicker">
- <PhoneCountrySelector label="Primary phone country" initialValue="US" />
- <PhoneCountrySelector label="Secondary phone country" initialValue="FR" />
- <PhoneCountrySelector label="Disabled phone country" disabled />
- </TwentyUiGalleryCard>
-);
-
export default defineFrontComponent({
universalIdentifier: 'e87226d5-27b6-4876-979b-b9567e0b94f9',
name: 'twenty-ui-phone-country-picker',
description:
- 'Country search, calling-code selection, and independent phone selectors',
+ 'Complete and compound phone country pickers sharing search and selection',
component: PhoneCountryPickerExample,
});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/phoneCountryPickerTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/phoneCountryPickerTest.ts
index 54107d3981b..1cd3de61e0c 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/phoneCountryPickerTest.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/phoneCountryPickerTest.ts
@@ -1,8 +1,131 @@
+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';
-export const phoneCountryPickerTest: TwentyUiGalleryPlayFunction =
- createDropdownOpenTest({
- triggerName: 'Primary phone country',
- popupText: 'United Kingdom',
+export const phoneCountryPickerTest: TwentyUiGalleryPlayFunction = async ({
+ canvasElement,
+}) => {
+ const canvas = within(canvasElement);
+ const page = within(canvasElement.ownerDocument.body);
+ await expectFrontComponentMounted(canvas);
+
+ const primary = canvas.getByRole('button', { name: 'Primary phone country' });
+ const secondary = canvas.getByRole('button', {
+ name: 'Secondary phone country',
+ });
+ const disabled = canvas.getByRole('button', {
+ name: 'Disabled phone country',
+ });
+ const primaryStatus = canvas.getByRole('status', {
+ name: 'Primary phone country selection',
+ });
+ const secondaryStatus = canvas.getByRole('status', {
+ name: 'Secondary phone country selection',
+ });
+
+ await userEvent.click(disabled);
+ await waitForSandboxRoundTrip();
+ expect(disabled).toHaveAttribute('aria-expanded', 'false');
+
+ await userEvent.click(primary);
+ const japan = await page.findByRole('option', { name: 'Japan (+81)' });
+ await waitFor(() => expect(japan).toBeVisible());
+ expect(japan).toBeDisabled();
+ await userEvent.click(japan);
+ await waitForSandboxRoundTrip();
+ expect(primaryStatus).toHaveTextContent('Country: US; Changes: 0');
+ expect(primary).toHaveAttribute('aria-expanded', 'true');
+
+ expect(
+ page.getByRole('listbox', { name: 'Primary phone countries' }),
+ ).toBeVisible();
+ const primarySearch = page.getByRole('searchbox', {
+ name: 'Search primary phone country',
+ });
+ await userEvent.type(primarySearch, '+966');
+ await waitFor(() => expect(primarySearch).toHaveValue('+966'));
+ const saudiArabia = await page.findByRole('option', {
+ name: 'المملكة العربية السعودية (+966)',
+ });
+ expect(within(saudiArabia).getByText('+966')).toHaveAttribute('dir', 'ltr');
+ expect(saudiArabia.closest('[data-phone-options="primary"]')?.tagName).toBe(
+ 'SECTION',
+ );
+ expect(saudiArabia.closest('[data-phone-options="primary"]')).toHaveAttribute(
+ 'dir',
+ 'rtl',
+ );
+
+ await userEvent.clear(primarySearch);
+ await userEvent.type(primarySearch, ' +44 ');
+ await waitFor(() => expect(primarySearch).toHaveValue(' +44 '));
+ const unitedKingdom = await page.findByRole('option', {
+ name: 'United Kingdom (+44)',
+ });
+ await waitFor(() => {
+ expect(
+ page.queryByRole('option', { name: 'United States (+1)' }),
+ ).toBeNull();
+ });
+ await userEvent.click(unitedKingdom);
+ await waitFor(() => {
+ expect(primaryStatus).toHaveTextContent(
+ 'Country: GB; Changes: 1; Event: item-press/click; Refs: primary/primary',
+ );
+ expect(primary).toHaveAttribute('aria-expanded', 'false');
+ });
+ expect(primary).toHaveTextContent('🇬🇧');
+ expect(secondary).toHaveTextContent('🇫🇷');
+
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Clear primary country' }),
+ );
+ await waitFor(() => {
+ expect(primaryStatus).toHaveTextContent('Country: none; Changes: 1');
+ expect(primary).not.toHaveAccessibleDescription();
+ });
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Set primary country to France' }),
+ );
+ await waitFor(() => {
+ expect(primaryStatus).toHaveTextContent('Country: FR; Changes: 1');
+ expect(primary).toHaveAccessibleDescription('France');
+ });
+
+ await userEvent.click(secondary);
+ await page.findByRole('listbox', { name: 'Secondary phone countries' });
+ const secondarySearch = await page.findByRole('searchbox', {
+ name: 'Search secondary phone country',
+ });
+ await userEvent.type(secondarySearch, ' gb ');
+ await waitFor(() => expect(secondarySearch).toHaveValue(' gb '));
+ await userEvent.click(
+ await page.findByRole('option', { name: 'United Kingdom (+44)' }),
+ );
+ await waitFor(() => {
+ expect(secondaryStatus).toHaveTextContent(
+ 'Country: FR; Changes: 0; Event: canceled/item-press',
+ );
+ expect(secondary).toHaveAttribute('aria-expanded', 'true');
+ });
+ expect(secondary).toHaveAccessibleDescription('France');
+
+ await userEvent.clear(secondarySearch);
+ await userEvent.type(secondarySearch, ' reunion ');
+ await waitFor(() => expect(secondarySearch).toHaveValue(' reunion '));
+ await userEvent.click(
+ await page.findByRole('option', { name: 'Réunion (+262)' }),
+ );
+ await waitFor(() => {
+ expect(secondaryStatus).toHaveTextContent(
+ 'Country: RE; Changes: 1; Event: item-press/click',
+ );
+ expect(secondary).toHaveAccessibleDescription('Réunion');
+ expect(secondary).toHaveAttribute('aria-expanded', 'false');
});
+ expect(primary).toHaveAccessibleDescription('France');
+ expect(errorHandler).not.toHaveBeenCalled();
+};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/phoneCountryPickerTriggerTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/phoneCountryPickerTriggerTest.ts
index 4b9dea5832e..d4d78bb3146 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/phoneCountryPickerTriggerTest.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/phoneCountryPickerTriggerTest.ts
@@ -21,6 +21,7 @@ export const phoneCountryPickerTriggerTest: TwentyUiGalleryPlayFunction =
});
expect(primary).toHaveAttribute('type', 'button');
+ expect(primary).toHaveAttribute('data-phone-trigger', 'primary');
expect(primary).toHaveTextContent('🇺🇸');
expect(primary).toHaveAccessibleDescription('United States');
expect(secondary).toHaveTextContent('🇫🇷');
@@ -29,10 +30,10 @@ export const phoneCountryPickerTriggerTest: TwentyUiGalleryPlayFunction =
expect(disabled).not.toHaveAccessibleDescription();
expect(
canvas.getByRole('status', { name: 'Primary phone country selection' }),
- ).toHaveTextContent('Country: US');
+ ).toHaveTextContent('Country: US; Changes: 0; Event: none; Refs: unread');
expect(
canvas.getByRole('status', { name: 'Secondary phone country selection' }),
- ).toHaveTextContent('Country: FR');
+ ).toHaveTextContent('Country: FR; Changes: 0; Event: none');
expect(
canvas.getByRole('status', { name: 'Disabled phone country selection' }),
).toHaveTextContent('Country: none');
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/PhonesFieldInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/PhonesFieldInput.stories.tsx
index 7562e04d203..705e5a5c1b6 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/PhonesFieldInput.stories.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/PhonesFieldInput.stories.tsx
@@ -14,7 +14,7 @@ import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePush
import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';
import { FieldMetadataType } from '~/generated-metadata/graphql';
-const { FieldInputEventContextProviderWithJestMocks } =
+const { FieldInputEventContextProviderWithJestMocks, handleSubmitMocked } =
getFieldInputEventContextProviderWithJestMocks();
const PhoneValueSetterEffect = ({ value }: { value: FieldPhonesValue }) => {
@@ -228,3 +228,54 @@ export const CanNotSetPrimaryLinkAsPrimaryLink: Story = {
expect(setPrimaryOption).not.toBeInTheDocument();
},
};
+
+export const CountryChangePreservesStoredPhoneFields: Story = {
+ args: {
+ value: {
+ primaryPhoneCountryCode: 'FR',
+ primaryPhoneNumber: '642646272',
+ primaryPhoneCallingCode: '+33',
+ additionalPhones: [],
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+
+ await userEvent.hover(await canvas.findByText('+33 6 42 64 62 72'));
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'More options', expanded: false }),
+ );
+ await userEvent.click(await body.findByRole('menuitem', { name: 'Edit' }));
+ const phoneInput = await canvas.findByPlaceholderText('Phone');
+ expect(phoneInput).toHaveValue('+33 6 42 64 62 72');
+ await userEvent.click(canvas.getByRole('button', { name: 'Country' }));
+ const popup = await body.findByRole('dialog', { name: 'Country' });
+ await userEvent.type(
+ within(popup).getByRole('searchbox', { name: 'Search' }),
+ 'germany',
+ );
+ await userEvent.click(
+ await within(popup).findByRole('option', { name: 'Germany (+49)' }),
+ );
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ await waitFor(() => expect(phoneInput).toHaveFocus());
+ expect(phoneInput).toHaveValue('+49');
+ await userEvent.type(phoneInput, '30123456');
+ await userEvent.click(canvas.getByRole('button', { name: 'Save item' }));
+
+ expect(handleSubmitMocked).toHaveBeenLastCalledWith({
+ newValue: {
+ primaryPhoneCountryCode: 'DE',
+ primaryPhoneNumber: '30123456',
+ primaryPhoneCallingCode: '+49',
+ additionalPhones: [],
+ },
+ skipClose: true,
+ });
+ expect(canvas.getByRole('link', { name: /49/ })).toHaveAttribute(
+ 'href',
+ 'tel:+4930123456',
+ );
+ },
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormPhoneFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormPhoneFieldInput.tsx
index 24451a3901b..ba07bf4b0e3 100644
--- a/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormPhoneFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-form/components/RecordFormPhoneFieldInput.tsx
@@ -52,7 +52,7 @@ export const RecordFormPhoneFieldInput = ({
});
};
- const handleCountryCodeChange = (newCountryCode: string) => {
+ const handleCountryCodeChange = (newCountryCode: string | undefined) => {
setCountryCode(newCountryCode);
emitPhoneValue(newCountryCode, phoneNumber);
};
diff --git a/packages/twenty-front/src/modules/ui/input/components/__stories__/PhoneCountryPicker.stories.tsx b/packages/twenty-front/src/modules/ui/input/components/__stories__/PhoneCountryPicker.stories.tsx
index 8c955039864..57f0dc98b8e 100644
--- a/packages/twenty-front/src/modules/ui/input/components/__stories__/PhoneCountryPicker.stories.tsx
+++ b/packages/twenty-front/src/modules/ui/input/components/__stories__/PhoneCountryPicker.stories.tsx
@@ -10,31 +10,56 @@ import { ComponentDecorator } from 'twenty-ui/testing';
import { PhoneCountryPickerDropdownButton } from '@/ui/input/components/internal/phone/components/PhoneCountryPickerDropdownButton';
const onCountryChange = fn();
+const onPhoneValueChange = fn();
+const onControlledCountryChange = fn();
+
+const FRENCH_PHONE_NUMBER = '+33642646274' as E164Number;
+const BRITISH_PHONE_NUMBER = '+442079460018' as E164Number;
+const AMERICAN_PHONE_NUMBER = '+16502530000' as E164Number;
const LibraryPhoneInput = ({
label = 'Phone',
disabled = false,
readOnly = false,
+ initialValue,
+ showExternalControls = false,
}: {
label?: string;
disabled?: boolean;
readOnly?: boolean;
+ initialValue?: E164Number;
+ showExternalControls?: boolean;
}) => {
- const [value, setValue] = useState<E164Number>();
+ const [value, setValue] = useState<E164Number | undefined>(initialValue);
+
+ const handleChange = (phoneValue: E164Number | undefined) => {
+ setValue(phoneValue);
+ onPhoneValueChange(phoneValue);
+ };
return (
- <ReactPhoneNumberInput
- aria-label={label}
- value={value}
- onChange={setValue}
- onCountryChange={onCountryChange}
- international
- withCountryCallingCode
- defaultCountry="US"
- disabled={disabled}
- readOnly={readOnly}
- countrySelectComponent={PhoneCountryPickerDropdownButton}
- />
+ <>
+ <ReactPhoneNumberInput
+ aria-label={label}
+ value={value}
+ onChange={handleChange}
+ onCountryChange={onCountryChange}
+ international
+ withCountryCallingCode
+ defaultCountry="US"
+ disabled={disabled}
+ readOnly={readOnly}
+ countrySelectComponent={PhoneCountryPickerDropdownButton}
+ />
+ {showExternalControls && (
+ <>
+ <Button onClick={() => setValue(BRITISH_PHONE_NUMBER)}>
+ Replace phone
+ </Button>
+ <Button onClick={() => setValue(undefined)}>Clear phone</Button>
+ </>
+ )}
+ </>
);
};
@@ -43,8 +68,15 @@ const ControlledCountryPicker = () => {
return (
<>
- <PhoneCountryPickerDropdownButton value={value} onChange={setValue} />
+ <PhoneCountryPickerDropdownButton
+ value={value}
+ onChange={(countryCode) => {
+ setValue(countryCode);
+ onControlledCountryChange(countryCode);
+ }}
+ />
<Button onClick={() => setValue(undefined)}>Clear country</Button>
+ <Button onClick={() => setValue('GB')}>Replace country</Button>
</>
);
};
@@ -54,6 +86,8 @@ const meta: Meta = {
decorators: [ComponentDecorator],
beforeEach: () => {
onCountryChange.mockClear();
+ onPhoneValueChange.mockClear();
+ onControlledCountryChange.mockClear();
},
};
@@ -76,14 +110,14 @@ export const PhoneLibrarySelectionAndFocus: Story = {
const popup = await body.findByRole('dialog', { name: 'Country' });
const search = within(popup).getByRole('searchbox', { name: 'Search' });
await waitFor(() => expect(search).toHaveFocus());
- expect(within(popup).getAllByRole('button')[0]).toHaveAccessibleName(
+ expect(within(popup).getAllByRole('option')[0]).toHaveAccessibleName(
'United States (+1)',
);
await userEvent.type(search, 'france');
- const france = await within(popup).findByRole('button', {
+ const france = await within(popup).findByRole('option', {
name: 'France (+33)',
});
- expect(within(popup).queryByRole('button', { pressed: true })).toBeNull();
+ expect(within(popup).queryByRole('option', { selected: true })).toBeNull();
await waitFor(() => expect(france).toHaveAttribute('data-highlighted'));
await userEvent.keyboard('{Enter}');
await waitFor(() => expect(popup).not.toBeInTheDocument());
@@ -98,11 +132,11 @@ export const PhoneLibrarySelectionAndFocus: Story = {
});
expect(reopenedSearch).toHaveValue('');
expect(
- within(reopenedPopup).getByRole('button', { name: 'France (+33)' }),
- ).toHaveAttribute('aria-pressed', 'true');
+ within(reopenedPopup).getByRole('option', { name: 'France (+33)' }),
+ ).toHaveAttribute('aria-selected', 'true');
await userEvent.type(reopenedSearch, 'germany');
await userEvent.click(
- await within(reopenedPopup).findByRole('button', {
+ await within(reopenedPopup).findByRole('option', {
name: 'Germany (+49)',
}),
);
@@ -141,7 +175,7 @@ export const IndependentPhoneInputs: Story = {
'france',
);
await userEvent.click(
- await within(workPopup).findByRole('button', { name: 'France (+33)' }),
+ await within(workPopup).findByRole('option', { name: 'France (+33)' }),
);
await waitFor(() => expect(workPopup).not.toBeInTheDocument());
await waitFor(() =>
@@ -158,10 +192,10 @@ export const IndependentPhoneInputs: Story = {
within(personalPopup).getByRole('searchbox', { name: 'Search' }),
).toHaveValue('');
expect(
- within(personalPopup).getByRole('button', {
+ within(personalPopup).getByRole('option', {
name: 'United States (+1)',
}),
- ).toHaveAttribute('aria-pressed', 'true');
+ ).toHaveAttribute('aria-selected', 'true');
await userEvent.keyboard('{Escape}');
await waitFor(() => expect(personalTrigger).toHaveFocus());
},
@@ -206,18 +240,19 @@ export const ClearedCountryRemovesSelection: Story = {
await userEvent.click(trigger);
const popup = await body.findByRole('dialog', { name: 'Country' });
expect(
- within(popup).getByRole('button', { name: 'United States (+1)' }),
- ).toHaveAttribute('aria-pressed', 'true');
+ within(popup).getByRole('option', { name: 'United States (+1)' }),
+ ).toHaveAttribute('aria-selected', 'true');
await userEvent.keyboard('{Escape}');
await waitFor(() => expect(popup).not.toBeInTheDocument());
await userEvent.click(
canvas.getByRole('button', { name: 'Clear country' }),
);
expect(trigger).not.toHaveAccessibleDescription();
+ expect(onControlledCountryChange).not.toHaveBeenCalled();
await userEvent.click(trigger);
const clearedPopup = await body.findByRole('dialog', { name: 'Country' });
expect(
- within(clearedPopup).queryByRole('button', { pressed: true }),
+ within(clearedPopup).queryByRole('option', { selected: true }),
).toBeNull();
await userEvent.type(
within(clearedPopup).getByRole('searchbox', { name: 'Search' }),
@@ -226,10 +261,134 @@ export const ClearedCountryRemovesSelection: Story = {
await userEvent.keyboard('{Enter}');
await waitFor(() => expect(clearedPopup).not.toBeInTheDocument());
expect(trigger).toHaveAccessibleDescription('France');
+ expect(onControlledCountryChange).toHaveBeenLastCalledWith('FR');
await userEvent.click(trigger);
expect(
- await body.findByRole('button', { name: 'France (+33)', pressed: true }),
+ await body.findByRole('option', { name: 'France (+33)', selected: true }),
).toBeVisible();
await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(body.queryByRole('dialog')).toBeNull());
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Replace country' }),
+ );
+ expect(trigger).toHaveAccessibleDescription('United Kingdom');
+ expect(onControlledCountryChange).toHaveBeenCalledTimes(1);
+ await userEvent.click(trigger);
+ const replacedPopup = await body.findByRole('dialog', { name: 'Country' });
+ expect(
+ within(replacedPopup).getByRole('option', {
+ name: 'United Kingdom (+44)',
+ }),
+ ).toHaveAttribute('aria-selected', 'true');
+ await userEvent.keyboard('{Escape}');
+ },
+};
+
+export const CountryChangesPreservePhoneLibraryBehavior: Story = {
+ render: () => <LibraryPhoneInput initialValue={FRENCH_PHONE_NUMBER} />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ const trigger = canvas.getByRole('button', { name: 'Country' });
+ const phoneInput = canvas.getByRole('textbox', { name: 'Phone' });
+
+ expect(trigger).toHaveAccessibleDescription('France');
+ expect(phoneInput).toHaveValue('+33 6 42 64 62 74');
+ await userEvent.click(trigger);
+ const canceledPopup = await body.findByRole('dialog', { name: 'Country' });
+ await userEvent.type(
+ within(canceledPopup).getByRole('searchbox', { name: 'Search' }),
+ 'germany',
+ );
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(canceledPopup).not.toBeInTheDocument());
+ expect(phoneInput).toHaveValue('+33 6 42 64 62 74');
+ expect(onPhoneValueChange).not.toHaveBeenCalled();
+
+ await userEvent.click(trigger);
+ const popup = await body.findByRole('dialog', { name: 'Country' });
+ await userEvent.type(
+ within(popup).getByRole('searchbox', { name: 'Search' }),
+ 'germany',
+ );
+ await userEvent.click(
+ await within(popup).findByRole('option', { name: 'Germany (+49)' }),
+ );
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(onCountryChange).toHaveBeenLastCalledWith('DE');
+ expect(onPhoneValueChange).toHaveBeenLastCalledWith('+49');
+ expect(trigger).toHaveAccessibleDescription('Germany');
+ expect(phoneInput).toHaveValue('+49');
+ await waitFor(() => expect(phoneInput).toHaveFocus());
+ await userEvent.type(phoneInput, '30123456');
+ expect(onPhoneValueChange).toHaveBeenLastCalledWith('+4930123456');
+ },
+};
+
+export const ExternalPhoneUpdatesControlCountry: Story = {
+ render: () => (
+ <LibraryPhoneInput
+ initialValue={FRENCH_PHONE_NUMBER}
+ showExternalControls
+ />
+ ),
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ const trigger = canvas.getByRole('button', { name: 'Country' });
+ const phoneInput = canvas.getByRole('textbox', { name: 'Phone' });
+
+ expect(trigger).toHaveAccessibleDescription('France');
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Replace phone' }),
+ );
+ expect(trigger).toHaveAccessibleDescription('United Kingdom');
+ expect(phoneInput).toHaveValue('+44 20 7946 0018');
+ expect(onPhoneValueChange).not.toHaveBeenCalled();
+ await userEvent.click(trigger);
+ const popup = await body.findByRole('dialog', { name: 'Country' });
+ expect(
+ within(popup).getByRole('option', { name: 'United Kingdom (+44)' }),
+ ).toHaveAttribute('aria-selected', 'true');
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+
+ await userEvent.click(canvas.getByRole('button', { name: 'Clear phone' }));
+ expect(onPhoneValueChange).not.toHaveBeenCalled();
+ expect(trigger).toHaveAccessibleDescription('United States');
+ expect(phoneInput).toHaveValue('+1');
+ await userEvent.click(trigger);
+ const clearedPopup = await body.findByRole('dialog', { name: 'Country' });
+ expect(
+ within(clearedPopup).getByRole('option', { name: 'United States (+1)' }),
+ ).toHaveAttribute('aria-selected', 'true');
+ await userEvent.keyboard('{Escape}');
+ },
+};
+
+export const SharedCallingCodesPreservePhoneDigits: Story = {
+ render: () => <LibraryPhoneInput initialValue={AMERICAN_PHONE_NUMBER} />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ const trigger = canvas.getByRole('button', { name: 'Country' });
+ const phoneInput = canvas.getByRole('textbox', { name: 'Phone' });
+
+ expect(trigger).toHaveAccessibleDescription('United States');
+ expect(phoneInput).toHaveValue('+1 650 253 0000');
+ await userEvent.click(trigger);
+ const popup = await body.findByRole('dialog', { name: 'Country' });
+ await userEvent.type(
+ within(popup).getByRole('searchbox', { name: 'Search' }),
+ 'canada',
+ );
+ await userEvent.click(
+ await within(popup).findByRole('option', { name: 'Canada (+1)' }),
+ );
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(onCountryChange).toHaveBeenLastCalledWith('CA');
+ expect(onPhoneValueChange).toHaveBeenLastCalledWith(AMERICAN_PHONE_NUMBER);
+ expect(trigger).toHaveAccessibleDescription('Canada');
+ expect(phoneInput).toHaveValue('+1 650 253 0000');
},
};
diff --git a/packages/twenty-front/src/modules/ui/input/components/internal/phone/components/PhoneCountryPickerDropdownButton.tsx b/packages/twenty-front/src/modules/ui/input/components/internal/phone/components/PhoneCountryPickerDropdownButton.tsx
index 31f83f1a9e0..923f27b6a00 100644
--- a/packages/twenty-front/src/modules/ui/input/components/internal/phone/components/PhoneCountryPickerDropdownButton.tsx
+++ b/packages/twenty-front/src/modules/ui/input/components/internal/phone/components/PhoneCountryPickerDropdownButton.tsx
@@ -8,7 +8,7 @@ import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
type PhoneCountryPickerDropdownButtonProps = {
value?: string;
- onChange: (countryCode: string) => void;
+ onChange: (countryCode: string | undefined) => void;
disabled?: boolean;
readOnly?: boolean;
};
@@ -43,30 +43,32 @@ export const PhoneCountryPickerDropdownButton = ({
),
[availableCountries],
);
- const selectedCountry = countries.find((country) => country.value === value);
return (
- <DropdownRoot dropdownId={dropdownId} type="picker">
- <PhoneCountryPicker.Trigger
- country={selectedCountry}
- disabled={disabled || readOnly}
- aria-label={t`Country`}
- onKeyDown={keepEnterAwayFromFieldHotkeys}
- />
- <DropdownContent
- side="bottom"
- align="start"
- sideOffset={4}
- alignOffset={0}
- >
- <PhoneCountryPicker.Options
- countries={countries}
- value={value}
- onValueChange={onChange}
- searchLabel={t`Search`}
- emptyLabel={t`No results`}
+ <PhoneCountryPicker.Root
+ countries={countries}
+ value={value ?? null}
+ onValueChange={(countryCode) => onChange(countryCode ?? undefined)}
+ disabled={disabled || readOnly}
+ >
+ <DropdownRoot dropdownId={dropdownId} type="picker">
+ <PhoneCountryPicker.Trigger
+ aria-label={t`Country`}
+ onKeyDown={keepEnterAwayFromFieldHotkeys}
/>
- </DropdownContent>
- </DropdownRoot>
+ <DropdownContent
+ side="bottom"
+ align="start"
+ sideOffset={4}
+ alignOffset={0}
+ >
+ <PhoneCountryPicker.Options
+ searchLabel={t`Search`}
+ listLabel={t`Countries`}
+ emptyLabel={t`No results`}
+ />
+ </DropdownContent>
+ </DropdownRoot>
+ </PhoneCountryPicker.Root>
);
};
diff --git a/packages/twenty-ui/docs/components.ts b/packages/twenty-ui/docs/components.ts
index d6ee8372dd0..a91c4bf2f28 100644
--- a/packages/twenty-ui/docs/components.ts
+++ b/packages/twenty-ui/docs/components.ts
@@ -23,6 +23,7 @@ import { TOAST_PROVIDER_PROP_DESCRIPTIONS } from './toastProviderPropDescription
import { TOASTER_PROP_DESCRIPTIONS } from './toasterPropDescriptions';
import { RADIO_PROP_DESCRIPTIONS } from './radioPropDescriptions';
import { PHONE_COUNTRY_PICKER_PART_PROP_DESCRIPTIONS } from './phoneCountryPickerPartPropDescriptions';
+import { PHONE_COUNTRY_PICKER_PROP_DESCRIPTIONS } from './phoneCountryPickerPropDescriptions';
import { SEARCH_INPUT_PROP_DESCRIPTIONS } from './searchInputPropDescriptions';
import { NUMBER_STEPPER_PROP_DESCRIPTIONS } from './numberStepperPropDescriptions';
import { NUMBER_FIELD_PART_PROP_DESCRIPTIONS } from './numberFieldPartPropDescriptions';
@@ -767,7 +768,8 @@ export const DOCUMENTED_COMPONENTS = [
source: 'components/input/PhoneCountryPicker/PhoneCountryPicker.tsx',
entryPoint: 'twenty-ui/components/input',
slug: 'components/input/phone-country-picker',
- parts: ['Trigger', 'Options'],
+ propDescriptions: PHONE_COUNTRY_PICKER_PROP_DESCRIPTIONS,
+ parts: ['Root', 'Trigger', 'Options'],
partPropDescriptions: PHONE_COUNTRY_PICKER_PART_PROP_DESCRIPTIONS,
},
{
diff --git a/packages/twenty-ui/docs/label-ownership.md b/packages/twenty-ui/docs/label-ownership.md
index e175ed040e8..1f454ddaac7 100644
--- a/packages/twenty-ui/docs/label-ownership.md
+++ b/packages/twenty-ui/docs/label-ownership.md
@@ -14,7 +14,7 @@ This covers production exports under components, primitives, and icons, includin
| 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. |
-| PhoneCountryPicker | Callers supply country labels and the trigger accessible name. The popup takes the trigger name unless a `Dropdown.Title` or an explicit `Dropdown.Content` label names it, and the selected country label describes the trigger. `searchLabel` defaults to `Search`; `emptyLabel` defaults to `No results`. Calling codes are supplied as data without a leading plus sign. |
+| 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. |
| Chip and Avatar | Chip content, translated fallbacks and interactive accessible names belong to the caller. Missing children add no label. Avatar's image and default fallback are decorative. `name` supplies the visual initial and colors. Explicit `imageProps.alt` labels the image and default fallback; caller fallback semantics take precedence. Composed buttons and links own their labels and interaction handlers. |
diff --git a/packages/twenty-ui/docs/phoneCountryPickerPartPropDescriptions.ts b/packages/twenty-ui/docs/phoneCountryPickerPartPropDescriptions.ts
index 1fea162674e..edd1eb80f25 100644
--- a/packages/twenty-ui/docs/phoneCountryPickerPartPropDescriptions.ts
+++ b/packages/twenty-ui/docs/phoneCountryPickerPartPropDescriptions.ts
@@ -3,25 +3,46 @@ import { type ComponentProps } from 'react';
import { type PhoneCountryPicker } from '../src/components/input/PhoneCountryPicker/PhoneCountryPicker';
export const PHONE_COUNTRY_PICKER_PART_PROP_DESCRIPTIONS = {
+ Root: {
+ countries:
+ 'Prepared choices shared by Trigger and Options, with unique stable values, localized labels, digits-only calling codes without a plus sign, decorative flag nodes and optional disabled states.',
+ value:
+ 'Controlled country identifier shared by the parts. Use null to clear the selection.',
+ defaultValue:
+ 'Initial uncontrolled country identifier. Omit it or use null to start empty.',
+ onValueChange:
+ 'Receives the requested identifier or null and Dropdown.SelectionGroup event details, including reason, event, trigger and cancel(). Cancel before updating controlled state to reject a selection.',
+ disabled: 'Disables the composed trigger, search and country selection.',
+ closeOnSelect:
+ 'Closes the composed Dropdown after an accepted selection. Defaults to true.',
+ children:
+ 'A Dropdown.Root with type="picker", its Trigger, Content and Options. Root shares prepared data and selection and renders no DOM node.',
+ } satisfies Partial<
+ Record<keyof ComponentProps<typeof PhoneCountryPicker.Root>, string>
+ >,
Trigger: {
- country:
- 'Prepared country whose flag is displayed and whose label describes the trigger. Omit it to show a world icon.',
'aria-label': 'Required accessible name for the country selector button.',
- disabled: 'Disables the native trigger button.',
+ children:
+ 'Optional trigger content replacing the selected country flag or empty world icon and chevron. The selected label comes from Root.',
+ disabled:
+ 'Disables the native trigger button in addition to Root.disabled.',
+ ref: 'Ref to the trigger button, or the element composed through render.',
+ render:
+ 'Composes the Dropdown trigger with an element or render callback. Native attributes, handlers, className, style and ref target this element.',
} satisfies Partial<
Record<keyof ComponentProps<typeof PhoneCountryPicker.Trigger>, string>
>,
Options: {
- countries:
- 'Prepared choices with a unique value, localized label, calling code without a plus sign, and flag node. The supplied order is preserved after the matching selected country.',
- value:
- 'Selected country value. Its row appears first only while it matches the search.',
- onValueChange:
- 'Called with the chosen country value. The host owns the selected country and phone number.',
+ listLabel:
+ 'Accessible name of the country listbox, separate from the search field. Defaults to Countries.',
searchLabel:
- 'Accessible name and placeholder of the country search field. Defaults to Search.',
+ 'Accessible name and placeholder of the country search field. Defaults to Search. Search matches normalized labels and identifiers, or calling codes with an optional leading plus sign. Surrounding query whitespace is trimmed.',
emptyLabel:
- 'Status message shown when no country names match. Defaults to No results.',
+ 'Status message shown when no country label, identifier or calling code matches. Defaults to No results.',
+ disabled: 'Disables search and selection in addition to Root.disabled.',
+ ref: 'Ref to the options root div, or the element composed through render.',
+ render:
+ 'Composes the non-interactive options root with an element or render callback. Native attributes, handlers, className, style and ref target this element. searchLabel names the internal search input.',
} satisfies Partial<
Record<keyof ComponentProps<typeof PhoneCountryPicker.Options>, string>
>,
diff --git a/packages/twenty-ui/docs/phoneCountryPickerPropDescriptions.ts b/packages/twenty-ui/docs/phoneCountryPickerPropDescriptions.ts
new file mode 100644
index 00000000000..1e4cc5a5254
--- /dev/null
+++ b/packages/twenty-ui/docs/phoneCountryPickerPropDescriptions.ts
@@ -0,0 +1,31 @@
+import { type ComponentProps } from 'react';
+
+import { type PhoneCountryPicker } from '../src/components/input/PhoneCountryPicker/PhoneCountryPicker';
+
+export const PHONE_COUNTRY_PICKER_PROP_DESCRIPTIONS = {
+ countries:
+ 'Prepared choices with a unique stable value, localized label, digits-only calling code without a plus sign, decorative flag node and optional disabled state. Matching choices retain their supplied order after the selected country.',
+ value:
+ 'Controlled country identifier. Use null to clear the selection. Labels and calling codes do not replace this value.',
+ defaultValue:
+ 'Initial uncontrolled country identifier. Omit it or use null to start empty.',
+ onValueChange:
+ 'Receives the requested country identifier or null and Dropdown.SelectionGroup event details, including reason, event, trigger and cancel(). Cancel before updating controlled state to reject a selection.',
+ disabled: 'Disables the trigger, search and country selection.',
+ closeOnSelect:
+ 'Closes the dropdown after an accepted selection. Defaults to true.',
+ 'aria-label': 'Required accessible name for the country selector trigger.',
+ children:
+ 'Optional trigger content replacing the default country flag or world icon and chevron.',
+ ref: 'Ref to the trigger button, or the element composed through render.',
+ render:
+ 'Composes the trigger with an element or render callback. Native attributes, handlers, className, style and ref target the trigger.',
+ dropdownProps:
+ 'Props for the internally assembled Dropdown.Root, including controlled open state and open-change events. The picker fixes its type to picker.',
+ contentProps:
+ 'Props for the internally assembled Dropdown.Content, including its accessible name, placement, width and popup ref.',
+ optionsProps:
+ 'Props for the options root div, including native attributes, ref, render, searchLabel, listLabel and emptyLabel. Search matches normalized labels and identifiers, or calling codes with an optional leading plus sign. Surrounding query whitespace is trimmed.',
+} satisfies Partial<
+ Record<keyof ComponentProps<typeof PhoneCountryPicker>, string>
+>;
diff --git a/packages/twenty-ui/docs/public-exports.json b/packages/twenty-ui/docs/public-exports.json
index 9c1b41bedf2..7c6f0cea40c 100644
--- a/packages/twenty-ui/docs/public-exports.json
+++ b/packages/twenty-ui/docs/public-exports.json
@@ -118,6 +118,8 @@
"NumberStepperProps": "components/input/NumberStepper/types/NumberStepperProps",
"PhoneCountryOption": "components/input/PhoneCountryPicker/types/PhoneCountryOption",
"PhoneCountryPickerOptionsProps": "components/input/PhoneCountryPicker/types/PhoneCountryPickerOptionsProps",
+ "PhoneCountryPickerProps": "components/input/PhoneCountryPicker/types/PhoneCountryPickerProps",
+ "PhoneCountryPickerRootProps": "components/input/PhoneCountryPicker/types/PhoneCountryPickerRootProps",
"PhoneCountryPickerTriggerProps": "components/input/PhoneCountryPicker/types/PhoneCountryPickerTriggerProps",
"SearchInputProps": "components/input/SearchInput/types/SearchInputProps",
"SegmentedControlOption": "components/input/SegmentedControl/types/SegmentedControlOption",
diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.json
index 7b4be243bf8..ffe37b8c020 100644
--- a/packages/twenty-ui/generated/components.docs.json
+++ b/packages/twenty-ui/generated/components.docs.json
@@ -11143,8 +11143,203 @@
"name": "PhoneCountryPicker",
"entryPoint": "twenty-ui/components/input",
"slug": "components/input/phone-country-picker",
- "props": [],
+ "props": [
+ {
+ "name": "aria-label",
+ "type": "string",
+ "required": true,
+ "defaultValue": null,
+ "description": "Required accessible name for the country selector trigger."
+ },
+ {
+ "name": "children",
+ "type": "ReactNode",
+ "required": false,
+ "defaultValue": null,
+ "description": "Optional trigger content replacing the default country flag or world icon and chevron."
+ },
+ {
+ "name": "className",
+ "type": "string | ((state: PopoverTriggerState) => string | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "CSS class applied to the element, or a function that\nreturns a class based on the component's state."
+ },
+ {
+ "name": "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 dropdown after an accepted selection. Defaults to true."
+ },
+ {
+ "name": "contentProps",
+ "type": "Omit<DropdownContentProps, \"children\">",
+ "required": false,
+ "defaultValue": null,
+ "description": "Props for the internally assembled Dropdown.Content, including its accessible name, placement, width and popup ref."
+ },
+ {
+ "name": "countries",
+ "type": "readonly PhoneCountryOption[]",
+ "required": true,
+ "defaultValue": null,
+ "description": "Prepared choices with a unique stable value, localized label, digits-only calling code without a plus sign, decorative flag node and optional disabled state. Matching choices retain their supplied order after the selected country."
+ },
+ {
+ "name": "defaultValue",
+ "type": "string | null",
+ "required": false,
+ "defaultValue": null,
+ "description": "Initial uncontrolled country identifier. Omit it or use null to start empty."
+ },
+ {
+ "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": null,
+ "description": "Disables the trigger, search and country selection."
+ },
+ {
+ "name": "dropdownProps",
+ "type": "Omit<DropdownRootProps, \"children\" | \"type\" | \"multiple\">",
+ "required": false,
+ "defaultValue": null,
+ "description": "Props for the internally assembled Dropdown.Root, including controlled open state and open-change events. The picker fixes its type to picker."
+ },
+ {
+ "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": "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": "onValueChange",
+ "type": "((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) => void)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Receives the requested country identifier or null and Dropdown.SelectionGroup event details, including reason, event, trigger and cancel(). Cancel before updating controlled state to reject a selection."
+ },
+ {
+ "name": "openOnHover",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": "false",
+ "description": "Whether the popover should also open when the trigger is hovered."
+ },
+ {
+ "name": "optionsProps",
+ "type": "PhoneCountryPickerOptionsProps",
+ "required": false,
+ "defaultValue": null,
+ "description": "Props for the options root div, including native attributes, ref, render, searchLabel, listLabel and emptyLabel. Search matches normalized labels and identifiers, or calling codes with an optional leading plus sign. Surrounding query whitespace is trimmed."
+ },
+ {
+ "name": "ref",
+ "type": "Ref<HTMLButtonElement>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Ref to the trigger button, or the element composed through render."
+ },
+ {
+ "name": "render",
+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, PopoverTriggerState>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Composes the trigger with an element or render callback. Native attributes, handlers, className, style and ref target the trigger."
+ },
+ {
+ "name": "style",
+ "type": "CSSProperties | ((state: PopoverTriggerState) => CSSProperties | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Style applied to the element, or a function that\nreturns a style object based on the component's state."
+ },
+ {
+ "name": "value",
+ "type": "string | null",
+ "required": false,
+ "defaultValue": null,
+ "description": "Controlled country identifier. Use null to clear the selection. Labels and calling codes do not replace this value."
+ }
+ ],
"parts": [
+ {
+ "name": "Root",
+ "props": [
+ {
+ "name": "children",
+ "type": "ReactNode",
+ "required": true,
+ "defaultValue": null,
+ "description": "A Dropdown.Root with type=\"picker\", its Trigger, Content and Options. Root shares prepared data and selection and renders no DOM node."
+ },
+ {
+ "name": "closeOnSelect",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": "true",
+ "description": "Closes the composed Dropdown after an accepted selection. Defaults to true."
+ },
+ {
+ "name": "countries",
+ "type": "readonly PhoneCountryOption[]",
+ "required": true,
+ "defaultValue": null,
+ "description": "Prepared choices shared by Trigger and Options, with unique stable values, localized labels, digits-only calling codes without a plus sign, decorative flag nodes and optional disabled states."
+ },
+ {
+ "name": "defaultValue",
+ "type": "string | null",
+ "required": false,
+ "defaultValue": "null",
+ "description": "Initial uncontrolled country identifier. Omit it or use null to start empty."
+ },
+ {
+ "name": "disabled",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": "false",
+ "description": "Disables the composed trigger, search and country selection."
+ },
+ {
+ "name": "onValueChange",
+ "type": "((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) => void)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Receives the requested identifier or null and Dropdown.SelectionGroup event details, including reason, event, trigger and cancel(). Cancel before updating controlled state to reject a selection."
+ },
+ {
+ "name": "value",
+ "type": "string | null",
+ "required": false,
+ "defaultValue": null,
+ "description": "Controlled country identifier shared by the parts. Use null to clear the selection."
+ }
+ ]
+ },
{
"name": "Trigger",
"props": [
@@ -11155,6 +11350,13 @@
"defaultValue": null,
"description": "Required accessible name for the country selector button."
},
+ {
+ "name": "children",
+ "type": "ReactNode",
+ "required": false,
+ "defaultValue": null,
+ "description": "Optional trigger content replacing the selected country flag or empty world icon and chevron. The selected label comes from Root."
+ },
{
"name": "className",
"type": "string | ((state: PopoverTriggerState) => string | undefined)",
@@ -11169,13 +11371,6 @@
"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": "country",
- "type": "PhoneCountryOption",
- "required": false,
- "defaultValue": null,
- "description": "Prepared country whose flag is displayed and whose label describes the trigger. Omit it to show a world icon."
- },
{
"name": "delay",
"type": "number",
@@ -11188,7 +11383,7 @@
"type": "boolean",
"required": false,
"defaultValue": null,
- "description": "Disables the native trigger button."
+ "description": "Disables the native trigger button in addition to Root.disabled."
},
{
"name": "id",
@@ -11197,6 +11392,13 @@
"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": "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",
@@ -11204,6 +11406,20 @@
"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 button, or the element composed through render."
+ },
+ {
+ "name": "render",
+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, PopoverTriggerState>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Composes the Dropdown trigger with an element or render callback. Native attributes, handlers, className, style and ref target this element."
+ },
{
"name": "style",
"type": "CSSProperties | ((state: PopoverTriggerState) => CSSProperties | undefined)",
@@ -11217,39 +11433,46 @@
"name": "Options",
"props": [
{
- "name": "countries",
- "type": "readonly PhoneCountryOption[]",
- "required": true,
+ "name": "disabled",
+ "type": "boolean",
+ "required": false,
"defaultValue": null,
- "description": "Prepared choices with a unique value, localized label, calling code without a plus sign, and flag node. The supplied order is preserved after the matching selected country."
+ "description": "Disables search and selection in addition to Root.disabled."
},
{
"name": "emptyLabel",
"type": "string",
"required": false,
"defaultValue": "No results",
- "description": "Status message shown when no country names match. Defaults to No results."
+ "description": "Status message shown when no country label, identifier or calling code matches. Defaults to No results."
},
{
- "name": "onValueChange",
- "type": "(value: string) => void",
- "required": true,
+ "name": "listLabel",
+ "type": "string",
+ "required": false,
+ "defaultValue": "Countries",
+ "description": "Accessible name of the country listbox, separate from the search field. Defaults to Countries."
+ },
+ {
+ "name": "ref",
+ "type": "Ref<HTMLDivElement>",
+ "required": false,
"defaultValue": null,
- "description": "Called with the chosen country value. The host owns the selected country and phone number."
+ "description": "Ref to the options root div, or the element composed through render."
},
{
- "name": "searchLabel",
- "type": "string",
+ "name": "render",
+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, {}>",
"required": false,
- "defaultValue": "Search",
- "description": "Accessible name and placeholder of the country search field. Defaults to Search."
+ "defaultValue": null,
+ "description": "Composes the non-interactive options root with an element or render callback. Native attributes, handlers, className, style and ref target this element. searchLabel names the internal search input."
},
{
- "name": "value",
+ "name": "searchLabel",
"type": "string",
"required": false,
- "defaultValue": null,
- "description": "Selected country value. Its row appears first only while it matches the search."
+ "defaultValue": "Search",
+ "description": "Accessible name and placeholder of the country search field. Defaults to Search. Search matches normalized labels and identifiers, or calling codes with an optional leading plus sign. Surrounding query whitespace is trimmed."
}
]
}
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/PhoneCountryPicker.module.scss b/packages/twenty-ui/src/components/input/PhoneCountryPicker/PhoneCountryPicker.module.scss
index daf0c9b848a..b315b1db93f 100644
--- a/packages/twenty-ui/src/components/input/PhoneCountryPicker/PhoneCountryPicker.module.scss
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/PhoneCountryPicker.module.scss
@@ -70,3 +70,13 @@
position: absolute;
white-space: nowrap;
}
+
+.options {
+ display: flex;
+ flex-direction: column;
+ min-block-size: 0;
+}
+
+.emptyStatus:empty {
+ display: none;
+}
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/PhoneCountryPicker.module.scss.d.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/PhoneCountryPicker.module.scss.d.ts
index 417cb0fe949..8aba409b126 100644
--- a/packages/twenty-ui/src/components/input/PhoneCountryPicker/PhoneCountryPicker.module.scss.d.ts
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/PhoneCountryPicker.module.scss.d.ts
@@ -4,5 +4,7 @@ declare const classNames: {
readonly optionFlag: 'optionFlag';
readonly chevron: 'chevron';
readonly selectedCountryLabel: 'selectedCountryLabel';
+ readonly options: 'options';
+ readonly emptyStatus: 'emptyStatus';
};
export default classNames;
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/PhoneCountryPicker.tsx b/packages/twenty-ui/src/components/input/PhoneCountryPicker/PhoneCountryPicker.tsx
index 32f431ebbeb..836e45f64d6 100644
--- a/packages/twenty-ui/src/components/input/PhoneCountryPicker/PhoneCountryPicker.tsx
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/PhoneCountryPicker.tsx
@@ -1,7 +1,55 @@
+import { Dropdown } from '@ui/components/navigation/Dropdown/Dropdown';
+
import { PhoneCountryPickerOptions } from './internal/PhoneCountryPickerOptions';
+import { PhoneCountryPickerRoot } from './internal/PhoneCountryPickerRoot';
import { PhoneCountryPickerTrigger } from './internal/PhoneCountryPickerTrigger';
+import { type PhoneCountryPickerProps } from './types/PhoneCountryPickerProps';
+
+const PhoneCountryPickerShorthand = ({
+ countries,
+ value,
+ defaultValue,
+ onValueChange,
+ disabled,
+ closeOnSelect,
+ dropdownProps,
+ contentProps,
+ optionsProps,
+ ...triggerProps
+}: PhoneCountryPickerProps) => (
+ <PhoneCountryPickerRoot
+ countries={countries}
+ value={value}
+ defaultValue={defaultValue}
+ onValueChange={onValueChange}
+ disabled={disabled}
+ closeOnSelect={closeOnSelect}
+ >
+ <Dropdown.Root
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...dropdownProps}
+ type="picker"
+ >
+ <PhoneCountryPickerTrigger
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...triggerProps}
+ />
+ <Dropdown.Content
+ width={280}
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...contentProps}
+ >
+ <PhoneCountryPickerOptions
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...optionsProps}
+ />
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </PhoneCountryPickerRoot>
+);
-export const PhoneCountryPicker = {
+export const PhoneCountryPicker = Object.assign(PhoneCountryPickerShorthand, {
+ Root: PhoneCountryPickerRoot,
Trigger: PhoneCountryPickerTrigger,
Options: PhoneCountryPickerOptions,
-};
+});
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPicker.contracts.stories.tsx b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPicker.contracts.stories.tsx
new file mode 100644
index 00000000000..6919b8cf941
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPicker.contracts.stories.tsx
@@ -0,0 +1,337 @@
+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 { createStoryState } from '@ui/components/navigation/Dropdown/__stories__/createStoryState';
+import { Button } from '@ui/primitives/input/Button/Button';
+import { DirectionProvider } from '@ui/primitives/layout/DirectionProvider/DirectionProvider';
+import { Text } from '@ui/primitives/typography/Text/Text';
+import { ComponentDecorator } from '@ui/testing';
+
+import { PhoneCountryPicker } from '../PhoneCountryPicker';
+import { type PhoneCountryPickerRootProps } from '../types/PhoneCountryPickerRootProps';
+import { openPhoneCountryPicker } from './openPhoneCountryPicker';
+import { PHONE_COUNTRY_OPTIONS } from './phoneCountryOptions';
+import { PHONE_COUNTRY_PICKER_STORY_A11Y_PARAMETERS } from './phoneCountryPickerStoryA11yParameters';
+import { testPhoneCountryCallingCodeDirection } from './testPhoneCountryCallingCodeDirection';
+
+const onValueChange = fn();
+const onTriggerRef = fn();
+const onOptionsRef = fn();
+const externalCountry = createStoryState<string | null>('FR');
+
+const ContractPicker = ({ compound = false }: { compound?: boolean }) => {
+ const value = externalCountry.useValue();
+ const selectionProps: Omit<PhoneCountryPickerRootProps, 'children'> = {
+ countries: PHONE_COUNTRY_OPTIONS,
+ value,
+ onValueChange,
+ closeOnSelect: false,
+ };
+
+ if (!compound) {
+ return (
+ <PhoneCountryPicker
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...selectionProps}
+ aria-label="Phone country"
+ contentProps={{ 'aria-label': 'Phone country choices' }}
+ />
+ );
+ }
+
+ return (
+ <PhoneCountryPicker.Root
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...selectionProps}
+ >
+ <Dropdown.Root type="picker">
+ <PhoneCountryPicker.Trigger aria-label="Phone country" />
+ <Dropdown.Content aria-label="Phone country choices">
+ <PhoneCountryPicker.Options />
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </PhoneCountryPicker.Root>
+ );
+};
+
+const meta: Meta = {
+ id: 'ui-input-phonecountrypicker-contracts',
+ title: 'UI/Components/Input/PhoneCountryPicker/Interactions/Contracts',
+ tags: ['!autodocs'],
+ decorators: [ComponentDecorator],
+ parameters: {
+ container: { width: 360, height: 360 },
+ a11y: PHONE_COUNTRY_PICKER_STORY_A11Y_PARAMETERS,
+ },
+ beforeEach: () => {
+ onValueChange.mockClear();
+ onTriggerRef.mockClear();
+ onOptionsRef.mockClear();
+ externalCountry.set('FR');
+ },
+};
+
+export default meta;
+type Story = StoryObj;
+
+export const ControlledExternalChanges: Story = {
+ render: () => <ContractPicker />,
+ play: async ({ canvasElement }) => {
+ const { dialog, trigger } = await openPhoneCountryPicker({ canvasElement });
+ const france = within(dialog).getByRole('option', { name: 'France (+33)' });
+ const canada = within(dialog).getByRole('option', { name: 'Canada (+1)' });
+
+ await expect(france).toHaveAttribute('aria-selected', 'true');
+ await userEvent.click(canada);
+ await expect(onValueChange).toHaveBeenCalledOnce();
+ await expect(onValueChange).toHaveBeenLastCalledWith(
+ 'CA',
+ expect.objectContaining({
+ reason: 'item-press',
+ trigger: canada,
+ isCanceled: false,
+ event: expect.objectContaining({ type: 'click' }),
+ }),
+ );
+ await expect(canada).toHaveAttribute('aria-selected', 'false');
+ await expect(trigger).toHaveAccessibleDescription('France');
+
+ externalCountry.set('CA');
+
+ await waitFor(() =>
+ expect(canada).toHaveAttribute('aria-selected', 'true'),
+ );
+ await expect(trigger).toHaveAccessibleDescription('Canada');
+
+ externalCountry.set(null);
+
+ await waitFor(() =>
+ expect(canada).toHaveAttribute('aria-selected', 'false'),
+ );
+ await expect(trigger).not.toHaveAccessibleDescription();
+ await expect(
+ within(dialog)
+ .getAllByRole('option')
+ .every((option) => option.getAttribute('aria-selected') === 'false'),
+ ).toBe(true);
+
+ externalCountry.set('unknown');
+
+ await expect(trigger).not.toHaveAccessibleDescription();
+ await expect(onValueChange).toHaveBeenCalledOnce();
+
+ externalCountry.set('DE');
+
+ await waitFor(() =>
+ expect(
+ within(dialog).getByRole('option', { name: 'Germany (+49)' }),
+ ).toHaveAttribute('aria-selected', 'true'),
+ );
+ await expect(trigger).toHaveAccessibleDescription('Germany');
+ await expect(onValueChange).toHaveBeenCalledOnce();
+ await userEvent.keyboard('{Escape}');
+ },
+};
+
+export const CompoundControlledExternalChanges: Story = {
+ ...ControlledExternalChanges,
+ render: () => <ContractPicker compound />,
+};
+
+export const CancelledSelection: Story = {
+ render: () => (
+ <PhoneCountryPicker
+ aria-label="Phone country"
+ countries={PHONE_COUNTRY_OPTIONS}
+ defaultValue="FR"
+ onValueChange={(value, eventDetails) => {
+ onValueChange(value, eventDetails);
+ eventDetails.cancel();
+ }}
+ contentProps={{ 'aria-label': 'Phone country choices' }}
+ />
+ ),
+ play: async ({ canvasElement }) => {
+ const { dialog, trigger } = await openPhoneCountryPicker({ canvasElement });
+ const canada = within(dialog).getByRole('option', { name: 'Canada (+1)' });
+
+ await userEvent.click(canada);
+ await expect(onValueChange).toHaveBeenCalledOnce();
+ await expect(onValueChange).toHaveBeenLastCalledWith(
+ 'CA',
+ expect.objectContaining({ isCanceled: true, trigger: canada }),
+ );
+ await expect(canada).toHaveAttribute('aria-selected', 'false');
+ await expect(trigger).toHaveAccessibleDescription('France');
+ await expect(dialog).toBeVisible();
+ await userEvent.keyboard('{Escape}');
+ },
+};
+
+export const NativeTargetsAndRender: Story = {
+ render: () => (
+ <PhoneCountryPicker
+ aria-label="Phone country"
+ countries={PHONE_COUNTRY_OPTIONS}
+ defaultValue="FR"
+ ref={onTriggerRef}
+ name="phone-country"
+ title="Choose calling region"
+ children="Calling region"
+ render={<Button data-testid="phone-country-trigger" />}
+ contentProps={{ 'aria-label': 'Phone country choices' }}
+ optionsProps={{
+ ref: onOptionsRef,
+ id: 'phone-country-options',
+ title: 'Available calling regions',
+ render: <section data-testid="phone-country-options" />,
+ }}
+ />
+ ),
+ play: async ({ canvasElement }) => {
+ const trigger = within(canvasElement).getByTestId('phone-country-trigger');
+
+ await expect(trigger).toHaveAttribute('name', 'phone-country');
+ await expect(trigger).toHaveAttribute('title', 'Choose calling region');
+ await expect(trigger).toHaveTextContent('Calling region');
+ await expect(onTriggerRef).toHaveBeenCalledWith(trigger);
+ const { dialog } = await openPhoneCountryPicker({ canvasElement });
+ const options = within(dialog).getByTestId('phone-country-options');
+
+ await expect(options.tagName).toBe('SECTION');
+ await expect(options).toHaveAttribute('id', 'phone-country-options');
+ await expect(options).toHaveAttribute('title', 'Available calling regions');
+ await expect(onOptionsRef).toHaveBeenCalledWith(options);
+ await expect(within(options).getAllByRole('option')).toHaveLength(5);
+ await userEvent.click(
+ within(options).getByRole('option', { name: 'Canada (+1)' }),
+ );
+ await waitFor(() => expect(dialog).not.toBeInTheDocument());
+ await expect(trigger).toHaveAccessibleDescription('Canada');
+ },
+};
+
+export const RightToLeftCallingCodes: Story = {
+ render: () => (
+ <DirectionProvider direction="rtl">
+ <Text dir="rtl">
+ <PhoneCountryPicker
+ aria-label="Phone country"
+ countries={PHONE_COUNTRY_OPTIONS}
+ defaultValue="FR"
+ contentProps={{ 'aria-label': 'Phone country choices' }}
+ />
+ </Text>
+ </DirectionProvider>
+ ),
+ play: testPhoneCountryCallingCodeDirection,
+};
+
+const OVERFLOWING_ARABIC_COUNTRY_LABEL =
+ 'المملكة المتحدة لبريطانيا العظمى وأيرلندا الشمالية';
+
+export const RightToLeftOverflowTooltip: Story = {
+ render: () => (
+ <DirectionProvider direction="rtl">
+ <Text dir="rtl">
+ <PhoneCountryPicker
+ aria-label="Phone country"
+ countries={[
+ {
+ value: 'GB',
+ label: OVERFLOWING_ARABIC_COUNTRY_LABEL,
+ callingCode: '44',
+ flag: '🇬🇧',
+ },
+ ]}
+ defaultValue="GB"
+ contentProps={{ 'aria-label': 'Phone country choices', width: 180 }}
+ />
+ </Text>
+ </DirectionProvider>
+ ),
+ play: async ({ canvasElement }) => {
+ const { dialog } = await openPhoneCountryPicker({ canvasElement });
+ const option = within(dialog).getByRole('option', {
+ name: `${OVERFLOWING_ARABIC_COUNTRY_LABEL} (+44)`,
+ });
+ const countryLabel = within(option).getByText(
+ OVERFLOWING_ARABIC_COUNTRY_LABEL,
+ { exact: false },
+ );
+
+ await expect(countryLabel.scrollWidth).toBeGreaterThan(
+ countryLabel.clientWidth,
+ );
+ await userEvent.hover(countryLabel);
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ 'tooltip',
+ );
+
+ await waitFor(() => expect(tooltip).toBeVisible());
+ await expect(getComputedStyle(tooltip).direction).toBe('rtl');
+ await expect(tooltip).toHaveTextContent(
+ `${OVERFLOWING_ARABIC_COUNTRY_LABEL} (\u2066+44\u2069)`,
+ );
+ await userEvent.unhover(countryLabel);
+ await userEvent.keyboard('{Escape}');
+ },
+};
+
+export const CompoundCancelledSelection: Story = {
+ ...CancelledSelection,
+ render: () => (
+ <PhoneCountryPicker.Root
+ countries={PHONE_COUNTRY_OPTIONS}
+ defaultValue="FR"
+ onValueChange={(value, eventDetails) => {
+ onValueChange(value, eventDetails);
+ eventDetails.cancel();
+ }}
+ >
+ <Dropdown.Root type="picker">
+ <PhoneCountryPicker.Trigger aria-label="Phone country" />
+ <Dropdown.Content aria-label="Phone country choices">
+ <PhoneCountryPicker.Options />
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </PhoneCountryPicker.Root>
+ ),
+};
+
+const UncontrolledPicker = () => (
+ <PhoneCountryPicker
+ countries={PHONE_COUNTRY_OPTIONS}
+ defaultValue={externalCountry.useValue()}
+ onValueChange={onValueChange}
+ closeOnSelect={false}
+ aria-label="Phone country"
+ contentProps={{ 'aria-label': 'Phone country choices' }}
+ />
+);
+
+export const DefaultValueOnlyInitializes: Story = {
+ render: () => <UncontrolledPicker />,
+ play: async ({ canvasElement }) => {
+ const { dialog, trigger } = await openPhoneCountryPicker({ canvasElement });
+
+ externalCountry.set('DE');
+
+ await expect(trigger).toHaveAccessibleDescription('France');
+ await expect(
+ within(dialog).getByRole('option', { name: 'France (+33)' }),
+ ).toHaveAttribute('aria-selected', 'true');
+ await userEvent.click(
+ within(dialog).getByRole('option', { name: 'Canada (+1)' }),
+ );
+ await expect(trigger).toHaveAccessibleDescription('Canada');
+
+ externalCountry.set(null);
+
+ await expect(trigger).toHaveAccessibleDescription('Canada');
+ await expect(onValueChange).toHaveBeenCalledOnce();
+ await expect(dialog).toBeVisible();
+ await userEvent.keyboard('{Escape}');
+ },
+};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPicker.interactions.stories.tsx b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPicker.interactions.stories.tsx
index aa8d8507de9..0dad697f700 100644
--- a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPicker.interactions.stories.tsx
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPicker.interactions.stories.tsx
@@ -9,13 +9,20 @@ import { PhoneCountryPickerExample } from './PhoneCountryPickerExample';
import { openPhoneCountryPicker } from './openPhoneCountryPicker';
import { PHONE_COUNTRY_OPTIONS } from './phoneCountryOptions';
import { PHONE_COUNTRY_PICKER_STORY_A11Y_PARAMETERS } from './phoneCountryPickerStoryA11yParameters';
+import { testDisabledPhoneCountryPicker } from './testDisabledPhoneCountryPicker';
+import { testPhoneCountryNullSelection } from './testPhoneCountryNullSelection';
+import { testPhoneCountrySelection } from './testPhoneCountrySelection';
const meta: Meta<typeof PhoneCountryPickerExample> = {
id: 'ui-input-phonecountrypicker-interactions',
title: 'UI/Components/Input/PhoneCountryPicker/Interactions',
component: PhoneCountryPickerExample,
render: (args) => (
- <PhoneCountryPickerExample key={args.initialValue} {...args} />
+ <PhoneCountryPickerExample
+ key={args.initialValue}
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...args}
+ />
),
tags: ['!autodocs'],
decorators: [ComponentDecorator],
@@ -28,7 +35,7 @@ const meta: Meta<typeof PhoneCountryPickerExample> = {
export default meta;
type Story = StoryObj<typeof PhoneCountryPickerExample>;
-export const CountryNameSearch: Story = {
+export const SearchableCountryFields: Story = {
args: {
countries: [
...PHONE_COUNTRY_OPTIONS,
@@ -39,19 +46,30 @@ export const CountryNameSearch: Story = {
play: async ({ canvasElement, args }) => {
const { dialog, search } = await openPhoneCountryPicker({ canvasElement });
- for (const query of ['reunion', 'RÉUNION']) {
+ const initialOptions = within(dialog).getAllByRole('option');
+
+ await userEvent.type(search, ' ');
+ await expect(within(dialog).getAllByRole('option')).toHaveLength(
+ initialOptions.length,
+ );
+ await userEvent.clear(search);
+ await expect(within(dialog).getAllByRole('option')).toHaveLength(
+ initialOptions.length,
+ );
+
+ for (const query of ['reunion', ' RÉUNION ']) {
await userEvent.clear(search);
await userEvent.type(search, query);
- await expect(within(dialog).getAllByRole('button')).toHaveLength(1);
+ await expect(within(dialog).getAllByRole('option')).toHaveLength(1);
await expect(
- within(dialog).getByRole('button', { name: 'Réunion (+262)' }),
+ within(dialog).getByRole('option', { name: 'Réunion (+262)' }),
).toBeVisible();
}
await userEvent.clear(search);
await userEvent.type(search, 'a');
await expect(
within(dialog)
- .getAllByRole('button')
+ .getAllByRole('option')
.map((choice) => choice.textContent),
).toEqual([
expect.stringContaining('France (+33)'),
@@ -61,18 +79,32 @@ export const CountryNameSearch: Story = {
]);
await userEvent.clear(search);
await userEvent.type(search, 'uNiTeD');
- await expect(within(dialog).getAllByRole('button')).toHaveLength(2);
+ await expect(within(dialog).getAllByRole('option')).toHaveLength(2);
await expect(
- within(dialog).queryByRole('button', { name: 'France (+33)' }),
+ within(dialog).queryByRole('option', { name: 'France (+33)' }),
).not.toBeInTheDocument();
- await expect(within(dialog).getAllByRole('button')[0]).toHaveAccessibleName(
+ await expect(within(dialog).getAllByRole('option')[0]).toHaveAccessibleName(
'United Kingdom (+44)',
);
- for (const query of [' France ', '+33', '33', 'GB', 'unknown']) {
+ for (const { query, option } of [
+ { query: ' France ', option: 'France (+33)' },
+ { query: '+33', option: 'France (+33)' },
+ { query: '33', option: 'France (+33)' },
+ { query: ' gb ', option: 'United Kingdom (+44)' },
+ ]) {
+ await userEvent.clear(search);
+ await userEvent.type(search, query);
+ await expect(within(dialog).getAllByRole('option')).toHaveLength(1);
+ await expect(
+ within(dialog).getByRole('option', { name: option }),
+ ).toBeVisible();
+ }
+
+ for (const query of ['unknown', '+999', '+']) {
await userEvent.clear(search);
await userEvent.type(search, query);
- await expect(within(dialog).queryAllByRole('button')).toHaveLength(0);
+ await expect(within(dialog).queryAllByRole('option')).toHaveLength(0);
await expect(within(dialog).getByRole('status')).toHaveTextContent(
'No results',
);
@@ -105,10 +137,23 @@ export const KeyboardSelection: Story = {
await expect(args.onValueChange).not.toHaveBeenCalled();
await userEvent.keyboard('{ArrowDown}{ArrowDown}');
await expect(
- within(dialog).getByRole('button', { name: 'Canada (+1)' }),
+ within(dialog).getByRole('option', { name: 'Canada (+1)' }),
).toHaveFocus();
- await userEvent.keyboard('{Enter}');
- await expect(args.onValueChange).toHaveBeenCalledWith('CA');
+ await expect(args.onValueChange).not.toHaveBeenCalled();
+ await userEvent.keyboard('{End}');
+ await expect(
+ within(dialog).getByRole('option', { name: 'United States (+1)' }),
+ ).toHaveFocus();
+ await userEvent.keyboard('{Home}');
+ await expect(
+ within(dialog).getByRole('option', { name: 'France (+33)' }),
+ ).toHaveFocus();
+ await expect(args.onValueChange).not.toHaveBeenCalled();
+ await userEvent.keyboard('{ArrowDown} ');
+ await expect(args.onValueChange).toHaveBeenCalledWith(
+ 'CA',
+ expect.anything(),
+ );
await waitFor(() => expect(dialog).not.toBeInTheDocument());
await waitFor(() => expect(trigger).toHaveFocus());
@@ -116,7 +161,10 @@ export const KeyboardSelection: Story = {
await userEvent.type(reopened.search, 'germany');
await userEvent.keyboard('{Enter}');
- await expect(args.onValueChange).toHaveBeenLastCalledWith('DE');
+ await expect(args.onValueChange).toHaveBeenLastCalledWith(
+ 'DE',
+ expect.anything(),
+ );
await waitFor(() => expect(reopened.dialog).not.toBeInTheDocument());
await waitFor(() => expect(trigger).toHaveFocus());
},
@@ -129,14 +177,17 @@ export const LetterNavigation: Story = {
await userEvent.keyboard('{ArrowDown}');
await expect(
- within(dialog).getByRole('button', { name: 'France (+33)' }),
+ within(dialog).getByRole('option', { name: 'France (+33)' }),
).toHaveFocus();
await userEvent.keyboard('g');
await expect(
- within(dialog).getByRole('button', { name: 'Germany (+49)' }),
+ within(dialog).getByRole('option', { name: 'Germany (+49)' }),
).toHaveFocus();
await userEvent.keyboard('{Enter}');
- await expect(args.onValueChange).toHaveBeenCalledWith('DE');
+ await expect(args.onValueChange).toHaveBeenCalledWith(
+ 'DE',
+ expect.anything(),
+ );
await waitFor(() => expect(dialog).not.toBeInTheDocument());
},
};
@@ -145,7 +196,11 @@ export const DismissalResetsSearch: Story = {
args: { onValueChange: fn() },
render: (args) => (
<Text style={{ display: 'grid', gap: 16 }}>
- <PhoneCountryPickerExample key={args.initialValue} {...args} />
+ <PhoneCountryPickerExample
+ key={args.initialValue}
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...args}
+ />
<Button>Next field</Button>
</Text>
),
@@ -161,7 +216,7 @@ export const DismissalResetsSearch: Story = {
const reopened = await openPhoneCountryPicker({ canvasElement });
await expect(reopened.search).toHaveValue('');
- await expect(within(reopened.dialog).getAllByRole('button')).toHaveLength(
+ await expect(within(reopened.dialog).getAllByRole('option')).toHaveLength(
5,
);
const nextField = within(canvasElement).getByRole('button', {
@@ -180,6 +235,7 @@ export const IndependentInstances: Story = {
<Text style={{ display: 'flex', gap: 24 }}>
<PhoneCountryPickerExample
key={args.initialValue}
+ // oxlint-disable-next-line react/jsx-props-no-spreading
{...args}
label="Primary country"
/>
@@ -210,10 +266,10 @@ export const IndependentInstances: Story = {
await expect(secondary.search).toHaveValue('');
await expect(
- within(secondary.dialog).getAllByRole('button')[0],
+ within(secondary.dialog).getAllByRole('option')[0],
).toHaveAccessibleName('United Kingdom (+44)');
await userEvent.click(
- within(secondary.dialog).getByRole('button', { name: 'Germany (+49)' }),
+ within(secondary.dialog).getByRole('option', { name: 'Germany (+49)' }),
);
await waitFor(() => expect(secondary.dialog).not.toBeInTheDocument());
await expect(
@@ -229,6 +285,7 @@ export const CustomLabelsAndEmptyChoices: Story = {
args: {
countries: [],
searchLabel: 'Find a country',
+ listLabel: 'Available countries',
emptyLabel: 'No countries available',
onValueChange: fn(),
},
@@ -236,6 +293,9 @@ export const CustomLabelsAndEmptyChoices: Story = {
const { dialog, search } = await openPhoneCountryPicker({ canvasElement });
await expect(search).toHaveAccessibleName('Find a country');
+ await expect(
+ within(dialog).getByRole('listbox', { name: 'Available countries' }),
+ ).toBeVisible();
await expect(within(dialog).getByRole('status')).toHaveTextContent(
'No countries available',
);
@@ -245,3 +305,66 @@ export const CustomLabelsAndEmptyChoices: Story = {
await expect(args.onValueChange).not.toHaveBeenCalled();
},
};
+
+export const ShorthandSelection: Story = {
+ args: { onValueChange: fn() },
+ play: testPhoneCountrySelection,
+};
+
+export const CompoundSelection: Story = {
+ ...ShorthandSelection,
+ args: { composition: 'compound', controlled: true, onValueChange: fn() },
+};
+
+export const NullInitialValue: Story = {
+ args: { initialValue: null, onValueChange: fn() },
+ play: testPhoneCountryNullSelection,
+};
+
+export const DisabledInteractions: Story = {
+ args: { onValueChange: fn() },
+ render: (args) => (
+ <Text style={{ display: 'flex', gap: 24 }}>
+ <PhoneCountryPickerExample
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...args}
+ disabled
+ />
+ <PhoneCountryPickerExample
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...args}
+ label="Available country"
+ countries={PHONE_COUNTRY_OPTIONS.map((country) => ({
+ ...country,
+ disabled: country.value === 'CA',
+ }))}
+ />
+ </Text>
+ ),
+ play: async ({ canvasElement, args }) => {
+ await testDisabledPhoneCountryPicker({ canvasElement, args });
+ const { dialog } = await openPhoneCountryPicker({
+ canvasElement,
+ label: 'Available country',
+ });
+ const disabledOption = within(dialog).getByRole('option', {
+ name: 'Canada (+1)',
+ });
+
+ await expect(disabledOption).toBeDisabled();
+ await userEvent.click(disabledOption);
+ await expect(args.onValueChange).not.toHaveBeenCalled();
+ await expect(dialog).toBeVisible();
+ await userEvent.keyboard('{ArrowDown}{ArrowDown}');
+ await expect(
+ within(dialog).getByRole('option', { name: 'Germany (+49)' }),
+ ).toHaveFocus();
+ await expect(args.onValueChange).not.toHaveBeenCalled();
+ await userEvent.keyboard('{Enter}');
+ await expect(args.onValueChange).toHaveBeenLastCalledWith(
+ 'DE',
+ expect.anything(),
+ );
+ await waitFor(() => expect(dialog).not.toBeInTheDocument());
+ },
+};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPicker.stories.tsx b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPicker.stories.tsx
index 6077092e556..79257a3fd52 100644
--- a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPicker.stories.tsx
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPicker.stories.tsx
@@ -1,20 +1,27 @@
import { type Meta, type StoryObj } from '@storybook/react-vite';
-import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+import { fn } from 'storybook/test';
import { DirectionProvider } from '@ui/primitives/layout/DirectionProvider/DirectionProvider';
import { Text } from '@ui/primitives/typography/Text/Text';
import { ComponentDecorator } from '@ui/testing';
import { PhoneCountryPickerExample } from './PhoneCountryPickerExample';
-import { openPhoneCountryPicker } from './openPhoneCountryPicker';
import { PHONE_COUNTRY_PICKER_STORY_A11Y_PARAMETERS } from './phoneCountryPickerStoryA11yParameters';
+import { testDisabledPhoneCountryPicker } from './testDisabledPhoneCountryPicker';
+import { testPhoneCountryCallingCodeDirection } from './testPhoneCountryCallingCodeDirection';
+import { testPhoneCountryNullSelection } from './testPhoneCountryNullSelection';
+import { testPhoneCountrySelection } from './testPhoneCountrySelection';
const meta: Meta<typeof PhoneCountryPickerExample> = {
id: 'ui-input-phonecountrypicker',
title: 'UI/Components/Input/PhoneCountryPicker',
component: PhoneCountryPickerExample,
render: (args) => (
- <PhoneCountryPickerExample key={args.initialValue} {...args} />
+ <PhoneCountryPickerExample
+ key={args.initialValue}
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...args}
+ />
),
decorators: [ComponentDecorator],
parameters: {
@@ -40,114 +47,41 @@ export const Display: Story = {
export const Default: Story = {
args: { onValueChange: fn() },
- play: async ({ canvasElement, args }) => {
- const { dialog, trigger } = await openPhoneCountryPicker({ canvasElement });
- const choices = within(dialog).getAllByRole('button');
-
- await expect(trigger).toHaveAccessibleDescription('France');
- await expect(choices.map((choice) => choice.textContent)).toEqual([
- expect.stringContaining('France (+33)'),
- expect.stringContaining('Canada (+1)'),
- expect.stringContaining('Germany (+49)'),
- expect.stringContaining('United Kingdom (+44)'),
- expect.stringContaining('United States (+1)'),
- ]);
- await expect(
- within(dialog).getByRole('button', { name: 'France (+33)' }),
- ).toHaveAttribute('aria-pressed', 'true');
- await userEvent.click(
- within(dialog).getByRole('button', { name: 'Canada (+1)' }),
- );
- await expect(args.onValueChange).toHaveBeenCalledOnce();
- await expect(args.onValueChange).toHaveBeenCalledWith('CA');
- await waitFor(() => expect(dialog).not.toBeInTheDocument());
- await waitFor(() => expect(trigger).toHaveFocus());
- await expect(trigger).toHaveAccessibleDescription('Canada');
- await expect(
- within(canvasElement).getByRole('status', {
- name: 'Phone country selection',
- }),
- ).toHaveTextContent('Canada (+1)');
-
- const reopened = await openPhoneCountryPicker({ canvasElement });
+ play: testPhoneCountrySelection,
+};
- await expect(
- within(reopened.dialog).getAllByRole('button')[0],
- ).toHaveAccessibleName('Canada (+1)');
- await expect(
- within(reopened.dialog).getByRole('button', { name: 'Canada (+1)' }),
- ).toHaveAttribute('aria-pressed', 'true');
- },
+export const Compound: Story = {
+ args: { composition: 'compound', controlled: true, onValueChange: fn() },
+ play: testPhoneCountrySelection,
};
export const Dark: Story = {
- ...Default,
args: { onValueChange: fn() },
globals: { colorScheme: 'dark' },
+ play: testPhoneCountrySelection,
};
export const International: Story = {
- args: { initialValue: '' },
- play: async ({ canvasElement }) => {
- const { dialog, trigger } = await openPhoneCountryPicker({ canvasElement });
-
- await expect(trigger).not.toHaveAccessibleDescription();
- for (const choice of within(dialog).getAllByRole('button')) {
- await expect(choice).toHaveAttribute('aria-pressed', 'false');
- }
- await userEvent.click(
- within(dialog).getByRole('button', { name: 'United States (+1)' }),
- );
- await waitFor(() => expect(dialog).not.toBeInTheDocument());
- await expect(trigger).toHaveAccessibleDescription('United States');
- await expect(
- within(canvasElement).getByRole('status', {
- name: 'Phone country selection',
- }),
- ).toHaveTextContent('United States (+1)');
- },
+ args: { initialValue: null, onValueChange: fn() },
+ play: testPhoneCountryNullSelection,
};
export const Disabled: Story = {
args: { disabled: true, onValueChange: fn() },
- play: async ({ canvasElement, args }) => {
- const trigger = within(canvasElement).getByRole('button', {
- name: 'Phone country',
- });
-
- await expect(trigger).toBeDisabled();
- await userEvent.click(trigger);
- await expect(
- within(canvasElement.ownerDocument.body).queryByRole('dialog'),
- ).not.toBeInTheDocument();
- await expect(args.onValueChange).not.toHaveBeenCalled();
- },
+ play: testDisabledPhoneCountryPicker,
};
export const RightToLeft: Story = {
render: (args) => (
<DirectionProvider direction="rtl">
<Text dir="rtl">
- <PhoneCountryPickerExample key={args.initialValue} {...args} />
+ <PhoneCountryPickerExample
+ key={args.initialValue}
+ // oxlint-disable-next-line react/jsx-props-no-spreading
+ {...args}
+ />
</Text>
</DirectionProvider>
),
- play: async ({ canvasElement }) => {
- const { dialog, trigger } = await openPhoneCountryPicker({ canvasElement });
-
- await expect(getComputedStyle(trigger).direction).toBe('rtl');
- await expect(getComputedStyle(trigger).borderLeftWidth).toBe('1px');
- await expect(getComputedStyle(trigger).borderRightWidth).toBe('0px');
- await expect(getComputedStyle(dialog).direction).toBe('rtl');
- await userEvent.click(
- within(dialog).getByRole('button', { name: 'United Kingdom (+44)' }),
- );
- await waitFor(() => expect(dialog).not.toBeInTheDocument());
- await waitFor(() => expect(trigger).toHaveFocus());
- await expect(
- within(canvasElement).getByRole('status', {
- name: 'Phone country selection',
- }),
- ).toHaveTextContent('United Kingdom (+44)');
- },
+ play: testPhoneCountryCallingCodeDirection,
};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPickerExample.tsx b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPickerExample.tsx
index ce60a91532f..7e9d7fa8d08 100644
--- a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPickerExample.tsx
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/PhoneCountryPickerExample.tsx
@@ -1,6 +1,7 @@
import { useState } from 'react';
import { Dropdown } from '@ui/components/navigation/Dropdown/Dropdown';
+import { type DropdownSelectionGroupChangeEventDetails } from '@ui/components/navigation/Dropdown/types/DropdownSelectionGroupChangeEventDetails';
import { Text } from '@ui/primitives/typography/Text/Text';
import { themeCssVariables } from '@ui/theme';
import { isDefined } from '@ui/utilities/utils/isDefined';
@@ -10,26 +11,50 @@ import { type PhoneCountryOption } from '../types/PhoneCountryOption';
import { PHONE_COUNTRY_OPTIONS } from './phoneCountryOptions';
type PhoneCountryPickerExampleProps = {
- initialValue?: string;
+ initialValue?: string | null;
+ composition?: 'shorthand' | 'compound';
+ controlled?: boolean;
disabled?: boolean;
label?: string;
countries?: readonly PhoneCountryOption[];
searchLabel?: string;
+ listLabel?: string;
emptyLabel?: string;
- onValueChange?: (value: string) => void;
+ onValueChange?: (
+ value: string | null,
+ eventDetails: DropdownSelectionGroupChangeEventDetails,
+ ) => void;
};
export const PhoneCountryPickerExample = ({
initialValue = 'FR',
+ composition = 'shorthand',
+ controlled = false,
disabled = false,
label = 'Phone country',
countries = PHONE_COUNTRY_OPTIONS,
searchLabel,
+ listLabel,
emptyLabel,
onValueChange,
}: PhoneCountryPickerExampleProps) => {
const [value, setValue] = useState(initialValue);
const country = countries.find((choice) => choice.value === value);
+ const handleValueChange = ({
+ nextValue,
+ eventDetails,
+ }: {
+ nextValue: string | null;
+ eventDetails: DropdownSelectionGroupChangeEventDetails;
+ }) => {
+ onValueChange?.(nextValue, eventDetails);
+
+ if (eventDetails.isCanceled) {
+ return;
+ }
+
+ setValue(nextValue);
+ };
return (
<Text
@@ -41,25 +66,41 @@ export const PhoneCountryPickerExample = ({
}}
>
<Text>{label}</Text>
- <Dropdown.Root type="picker">
- <PhoneCountryPicker.Trigger
+ {composition === 'shorthand' ? (
+ <PhoneCountryPicker
aria-label={label}
- country={country}
+ countries={countries}
+ value={controlled ? value : undefined}
+ defaultValue={initialValue}
+ onValueChange={(nextValue, eventDetails) =>
+ handleValueChange({ nextValue, eventDetails })
+ }
disabled={disabled}
+ contentProps={{ 'aria-label': `${label} choices`, width: 280 }}
+ optionsProps={{ searchLabel, listLabel, emptyLabel }}
/>
- <Dropdown.Content aria-label={`${label} choices`} width={280}>
- <PhoneCountryPicker.Options
- countries={countries}
- value={value}
- onValueChange={(nextValue) => {
- setValue(nextValue);
- onValueChange?.(nextValue);
- }}
- searchLabel={searchLabel}
- emptyLabel={emptyLabel}
- />
- </Dropdown.Content>
- </Dropdown.Root>
+ ) : (
+ <PhoneCountryPicker.Root
+ countries={countries}
+ value={controlled ? value : undefined}
+ defaultValue={initialValue}
+ onValueChange={(nextValue, eventDetails) =>
+ handleValueChange({ nextValue, eventDetails })
+ }
+ disabled={disabled}
+ >
+ <Dropdown.Root type="picker">
+ <PhoneCountryPicker.Trigger aria-label={label} />
+ <Dropdown.Content aria-label={`${label} choices`} width={280}>
+ <PhoneCountryPicker.Options
+ searchLabel={searchLabel}
+ listLabel={listLabel}
+ emptyLabel={emptyLabel}
+ />
+ </Dropdown.Content>
+ </Dropdown.Root>
+ </PhoneCountryPicker.Root>
+ )}
<Text
role="status"
aria-label={`${label} selection`}
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/testDisabledPhoneCountryPicker.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/testDisabledPhoneCountryPicker.ts
new file mode 100644
index 00000000000..010d09288d4
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/testDisabledPhoneCountryPicker.ts
@@ -0,0 +1,22 @@
+import { expect, userEvent, within } from 'storybook/test';
+
+import { type PhoneCountryPickerRootProps } from '../types/PhoneCountryPickerRootProps';
+
+export const testDisabledPhoneCountryPicker = async ({
+ canvasElement,
+ args,
+}: {
+ canvasElement: HTMLElement;
+ args: Pick<PhoneCountryPickerRootProps, 'onValueChange'>;
+}) => {
+ const disabledTrigger = within(canvasElement).getByRole('button', {
+ name: 'Phone country',
+ });
+
+ await expect(disabledTrigger).toBeDisabled();
+ await userEvent.click(disabledTrigger);
+ await expect(
+ within(canvasElement.ownerDocument.body).queryByRole('dialog'),
+ ).not.toBeInTheDocument();
+ await expect(args.onValueChange).not.toHaveBeenCalled();
+};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/testPhoneCountryCallingCodeDirection.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/testPhoneCountryCallingCodeDirection.ts
new file mode 100644
index 00000000000..0e97258b1a8
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/testPhoneCountryCallingCodeDirection.ts
@@ -0,0 +1,24 @@
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+
+import { openPhoneCountryPicker } from './openPhoneCountryPicker';
+
+export const testPhoneCountryCallingCodeDirection = async ({
+ canvasElement,
+}: {
+ canvasElement: HTMLElement;
+}) => {
+ const { dialog, trigger } = await openPhoneCountryPicker({ canvasElement });
+
+ await expect(getComputedStyle(trigger).direction).toBe('rtl');
+ await expect(getComputedStyle(dialog).direction).toBe('rtl');
+ const option = within(dialog).getByRole('option', {
+ name: 'United Kingdom (+44)',
+ });
+ const callingCode = within(option).getByText('+44');
+
+ await expect(callingCode).toHaveAttribute('dir', 'ltr');
+ await expect(getComputedStyle(callingCode).direction).toBe('ltr');
+ await userEvent.click(option);
+ await waitFor(() => expect(dialog).not.toBeInTheDocument());
+ await expect(trigger).toHaveAccessibleDescription('United Kingdom');
+};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/testPhoneCountryNullSelection.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/testPhoneCountryNullSelection.ts
new file mode 100644
index 00000000000..c07b5651e96
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/testPhoneCountryNullSelection.ts
@@ -0,0 +1,31 @@
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+
+import { type PhoneCountryPickerRootProps } from '../types/PhoneCountryPickerRootProps';
+import { openPhoneCountryPicker } from './openPhoneCountryPicker';
+
+export const testPhoneCountryNullSelection = async ({
+ canvasElement,
+ args,
+}: {
+ canvasElement: HTMLElement;
+ args: Pick<PhoneCountryPickerRootProps, 'onValueChange'>;
+}) => {
+ const { dialog, trigger } = await openPhoneCountryPicker({ canvasElement });
+
+ await expect(trigger).not.toHaveAccessibleDescription();
+
+ for (const option of within(dialog).getAllByRole('option')) {
+ await expect(option).toHaveAttribute('aria-selected', 'false');
+ }
+
+ await userEvent.click(
+ within(dialog).getByRole('option', { name: 'United States (+1)' }),
+ );
+ await waitFor(() => expect(dialog).not.toBeInTheDocument());
+ await expect(trigger).toHaveAccessibleDescription('United States');
+ await expect(args.onValueChange).toHaveBeenCalledOnce();
+ await expect(args.onValueChange).toHaveBeenLastCalledWith(
+ 'US',
+ expect.anything(),
+ );
+};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/testPhoneCountrySelection.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/testPhoneCountrySelection.ts
new file mode 100644
index 00000000000..42845689d01
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__stories__/testPhoneCountrySelection.ts
@@ -0,0 +1,47 @@
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+
+import { type PhoneCountryPickerRootProps } from '../types/PhoneCountryPickerRootProps';
+import { openPhoneCountryPicker } from './openPhoneCountryPicker';
+
+export const testPhoneCountrySelection = async ({
+ canvasElement,
+ args,
+}: {
+ canvasElement: HTMLElement;
+ args: Pick<PhoneCountryPickerRootProps, 'onValueChange'>;
+}) => {
+ const { dialog, trigger } = await openPhoneCountryPicker({ canvasElement });
+ const canada = within(dialog).getByRole('option', { name: 'Canada (+1)' });
+
+ await expect(trigger).toHaveAccessibleDescription('France');
+ await expect(within(dialog).getByRole('listbox')).toBeVisible();
+ await expect(
+ within(dialog).getByRole('option', { name: 'France (+33)' }),
+ ).toHaveAttribute('aria-selected', 'true');
+ await userEvent.click(canada);
+ await expect(args.onValueChange).toHaveBeenCalledOnce();
+ await expect(args.onValueChange).toHaveBeenLastCalledWith(
+ 'CA',
+ expect.objectContaining({
+ reason: 'item-press',
+ trigger: canada,
+ isCanceled: false,
+ }),
+ );
+ await waitFor(() => expect(dialog).not.toBeInTheDocument());
+ await expect(trigger).toHaveAccessibleDescription('Canada');
+ await expect(
+ within(canvasElement).getByRole('status', {
+ name: 'Phone country selection',
+ }),
+ ).toHaveTextContent('Canada (+1)');
+ const reopened = await openPhoneCountryPicker({ canvasElement });
+
+ await expect(
+ within(reopened.dialog).getAllByRole('option')[0],
+ ).toHaveAccessibleName('Canada (+1)');
+ await expect(
+ within(reopened.dialog).getByRole('option', { name: 'Canada (+1)' }),
+ ).toHaveAttribute('aria-selected', 'true');
+ await userEvent.keyboard('{Escape}');
+};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__tests__/PhoneCountryPicker.test.tsx b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__tests__/PhoneCountryPicker.test.tsx
index 4de91df46e6..1e3b0320879 100644
--- a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__tests__/PhoneCountryPicker.test.tsx
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__tests__/PhoneCountryPicker.test.tsx
@@ -7,36 +7,80 @@ import { Dropdown } from '@ui/components/navigation/Dropdown/Dropdown';
import { PhoneCountryPicker } from '../PhoneCountryPicker';
import styles from '../PhoneCountryPicker.module.scss';
+import { PHONE_COUNTRY_OPTIONS } from '../__stories__/phoneCountryOptions';
const PhoneCountryPickerWrapper = ({ children }: { children: ReactNode }) => (
- <Dropdown.Root type="picker">{children}</Dropdown.Root>
+ <PhoneCountryPicker.Root countries={PHONE_COUNTRY_OPTIONS} defaultValue="FR">
+ <Dropdown.Root type="picker">{children}</Dropdown.Root>
+ </PhoneCountryPicker.Root>
+);
+
+const PhoneCountryPickerOptionsWrapper = ({
+ children,
+}: {
+ children: ReactNode;
+}) => (
+ <PhoneCountryPicker.Root countries={PHONE_COUNTRY_OPTIONS} defaultValue="FR">
+ <Dropdown.Root type="picker" open>
+ <Dropdown.Content aria-label="Phone country">{children}</Dropdown.Content>
+ </Dropdown.Root>
+ </PhoneCountryPicker.Root>
);
+runComponentConformance({
+ name: 'PhoneCountryPicker',
+ element: (
+ <PhoneCountryPicker
+ countries={PHONE_COUNTRY_OPTIONS}
+ defaultValue="FR"
+ aria-label="Phone country"
+ />
+ ),
+ refInstanceOf: HTMLButtonElement,
+ ownClassName: styles.trigger,
+ renderPropTagName: 'button',
+});
+
runComponentConformance({
name: 'PhoneCountryPicker.Trigger',
element: <PhoneCountryPicker.Trigger aria-label="Phone country" />,
refInstanceOf: HTMLButtonElement,
wrapper: PhoneCountryPickerWrapper,
ownClassName: styles.trigger,
- skip: ['renderProp'],
+ renderPropTagName: 'button',
+});
+
+runComponentConformance({
+ name: 'PhoneCountryPicker.Options',
+ element: <PhoneCountryPicker.Options />,
+ refInstanceOf: HTMLDivElement,
+ wrapper: PhoneCountryPickerOptionsWrapper,
+ ownClassName: styles.options,
+ renderPropTagName: 'div',
});
describe('PhoneCountryPicker.Trigger', () => {
it('preserves native button attributes and the accessible name with a decorative flag', () => {
render(
- <PhoneCountryPickerWrapper>
- <PhoneCountryPicker.Trigger
- aria-label="Phone country"
- name="phone-country"
- value="CA"
- country={{
+ <PhoneCountryPicker.Root
+ countries={[
+ {
value: 'CA',
label: 'Canada',
callingCode: '1',
flag: <svg role="img" aria-label="Canada flag" />,
- }}
- />
- </PhoneCountryPickerWrapper>,
+ },
+ ]}
+ value="CA"
+ >
+ <Dropdown.Root type="picker">
+ <PhoneCountryPicker.Trigger
+ aria-label="Phone country"
+ name="phone-country"
+ value="CA"
+ />
+ </Dropdown.Root>
+ </PhoneCountryPicker.Root>,
);
const trigger = screen.getByRole('button', { name: 'Phone country' });
@@ -56,12 +100,6 @@ describe('PhoneCountryPicker.Trigger', () => {
<PhoneCountryPicker.Trigger
aria-label="Phone country"
aria-describedby="phone-country-hint"
- country={{
- value: 'FR',
- label: 'France',
- callingCode: '33',
- flag: <svg />,
- }}
/>
</PhoneCountryPickerWrapper>,
);
@@ -71,15 +109,38 @@ describe('PhoneCountryPicker.Trigger', () => {
).toHaveAccessibleDescription('France Used for text messages');
});
- it('has no description without a selected country', () => {
+ it.each([null, 'unknown'])(
+ 'has no description for an unresolved selection %s',
+ (value) => {
+ render(
+ <PhoneCountryPicker.Root
+ countries={PHONE_COUNTRY_OPTIONS}
+ value={value}
+ >
+ <Dropdown.Root type="picker">
+ <PhoneCountryPicker.Trigger aria-label="Phone country" />
+ </Dropdown.Root>
+ </PhoneCountryPicker.Root>,
+ );
+
+ expect(
+ screen.getByRole('button', { name: 'Phone country' }),
+ ).not.toHaveAccessibleDescription();
+ },
+ );
+
+ it('keeps caller-owned trigger content alongside the selected description', () => {
render(
<PhoneCountryPickerWrapper>
- <PhoneCountryPicker.Trigger aria-label="Phone country" />
+ <PhoneCountryPicker.Trigger aria-label="Phone country">
+ Choose country
+ </PhoneCountryPicker.Trigger>
</PhoneCountryPickerWrapper>,
);
- expect(
- screen.getByRole('button', { name: 'Phone country' }),
- ).not.toHaveAccessibleDescription();
+ const trigger = screen.getByRole('button', { name: 'Phone country' });
+
+ expect(trigger).toHaveTextContent('Choose country');
+ expect(trigger).toHaveAccessibleDescription('France');
});
});
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/__tests__/matchesPhoneCountrySearch.test.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__tests__/matchesPhoneCountrySearch.test.ts
new file mode 100644
index 00000000000..ef845b844aa
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/__tests__/matchesPhoneCountrySearch.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from 'vitest';
+
+import { matchesPhoneCountrySearch } from '../internal/matchesPhoneCountrySearch';
+
+const REUNION = {
+ callingCode: '262',
+ searchLabel: 'reunion',
+ searchValue: 're',
+};
+
+const CANADA = {
+ callingCode: '1',
+ searchLabel: 'canada',
+ searchValue: 'ca',
+};
+
+const UNITED_STATES = {
+ callingCode: '1',
+ searchLabel: 'united states',
+ searchValue: 'us',
+};
+
+describe('matchesPhoneCountrySearch', () => {
+ it.each(['reunion', 're', '262', '62', ''])(
+ 'matches a prepared label, identifier or calling code for %s',
+ (normalizedSearch) => {
+ expect(
+ matchesPhoneCountrySearch({
+ country: REUNION,
+ normalizedSearch,
+ callingCodeSearch: normalizedSearch,
+ }),
+ ).toBe(true);
+ },
+ );
+
+ it('keeps countries sharing a calling code independently searchable', () => {
+ expect(
+ matchesPhoneCountrySearch({
+ country: CANADA,
+ normalizedSearch: '+1',
+ callingCodeSearch: '1',
+ }),
+ ).toBe(true);
+ expect(
+ matchesPhoneCountrySearch({
+ country: UNITED_STATES,
+ normalizedSearch: '+1',
+ callingCodeSearch: '1',
+ }),
+ ).toBe(true);
+ expect(
+ matchesPhoneCountrySearch({
+ country: CANADA,
+ normalizedSearch: 'us',
+ callingCodeSearch: 'us',
+ }),
+ ).toBe(false);
+ expect(
+ matchesPhoneCountrySearch({
+ country: UNITED_STATES,
+ normalizedSearch: 'us',
+ callingCodeSearch: 'us',
+ }),
+ ).toBe(true);
+ });
+
+ it.each([
+ { normalizedSearch: '+', callingCodeSearch: '' },
+ { normalizedSearch: '++262', callingCodeSearch: '+262' },
+ { normalizedSearch: '🇷🇪', callingCodeSearch: '🇷🇪' },
+ { normalizedSearch: 'france', callingCodeSearch: 'france' },
+ { normalizedSearch: 're +262', callingCodeSearch: 're +262' },
+ ])(
+ 'does not match unsupported combined fields or flag content for $normalizedSearch',
+ ({ normalizedSearch, callingCodeSearch }) => {
+ expect(
+ matchesPhoneCountrySearch({
+ country: REUNION,
+ normalizedSearch,
+ callingCodeSearch,
+ }),
+ ).toBe(false);
+ },
+ );
+});
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerContext.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerContext.ts
new file mode 100644
index 00000000000..ad0339dda56
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerContext.ts
@@ -0,0 +1,12 @@
+import { createContext } from 'react';
+
+import { type PhoneCountryPickerRootProps } from '../types/PhoneCountryPickerRootProps';
+import { type PreparedPhoneCountryOption } from './PreparedPhoneCountryOption';
+
+export const PhoneCountryPickerContext = createContext<{
+ countries: readonly PreparedPhoneCountryOption[];
+ value: string | null;
+ onValueChange: NonNullable<PhoneCountryPickerRootProps['onValueChange']>;
+ disabled: boolean;
+ closeOnSelect: boolean;
+} | null>(null);
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerOptions.tsx b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerOptions.tsx
index 4dcba1a97cb..ed693d4560a 100644
--- a/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerOptions.tsx
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerOptions.tsx
@@ -1,27 +1,51 @@
+import { useRender } from '@base-ui/react/use-render';
import { isNonEmptyArray } from '@sniptt/guards';
-import { useState } from 'react';
+import { clsx } from 'clsx';
+import { useId, useState } from 'react';
import { Dropdown } from '@ui/components/navigation/Dropdown/Dropdown';
import { OverflowingTextWithTooltip } from '@ui/primitives/typography/OverflowingTextWithTooltip/OverflowingTextWithTooltip';
-import { normalizeSearchText } from '@ui/utilities/utils/normalizeSearchText';
+import { doNotTranslate } from '@ui/utilities/internal/doNotTranslate';
import { isDefined } from '@ui/utilities/utils/isDefined';
+import { normalizeSearchText } from '@ui/utilities/utils/normalizeSearchText';
import styles from '../PhoneCountryPicker.module.scss';
import { type PhoneCountryPickerOptionsProps } from '../types/PhoneCountryPickerOptionsProps';
import { getPhoneCountryOptionLabel } from './getPhoneCountryOptionLabel';
-import { doNotTranslate } from '@ui/utilities/internal/doNotTranslate';
+import { getPhoneCountryOptionTooltipLabel } from './getPhoneCountryOptionTooltipLabel';
+import { matchesPhoneCountrySearch } from './matchesPhoneCountrySearch';
+import { usePhoneCountryPickerContextOrThrow } from './usePhoneCountryPickerContextOrThrow';
export const PhoneCountryPickerOptions = ({
- countries,
- value,
- onValueChange,
searchLabel = doNotTranslate('Search'),
+ listLabel = doNotTranslate('Countries'),
emptyLabel = doNotTranslate('No results'),
+ disabled: optionsDisabled = false,
+ className,
+ render,
+ ref,
+ ...props
}: PhoneCountryPickerOptionsProps) => {
+ const {
+ countries,
+ value,
+ onValueChange,
+ disabled: rootDisabled,
+ closeOnSelect,
+ } = usePhoneCountryPickerContextOrThrow();
+ const disabled = rootDisabled || optionsDisabled;
+ const selectionId = useId();
const [search, setSearch] = useState('');
- const normalizedSearch = normalizeSearchText(search);
- const matchingCountries = countries.filter(({ label }) =>
- normalizeSearchText(label).includes(normalizedSearch),
+ const normalizedSearch = normalizeSearchText(search).trim();
+ const callingCodeSearch = normalizedSearch.startsWith('+')
+ ? normalizedSearch.slice(1)
+ : normalizedSearch;
+ const matchingCountries = countries.filter((country) =>
+ matchesPhoneCountrySearch({
+ country,
+ normalizedSearch,
+ callingCodeSearch,
+ }),
);
const selectedCountry = matchingCountries.find(
(country) => country.value === value,
@@ -33,47 +57,66 @@ export const PhoneCountryPickerOptions = ({
]
: matchingCountries;
- return (
- <>
- <Dropdown.Search
- value={search}
- onValueChange={setSearch}
- placeholder={searchLabel}
- aria-label={searchLabel}
- />
- <Dropdown.Separator />
- <Dropdown.Section scrollable>
- {!isNonEmptyArray(orderedCountries) && (
- <Dropdown.Empty>{emptyLabel}</Dropdown.Empty>
- )}
- {orderedCountries.map((country) => {
- const optionLabel = getPhoneCountryOptionLabel(country);
-
- return (
- <Dropdown.OptionItem
- key={country.value}
- aria-label={optionLabel}
- selected={country.value === value}
- onSelect={() => onValueChange(country.value)}
- startIcon={
- <span className={styles.optionFlag} aria-hidden>
- {country.flag}
- </span>
- }
+ return useRender({
+ render,
+ ref,
+ props: {
+ ...props,
+ className: clsx(styles.options, className),
+ children: (
+ <>
+ <Dropdown.Search
+ value={search}
+ onValueChange={setSearch}
+ placeholder={searchLabel}
+ aria-label={searchLabel}
+ disabled={disabled}
+ />
+ <Dropdown.Separator />
+ <Dropdown.Section scrollable>
+ <Dropdown.SelectionGroup
+ id={selectionId}
+ aria-label={listLabel}
+ value={value}
+ onValueChange={onValueChange}
+ closeOnSelect={closeOnSelect}
>
- <OverflowingTextWithTooltip
- text={
- <>
- {country.label} (<bdi dir="ltr">+{country.callingCode}</bdi>
- )
- </>
- }
- tooltipContent={optionLabel}
- />
- </Dropdown.OptionItem>
- );
- })}
- </Dropdown.Section>
- </>
- );
+ {orderedCountries.map((country) => {
+ const optionLabel = getPhoneCountryOptionLabel(country);
+
+ return (
+ <Dropdown.OptionItem
+ key={country.value}
+ value={country.value}
+ aria-label={optionLabel}
+ disabled={disabled || country.disabled}
+ startIcon={
+ <span className={styles.optionFlag} aria-hidden>
+ {country.flag}
+ </span>
+ }
+ >
+ <OverflowingTextWithTooltip
+ text={
+ <>
+ {country.label} (
+ <bdi dir="ltr">+{country.callingCode}</bdi>)
+ </>
+ }
+ tooltipContent={getPhoneCountryOptionTooltipLabel(
+ country,
+ )}
+ />
+ </Dropdown.OptionItem>
+ );
+ })}
+ </Dropdown.SelectionGroup>
+ </Dropdown.Section>
+ <Dropdown.Empty className={styles.emptyStatus}>
+ {isNonEmptyArray(orderedCountries) ? null : emptyLabel}
+ </Dropdown.Empty>
+ </>
+ ),
+ },
+ });
};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerRoot.tsx b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerRoot.tsx
new file mode 100644
index 00000000000..bb2904c1f8f
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerRoot.tsx
@@ -0,0 +1,47 @@
+import { isUndefined } from '@sniptt/guards';
+import { useState } from 'react';
+
+import { normalizeSearchText } from '@ui/utilities/utils/normalizeSearchText';
+
+import { type PhoneCountryPickerRootProps } from '../types/PhoneCountryPickerRootProps';
+import { PhoneCountryPickerContext } from './PhoneCountryPickerContext';
+
+export const PhoneCountryPickerRoot = ({
+ children,
+ countries,
+ value: controlledValue,
+ defaultValue = null,
+ onValueChange,
+ disabled = false,
+ closeOnSelect = true,
+}: PhoneCountryPickerRootProps) => {
+ const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue);
+ const value = isUndefined(controlledValue)
+ ? uncontrolledValue
+ : controlledValue;
+ const preparedCountries = countries.map((country) => ({
+ ...country,
+ searchLabel: normalizeSearchText(country.label),
+ searchValue: normalizeSearchText(country.value),
+ }));
+
+ return (
+ <PhoneCountryPickerContext.Provider
+ value={{
+ countries: preparedCountries,
+ value,
+ disabled,
+ closeOnSelect,
+ onValueChange: (nextValue, eventDetails) => {
+ onValueChange?.(nextValue, eventDetails);
+
+ if (!eventDetails.isCanceled && isUndefined(controlledValue)) {
+ setUncontrolledValue(nextValue);
+ }
+ },
+ }}
+ >
+ {children}
+ </PhoneCountryPickerContext.Provider>
+ );
+};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerTrigger.tsx b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerTrigger.tsx
index d077943b6d0..5adfac81ee1 100644
--- a/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerTrigger.tsx
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PhoneCountryPickerTrigger.tsx
@@ -8,13 +8,17 @@ import { isDefined } from '@ui/utilities/utils/isDefined';
import styles from '../PhoneCountryPicker.module.scss';
import { type PhoneCountryPickerTriggerProps } from '../types/PhoneCountryPickerTriggerProps';
+import { usePhoneCountryPickerContextOrThrow } from './usePhoneCountryPickerContextOrThrow';
export const PhoneCountryPickerTrigger = ({
- country,
+ children,
+ disabled: triggerDisabled = false,
className,
'aria-describedby': ariaDescribedBy,
...props
}: PhoneCountryPickerTriggerProps) => {
+ const { countries, value, disabled } = usePhoneCountryPickerContextOrThrow();
+ const country = countries.find((choice) => choice.value === value);
const selectedCountryLabelId = useId();
const describedBy =
[isDefined(country) && selectedCountryLabelId, ariaDescribedBy]
@@ -23,13 +27,20 @@ export const PhoneCountryPickerTrigger = ({
return (
<Dropdown.Trigger
+ // oxlint-disable-next-line react/jsx-props-no-spreading
{...props}
+ disabled={disabled || triggerDisabled}
aria-describedby={describedBy}
className={mergeClassNames(styles.trigger, className)}
>
- <span className={styles.triggerFlag} aria-hidden>
- {country?.flag ?? <IconWorld />}
- </span>
+ {children ?? (
+ <>
+ <span className={styles.triggerFlag} aria-hidden>
+ {country?.flag ?? <IconWorld />}
+ </span>
+ <IconChevronDown className={styles.chevron} aria-hidden />
+ </>
+ )}
{isDefined(country) && (
<span
id={selectedCountryLabelId}
@@ -38,7 +49,6 @@ export const PhoneCountryPickerTrigger = ({
{country.label}
</span>
)}
- <IconChevronDown className={styles.chevron} aria-hidden />
</Dropdown.Trigger>
);
};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PreparedPhoneCountryOption.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PreparedPhoneCountryOption.ts
new file mode 100644
index 00000000000..ebfcec224c3
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/PreparedPhoneCountryOption.ts
@@ -0,0 +1,6 @@
+import { type PhoneCountryOption } from '../types/PhoneCountryOption';
+
+export type PreparedPhoneCountryOption = PhoneCountryOption & {
+ searchLabel: string;
+ searchValue: string;
+};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/getPhoneCountryOptionTooltipLabel.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/getPhoneCountryOptionTooltipLabel.ts
new file mode 100644
index 00000000000..b675654cbbc
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/getPhoneCountryOptionTooltipLabel.ts
@@ -0,0 +1,10 @@
+import { type PhoneCountryOption } from '../types/PhoneCountryOption';
+
+const LEFT_TO_RIGHT_ISOLATE = '\u2066';
+const POP_DIRECTIONAL_ISOLATE = '\u2069';
+
+export const getPhoneCountryOptionTooltipLabel = ({
+ label,
+ callingCode,
+}: Pick<PhoneCountryOption, 'label' | 'callingCode'>) =>
+ `${label} (${LEFT_TO_RIGHT_ISOLATE}+${callingCode}${POP_DIRECTIONAL_ISOLATE})`;
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/matchesPhoneCountrySearch.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/matchesPhoneCountrySearch.ts
new file mode 100644
index 00000000000..5fdb37db82e
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/matchesPhoneCountrySearch.ts
@@ -0,0 +1,23 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type PreparedPhoneCountryOption } from './PreparedPhoneCountryOption';
+
+export const matchesPhoneCountrySearch = ({
+ country,
+ normalizedSearch,
+ callingCodeSearch,
+}: {
+ country: Pick<
+ PreparedPhoneCountryOption,
+ 'searchLabel' | 'searchValue' | 'callingCode'
+ >;
+ normalizedSearch: string;
+ callingCodeSearch: string;
+}) => {
+ return (
+ country.searchLabel.includes(normalizedSearch) ||
+ country.searchValue.includes(normalizedSearch) ||
+ (isNonEmptyString(callingCodeSearch) &&
+ country.callingCode.includes(callingCodeSearch))
+ );
+};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/usePhoneCountryPickerContextOrThrow.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/usePhoneCountryPickerContextOrThrow.ts
new file mode 100644
index 00000000000..d853e91f72c
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/internal/usePhoneCountryPickerContextOrThrow.ts
@@ -0,0 +1,20 @@
+import { useContext } from 'react';
+
+import { doNotTranslate } from '@ui/utilities/internal/doNotTranslate';
+import { isDefined } from '@ui/utilities/utils/isDefined';
+
+import { PhoneCountryPickerContext } from './PhoneCountryPickerContext';
+
+export const usePhoneCountryPickerContextOrThrow = () => {
+ const context = useContext(PhoneCountryPickerContext);
+
+ if (!isDefined(context)) {
+ throw new Error(
+ doNotTranslate(
+ 'PhoneCountryPicker parts require PhoneCountryPicker.Root.',
+ ),
+ );
+ }
+
+ return context;
+};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryOption.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryOption.ts
index 41cc105bf4c..6ee64b0d1df 100644
--- a/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryOption.ts
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryOption.ts
@@ -5,4 +5,5 @@ export type PhoneCountryOption = {
label: string;
callingCode: string;
flag: ReactNode;
+ disabled?: boolean;
};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerOptionsProps.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerOptionsProps.ts
index 96f65ca4739..7318abf167e 100644
--- a/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerOptionsProps.ts
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerOptionsProps.ts
@@ -1,9 +1,11 @@
-import { type PhoneCountryOption } from './PhoneCountryOption';
+import { type useRender } from '@base-ui/react/use-render';
-export type PhoneCountryPickerOptionsProps = {
- countries: readonly PhoneCountryOption[];
- value?: string;
- onValueChange: (value: string) => void;
+export type PhoneCountryPickerOptionsProps = Omit<
+ useRender.ComponentProps<'div'>,
+ 'children'
+> & {
+ disabled?: boolean;
searchLabel?: string;
+ listLabel?: string;
emptyLabel?: string;
};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerProps.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerProps.ts
new file mode 100644
index 00000000000..94abb44cfd1
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerProps.ts
@@ -0,0 +1,16 @@
+import { type DropdownContentProps } from '@ui/components/navigation/Dropdown/types/DropdownContentProps';
+import { type DropdownRootProps } from '@ui/components/navigation/Dropdown/types/DropdownRootProps';
+
+import { type PhoneCountryPickerOptionsProps } from './PhoneCountryPickerOptionsProps';
+import { type PhoneCountryPickerRootProps } from './PhoneCountryPickerRootProps';
+import { type PhoneCountryPickerTriggerProps } from './PhoneCountryPickerTriggerProps';
+
+export type PhoneCountryPickerProps = Omit<
+ PhoneCountryPickerRootProps,
+ 'children'
+> &
+ Omit<PhoneCountryPickerTriggerProps, 'value' | 'defaultValue'> & {
+ dropdownProps?: Omit<DropdownRootProps, 'children' | 'type' | 'multiple'>;
+ contentProps?: Omit<DropdownContentProps, 'children'>;
+ optionsProps?: PhoneCountryPickerOptionsProps;
+ };
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerRootProps.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerRootProps.ts
new file mode 100644
index 00000000000..da2a5e662df
--- /dev/null
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerRootProps.ts
@@ -0,0 +1,18 @@
+import { type ReactNode } from 'react';
+
+import { type DropdownSelectionGroupChangeEventDetails } from '@ui/components/navigation/Dropdown/types/DropdownSelectionGroupChangeEventDetails';
+
+import { type PhoneCountryOption } from './PhoneCountryOption';
+
+export type PhoneCountryPickerRootProps = {
+ children: ReactNode;
+ countries: readonly PhoneCountryOption[];
+ value?: string | null;
+ defaultValue?: string | null;
+ onValueChange?: (
+ value: string | null,
+ eventDetails: DropdownSelectionGroupChangeEventDetails,
+ ) => void;
+ disabled?: boolean;
+ closeOnSelect?: boolean;
+};
diff --git a/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerTriggerProps.ts b/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerTriggerProps.ts
index d7e99b8e4f7..7ce53661159 100644
--- a/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerTriggerProps.ts
+++ b/packages/twenty-ui/src/components/input/PhoneCountryPicker/types/PhoneCountryPickerTriggerProps.ts
@@ -1,11 +1,8 @@
import { type DropdownTriggerProps } from '@ui/components/navigation/Dropdown/types/DropdownTriggerProps';
-import { type PhoneCountryOption } from './PhoneCountryOption';
-
export type PhoneCountryPickerTriggerProps = Omit<
DropdownTriggerProps,
- 'children' | 'render' | 'nativeButton' | 'aria-label'
+ 'aria-label'
> & {
- country?: PhoneCountryOption;
'aria-label': string;
};
diff --git a/packages/twenty-ui/src/components/input/index.ts b/packages/twenty-ui/src/components/input/index.ts
index 035be1b4309..6f1f35c2719 100644
--- a/packages/twenty-ui/src/components/input/index.ts
+++ b/packages/twenty-ui/src/components/input/index.ts
@@ -33,6 +33,8 @@ export type { NumberStepperProps } from './NumberStepper/types/NumberStepperProp
export { PhoneCountryPicker } from './PhoneCountryPicker/PhoneCountryPicker';
export type { PhoneCountryOption } from './PhoneCountryPicker/types/PhoneCountryOption';
export type { PhoneCountryPickerOptionsProps } from './PhoneCountryPicker/types/PhoneCountryPickerOptionsProps';
+export type { PhoneCountryPickerProps } from './PhoneCountryPicker/types/PhoneCountryPickerProps';
+export type { PhoneCountryPickerRootProps } from './PhoneCountryPicker/types/PhoneCountryPickerRootProps';
export type { PhoneCountryPickerTriggerProps } from './PhoneCountryPicker/types/PhoneCountryPickerTriggerProps';
export { SearchInput } from './SearchInput/SearchInput';
export type { SearchInputProps } from './SearchInput/types/SearchInputProps';