{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "address-fields",
  "title": "Address Fields",
  "description": "Country first, then the fields its addresses use, named its way and in its order, with a list of states or provinces where the country has one and a check of the postal code.",
  "registryDependencies": [
    "field",
    "input",
    "https://www.dashboardblocks.com/r/radix/countries.json",
    "https://www.dashboardblocks.com/r/radix/country-flag.json",
    "https://www.dashboardblocks.com/r/radix/option-select.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/address-fields.tsx",
      "content": "'use client'\n\nimport { CountryFlag } from '@/registry/components/dashboardblocks/country-flag'\nimport {\n  OptionSelect,\n  type SelectOption,\n} from '@/registry/components/dashboardblocks/option-select'\nimport {\n  countries as allCountries,\n  getCountryName,\n} from '@/registry/lib/dashboardblocks/countries'\nimport { useId } from 'react'\n\nimport { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'\nimport { Input } from '@/components/ui/input'\n\n/** The same shape as Stripe's `address`, with `postalCode` for `postal_code`. */\ntype Address = {\n  city: string\n  /** The ISO 3166-1 two-letter code, such as `GB`. */\n  country: string\n  line1: string\n  line2: string\n  postalCode: string\n  /** A state, province or county: the code from the list where the country has one (`CA`, `NSW`), otherwise as typed. */\n  state: string\n}\n\ntype AddressField = keyof Address\n\ninterface AddressFormat {\n  /** Postal code, prefecture and city before the street, as in Japan. */\n  bigFirst?: boolean\n  cityLabel: string\n  /** Left out where the country has no postal codes. */\n  postalCode?: {\n    example?: string\n    label: string\n    pattern?: RegExp\n    required: boolean\n  }\n  /** The postal code before the city on one line, as in most of Europe. */\n  postalFirst?: boolean\n  state?: {\n    label: string\n    options?: readonly SelectOption[]\n    required: boolean\n  }\n}\n\nconst US_STATES: readonly SelectOption[] = [\n  ['AL', 'Alabama'],\n  ['AK', 'Alaska'],\n  ['AS', 'American Samoa'],\n  ['AZ', 'Arizona'],\n  ['AR', 'Arkansas'],\n  ['CA', 'California'],\n  ['CO', 'Colorado'],\n  ['CT', 'Connecticut'],\n  ['DE', 'Delaware'],\n  ['DC', 'District of Columbia'],\n  ['FL', 'Florida'],\n  ['GA', 'Georgia'],\n  ['GU', 'Guam'],\n  ['HI', 'Hawaii'],\n  ['ID', 'Idaho'],\n  ['IL', 'Illinois'],\n  ['IN', 'Indiana'],\n  ['IA', 'Iowa'],\n  ['KS', 'Kansas'],\n  ['KY', 'Kentucky'],\n  ['LA', 'Louisiana'],\n  ['ME', 'Maine'],\n  ['MD', 'Maryland'],\n  ['MA', 'Massachusetts'],\n  ['MI', 'Michigan'],\n  ['MN', 'Minnesota'],\n  ['MS', 'Mississippi'],\n  ['MO', 'Missouri'],\n  ['MT', 'Montana'],\n  ['NE', 'Nebraska'],\n  ['NV', 'Nevada'],\n  ['NH', 'New Hampshire'],\n  ['NJ', 'New Jersey'],\n  ['NM', 'New Mexico'],\n  ['NY', 'New York'],\n  ['NC', 'North Carolina'],\n  ['ND', 'North Dakota'],\n  ['MP', 'Northern Mariana Islands'],\n  ['OH', 'Ohio'],\n  ['OK', 'Oklahoma'],\n  ['OR', 'Oregon'],\n  ['PA', 'Pennsylvania'],\n  ['PR', 'Puerto Rico'],\n  ['RI', 'Rhode Island'],\n  ['SC', 'South Carolina'],\n  ['SD', 'South Dakota'],\n  ['TN', 'Tennessee'],\n  ['TX', 'Texas'],\n  ['VI', 'U.S. Virgin Islands'],\n  ['UT', 'Utah'],\n  ['VT', 'Vermont'],\n  ['VA', 'Virginia'],\n  ['WA', 'Washington'],\n  ['WV', 'West Virginia'],\n  ['WI', 'Wisconsin'],\n  ['WY', 'Wyoming'],\n].map(([value, label]) => ({ label, value }))\n\nconst CA_PROVINCES: readonly SelectOption[] = [\n  ['AB', 'Alberta'],\n  ['BC', 'British Columbia'],\n  ['MB', 'Manitoba'],\n  ['NB', 'New Brunswick'],\n  ['NL', 'Newfoundland and Labrador'],\n  ['NT', 'Northwest Territories'],\n  ['NS', 'Nova Scotia'],\n  ['NU', 'Nunavut'],\n  ['ON', 'Ontario'],\n  ['PE', 'Prince Edward Island'],\n  ['QC', 'Quebec'],\n  ['SK', 'Saskatchewan'],\n  ['YT', 'Yukon'],\n].map(([value, label]) => ({ label, value }))\n\nconst AU_STATES: readonly SelectOption[] = [\n  ['ACT', 'Australian Capital Territory'],\n  ['NSW', 'New South Wales'],\n  ['NT', 'Northern Territory'],\n  ['QLD', 'Queensland'],\n  ['SA', 'South Australia'],\n  ['TAS', 'Tasmania'],\n  ['VIC', 'Victoria'],\n  ['WA', 'Western Australia'],\n].map(([value, label]) => ({ label, value }))\n\nconst NO_POSTAL_CODES = new Set(\n  'AE AG AO AW BF BI BJ BO BS BW BZ CD CF CG CI CK CM DJ DM ER FJ GA GD GH GM GQ GY HK KI KM KN KP LY ML MO MR MW NR NU QA RW SB SC SL SR SS ST SY TD TG TK TL TO TT TV UG VU YE ZW'.split(\n    ' ',\n  ),\n)\n\nconst POSTAL_FIRST = new Set(\n  'AT BE BG CH CZ DE DK EE ES FI FR GR HR HU IS IT LI LT LU LV MC NL NO PL PT RO SE SI SK'.split(\n    ' ',\n  ),\n)\n\nconst postalCodeFormat = (pattern?: RegExp, example?: string) => ({\n  example,\n  label: 'Postal code',\n  pattern,\n  required: true,\n})\n\nconst FORMATS: Partial<Record<string, AddressFormat>> = {\n  AU: {\n    cityLabel: 'Suburb',\n    postalCode: {\n      example: '2000',\n      label: 'Postcode',\n      pattern: /^\\d{4}$/,\n      required: true,\n    },\n    state: { label: 'State', options: AU_STATES, required: true },\n  },\n  BR: {\n    cityLabel: 'City',\n    postalCode: {\n      example: '01310-100',\n      label: 'CEP',\n      pattern: /^\\d{5}-?\\d{3}$/,\n      required: true,\n    },\n    state: { label: 'State', required: true },\n  },\n  CA: {\n    cityLabel: 'City',\n    postalCode: postalCodeFormat(/^[A-Z]\\d[A-Z] ?\\d[A-Z]\\d$/i, 'M5V 2T6'),\n    state: { label: 'Province', options: CA_PROVINCES, required: true },\n  },\n  CN: {\n    cityLabel: 'City',\n    postalCode: postalCodeFormat(/^\\d{6}$/, '100000'),\n    state: { label: 'Province', required: true },\n  },\n  DE: {\n    cityLabel: 'City',\n    postalCode: postalCodeFormat(/^\\d{5}$/, '10115'),\n    postalFirst: true,\n  },\n  ES: {\n    cityLabel: 'City',\n    postalCode: postalCodeFormat(/^\\d{5}$/, '28001'),\n    postalFirst: true,\n    state: { label: 'Province', required: false },\n  },\n  FR: {\n    cityLabel: 'City',\n    postalCode: postalCodeFormat(/^\\d{5}$/, '75001'),\n    postalFirst: true,\n  },\n  GB: {\n    cityLabel: 'Town or city',\n    postalCode: {\n      example: 'SW1A 1AA',\n      label: 'Postcode',\n      pattern: /^[A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}$/i,\n      required: true,\n    },\n  },\n  IE: {\n    cityLabel: 'Town or city',\n    postalCode: { label: 'Eircode', required: false },\n    state: { label: 'County', required: false },\n  },\n  IN: {\n    cityLabel: 'City',\n    postalCode: {\n      example: '560001',\n      label: 'PIN code',\n      pattern: /^\\d{6}$/,\n      required: true,\n    },\n    state: { label: 'State', required: true },\n  },\n  IT: {\n    cityLabel: 'City',\n    postalCode: postalCodeFormat(/^\\d{5}$/, '00184'),\n    postalFirst: true,\n    state: { label: 'Province', required: false },\n  },\n  JP: {\n    bigFirst: true,\n    cityLabel: 'City',\n    postalCode: postalCodeFormat(/^\\d{3}-?\\d{4}$/, '100-0001'),\n    state: { label: 'Prefecture', required: true },\n  },\n  MX: {\n    cityLabel: 'City',\n    postalCode: postalCodeFormat(/^\\d{5}$/, '06600'),\n    state: { label: 'State', required: true },\n  },\n  NL: {\n    cityLabel: 'City',\n    postalCode: postalCodeFormat(/^\\d{4} ?[A-Z]{2}$/i, '1012 JS'),\n    postalFirst: true,\n  },\n  US: {\n    cityLabel: 'City',\n    postalCode: {\n      example: '94107',\n      label: 'ZIP code',\n      pattern: /^\\d{5}(-\\d{4})?$/,\n      required: true,\n    },\n    state: { label: 'State', options: US_STATES, required: true },\n  },\n}\n\n/** Which fields the country's addresses have, what each is called, and which must be filled in. */\nfunction getAddressFormat(country: string): AddressFormat {\n  const code = country.toUpperCase()\n  const known = FORMATS[code]\n  if (known) return known\n  if (NO_POSTAL_CODES.has(code)) return { cityLabel: 'City' }\n  return {\n    cityLabel: 'City',\n    postalCode: { label: 'Postal code', required: false },\n    postalFirst: POSTAL_FIRST.has(code),\n  }\n}\n\nfunction getAddressRows(format: AddressFormat): AddressField[][] {\n  const postal: AddressField[] = format.postalCode ? ['postalCode'] : []\n  const state: AddressField[] = format.state ? ['state'] : []\n  if (format.bigFirst) return [[...postal, ...state], ['city'], ['line1'], ['line2']]\n  if (format.postalFirst) return [['line1'], ['line2'], [...postal, 'city', ...state]]\n  return [['line1'], ['line2'], ['city', ...state, ...postal]]\n}\n\nfunction inSentence(label: string) {\n  return /^[A-Z]{2}/.test(label) ? label : label.charAt(0).toLowerCase() + label.slice(1)\n}\n\n/** One sentence per field that's missing or doesn't look right for the country, as `useSimpleForm`'s `validate` returns. */\nfunction validateAddress(address: Address): Partial<Record<AddressField, string>> {\n  if (!address.country) return { country: 'Choose a country.' }\n  const format = getAddressFormat(address.country)\n  const errors: Partial<Record<AddressField, string>> = {}\n  if (!address.line1.trim()) errors.line1 = 'Enter the street address.'\n  if (!address.city.trim()) errors.city = `Enter the ${inSentence(format.cityLabel)}.`\n  if (format.state?.required && !address.state.trim()) {\n    errors.state = `${format.state.options ? 'Choose' : 'Enter'} the ${inSentence(format.state.label)}.`\n  }\n  const postal = format.postalCode\n  const code = address.postalCode.trim()\n  if (postal?.required && !code)\n    errors.postalCode = `Enter the ${inSentence(postal.label)}.`\n  else if (postal?.pattern && code && !postal.pattern.test(code)) {\n    errors.postalCode = `Enter a ${inSentence(postal.label)} like ${postal.example}.`\n  }\n  return errors\n}\n\nconst AUTOCOMPLETE: Record<AddressField, string> = {\n  city: 'address-level2',\n  country: 'country',\n  line1: 'address-line1',\n  line2: 'address-line2',\n  postalCode: 'postal-code',\n  state: 'address-level1',\n}\n\n/** The countries given, or every country, as `OptionSelect` options with their flags. */\nfunction getCountryOptions(\n  countries: readonly string[] = allCountries.map((country) => country.code),\n): SelectOption[] {\n  return countries.map((code) => ({\n    icon: <CountryFlag code={code} />,\n    label: getCountryName(code),\n    value: code,\n  }))\n}\n\ninterface AddressFieldsProps {\n  /** Two-letter codes of the countries to offer, in the order to list them. @default every country */\n  countries?: readonly string[]\n  disabled?: boolean\n  errors?: Partial<Record<AddressField, string | undefined>>\n  /** Each field's input id, such as `useSimpleForm`'s `getId`, so a refused submit can focus the field. */\n  getId?: (field: AddressField) => string\n  /** Called once per field that changes. A new country also clears a state or postal code it doesn't use. */\n  onFieldChange: (field: AddressField, value: string) => void\n  value: Address\n}\n\nfunction AddressFields({\n  countries,\n  disabled,\n  errors = {},\n  getId,\n  onFieldChange,\n  value,\n}: AddressFieldsProps) {\n  const fallbackId = useId()\n  const wide = '@md/field-group:col-span-2'\n  const idOf = (field: AddressField) => getId?.(field) ?? `${fallbackId}-${field}`\n  const format = getAddressFormat(value.country)\n  const countryOptions = getCountryOptions(countries)\n\n  function changeCountry(country: string) {\n    const next = getAddressFormat(country)\n    onFieldChange('country', country)\n    const keepsState =\n      next.state &&\n      (next.state.options\n        ? next.state.options.some((option) => option.value === value.state)\n        : !format.state?.options)\n    if (value.state && !keepsState) onFieldChange('state', '')\n    if (value.postalCode && !next.postalCode) onFieldChange('postalCode', '')\n  }\n\n  function describe(field: AddressField) {\n    return {\n      'aria-describedby': errors[field] ? `${idOf(field)}-error` : undefined,\n      'aria-invalid': errors[field] ? true : undefined,\n      id: idOf(field),\n      name: field,\n    }\n  }\n\n  function input(field: AddressField, label: string, className?: string) {\n    return (\n      <Field\n        key={field}\n        data-invalid={errors[field] ? true : undefined}\n        className={className}\n      >\n        <FieldLabel htmlFor={idOf(field)}>{label}</FieldLabel>\n        <Input\n          {...describe(field)}\n          autoComplete={AUTOCOMPLETE[field]}\n          disabled={disabled}\n          value={value[field]}\n          onChange={(event) => onFieldChange(field, event.target.value)}\n        />\n        <FieldError id={`${idOf(field)}-error`}>{errors[field]}</FieldError>\n      </Field>\n    )\n  }\n\n  function render(field: AddressField, row: AddressField[]) {\n    if (field === 'line1') return input(field, 'Address')\n    if (field === 'line2') return input(field, 'Apartment, suite or floor (optional)')\n    if (field === 'city') {\n      return input(field, format.cityLabel, row.length === 2 ? wide : undefined)\n    }\n    if (field === 'postalCode' && format.postalCode) {\n      return input(\n        field,\n        format.postalCode.required\n          ? format.postalCode.label\n          : `${format.postalCode.label} (optional)`,\n        row.length === 2 && !row.includes('city') && row.at(-1) === field\n          ? wide\n          : undefined,\n      )\n    }\n    const state = format.state\n    if (field !== 'state' || !state) return null\n    const stateClass =\n      row.length === 2 && !row.includes('city') && row.at(-1) === field ? wide : undefined\n    if (!state.options) {\n      return input(\n        field,\n        state.required ? state.label : `${state.label} (optional)`,\n        stateClass,\n      )\n    }\n    return (\n      <Field\n        key={field}\n        data-invalid={errors[field] ? true : undefined}\n        className={stateClass}\n      >\n        <FieldLabel htmlFor={idOf(field)}>{state.label}</FieldLabel>\n        <OptionSelect\n          {...describe(field)}\n          disabled={disabled}\n          options={state.options}\n          placeholder={`Choose a ${inSentence(state.label)}`}\n          value={value.state || null}\n          onValueChange={(next) => onFieldChange('state', next)}\n        />\n        <FieldError id={`${idOf(field)}-error`}>{errors[field]}</FieldError>\n      </Field>\n    )\n  }\n\n  return (\n    <FieldGroup data-slot='address-fields'>\n      <Field data-invalid={errors.country ? true : undefined}>\n        <FieldLabel htmlFor={idOf('country')}>Country</FieldLabel>\n        <OptionSelect\n          {...describe('country')}\n          disabled={disabled}\n          options={countryOptions}\n          placeholder='Choose a country'\n          value={value.country || null}\n          onValueChange={changeCountry}\n        />\n        <FieldError id={`${idOf('country')}-error`}>{errors.country}</FieldError>\n      </Field>\n      {getAddressRows(format).map((row) =>\n        row.length > 1 ? (\n          <div key={row.join('-')} className='grid gap-4 @md/field-group:grid-cols-3'>\n            {row.map((field) => render(field, row))}\n          </div>\n        ) : (\n          render(row[0], row)\n        ),\n      )}\n    </FieldGroup>\n  )\n}\n\nexport { AddressFields, getAddressFormat, getCountryOptions, validateAddress }\nexport type { Address, AddressField, AddressFieldsProps, AddressFormat }\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/address-fields.tsx"
    }
  ],
  "type": "registry:component"
}
