{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "phone-input",
  "title": "Phone input",
  "description": "A phone number with its country: a button with the flag and dial code opens a searchable list of countries, the number is formatted as it is typed, a number pasted with its code moves the country to it, and the form gets the number in E.164.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core",
    "libphonenumber-js"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/input.json",
    "https://kinoui.com/r/input-group.json",
    "https://kinoui.com/r/addon-picker.json",
    "https://kinoui.com/r/countries.json",
    "https://kinoui.com/r/phone-number.json",
    "https://kinoui.com/r/dates.json",
    "https://kinoui.com/r/field-control.json",
    "https://kinoui.com/r/refs.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/phone-input.tsx",
      "content": "'use client'\n\nimport { inputControlClassName } from '@/registry/components/kino/input'\nimport { InputGroup, inputGroupBesideStart } from '@/registry/components/kino/input-group'\nimport { AddonPicker, type AddonPickerOption } from '@/registry/lib/addon-picker'\nimport { countryAliases, CountryFlag, countryName } from '@/registry/lib/countries'\nimport { useLocale } from '@/registry/lib/dates'\nimport {\n  changeDetails,\n  FieldCheck,\n  keptOnReset,\n  useField,\n} from '@/registry/lib/field-control'\nimport {\n  callingCode,\n  caretAt,\n  deleteAcross,\n  examplePhone,\n  phoneChars,\n  phoneProblem,\n  type PhoneReading,\n  readForCountry,\n  readPhone,\n  readValue,\n  wholeNumber,\n} from '@/registry/lib/phone-number'\nimport { markMounted, mergeRefs } from '@/registry/lib/refs'\nimport type { ChangeDetails } from '@ui-sdk/core'\nimport { Input as InputPrimitive } from '@ui-sdk/react/input'\nimport { type CountryCode, getCountries } from 'libphonenumber-js/min'\nimport {\n  type ComponentProps,\n  type KeyboardEvent,\n  type Ref,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * A phone number with its country. The button holds the country's flag and\n * code, `+44`, and the field the rest of the number, `20 7946 0958`,\n * formatted as it is typed; the 0 people type at home falls away. A number\n * typed or pasted with `+` and its code moves the country to it, and the\n * value is the number in E.164 (`+442079460958`), for a form and your server.\n */\n\ninterface PhoneInputProps extends Omit<\n  ComponentProps<typeof InputPrimitive>,\n  | 'value'\n  | 'defaultValue'\n  | 'onValueChange'\n  | 'controller'\n  | 'type'\n  | 'className'\n  | 'children'\n> {\n  /** The number in E.164, such as `+442079460958`, or `''`. */\n  value?: string\n  defaultValue?: string\n  /** Called with the number in E.164 and who changed it in `details.source`; `details.cancel()` keeps the last number. */\n  onValueChange?: (value: string, details: ChangeDetails) => void\n  /** An ISO 3166-1 code, such as `GB`. */\n  country?: CountryCode\n  defaultCountry?: CountryCode\n  /** Called with the country, from a pick or a number typed with another's code; `details.cancel()` keeps the last one. */\n  onCountryChange?: (country: CountryCode, details: ChangeDetails) => void\n  /** The countries the list offers, when not every one. */\n  countries?: readonly CountryCode[]\n  /** The language of the countries' names; the browser's by default. */\n  locale?: string\n  /** What the button picks: it reads \"Country: United Kingdom, +44\". */\n  label?: string\n  searchPlaceholder?: string\n  className?: string\n  ref?: Ref<HTMLInputElement>\n}\n\nfunction PhoneInput({\n  value: valueProp,\n  defaultValue,\n  onValueChange,\n  country: countryProp,\n  defaultCountry = 'US',\n  onCountryChange,\n  countries,\n  locale: localeProp,\n  label = 'Country',\n  searchPlaceholder = 'Search countries',\n  name,\n  form,\n  required,\n  disabled: disabledProp = false,\n  readOnly = false,\n  placeholder,\n  className,\n  ref,\n  id: idProp,\n  onKeyDown,\n  onFocus,\n  onBlur,\n  ...props\n}: PhoneInputProps) {\n  const locale = useLocale(localeProp)\n  const [reading, setReading] = useState(() =>\n    readValue(valueProp ?? defaultValue ?? '', countryProp ?? defaultCountry),\n  )\n  // A value set from outside is shown the field's way, once per change.\n  const [synced, setSynced] = useState(valueProp)\n  if (valueProp !== synced) {\n    setSynced(valueProp)\n    if (valueProp !== undefined && valueProp !== reading.value) {\n      setReading(readValue(valueProp, countryProp ?? reading.country))\n    }\n  }\n  // The value wins: a number with another country's code shows that country, never a number the form won't get.\n  const owned = countryProp ?? reading.country\n  const country =\n    reading.value && !reading.value.startsWith(`+${callingCode(owned)}`)\n      ? reading.country\n      : owned\n  const input = useRef<HTMLInputElement>(null)\n  const caret = useRef<number | null>(null)\n  useLayoutEffect(() => {\n    if (caret.current === null || !input.current) return\n    if (document.activeElement === input.current) {\n      input.current.setSelectionRange(caret.current, caret.current)\n    }\n    caret.current = null\n  })\n\n  const problem = phoneProblem(reading.value)\n  const field = useField()\n  const inputRef = useMemo(\n    () => mergeRefs<HTMLInputElement>(input, markMounted, ref),\n    [ref],\n  )\n  const disabled = disabledProp || field?.disabled === true\n\n  /** Tells the owner what `next` changes, and whether to keep it: no unless both take it. */\n  function told(next: PhoneReading, details: ChangeDetails) {\n    if (next.value !== reading.value) onValueChange?.(next.value, details)\n    if (next.country !== country && !details.canceled)\n      onCountryChange?.(next.country, details)\n    return !details.canceled\n  }\n\n  function commit(next: PhoneReading, caretAfter: number, details: ChangeDetails) {\n    caret.current = caretAfter\n    // A render even when nothing changed, so the caret is placed after React puts the old text back.\n    const changed = next.text !== reading.text || next.country !== reading.country\n    setReading(changed && told(next, details) ? next : { ...reading })\n  }\n\n  /** `text` as the person left it, with the caret at `caretIn`. */\n  function take(\n    text: string,\n    caretIn: number,\n    replaced: boolean,\n    details: ChangeDetails,\n  ) {\n    const chars = replaced ? wholeNumber(text, country) : phoneChars(text)\n    // Only an edit that adds digits can make the number too long: one too long already (picked for another country) can still be shortened.\n    const shorter = !replaced && chars.length <= phoneChars(reading.text).length\n    const read = readPhone(chars, country, shorter)\n    if (!read) {\n      // Too long: the number stays, with the caret after the digit it was after.\n      caret.current = caretAt(\n        reading.text,\n        phoneChars(text.slice(0, caretIn)).length -\n          (chars.length - phoneChars(reading.text).length),\n      )\n      // A render of its own, so the caret is placed after React puts the old text back.\n      setReading({ ...reading })\n      return\n    }\n    const before = phoneChars(text.slice(0, caretIn)).length\n    // A number that arrived whole leaves the caret at its end.\n    const after =\n      read.shift === null || replaced\n        ? read.reading.text.length\n        : caretAt(read.reading.text, before + read.shift)\n    commit(read.reading, after, details)\n  }\n\n  /** Back to the number it started with, as a form's reset does. */\n  function reset(event: Event) {\n    if (keptOnReset(valueProp, defaultValue)) return\n    const initial = readValue(defaultValue ?? '', countryProp ?? defaultCountry)\n    told(initial, changeDetails('reset', event))\n    // A reset can't be turned down: the form has already put its fields back.\n    setReading(initial)\n  }\n\n  function pick(next: string, event: Event | undefined) {\n    const read = readForCountry(reading, next as CountryCode)\n    caret.current = read.text.length\n    if (told(read, changeDetails('item-press', event))) setReading(read)\n  }\n\n  const options = useMemo(() => {\n    const collator = new Intl.Collator(locale)\n    return (countries ?? getCountries())\n      .map((code): AddonPickerOption => ({\n        value: code,\n        label: countryName(code, locale),\n        detail: `+${callingCode(code)}`,\n        visual: <CountryFlag country={code} />,\n        keywords: [code, ...countryAliases(code)],\n      }))\n      .sort((a, b) => collator.compare(a.label, b.label))\n  }, [countries, locale])\n\n  return (\n    <InputGroup data-phone-input='' className={className}>\n      <AddonPicker\n        options={options}\n        value={country}\n        onValueChange={pick}\n        label={label}\n        searchPlaceholder={searchPlaceholder}\n        noMatch={(query) => `No country matches “${query.trim()}”.`}\n        disabled={disabled}\n        readOnly={readOnly}\n        returnFocus={input}\n      >\n        <span className='flex items-center gap-1.5'>\n          <CountryFlag country={country} />\n          <span dir='ltr' className='tabular-nums'>\n            +{callingCode(country)}\n          </span>\n        </span>\n      </AddonPicker>\n      {/* The number's box is what its Field's label names, its description and check describe; the check below sends the number. */}\n      <InputPrimitive\n        {...props}\n        id={idProp}\n        ref={inputRef}\n        // The Field's name goes on the check, which sends the number in E.164, not the text shown.\n        name={undefined}\n        data-phone-input-control=''\n        type='tel'\n        inputMode='tel'\n        autoComplete={props.autoComplete ?? 'tel'}\n        // A number reads left to right in every language.\n        dir='ltr'\n        aria-required={required || undefined}\n        value={reading.text}\n        placeholder={placeholder ?? examplePhone(country)}\n        disabled={disabled}\n        readOnly={readOnly}\n        onValueChange={(text, details) => {\n          // A form's reset is the check's to make.\n          if (details.reason === 'reset') return\n          // An agent's or a controller's change has no event: a whole number arrived.\n          const inputType = (details.event as InputEvent | undefined)?.inputType\n          const replaced =\n            inputType === undefined ||\n            inputType === 'insertFromPaste' ||\n            inputType === 'insertReplacementText' ||\n            reading.text === ''\n          take(text, input.current?.selectionStart ?? text.length, replaced, details)\n        }}\n        onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => {\n          onKeyDown?.(event)\n          if (event.defaultPrevented) return\n          if (event.key !== 'Backspace' && event.key !== 'Delete') return\n          const target = event.currentTarget\n          if (target.readOnly) return\n          const start = target.selectionStart ?? 0\n          if (\n            start !== target.selectionEnd ||\n            event.altKey ||\n            event.metaKey ||\n            event.ctrlKey\n          ) {\n            return\n          }\n          const next = deleteAcross(target.value, start, event.key === 'Backspace')\n          if (!next) return\n          event.preventDefault()\n          take(\n            next.text,\n            next.caret,\n            false,\n            changeDetails('input-change', event.nativeEvent),\n          )\n        }}\n        onFocus={onFocus}\n        onBlur={onBlur}\n        className={cn(\n          inputControlClassName,\n          inputGroupBesideStart,\n          'tabular-nums rtl:text-right rtl:placeholder:text-right',\n        )}\n      />\n      <FieldCheck\n        value={reading.value}\n        name={name ?? field?.name}\n        form={form}\n        required={required}\n        readOnly={readOnly}\n        disabled={disabled}\n        message={problem}\n        onFocus={() => input.current?.focus()}\n        onReset={reset}\n      />\n    </InputGroup>\n  )\n}\n\nexport { PhoneInput }\nexport type { PhoneInputProps }\n",
      "type": "registry:component",
      "target": "@components/kino/phone-input.tsx"
    }
  ],
  "type": "registry:component"
}