> ## Documentation Index
> Fetch the complete documentation index at: https://docs.twenty.com/llms.txt
> Use this file to discover all available pages before exploring further.

# PhoneCountryPicker

> Полный селектор страны для телефона и составные части, использующие общие данные о странах и выборе.

## Обзор

`PhoneCountryPicker` объединяет триггер с флагом страны, всплывающее окно, поиск и варианты кода вызова. Используйте полный компонент для обычного выбора или скомпонуйте `Root`, `Trigger` и `Options` с [Dropdown](https://docs.twenty.com/ru/ui/components/navigation/dropdown.md), если вам нужно пользовательское всплывающее окно. Обе формы используют одни и те же подготовленные страны и выбор.

**Light**

[Выбор страны для телефона (light)](https://storybook.twenty.com/iframe.html?id=ui-input-phonecountrypicker--display\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Выбор страны для телефона (dark)](https://storybook.twenty.com/iframe.html?id=ui-input-phonecountrypicker--display\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-input-phonecountrypicker--display)

## Использование

Предоставьте собственные данные о странах и доступное имя триггера. Используйте `value` с `onValueChange` для контролируемого выбора или `defaultValue` для неконтролируемого выбора. `null` означает, что страна не выбрана.

```tsx theme={null}
import { useState } from 'react';
import {
  PhoneCountryPicker,
  type PhoneCountryOption,
} from 'twenty-ui/components/input';

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: '🇺🇸' },
];

export const PhoneCountryExample = () => {
  const [value, setValue] = useState<string | null>('FR');

  return (
    <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',
      }}
    />
  );
};
```

Каждый `PhoneCountryOption` имеет уникальное стабильное значение `value`, локализованную метку страны `label`, состоящий только из цифр `callingCode` без начального знака «плюс» и декоративный узел `flag`. Он также может быть `disabled`. Значения являются идентификаторами, принадлежащими вызывающей стороне, например кодами стран ISO, и возвращаются без изменений. Метки, флаги и коды вызова являются данными представления и не становятся выбранным идентификатором.

Селектор добавляет знак «плюс» и изолирует коды вызова слева направо в строках вариантов и всплывающих подсказках при переполнении, в том числе в интерфейсах справа налево. Указывайте страны в том порядке, в котором они должны отображаться. Выбранная страна отображается первой, пока она соответствует запросу; остальные совпадения сохраняют заданный порядок.

## Составная композиция

Это критическое изменение API для существующих составных вызывающих сторон. Добавьте `PhoneCountryPicker.Root` вокруг `Dropdown.Root`, переместите `countries`, `value` и `onValueChange` из `Options` в `Root` и удалите `Trigger.country`. Теперь обе части требуют `Root` и получают из него выбранную страну.

`Root` управляет странами и контролируемым или неконтролируемым выбором. Поместите общий `Dropdown.Root` внутрь него и скомпонуйте триггер, содержимое и варианты. `Trigger` получает выбранный флаг и доступное описание из `Root`; `Options` считывает те же данные и выбор. Не передавайте этим частям другую страну или выбранное значение.

```tsx theme={null}
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>;
```

Используйте один корневой компонент для каждого селектора. Общий Dropdown управляет открытием, размещением всплывающего окна, страницами, фокусом и навигацией поиска. Используйте `dropdownProps` и `contentProps` в полном селекторе или настраивайте части Dropdown напрямую при составном использовании.

## Поиск и выбор

Поиск находит подстроки в заданных метках стран, стабильных идентификаторах и кодах вызова. Метки и идентификаторы используют общую нормализацию `normalizeSearchText`: текст в нижнем регистре, декомпозицию Unicode NFD и обработку акцентов с учетом системы письма. Например, `reunion` соответствует `Réunion`, а `gb` соответствует идентификатору `GB`. Значимые различия в системах письма сохраняются согласно этой функции-помощнику. Пробелы вокруг запроса удаляются; внутренние пробелы сохраняются. При поиске по коду вызова один начальный знак «плюс» необязателен, поэтому `44`, `+44` и `" +44 "` соответствуют заданному коду вызова `44`. Поиск не анализирует полный номер телефона и не определяет по нему страну.

`onValueChange(value, eventDetails)` получает запрошенный идентификатор и общие сведения `Dropdown.SelectionGroup`: `reason`, нативный `event`, `trigger` выбранного варианта, `cancel()` и `isCanceled`. Вызовите `cancel()` перед обновлением контролируемого состояния, чтобы отклонить запрос. Отмененный запрос сохраняет неконтролируемый выбор и оставляет всплывающее окно открытым. Установите `closeOnSelect={false}`, чтобы оно оставалось открытым после принятого выбора. Изменения выбора не изменяют значение какого-либо поля ввода телефона.

Установите `disabled` для полного селектора или `Root`, чтобы отключить его триггер, поиск и выбор. Отключенная страна остается видимой, и ее нельзя выбрать. `Trigger.disabled` и `Options.disabled` могут дополнительно отключать эти отдельные части.

## Нативные цели и метки

Нативные атрибуты полного селектора, обработчики событий, `className`, `style`, `ref`, `render` и необязательный `children` применяются к его триггеру. `children` заменяет флаг или значок мира и шеврон по умолчанию. `contentProps` применяется к `Dropdown.Content`; `optionsProps` применяется к корневому div вариантов и предоставляет `searchLabel`, `listLabel` и `emptyLabel`. При составном использовании нативные свойства, ссылки и композиция рендеринга применяются к соответствующей кнопке `Trigger` или div `Options`. `Root` не рендерит узел DOM.

Предоставьте локализованные метки стран и обязательный `aria-label` триггера. Метка выбранной страны описывает триггер, а ее флаг и шеврон являются декоративными. При пустом выборе отображается значок мира. Всплывающее окно получает имя триггера, если только его не задает `Dropdown.Title` или явная метка содержимого. `searchLabel` по умолчанию имеет значение `Search` и задаёт имя как поля поиска, так и его заполнителя. По умолчанию `listLabel` имеет значение `Countries` и независимо именует список. `emptyLabel` по умолчанию имеет значение `No results`.

## Интеграция поля ввода телефона

Селектор поставляется без каталога стран, пакета ресурсов флагов или среды выполнения поля ввода телефона. Адаптер фронтенда управляет разбором, проверкой, форматированием телефонов, черновиками редактирования и сохранением. Сопоставьте выбранную страну библиотеки телефона с `Root.value` или `value` полного селектора и сопоставьте изменения страны обратно через один обратный вызов. Сохраняйте текст телефона в его текущем владельце при изменении или очистке страны либо при применении внешнего обновления выбранной страны.

Нативная отправка формы, сброс, обязательность, режим только для чтения и интеграция Field для этого пользовательского селектора отложены. Полный селектор передает нативные атрибуты триггера согласно контракту кнопки Dropdown.

## Средство рендеринга компонентов Front

Фикстуры галереи React и Preact включают полный селектор и составную композицию. Размещение портала, геометрия, прокрутка, закрытие и фокус относятся к общему Dropdown и интеграции рендерера. Селектор не вводит отдельную среду выполнения рендерера.

## Свойства

**aria-label** `string` *required*

Required accessible name for the country selector trigger.

**children** `ReactNode`

Optional trigger content replacing the default country flag or world icon and chevron.

**className** `string | ((state: PopoverTriggerState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**closeDelay** `number` (default: 0)

How long to wait before closing the popover that was opened on hover.
Specified in milliseconds.

Requires the `openOnHover` prop.

**closeOnSelect** `boolean`

Closes the dropdown after an accepted selection. Defaults to true.

**contentProps** `Omit\<DropdownContentProps, "children"\>`

Props for the internally assembled Dropdown.Content, including its accessible name, placement, width and popup ref.

**countries** `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.

**defaultValue** `string | null`

Initial uncontrolled country identifier. Omit it or use null to start empty.

**delay** `number` (default: 300)

How long to wait before the popover may be opened on hover. Specified in milliseconds.

Requires the `openOnHover` prop.

**disabled** `boolean`

Disables the trigger, search and country selection.

**dropdownProps** `Omit\<DropdownRootProps, "children" | "type" | "multiple"\>`

Props for the internally assembled Dropdown.Root, including controlled open state and open-change events. The picker fixes its type to picker.

**id** `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).

**nativeButton** `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>`).

**onValueChange** `((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) =\> 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.

**openOnHover** `boolean` (default: false)

Whether the popover should also open when the trigger is hovered.

**optionsProps** `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.

**ref** `Ref\<HTMLButtonElement\>`

Ref to the trigger button, or the element composed through render.

**render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, PopoverTriggerState\>`

Composes the trigger with an element or render callback. Native attributes, handlers, className, style and ref target the trigger.

**style** `CSSProperties | ((state: PopoverTriggerState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

**value** `string | null`

Controlled country identifier. Use null to clear the selection. Labels and calling codes do not replace this value.

### PhoneCountryPicker.Root

**Root.children** `ReactNode` *required*

A Dropdown.Root with type="picker", its Trigger, Content and Options. Root shares prepared data and selection and renders no DOM node.

**Root.closeOnSelect** `boolean` (default: true)

Closes the composed Dropdown after an accepted selection. Defaults to true.

**Root.countries** `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.

**Root.defaultValue** `string | null` (default: null)

Initial uncontrolled country identifier. Omit it or use null to start empty.

**Root.disabled** `boolean` (default: false)

Disables the composed trigger, search and country selection.

**Root.onValueChange** `((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) =\> 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.

**Root.value** `string | null`

Controlled country identifier shared by the parts. Use null to clear the selection.

### PhoneCountryPicker.Trigger

**Trigger.aria-label** `string` *required*

Required accessible name for the country selector button.

**Trigger.children** `ReactNode`

Optional trigger content replacing the selected country flag or empty world icon and chevron. The selected label comes from Root.

**Trigger.className** `string | ((state: PopoverTriggerState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Trigger.closeDelay** `number` (default: 0)

How long to wait before closing the popover that was opened on hover.
Specified in milliseconds.

Requires the `openOnHover` prop.

**Trigger.delay** `number` (default: 300)

How long to wait before the popover may be opened on hover. Specified in milliseconds.

Requires the `openOnHover` prop.

**Trigger.disabled** `boolean`

Disables the native trigger button in addition to Root.disabled.

**Trigger.id** `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).

**Trigger.nativeButton** `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>`).

**Trigger.openOnHover** `boolean` (default: false)

Whether the popover should also open when the trigger is hovered.

**Trigger.ref** `Ref\<HTMLButtonElement\>`

Ref to the trigger button, or the element composed through render.

**Trigger.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, PopoverTriggerState\>`

Composes the Dropdown trigger with an element or render callback. Native attributes, handlers, className, style and ref target this element.

**Trigger.style** `CSSProperties | ((state: PopoverTriggerState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

### PhoneCountryPicker.Options

**Options.disabled** `boolean`

Disables search and selection in addition to Root.disabled.

**Options.emptyLabel** `string` (default: No results)

Status message shown when no country label, identifier or calling code matches. Defaults to No results.

**Options.listLabel** `string` (default: Countries)

Accessible name of the country listbox, separate from the search field. Defaults to Countries.

**Options.ref** `Ref\<HTMLDivElement\>`

Ref to the options root div, or the element composed through render.

**Options.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, \{\}\>`

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.

**Options.searchLabel** `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.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.