{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"streak-chain","type":"registry:component","title":"Streak chain","description":"“Don’t break the chain”, drawn big enough to care: today’s ring hangs open until you complete it, then it closes, fills with colour and the chain grows a ring.","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/streak-chain.tsx","type":"registry:component","content":"// Hairline UI · streak-chain · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { Snowflake } from \"lucide-react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\nimport { createSpring, type Spring } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * STREAK CHAIN: \"don't break the chain\", drawn big enough to care\n *\n *   chain     every day is a ring, joined to the next: done days in\n *             your colours, a frozen day pale with a frost mark that\n *             still holds, a missed day broken off and fallen\n *   today     today's ring hangs open off the end of the chain and\n *             sways a little, with the time left to save it under\n *   forge     complete today and the ring swings up and closes, your\n *             colour pours round it from the joint while sparks\n *             flick off, then the whole chain moves along one ring and\n *             tomorrow's empty ring slides in at the end: the chain\n *             visibly grew\n *   ahead     under the chain, the next milestone and how many days\n *             to it; at a milestone a glint runs the length of it\n *\n * The days are yours: pass the history, whether today is done, when\n * today ends and the freezes left. onCompleteToday saves it; if it\n * throws, the ring swings open again.\n * ───────────────────────────────────────────────────────── */\n\nexport type StreakDay = \"done\" | \"missed\" | \"frozen\";\n\nexport interface StreakChainProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"title\"> {\n  /** Days before today, oldest first. */\n  history: StreakDay[];\n  /** Whether today is done, controlled; or leave it to the chain with defaultToday. */\n  today?: boolean;\n  defaultToday?: boolean;\n  /** Save today. Throw or reject to undo it on screen. */\n  onCompleteToday?: () => Promise<unknown> | void;\n  /** When today ends, for \"5h 12m left\". */\n  deadline?: Date | string | number;\n  /** Streak freezes still available. */\n  freezes?: number;\n  /** The longest streak so far. */\n  best?: number;\n  /** Milestones to count toward. */\n  milestones?: number[];\n  /** Today's date, YYYY-MM-DD, for the day letters under the rings. */\n  date?: string;\n  title?: string;\n  /** The button's words. */\n  actionLabel?: string;\n  /** The chain's two colours: any CSS colours. */\n  colors?: [string, string];\n  locale?: string;\n}\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst FOCUS = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background\";\nconst DEFAULT_COLORS: [string, string] = [\"var(--chart-5, var(--primary))\", \"var(--chart-2, var(--primary))\"];\nconst MILESTONES = [7, 14, 30, 60, 100, 365];\nconst OPEN_ANGLE = 26;\nconst OPEN_GAP = 30;\nconst MS = 86_400_000;\nconst TICKS = \"repeating-linear-gradient(to right, #000 0 2px, transparent 2px 4px)\";\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nconst useReducedMotion = () =>\n  React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\n\nconst mix = (color: string, amount: number, into = \"transparent\") => `color-mix(in oklab, ${color} ${amount}%, ${into})`;\n\n/** A stadium traced clockwise from its rightmost point, so a gap there opens the ring away from the chain. */\nfunction stadium(cx: number, cy: number, w: number, h: number) {\n  const r = h / 2;\n  const x1 = cx - w / 2;\n  const x2 = cx + w / 2;\n  return `M ${x2} ${cy} A ${r} ${r} 0 0 1 ${x2 - r} ${cy + r} L ${x1 + r} ${cy + r} A ${r} ${r} 0 0 1 ${x1} ${cy} A ${r} ${r} 0 0 1 ${x1 + r} ${cy - r} L ${x2 - r} ${cy - r} A ${r} ${r} 0 0 1 ${x2} ${cy}`;\n}\n\nexport function StreakChain({\n  history,\n  today: todayProp,\n  defaultToday = false,\n  onCompleteToday,\n  deadline,\n  freezes,\n  best,\n  milestones = MILESTONES,\n  date,\n  title = \"Daily streak\",\n  actionLabel = \"Complete today\",\n  colors = DEFAULT_COLORS,\n  locale = \"en-US\",\n  className = \"\",\n  ...props\n}: StreakChainProps) {\n  const reduced = useReducedMotion();\n  const [own, setOwn] = React.useState(defaultToday);\n  const [optimistic, setOptimistic] = React.useState<boolean | null>(null);\n  const done = optimistic ?? todayProp ?? own;\n  // The chain grows a ring once the forge has played; already done on arrival, it has grown.\n  const [grown, setGrown] = React.useState(done);\n  if (!done && grown) setGrown(false);\n  const [width, setWidth] = React.useState(0);\n  const [now, setNow] = React.useState<number | null>(null);\n  const [said, setSaid] = React.useState(\"\");\n  const [colorA, colorB] = colors;\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const chainRef = React.useRef<SVGGElement>(null);\n  const todayRef = React.useRef<SVGGElement>(null);\n  const todayPath = React.useRef<SVGPathElement>(null);\n  const pourPath = React.useRef<SVGPathElement>(null);\n  const sparkRef = React.useRef<SVGGElement>(null);\n  const ringRefs = React.useRef<(SVGGElement | null)[]>([]);\n  const springs = React.useRef<{ angle: Spring | null; gap: Spring | null }>({ angle: null, gap: null });\n  const geo = React.useRef({ pivotX: 0, pivotY: 0, sway: 0, frame: 0, onScreen: false });\n  const timer = React.useRef(0);\n\n  // Done days back from today; a frozen day keeps the streak alive without adding to it.\n  let streak = done ? 1 : 0;\n  for (let i = history.length - 1; i >= 0; i--) {\n    if (history[i] === \"missed\") break;\n    if (history[i] === \"done\") streak++;\n  }\n  const next = milestones.find((m) => m > streak) ?? null;\n  const prevMilestone = [...milestones].reverse().find((m) => m <= streak) ?? 0;\n\n  React.useLayoutEffect(() => {\n    const box = boxRef.current;\n    if (!box) return;\n    const measure = () => setWidth((w) => (w === box.offsetWidth ? w : box.offsetWidth));\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(box);\n    return () => observer.disconnect();\n  }, []);\n\n  // The clock for \"left today\": a minute is plenty.\n  React.useEffect(() => {\n    const tick = () => setNow(Date.now());\n    const first = window.setTimeout(tick, 0);\n    const every = window.setInterval(tick, 30_000);\n    return () => {\n      window.clearTimeout(first);\n      window.clearInterval(every);\n    };\n  }, []);\n\n  React.useEffect(() => () => window.clearTimeout(timer.current), []);\n\n  // As many rings as fit at a size you can see, today (and tomorrow, once grown) at the end.\n  const slots = Math.max(5, Math.min(9, Math.round((width || 320) / 46)));\n  type Slot = StreakDay | \"today\" | \"tomorrow\";\n  const days: Slot[] = grown ? [...history.slice(-(slots - 2)), \"today\", \"tomorrow\"] : [...history.slice(-(slots - 1)), \"today\"];\n  const n = days.length;\n  const P = (width || 320) / n;\n  const ringW = P * 0.74;\n  const ringH = Math.min(P * 0.52, 30);\n  const stroke = Math.max(3, Math.min(5, P * 0.1));\n  const H = Math.ceil(ringH * 2.4 + 8);\n  const cy = ringH * 0.9 + 4;\n  const todayIndex = days.indexOf(\"today\");\n  const colorAt = (i: number) => mix(colorA, Math.round(100 - (n > 1 ? i / (n - 1) : 1) * 100), colorB);\n  const cxOf = (i: number) => (i + 0.5) * P;\n\n  // Today's ring: an angle and a gap on springs, plus a small sway while it waits, written straight to the SVG.\n  const paintToday = React.useCallback(() => {\n    const g = todayRef.current;\n    const p = todayPath.current;\n    const { angle, gap } = springs.current;\n    if (!g || !p || !angle || !gap) return;\n    const a = angle.get() + geo.current.sway;\n    const open = Math.max(0, gap.get());\n    g.setAttribute(\"transform\", `rotate(${a} ${geo.current.pivotX} ${geo.current.pivotY})`);\n    p.style.strokeDasharray = `${100 - open} ${open}`;\n    p.style.strokeDashoffset = `${-open / 2}`;\n  }, []);\n\n  const startDone = React.useRef(done);\n  React.useLayoutEffect(() => {\n    const s = springs.current;\n    s.angle = createSpring(startDone.current ? 0 : OPEN_ANGLE, { stiffness: 300, damping: 12 }, paintToday, 0.02);\n    s.gap = createSpring(startDone.current ? 0 : OPEN_GAP, { stiffness: 340, damping: 26 }, paintToday, 0.02);\n    paintToday();\n    return () => {\n      s.angle?.stop();\n      s.gap?.stop();\n      s.angle = s.gap = null;\n    };\n  }, [paintToday]);\n\n  React.useLayoutEffect(() => {\n    // Today's ring hangs from where it hooks into yesterday's: its left end.\n    geo.current.pivotX = cxOf(todayIndex) - ringW / 2 + stroke;\n    geo.current.pivotY = cy;\n    paintToday();\n  });\n\n  React.useEffect(() => {\n    const { angle, gap } = springs.current;\n    if (!angle || !gap) return;\n    if (reduced) {\n      angle.jump(done ? 0 : OPEN_ANGLE);\n      gap.jump(done ? 0 : OPEN_GAP);\n    } else {\n      angle.set(done ? 0 : OPEN_ANGLE);\n      gap.set(done ? 0 : OPEN_GAP);\n    }\n  }, [done, reduced]);\n\n  // While today waits, the open ring sways a little, on screen only.\n  React.useEffect(() => {\n    const g = geo.current;\n    const el = rootRef.current;\n    if (done || reduced || !el) {\n      g.sway = 0;\n      paintToday();\n      return;\n    }\n    const loop = (t: number) => {\n      g.sway = Math.sin(t / 620) * 3.2;\n      paintToday();\n      g.frame = g.onScreen ? requestAnimationFrame(loop) : 0;\n    };\n    const observer = new IntersectionObserver(([entry]) => {\n      g.onScreen = entry.isIntersecting;\n      if (g.onScreen && !g.frame) g.frame = requestAnimationFrame(loop);\n    });\n    observer.observe(el);\n    return () => {\n      observer.disconnect();\n      cancelAnimationFrame(g.frame);\n      g.frame = 0;\n      g.sway = 0;\n    };\n  }, [done, reduced, paintToday]);\n\n  // The chain grows: everything moves along one ring as tomorrow's slides in.\n  const grewFrom = React.useRef(grown);\n  React.useLayoutEffect(() => {\n    if (grewFrom.current === grown) return;\n    grewFrom.current = grown;\n    if (!grown || reduced) return;\n    chainRef.current?.animate([{ transform: `translateX(${P}px)` }, { transform: \"translateX(0)\" }], { duration: 680, easing: \"cubic-bezier(0.65,0,0.35,1)\" });\n    ringRefs.current[n - 1]?.animate(\n      [\n        { opacity: 0, transform: \"translateX(18px)\" },\n        { opacity: 1, transform: \"none\" },\n      ],\n      { duration: 620, delay: 120, easing: EASE, fill: \"backwards\" },\n    );\n    if (streak === prevMilestone && prevMilestone > 0)\n      ringRefs.current.forEach((el, i) =>\n        el?.animate([{ filter: \"brightness(1)\" }, { filter: \"brightness(1.5)\" }, { filter: \"brightness(1)\" }], { duration: 520, delay: 700 + i * 50, easing: \"ease-in-out\" }),\n      );\n  }, [grown, reduced, P, n, streak, prevMilestone]);\n\n  const forge = () => {\n    if (reduced) return;\n    // The snap: a kick past closed, colour poured round from the joint, sparks off it.\n    springs.current.angle?.push(-150);\n    pourPath.current?.animate([{ strokeDashoffset: 100 }, { strokeDashoffset: 0 }], { duration: 560, delay: 120, easing: \"cubic-bezier(0.4,0,0.2,1)\", fill: \"backwards\" });\n    sparkRef.current?.querySelectorAll(\"line\").forEach((l, i) =>\n      l.animate(\n        [\n          { opacity: 0, transform: \"scale(0.3)\" },\n          { opacity: 1, transform: \"scale(1)\", offset: 0.3 },\n          { opacity: 0, transform: \"scale(1.7)\" },\n        ],\n        { duration: 520, delay: 140 + i * 22, easing: EASE, fill: \"backwards\" },\n      ),\n    );\n  };\n\n  const complete = () => {\n    if (done) return;\n    setOptimistic(true);\n    forge();\n    setSaid(`Today is done. ${streak + 1}-day streak.`);\n    window.clearTimeout(timer.current);\n    timer.current = window.setTimeout(() => setGrown(true), reduced ? 0 : 760);\n    const settle = () => {\n      if (todayProp === undefined) setOwn(true);\n      setOptimistic(null);\n    };\n    const refuse = () => {\n      window.clearTimeout(timer.current);\n      setOptimistic(false);\n      setGrown(false);\n      window.setTimeout(() => setOptimistic(null), 0);\n      setSaid(\"Couldn’t save today. Try again.\");\n    };\n    let result: unknown;\n    try {\n      result = onCompleteToday?.();\n    } catch {\n      refuse();\n      return;\n    }\n    if (result && typeof (result as Promise<unknown>).then === \"function\") (result as Promise<unknown>).then(settle, refuse);\n    else settle();\n  };\n\n  const letter = (i: number) => {\n    if (!date) return \"\";\n    const [y, m, d] = date.split(\"-\").map(Number);\n    const day = Date.UTC(y, m - 1, d) + (i - todayIndex) * MS;\n    return new Date(day).toLocaleDateString(locale, { weekday: \"narrow\", timeZone: \"UTC\" });\n  };\n\n  const end = deadline !== undefined ? new Date(deadline).getTime() : null;\n  const left = end !== null && now !== null ? Math.max(0, end - now) : null;\n  const leftText = left === null ? \"\" : left < 3_600_000 ? `${Math.max(1, Math.round(left / 60_000))}m left today` : `${Math.floor(left / 3_600_000)}h ${Math.round((left % 3_600_000) / 60_000)}m left today`;\n  const urgent = left !== null && left < 3 * 3_600_000 && !done;\n  const toNext = next ? next - streak : 0;\n  const nextFill = next ? (streak - prevMilestone) / (next - prevMilestone) : 1;\n  const ink = mix(\"var(--foreground)\", 26, \"var(--border)\");\n\n  return (\n    <div ref={rootRef} className={`w-full rounded-[22px] bg-background shadow-[0_0_0_1px_var(--border)] ${className}`} {...props}>\n      <div aria-hidden=\"true\" data-natural-width className=\"grid h-0\" style={{ gridTemplateColumns: \"minmax(0, 400px)\" }} />\n      <div className=\"p-4 sm:p-5\">\n        <div className=\"flex items-start justify-between gap-3\">\n          <div>\n            <p className=\"text-[12.5px] text-muted-foreground\">{title}</p>\n            <p className=\"mt-1 flex items-baseline gap-1.5 text-foreground\">\n              <span className=\"text-[40px] font-medium leading-none tracking-[-0.045em] tabular-nums\">\n                <NumberRoll value={streak} duration={900} />\n              </span>\n              <span className=\"text-[14px] text-muted-foreground\">{streak === 1 ? \"day\" : \"days\"}</span>\n            </p>\n          </div>\n          <div className=\"flex flex-col items-end gap-1 pt-0.5 text-[12px] text-muted-foreground tabular-nums\">\n            {best !== undefined && (\n              <span>\n                Best <span className=\"font-medium text-foreground\">{Math.max(best, streak)}</span>\n              </span>\n            )}\n            {freezes !== undefined && (\n              <span className=\"inline-flex items-center gap-1\" title=\"Streak freezes\">\n                <Snowflake aria-hidden=\"true\" className=\"size-3.5\" style={{ color: \"var(--chart-1, var(--primary))\" }} />\n                <span className=\"font-medium text-foreground\">{freezes}</span> {freezes === 1 ? \"freeze\" : \"freezes\"}\n              </span>\n            )}\n          </div>\n        </div>\n\n        <div ref={boxRef} className=\"mt-4 w-full overflow-x-clip\">\n          {width > 0 && (\n            <svg width={width} height={H + (date ? 16 : 0)} viewBox={`0 0 ${width} ${H + (date ? 16 : 0)}`} aria-hidden=\"true\" className=\"block overflow-visible\">\n              <g ref={chainRef}>\n                {/* The joints between rings: a short bar hooked through each pair, missing where the chain broke. */}\n                {days.map((d, i) => {\n                  if (i === 0 || d === \"tomorrow\" || d === \"missed\" || days[i - 1] === \"missed\" || (d === \"today\" && !done)) return null;\n                  const x1 = cxOf(i - 1) + ringW / 2 - stroke * 1.4;\n                  const x2 = cxOf(i) - ringW / 2 + stroke * 1.4;\n                  const frozen = d === \"frozen\" || days[i - 1] === \"frozen\";\n                  return (\n                    <rect\n                      key={`j${i}`}\n                      x={x1}\n                      y={cy - stroke * 0.7}\n                      width={Math.max(2, x2 - x1)}\n                      height={stroke * 1.4}\n                      rx={stroke * 0.7}\n                      fill={frozen ? mix(\"var(--chart-1, var(--primary))\", 40, \"var(--background)\") : colorAt(i)}\n                    />\n                  );\n                })}\n                {days.map((d, i) => {\n                  if (d === \"today\") return null;\n                  const cx = cxOf(i);\n                  const missed = d === \"missed\";\n                  const frozen = d === \"frozen\";\n                  const ghost = d === \"tomorrow\";\n                  const color = missed ? ink : frozen ? mix(\"var(--chart-1, var(--primary))\", 42, \"var(--background)\") : ghost ? mix(\"var(--foreground)\", 22, \"var(--border)\") : colorAt(i);\n                  return (\n                    <g\n                      key={`r${i}`}\n                      ref={(el) => {\n                        ringRefs.current[i] = el;\n                      }}\n                      transform={missed ? `translate(0 ${ringH * 0.55}) rotate(14 ${cx} ${cy})` : undefined}\n                    >\n                      <path\n                        d={stadium(cx, cy, ringW, ringH)}\n                        pathLength={100}\n                        fill=\"none\"\n                        stroke={color}\n                        strokeWidth={stroke}\n                        strokeLinecap=\"round\"\n                        style={missed ? { strokeDasharray: \"72 28\", strokeDashoffset: 10 } : ghost ? { strokeDasharray: \"5 5\" } : undefined}\n                      />\n                      {frozen && <Snow cx={cx} cy={cy} r={ringH * 0.24} />}\n                    </g>\n                  );\n                })}\n\n                {/* Today: hanging open off the end, or forged shut. */}\n                <g\n                  ref={(el) => {\n                    todayRef.current = el;\n                    ringRefs.current[todayIndex] = el;\n                  }}\n                >\n                  <path\n                    ref={todayPath}\n                    d={stadium(cxOf(todayIndex), cy, ringW, ringH)}\n                    pathLength={100}\n                    fill=\"none\"\n                    stroke={done ? colorAt(todayIndex) : ink}\n                    strokeWidth={stroke}\n                    strokeLinecap=\"round\"\n                    style={{ transition: reduced ? \"none\" : `stroke 300ms ${EASE} 500ms` }}\n                  />\n                  <path\n                    ref={pourPath}\n                    d={stadium(cxOf(todayIndex), cy, ringW, ringH)}\n                    pathLength={100}\n                    fill=\"none\"\n                    stroke={`url(#streak-pour)`}\n                    strokeWidth={stroke}\n                    strokeLinecap=\"round\"\n                    style={{ strokeDasharray: 100, strokeDashoffset: done ? 0 : 100, opacity: done ? 1 : 0, transition: `opacity 1ms linear ${done ? 0 : 300}ms` }}\n                  />\n                </g>\n                <defs>\n                  <linearGradient id=\"streak-pour\" x1=\"0\" x2=\"1\">\n                    <stop offset=\"0\" stopColor={colorA} />\n                    <stop offset=\"1\" stopColor={colorB} />\n                  </linearGradient>\n                </defs>\n              </g>\n\n              <g ref={sparkRef} stroke={colorB} strokeWidth={1.6} strokeLinecap=\"round\">\n                {[-80, -45, -12, 20, 55].map((deg) => {\n                  const a = (deg * Math.PI) / 180;\n                  const x = cxOf(todayIndex) - ringW / 2 + stroke;\n                  return (\n                    <line\n                      key={deg}\n                      x1={x - Math.cos(a) * ringH * 0.7}\n                      y1={cy + Math.sin(a) * ringH * 0.7}\n                      x2={x - Math.cos(a) * ringH * 1.15}\n                      y2={cy + Math.sin(a) * ringH * 1.15}\n                      style={{ opacity: 0, transformBox: \"view-box\", transformOrigin: `${x}px ${cy}px` }}\n                    />\n                  );\n                })}\n              </g>\n\n              {date &&\n                days.map((d, i) => (\n                  <text\n                    key={`l${i}`}\n                    x={cxOf(i)}\n                    y={H + 11}\n                    textAnchor=\"middle\"\n                    className={`text-[10px] ${d === \"today\" ? \"fill-foreground font-semibold\" : \"fill-muted-foreground\"}`}\n                  >\n                    {d === \"today\" ? \"Today\" : letter(i)}\n                  </text>\n                ))}\n            </svg>\n          )}\n        </div>\n\n        <div className=\"mt-3 flex items-center justify-between gap-3 text-[12px] tabular-nums\">\n          <span className={urgent ? \"font-medium text-amber-600 dark:text-amber-400\" : \"text-muted-foreground\"}>\n            <TextMorph>{done ? \"Saved for today\" : leftText || \"Today is still open\"}</TextMorph>\n          </span>\n          {next && (\n            <span className=\"text-muted-foreground\">\n              <span className=\"font-medium text-foreground\">\n                <NumberRoll value={toNext} duration={700} direction=\"down\" />\n              </span>{\" \"}\n              {toNext === 1 ? \"day\" : \"days\"} to {next}\n            </span>\n          )}\n        </div>\n        {next && (\n          <div aria-hidden=\"true\" className=\"relative mt-1.5 h-2\">\n            <div className=\"absolute inset-0\" style={{ background: mix(\"var(--foreground)\", 14), maskImage: TICKS, WebkitMaskImage: TICKS }} />\n            <div\n              className=\"absolute inset-0 origin-left\"\n              style={{\n                background: `linear-gradient(90deg, ${colorA}, ${colorB})`,\n                maskImage: TICKS,\n                WebkitMaskImage: TICKS,\n                transform: `scaleX(${Math.max(0.02, nextFill)})`,\n                transition: reduced ? \"none\" : `transform 700ms ${EASE} 600ms`,\n              }}\n            />\n          </div>\n        )}\n\n        <button\n          type=\"button\"\n          onClick={complete}\n          disabled={done}\n          className={`mt-4 inline-flex h-10 w-full cursor-pointer items-center justify-center gap-2 rounded-full text-[13.5px] font-medium transition-[background-color,color,box-shadow,scale] duration-300 active:scale-[0.98] disabled:cursor-default disabled:active:scale-100 ${FOCUS}`}\n          style={{\n            background: done ? \"var(--muted)\" : `linear-gradient(100deg, ${colorA}, ${colorB})`,\n            color: done ? \"var(--muted-foreground)\" : `oklch(from ${colorA} clamp(0.2, (0.72 - l) * 100, 0.99) 0 h)`,\n            transitionTimingFunction: EASE,\n          }}\n        >\n          <TextMorph>{done ? \"Done for today\" : actionLabel}</TextMorph>\n        </button>\n        <p className=\"sr-only\" aria-live=\"polite\">\n          {said}\n        </p>\n        <div className=\"sr-only\">\n          <ul aria-label=\"Recent days\">\n            {days\n              .filter((d) => d !== \"tomorrow\")\n              .map((d, i) => (\n                <li key={i}>\n                  {date ? letter(i) : `Day ${i + 1}`}: {d === \"today\" ? (done ? \"today, done\" : \"today, not done yet\") : d}\n                </li>\n              ))}\n          </ul>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nfunction Snow({ cx, cy, r }: { cx: number; cy: number; r: number }) {\n  return (\n    <g stroke=\"var(--chart-1, var(--primary))\" strokeWidth={1.2} strokeLinecap=\"round\" opacity={0.8}>\n      {[0, 60, 120].map((deg) => {\n        const a = (deg * Math.PI) / 180;\n        return <line key={deg} x1={cx - Math.cos(a) * r} y1={cy - Math.sin(a) * r} x2={cx + Math.cos(a) * r} y2={cy + Math.sin(a) * r} />;\n      })}\n    </g>\n  );\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · streak-chain · 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":{},"docs":"Docs and live preview: https://hairlineui.com/ui/streak-chain. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}