{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"goal-tape","type":"registry:component","title":"Goal tape","description":"How far to free shipping, and the moment you get there: the fill runs into a satin ribbon stretched across the bar at the goal and bows it until it snaps.","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/goal-tape.tsx","type":"registry:component","content":"// Hairline UI · goal-tape · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { Check } from \"lucide-react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\nimport { createSpring, type Spring } from \"./ui-interaction-motion\";\nimport { playSound } from \"./ui-sounds\";\n\n/* ─────────────────────────────────────────────────────────\n * GOAL TAPE: how far to the next reward, and the moment you\n * reach it\n *\n *   lane      a recessed lane fills with your colour as the total\n *             grows; at each goal a satin ribbon is stretched\n *             across it between two pins, like a finish line\n *             seen from above\n *   break     crossing a goal, the fill's nose runs into the\n *             ribbon and bows it forward until it snaps; the two\n *             halves whip back towards their pins and curl, the\n *             satin catching the light as it twists, and the\n *             line above rolls to \"You've unlocked free shipping\"\n *   retie     drop back under a goal and the two ends swing out,\n *             meet in the middle and tie, leaving a small knot\n *\n * The total is yours (a cart, a fundraiser, points); the bar only\n * shows it. The ribbons are a little rope simulation on one\n * canvas that sleeps once they come to rest.\n * ───────────────────────────────────────────────────────── */\n\nexport interface GoalTapeGoal {\n  /** The total at which it unlocks. */\n  at: number;\n  /** Read in a sentence: \"free shipping\", \"a free tote\". */\n  label: string;\n  /** The ribbon: any CSS colour. Defaults to your chart colours in turn. */\n  color?: string;\n}\n\nexport interface GoalTapeProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\"> {\n  /** The running total: the cart's subtotal, money raised, points earned. */\n  value: number;\n  /** One or more goals, any order. Or use goal and label for a single one. */\n  goals?: GoalTapeGoal[];\n  goal?: number;\n  label?: string;\n  /** How amounts are written, e.g. { style: \"currency\", currency: \"USD\" }. */\n  format?: Intl.NumberFormatOptions;\n  locales?: string | string[];\n  /** The two sentences, if yours read differently. */\n  messages?: { add?: string; more?: string; unlocked?: string };\n  /** A soft snap as a ribbon breaks, off by default. */\n  sound?: boolean;\n}\n\nconst TRACK = 16; // lane height\nconst PAD_X = 18; // the canvas reaches past the lane for the pins and the ribbon ends\nconst PAD_Y = 40;\nconst PIN = 12; // how far the pins stand off the lane's edges\nconst BREAK = 16; // how far the ribbon bows before it snaps\nconst HEADROOM = 1.16; // the lane runs on past the last goal, so the fill can break its ribbon\nconst SEGMENTS = 11;\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\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 = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\nconst subscribeNothing = () => () => {};\nconst useHydrated = () => React.useSyncExternalStore(subscribeNothing, () => true, () => false);\n\nconst clamp = (v: number, a: number, b: number) => (v < a ? a : v > b ? b : v);\n\n/* ── colours, mixed in JS so any colour format works ── */\n\ntype RGB = [number, number, number];\nconst mix = (a: RGB, b: RGB, t: number): RGB => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];\nconst css = (c: RGB, alpha = 1) => `rgba(${Math.round(c[0])},${Math.round(c[1])},${Math.round(c[2])},${alpha})`;\nconst lum = (c: RGB) => (0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]) / 255;\nconst chroma = (c: RGB) => (Math.max(...c) - Math.min(...c)) / 255;\nlet probe: CanvasRenderingContext2D | null = null;\nfunction toRgb(color: string, fallback: RGB): RGB {\n  if (typeof document === \"undefined\" || !color) return fallback;\n  probe ??= document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\n  if (!probe) return fallback;\n  probe.clearRect(0, 0, 1, 1);\n  probe.fillStyle = \"#000\";\n  probe.fillStyle = color;\n  probe.fillRect(0, 0, 1, 1);\n  const [r, g, b, a] = probe.getImageData(0, 0, 1, 1).data;\n  return a === 0 ? fallback : [r, g, b];\n}\n/** Satin ribbons: theme colours, or a gold one when the theme's chart colours are greys. */\nconst GOLD: RGB = [205, 152, 34];\n\n/* ── the ribbons ── */\n\ntype Rope = { x: Float32Array; y: Float32Array; px: Float32Array; py: Float32Array; rest: number; born: number; awake: boolean; still: number };\ntype Tape = {\n  x: number; // where the goal sits along the lane, px\n  phase: \"intact\" | \"stretch\" | \"broken\" | \"retie\";\n  bow: number;\n  ropes: [Rope, Rope] | null;\n  knot: number; // 0–1, shown once it has been tied again\n  color: RGB;\n};\n\ninterface Engine {\n  canvas: HTMLCanvasElement | null;\n  fill: HTMLDivElement | null;\n  width: number;\n  max: number;\n  dpr: number;\n  value: Spring | null;\n  tapes: Tape[];\n  frame: number;\n  last: number;\n  metal: RGB;\n  hi: RGB;\n  lo: RGB;\n  bg: RGB;\n  dark: boolean;\n  reduced: boolean;\n  sound: boolean;\n  onBreak: (i: number) => void;\n  onTie: (i: number) => void;\n  stripes: HTMLDivElement | null;\n}\n\nconst laneY = () => PAD_Y + TRACK / 2;\nconst pins = (t: Tape): [number, number, number, number] => [PAD_X + t.x, PAD_Y - PIN, PAD_X + t.x, PAD_Y + TRACK + PIN];\n\nfunction makeRope(ax: number, ay: number, bx: number, by: number, born: number): Rope {\n  const n = SEGMENTS + 1;\n  const rope: Rope = { x: new Float32Array(n), y: new Float32Array(n), px: new Float32Array(n), py: new Float32Array(n), rest: 0, born, awake: true, still: 0 };\n  for (let i = 0; i < n; i++) {\n    const t = i / SEGMENTS;\n    rope.x[i] = rope.px[i] = ax + (bx - ax) * t;\n    rope.y[i] = rope.py[i] = ay + (by - ay) * t;\n  }\n  rope.rest = Math.hypot(bx - ax, by - ay) / SEGMENTS;\n  return rope;\n}\n\n/** Snaps a bowed ribbon: two halves from the pins to where the nose met it, thrown forward and back towards their pins. */\nfunction snap(e: Engine, t: Tape, speed: number, now: number) {\n  const [tx, ty, bx, by] = pins(t);\n  const cx = PAD_X + t.x + t.bow;\n  const cy = laneY();\n  const top = makeRope(tx, ty, cx, cy - 0.6, now);\n  const bottom = makeRope(bx, by, cx, cy + 0.6, now);\n  const forward = clamp(speed, 90, 520) * 0.85;\n  for (const [rope, side] of [\n    [top, -1],\n    [bottom, 1],\n  ] as const) {\n    for (let i = 1; i <= SEGMENTS; i++) {\n      const k = i / SEGMENTS;\n      // Velocity in px per step (1/120 s): forward with the nose, back towards its own pin, with a little twist.\n      const vx = (forward * k * k + (Math.random() - 0.5) * 110 * k) / 120;\n      const vy = (side * 240 * k + (Math.random() - 0.5) * 40) / 120;\n      rope.px[i] = rope.x[i] - vx;\n      rope.py[i] = rope.y[i] - vy;\n    }\n  }\n  t.ropes = [top, bottom];\n  t.phase = \"broken\";\n  t.bow = 0;\n  t.knot = 0;\n  if (e.sound) playSound(\"pop\", 0.3);\n}\n\n/** One step of the rope: Verlet with damping, a rest length that contracts after the snap (or grows back to retie). */\nfunction stepRope(rope: Rope, t: Tape, now: number, tying: boolean) {\n  const n = SEGMENTS + 1;\n  const age = (now - rope.born) / 1000;\n  const full = rope.rest;\n  const target = tying ? full : full * (0.56 + 0.44 * Math.exp(-age / 0.07));\n  const damp = tying ? 0.86 : age < 0.3 ? 0.982 : 0.93;\n  const cx = PAD_X + t.x;\n  const cy = laneY();\n  let moving = 0;\n  for (let i = 1; i < n; i++) {\n    const vx = (rope.x[i] - rope.px[i]) * damp;\n    const vy = (rope.y[i] - rope.py[i]) * damp;\n    rope.px[i] = rope.x[i];\n    rope.py[i] = rope.y[i];\n    rope.x[i] += vx;\n    rope.y[i] += vy;\n    moving = Math.max(moving, Math.abs(vx) + Math.abs(vy));\n  }\n  if (!tying) {\n    // Thrown ends come to lie the way they were thrown: trailing forward, out to their own side of the lane.\n    const side = rope.y[0] < cy ? -1 : 1;\n    for (let i = 1; i < n; i++) {\n      const k = i / (n - 1);\n      rope.x[i] += 0.05 * k;\n      rope.y[i] += side * 0.06 * k;\n    }\n  }\n  if (tying) {\n    // The free end is drawn to the middle of the lane, where the two ends meet.\n    const j = n - 1;\n    rope.x[j] += (cx - rope.x[j]) * 0.22;\n    rope.y[j] += (cy - rope.y[j]) * 0.22;\n  }\n  for (let it = 0; it < 6; it++) {\n    for (let i = 0; i < n - 1; i++) {\n      const dx = rope.x[i + 1] - rope.x[i];\n      const dy = rope.y[i + 1] - rope.y[i];\n      const d = Math.hypot(dx, dy) || 1e-4;\n      const diff = (d - target) / d;\n      if (i === 0) {\n        rope.x[1] -= dx * diff;\n        rope.y[1] -= dy * diff;\n      } else {\n        rope.x[i] += dx * diff * 0.5;\n        rope.y[i] += dy * diff * 0.5;\n        rope.x[i + 1] -= dx * diff * 0.5;\n        rope.y[i + 1] -= dy * diff * 0.5;\n      }\n    }\n  }\n  rope.still = moving < 0.02 ? rope.still + 1 : 0;\n  rope.awake = tying || rope.still < 24 || age < 0.5;\n}\n\n/** A length of satin: each segment shaded by how it faces the light, so a twist reads as a twist. */\nfunction ribbon(ctx: CanvasRenderingContext2D, xs: ArrayLike<number>, ys: ArrayLike<number>, n: number, color: RGB, dark: boolean) {\n  ctx.lineCap = \"round\";\n  ctx.lineJoin = \"round\";\n  for (let i = 0; i < n - 1; i++) {\n    const dx = xs[i + 1] - xs[i];\n    const dy = ys[i + 1] - ys[i];\n    const facing = Math.abs(Math.cos(Math.atan2(dy, dx) - Math.PI / 2 - 0.5));\n    const lit = facing ** 3;\n    const shade = mix(mix(color, [0, 0, 0], (1 - facing) * (dark ? 0.35 : 0.28)), [255, 255, 255], lit * 0.32);\n    ctx.beginPath();\n    ctx.moveTo(xs[i], ys[i]);\n    ctx.lineTo(xs[i + 1], ys[i + 1]);\n    ctx.strokeStyle = css(shade);\n    ctx.lineWidth = 5;\n    ctx.stroke();\n    if (lit > 0.4) {\n      ctx.beginPath();\n      ctx.moveTo(xs[i], ys[i]);\n      ctx.lineTo(xs[i + 1], ys[i + 1]);\n      ctx.strokeStyle = css([255, 255, 255], (lit - 0.4) * 0.6);\n      ctx.lineWidth = 1.4;\n      ctx.stroke();\n    }\n  }\n}\n\nfunction pinHead(ctx: CanvasRenderingContext2D, e: Engine, x: number, y: number) {\n  ctx.save();\n  ctx.shadowColor = css([0, 0, 0], e.dark ? 0.55 : 0.25);\n  ctx.shadowBlur = 2.5;\n  ctx.shadowOffsetY = 1;\n  ctx.beginPath();\n  ctx.arc(x, y, 4, 0, Math.PI * 2);\n  const g = ctx.createRadialGradient(x - 1.3, y - 1.4, 0.3, x, y, 4.1);\n  g.addColorStop(0, css(e.hi));\n  g.addColorStop(0.55, css(e.metal));\n  g.addColorStop(1, css(e.lo));\n  ctx.fillStyle = g;\n  ctx.fill();\n  ctx.restore();\n}\n\nfunction draw(e: Engine) {\n  const canvas = e.canvas;\n  const ctx = canvas?.getContext(\"2d\");\n  if (!canvas || !ctx) return;\n  const W = e.width + PAD_X * 2;\n  const H = TRACK + PAD_Y * 2;\n  if (canvas.width !== Math.round(W * e.dpr) || canvas.height !== Math.round(H * e.dpr)) {\n    canvas.width = Math.round(W * e.dpr);\n    canvas.height = Math.round(H * e.dpr);\n  }\n  ctx.setTransform(e.dpr, 0, 0, e.dpr, 0, 0);\n  ctx.clearRect(0, 0, W, H);\n  const cy = laneY();\n  for (const t of e.tapes) {\n    const [tx, ty, bx, by] = pins(t);\n    if (t.phase === \"broken\" || t.phase === \"retie\") {\n      for (const rope of t.ropes ?? []) ribbon(ctx, rope.x, rope.y, SEGMENTS + 1, t.color, e.dark);\n    } else {\n      // Whole: straight across the lane, or bowed around the nose that's pushing it.\n      const nx = tx + t.bow;\n      const xs = [tx, (tx + nx) / 2 + t.bow * 0.15, nx, (bx + nx) / 2 + t.bow * 0.15, bx];\n      const ys = [ty, (ty + cy) / 2, cy, (by + cy) / 2, by];\n      ribbon(ctx, xs, ys, 5, t.color, e.dark);\n      if (t.knot > 0.01) {\n        ctx.beginPath();\n        ctx.ellipse(nx, cy, 3.2 * t.knot, 2.6 * t.knot, 0.3, 0, Math.PI * 2);\n        ctx.fillStyle = css(mix(t.color, [0, 0, 0], 0.22));\n        ctx.fill();\n        ctx.beginPath();\n        ctx.ellipse(nx - 0.8, cy - 0.8, 1.2 * t.knot, 0.8 * t.knot, 0.3, 0, Math.PI * 2);\n        ctx.fillStyle = css([255, 255, 255], 0.35);\n        ctx.fill();\n      }\n    }\n    pinHead(ctx, e, tx, ty);\n    pinHead(ctx, e, bx, by);\n  }\n}\n\n/** One frame: the fill's nose against each ribbon, the ropes, the paint. Runs while anything moves. */\nfunction frame(e: Engine, now: number) {\n  e.frame = 0;\n  const dt = clamp((now - e.last) / 1000, 0, 0.05);\n  e.last = now;\n  const value = e.value?.get() ?? 0;\n  const speed = Math.abs(e.value?.getVelocity() ?? 0) * (e.width / Math.max(1e-6, e.max));\n  const nose = clamp(value / Math.max(1e-6, e.max), 0, 1) * e.width;\n  if (e.fill) e.fill.style.transform = `translate3d(${nose - e.width}px, 0, 0)`;\n  if (e.stripes) e.stripes.style.transform = `translate3d(${e.width - nose}px, 0, 0)`;\n  let busy = Boolean(e.value && (e.value.getVelocity() !== 0 || Math.abs(e.value.get() - e.value.getTarget()) > 1e-6));\n  e.tapes.forEach((t, i) => {\n    const past = nose - t.x;\n    if (t.phase === \"intact\" || t.phase === \"stretch\") {\n      if (past > 0.2) {\n        t.phase = \"stretch\";\n        t.bow = Math.min(past, BREAK + 4);\n        const resting = !busy || (e.value && Math.abs(e.value.getVelocity()) < 0.002 * e.max);\n        if (e.reduced || past >= BREAK || resting) {\n          if (e.reduced) {\n            t.phase = \"broken\";\n            t.ropes = null;\n            t.bow = 0;\n          } else snap(e, t, speed, now);\n          e.onBreak(i);\n        }\n      } else if (t.phase === \"stretch\") {\n        t.phase = \"intact\";\n        t.bow = 0;\n      }\n    } else if (past < -0.5 && t.phase === \"broken\") {\n      if (e.reduced || !t.ropes) {\n        t.phase = \"intact\";\n        t.knot = 1;\n        e.onTie(i);\n      } else {\n        t.phase = \"retie\";\n        t.ropes.forEach((r) => (r.born = now));\n      }\n    } else if (t.phase === \"retie\") {\n      if (past > 0.2) {\n        // Over the goal again before the ends met: they spring back.\n        t.phase = \"broken\";\n        t.ropes?.forEach((r) => {\n          r.born = now;\n          r.awake = true;\n        });\n      } else if (t.ropes) {\n        const cx = PAD_X + t.x;\n        const cy = laneY();\n        const met = t.ropes.every((r) => Math.hypot(r.x[SEGMENTS] - cx, r.y[SEGMENTS] - cy) < 1.2);\n        if (met) {\n          t.phase = \"intact\";\n          t.ropes = null;\n          t.knot = 0.01;\n          e.onTie(i);\n          if (e.sound) playSound(\"tick\", 0.25);\n        }\n      }\n    }\n    if (t.ropes) {\n      const tying = t.phase === \"retie\";\n      for (let s = 0; s < Math.max(1, Math.round(dt * 120)); s++) t.ropes.forEach((r) => stepRope(r, t, now, tying));\n      if (t.ropes.some((r) => r.awake)) busy = true;\n    }\n    if (t.phase === \"intact\" && t.knot > 0 && t.knot < 1) {\n      t.knot = Math.min(1, t.knot + dt * 6);\n      busy = true;\n    }\n  });\n  draw(e);\n  if (busy) e.frame = requestAnimationFrame((ts) => frame(e, ts));\n}\n\nfunction kick(e: Engine) {\n  if (e.frame || !e.canvas) return;\n  e.last = performance.now();\n  e.frame = requestAnimationFrame((ts) => frame(e, ts));\n}\n\n/* ── the component ── */\n\nexport function GoalTape({ value, goals: goalsProp, goal, label, format, locales, messages, sound = false, className = \"\", ...props }: GoalTapeProps) {\n  const reduced = useReducedMotion();\n  const hydrated = useHydrated();\n  const goals = React.useMemo(() => {\n    const list = goalsProp ?? (goal !== undefined ? [{ at: goal, label: label ?? \"the reward\" }] : []);\n    return [...list].sort((a, b) => a.at - b.at);\n  }, [goalsProp, goal, label]);\n  const last = goals.length ? goals[goals.length - 1].at : 1;\n  const max = last * HEADROOM;\n  const laneRef = React.useRef<HTMLDivElement>(null);\n  const fillRef = React.useRef<HTMLDivElement>(null);\n  const stripesRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const probes = React.useRef<(HTMLSpanElement | null)[]>([]);\n  const engineRef = React.useRef<Engine | null>(null);\n  const [announce, setAnnounce] = React.useState(\"\");\n\n  const text = { add: \"Add \", more: \" more for \", unlocked: \"You’ve unlocked \", ...messages };\n  // The line changes when a ribbon actually snaps (or ties), not the moment the total crosses the goal.\n  const [snapped, setSnapped] = React.useState<Record<number, boolean>>(() => Object.fromEntries(goals.map((g) => [g.at, value >= g.at])));\n  const isSnapped = (g: GoalTapeGoal) => snapped[g.at] ?? value >= g.at;\n  const next = goals.find((g) => !isSnapped(g));\n  const reached = goals.filter((g) => isSnapped(g));\n  const remaining = next ? Math.max(0, next.at - value) : 0;\n  const locale = locales ?? (hydrated ? undefined : \"en-US\");\n  const formatter = React.useMemo(() => new Intl.NumberFormat(locale, format), [locale, format]);\n  const whole = React.useMemo(() => new Intl.NumberFormat(locale, { ...format, minimumFractionDigits: 0, maximumFractionDigits: 0 }), [locale, format]);\n\n  const engine = React.useCallback((): Engine => {\n    if (!engineRef.current) {\n      engineRef.current = {\n        canvas: null,\n        fill: null,\n        width: 0,\n        max: 1,\n        dpr: 1,\n        value: null,\n        tapes: [],\n        frame: 0,\n        last: 0,\n        metal: [180, 184, 190],\n        hi: [250, 250, 252],\n        lo: [110, 114, 120],\n        bg: [255, 255, 255],\n        dark: false,\n        reduced: false,\n        sound: false,\n        onBreak: () => {},\n        onTie: () => {},\n        stripes: null,\n      };\n    }\n    return engineRef.current;\n  }, []);\n\n  React.useLayoutEffect(() => {\n    const e = engine();\n    e.canvas = canvasRef.current;\n    e.fill = fillRef.current;\n    e.stripes = stripesRef.current;\n    e.value = createSpring(value, { stiffness: 150, damping: 17 }, () => kick(e), 0.0005 * Math.max(1, max));\n    return () => {\n      e.value?.stop();\n      cancelAnimationFrame(e.frame);\n      e.frame = 0;\n    };\n    // The spring is made once; later values re-aim it below.\n  }, [engine]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  React.useEffect(() => {\n    const e = engine();\n    e.reduced = reduced;\n    e.sound = sound;\n    e.max = max;\n    e.onBreak = (i) => {\n      const g = goals[i];\n      if (!g) return;\n      setSnapped((was) => (was[g.at] ? was : { ...was, [g.at]: true }));\n      setAnnounce(`${text.unlocked}${g.label}`);\n    };\n    e.onTie = (i) => {\n      const g = goals[i];\n      if (g) setSnapped((was) => (was[g.at] === false ? was : { ...was, [g.at]: false }));\n    };\n  });\n\n  // Ribbons: one per goal, placed along the lane; their phases survive a re-measure.\n  React.useLayoutEffect(() => {\n    const e = engine();\n    const lane = laneRef.current;\n    if (!lane) return;\n    const place = () => {\n      e.width = lane.clientWidth;\n      e.dpr = Math.min(3, window.devicePixelRatio || 1);\n      const colors = goals.map((g, i) => {\n        const c = toRgb(probes.current[i] ? getComputedStyle(probes.current[i]!).color : \"\", GOLD);\n        return chroma(c) < 0.12 ? GOLD : c;\n      });\n      const v = e.value?.get() ?? value;\n      e.tapes = goals.map((g, i) => {\n        const was = e.tapes[i];\n        const x = (g.at / Math.max(1e-6, max)) * e.width;\n        if (was) return { ...was, x, color: colors[i] };\n        return { x, phase: v >= g.at ? \"broken\" : \"intact\", bow: 0, ropes: null, knot: 0, color: colors[i] } as Tape;\n      });\n      // Ribbons already broken when it first shows lie curled by their pins, at rest.\n      e.tapes.forEach((t) => {\n        if (t.phase === \"broken\" && !t.ropes && !e.reduced) {\n          // Settled the way a live snap ends: the halves contracted and trailing forward, out to their sides.\n          const [tx, ty, bx, by] = pins(t);\n          const top = makeRope(tx, ty, tx + 2, laneY() - 1, -1e6);\n          const bottom = makeRope(bx, by, bx + 2, laneY() + 1, -1e6);\n          for (const r of [top, bottom]) for (let k = 0; k < 320; k++) stepRope(r, t, 0, false);\n          top.awake = bottom.awake = false;\n          t.ropes = [top, bottom];\n        }\n      });\n      kick(e);\n      draw(e);\n    };\n    place();\n    const observer = new ResizeObserver(place);\n    observer.observe(lane);\n    return () => observer.disconnect();\n  }, [engine, goals, max]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  // Theme colours for the pins and ribbons, read again when the theme changes.\n  React.useEffect(() => {\n    const e = engine();\n    const read = () => {\n      const fg = toRgb(probes.current[goals.length] ? getComputedStyle(probes.current[goals.length]!).color : \"\", [20, 20, 20]);\n      const bg = toRgb(probes.current[goals.length + 1] ? getComputedStyle(probes.current[goals.length + 1]!).color : \"\", [255, 255, 255]);\n      e.dark = lum(bg) < 0.5;\n      e.bg = bg;\n      e.metal = e.dark ? mix(bg, fg, 0.62) : mix(bg, fg, 0.3);\n      e.hi = mix(e.metal, [255, 255, 255], 0.75);\n      e.lo = mix(e.metal, [0, 0, 0], 0.4);\n      e.tapes.forEach((t, i) => {\n        const c = toRgb(probes.current[i] ? getComputedStyle(probes.current[i]!).color : \"\", GOLD);\n        t.color = chroma(c) < 0.12 ? GOLD : c;\n      });\n      draw(e);\n    };\n    read();\n    const observer = new MutationObserver(read);\n    observer.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n    const media = window.matchMedia(\"(prefers-color-scheme: dark)\");\n    media.addEventListener(\"change\", read);\n    return () => {\n      observer.disconnect();\n      media.removeEventListener(\"change\", read);\n    };\n  }, [engine, goals]);\n\n  // A new total: the fill glides to it on a spring (a slight push past a goal is what breaks the ribbon).\n  React.useEffect(() => {\n    const e = engine();\n    if (!e.value) return;\n    if (reduced) e.value.jump(value);\n    else e.value.set(value);\n    kick(e);\n  }, [engine, value, reduced]);\n\n  const unlockedAll = !next && goals.length > 0;\n  const lastReached = reached[reached.length - 1];\n\n  return (\n    <div className={`w-full ${className}`} {...props}>\n      {goals.map((g, i) => (\n        <span key={g.at} ref={(el) => void (probes.current[i] = el)} hidden style={{ color: g.color ?? `var(--chart-${(i % 4) + 2})` }} />\n      ))}\n      <span ref={(el) => void (probes.current[goals.length] = el)} hidden className=\"text-foreground\" />\n      <span ref={(el) => void (probes.current[goals.length + 1] = el)} hidden className=\"text-background\" />\n\n      <p className=\"flex min-h-6 flex-wrap items-baseline text-[13.5px] text-foreground\">\n        {unlockedAll ? (\n          <span className=\"font-medium\">\n            <TextMorph>{`${text.unlocked}${lastReached?.label ?? \"\"}`}</TextMorph>\n          </span>\n        ) : (\n          <>\n            <TextMorph>{text.add}</TextMorph>\n            <span className=\"font-medium tabular-nums\">\n              <NumberRoll value={remaining} format={format} locales={locales} />\n            </span>\n            <TextMorph>{`${text.more}${next?.label ?? \"\"}`}</TextMorph>\n          </>\n        )}\n      </p>\n\n      <div className=\"relative mt-6\" style={{ height: TRACK }}>\n        <div\n          ref={laneRef}\n          role=\"meter\"\n          aria-label={next ? `${text.add}${formatter.format(remaining)}${text.more}${next.label}` : `${text.unlocked}${lastReached?.label ?? \"\"}`}\n          aria-valuemin={0}\n          aria-valuemax={last}\n          aria-valuenow={Math.min(value, last)}\n          aria-valuetext={formatter.format(value)}\n          className=\"absolute inset-0 overflow-clip rounded-full bg-background shadow-[inset_0_0_0_1px_var(--border),inset_0_1.5px_3px_rgb(0_0_0/0.09)] dark:shadow-[inset_0_0_0_1px_var(--border),inset_0_1.5px_3px_rgb(0_0_0/0.45)]\"\n        >\n          <div\n            aria-hidden\n            className=\"absolute inset-0\"\n            style={{ backgroundImage: \"repeating-linear-gradient(90deg, color-mix(in oklab, var(--foreground) 9%, transparent) 0 2px, transparent 2px 4px)\" }}\n          />\n          <div\n            ref={fillRef}\n            className=\"absolute inset-y-0 left-0 w-full overflow-clip rounded-full bg-[color-mix(in_oklab,var(--primary)_22%,var(--background))]\"\n            style={{ transform: \"translate3d(-100%, 0, 0)\", willChange: \"transform\" }}\n          >\n            <div\n              ref={stripesRef}\n              className=\"absolute inset-0\"\n              style={{ backgroundImage: \"repeating-linear-gradient(90deg, var(--primary) 0 2px, transparent 2px 4px)\", transform: \"translate3d(100%, 0, 0)\", willChange: \"transform\" }}\n            />\n          </div>\n        </div>\n        <canvas\n          ref={canvasRef}\n          aria-hidden\n          className=\"pointer-events-none absolute\"\n          style={{ left: -PAD_X, top: -PAD_Y, width: `calc(100% + ${PAD_X * 2}px)`, height: TRACK + PAD_Y * 2 }}\n        />\n      </div>\n\n      <div className=\"relative mt-[26px] h-5 text-[12px]\">\n        {goals.map((g) => {\n          const met = value >= g.at;\n          const pct = (g.at / max) * 100;\n          return (\n            <span\n              key={g.at}\n              className={`absolute top-0 flex items-center gap-1 whitespace-nowrap transition-colors duration-300 ${met ? \"text-foreground\" : \"text-muted-foreground\"}`}\n              style={{ left: `${pct}%`, transform: pct < 22 ? \"translateX(12px)\" : \"translateX(calc(-100% - 12px))\" }}\n            >\n              <span\n                aria-hidden\n                className=\"grid overflow-clip\"\n                style={{ gridTemplateColumns: met ? \"1fr\" : \"0fr\", opacity: met ? 1 : 0, transition: `grid-template-columns 360ms ${EASE}, opacity 260ms ${EASE}` }}\n              >\n                <span className=\"min-w-0\">\n                  <Check className=\"mr-0.5 size-3.5 text-emerald-600 dark:text-emerald-400\" />\n                </span>\n              </span>\n              <span className=\"tabular-nums\">{(Number.isInteger(g.at) ? whole : formatter).format(g.at)}</span>\n              <span className=\"text-muted-foreground\">·</span>\n              <span className=\"inline-block first-letter:uppercase\">{g.label}</span>\n            </span>\n          );\n        })}\n      </div>\n\n      <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n        {announce}\n      </span>\n    </div>\n  );\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · goal-tape · 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"},{"path":"registry/ui-sounds.ts","type":"registry:component","content":"// Hairline UI · goal-tape · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * UI SOUNDS: small interface sounds, made in code\n *\n * No files and nothing to license: every sound is built from a\n * tone or a burst of noise with the Web Audio API the moment it\n * plays. They're short and quiet, made to sit under an interface,\n * and components only play them when you pass `sound`.\n *\n *   fold     paper creasing: two short crisp bursts\n *   unfold   paper opening: a soft rising sweep\n *   drop     something small landing: a low, soft knock\n *   tick     a light click\n *   pop      a quick bright blip\n *   success  two soft rising notes\n *   error    two low falling notes\n *\n * Browsers only start audio after the visitor has pressed\n * something on the page, so a sound before that stays silent.\n * ───────────────────────────────────────────────────────── */\n\nexport type UiSound = \"fold\" | \"unfold\" | \"drop\" | \"tick\" | \"pop\" | \"success\" | \"error\";\n\nlet context: AudioContext | null = null;\nlet noise: AudioBuffer | null = null;\n\nfunction audio() {\n  if (typeof window === \"undefined\") return null;\n  if (!context) {\n    const Ctx = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n    if (!Ctx) return null;\n    context = new Ctx();\n  }\n  if (context.state === \"suspended\") void context.resume().catch(() => {});\n  return context;\n}\n\nfunction noiseBuffer(ctx: AudioContext) {\n  if (noise && noise.sampleRate === ctx.sampleRate) return noise;\n  noise = ctx.createBuffer(1, Math.floor(ctx.sampleRate * 0.5), ctx.sampleRate);\n  const data = noise.getChannelData(0);\n  for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n  return noise;\n}\n\n/** A burst of filtered noise. */\nfunction burst(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"bandpass\", from = 2000, to = from, q = 0.9, level = 0.5 }: { type?: BiquadFilterType; from?: number; to?: number; q?: number; level?: number }) {\n  const src = ctx.createBufferSource();\n  src.buffer = noiseBuffer(ctx);\n  const filter = ctx.createBiquadFilter();\n  filter.type = type;\n  filter.Q.value = q;\n  filter.frequency.setValueAtTime(from, at);\n  filter.frequency.exponentialRampToValueAtTime(Math.max(40, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + Math.min(0.012, length / 3));\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  src.connect(filter).connect(gain).connect(out);\n  src.start(at, Math.random() * 0.3, length + 0.02);\n}\n\n/** A tone that glides from one pitch to another. */\nfunction tone(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"sine\", from, to = from, level = 0.4 }: { type?: OscillatorType; from: number; to?: number; level?: number }) {\n  const osc = ctx.createOscillator();\n  osc.type = type;\n  osc.frequency.setValueAtTime(from, at);\n  osc.frequency.exponentialRampToValueAtTime(Math.max(20, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + 0.006);\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  osc.connect(gain).connect(out);\n  osc.start(at);\n  osc.stop(at + length + 0.02);\n}\n\n/** Plays one sound. `volume` is 0 to 1; the default sits quietly under an interface. */\nexport function playSound(name: UiSound, volume = 0.5) {\n  const ctx = audio();\n  if (!ctx) return;\n  const out = ctx.createGain();\n  out.gain.value = Math.max(0, Math.min(1, volume)) * 0.5;\n  out.connect(ctx.destination);\n  const t = ctx.currentTime + 0.005;\n  switch (name) {\n    case \"fold\":\n      burst(ctx, out, t, 0.05, { type: \"highpass\", from: 2600, q: 0.7, level: 0.45 });\n      burst(ctx, out, t + 0.07, 0.07, { type: \"bandpass\", from: 3200, to: 1800, q: 1.2, level: 0.35 });\n      break;\n    case \"unfold\":\n      burst(ctx, out, t, 0.16, { type: \"bandpass\", from: 900, to: 2800, q: 0.8, level: 0.3 });\n      break;\n    case \"drop\":\n      tone(ctx, out, t, 0.12, { from: 180, to: 70, level: 0.55 });\n      burst(ctx, out, t, 0.03, { type: \"lowpass\", from: 1200, q: 0.5, level: 0.2 });\n      break;\n    case \"tick\":\n      tone(ctx, out, t, 0.025, { type: \"triangle\", from: 1900, to: 1500, level: 0.25 });\n      break;\n    case \"pop\":\n      tone(ctx, out, t, 0.06, { from: 620, to: 980, level: 0.3 });\n      break;\n    case \"success\":\n      tone(ctx, out, t, 0.11, { from: 660, level: 0.22 });\n      tone(ctx, out, t + 0.09, 0.16, { from: 990, level: 0.22 });\n      break;\n    case \"error\":\n      tone(ctx, out, t, 0.12, { type: \"triangle\", from: 330, level: 0.25 });\n      tone(ctx, out, t + 0.1, 0.18, { type: \"triangle\", from: 247, level: 0.25 });\n      break;\n  }\n  window.setTimeout(() => out.disconnect(), 600);\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/goal-tape. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}