{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "locale-picker",
  "title": "Locale Picker",
  "description": "Combobox for picking a BCP 47 locale with native names, English names and country flags.",
  "dependencies": [
    "lucide-react",
    "radix-ui"
  ],
  "registryDependencies": [
    "utils",
    "popover",
    "@drift-ui/use-controllable-state",
    "@drift-ui/shape"
  ],
  "files": [
    {
      "path": "registry/default/ui/locale-picker.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { CheckIcon, ChevronsUpDownIcon } from \"lucide-react\"\n\nimport { useControllableState } from \"@/registry/default/hooks/use-controllable-state\"\nimport {\n  filterLocales,\n  isValidLocale,\n  listLocales,\n  normalizeLocale,\n  type LocaleOption,\n} from \"@/registry/default/lib/locale-picker-utils\"\nimport { cn } from \"@/registry/default/lib/utils\"\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@/registry/default/ui/popover\"\n\nfunction scrollOptionIntoList(option: HTMLElement | null) {\n  option?.scrollIntoView({ block: \"nearest\" })\n}\n\nexport type LocalePickerProps = Omit<\n  React.ComponentProps<\"button\">,\n  \"value\" | \"defaultValue\" | \"children\"\n> & {\n  value?: string\n  defaultValue?: string\n  onValueChange?: (value: string) => void\n  locales?: string[]\n  displayLocale?: string\n  placeholder?: string\n  searchPlaceholder?: string\n  name?: string\n  showTag?: boolean\n}\n\nfunction LocalePicker({\n  value: valueProp,\n  defaultValue = \"\",\n  onValueChange,\n  locales,\n  displayLocale = \"en\",\n  placeholder = \"Select a locale\",\n  searchPlaceholder = \"Search locales\",\n  disabled,\n  name,\n  showTag = true,\n  className,\n  onKeyDown,\n  ...props\n}: LocalePickerProps) {\n  const listId = React.useId()\n  const { value, setValue } = useControllableState({\n    value: valueProp,\n    defaultValue,\n    onChange: onValueChange,\n  })\n\n  const normalized = normalizeLocale(value)\n  const current = normalized && isValidLocale(normalized) ? normalized : \"\"\n\n  const [isOpen, setIsOpen] = React.useState(false)\n  const [query, setQuery] = React.useState(\"\")\n  const [highlighted, setHighlighted] = React.useState<number | null>(null)\n\n  const options = React.useMemo(\n    () => listLocales(locales, displayLocale),\n    [locales, displayLocale]\n  )\n\n  const currentOption = React.useMemo<LocaleOption | null>(() => {\n    if (!current) return null\n    const found = options.find((option) => option.value === current)\n    if (found) return found\n    const custom = listLocales([current], displayLocale)\n    return custom[0] ?? null\n  }, [options, current, displayLocale])\n\n  const matches = filterLocales(options, query)\n  const highlightedIndex = Math.min(\n    highlighted ??\n      Math.max(\n        0,\n        matches.findIndex((option) => option.value === current)\n      ),\n    Math.max(0, matches.length - 1)\n  )\n\n  function handleOpenChange(nextOpen: boolean) {\n    setIsOpen(nextOpen)\n    if (!nextOpen) return\n    setQuery(\"\")\n    setHighlighted(null)\n  }\n\n  function select(next: string) {\n    setValue(next)\n    setIsOpen(false)\n  }\n\n  function handleKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {\n    // Leave keys that confirm an IME composition to the IME.\n    if (event.nativeEvent.isComposing || event.keyCode === 229) return\n    switch (event.key) {\n      case \"ArrowDown\":\n      case \"ArrowUp\": {\n        event.preventDefault()\n        if (matches.length === 0) return\n        const delta = event.key === \"ArrowDown\" ? 1 : -1\n        setHighlighted(\n          (highlightedIndex + delta + matches.length) % matches.length\n        )\n        return\n      }\n      case \"Enter\": {\n        event.preventDefault()\n        const match = matches[highlightedIndex]\n        if (match) select(match.value)\n        return\n      }\n    }\n  }\n\n  return (\n    <>\n      <Popover open={isOpen} onOpenChange={handleOpenChange}>\n        <PopoverTrigger\n          type=\"button\"\n          role=\"combobox\"\n          aria-expanded={isOpen}\n          aria-haspopup=\"listbox\"\n          aria-controls={isOpen ? listId : undefined}\n          disabled={disabled}\n          data-slot=\"locale-picker\"\n          {...props}\n          onKeyDown={(event) => {\n            onKeyDown?.(event)\n            if (\n              !event.defaultPrevented &&\n              !isOpen &&\n              (event.key === \"ArrowDown\" || event.key === \"ArrowUp\")\n            ) {\n              event.preventDefault()\n              setIsOpen(true)\n            }\n          }}\n          className={cn(\n            \"flex h-control w-full min-w-0 items-center gap-2 rounded-control border border-input bg-transparent px-3 text-left text-sm shadow-control outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30\",\n            className\n          )}\n        >\n          {currentOption ? (\n            <>\n              {currentOption.flag && (\n                <span\n                  className=\"shrink-0 text-base leading-none\"\n                  aria-hidden=\"true\"\n                >\n                  {currentOption.flag}\n                </span>\n              )}\n              <span className=\"min-w-0 flex-1 truncate\">\n                {currentOption.label}\n              </span>\n              {showTag && (\n                <span className=\"shrink-0 font-mono text-xs text-muted-foreground\">\n                  {currentOption.value}\n                </span>\n              )}\n            </>\n          ) : (\n            <span className=\"flex-1 text-muted-foreground\">{placeholder}</span>\n          )}\n          <ChevronsUpDownIcon className=\"size-4 shrink-0 opacity-50\" />\n        </PopoverTrigger>\n        <PopoverContent\n          align=\"start\"\n          aria-label=\"Choose a locale\"\n          className=\"flex w-80 min-w-[var(--radix-popover-trigger-width,var(--anchor-width))] flex-col gap-1 p-1\"\n        >\n          <input\n            type=\"text\"\n            role=\"combobox\"\n            data-slot=\"locale-picker-search\"\n            aria-label=\"Search locales\"\n            aria-autocomplete=\"list\"\n            aria-expanded=\"true\"\n            aria-controls={listId}\n            aria-activedescendant={\n              matches.length > 0 ? `${listId}-${highlightedIndex}` : undefined\n            }\n            value={query}\n            placeholder={searchPlaceholder}\n            onChange={(event) => {\n              setQuery(event.target.value)\n              setHighlighted(0)\n            }}\n            onKeyDown={handleKeyDown}\n            className=\"h-8 w-full rounded-sm bg-transparent px-2 text-sm outline-none placeholder:text-muted-foreground\"\n          />\n          <div\n            id={listId}\n            role=\"listbox\"\n            aria-label=\"Locales\"\n            data-slot=\"locale-picker-list\"\n            className=\"relative max-h-64 overflow-y-auto\"\n          >\n            {matches.map((option, index) => (\n              <div\n                key={option.value}\n                ref={\n                  index === highlightedIndex ? scrollOptionIntoList : undefined\n                }\n                id={`${listId}-${index}`}\n                role=\"option\"\n                aria-selected={option.value === current}\n                data-highlighted={index === highlightedIndex ? \"\" : undefined}\n                onPointerMove={() => setHighlighted(index)}\n                onClick={() => select(option.value)}\n                className=\"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground\"\n              >\n                {option.flag && (\n                  <span\n                    className=\"shrink-0 text-base leading-none\"\n                    aria-hidden=\"true\"\n                  >\n                    {option.flag}\n                  </span>\n                )}\n                <span className=\"min-w-0 flex-1 truncate\">{option.label}</span>\n                {showTag && (\n                  <span className=\"shrink-0 font-mono text-xs text-muted-foreground\">\n                    {option.value}\n                  </span>\n                )}\n                {option.value === current && (\n                  <CheckIcon className=\"size-4 shrink-0\" />\n                )}\n              </div>\n            ))}\n          </div>\n          {matches.length === 0 && (\n            <p\n              role=\"status\"\n              className=\"px-2 py-1.5 text-sm text-muted-foreground\"\n            >\n              No locale found\n            </p>\n          )}\n        </PopoverContent>\n      </Popover>\n      {name && (\n        <input type=\"hidden\" name={name} value={current} disabled={disabled} />\n      )}\n    </>\n  )\n}\n\nexport { LocalePicker }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/default/lib/locale-picker-utils.ts",
      "content": "import { COUNTRY_CODES, countryFlag } from \"@/registry/default/lib/countries\"\n\nexport interface LocaleOption {\n  value: string\n  nativeName: string\n  currentName: string\n  label: string\n  region?: string\n  flag?: string | null\n}\n\nexport const DEFAULT_LOCALES: string[] = [\n  \"ar-SA\",\n  \"cs-CZ\",\n  \"da-DK\",\n  \"de-DE\",\n  \"el-GR\",\n  \"en-GB\",\n  \"en-US\",\n  \"es-ES\",\n  \"es-MX\",\n  \"fi-FI\",\n  \"fr-CA\",\n  \"fr-FR\",\n  \"he-IL\",\n  \"hi-IN\",\n  \"hu-HU\",\n  \"id-ID\",\n  \"it-IT\",\n  \"ja-JP\",\n  \"ko-KR\",\n  \"nb-NO\",\n  \"nl-NL\",\n  \"pl-PL\",\n  \"pt-BR\",\n  \"pt-PT\",\n  \"ro-RO\",\n  \"ru-RU\",\n  \"sk-SK\",\n  \"sv-SE\",\n  \"th-TH\",\n  \"tr-TR\",\n  \"uk-UA\",\n  \"vi-VN\",\n  \"zh-CN\",\n  \"zh-TW\",\n]\n\nconst validityCache = new Map<string, boolean>()\nconst countryCodeSet = new Set(COUNTRY_CODES)\n\n/**\n * Validates whether a string is a syntactically valid BCP 47 language tag using `Intl.Locale`.\n */\nexport function isValidLocale(tag: string): boolean {\n  if (!tag || typeof tag !== \"string\") return false\n  let valid = validityCache.get(tag)\n  if (valid === undefined) {\n    try {\n      new Intl.Locale(tag)\n      valid = true\n    } catch {\n      valid = false\n    }\n    validityCache.set(tag, valid)\n  }\n  return valid\n}\n\nexport function normalizeLocale(tag: string): string {\n  try {\n    const cleaned = tag.trim().replaceAll(\"_\", \"-\")\n    return new Intl.Locale(cleaned).toString()\n  } catch {\n    return tag.trim()\n  }\n}\n\nexport function getLocaleFlag(tag: string): string | null {\n  try {\n    const locale = new Intl.Locale(tag)\n    if (\n      locale.region &&\n      locale.region.length === 2 &&\n      countryCodeSet.has(locale.region.toUpperCase())\n    ) {\n      return countryFlag(locale.region)\n    }\n  } catch {\n    // Ignore invalid tags\n  }\n  return null\n}\n\nconst displayNamesCache = new Map<string, Intl.DisplayNames>()\n\nfunction getDisplayNames(locale: string): Intl.DisplayNames {\n  let dn = displayNamesCache.get(locale)\n  if (!dn) {\n    try {\n      dn = new Intl.DisplayNames([locale], { type: \"language\" })\n    } catch {\n      dn = new Intl.DisplayNames([\"en\"], { type: \"language\" })\n    }\n    displayNamesCache.set(locale, dn)\n  }\n  return dn\n}\n\nfunction capitalize(text: string): string {\n  if (!text) return text\n  return text.charAt(0).toUpperCase() + text.slice(1)\n}\n\nexport function formatLocaleNames(\n  tag: string,\n  displayLocale = \"en\"\n): { nativeName: string; currentName: string; label: string } {\n  const normalized = normalizeLocale(tag)\n  let lookupTag = normalized\n  try {\n    lookupTag = new Intl.Locale(normalized).baseName\n  } catch {\n    // Fallback to normalized\n  }\n\n  let nativeName = normalized\n  let currentName = normalized\n\n  try {\n    const nativeDn = getDisplayNames(lookupTag)\n    const rawNative = nativeDn.of(lookupTag)\n    if (rawNative) nativeName = capitalize(rawNative)\n  } catch {\n    // Fallback to tag\n  }\n\n  try {\n    const currentDn = getDisplayNames(displayLocale)\n    const rawCurrent = currentDn.of(lookupTag)\n    if (rawCurrent) currentName = capitalize(rawCurrent)\n  } catch {\n    // Fallback to tag\n  }\n\n  const label =\n    nativeName.toLowerCase() === currentName.toLowerCase()\n      ? nativeName\n      : `${nativeName} · ${currentName}`\n\n  return { nativeName, currentName, label }\n}\n\nexport function listLocales(\n  tags: string[] = DEFAULT_LOCALES,\n  displayLocale = \"en\"\n): LocaleOption[] {\n  const seen = new Set<string>()\n  const result: LocaleOption[] = []\n\n  for (const rawTag of tags) {\n    const normalized = normalizeLocale(rawTag)\n    if (!isValidLocale(normalized) || seen.has(normalized)) continue\n    seen.add(normalized)\n\n    const flag = getLocaleFlag(normalized)\n    const { nativeName, currentName, label } = formatLocaleNames(\n      normalized,\n      displayLocale\n    )\n    let region: string | undefined\n    try {\n      const loc = new Intl.Locale(normalized)\n      region = loc.region\n    } catch {\n      // Ignore\n    }\n\n    result.push({\n      value: normalized,\n      nativeName,\n      currentName,\n      label,\n      region,\n      flag,\n    })\n  }\n\n  return result\n}\n\nfunction normalize(text: string) {\n  return text\n    .normalize(\"NFD\")\n    .replace(/[\\u0300-\\u036f]/g, \"\")\n    .toLowerCase()\n    .trim()\n}\n\nexport function filterLocales(\n  options: LocaleOption[],\n  query: string\n): LocaleOption[] {\n  const needle = normalize(query)\n  if (!needle) return options\n\n  return options.filter(\n    (option) =>\n      normalize(option.value).includes(needle) ||\n      normalize(option.nativeName).includes(needle) ||\n      normalize(option.currentName).includes(needle) ||\n      normalize(option.label).includes(needle) ||\n      (option.region ? normalize(option.region).includes(needle) : false)\n  )\n}\n",
      "type": "registry:lib"
    },
    {
      "path": "registry/default/lib/countries.ts",
      "content": "const REGIONAL_INDICATOR_OFFSET = 0x1f1a5\n\nexport const COUNTRY_CODES = (\n  \"AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ \" +\n  \"BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ \" +\n  \"CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ \" +\n  \"DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR \" +\n  \"GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY \" +\n  \"HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP \" +\n  \"KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY \" +\n  \"MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ \" +\n  \"NA NC NE NF NG NI NL NO NP NR NU NZ OM \" +\n  \"PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW \" +\n  \"SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ \" +\n  \"TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ \" +\n  \"VA VC VE VG VI VN VU WF WS XK YE YT ZA ZM ZW\"\n).split(\" \")\n\nexport function countryFlag(country: string) {\n  return String.fromCodePoint(\n    ...Array.from(\n      country.toUpperCase(),\n      (letter) => REGIONAL_INDICATOR_OFFSET + letter.charCodeAt(0)\n    )\n  )\n}\n\nexport function countryName(country: string, locale = \"en\") {\n  return (\n    new Intl.DisplayNames([locale], { type: \"region\" }).of(country) ?? country\n  )\n}\n",
      "type": "registry:lib"
    }
  ],
  "type": "registry:ui"
}