{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"spending-ring","type":"registry:component","title":"Spending ring","description":"Where the money went, and what is inside it: thick tiles with their amounts on them, and a category that blooms open into a ring of its own.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency","https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/spending-ring.tsx","type":"registry:component","content":"// Hairline UI · spending-ring · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { ChevronLeft, ChevronRight } from \"lucide-react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\nimport { createSpring, INTERACTION_FOCUS, useInteractionReducedMotion, type Spring } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * SPENDING RING: where the money went, and what's inside\n *\n *   tiles     each category is a thick tile of the ring with\n *             its amount written on it, so the ring reads on\n *             its own; no legend needed (legend adds a list)\n *   point     point at a tile (or tab to it) and it slides out\n *             while the others turn to the muted surface; the\n *             centre's label morphs to it and the total rolls\n *   open      click a category and its tile splits into its\n *             parts, then blooms open from where it sits,\n *             pushing the others out of the ring until it is\n *             the whole ring: Food becomes Groceries, Dining\n *             and Coffee. \"All\" (or Escape) folds it home.\n *   budget    the overspent end of a tile is hatched in red\n *\n * Every angle is computed from one spring, so an open can be\n * turned back mid-way and nothing jumps. Tiles are buttons:\n * Tab to point, Enter to open.\n * ───────────────────────────────────────────────────────── */\n\nexport interface SpendCategory {\n  id: string;\n  label: string;\n  value: number;\n  /** Over this, the overspent end of the tile is hatched in red and the centre says so. */\n  budget?: number;\n  /** Any CSS colour. Top-level slices without one take --chart-1 to --chart-5; parts take shades of their category. */\n  color?: string;\n  /** What the category is made of. A category with parts opens into its own ring. */\n  children?: SpendCategory[];\n}\n\nexport interface SpendingRingProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\"> {\n  data: SpendCategory[];\n  /** Above the total while nothing is open, e.g. \"Spent in October\". */\n  label?: string;\n  format?: Intl.NumberFormatOptions;\n  locales?: string | string[];\n  /** The open category's id; controlled. */\n  open?: string | null;\n  defaultOpen?: string | null;\n  onOpenChange?: (id: string | null) => void;\n  /** Ring diameter in px. */\n  size?: number;\n  thickness?: number;\n  /** Also list the categories under the ring. */\n  legend?: boolean;\n}\n\nconst GAP = 5; // px between tiles, measured along the middle of the ring\nconst CORNER = 7; // px, the tiles' corner radius\nconst LIFT = 5; // px a pointed tile moves out\nconst PALETTE = [\"var(--chart-1)\", \"var(--chart-2)\", \"var(--chart-3)\", \"var(--chart-4)\", \"var(--chart-5)\"];\n// Parts are lighter and darker steps of their category's colour, so they read as one family in light and dark.\nconst SHADES = [0, 0.12, -0.12, 0.2, -0.2, 0.06];\nconst clamp01 = (n: number) => (n < 0 ? 0 : n > 1 ? 1 : n);\nconst lerp = (a: number, b: number, t: number) => a + (b - a) * t;\nconst sum = (list: SpendCategory[]) => list.reduce((s, c) => s + Math.max(0, c.value), 0);\nconst RAD = Math.PI / 180;\n// Ink that reads on a colour: black on light tiles, white on dark ones (relative colour, so it follows the theme).\nconst inkOn = (fill: string) => `oklch(from ${fill} calc((0.7 - l) * 100) 0 0)`;\n\n/** A tile of the ring: an annular sector from a0 to a1 degrees (0 at the top, clockwise), corners rounded by ca / cb. */\nfunction sector(c: number, r0: number, r1: number, a0: number, a1: number, ca = CORNER, cb = CORNER) {\n  if (a1 - a0 <= 0.01) return \"\";\n  const pt = (r: number, deg: number) => {\n    const a = (deg - 90) * RAD;\n    return `${(c + r * Math.cos(a)).toFixed(2)} ${(c + r * Math.sin(a)).toFixed(2)}`;\n  };\n  // Corners can't be bigger than half the tile in either direction.\n  const fit = (k: number) => Math.max(0, Math.min(k, (r1 - r0) / 2, (((a1 - a0) * RAD) * r0) / 2 - 0.01));\n  const A = fit(ca), B = fit(cb);\n  const oA = A / r1 / RAD, iA = A / r0 / RAD, oB = B / r1 / RAD, iB = B / r0 / RAD;\n  const big = a1 - a0 > 180 ? 1 : 0;\n  return [\n    `M ${pt(r1, a0 + oA)}`,\n    `A ${r1} ${r1} 0 ${big} 1 ${pt(r1, a1 - oB)}`,\n    `Q ${pt(r1, a1)} ${pt(r1 - B, a1)}`,\n    `L ${pt(r0 + B, a1)}`,\n    `Q ${pt(r0, a1)} ${pt(r0, a1 - iB)}`,\n    `A ${r0} ${r0} 0 ${big} 0 ${pt(r0, a0 + iA)}`,\n    `Q ${pt(r0, a0)} ${pt(r0 + A, a0)}`,\n    `L ${pt(r1 - A, a0)}`,\n    `Q ${pt(r1, a0)} ${pt(r1, a0 + oA)}`,\n    \"Z\",\n  ].join(\" \");\n}\n\ntype Shown = { id: string; label: string; value: number; color: string; budget?: number; share: number; parent?: SpendCategory };\n\nexport function SpendingRing({\n  data,\n  label = \"Spent\",\n  format,\n  locales,\n  open: openProp,\n  defaultOpen = null,\n  onOpenChange,\n  size = 256,\n  thickness = 42,\n  legend = false,\n  className = \"\",\n  ...props\n}: SpendingRingProps) {\n  const reduced = useInteractionReducedMotion();\n  const hatch = React.useId().replace(/:/g, \"\");\n  const [openState, setOpenState] = React.useState<string | null>(defaultOpen);\n  const open = openProp !== undefined ? openProp : openState;\n  const [point, setPoint] = React.useState<string | null>(null);\n  // The category whose parts are drawn: the open one, and it stays while it folds back home.\n  const [unfolded, setUnfolded] = React.useState<string | null>(open);\n\n  const colour = (c: SpendCategory, i: number) => c.color ?? PALETTE[i % PALETTE.length];\n  const total = sum(data);\n  const home = data.find((c) => c.id === unfolded) ?? null;\n  const homeIndex = home ? data.indexOf(home) : -1;\n  const parts = home?.children ?? [];\n  const partColour = (c: SpendCategory, i: number) =>\n    c.color ?? `oklch(from ${colour(home!, homeIndex)} calc(l + ${SHADES[i % SHADES.length]}) c h)`;\n  const money = (n: number) => new Intl.NumberFormat(locales, format).format(n);\n\n  const setOpen = React.useCallback(\n    (id: string | null) => {\n      if (openProp === undefined) setOpenState(id);\n      onOpenChange?.(id);\n    },\n    [openProp, onOpenChange],\n  );\n\n  const svg = React.useRef<SVGSVGElement>(null);\n  const live = React.useRef({ data, total, unfolded, open, thickness, size });\n  React.useLayoutEffect(() => {\n    live.current = { data, total, unfolded, open, thickness, size };\n  });\n\n  // One spring opens and closes; each tile has its own for pointing (1 lifted, -1 stepped back).\n  const paintRef = React.useRef<() => void>(() => {});\n  // Made on first use (from an effect or an event, never while rendering), starting where the ring first rendered.\n  const springsRef = React.useRef<{ open: Spring; point: Map<string, Spring> } | null>(null);\n  const getSprings = React.useCallback(() => {\n    if (!springsRef.current) {\n      springsRef.current = {\n        open: createSpring(live.current.unfolded && live.current.open ? 1 : 0, { stiffness: 64, damping: 16 }, () => paintRef.current()),\n        point: new Map(),\n      };\n    }\n    return springsRef.current;\n  }, []);\n\n  const draw = React.useCallback(() => {\n    const root = svg.current;\n    if (!root) return;\n    const s = getSprings();\n    const { data: list, total: whole, unfolded: id, thickness: T, size: D } = live.current;\n    const p = clamp01(s.open.get());\n    const C = D / 2, R = C - T / 2 - LIFT - 3;\n    const gapDeg = GAP / R / RAD;\n    const spans = list.map((c) => (whole > 0 ? (360 * Math.max(0, c.value)) / whole : 0));\n    const k = list.findIndex((c) => c.id === id);\n    const emphasis = (key: string) => s.point.get(key)?.get() ?? 0;\n    type Paint = { opacity?: number; width?: number; budget?: { value: number; budget?: number }; ca?: number; cb?: number; text?: number };\n    const paint = (key: string, from: number, to: number, { opacity = 1, width = T, budget, ca = CORNER, cb = CORNER, text = 1 }: Paint = {}) => {\n      const tile = root.querySelector<SVGGElement>(`[data-tile=\"${CSS.escape(key)}\"]`);\n      if (!tile) return;\n      const shape = tile.querySelector<SVGPathElement>(\"[data-shape]\")!;\n      const e = emphasis(key);\n      const lift = Math.max(0, e), quiet = Math.max(0, -e);\n      const mid = ((from + to) / 2 - 90) * RAD;\n      tile.setAttribute(\"transform\", `translate(${(Math.cos(mid) * lift * LIFT).toFixed(2)} ${(Math.sin(mid) * lift * LIFT).toFixed(2)})`);\n      tile.style.opacity = opacity.toFixed(3);\n      const r0 = R - width / 2, r1 = R + width / 2;\n      shape.setAttribute(\"d\", sector(C, r0, r1, from, to, ca, cb));\n      // Stepping back is a change of colour, not of opacity: the others turn to the muted surface.\n      const base = tile.dataset.color!;\n      const fill = quiet > 0.002 ? `color-mix(in oklab, ${base} ${(100 - 84 * quiet).toFixed(1)}%, var(--muted))` : base;\n      shape.style.fill = fill;\n      // The amount sits on the tile if there's room along it.\n      const amount = tile.querySelector<SVGTextElement>(\"[data-amount]\");\n      if (amount) {\n        const room = (to - from) * RAD * R;\n        const fits = room >= Number(amount.dataset.w) + 18 && width > 30;\n        amount.setAttribute(\"x\", (C + R * Math.cos(mid)).toFixed(2));\n        amount.setAttribute(\"y\", (C + R * Math.sin(mid)).toFixed(2));\n        amount.style.fill = inkOn(fill);\n        amount.style.opacity = fits ? (text * (1 - 0.35 * quiet)).toFixed(3) : \"0\";\n      }\n      // Over budget: the overspent end of the tile is hatched in red.\n      const over = tile.querySelector<SVGPathElement>(\"[data-over]\");\n      if (over) {\n        const share = budget?.budget !== undefined && budget.value > budget.budget ? (budget.value - budget.budget) / budget.value : 0;\n        const start = to - (to - from) * share;\n        over.setAttribute(\"d\", share > 0 ? sector(C, r0, r1, start, to, 3, cb) : \"\");\n        over.style.opacity = (1 - quiet * 0.7).toFixed(3);\n      }\n    };\n\n    if (k < 0) {\n      let at = 0;\n      list.forEach((c, i) => {\n        paint(c.id, at + gapDeg / 2, at + spans[i] - gapDeg / 2, { budget: c });\n        at += spans[i];\n      });\n      return;\n    }\n    // Opening: the tile blooms from its middle to the whole ring and the others are pushed out of what's left.\n    const starts: number[] = [];\n    spans.reduce((at, span, i) => ((starts[i] = at), at + span), 0);\n    const mid = starts[k] + spans[k] / 2;\n    const S = lerp(spans[k], 360, p);\n    const from = mid - S / 2;\n    const rest = 360 - S, before = 360 - spans[k];\n    const squeeze = before > 0 ? rest / before : 0;\n    let at = from + S;\n    for (let step = 1; step < list.length; step++) {\n      const i = (k + step) % list.length;\n      const len = spans[i] * squeeze;\n      const g = gapDeg * (1 - p);\n      paint(list[i].id, at + g / 2, at + len - g / 2, { opacity: clamp01(1 - p * 1.5), width: T * (1 - p * 0.5), budget: list[i], text: clamp01(1 - p * 3) });\n      at += len;\n    }\n    // The parts stand in for the tile from the first frame: in its colour, touching, so they look like it. As it\n    // opens, gaps and corners appear between them and each takes its own shade.\n    const children = list[k].children ?? [];\n    const parent = list[k].color ?? PALETTE[k % PALETTE.length];\n    const split = clamp01(p / 0.3);\n    paint(list[k].id, from + gapDeg / 2, from + S - gapDeg / 2, { opacity: 0, budget: list[k] });\n    const childTotal = sum(children);\n    const g = gapDeg * split;\n    let c0 = from;\n    children.forEach((child, j) => {\n      const len = childTotal > 0 ? (S * Math.max(0, child.value)) / childTotal : 0;\n      const first = j === 0, last = j === children.length - 1;\n      const tile = root.querySelector<SVGGElement>(`[data-tile=\"${CSS.escape(`${list[k].id}/${child.id}`)}\"]`);\n      const shade = child.color ?? `oklch(from ${parent} calc(l + ${SHADES[j % SHADES.length]}) c h)`;\n      if (tile) tile.dataset.color = split >= 1 ? shade : `color-mix(in oklab, ${shade} ${(split * 100).toFixed(1)}%, ${parent})`;\n      paint(`${list[k].id}/${child.id}`, c0 + (first ? gapDeg : g) / 2, c0 + len - (last ? gapDeg : g) / 2, {\n        budget: child,\n        ca: first ? CORNER : CORNER * split,\n        cb: last ? CORNER : CORNER * split,\n        text: clamp01((p - 0.45) / 0.4),\n      });\n      c0 += len;\n    });\n  }, [getSprings]);\n\n  // Open and close: unfold the new category first, then run the spring; once folded home, drop its parts.\n  React.useEffect(() => {\n    const s = getSprings();\n    if (open) {\n      if (unfolded !== open) {\n        if (s.open.get() > 0.02 && unfolded) {\n          s.open.set(0); // fold the other one home first; the effect runs again when it has\n          return;\n        }\n        const frame = requestAnimationFrame(() => setUnfolded(open));\n        return () => cancelAnimationFrame(frame);\n      }\n      if (reduced) s.open.jump(1);\n      else s.open.set(1);\n    } else if (reduced) {\n      s.open.jump(0);\n    } else {\n      s.open.set(0);\n    }\n  }, [open, unfolded, reduced, getSprings]);\n\n  // Watch the fold: when it's home, forget the parts (or move on to the next one asked for).\n  React.useEffect(() => {\n    if (!unfolded || open === unfolded) return;\n    const s = getSprings();\n    let frame = 0;\n    const wait = () => {\n      if (s.open.get() <= 0.002 && Math.abs(s.open.getVelocity()) < 0.01) setUnfolded(open && open !== unfolded ? open : null);\n      else frame = requestAnimationFrame(wait);\n    };\n    frame = requestAnimationFrame(wait);\n    return () => cancelAnimationFrame(frame);\n  }, [open, unfolded, getSprings]);\n\n  // Pointing lifts one tile and steps the rest back.\n  React.useEffect(() => {\n    const s = getSprings();\n    const keys = open && home ? parts.map((c) => `${home.id}/${c.id}`) : data.map((c) => c.id);\n    const all = new Set([...data.map((c) => c.id), ...(home ? parts.map((c) => `${home.id}/${c.id}`) : [])]);\n    all.forEach((key) => {\n      if (!s.point.has(key)) s.point.set(key, createSpring(0, { stiffness: 380, damping: 34 }, () => paintRef.current()));\n      const target = !point || !keys.includes(key) ? 0 : key === point ? 1 : -1;\n      const spring = s.point.get(key)!;\n      if (reduced) spring.jump(target);\n      else spring.set(target);\n    });\n  }, [point, open, home, parts, data, reduced, getSprings]);\n\n  React.useLayoutEffect(() => {\n    paintRef.current = draw;\n    draw();\n  });\n\n  React.useEffect(() => {\n    if (!open) return;\n    const onKey = (event: KeyboardEvent) => {\n      if (event.key === \"Escape\") setOpen(null);\n    };\n    window.addEventListener(\"keydown\", onKey);\n    return () => window.removeEventListener(\"keydown\", onKey);\n  }, [open, setOpen]);\n\n  // What the centre (and the list, if shown) say.\n  const opened = open ? data.find((c) => c.id === open) ?? null : null;\n  const rows: Shown[] = opened && opened.id === unfolded\n    ? parts.map((c, i) => ({ id: `${opened.id}/${c.id}`, label: c.label, value: c.value, budget: c.budget, color: partColour(c, i), share: sum(parts) ? c.value / sum(parts) : 0, parent: opened }))\n    : data.map((c, i) => ({ id: c.id, label: c.label, value: c.value, budget: c.budget, color: colour(c, i), share: total ? c.value / total : 0 }));\n  const pointed = rows.find((r) => r.id === point) ?? null;\n  const centre = pointed\n    ? { label: pointed.label, value: pointed.value, note: noteFor(pointed.value, pointed.budget, `${Math.round(pointed.share * 100)}% of ${pointed.parent ? pointed.parent.label : \"spending\"}`) }\n    : opened\n      ? { label: opened.label, value: opened.value, note: noteFor(opened.value, opened.budget, `${Math.round((total ? opened.value / total : 0) * 100)}% of spending`) }\n      : { label, value: total, note: { text: \"\", over: false } };\n\n  function noteFor(value: number, budget: number | undefined, fallback: string) {\n    if (budget === undefined) return { text: fallback, over: false };\n    return value > budget ? { text: `${money(value - budget)} over budget`, over: true } : { text: `of ${money(budget)} budget`, over: false };\n  }\n\n  const opens = (row: Shown) => !row.parent && !!data.find((c) => c.id === row.id)?.children?.length;\n  const pick = (row: Shown) => {\n    if (!opens(row)) return;\n    setPoint(null);\n    setOpen(row.id);\n  };\n\n  // Every tile that may be drawn: the categories, and the open one's parts.\n  const tiles = [\n    ...data.map((c, i) => ({ key: c.id, color: colour(c, i), value: c.value, over: c.budget !== undefined })),\n    ...(home ? parts.map((c, i) => ({ key: `${home.id}/${c.id}`, color: partColour(c, i), value: c.value, over: c.budget !== undefined })) : []),\n  ];\n  const live_ = new Set(rows.map((r) => r.id));\n  const amountText = (n: number) => money(n);\n\n  return (\n    <div className={`flex w-full flex-col items-center gap-5 ${className}`} {...props}>\n      <div className=\"relative shrink-0\" style={{ width: size, height: size }}>\n        <svg\n          ref={svg}\n          width={size}\n          height={size}\n          viewBox={`0 0 ${size} ${size}`}\n          className=\"block overflow-visible\"\n          role=\"group\"\n          aria-label={opened ? `${opened.label}, by part` : label}\n          onPointerLeave={() => setPoint(null)}\n        >\n          <defs>\n            <pattern id={hatch} width=\"6\" height=\"6\" patternUnits=\"userSpaceOnUse\" patternTransform=\"rotate(45)\">\n              <rect width=\"6\" height=\"6\" className=\"fill-red-500 dark:fill-red-400\" />\n              <rect width=\"2.4\" height=\"6\" fill=\"rgb(255 255 255 / 0.55)\" />\n            </pattern>\n          </defs>\n          {tiles.map(({ key, color, value, over }) => {\n            const row = rows.find((r) => r.id === key);\n            const active = live_.has(key);\n            const text = amountText(value);\n            return (\n              <g\n                key={key}\n                data-tile={key}\n                data-color={color}\n                role={active ? \"button\" : undefined}\n                tabIndex={active ? 0 : -1}\n                aria-hidden={!active}\n                aria-label={row ? `${row.label}, ${money(row.value)}, ${Math.round(row.share * 100)}%${opens(row) ? \", opens its parts\" : \"\"}` : undefined}\n                className={`outline-none ${row && opens(row) ? \"cursor-pointer\" : \"cursor-default\"} [&:focus-visible>path[data-shape]]:stroke-ring [&:focus-visible>path[data-shape]]:[stroke-width:2.5]`}\n                onPointerMove={(event) => {\n                  // Only a hand that moves points: tiles sliding under a resting cursor while it opens don't count.\n                  const p = getSprings().open.get();\n                  if (event.pointerType === \"mouse\" && active && (p < 0.02 || p > 0.98) && point !== key) setPoint(key);\n                }}\n                onClick={() => row && pick(row)}\n                onKeyDown={(event) => {\n                  if ((event.key === \"Enter\" || event.key === \" \") && row) {\n                    event.preventDefault();\n                    pick(row);\n                  }\n                }}\n                onFocus={() => active && setPoint(key)}\n                onBlur={() => setPoint(null)}\n              >\n                <path data-shape=\"\" style={{ fill: color }} />\n                {over ? <path data-over=\"\" fill={`url(#${hatch})`} className=\"pointer-events-none\" /> : null}\n                <text\n                  data-amount=\"\"\n                  data-w={text.length * 7.1}\n                  textAnchor=\"middle\"\n                  dominantBaseline=\"central\"\n                  className=\"pointer-events-none select-none text-[12.5px] font-semibold tracking-[-0.01em] tabular-nums\"\n                  aria-hidden=\"true\"\n                >\n                  {text}\n                </text>\n              </g>\n            );\n          })}\n        </svg>\n        <div className=\"pointer-events-none absolute inset-0 flex flex-col items-center justify-center text-center\">\n          <button\n            type=\"button\"\n            onClick={() => setOpen(null)}\n            tabIndex={opened ? 0 : -1}\n            aria-hidden={!opened}\n            className={`pointer-events-auto mb-1 flex h-6 cursor-pointer items-center gap-0.5 rounded-full pr-2 pl-1 text-[12px] font-medium text-muted-foreground transition-[opacity,translate,background-color] duration-300 hover:bg-muted hover:text-foreground motion-reduce:transition-none ${INTERACTION_FOCUS} ${opened ? \"opacity-100\" : \"pointer-events-none -translate-y-1 opacity-0\"}`}\n          >\n            <ChevronLeft className=\"size-3.5\" aria-hidden=\"true\" />\n            All\n          </button>\n          <TextMorph className=\"text-[12.5px] text-muted-foreground\">{centre.label}</TextMorph>\n          <span className=\"mt-1 text-[34px] leading-none font-semibold tracking-[-0.04em] tabular-nums text-foreground\">\n            <NumberRoll value={centre.value} format={format} locales={locales} duration={700} />\n          </span>\n          <span className=\"mt-2 h-4\">\n            <TextMorph className={`text-[12px] ${centre.note.over ? \"text-red-600 dark:text-red-400\" : \"text-muted-foreground\"}`}>{centre.note.text}</TextMorph>\n          </span>\n        </div>\n      </div>\n\n      {legend ? (\n        <ul className=\"w-full max-w-[320px]\" aria-label={opened ? `${opened.label}, by part` : \"Spending by category\"}>\n          {rows.map((row, i) => {\n            const over = row.budget !== undefined && row.value > row.budget;\n            return (\n              <li key={row.id} className=\"motion-safe:animate-[ui-fade-up_360ms_cubic-bezier(0.16,1,0.3,1)_both]\" style={{ animationDelay: `${i * 35}ms` }}>\n                <button\n                  type=\"button\"\n                  onClick={() => pick(row)}\n                  onPointerEnter={(event) => event.pointerType === \"mouse\" && setPoint(row.id)}\n                  onPointerLeave={() => setPoint(null)}\n                  onFocus={() => setPoint(row.id)}\n                  onBlur={() => setPoint(null)}\n                  aria-disabled={!opens(row)}\n                  className={`flex h-9 w-full items-center gap-2.5 rounded-lg px-2 text-left text-[13px] transition-colors duration-200 hover:bg-muted/70 ${opens(row) ? \"cursor-pointer\" : \"cursor-default\"} ${INTERACTION_FOCUS}`}\n                >\n                  <span className=\"size-2.5 shrink-0 rounded-full\" style={{ background: row.color }} aria-hidden=\"true\" />\n                  <span className=\"min-w-0 flex-1 truncate text-foreground\">{row.label}</span>\n                  {over ? <span className=\"text-[11.5px] text-red-600 tabular-nums dark:text-red-400\">+{money(row.value - row.budget!)}</span> : null}\n                  <span className=\"w-9 text-right text-[11.5px] text-muted-foreground tabular-nums\">{Math.round(row.share * 100)}%</span>\n                  <span className=\"w-[72px] text-right font-medium text-foreground tabular-nums\">{money(row.value)}</span>\n                  <ChevronRight className={`size-3.5 shrink-0 text-muted-foreground ${opens(row) ? \"\" : \"invisible\"}`} aria-hidden=\"true\" />\n                </button>\n              </li>\n            );\n          })}\n        </ul>\n      ) : null}\n    </div>\n  );\n}\n\nexport default SpendingRing;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · spending-ring · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{"@keyframes ui-fade-up":{"from":{"opacity":"0","transform":"translateY(4px)"},"to":{"opacity":"1","transform":"none"}}},"docs":"Docs and live preview: https://hairlineui.com/ui/spending-ring. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}