{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "money-input",
  "title": "Money input",
  "description": "An amount of money: the symbol where the locale writes it, digits grouped as they are typed, the currency’s own decimals, and the value in minor units.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/number-input.json",
    "https://kinoui.com/r/input.json",
    "https://kinoui.com/r/field-control.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/addon-picker.json",
    "https://kinoui.com/r/countries.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/money-input.tsx",
      "content": "'use client'\n\nimport {\n  focusControl,\n  InputInvalidIcon,\n  inputBoxClassName,\n} from '@/registry/components/kino/input'\nimport { NumberInput, RollingInput } from '@/registry/components/kino/number-input'\nimport { AddonPicker, type AddonPickerOption } from '@/registry/lib/addon-picker'\nimport { CountryFlag } from '@/registry/lib/countries'\nimport {\n  changeDetails,\n  FieldValues,\n  keptOnReset,\n  useFormReset,\n} from '@/registry/lib/field-control'\nimport { numberFormatter } from '@/registry/lib/number-format'\nimport { mergeRefs } from '@/registry/lib/refs'\nimport { isComposing, type ChangeDetails as PickDetails } from '@ui-sdk/core'\nimport {\n  createNumberInputController,\n  type NumberInputControl as NumberInputControlPrimitive,\n  NumberInputGroup as NumberInputGroupPrimitive,\n} from '@ui-sdk/react/number-input'\nimport {\n  type ComponentProps,\n  createContext,\n  type KeyboardEvent,\n  type ClipboardEvent,\n  type ChangeEvent,\n  type RefObject,\n  use,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * An amount of money: the currency's symbol where the locale writes it,\n * digits grouped as they're typed, the currency's own number of decimals,\n * and the value in minor units (cents), so no amount is ever a float.\n */\n\n/** How a locale writes an amount in a currency. */\ninterface MoneyFormat {\n  locale: Intl.LocalesArgument\n  currency: string\n  /** Decimals in the currency's minor unit: 2 for USD, 0 for JPY, 3 for KWD. */\n  digits: number\n  symbol: string\n  /** The symbol's side, in reading order. */\n  side: 'start' | 'end'\n  /** Whether a space parts the symbol from the digits. */\n  spaced: boolean\n  /** The currency's name, such as \"US Dollar\". */\n  name: string\n  decimal: string\n  group: string\n  /** The locale's digits, 0 to 9. */\n  numerals: string[]\n  /** The locale's own direction, which the amount and its symbol keep on any page. */\n  direction: 'ltr' | 'rtl'\n}\n\n// Scripts written right to left, from Unicode's list of those in use today.\nconst RTL_SCRIPTS = new Set([\n  'Arab',\n  'Hebr',\n  'Thaa',\n  'Syrc',\n  'Nkoo',\n  'Adlm',\n  'Rohg',\n  'Mand',\n])\n\n/** Which way a locale writes, from its script. */\nfunction localeDirection(locale: string): 'ltr' | 'rtl' {\n  const script = new Intl.Locale(locale).maximize().script\n  return script && RTL_SCRIPTS.has(script) ? 'rtl' : 'ltr'\n}\n\n// Bidi marks, which right-to-left locales put around the symbol and the sign.\nconst FORMAT_CONTROLS = /\\p{Cf}/gu\nconst SPACE = /\\p{Zs}/u\n\nfunction moneyFormat(locale: Intl.LocalesArgument, currency: string): MoneyFormat {\n  const money = numberFormatter(locale, { style: 'currency', currency })\n  const parts = money.formatToParts(1)\n  const symbolAt = parts.findIndex((part) => part.type === 'currency')\n  const numberAt = parts.findIndex((part) => part.type === 'integer')\n  const between = parts.slice(\n    Math.min(symbolAt, numberAt) + 1,\n    Math.max(symbolAt, numberAt),\n  )\n  const plain = numberFormatter(locale, { useGrouping: true })\n  const separators = plain.formatToParts(11111.1)\n  return {\n    locale,\n    currency,\n    digits: money.resolvedOptions().maximumFractionDigits ?? 2,\n    symbol: (parts[symbolAt]?.value ?? currency).replace(FORMAT_CONTROLS, ''),\n    side: symbolAt < numberAt ? 'start' : 'end',\n    spaced: between.some((part) => SPACE.test(part.value)),\n    name: new Intl.DisplayNames(locale, { type: 'currency' }).of(currency) ?? currency,\n    decimal: separators.find((part) => part.type === 'decimal')?.value ?? '.',\n    group: separators.find((part) => part.type === 'group')?.value ?? ',',\n    numerals: Array.from({ length: 10 }, (_, digit) =>\n      numberFormatter(locale, { useGrouping: false }).format(digit),\n    ),\n    direction: localeDirection(money.resolvedOptions().locale),\n  }\n}\n\n// Digits in the numeral systems people type: ASCII, Arabic-Indic, Persian and fullwidth.\nconst DIGIT = /[0-9٠-٩۰-۹０-９]/\nconst MINUS = /[-−－‒–—﹣]/\nconst POINTS = ['.', ',', '٫', '．', '，']\n\n/** A typed or pasted digit as ASCII, or null when the character isn't one. */\nfunction asciiDigit(char: string): string | null {\n  if (!DIGIT.test(char)) return null\n  // Each block starts at a multiple of 16, so the code point says the digit.\n  return char <= '9' ? char : String((char.codePointAt(0) ?? 0) % 16)\n}\n\n/** The most digits before the point, so the amount in minor units stays a safe integer. */\nfunction maxIntegerDigits(digits: number) {\n  return 15 - digits\n}\n\n/** An amount's sign and digits, as typed: no grouping, ASCII digits, `.` as the point. */\ninterface Amount {\n  negative: boolean\n  integer: string\n  /** The point and what follows it, or null without one. */\n  fraction: string | null\n}\n\n/** Writes an amount in the locale's digits and separators, grouped. */\nfunction writeAmount({ negative, integer, fraction }: Amount, format: MoneyFormat) {\n  const numerals = (ascii: string) =>\n    Array.from(ascii, (char) => format.numerals[Number(char)]).join('')\n  const grouped =\n    integer === ''\n      ? ''\n      : numberFormatter(format.locale, { useGrouping: true }).format(BigInt(integer))\n  return `${negative ? '-' : ''}${grouped}${fraction === null ? '' : format.decimal + numerals(fraction)}`\n}\n\n/**\n * The text a person typed, grouped again, and where the caret goes: after as\n * many digits, signs and points as it had before it. Group separators typed\n * by hand are dropped, since grouping is the field's job; `.` or `,` is the\n * point unless the locale groups with it. Digits past the currency's decimals\n * are left out.\n */\nfunction regroup(\n  text: string,\n  caret: number,\n  format: MoneyFormat,\n  allowNegative: boolean,\n): { text: string; caret: number } {\n  let negative = false\n  let integer = ''\n  let fraction: string | null = null\n  // How many of the digits and points kept came before the caret; the sign is counted apart.\n  let beforeCaret = 0\n  let index = 0\n  for (const char of text.replace(FORMAT_CONTROLS, '')) {\n    const digit = asciiDigit(char)\n    let keep = false\n    if (digit !== null) {\n      if (fraction !== null) keep = fraction.length < format.digits\n      else keep = integer.length < maxIntegerDigits(format.digits)\n      if (keep && fraction !== null) fraction += digit\n      else if (keep) integer += digit\n    } else if (MINUS.test(char)) {\n      // A minus anywhere keeps the amount negative; it is written in front.\n      negative ||= allowNegative\n    } else if (\n      char === format.decimal ||\n      (POINTS.includes(char) && char !== format.group)\n    ) {\n      keep = fraction === null && format.digits > 0\n      if (keep) fraction = ''\n    }\n    if (keep && index < caret) beforeCaret += 1\n    index += char.length\n  }\n  // Leading zeros go, but for one before the point; the caret loses those it passed.\n  const zeros =\n    integer === '' ? 0 : integer.length - (integer.replace(/^0+/, '') || '0').length\n  beforeCaret -= Math.min(zeros, beforeCaret)\n  const written = writeAmount(\n    { negative, integer: integer.slice(zeros), fraction },\n    format,\n  )\n  // The caret goes after the sign and as many digits and points.\n  let count = 0\n  let position = negative ? 1 : 0\n  for (const char of written.slice(position)) {\n    if (count === beforeCaret) break\n    position += char.length\n    if (asciiDigit(char) !== null || char === format.decimal) count += 1\n  }\n  return { text: written, caret: position }\n}\n\n/**\n * The amount in pasted text, in minor units, or null when it holds no digits.\n * It reads any symbol, code, sign or grouping: \"$1,234.56\", \"1.234,56 €\",\n * \"USD 1,234\", \"(1,234)\" or \"1 234,56\". The last `.` or `,` is the point\n * when both are used; one used several times groups; one used once is the\n * point when the decimals it leaves fit the currency or nothing but zeros\n * comes before it, and groups when three digits follow it that don't.\n */\nfunction parseMoney(text: string, digits: number): number | null {\n  const clean = text.replace(FORMAT_CONTROLS, '').trim()\n  const negative = MINUS.test(clean) || /^\\(.*\\)$/.test(clean)\n  const body = Array.from(clean)\n    .map((char) => asciiDigit(char) ?? (POINTS.includes(char) ? char : ''))\n    .join('')\n    .replace(/[٫．]/g, '.')\n    .replace(/，/g, ',')\n  if (!/\\d/.test(body)) return null\n  const lastDot = body.lastIndexOf('.')\n  const lastComma = body.lastIndexOf(',')\n  let point = -1\n  if (lastDot !== -1 && lastComma !== -1) point = Math.max(lastDot, lastComma)\n  else {\n    const at = Math.max(lastDot, lastComma)\n    const mark = body[at]\n    const once = at !== -1 && body.indexOf(mark) === at\n    const after = body.length - at - 1\n    const lead = body.slice(0, at).replace(/\\D/g, '')\n    if (once && (after <= digits || after !== 3 || /^0*$/.test(lead))) point = at\n  }\n  const integer = (point === -1 ? body : body.slice(0, point)).replace(/\\D/g, '')\n  const fraction = point === -1 ? '' : body.slice(point + 1).replace(/\\D/g, '')\n  // Decimals past the currency's round half up.\n  const kept = fraction.slice(0, digits).padEnd(digits, '0')\n  const roundUp = Number(fraction[digits] ?? '0') >= 5\n  const minor = BigInt(`${integer || '0'}${kept}`) + (roundUp ? 1n : 0n)\n  if (minor > BigInt(Number.MAX_SAFE_INTEGER)) return null\n  return Number(minor) * (negative && minor !== 0n ? -1 : 1)\n}\n\n/** Minor units to the decimal the field holds. */\nfunction toMajor(minor: number, digits: number) {\n  return minor / 10 ** digits\n}\n\n/** The field's decimal back to minor units. */\nfunction toMinor(major: number, digits: number) {\n  return Math.round(major * 10 ** digits)\n}\n\ntype NumberInputProps = ComponentProps<typeof NumberInput>\n\ntype ChangeDetails = Parameters<NonNullable<NumberInputProps['onValueChange']>>[1]\n\ntype CommitDetails = Parameters<NonNullable<NumberInputProps['onValueCommit']>>[1]\n\nconst MoneyContext = createContext<{\n  format: MoneyFormat\n  allowNegative: boolean\n  changeCurrency: (currency: string, event: Event | undefined) => void\n  inputRef: RefObject<HTMLInputElement | null>\n  disabled: boolean\n  readOnly: boolean\n} | null>(null)\n\nfunction useMoney() {\n  const context = use(MoneyContext)\n  if (!context) throw new Error('Money input parts go inside <MoneyInput>.')\n  return context\n}\n\n// Props the Money input takes in minor units. `smallStep` is always `step`: a finer one would leave part of a minor unit.\ntype MinorUnits =\n  | 'value'\n  | 'defaultValue'\n  | 'min'\n  | 'max'\n  | 'step'\n  | 'largeStep'\n  | 'smallStep'\n\ntype MoneyInputProps = Omit<\n  NumberInputProps,\n  'className' | 'format' | 'onValueChange' | 'onValueCommit' | MinorUnits\n> & {\n  className?: string\n  /** The currency, as an ISO 4217 code such as `USD`, when you hold the state. */\n  currency?: string\n  /** The currency at first, when you leave the state to the field. */\n  defaultCurrency?: string\n  /**\n   * Called when a person picks another currency, with the amount moved to it:\n   * the same number, rounded to the new currency’s decimals, and who picked\n   * it in `details.source`. A parent that holds both sets them together, or\n   * neither to turn the change down; left to the field, `details.cancel()` does.\n   */\n  onCurrencyChange?: (\n    currency: string,\n    details: PickDetails<'item-press'> & { value: number | null },\n  ) => void\n  /** The amount in minor units, such as cents. */\n  value?: number | null\n  /** The amount at first, in minor units, when you leave the state to the field. */\n  defaultValue?: number | null\n  /** Called with the amount in minor units. */\n  onValueChange?: (value: number | null, details: ChangeDetails) => void\n  /** Called with the amount in minor units when a change is done: on blur, Enter or the end of a step. */\n  onValueCommit?: (value: number | null, details: CommitDetails) => void\n  /** The lowest amount, in minor units. */\n  min?: number\n  /** The highest amount, in minor units. */\n  max?: number\n  /**\n   * How far an arrow key steps, in minor units, and what a typed amount is\n   * rounded to once it's done. One minor unit, such as a cent, by default,\n   * so a typed amount keeps every digit the currency has.\n   */\n  step?: number\n  /** How far Shift with an arrow steps, in minor units. Ten units by default. */\n  largeStep?: number\n  /** Sends the currency with a form, under this name. The amount goes under the field’s `name`, as a decimal. */\n  currencyName?: string\n}\n\n/** An amount in minor units moved to a currency with other decimals, keeping its number. */\nfunction rescale(minor: number, fromDigits: number, toDigits: number) {\n  return toMinor(toMajor(minor, fromDigits), toDigits)\n}\n\nfunction MoneyInput({\n  className,\n  currency: currencyProp,\n  defaultCurrency = 'USD',\n  onCurrencyChange,\n  locale,\n  value: valueProp,\n  defaultValue: defaultValueProp,\n  onValueChange,\n  onValueCommit,\n  min,\n  max,\n  step,\n  largeStep,\n  currencyName,\n  form,\n  controller: controllerProp,\n  ref,\n  ...props\n}: MoneyInputProps) {\n  const defaultValue = defaultValueProp ?? null\n  const [ownCurrency, setOwnCurrency] = useState(defaultCurrency)\n  const [ownValue, setOwnValue] = useState<number | null>(defaultValue)\n  const currency = currencyProp ?? ownCurrency\n  const value = valueProp === undefined ? ownValue : valueProp\n  // The currency the field's own amount is in.\n  const [ownValueCurrency, setOwnValueCurrency] = useState(currency)\n  const localeKey = Array.isArray(locale) ? locale.join() : String(locale ?? '')\n  // eslint-disable-next-line react-hooks/exhaustive-deps -- the key stands for the locale\n  const format = useMemo(() => moneyFormat(locale, currency), [localeKey, currency])\n  const { digits } = format\n  const inputRef = useRef<HTMLInputElement>(null)\n  const major = (minor: number | undefined) =>\n    minor === undefined ? undefined : toMajor(minor, digits)\n  const unit = 10 ** digits\n\n  const changeValue = (next: number | null, details: ChangeDetails) => {\n    onValueChange?.(next, details)\n    if (!details.canceled) setOwnValue(next)\n  }\n\n  // The number input always holds the amount from here, so a form's reset is\n  // ours: the amount and the currency go back to their defaults, in the\n  // default currency's decimals, and a parent that holds the amount with a\n  // default hears it, as a native field's owner would.\n  const root = useRef<HTMLDivElement>(null)\n  const refs = useMemo(() => mergeRefs(root, ref), [ref])\n  useFormReset(\n    root,\n    () => {\n      if (currencyProp === undefined) {\n        setOwnCurrency(defaultCurrency)\n        setOwnValueCurrency(defaultCurrency)\n      }\n      if (valueProp === undefined) setOwnValue(defaultValue)\n    },\n    form,\n  )\n  const resetValue = (details: ChangeDetails) => {\n    if (keptOnReset(valueProp, defaultValueProp)) details.cancel()\n    else if (valueProp !== undefined) onValueChange?.(defaultValue, details)\n  }\n\n  // A pick moves a parent's amount to the new currency once the input has\n  // its decimals, step and limits, through the input, so the parent hears a\n  // change like any other.\n  const ownController = useMemo(() => createNumberInputController(), [])\n  const controller = controllerProp ?? ownController\n  const moving = useRef<number | null | undefined>(undefined)\n  useLayoutEffect(() => {\n    if (moving.current === undefined) return\n    const moved = moving.current\n    moving.current = undefined\n    controller.setValue(moved === null ? null : toMajor(moved, digits))\n  })\n\n  // When the currency changes, by a pick or from its parent, the field's own amount moves to it.\n  if (ownValueCurrency !== currency) {\n    setOwnValueCurrency(currency)\n    if (ownValue !== null) {\n      setOwnValue(rescale(ownValue, moneyFormat(locale, ownValueCurrency).digits, digits))\n    }\n  }\n\n  const changeCurrency = (next: string, event: Event | undefined) => {\n    if (next === currency) return\n    const moved =\n      value === null ? null : rescale(value, digits, moneyFormat(locale, next).digits)\n    const details = Object.assign(changeDetails('item-press', event), { value: moved })\n    onCurrencyChange?.(next, details)\n    if (currencyProp !== undefined || details.canceled) return\n    setOwnCurrency(next)\n    if (valueProp !== undefined && moved !== value) moving.current = moved\n  }\n\n  return (\n    <MoneyContext\n      value={{\n        format,\n        allowNegative: min !== undefined && min < 0,\n        changeCurrency,\n        inputRef,\n        disabled: props.disabled ?? false,\n        readOnly: props.readOnly ?? false,\n      }}\n    >\n      <NumberInput\n        ref={refs}\n        data-money-input=''\n        className={className}\n        controller={controller}\n        locale={locale}\n        format={{ minimumFractionDigits: digits, maximumFractionDigits: digits }}\n        value={value === null ? null : toMajor(value, digits)}\n        min={major(min)}\n        max={major(max)}\n        // ui-sdk snaps a committed amount to `step`, so it is the amount's\n        // precision, and Alt with an arrow moves no finer than the currency.\n        step={(step ?? 1) / unit}\n        smallStep={(step ?? 1) / unit}\n        largeStep={(largeStep ?? unit * 10) / unit}\n        onValueChange={(next, details) => {\n          if (details.reason === 'reset') resetValue(details)\n          else changeValue(next === null ? null : toMinor(next, digits), details)\n        }}\n        onValueCommit={(next, details) =>\n          onValueCommit?.(next === null ? null : toMinor(next, digits), details)\n        }\n        form={form}\n        {...props}\n      />\n      <FieldValues name={currencyName} form={form} values={[currency]} />\n    </MoneyContext>\n  )\n}\n\nfunction MoneyInputGroup({\n  className,\n  ...props\n}: Omit<ComponentProps<typeof NumberInputGroupPrimitive>, 'className'> & {\n  className?: string\n}) {\n  return (\n    <NumberInputGroupPrimitive\n      data-money-input-group=''\n      onPointerDown={focusControl}\n      className={cn(inputBoxClassName, 'w-full', className)}\n      {...props}\n    />\n  )\n}\n\n/**\n * Replaces a text control's value as an edit, so undo can take it back and\n * React and ui-sdk hear it. Where the browser has no `insertText`, the value\n * is set and the input event sent by hand.\n */\nfunction writeText(input: HTMLInputElement, text: string) {\n  // Only the part that differs is replaced, so undo brings back a small change.\n  const old = input.value\n  let start = 0\n  while (start < old.length && start < text.length && old[start] === text[start])\n    start += 1\n  let end = 0\n  while (\n    end < old.length - start &&\n    end < text.length - start &&\n    old[old.length - 1 - end] === text[text.length - 1 - end]\n  ) {\n    end += 1\n  }\n  input.setSelectionRange(start, old.length - end)\n  const inserted = text.slice(start, text.length - end)\n  if (document.execCommand('insertText', false, inserted) && input.value === text) return\n  Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set?.call(\n    input,\n    text,\n  )\n  input.dispatchEvent(new Event('input', { bubbles: true }))\n}\n\nfunction MoneyInputInput({\n  className,\n  onChange,\n  onKeyDown,\n  onPaste,\n  ref,\n  ...props\n}: Omit<ComponentProps<typeof NumberInputControlPrimitive>, 'className'> & {\n  className?: string\n}) {\n  const { format, allowNegative, inputRef } = useMoney()\n  const nameId = useId()\n  const refs = useMemo(() => mergeRefs(inputRef, ref), [inputRef, ref])\n\n  // Groups the digits as they're typed, keeping the caret beside the same digit.\n  const regroupTyping = (event: ChangeEvent<HTMLInputElement>) => {\n    const input = event.currentTarget\n    const composing = isComposing(event)\n    // An undo or a redo brings back a text as it was; regrouping it would be a new edit, and undo would never get past it.\n    const history =\n      'inputType' in event.nativeEvent &&\n      typeof event.nativeEvent.inputType === 'string' &&\n      event.nativeEvent.inputType.startsWith('history')\n    // An undo leaves what it brought back selected; the caret goes after it, so the next key doesn't replace it.\n    if (history) input.setSelectionRange(input.selectionEnd, input.selectionEnd)\n    if (!composing && !history) {\n      const next = regroup(\n        input.value,\n        input.selectionStart ?? input.value.length,\n        format,\n        allowNegative,\n      )\n      if (next.text !== input.value) {\n        writeText(input, next.text)\n        input.setSelectionRange(next.caret, next.caret)\n      }\n    }\n    onChange?.(event)\n  }\n\n  // Backspace or Delete beside a group separator removes the digit past it.\n  const skipSeparator = (event: KeyboardEvent<HTMLInputElement>) => {\n    onKeyDown?.(event)\n    const input = event.currentTarget\n    const { selectionStart: start, selectionEnd: end, value } = input\n    // A currency without decimals takes no point.\n    if (format.digits === 0 && POINTS.includes(event.key)) event.preventDefault()\n    // Home and End move the caret, as in any text, where the number input\n    // would set the amount to its min or max. Stopping that stops the\n    // browser's move too, so it is made here, Shift selecting as it goes.\n    if ((event.key === 'Home' || event.key === 'End') && start !== null && end !== null) {\n      event.preventDefault()\n      const home = event.key === 'Home'\n      const to = home ? 0 : value.length\n      const anchor = input.selectionDirection === 'backward' ? end : start\n      if (!event.shiftKey) input.setSelectionRange(to, to)\n      else if (home) input.setSelectionRange(to, anchor, 'backward')\n      else input.setSelectionRange(anchor, to, 'forward')\n      return\n    }\n    if (start === null || start !== end) return\n    const isGroup = (char: string | undefined) =>\n      char !== undefined &&\n      (char === format.group || (SPACE.test(char) && SPACE.test(format.group)))\n    if (event.key === 'Backspace' && isGroup(value[start - 1])) {\n      input.setSelectionRange(start - 1, start - 1)\n    } else if (event.key === 'Delete' && isGroup(value[start])) {\n      input.setSelectionRange(start + 1, start + 1)\n    }\n  }\n\n  // A pasted amount is read in any format and written in the locale's.\n  const pasteAmount = (event: ClipboardEvent<HTMLInputElement>) => {\n    onPaste?.(event)\n    if (event.defaultPrevented) return\n    const input = event.currentTarget\n    const pasted = parseMoney(event.clipboardData.getData('text/plain'), format.digits)\n    event.preventDefault()\n    if (pasted === null || (pasted < 0 && !allowNegative)) return\n    const minor = Math.abs(pasted)\n      .toString()\n      .padStart(format.digits + 1, '0')\n    const amount: Amount = {\n      negative: pasted < 0,\n      integer: minor.slice(0, minor.length - format.digits),\n      fraction: format.digits > 0 ? minor.slice(-format.digits) : null,\n    }\n    const start = input.selectionStart ?? 0\n    const end = input.selectionEnd ?? input.value.length\n    // A whole amount replaces what's selected. Into the middle of one go its\n    // digits, and its decimals only when it has some, so \"5\" stays a 5.\n    const whole = start === 0 && end === input.value.length\n    const fraction = amount.fraction?.replace(/0+$/, '')\n    const inserted = whole\n      ? writeAmount(amount, format)\n      : `${amount.integer}${fraction ? format.decimal + fraction : ''}`\n    const next = regroup(\n      input.value.slice(0, start) + inserted + input.value.slice(end),\n      start + inserted.length,\n      format,\n      allowNegative,\n    )\n    writeText(input, next.text)\n    input.setSelectionRange(next.caret, next.caret)\n  }\n\n  const symbol = (\n    <span\n      data-money-input-symbol=''\n      aria-hidden\n      suppressHydrationWarning\n      className={cn(\n        'text-muted-foreground shrink-0 text-base whitespace-nowrap select-none md:text-sm',\n        format.side === 'start' ? 'order-first ps-(--control-padding)' : 'order-last',\n        format.side === 'end' && 'pe-(--control-padding)',\n      )}\n    >\n      {format.symbol}\n    </span>\n  )\n\n  return (\n    <span className={cn('flex min-w-0 flex-1 items-center', className)}>\n      {/* The amount reads the locale's way on any page: dollars in a right-to-left app are still $1,280.50. */}\n      <span dir={format.direction} className='flex min-w-0 flex-1 items-center'>\n        {symbol}\n        <RollingInput\n          data-money-input-input=''\n          inputMode={format.digits > 0 ? 'decimal' : 'numeric'}\n          // Zero in the currency's decimals, so an empty field shows what it takes.\n          placeholder={writeAmount(\n            {\n              negative: false,\n              integer: '0',\n              fraction: format.digits > 0 ? '0'.repeat(format.digits) : null,\n            },\n            format,\n          )}\n          decimal={format.decimal}\n          className={cn(\n            // The digits sit against the symbol.\n            format.side === 'start' ? 'text-start' : 'text-end',\n            format.side === 'start' && (format.spaced ? 'ps-1' : 'ps-0'),\n            format.side === 'end' && (format.spaced ? 'pe-1' : 'pe-0'),\n          )}\n          {...props}\n          ref={refs}\n          aria-describedby={[nameId, props['aria-describedby']].filter(Boolean).join(' ')}\n          onChange={regroupTyping}\n          onKeyDown={skipSeparator}\n          onPaste={pasteAmount}\n        />\n      </span>\n      <span id={nameId} className='sr-only' suppressHydrationWarning>\n        {format.name}\n      </span>\n      <InputInvalidIcon />\n    </span>\n  )\n}\n\n/**\n * A currency's flag: the country its code starts with, as ISO 4217 codes do\n * (`GB` for GBP), and the EU's for the euro. Codes for no one country, such\n * as XAF, keep the flag's room, empty.\n */\nfunction CurrencyFlag({ currency }: { currency: string }) {\n  // X codes belong to no country, though the flags use XA, XO and XC for places.\n  return <CountryFlag country={currency.startsWith('X') ? '' : currency.slice(0, 2)} />\n}\n\n/**\n * A button in the box that picks the currency from `currencies`, at the\n * box's end. Its list searches names, codes and symbols.\n */\nfunction MoneyInputCurrency({\n  currencies,\n  label = 'Currency',\n  searchPlaceholder = 'Search currencies',\n  className,\n}: {\n  /** ISO 4217 codes, in the order the list shows them. */\n  currencies: readonly string[]\n  /** What is picked: the button reads \"Currency: US Dollar, USD\". */\n  label?: string\n  searchPlaceholder?: string\n  className?: string\n}) {\n  const { format, changeCurrency, inputRef, disabled, readOnly } = useMoney()\n  const options = useMemo(\n    () =>\n      currencies.map((code): AddonPickerOption => {\n        const { name, symbol } = moneyFormat(format.locale, code)\n        return {\n          value: code,\n          label: name,\n          detail: code,\n          visual: <CurrencyFlag currency={code} />,\n          keywords: [symbol],\n        }\n      }),\n    [currencies, format.locale],\n  )\n  return (\n    <AddonPicker\n      options={options}\n      value={format.currency}\n      onValueChange={changeCurrency}\n      label={label}\n      searchPlaceholder={searchPlaceholder}\n      noMatch={(query) => `No currency matches “${query}”.`}\n      align='inline-end'\n      disabled={disabled}\n      readOnly={readOnly}\n      returnFocus={inputRef}\n      className={className}\n    >\n      <CurrencyFlag currency={format.currency} />\n      <span className='tabular-nums'>{format.currency}</span>\n    </AddonPicker>\n  )\n}\n\nexport { MoneyInput, MoneyInputCurrency, MoneyInputGroup, MoneyInputInput }\nexport { moneyFormat, parseMoney, regroup, rescale, toMajor, toMinor }\nexport type { MoneyFormat, MoneyInputProps }\n",
      "type": "registry:component",
      "target": "@components/kino/money-input.tsx"
    }
  ],
  "type": "registry:component"
}