@42-central/ui-react 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/dist/{chunk-I53TMAV2.js → chunk-2RQLPN4U.js} +3 -3
  2. package/dist/{chunk-I53TMAV2.js.map → chunk-2RQLPN4U.js.map} +1 -1
  3. package/dist/{chunk-SOUDKESO.js → chunk-37HYN7PC.js} +3 -3
  4. package/dist/{chunk-SOUDKESO.js.map → chunk-37HYN7PC.js.map} +1 -1
  5. package/dist/{chunk-TGGNSSOJ.js → chunk-5EOMSWNO.js} +4 -4
  6. package/dist/{chunk-TGGNSSOJ.js.map → chunk-5EOMSWNO.js.map} +1 -1
  7. package/dist/{chunk-K3FZHYJL.js → chunk-7FPSQBWB.js} +3 -3
  8. package/dist/{chunk-K3FZHYJL.js.map → chunk-7FPSQBWB.js.map} +1 -1
  9. package/dist/{chunk-WERJ44ZN.js → chunk-DTFSCR3U.js} +3 -3
  10. package/dist/{chunk-WERJ44ZN.js.map → chunk-DTFSCR3U.js.map} +1 -1
  11. package/dist/{chunk-PFZMB3US.js → chunk-FQJNQW3G.js} +3 -3
  12. package/dist/{chunk-PFZMB3US.js.map → chunk-FQJNQW3G.js.map} +1 -1
  13. package/dist/{chunk-ASKQ6N5V.js → chunk-FSPS7TVD.js} +4 -4
  14. package/dist/{chunk-ASKQ6N5V.js.map → chunk-FSPS7TVD.js.map} +1 -1
  15. package/dist/{chunk-GJFCIG34.js → chunk-GEZYGBXY.js} +5 -5
  16. package/dist/{chunk-GJFCIG34.js.map → chunk-GEZYGBXY.js.map} +1 -1
  17. package/dist/{chunk-ULF5LOBS.js → chunk-HMNXNKDA.js} +3 -3
  18. package/dist/{chunk-ULF5LOBS.js.map → chunk-HMNXNKDA.js.map} +1 -1
  19. package/dist/{chunk-NF2PBGD3.js → chunk-IANYMDKH.js} +3 -3
  20. package/dist/{chunk-NF2PBGD3.js.map → chunk-IANYMDKH.js.map} +1 -1
  21. package/dist/{chunk-QEMXXQQO.js → chunk-JKFPRQB2.js} +3 -3
  22. package/dist/{chunk-QEMXXQQO.js.map → chunk-JKFPRQB2.js.map} +1 -1
  23. package/dist/{chunk-P7SH3XWY.js → chunk-MQHD3EJE.js} +3 -3
  24. package/dist/{chunk-P7SH3XWY.js.map → chunk-MQHD3EJE.js.map} +1 -1
  25. package/dist/{chunk-IUK7OJXZ.js → chunk-OBSZ4NE2.js} +5 -4
  26. package/dist/chunk-OBSZ4NE2.js.map +1 -0
  27. package/dist/{chunk-DJ72KP32.js → chunk-OXR7BXZA.js} +3 -3
  28. package/dist/{chunk-DJ72KP32.js.map → chunk-OXR7BXZA.js.map} +1 -1
  29. package/dist/{chunk-LIZWCWED.js → chunk-PQZSTI3R.js} +3 -3
  30. package/dist/{chunk-LIZWCWED.js.map → chunk-PQZSTI3R.js.map} +1 -1
  31. package/dist/{chunk-7BY5I2RB.js → chunk-S5CQRCTF.js} +4 -4
  32. package/dist/{chunk-7BY5I2RB.js.map → chunk-S5CQRCTF.js.map} +1 -1
  33. package/dist/{chunk-BGDVUC3B.js → chunk-TUP7WXQE.js} +3 -3
  34. package/dist/{chunk-BGDVUC3B.js.map → chunk-TUP7WXQE.js.map} +1 -1
  35. package/dist/{chunk-KYVXPSNW.js → chunk-V2QZG4IT.js} +3 -3
  36. package/dist/{chunk-KYVXPSNW.js.map → chunk-V2QZG4IT.js.map} +1 -1
  37. package/dist/components/alert/index.js +1 -1
  38. package/dist/components/ambient-background/index.js +1 -1
  39. package/dist/components/app-shell/index.js +3 -3
  40. package/dist/components/avatar/index.js +2 -2
  41. package/dist/components/calendar/index.js +3 -3
  42. package/dist/components/calendar-heatmap/index.js +2 -2
  43. package/dist/components/camera/index.js +3 -3
  44. package/dist/components/carousel/index.js +2 -2
  45. package/dist/components/code-block/index.js +1 -1
  46. package/dist/components/code-block/static.js.map +1 -1
  47. package/dist/components/compare/index.js +2 -2
  48. package/dist/components/data-table/index.js +10 -10
  49. package/dist/components/date-picker/index.js +7 -7
  50. package/dist/components/drawer/index.js +3 -3
  51. package/dist/components/file-item/index.js +4 -4
  52. package/dist/components/file-preview/index.js +3 -3
  53. package/dist/components/file-upload/index.js +4 -4
  54. package/dist/components/gallery/index.js +2 -2
  55. package/dist/components/image-cropper/index.js +4 -4
  56. package/dist/components/indicator/index.js +1 -1
  57. package/dist/components/kbd/index.js +3 -3
  58. package/dist/components/lightbox/index.js +4 -4
  59. package/dist/components/menu/index.js +2 -2
  60. package/dist/components/modal/index.js +3 -3
  61. package/dist/components/multi-select/index.js +3 -3
  62. package/dist/components/overlays/index.js +4 -4
  63. package/dist/components/password-input/index.js +1 -1
  64. package/dist/components/phone-input/flag.d.ts +9 -0
  65. package/dist/components/phone-input/flag.d.ts.map +1 -0
  66. package/dist/components/phone-input/index.d.ts +4 -0
  67. package/dist/components/phone-input/index.d.ts.map +1 -0
  68. package/dist/components/phone-input/index.js +503 -0
  69. package/dist/components/phone-input/index.js.map +1 -0
  70. package/dist/components/phone-input/phone-input.d.ts +125 -0
  71. package/dist/components/phone-input/phone-input.d.ts.map +1 -0
  72. package/dist/components/phone-input/phone.d.ts +117 -0
  73. package/dist/components/phone-input/phone.d.ts.map +1 -0
  74. package/dist/components/photo-capture/index.js +5 -5
  75. package/dist/components/pills-input/index.js +3 -3
  76. package/dist/components/schedule/index.js +3 -3
  77. package/dist/components/segment-group/index.js +3 -3
  78. package/dist/components/spotlight/index.js +5 -5
  79. package/dist/components/tabs/index.js +3 -3
  80. package/dist/components/tags-input/index.js +3 -3
  81. package/dist/components/time-input/index.js +4 -4
  82. package/dist/components/timeline/index.d.ts +1 -1
  83. package/dist/components/timeline/index.d.ts.map +1 -1
  84. package/dist/components/timeline/index.js +40 -11
  85. package/dist/components/timeline/index.js.map +1 -1
  86. package/dist/components/timeline/timeline.d.ts +8 -3
  87. package/dist/components/timeline/timeline.d.ts.map +1 -1
  88. package/dist/components/tree-multi-select/index.js +3 -3
  89. package/dist/index.js +4 -4
  90. package/dist/lib/dev-warn.d.ts +1 -0
  91. package/dist/lib/dev-warn.d.ts.map +1 -1
  92. package/dist/lib/intl.d.ts +5 -0
  93. package/dist/lib/intl.d.ts.map +1 -1
  94. package/package.json +3 -1
  95. package/src/as-child.contract.test.tsx +2 -0
  96. package/src/components/phone-input/flag.tsx +86 -0
  97. package/src/components/phone-input/index.ts +14 -0
  98. package/src/components/phone-input/phone-input.test.tsx +285 -0
  99. package/src/components/phone-input/phone-input.tsx +527 -0
  100. package/src/components/phone-input/phone.test.ts +187 -0
  101. package/src/components/phone-input/phone.ts +298 -0
  102. package/src/components/timeline/index.ts +1 -0
  103. package/src/components/timeline/timeline.test.tsx +105 -4
  104. package/src/components/timeline/timeline.tsx +46 -11
  105. package/src/lib/dev-warn.ts +1 -1
  106. package/src/lib/intl-direction.test.tsx +23 -0
  107. package/src/lib/intl.tsx +8 -2
  108. package/dist/chunk-IUK7OJXZ.js.map +0 -1
@@ -0,0 +1,527 @@
1
+ "use client"
2
+
3
+ import { ark } from "@ark-ui/react"
4
+ import { Combobox as ArkCombobox } from "@ark-ui/react/combobox"
5
+ import { useFieldContext } from "@ark-ui/react/field"
6
+ import { Globe } from "lucide-react"
7
+ import {
8
+ type ComponentProps,
9
+ type FocusEvent,
10
+ type KeyboardEvent,
11
+ type ReactNode,
12
+ type Ref,
13
+ useMemo,
14
+ useRef,
15
+ useState,
16
+ } from "react"
17
+ import { cn } from "../../lib/cn"
18
+ import { type IconMap, iconStroke, mergeIcons } from "../../lib/icons"
19
+ import { useLocale } from "../../lib/intl"
20
+ import { useMergedRefs } from "../../lib/merge-refs"
21
+ import { props } from "../../lib/props"
22
+ import type { SelectData } from "../../lib/select-data"
23
+ import type { WithTestId } from "../../lib/test-id"
24
+ import { TEXT_COLOR_CLASSES } from "../../lib/typography-size"
25
+ import { useIsomorphicLayoutEffect } from "../../lib/use-isomorphic-layout-effect"
26
+ import { ComboboxList } from "../combobox-list/combobox-list"
27
+ import { type FieldProps, FieldShell, fieldA11yProps } from "../field/field"
28
+ import { InputBase, type InputSize, type InputVariant, inputControlClasses } from "../input/input"
29
+ import { CheckIcon, ChevronIcon } from "../popover/icons"
30
+ import { Popover, popoverChevron, popoverIndicator } from "../popover/popover"
31
+ import { Flag } from "./flag"
32
+ import {
33
+ type CountryCode,
34
+ callingCodeOf,
35
+ caretAfter,
36
+ countryOfLocale,
37
+ deleteAcrossSeparator,
38
+ exampleOf,
39
+ formatPhone,
40
+ PHONE_COUNTRIES,
41
+ type PhoneState,
42
+ parsePhone,
43
+ releaseCountry,
44
+ significantBefore,
45
+ switchCountry,
46
+ } from "./phone"
47
+
48
+ /**
49
+ * PhoneInput — a phone number field with a country picker. It formats as the
50
+ * user types (`06 12 34 56 78` for France, `(201) 555-0123` for the US) and
51
+ * hands back one canonical value, the E.164 string (`"+33612345678"`), which
52
+ * is what a backend or an SMS provider wants.
53
+ *
54
+ * - The country picker at the inline-start is a searchable list (by name or
55
+ * dial code: "33" finds France), with each country's flag. Typing or
56
+ * pasting a dial code (`+44 20 …`) moves it into the trigger, and
57
+ * Backspace at the start of the number pulls it back out for editing.
58
+ * - `onChange(value, { country, isValid })` reports `null` while there is no
59
+ * number. The field never turns red on its own while the user is still
60
+ * typing: read `isValid` (or use the exported `isValidPhoneNumber` in your
61
+ * schema) and pass `error`.
62
+ * - The country defaults to the locale's region (`fr-FR` gives France).
63
+ * Pass `defaultCountry` to pin it, which also keeps SSR and the first
64
+ * client render identical when the locale is `"auto"`.
65
+ *
66
+ * Formatting and validation come from libphonenumber-js (its `min` metadata),
67
+ * flags from country-flag-icons, loaded lazily on first use.
68
+ */
69
+
70
+ export type { CountryCode }
71
+
72
+ type PhoneInputClassNames = {
73
+ /** The field wrapper (label / description / error). */
74
+ field?: string
75
+ /** The label element itself. */
76
+ label?: string
77
+ /** The shell `<div>` (also targeted by `className`). */
78
+ root?: string
79
+ /** The country trigger button. */
80
+ country?: string
81
+ /** The inner `<input>`. */
82
+ input?: string
83
+ /** The country list panel. */
84
+ list?: string
85
+ }
86
+
87
+ export type PhoneInputTranslations = {
88
+ /** The country trigger's accessible name, given the selected country's name (`null` when
89
+ * none is selected). */
90
+ triggerLabel?: (country: string | null) => string
91
+ /** The country search's placeholder. */
92
+ searchPlaceholder?: string
93
+ /** Shown when no country matches the search. */
94
+ empty?: string
95
+ /** Group heading over `preferredCountries`. */
96
+ preferredLabel?: string
97
+ /** Group heading over the rest of the list, when `preferredCountries` is set. */
98
+ allLabel?: string
99
+ }
100
+
101
+ export const PHONE_INPUT_DEFAULT_TRANSLATIONS = {
102
+ triggerLabel: (country: string | null) =>
103
+ country ? `Country: ${country}` : "Country: none selected",
104
+ searchPlaceholder: "Search country",
105
+ empty: "No country found",
106
+ preferredLabel: "Suggested",
107
+ allLabel: "All countries",
108
+ } as const satisfies Required<PhoneInputTranslations>
109
+
110
+ export type PhoneInputIconSlot = "chevron" | "international"
111
+ export type PhoneInputIcons = IconMap<PhoneInputIconSlot>
112
+
113
+ /** The default icons: the trigger's chevron, and the globe shown while no country is set. */
114
+ export const DEFAULT_ICONS: Record<PhoneInputIconSlot, ReactNode> = {
115
+ chevron: <ChevronIcon />,
116
+ international: <Globe className={iconStroke} />,
117
+ }
118
+
119
+ /** What `onChange` reports alongside the value. */
120
+ export type PhoneInputChangeDetails = {
121
+ /** The country the number belongs to, or `null` when it can't be told yet. */
122
+ country: CountryCode | null
123
+ /** A complete, valid number for that country, and the country is in `countries`. */
124
+ isValid: boolean
125
+ }
126
+
127
+ export type PhoneInputProps = Pick<FieldProps, "label" | "description" | "error" | "required"> &
128
+ WithTestId & {
129
+ /** Controlled value, E.164 (`"+33612345678"`); `null` for empty. */
130
+ value?: string | null
131
+ /** Uncontrolled initial value, E.164. */
132
+ defaultValue?: string | null
133
+ /** Fires with the E.164 value (`null` while there's no number) on every change. */
134
+ onChange?: (value: string | null, details: PhoneInputChangeDetails) => void
135
+ /** Controlled country. */
136
+ country?: CountryCode | null
137
+ /** Uncontrolled initial country. Defaults to the locale's region, when it's in `countries`. */
138
+ defaultCountry?: CountryCode | null
139
+ /** Fires when the country changes, picked from the list or detected from a `+…` number. */
140
+ onCountryChange?: (country: CountryCode | null) => void
141
+ /** Only offer these countries. A number from elsewhere still formats, but isn't valid. */
142
+ countries?: readonly CountryCode[]
143
+ /** Pinned at the top of the list, under their own heading. */
144
+ preferredCountries?: readonly CountryCode[]
145
+ /** Draw each country's flag yourself (an emoji, your own sprite). Defaults to the kit's
146
+ * SVG flags. */
147
+ renderFlag?: (country: CountryCode) => ReactNode
148
+ /** Locale for the country names and the default country; defaults to the `IntlProvider`'s. */
149
+ locale?: string
150
+ /**
151
+ * Placeholder shown while the field is empty. Defaults to an example number of the selected
152
+ * country (`06 12 34 56 78` for France) and none while no country is selected. The field's
153
+ * meaning changes with the country, so a fixed string can contradict it (`+33 …` next to a
154
+ * selected France). Pass a function of the country to word it yourself, or `""` for none.
155
+ */
156
+ placeholder?: string | ((country: CountryCode | null) => string | undefined)
157
+ /** Field name for native form submission; submits the E.164 value. */
158
+ name?: string
159
+ /** Red invalid state; OR'd with `error`. */
160
+ invalid?: boolean
161
+ /** Dims the shell and disables the input and the country picker. */
162
+ disabled?: boolean
163
+ /** Keeps full contrast but blocks edits and the country picker. */
164
+ readOnly?: boolean
165
+ variant?: InputVariant
166
+ size?: InputSize
167
+ /** Lands on the `<input>` for focus-on-error. */
168
+ ref?: Ref<HTMLInputElement>
169
+ /** Forwarded to the `<input>`; drives touched/blurred validation. */
170
+ onBlur?: (event: FocusEvent<HTMLInputElement>) => void
171
+ className?: string
172
+ classNames?: PhoneInputClassNames
173
+ /** Overrides the country picker's wording. A partial override keeps the other defaults. */
174
+ translations?: PhoneInputTranslations
175
+ /** Replaces the default icons: `chevron`, `international`. */
176
+ icons?: PhoneInputIcons
177
+ }
178
+
179
+ type CountryPayload = { name: string; callingCode: string }
180
+ type CountryData = SelectData<CountryPayload, CountryCode>
181
+
182
+ /**
183
+ * The country trigger fills the whole start zone of the shell, full height, from its edge to the
184
+ * divider, so the hover wash and the click target are the zone you see rather than a chip inset
185
+ * in it. The shell drops its own start padding (`ps-0!`) and clips (`overflow-clip`), so its
186
+ * rounded corners clip the wash. The trigger takes the padding the shell would have had, per
187
+ * `size`. Its border is the divider, except under `variant="unstyled"`, which draws no chrome. Its focus shows as the shell's own ring (`shellChrome`'s
188
+ * `:has(:focus-visible)`), like every control inside the family.
189
+ */
190
+ const countryTrigger = cn(
191
+ "inline-flex shrink-0 cursor-pointer items-center gap-1 self-stretch outline-none transition-colors",
192
+ "[&:hover:not(:disabled)]:bg-brand-900/6 dark:[&:hover:not(:disabled)]:bg-white/8",
193
+ "disabled:cursor-not-allowed",
194
+ )
195
+
196
+ /** The trigger's inline padding: the shell's own slot-side padding at each size (`inputShell`). */
197
+ const countryTriggerPadding = {
198
+ xs: "px-2",
199
+ sm: "px-2.5",
200
+ md: "px-2.5",
201
+ lg: "px-3.5",
202
+ xl: "px-4",
203
+ } as const satisfies Record<InputSize, string>
204
+
205
+ /** The divider between the country and the number, per `variant`. The same hairline as the
206
+ * shell's own border, and none where the shell draws none. */
207
+ const countryTriggerDivider = {
208
+ default: "border-e border-brand-900/20 dark:border-white/15",
209
+ unstyled: "",
210
+ } as const satisfies Record<InputVariant, string>
211
+
212
+ /** The `<input>`, split out so it reads the `Field` context from inside `FieldShell`. */
213
+ const PhoneInputControl = ({
214
+ ref,
215
+ testId,
216
+ className,
217
+ ...rest
218
+ }: Omit<ComponentProps<"input">, "ref"> & { ref?: Ref<HTMLInputElement>; testId?: string }) => {
219
+ const field = useFieldContext()
220
+ return (
221
+ <ark.input
222
+ ref={ref}
223
+ {...field?.getInputProps()}
224
+ {...fieldA11yProps(field)}
225
+ {...props({ "data-testid": testId })}
226
+ className={className}
227
+ {...rest}
228
+ />
229
+ )
230
+ }
231
+
232
+ export const PhoneInput = ({
233
+ value,
234
+ defaultValue,
235
+ onChange,
236
+ country: countryProp,
237
+ defaultCountry,
238
+ onCountryChange,
239
+ countries,
240
+ preferredCountries,
241
+ renderFlag,
242
+ locale: localeProp,
243
+ placeholder,
244
+ name,
245
+ invalid,
246
+ disabled,
247
+ readOnly,
248
+ required,
249
+ label,
250
+ description,
251
+ error,
252
+ variant = "default",
253
+ size = "md",
254
+ ref,
255
+ onBlur,
256
+ className,
257
+ classNames,
258
+ testId,
259
+ translations,
260
+ icons: iconsProp,
261
+ }: PhoneInputProps) => {
262
+ const locale = useLocale(localeProp)
263
+ const t = { ...PHONE_INPUT_DEFAULT_TRANSLATIONS, ...translations }
264
+ const icons = mergeIcons(DEFAULT_ICONS, iconsProp)
265
+ const isInvalid = invalid || error != null
266
+ const allowed = countries ?? PHONE_COUNTRIES
267
+
268
+ const [initial] = useState<PhoneState>(() => {
269
+ const localeCountry = countryOfLocale(locale)
270
+ const fallback =
271
+ countryProp !== undefined
272
+ ? countryProp
273
+ : defaultCountry !== undefined
274
+ ? defaultCountry
275
+ : localeCountry && allowed.includes(localeCountry)
276
+ ? localeCountry
277
+ : null
278
+ return parsePhone(value ?? defaultValue ?? null, fallback)
279
+ })
280
+ const [text, setText] = useState(initial.text)
281
+ const [innerCountry, setInnerCountry] = useState(initial.country)
282
+ // The last value this field reported (or was handed). A controlled `value` that differs from
283
+ // it came from outside — a reset, a server load — and replaces the text; one that matches is
284
+ // just the parent echoing a keystroke back, and must not reformat what the user is typing.
285
+ const [current, setCurrent] = useState(initial.value)
286
+ const country = countryProp !== undefined ? countryProp : innerCountry
287
+ // Whether the country came from the number itself (a typed or pasted `+…` code, or a value)
288
+ // rather than from the user's pick, `defaultCountry` or `country`. Only then may the digits
289
+ // move it within a shared calling code (`+1 204 …` is Canada, not the US). A chosen country
290
+ // stays put. See `formatPhone`'s `refine`.
291
+ const [resolved, setResolved] = useState(initial.value !== null && initial.country !== null)
292
+
293
+ if (value !== undefined && value !== current) {
294
+ const next = parsePhone(value, country)
295
+ setCurrent(value)
296
+ setText(next.text)
297
+ setInnerCountry(next.country)
298
+ setResolved(next.value !== null && next.country !== null)
299
+ }
300
+
301
+ const inputRef = useRef<HTMLInputElement>(null)
302
+ const mergedRef = useMergedRefs(inputRef, ref)
303
+ const pendingCaret = useRef<number | null>(null)
304
+ const [open, setOpen] = useState(false)
305
+ const picked = useRef(false)
306
+
307
+ // Put the caret back where the user left it, counted in digits, once the formatted text is in
308
+ // the DOM. Only while the input has focus: a programmatic change mustn't steal it.
309
+ useIsomorphicLayoutEffect(() => {
310
+ const caret = pendingCaret.current
311
+ const input = inputRef.current
312
+ pendingCaret.current = null
313
+ if (caret === null || !input || input.ownerDocument.activeElement !== input) return
314
+ input.setSelectionRange(caret, caret)
315
+ })
316
+
317
+ const commit = (next: PhoneState, caretCount: number | null, fromNumber: boolean) => {
318
+ setText(next.text)
319
+ setResolved(fromNumber && next.country !== null)
320
+ pendingCaret.current = caretCount === null ? null : caretAfter(next.text, caretCount)
321
+ if (next.country !== country) {
322
+ setInnerCountry(next.country)
323
+ onCountryChange?.(next.country)
324
+ }
325
+ if (next.value !== current) {
326
+ setCurrent(next.value)
327
+ onChange?.(next.value, {
328
+ country: next.country,
329
+ isValid: next.isValid && next.country !== null && allowed.includes(next.country),
330
+ })
331
+ }
332
+ }
333
+
334
+ const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
335
+ if (event.key !== "Backspace" && event.key !== "Delete") return
336
+ if (event.altKey || event.ctrlKey || event.metaKey) return
337
+ const input = event.currentTarget
338
+ const caret = input.selectionStart
339
+ if (caret === null || caret !== input.selectionEnd) return
340
+ // Backspace at the very start of a national number pulls the dial code back out of the
341
+ // trigger as editable text (see `releaseCountry`).
342
+ if (event.key === "Backspace" && caret === 0 && country && !input.value.startsWith("+")) {
343
+ event.preventDefault()
344
+ const released = releaseCountry(input.value, country)
345
+ commit(released.next, released.caret, false)
346
+ return
347
+ }
348
+ const edit = deleteAcrossSeparator(
349
+ input.value,
350
+ caret,
351
+ event.key === "Backspace" ? "backward" : "forward",
352
+ )
353
+ if (!edit) return
354
+ event.preventDefault()
355
+ const next = formatPhone(edit.raw, country, edit.count, resolved)
356
+ commit(next, edit.count - next.consumed, resolved || next.consumed > 0)
357
+ }
358
+
359
+ const pick = (next: CountryCode) => {
360
+ picked.current = true
361
+ setOpen(false)
362
+ commit(switchCountry(text, next), null, false)
363
+ }
364
+
365
+ const data = useMemo<CountryData>(() => {
366
+ const names = new Intl.DisplayNames([locale], { type: "region", fallback: "code" })
367
+ const collator = new Intl.Collator(locale)
368
+ const toItem = (code: CountryCode) => {
369
+ const countryName = names.of(code) ?? code
370
+ const callingCode = callingCodeOf(code)
371
+ // The label is what the search matches: the name and the dial code both find it.
372
+ return {
373
+ value: code,
374
+ label: `${countryName} +${callingCode}`,
375
+ payload: { name: countryName, callingCode },
376
+ }
377
+ }
378
+ const all = allowed.map(toItem).sort((a, b) => collator.compare(a.payload.name, b.payload.name))
379
+ const preferred = (preferredCountries ?? []).filter((code) => allowed.includes(code))
380
+ if (preferred.length === 0) return all
381
+ return [
382
+ { group: t.preferredLabel, items: preferred.map(toItem) },
383
+ { group: t.allLabel, items: all.filter((item) => !preferred.includes(item.value)) },
384
+ ]
385
+ }, [locale, allowed, preferredCountries, t.preferredLabel, t.allLabel])
386
+
387
+ const countryName = useMemo(
388
+ () =>
389
+ country
390
+ ? (new Intl.DisplayNames([locale], { type: "region", fallback: "code" }).of(country) ??
391
+ country)
392
+ : null,
393
+ [country, locale],
394
+ )
395
+ const placeholderText =
396
+ typeof placeholder === "function"
397
+ ? placeholder(country)
398
+ : (placeholder ?? (country ? exampleOf(country) : undefined))
399
+ const flagOf = (code: CountryCode) => (renderFlag ? renderFlag(code) : <Flag country={code} />)
400
+ const locked = disabled || readOnly
401
+
402
+ return (
403
+ <Popover.Root
404
+ open={open}
405
+ onOpenChange={(details) => {
406
+ if (details.open) picked.current = false
407
+ setOpen(details.open)
408
+ }}
409
+ width="auto"
410
+ position="bottom-start"
411
+ // ~250 rows with their flags: only mount them while the list is open.
412
+ lazyMount
413
+ unmountOnExit
414
+ // After a pick, the user's next move is to type the number.
415
+ finalFocusEl={() => (picked.current ? inputRef.current : null)}
416
+ >
417
+ <FieldShell
418
+ label={label}
419
+ description={description}
420
+ error={error}
421
+ required={required}
422
+ disabled={disabled}
423
+ size={size}
424
+ className={classNames?.field}
425
+ classNames={{ label: classNames?.label }}
426
+ >
427
+ {/* The list hangs off the whole field, aligned to its edge, not off the trigger. */}
428
+ <Popover.Anchor asChild>
429
+ <InputBase
430
+ variant={variant}
431
+ size={size}
432
+ invalid={isInvalid}
433
+ disabled={disabled}
434
+ readOnly={readOnly}
435
+ classNames={{ root: classNames?.root }}
436
+ // The country trigger is interactive, so it can't sit in the `aria-hidden` start slot.
437
+ // It's a direct child that owns the start padding (see `countryTrigger`).
438
+ className={cn("ps-0! overflow-clip", className)}
439
+ >
440
+ <Popover.Trigger asChild>
441
+ <button
442
+ type="button"
443
+ disabled={locked}
444
+ aria-label={t.triggerLabel(
445
+ countryName && country ? `${countryName} +${callingCodeOf(country)}` : null,
446
+ )}
447
+ className={cn(
448
+ countryTrigger,
449
+ countryTriggerPadding[size],
450
+ countryTriggerDivider[variant],
451
+ classNames?.country,
452
+ )}
453
+ >
454
+ {country ? flagOf(country) : icons.international}
455
+ {country && (
456
+ <span dir="ltr" className="tabular-nums">
457
+ +{callingCodeOf(country)}
458
+ </span>
459
+ )}
460
+ <span className={cn(popoverChevron, "inline-flex", open && "rotate-180")}>
461
+ {icons.chevron}
462
+ </span>
463
+ </button>
464
+ </Popover.Trigger>
465
+ <PhoneInputControl
466
+ ref={mergedRef}
467
+ type="tel"
468
+ inputMode="tel"
469
+ autoComplete="tel"
470
+ // A phone number reads left to right in every script.
471
+ dir="ltr"
472
+ value={text}
473
+ placeholder={placeholderText}
474
+ onChange={(event) => {
475
+ const raw = event.currentTarget.value
476
+ const caret = event.currentTarget.selectionStart ?? raw.length
477
+ const count = significantBefore(raw, caret)
478
+ const next = formatPhone(raw, country, count, resolved)
479
+ // A code that just collapsed into the trigger took its characters with it, and
480
+ // the country it resolved to came from the number.
481
+ commit(next, Math.max(0, count - next.consumed), resolved || next.consumed > 0)
482
+ }}
483
+ onKeyDown={onKeyDown}
484
+ onBlur={onBlur}
485
+ testId={testId}
486
+ {...props({
487
+ disabled,
488
+ readOnly,
489
+ "aria-invalid": isInvalid,
490
+ })}
491
+ className={cn(inputControlClasses, "rtl:text-right", classNames?.input)}
492
+ />
493
+ {name != null && <input type="hidden" name={name} value={current ?? ""} />}
494
+ </InputBase>
495
+ </Popover.Anchor>
496
+ </FieldShell>
497
+ <Popover.Content className={cn("w-72", classNames?.list)}>
498
+ <Popover.Body className="overflow-visible p-0">
499
+ <ComboboxList<CountryData>
500
+ size="sm"
501
+ data={data}
502
+ value={country}
503
+ onChange={(next) => {
504
+ if (next) pick(next)
505
+ }}
506
+ placeholder={t.searchPlaceholder}
507
+ empty={t.empty}
508
+ renderItem={(item) => (
509
+ <>
510
+ {flagOf(item.value)}
511
+ <ArkCombobox.ItemText className="min-w-0 flex-1 truncate">
512
+ {item.payload?.name}
513
+ </ArkCombobox.ItemText>
514
+ <span dir="ltr" className={cn("tabular-nums", TEXT_COLOR_CLASSES.muted)}>
515
+ +{item.payload?.callingCode}
516
+ </span>
517
+ <ArkCombobox.ItemIndicator className={popoverIndicator}>
518
+ <CheckIcon />
519
+ </ArkCombobox.ItemIndicator>
520
+ </>
521
+ )}
522
+ />
523
+ </Popover.Body>
524
+ </Popover.Content>
525
+ </Popover.Root>
526
+ )
527
+ }