{
  "name": "cart-button",
  "type": "registry:component",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "files": [
    {
      "type": "registry:component",
      "content": "\"use client\";\n\n/**\n * @author: @dorianbaffier\n * @description: Cart Button\n * @version: 1.0.0\n * @date: 2026-10-22\n * @license: MIT\n * @website: https://kokonutui.com\n * @github: https://github.com/kokonut-labs/kokonutui\n */\n\nimport {\n  Cherry,\n  Croissant,\n  type LucideIcon,\n  Milk,\n  Minus,\n  Plus,\n  Trash2,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type MouseEvent,\n  type PointerEvent,\n  useCallback,\n  useEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n/** Pill widths: \"Add +\" at rest, \"− n +\" once something is in the cart. */\nconst WIDTH_CLOSED = 80;\nconst WIDTH_OPEN = 108;\n/** Press and hold + or −: wait, then repeat faster and faster. */\nconst HOLD_DELAY = 380;\nconst REPEAT_FIRST = 150;\nconst REPEAT_FASTEST = 55;\n/** How long \"Limit n per order\" stays up. */\nconst LIMIT_FOR = 1600;\n\nexport interface AddToCartButtonProps {\n  /** Controlled quantity. Leave out to let the button keep its own. */\n  quantity?: number;\n  defaultQuantity?: number;\n  /** Most of this item one order can hold. */\n  max?: number;\n  /** Item name, used in the button labels for screen readers. */\n  name?: string;\n  label?: string;\n  onQuantityChange?: (quantity: number) => void;\n  className?: string;\n}\n\n/**\n * \"Add +\" that opens into a \"− n +\" stepper in place. The + never moves, so a\n * second tap lands where the first did. At one, − turns into a bin; holding\n * + or − repeats, and a hold on − stops at one rather than emptying the line.\n */\nexport function AddToCartButton({\n  quantity,\n  defaultQuantity = 0,\n  max = 9,\n  name = \"item\",\n  label = \"Add\",\n  onQuantityChange,\n  className,\n}: AddToCartButtonProps) {\n  const [ownQuantity, setOwnQuantity] = useState(defaultQuantity);\n  const value = quantity ?? ownQuantity;\n  const [direction, setDirection] = useState(1);\n  const [limitHits, setLimitHits] = useState(0);\n  const [showLimit, setShowLimit] = useState(false);\n  const reduceMotion = Boolean(useReducedMotion());\n\n  const valueRef = useRef(value);\n  valueRef.current = value;\n  const holdRef = useRef<ReturnType<typeof setTimeout>>(undefined);\n  // A touch press waiting to turn out a tap, a hold, or the start of a scroll.\n  const touchRef = useRef<number | null>(null);\n  const limitRef = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const addRef = useRef<HTMLButtonElement>(null);\n  const plusRef = useRef<HTMLButtonElement>(null);\n  const focusNext = useRef<\"add\" | \"plus\" | null>(null);\n\n  const open = value > 0;\n\n  const commit = useCallback(\n    (next: number) => {\n      const clamped = Math.min(max, Math.max(0, next));\n      if (clamped === valueRef.current) {\n        return;\n      }\n      setDirection(clamped > valueRef.current ? 1 : -1);\n      valueRef.current = clamped;\n      if (quantity === undefined) {\n        setOwnQuantity(clamped);\n      }\n      onQuantityChange?.(clamped);\n    },\n    [max, quantity, onQuantityChange]\n  );\n\n  const hitLimit = useCallback(() => {\n    setLimitHits((hits) => hits + 1);\n    setShowLimit(true);\n    clearTimeout(limitRef.current);\n    limitRef.current = setTimeout(() => setShowLimit(false), LIMIT_FOR);\n  }, []);\n\n  /** One step; returns false when the step can't happen. */\n  const step = useCallback(\n    (delta: number) => {\n      if (delta > 0 && valueRef.current >= max) {\n        hitLimit();\n        return false;\n      }\n      if (delta < 0 && valueRef.current === 1) {\n        // The last one out: hand focus back to \"Add\" if it was on −.\n        focusNext.current = \"add\";\n      }\n      commit(valueRef.current + delta);\n      return true;\n    },\n    [commit, hitLimit, max]\n  );\n\n  const stopHold = useCallback(() => {\n    clearTimeout(holdRef.current);\n    touchRef.current = null;\n  }, []);\n\n  // A touch that was neither cancelled by a scroll nor held long enough to\n  // repeat counts as one tap when the finger lifts.\n  const endPress = () => {\n    const delta = touchRef.current;\n    stopHold();\n    if (delta !== null) {\n      step(delta);\n    }\n  };\n\n  const startHold = (delta: number) => (event: PointerEvent) => {\n    if (event.button !== 0) {\n      return;\n    }\n    event.currentTarget.setPointerCapture(event.pointerId);\n    stopHold();\n    let interval = REPEAT_FIRST;\n    const tick = () => {\n      // A hold on − stops at one: emptying the line takes its own tap.\n      if (delta < 0 && valueRef.current <= 1) {\n        return;\n      }\n      if (!step(delta)) {\n        return;\n      }\n      interval = Math.max(REPEAT_FASTEST, interval * 0.82);\n      holdRef.current = setTimeout(tick, interval);\n    };\n    // In a list, a finger landing on + may be starting a scroll, so touch\n    // waits for the lift (or the hold) instead of stepping on contact.\n    if (event.pointerType === \"touch\") {\n      touchRef.current = delta;\n      holdRef.current = setTimeout(() => {\n        touchRef.current = null;\n        if (step(delta)) {\n          holdRef.current = setTimeout(tick, REPEAT_FIRST);\n        }\n      }, HOLD_DELAY);\n      return;\n    }\n    if (!step(delta)) {\n      return;\n    }\n    holdRef.current = setTimeout(tick, HOLD_DELAY);\n  };\n\n  // Mouse presses step on pointerdown, touch on release; Enter and Space\n  // arrive as a click.\n  const keyStep = (delta: number) => (event: MouseEvent) => {\n    if (event.detail === 0) {\n      step(delta);\n    }\n  };\n\n  const add = () => {\n    focusNext.current = \"plus\";\n    setDirection(1);\n    commit(1);\n  };\n\n  useEffect(() => {\n    if (focusNext.current === \"plus\" && value > 0) {\n      plusRef.current?.focus();\n    }\n    if (focusNext.current === \"add\" && value === 0) {\n      // After the press settles, or the browser drops focus on the removed −.\n      requestAnimationFrame(() => addRef.current?.focus());\n    }\n    focusNext.current = null;\n    if (value === 0) {\n      clearTimeout(holdRef.current);\n    }\n  }, [value]);\n\n  useEffect(\n    () => () => {\n      clearTimeout(holdRef.current);\n      clearTimeout(limitRef.current);\n    },\n    []\n  );\n\n  const atMax = value >= max;\n  const fade = reduceMotion\n    ? { duration: 0 }\n    : { duration: 0.2, ease: EASE_OUT };\n\n  return (\n    <div className={cn(\"relative inline-flex\", className)}>\n      <AnimatePresence>\n        {showLimit && (\n          <motion.span\n            animate={{ opacity: 1, y: 0 }}\n            className=\"pointer-events-none absolute right-0 bottom-full mb-2 whitespace-nowrap rounded-md bg-zinc-900 px-2 py-1 font-medium text-[11px] text-white dark:bg-zinc-100 dark:text-zinc-900\"\n            exit={{ opacity: 0, y: 2 }}\n            initial={{ opacity: 0, y: 4 }}\n            role=\"status\"\n            transition={fade}\n          >\n            Limit {max} per order\n          </motion.span>\n        )}\n      </AnimatePresence>\n\n      <motion.div\n        animate={{ width: open ? WIDTH_OPEN : WIDTH_CLOSED }}\n        className={cn(\n          \"relative h-9 overflow-hidden rounded-full ring-1 transition-colors duration-200 motion-reduce:transition-none\",\n          open\n            ? \"bg-zinc-900 text-white ring-zinc-900 dark:bg-zinc-100 dark:text-zinc-900 dark:ring-zinc-100\"\n            : \"bg-white text-zinc-900 shadow-xs ring-zinc-200 hover:bg-zinc-50 dark:bg-zinc-900 dark:text-zinc-100 dark:ring-zinc-800 dark:hover:bg-zinc-800/70\"\n        )}\n        initial={false}\n        transition={{ ...fade, duration: reduceMotion ? 0 : 0.32 }}\n      >\n        <AnimatePresence initial={false}>\n          {!open && (\n            <motion.span\n              animate={{ opacity: 1, x: 0, filter: \"blur(0px)\" }}\n              aria-hidden\n              className=\"pointer-events-none absolute inset-y-0 left-3.5 z-10 flex items-center font-medium text-sm\"\n              exit={{ opacity: 0, x: -6, filter: \"blur(2px)\" }}\n              initial={{ opacity: 0, x: -6, filter: \"blur(2px)\" }}\n              key=\"label\"\n              transition={fade}\n            >\n              {label}\n            </motion.span>\n          )}\n        </AnimatePresence>\n\n        {open ? (\n          <fieldset className=\"contents\">\n            <legend className=\"sr-only\">{`Quantity of ${name}`}</legend>\n            <motion.button\n              animate={{ opacity: 1, x: 0 }}\n              aria-label={value === 1 ? `Remove ${name}` : `One less ${name}`}\n              className=\"absolute inset-y-0 left-0 flex w-9 items-center justify-center rounded-full outline-none transition-colors duration-150 hover:bg-white/10 focus-visible:ring-2 focus-visible:ring-white/50 focus-visible:ring-inset active:bg-white/20 dark:active:bg-black/10 dark:focus-visible:ring-black/30 dark:hover:bg-black/5\"\n              initial={{ opacity: 0, x: 16 }}\n              onClick={keyStep(-1)}\n              onLostPointerCapture={stopHold}\n              onPointerCancel={stopHold}\n              onPointerDown={startHold(-1)}\n              onPointerUp={endPress}\n              transition={fade}\n              type=\"button\"\n            >\n              <MinusGlyph bin={value === 1} reduceMotion={reduceMotion} />\n            </motion.button>\n\n            <motion.output\n              animate={{ opacity: 1, x: 0 }}\n              aria-live=\"polite\"\n              className=\"absolute inset-y-0 right-9 left-9 flex items-center justify-center overflow-hidden font-semibold text-sm tabular-nums\"\n              initial={{ opacity: 0, x: 12 }}\n              transition={fade}\n            >\n              <span className=\"sr-only\">{`${value} ${name} in cart`}</span>\n              <motion.span\n                animate={\n                  limitHits > 0 && !reduceMotion\n                    ? { x: [0, -3, 3, -2, 2, 0] }\n                    : undefined\n                }\n                aria-hidden\n                className=\"flex\"\n                key={limitHits}\n                transition={{ duration: 0.3, ease: \"easeOut\" }}\n              >\n                <RollingText\n                  direction={direction}\n                  reduceMotion={reduceMotion}\n                  text={String(value)}\n                />\n              </motion.span>\n            </motion.output>\n\n            <button\n              aria-disabled={atMax}\n              aria-label={`One more ${name}`}\n              className={cn(\n                \"absolute inset-y-0 right-0 flex w-9 items-center justify-center rounded-full outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-white/50 focus-visible:ring-inset dark:focus-visible:ring-black/30\",\n                atMax\n                  ? \"text-white/40 dark:text-zinc-900/35\"\n                  : \"hover:bg-white/10 active:bg-white/20 dark:active:bg-black/10 dark:hover:bg-black/5\"\n              )}\n              onClick={keyStep(1)}\n              onLostPointerCapture={stopHold}\n              onPointerCancel={stopHold}\n              onPointerDown={startHold(1)}\n              onPointerUp={endPress}\n              ref={plusRef}\n              type=\"button\"\n            >\n              <Plus aria-hidden className=\"size-4\" />\n            </button>\n          </fieldset>\n        ) : (\n          <button\n            aria-label={`${label} ${name} to cart`}\n            className=\"absolute inset-0 flex items-center justify-end rounded-full outline-none focus-visible:ring-2 focus-visible:ring-zinc-900/20 focus-visible:ring-inset dark:focus-visible:ring-white/25\"\n            onClick={add}\n            ref={addRef}\n            type=\"button\"\n          >\n            <span className=\"flex w-9 items-center justify-center\">\n              <Plus aria-hidden className=\"size-4\" />\n            </span>\n          </button>\n        )}\n      </motion.div>\n    </div>\n  );\n}\n\n/** − at two or more; a bin at one, since the next tap empties the line. */\nfunction MinusGlyph({\n  bin,\n  reduceMotion,\n}: {\n  bin: boolean;\n  reduceMotion: boolean;\n}) {\n  return (\n    <AnimatePresence initial={false} mode=\"popLayout\">\n      <motion.span\n        animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n        className=\"flex\"\n        exit={{ opacity: 0, scale: 0.6, filter: \"blur(2px)\" }}\n        initial={{ opacity: 0, scale: 0.6, filter: \"blur(2px)\" }}\n        key={bin ? \"bin\" : \"minus\"}\n        transition={reduceMotion ? { duration: 0 } : { duration: 0.16 }}\n      >\n        {bin ? (\n          <Trash2 aria-hidden className=\"size-3.5\" />\n        ) : (\n          <Minus aria-hidden className=\"size-4\" />\n        )}\n      </motion.span>\n    </AnimatePresence>\n  );\n}\n\n/** Each character rolls on its own, keyed by its place from the right. */\nfunction RollingText({\n  text,\n  direction,\n  reduceMotion,\n}: {\n  text: string;\n  direction: number;\n  reduceMotion: boolean;\n}) {\n  const places = text.split(\"\").map((char, index) => ({\n    char,\n    place: text.length - index,\n  }));\n  return (\n    <span className=\"inline-flex overflow-hidden tabular-nums\">\n      {places.map(({ char, place }) => (\n        <span className=\"relative inline-block\" key={place}>\n          <AnimatePresence custom={direction} initial={false} mode=\"popLayout\">\n            <motion.span\n              animate={{ y: 0, opacity: 1 }}\n              className=\"inline-block\"\n              custom={direction}\n              exit={reduceMotion ? { opacity: 0 } : \"out\"}\n              initial={reduceMotion ? { opacity: 0 } : \"in\"}\n              key={char}\n              transition={\n                reduceMotion\n                  ? { duration: 0 }\n                  : { duration: 0.24, ease: EASE_OUT }\n              }\n              variants={{\n                in: (dir: number) => ({ y: dir * 12, opacity: 0 }),\n                out: (dir: number) => ({ y: dir * -12, opacity: 0 }),\n              }}\n            >\n              {char}\n            </motion.span>\n          </AnimatePresence>\n        </span>\n      ))}\n    </span>\n  );\n}\n\nexport interface CartItem {\n  id: string;\n  name: string;\n  /** Pack size or weight, shown under the name. */\n  detail: string;\n  price: number;\n  icon: LucideIcon;\n  /** Tailwind classes for the icon tile. */\n  tint: string;\n  max?: number;\n}\n\nexport interface CartButtonProps {\n  items?: CartItem[];\n  /** Starting quantities, by item id. */\n  defaultQuantities?: Record<string, number>;\n  currency?: string;\n  onCheckout?: (quantities: Record<string, number>) => void;\n  className?: string;\n}\n\nconst DEFAULT_ITEMS: CartItem[] = [\n  {\n    id: \"oat-milk\",\n    name: \"Oat milk\",\n    detail: \"1 L · Barista\",\n    price: 3.2,\n    icon: Milk,\n    tint: \"bg-sky-50 text-sky-600 dark:bg-sky-500/10 dark:text-sky-300\",\n    max: 6,\n  },\n  {\n    id: \"croissant\",\n    name: \"Butter croissant\",\n    detail: \"Baked this morning\",\n    price: 2.6,\n    icon: Croissant,\n    tint: \"bg-orange-50 text-orange-600 dark:bg-orange-500/10 dark:text-orange-300\",\n    max: 8,\n  },\n  {\n    id: \"cherries\",\n    name: \"Cherries\",\n    detail: \"500 g punnet\",\n    price: 5.8,\n    icon: Cherry,\n    tint: \"bg-rose-50 text-rose-600 dark:bg-rose-500/10 dark:text-rose-300\",\n    max: 3,\n  },\n];\n\nconst money = (value: number, currency: string) =>\n  `${currency}${value.toFixed(2)}`;\n\nexport default function CartButton({\n  items = DEFAULT_ITEMS,\n  defaultQuantities = { croissant: 2 },\n  currency = \"$\",\n  onCheckout,\n  className,\n}: CartButtonProps) {\n  const [quantities, setQuantities] = useState(defaultQuantities);\n  const reduceMotion = Boolean(useReducedMotion());\n\n  const count = items.reduce(\n    (sum, item) => sum + (quantities[item.id] ?? 0),\n    0\n  );\n  const total = items.reduce(\n    (sum, item) => sum + (quantities[item.id] ?? 0) * item.price,\n    0\n  );\n\n  let summary = \"Your cart is empty\";\n  if (count > 0) {\n    summary = `Subtotal · ${count} ${count === 1 ? \"item\" : \"items\"}`;\n  }\n\n  const lastTotal = useRef(total);\n  const direction = total >= lastTotal.current ? 1 : -1;\n  useEffect(() => {\n    lastTotal.current = total;\n  }, [total]);\n\n  return (\n    <div\n      className={cn(\n        \"w-full max-w-sm rounded-2xl bg-white ring-1 ring-zinc-200 dark:bg-zinc-950 dark:ring-zinc-800\",\n        className\n      )}\n    >\n      <ul className=\"divide-y divide-zinc-100 px-4 dark:divide-zinc-900\">\n        {items.map((item) => {\n          const Icon = item.icon;\n          return (\n            <li className=\"flex items-center gap-3 py-3\" key={item.id}>\n              <span\n                className={cn(\n                  \"flex size-11 shrink-0 items-center justify-center rounded-xl\",\n                  item.tint\n                )}\n              >\n                <Icon aria-hidden className=\"size-5\" strokeWidth={1.75} />\n              </span>\n              <span className=\"min-w-0 flex-1\">\n                <span className=\"block truncate font-medium text-sm text-zinc-900 dark:text-zinc-100\">\n                  {item.name}\n                </span>\n                <span className=\"block truncate text-xs text-zinc-500 dark:text-zinc-400\">\n                  <span className=\"text-zinc-700 tabular-nums dark:text-zinc-300\">\n                    {money(item.price, currency)}\n                  </span>\n                  {` · ${item.detail}`}\n                </span>\n              </span>\n              <AddToCartButton\n                max={item.max}\n                name={item.name}\n                onQuantityChange={(next) =>\n                  setQuantities((current) => ({ ...current, [item.id]: next }))\n                }\n                quantity={quantities[item.id] ?? 0}\n              />\n            </li>\n          );\n        })}\n      </ul>\n\n      <div className=\"flex items-center justify-between gap-3 border-zinc-100 border-t px-4 py-3.5 dark:border-zinc-900\">\n        <div className=\"min-w-0\">\n          <p className=\"text-xs text-zinc-500 dark:text-zinc-400\">{summary}</p>\n          <p className=\"font-semibold text-base text-zinc-900 dark:text-zinc-100\">\n            <RollingText\n              direction={direction}\n              reduceMotion={reduceMotion}\n              text={money(total, currency)}\n            />\n          </p>\n        </div>\n        <button\n          className={cn(\n            \"h-9 rounded-full px-4 font-medium text-sm transition-colors duration-150\",\n            count === 0\n              ? \"cursor-not-allowed bg-zinc-100 text-zinc-400 dark:bg-zinc-900 dark:text-zinc-600\"\n              : \"bg-zinc-900 text-white hover:bg-zinc-800 active:bg-zinc-700 dark:bg-zinc-100 dark:text-zinc-900 dark:active:bg-zinc-300 dark:hover:bg-zinc-200\"\n          )}\n          disabled={count === 0}\n          onClick={() => onCheckout?.(quantities)}\n          type=\"button\"\n        >\n          Checkout\n        </button>\n      </div>\n    </div>\n  );\n}\n",
      "path": "/components/kokonutui/cart-button.tsx",
      "target": "components/kokonutui/cart-button.tsx"
    }
  ]
}