{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "phone-number",
  "title": "Phone number",
  "description": "Phone numbers as a field reads and writes them: formatted as typed, a pasted number with its code moved to its country, the caret kept after the same digit, and the value in E.164.",
  "dependencies": [
    "libphonenumber-js"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/lib/phone-number.ts",
      "content": "import {\n  AsYouType,\n  Metadata,\n  type CountryCode,\n  getCountryCallingCode,\n  getExampleNumber,\n  isValidPhoneNumber,\n  parsePhoneNumberFromString,\n  validatePhoneNumberLength,\n} from 'libphonenumber-js/min'\nimport metadata from 'libphonenumber-js/min/metadata'\nimport examples from 'libphonenumber-js/mobile/examples'\n\n/*\n * A phone number as a field reads and writes it, on libphonenumber-js: the\n * country's code in a button (`+44`) and the rest of the number in the field\n * (`20 7946 0958`), grouped the way the country writes it, the country a\n * number with its code belongs to, and the number in E.164 (`+442079460958`),\n * for a form and for your server.\n */\n\ninterface PhoneReading {\n  /** What the field shows. */\n  text: string\n  country: CountryCode\n  /** The number so far in E.164, or `''` when there is none. */\n  value: string\n}\n\n/** The digits in `text`, after a `+` when one comes before them. */\nfunction phoneChars(text: string): string {\n  const digits = text.replace(/\\D/g, '')\n  return /^\\D*\\+/.test(text) ? `+${digits}` : digits\n}\n\n/** Where the caret goes in `text` to stand after its first `count` digits (a leading `+` counts as one). */\nfunction caretAt(text: string, count: number): number {\n  if (count <= 0) return 0\n  for (let index = 1; index <= text.length; index += 1) {\n    if (phoneChars(text.slice(0, index)).length >= count) return index\n  }\n  return text.length\n}\n\nfunction callingCode(country: CountryCode): string {\n  return getCountryCallingCode(country)\n}\n\n/** The country a calling code mostly means: `GB` for 44, `US` for 1. */\nfunction mainCountry(code: string): CountryCode | undefined {\n  return metadata.country_calling_codes[code]?.[0] as CountryCode | undefined\n}\n\n/** The digits `country` dials out with, such as 00 in the UK and 011 in the US, when it has one fixed code. */\nfunction exitCode(country: CountryCode): string {\n  const plan = new Metadata()\n  plan.selectNumberingPlan(country)\n  const prefix = plan.numberingPlan?.IDDPrefix() ?? ''\n  return /^\\d+$/.test(prefix) ? prefix : ''\n}\n\n/**\n * The country a number typed with its code belongs to. Codes that several\n * countries share (+1, +7, +44) name one only once the area code is in, so\n * until then the person's pick stays while it shares the code.\n */\nfunction countryOf(typed: AsYouType, current: CountryCode): CountryCode {\n  const found = typed.getCountry()\n  if (found) return found\n  const code = typed.getCallingCode()\n  if (!code || code === callingCode(current)) return current\n  return mainCountry(code) ?? current\n}\n\n/** The number after `country`'s code, without the trunk prefix people type at home (the 0 of `020`). */\nfunction nationalDigits(digits: string, country: CountryCode): string {\n  const typed = new AsYouType(country)\n  typed.input(digits)\n  return typed.getNumber()?.nationalNumber ?? ''\n}\n\n/** `digits` after `code`, grouped as the whole number would be, without the code. */\nfunction afterDialCode(code: string, digits: string): string {\n  if (!digits) return ''\n  const whole = new AsYouType().input(`+${code}${digits}`)\n  return whole.slice(whole.indexOf(code) + code.length).trimStart()\n}\n\nfunction isTooLong(value: string): boolean {\n  return value !== '' && validatePhoneNumberLength(value) === 'TOO_LONG'\n}\n\ninterface PhoneRead {\n  reading: PhoneReading\n  /**\n   * How many digits the field gained (or lost, below 0) in front of the\n   * ones that were typed, to keep the caret after the same digit; `null`\n   * when the number was rewritten, and the caret goes to its end.\n   */\n  shift: number | null\n}\n\n/**\n * Reads what is in the field, `chars` (from `phoneChars`), into what it\n * should show for `country`. Null when the number would be too long for its\n * country: the field keeps what it had.\n */\nfunction readPhone(\n  chars: string,\n  country: CountryCode,\n  /** Keeps a number too long for the country, as when the person picks another or deletes from one. */\n  long = false,\n): PhoneRead | null {\n  const tooLong = (value: string) => !long && isTooLong(value)\n  if (!chars) return { reading: { text: '', country, value: '' }, shift: 0 }\n  if (chars.startsWith('+')) {\n    const typed = new AsYouType()\n    const text = typed.input(chars)\n    const code = typed.getCallingCode()\n    // Until a calling code is in, the field shows what was typed.\n    if (!code) return { reading: { text, country, value: '' }, shift: 0 }\n    const next = countryOf(typed, country)\n    const rest = chars.slice(1 + code.length)\n    const digits = nationalDigits(rest, next)\n    const value = digits ? `+${code}${digits}` : ''\n    if (tooLong(value)) return null\n    return {\n      reading: { text: afterDialCode(code, digits), country: next, value },\n      shift: -(1 + code.length + rest.length - digits.length),\n    }\n  }\n\n  // The start of the country's exit code (0 of 00, 01 of 011) waits for the rest.\n  const exit = exitCode(country)\n  if (exit.startsWith(chars) && chars !== exit) {\n    return { reading: { text: chars, country, value: '' }, shift: 0 }\n  }\n  const typed = new AsYouType(country)\n  typed.input(chars)\n  // Dialled out with the country's own exit code, such as 00 44 or 011 44.\n  if (typed.isInternational()) {\n    const whole = typed.getNumberValue()\n    // Until the exit code is followed by a calling code, it stays as typed.\n    if (!whole || !typed.getCallingCode()) {\n      return { reading: { text: chars, country, value: '' }, shift: 0 }\n    }\n    const read = readPhone(whole, country, long)\n    return read && { reading: read.reading, shift: null }\n  }\n  const code = callingCode(country)\n  const digits = nationalDigits(chars, country)\n  // A trunk prefix alone, such as the 0 of 020, stays as typed.\n  if (!digits) return { reading: { text: chars, country, value: '' }, shift: 0 }\n  const value = `+${code}${digits}`\n  if (tooLong(value)) return null\n  // A code several countries share names one once the number does, as when typed with its code.\n  const whole = new AsYouType()\n  whole.input(value)\n  return {\n    reading: {\n      text: afterDialCode(code, digits),\n      country: countryOf(whole, country),\n      value,\n    },\n    shift: -(chars.length - digits.length),\n  }\n}\n\n/**\n * The number in a whole `text` that arrived at once, pasted or autofilled:\n * `+44 (0)20 7946 0958`, `tel:+44…`, or `0044…` under a country that dials\n * out with another code. As typed when it isn't a number on its own.\n */\nfunction wholeNumber(text: string, country: CountryCode): string {\n  const chars = phoneChars(text)\n  for (const candidate of [text, chars.startsWith('00') ? `+${chars.slice(2)}` : null]) {\n    if (candidate === null) continue\n    const number = parsePhoneNumberFromString(candidate, country)\n    if (number?.isValid()) return number.number\n  }\n  return chars\n}\n\n/** What the field shows for a value set from outside, such as a saved number. */\nfunction readValue(value: string, country: CountryCode): PhoneReading {\n  if (!value) return { text: '', country, value: '' }\n  return (\n    readPhone(phoneChars(value), country, true)?.reading ?? {\n      text: value,\n      country,\n      value,\n    }\n  )\n}\n\n/** The same number for another country, when the person picks one: the digits they typed stay, the code changes. */\nfunction readForCountry(reading: PhoneReading, country: CountryCode): PhoneReading {\n  const digits = reading.value.slice(1 + callingCode(reading.country).length)\n  return readPhone(digits, country, true)?.reading ?? { text: '', country, value: '' }\n}\n\n/**\n * What Backspace (`back`) or Delete does next to a space or bracket: it\n * takes the digit beyond it, since the field would only put the space back.\n * Null when a digit is next to the caret, for the browser to delete.\n */\nfunction deleteAcross(\n  text: string,\n  caret: number,\n  back: boolean,\n): { text: string; caret: number } | null {\n  const isChar = (char: string | undefined) => char !== undefined && /[\\d+]/.test(char)\n  if (back ? isChar(text[caret - 1]) : isChar(text[caret])) return null\n  let at = back ? caret - 1 : caret\n  while (at >= 0 && at < text.length && !isChar(text[at])) at += back ? -1 : 1\n  if (at < 0 || at >= text.length) return null\n  return { text: text.slice(0, at) + text.slice(at + 1), caret: back ? at : caret }\n}\n\n/**\n * Why `value` isn't a number to send, or `''` when it is (or is empty). A\n * number that more digits could still make whole asks for them, so the\n * message doesn't change while the person is typing.\n */\nfunction phoneProblem(value: string): string {\n  if (!value || isValidPhoneNumber(value)) return ''\n  return validatePhoneNumberLength(`${value}0`) === 'TOO_LONG'\n    ? 'Enter a phone number that exists.'\n    : 'Enter the whole phone number.'\n}\n\n/** An example number for `country` as the field shows it, after the code, for its placeholder. */\nfunction examplePhone(country: CountryCode): string {\n  const example = getExampleNumber(country, examples)\n  return example ? afterDialCode(callingCode(country), example.nationalNumber) : ''\n}\n\nexport {\n  callingCode,\n  caretAt,\n  deleteAcross,\n  examplePhone,\n  phoneChars,\n  phoneProblem,\n  readForCountry,\n  readPhone,\n  readValue,\n  wholeNumber,\n}\nexport type { PhoneReading }\n",
      "type": "registry:lib",
      "target": "@lib/phone-number.ts"
    }
  ],
  "type": "registry:lib"
}