{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "gulf-amount",
  "type": "registry:ui",
  "title": "Gulf amount",
  "description": "An amount in AED, SAR, QAR, KWD, BHD or OMR, with three decimals for the dinars and the rial and Arabic or Western digits.",
  "dependencies": [
    "@dualkit/format"
  ],
  "registryDependencies": [
    "input",
    "https://dualkit.dev/r/gulf-field.json"
  ],
  "files": [
    {
      "path": "gulf/gulf-amount.tsx",
      "type": "registry:ui",
      "target": "components/gulf/gulf-amount.tsx",
      "content": "import { formatMoney, toWesternDigits, type Currency, type Locale, type Numerals, type Result } from '@dualkit/format'\nimport { Input } from '@/components/ui/input'\nimport { GulfField, cx, LTR_PLACEHOLDER, useMaskedInput, useShownError, withNumerals, type GulfFieldText } from './gulf-field'\n\nexport type GulfAmountError = 'empty' | 'invalid_number' | 'too_large' | 'too_many_decimals'\nexport type GulfAmountValue = { readonly amount: number; readonly formatted: string }\nexport type GulfAmountResult = Result<GulfAmountValue, GulfAmountError>\nexport type GulfAmountOptions = {\n  readonly currency: Currency\n  readonly locale?: Locale\n  readonly numerals?: Numerals\n  /** Accept a leading minus. Off by default, so a stray hyphen is never read as a negative amount. */\n  readonly allowNegative?: boolean\n}\n\nconst NBSP = ' '\nconst err = (code: GulfAmountError, message: string): GulfAmountResult => ({ ok: false, error: { code, message } })\n\n/** How many decimals the currency shows, read from format: two for AED, SAR and QAR, three for the dinars and the rial. */\nconst decimalsOf = (currency: Currency): number => formatMoney(0, { currency }).split('.')[1]?.length ?? 0\n\n/** The code in English and format's Arabic abbreviation in Arabic, which is the part of formatMoney's output that is not the number. */\nfunction currencyMark(currency: Currency, locale: Locale): string {\n  const parts = formatMoney(0, { currency, locale }).split(NBSP)\n  return (locale === 'ar' ? parts[parts.length - 1] : parts[0]) ?? currency\n}\n\n/** Whole parts past 15 digits lose precision as a JavaScript number and can print with an exponent. */\nconst MAX_WHOLE_DIGITS = 15\n/** An optional minus, a whole part that is plain digits or grouped in threes with commas, and an optional fraction. */\nconst AMOUNT = /^(-?)(\\d{1,3}(?:,\\d{3})+|\\d*)(?:\\.(\\d*))?$/\n\n/**\n * Reads a typed amount. format has no amount parser yet, so this only turns the text into a number,\n * checks it against the currency's decimals, and leaves the formatting to formatMoney.\n * A comma is read only as thousands grouping, so \"12,5\" is refused rather than read as 125.\n */\nexport function readGulfAmount(value: string, options: GulfAmountOptions): GulfAmountResult {\n  const { currency, locale = 'en', numerals = 'latn', allowNegative = false } = options\n  const text = toWesternDigits(value).replace(/\\s/g, '')\n  if (text === '') return err('empty', 'Enter an amount.')\n  const match = AMOUNT.exec(text)\n  const [, sign = '', whole = '', fraction] = match ?? []\n  if (!match || (whole === '' && !fraction) || (sign !== '' && !allowNegative)) {\n    return err('invalid_number', 'Enter an amount in digits.')\n  }\n  const digits = whole.replace(/,/g, '')\n  if (digits.length > MAX_WHOLE_DIGITS) return err('too_large', `Enter at most ${MAX_WHOLE_DIGITS} digits before the decimal point.`)\n  const decimals = decimalsOf(currency)\n  if ((fraction ?? '').length > decimals) return err('too_many_decimals', `${currency} has ${decimals} decimal places.`)\n  const parsed = Number(`${sign}${digits}${fraction ? `.${fraction}` : ''}`)\n  const amount = parsed === 0 ? 0 : parsed // -0 reads as 0.\n  return { ok: true, value: { amount, formatted: formatMoney(amount, { currency, locale, numerals }) } }\n}\n\nexport type GulfAmountProps = GulfFieldText<GulfAmountError> & GulfAmountOptions & {\n  /** What was typed, with Western digits and a full stop for the decimal point. */\n  value: string\n  onChange: (value: string) => void\n  onResult?: (result: GulfAmountResult) => void\n}\n\n/** Digits, the point and grouping commas; a minus only at the start, and only when negatives are allowed. */\nfunction keepAmountCharacters(raw: string, allowNegative: boolean): string {\n  const kept = toWesternDigits(raw).replace(/[^\\d.,-]/g, '')\n  const negative = allowNegative && kept.startsWith('-')\n  return `${negative ? '-' : ''}${kept.replace(/-/g, '')}`\n}\n\nconst MARK = 'text-muted-foreground flex items-center px-3 text-sm'\n\n/** An amount in a Gulf currency. English puts the code first; Arabic puts the abbreviation after the number. */\nexport function GulfAmount(props: GulfAmountProps) {\n  const {\n    value, onChange, onResult, currency, locale = 'en', numerals = 'latn', allowNegative = false,\n    label, help, error, errorMessages, id, name, placeholder, disabled, required, className,\n  } = props\n  const options = { currency, locale, numerals, allowNegative }\n  const result = readGulfAmount(value, options)\n  const shown = useShownError(result, error, errorMessages)\n  const commit = (next: string) => {\n    onChange(next)\n    onResult?.(readGulfAmount(next, options))\n  }\n  const input = useMaskedInput(value, {\n    normalize: (raw) => keepAmountCharacters(raw, allowNegative),\n    display: (v) => withNumerals(v, numerals),\n  }, commit)\n\n  const onBlur = () => {\n    shown.onBlur()\n    if (!result.ok) return\n    const padded = result.value.amount.toFixed(decimalsOf(currency))\n    if (padded !== value) commit(padded)\n  }\n\n  return (\n    <GulfField id={id} label={label} help={help} error={shown.error} className={className}>\n      {(aria) => {\n        const markId = `${aria.id}-currency`\n        const mark = <span id={markId} className={MARK}>{currencyMark(currency, locale)}</span>\n        return (\n        <div className=\"grid gap-1\">\n          <div className={cx('border-input flex rounded-md border shadow-xs', 'focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]')}>\n            {locale === 'en' && mark}\n            <Input {...aria} aria-describedby={cx(markId, aria['aria-describedby'])} {...input} dir=\"ltr\" inputMode=\"decimal\" autoComplete=\"off\"\n              name={name} placeholder={placeholder} disabled={disabled} required={required}\n              className={cx('border-0 shadow-none focus-visible:ring-0 text-start tabular-nums', LTR_PLACEHOLDER)} onBlur={onBlur} />\n            {locale === 'ar' && mark}\n          </div>\n          {result.ok && (\n            <output htmlFor={aria.id} aria-live=\"off\" className=\"text-muted-foreground text-sm\">\n              <bdi>{result.value.formatted}</bdi>\n            </output>\n          )}\n        </div>\n        )\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."
}
