{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "gulf-hijri-date",
  "type": "registry:ui",
  "title": "Gulf Hijri date",
  "description": "A date typed once and shown in Gregorian and Umm al-Qura Hijri. The time zone is required.",
  "dependencies": [
    "@dualkit/format"
  ],
  "registryDependencies": [
    "input",
    "https://dualkit.dev/r/gulf-field.json"
  ],
  "files": [
    {
      "path": "gulf/gulf-hijri-date.tsx",
      "type": "registry:ui",
      "target": "components/gulf/gulf-hijri-date.tsx",
      "content": "import {\n  formatHijri, toHijri, toWesternDigits,\n  type HijriDate, type Locale, type Numerals, type Result,\n} from '@dualkit/format'\nimport type { ReactNode } from 'react'\nimport { Input } from '@/components/ui/input'\nimport { GulfField, cx, LTR_PLACEHOLDER, useMaskedInput, useShownError, withNumerals, type GulfFieldText, type Mask } from './gulf-field'\n\nexport type GulfDateError = 'empty' | 'invalid_format' | 'invalid_date'\nexport type GulfDateValue = {\n  readonly iso: string\n  /** Midday of that calendar day in the time zone. */\n  readonly date: Date\n  readonly hijri: HijriDate\n}\nexport type GulfDateResult = Result<GulfDateValue, GulfDateError>\n\nconst DAY = 86_400_000\nconst err = (code: GulfDateError, message: string): GulfDateResult => ({ ok: false, error: { code, message } })\nconst pad = (n: number): string => String(n).padStart(2, '0')\n\n/** The calendar day a moment falls on in a time zone, as a UTC midnight. en-US is used only for its digits. */\nfunction dayIn(moment: Date, timeZone: string): number {\n  const parts = new Intl.DateTimeFormat('en-US', { timeZone, year: 'numeric', month: 'numeric', day: 'numeric' }).formatToParts(moment)\n  const get = (type: string) => Number(parts.find((p) => p.type === type)?.value)\n  return Date.UTC(get('year'), get('month') - 1, get('day'))\n}\n\n/**\n * Reads a typed YYYY-MM-DD date as that calendar day in the time zone, and gives its Umm al-Qura date from format's toHijri.\n * The time zone is required, as toHijri requires it.\n */\nexport function readGulfDate(value: string, options: { readonly timeZone: string }): GulfDateResult {\n  const { timeZone } = options\n  const text = toWesternDigits(value).trim()\n  if (text === '') return err('empty', 'Enter a date.')\n  const match = /^(\\d{4})-(\\d{1,2})-(\\d{1,2})$/.exec(text)\n  if (!match) return err('invalid_format', 'Write the date as YYYY-MM-DD.')\n  const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]\n  const target = Date.UTC(year, month - 1, day)\n  const check = new Date(target)\n  if (check.getUTCFullYear() !== year || check.getUTCMonth() !== month - 1 || check.getUTCDate() !== day) {\n    return err('invalid_date', 'This date does not exist.')\n  }\n  const noon = new Date(target + DAY / 2)\n  toHijri(noon, { timeZone }) // Throws format's own error when the time zone is missing.\n  const date = new Date(noon.getTime() + (target - dayIn(noon, timeZone)))\n  return { ok: true, value: { iso: `${year}-${pad(month)}-${pad(day)}`, date, hijri: toHijri(date, { timeZone }) } }\n}\n\nconst DATE_MASK: Mask = {\n  normalize: (raw) => toWesternDigits(raw).replace(/[^\\d-]/g, '').slice(0, 10),\n  display: (value) => value,\n}\n\nexport type GulfHijriDateProps = GulfFieldText<GulfDateError> & {\n  /** YYYY-MM-DD with Western digits. */\n  value: string\n  onChange: (value: string) => void\n  onResult?: (result: GulfDateResult) => void\n  /** Required: the day is read in this zone, such as \"Asia/Dubai\" or \"Asia/Riyadh\". */\n  timeZone: string\n  locale?: Locale\n  numerals?: Numerals\n  /** Optional captions for the two dates, in the page language. */\n  calendarLabels?: { readonly gregorian?: ReactNode; readonly hijri?: ReactNode }\n}\n\nconst gregorianText = (date: Date, locale: Locale, numerals: Numerals, timeZone: string): string =>\n  new Intl.DateTimeFormat(`${locale === 'ar' ? 'ar' : 'en-GB'}-u-ca-gregory-nu-${numerals}`, {\n    day: 'numeric', month: 'long', year: 'numeric', timeZone,\n  }).format(date)\n\nfunction Line({ caption, text }: { caption: ReactNode; text: string }) {\n  return (\n    <span className=\"flex items-baseline gap-2\">\n      {caption != null && <span className=\"text-muted-foreground text-xs\">{caption}</span>}\n      <bdi className=\"text-foreground\">{text}</bdi>\n    </span>\n  )\n}\n\n/** A date typed once and shown in both calendars, Gregorian and Umm al-Qura Hijri, side by side. */\nexport function GulfHijriDate(props: GulfHijriDateProps) {\n  const {\n    value, onChange, onResult, timeZone, locale = 'en', numerals = 'latn', calendarLabels,\n    label, help, error, errorMessages, id, name, placeholder, disabled, required, className,\n  } = props\n  const result = readGulfDate(value, { timeZone })\n  const shown = useShownError(result, error, errorMessages)\n  const input = useMaskedInput(value, { ...DATE_MASK, display: (v) => withNumerals(v, numerals) }, (next) => {\n    onChange(next)\n    onResult?.(readGulfDate(next, { timeZone }))\n  })\n\n  return (\n    <GulfField id={id} label={label} help={help} error={shown.error} className={className}>\n      {(aria) => (\n        <div className=\"grid gap-1\">\n          <Input {...aria} {...input} dir=\"ltr\" inputMode=\"numeric\" autoComplete=\"off\"\n            name={name} placeholder={placeholder} disabled={disabled} required={required}\n            className={cx('text-start tabular-nums', LTR_PLACEHOLDER)} onBlur={shown.onBlur} />\n          {result.ok && (\n            <output htmlFor={aria.id} aria-live=\"off\" className=\"text-sm\">\n              <time dateTime={result.value.iso} className=\"flex flex-wrap gap-x-4 gap-y-1\">\n                <Line caption={calendarLabels?.gregorian} text={gregorianText(result.value.date, locale, numerals, timeZone)} />\n                <Line caption={calendarLabels?.hijri} text={formatHijri(result.value.date, { timeZone, locale, numerals })} />\n              </time>\n            </output>\n          )}\n        </div>\n      )}\n    </GulfField>\n  )\n}\n"
    }
  ],
  "docs": "Needs a shadcn project (Tailwind and the shadcn CSS variables). Works with and without `shadcn init --rtl`: set dir=\"rtl\" on <html> or a parent for Arabic. Pass every label, help text and error message as props."
}
