{
  "name": "amount-pad",
  "type": "registry:component",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "files": [
    {
      "type": "registry:component",
      "content": "\"use client\";\n\n/**\n * @author: @dorianbaffier\n * @description: Amount Pad\n * @version: 1.0.0\n * @date: 2026-10-21\n * @license: MIT\n * @website: https://kokonutui.com\n * @github: https://github.com/kokonut-labs/kokonutui\n */\n\nimport { ArrowUp, Check, Delete } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useMotionValue,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  type KeyboardEvent,\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst MAX_WHOLE_DIGITS = 7;\nconst DIGIT = /^\\d$/;\nconst KEY_LABELS: Record<string, string> = {\n  back: \"Delete\",\n  \".\": \"Decimal point\",\n};\nconst KEYS = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \".\", \"0\", \"back\"];\n\nexport interface AmountPadProps {\n  /** Who the money goes to. */\n  recipient?: { name: string; handle?: string };\n  /** Currency sign drawn before the amount. */\n  currency?: string;\n  /** Largest amount allowed in one go. */\n  max?: number;\n  /** Shown under the amount until you hit the cap. */\n  balance?: number;\n  /** One-tap amounts. */\n  presets?: number[];\n  onSend?: (amount: number) => void;\n  className?: string;\n}\n\n/** One typed character, with an id that follows it as commas move around. */\ninterface Char {\n  id: number;\n  char: string;\n}\n\ninterface Glyph {\n  key: string;\n  char: string;\n  kind: \"digit\" | \"sep\" | \"ghost\";\n}\n\nconst toNumber = (chars: Char[]) =>\n  Number.parseFloat(chars.map((c) => c.char).join(\"\") || \"0\");\n\nconst money = (value: number, currency: string) =>\n  `${currency}${value.toLocaleString(\"en-US\", {\n    minimumFractionDigits: value % 1 === 0 ? 0 : 2,\n    maximumFractionDigits: 2,\n  })}`;\n\n/** What typing `key` does to the amount: the new characters, or null if it can't take it. */\nfunction typeKey(\n  chars: Char[],\n  key: string,\n  make: (char: string) => Char\n): Char[] | null {\n  const point = chars.findIndex((c) => c.char === \".\");\n  if (key === \".\") {\n    if (point !== -1) {\n      return null;\n    }\n    return chars.length === 0 ? [make(\"0\"), make(\".\")] : [...chars, make(\".\")];\n  }\n  const centsFull = point !== -1 && chars.length - point > 2;\n  const wholeFull = point === -1 && chars.length >= MAX_WHOLE_DIGITS;\n  if (centsFull || wholeFull) {\n    return null;\n  }\n  // A lone leading zero is replaced, not followed.\n  return chars.length === 1 && chars[0].char === \"0\"\n    ? [make(key)]\n    : [...chars, make(key)];\n}\n\n/**\n * Lays typed characters out as an amount: commas every three whole digits,\n * keyed by the digit they sit in front of, and faint zeros after the point\n * for the cents still to come.\n */\nfunction layout(chars: Char[]): Glyph[] {\n  const point = chars.findIndex((c) => c.char === \".\");\n  const whole = point === -1 ? chars : chars.slice(0, point);\n  const glyphs: Glyph[] = [];\n\n  whole.forEach((c, index) => {\n    const fromRight = whole.length - index;\n    if (index > 0 && fromRight % 3 === 0) {\n      glyphs.push({ key: `comma-${c.id}`, char: \",\", kind: \"sep\" });\n    }\n    glyphs.push({ key: `d-${c.id}`, char: c.char, kind: \"digit\" });\n  });\n\n  if (point !== -1) {\n    const cents = chars.slice(point + 1);\n    glyphs.push({ key: `d-${chars[point].id}`, char: \".\", kind: \"sep\" });\n    for (const c of cents) {\n      glyphs.push({ key: `d-${c.id}`, char: c.char, kind: \"digit\" });\n    }\n    for (let i = cents.length; i < 2; i++) {\n      glyphs.push({ key: `ghost-${i}`, char: \"0\", kind: \"ghost\" });\n    }\n  }\n  return glyphs;\n}\n\nexport default function AmountPad({\n  recipient = { name: \"Maya Chen\", handle: \"@maya\" },\n  currency = \"$\",\n  max = 2500,\n  balance = 3204.18,\n  presets = [20, 50, 100],\n  onSend,\n  className,\n}: AmountPadProps) {\n  const [chars, setChars] = useState<Char[]>([]);\n  const [capped, setCapped] = useState(false);\n  const [sent, setSent] = useState<number | null>(null);\n  const reduceMotion = useReducedMotion();\n\n  const nextId = useRef(1);\n  const frameRef = useRef<HTMLDivElement>(null);\n  const amountRef = useRef<HTMLDivElement>(null);\n  const capTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const sentTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const fit = useMotionValue(1);\n  const shakeX = useMotionValue(0);\n\n  const value = toNumber(chars);\n  const empty = chars.length === 0;\n\n  useEffect(\n    () => () => {\n      clearTimeout(capTimer.current);\n      clearTimeout(sentTimer.current);\n    },\n    []\n  );\n\n  // The amount shrinks to stay on one line as it grows, and grows back as\n  // digits are deleted.\n  useLayoutEffect(() => {\n    const frame = frameRef.current;\n    const amount = amountRef.current;\n    if (!(frame && amount)) {\n      return;\n    }\n    const measure = () => {\n      const target = Math.min(1, frame.clientWidth / amount.scrollWidth);\n      animate(\n        fit,\n        target,\n        reduceMotion\n          ? { duration: 0 }\n          : { type: \"spring\", stiffness: 380, damping: 34 }\n      );\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(frame);\n    observer.observe(amount);\n    return () => observer.disconnect();\n  }, [fit, reduceMotion]);\n\n  const refuse = useCallback(\n    (showCap: boolean) => {\n      if (showCap) {\n        setCapped(true);\n        clearTimeout(capTimer.current);\n        capTimer.current = setTimeout(() => setCapped(false), 1800);\n      }\n      if (!reduceMotion) {\n        animate(shakeX, [0, -10, 9, -6, 4, 0], {\n          duration: 0.36,\n          ease: \"easeOut\",\n        });\n      }\n    },\n    [reduceMotion, shakeX]\n  );\n\n  const make = (char: string): Char => {\n    const id = nextId.current;\n    nextId.current += 1;\n    return { id, char };\n  };\n\n  // Touching the pad after a send keeps what you type: the pending reset\n  // would otherwise wipe it.\n  const clearSent = () => {\n    clearTimeout(sentTimer.current);\n    setSent(null);\n  };\n\n  const press = (key: string) => {\n    clearSent();\n    if (key === \"back\") {\n      setChars((current) => current.slice(0, -1));\n      setCapped(false);\n      return;\n    }\n\n    const next = typeKey(chars, key, make);\n    if (!next) {\n      refuse(false);\n    } else if (toNumber(next) > max) {\n      refuse(true);\n    } else {\n      setChars(next);\n    }\n  };\n\n  const preset = (amount: number) => {\n    clearSent();\n    setCapped(false);\n    setChars([...String(Math.min(amount, max))].map(make));\n  };\n\n  const send = () => {\n    if (sent !== null) {\n      return;\n    }\n    if (empty || value <= 0) {\n      refuse(false);\n      return;\n    }\n    onSend?.(value);\n    setSent(value);\n    clearTimeout(sentTimer.current);\n    sentTimer.current = setTimeout(() => {\n      setChars([]);\n      setSent(null);\n    }, 1600);\n  };\n\n  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    if (event.metaKey || event.ctrlKey || event.altKey) {\n      return;\n    }\n    let key: string | null = null;\n    if (DIGIT.test(event.key) || event.key === \".\") {\n      key = event.key;\n    } else if (event.key === \",\") {\n      key = \".\";\n    } else if (event.key === \"Backspace\") {\n      key = \"back\";\n    }\n    // Enter is left alone: on a focused key or Send it already clicks it.\n    if (key) {\n      event.preventDefault();\n      press(key);\n    }\n  };\n\n  const glyphs = layout(chars);\n  let sendTone =\n    \"bg-zinc-900 text-white hover:bg-zinc-800 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-white\";\n  if (sent !== null) {\n    sendTone =\n      \"bg-emerald-600 text-white dark:bg-emerald-500 dark:text-emerald-950\";\n  } else if (empty) {\n    sendTone = \"bg-zinc-100 text-zinc-400 dark:bg-zinc-900 dark:text-zinc-600\";\n  }\n  const digitIn = reduceMotion\n    ? { duration: 0 }\n    : { type: \"spring\" as const, stiffness: 520, damping: 30, mass: 0.8 };\n  const slide = reduceMotion\n    ? { duration: 0 }\n    : { type: \"spring\" as const, stiffness: 500, damping: 40 };\n\n  const initials = recipient.name\n    .split(\" \")\n    .map((part) => part[0])\n    .join(\"\")\n    .slice(0, 2);\n\n  return (\n    // biome-ignore lint/a11y/noStaticElementInteractions: typing anywhere in the pad goes to the amount; the keys themselves are buttons.\n    // biome-ignore lint/a11y/noNoninteractiveElementInteractions: same as above\n    <div\n      className={cn(\n        \"flex w-full max-w-xs flex-col rounded-3xl border border-zinc-200 bg-white p-5 dark:border-zinc-800 dark:bg-zinc-950\",\n        className\n      )}\n      onKeyDown={onKeyDown}\n    >\n      <div className=\"flex items-center gap-3\">\n        <span className=\"flex size-9 items-center justify-center rounded-full bg-orange-100 font-medium text-orange-700 text-xs dark:bg-orange-500/15 dark:text-orange-300\">\n          {initials}\n        </span>\n        <div className=\"min-w-0 leading-tight\">\n          <p className=\"text-xs text-zinc-500 dark:text-zinc-400\">Send to</p>\n          <p className=\"truncate font-medium text-sm text-zinc-900 dark:text-zinc-100\">\n            {recipient.name}\n            {recipient.handle && (\n              <span className=\"ml-1.5 font-normal text-zinc-400 dark:text-zinc-500\">\n                {recipient.handle}\n              </span>\n            )}\n          </p>\n        </div>\n      </div>\n\n      <div\n        className=\"mt-6 flex h-20 items-center justify-center\"\n        ref={frameRef}\n      >\n        <output aria-live=\"polite\" className=\"sr-only\">\n          {money(value, currency)}\n        </output>\n        <motion.div\n          aria-hidden=\"true\"\n          className=\"flex origin-center items-baseline whitespace-nowrap font-semibold text-[56px] text-zinc-900 tabular-nums leading-none tracking-tight dark:text-zinc-50\"\n          ref={amountRef}\n          style={{ scale: fit, x: shakeX }}\n        >\n          <span\n            className={cn(\n              \"mr-0.5 transition-colors duration-200\",\n              empty\n                ? \"text-zinc-300 dark:text-zinc-700\"\n                : \"text-zinc-400 dark:text-zinc-500\"\n            )}\n          >\n            {currency}\n          </span>\n          <AnimatePresence initial={false} mode=\"popLayout\">\n            {empty && (\n              <motion.span\n                animate={{ opacity: 1 }}\n                className=\"text-zinc-300 dark:text-zinc-700\"\n                exit={{ opacity: 0, transition: { duration: 0.08 } }}\n                initial={{ opacity: 0 }}\n                key=\"placeholder\"\n                transition={{ duration: 0.15 }}\n              >\n                0\n              </motion.span>\n            )}\n            {glyphs.map((glyph) => (\n              <motion.span\n                animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n                className={cn(\n                  \"inline-block\",\n                  glyph.kind === \"ghost\" && \"text-zinc-300 dark:text-zinc-700\",\n                  glyph.kind === \"sep\" && \"text-zinc-400 dark:text-zinc-500\"\n                )}\n                exit={{\n                  opacity: 0,\n                  y: 18,\n                  filter: \"blur(2px)\",\n                  transition: { duration: 0.14, ease: EASE_OUT },\n                }}\n                initial={{ opacity: 0, y: -22, filter: \"blur(2px)\" }}\n                key={glyph.key}\n                layout=\"position\"\n                transition={{\n                  default: digitIn,\n                  layout: slide,\n                  filter: { duration: 0.16 },\n                }}\n              >\n                {glyph.char}\n              </motion.span>\n            ))}\n          </AnimatePresence>\n        </motion.div>\n      </div>\n\n      <div className=\"relative h-5 text-center text-xs\">\n        <AnimatePresence initial={false} mode=\"popLayout\">\n          <motion.p\n            animate={{ opacity: 1, y: 0 }}\n            className={cn(\n              capped\n                ? \"text-red-600 dark:text-red-400\"\n                : \"text-zinc-500 dark:text-zinc-400\"\n            )}\n            exit={{ opacity: 0, y: -6 }}\n            initial={{ opacity: 0, y: 6 }}\n            key={capped ? \"cap\" : \"balance\"}\n            transition={{ duration: 0.18, ease: EASE_OUT }}\n          >\n            {capped\n              ? `Up to ${money(max, currency)} per transfer`\n              : `Balance ${currency}${balance.toLocaleString(\"en-US\", { minimumFractionDigits: 2 })}`}\n          </motion.p>\n        </AnimatePresence>\n      </div>\n\n      <div className=\"mt-4 flex justify-center gap-2\">\n        {presets.map((amount) => (\n          <button\n            className=\"h-8 rounded-full border border-zinc-200 px-3 font-medium text-xs text-zinc-700 tabular-nums transition-colors duration-150 hover:bg-zinc-50 active:bg-zinc-100 dark:border-zinc-800 dark:text-zinc-300 dark:active:bg-zinc-800 dark:hover:bg-zinc-900\"\n            key={amount}\n            onClick={() => preset(amount)}\n            type=\"button\"\n          >\n            {money(amount, currency)}\n          </button>\n        ))}\n      </div>\n\n      <div className=\"mt-4 grid grid-cols-3 gap-1\">\n        {KEYS.map((key) => (\n          <button\n            aria-label={KEY_LABELS[key] ?? key}\n            className={cn(\n              \"flex h-14 items-center justify-center rounded-2xl font-medium text-2xl text-zinc-900 tabular-nums outline-none\",\n              \"transition-colors duration-100 ease-out hover:bg-zinc-50 active:bg-zinc-100 active:duration-0\",\n              \"focus-visible:ring-2 focus-visible:ring-zinc-400 dark:text-zinc-100 dark:active:bg-zinc-800 dark:hover:bg-zinc-900\"\n            )}\n            key={key}\n            onClick={() => press(key)}\n            type=\"button\"\n          >\n            {key === \"back\" ? (\n              <Delete\n                aria-hidden\n                className=\"size-6 text-zinc-500\"\n                strokeWidth={1.75}\n              />\n            ) : (\n              key\n            )}\n          </button>\n        ))}\n      </div>\n\n      <button\n        aria-disabled={empty}\n        className={cn(\n          \"relative mt-3 flex h-12 items-center justify-center gap-2 overflow-hidden rounded-2xl font-medium text-sm outline-none\",\n          \"transition-colors duration-200 ease-out focus-visible:ring-2 focus-visible:ring-zinc-400 focus-visible:ring-offset-2 dark:focus-visible:ring-offset-zinc-950\",\n          sendTone\n        )}\n        onClick={send}\n        type=\"button\"\n      >\n        <AnimatePresence initial={false} mode=\"popLayout\">\n          <motion.span\n            animate={{ opacity: 1, y: 0 }}\n            className=\"inline-flex items-center gap-2\"\n            exit={{ opacity: 0, y: -10 }}\n            initial={{ opacity: 0, y: 10 }}\n            key={sent === null ? \"send\" : \"sent\"}\n            transition={{ duration: 0.2, ease: EASE_OUT }}\n          >\n            {sent === null ? (\n              <>\n                <ArrowUp aria-hidden className=\"size-4\" />\n                {empty ? \"Enter an amount\" : `Send ${money(value, currency)}`}\n              </>\n            ) : (\n              <>\n                <Check aria-hidden className=\"size-4\" strokeWidth={2.5} />\n                Sent {money(sent, currency)}\n              </>\n            )}\n          </motion.span>\n        </AnimatePresence>\n      </button>\n    </div>\n  );\n}\n",
      "path": "/components/kokonutui/amount-pad.tsx",
      "target": "components/kokonutui/amount-pad.tsx"
    }
  ]
}