{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"range-brush","type":"registry:component","title":"Range brush","description":"Pick a stretch of days by holding it: a lit window over a year of hairlines that glides when thrown, stretches from either edge and settles on whole days.","author":"Hairline UI","dependencies":[],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency"],"files":[{"path":"registry/range-brush.tsx","type":"registry:component","content":"// Hairline UI · range-brush · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { createSpring, projectInertia, releaseVelocity, rubberBand, samplePointer, type PointerSample, type Spring } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * RANGE BRUSH: pick a stretch of days by holding it\n *\n *   rest      the whole history as a silhouette ruled in hairlines,\n *             the chosen stretch lit inside a hairline window\n *   pan       drag inside the window and it slides; let go and it\n *             glides on with your speed and settles on whole days,\n *             pulling back like a rubber band at either end. The days\n *             it leaves don't go dark at once: they cool behind it\n *   resize    drag either edge to widen or narrow it (never under the\n *             shortest span), on the same springs\n *   draw      press outside the window and drag to draw a new one\n *   settle    when you let go, the stretch's total and its change\n *             against the stretch before roll to their figures\n *\n * Two springs (the window's edges) and one canvas; nothing renders\n * while you drag. The window is a group (arrows move it a day, Shift\n * a week) and each edge is a slider.\n * ───────────────────────────────────────────────────────── */\n\nexport interface RangeBrushDatum {\n  key: string;\n  value: number;\n  /** In the range caption, e.g. \"14 Mar\". */\n  label: string;\n  /** A tick under this bar, e.g. \"Mar\". */\n  tick?: string;\n}\n\n/** Start and end as day indexes, the end not included: [0, 30] is the first thirty days. */\nexport type RangeBrushValue = [number, number];\n\nexport interface RangeBrushProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"defaultValue\" | \"onChange\"> {\n  data: RangeBrushDatum[];\n  value?: RangeBrushValue;\n  defaultValue?: RangeBrushValue;\n  /** Called when a drag or key press settles on a new stretch. */\n  onValueChange?: (value: RangeBrushValue) => void;\n  /** The shortest stretch, in days. */\n  minSpan?: number;\n  title?: string;\n  format?: Intl.NumberFormatOptions;\n  locales?: string | string[];\n  /** Any CSS colour. Defaults to your first chart colour. */\n  color?: string;\n}\n\nconst FOCUS = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40\";\nconst LINE = 2;\nconst PITCH = 4;\nconst TRAIL = 0.6; // seconds for a day the window left to cool\nconst EDGE = 10; // px either side of an edge that grabs it\nconst LEVELS = 16;\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\n// Formatting waits for hydration: the server and the hydrating render share one fixed locale, then the visitor's takes over.\nconst subscribeNothing = () => () => {};\nconst useHydrated = () => React.useSyncExternalStore(subscribeNothing, () => true, () => false);\n\nfunction niceMax(value: number) {\n  if (value <= 0) return 1;\n  const step = 10 ** Math.floor(Math.log10(value));\n  for (const m of [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) if (m * step >= value) return m * step;\n  return 10 * step;\n}\n\nconst clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);\n\ntype Drag = {\n  id: number;\n  mode: \"pan\" | \"start\" | \"end\" | \"draw\";\n  x0: number;\n  s0: number;\n  e0: number;\n  anchor: number;\n  samples: PointerSample[];\n};\n\nexport function RangeBrush({\n  data,\n  value,\n  defaultValue,\n  onValueChange,\n  minSpan = 7,\n  title = \"Signups\",\n  format,\n  locales,\n  color = \"var(--chart-1, var(--primary))\",\n  className = \"\",\n  ...props\n}: RangeBrushProps) {\n  const reduced = useReducedMotion();\n  const hydrated = useHydrated();\n  const locale = locales ?? (hydrated ? undefined : \"en-US\");\n  const n = data.length;\n  const span = Math.max(1, Math.min(minSpan, n));\n  const [own, setOwn] = React.useState<RangeBrushValue>(() => defaultValue ?? [Math.max(0, n - 30), n]);\n  const range = value ?? own;\n  const max = niceMax(Math.max(0, ...data.map((d) => d.value)));\n\n  const [visible, setVisible] = React.useState(false);\n  const [plotW, setPlotW] = React.useState(0);\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const probeRef = React.useRef<HTMLSpanElement>(null);\n  const inkRef = React.useRef<HTMLSpanElement>(null);\n  const startRef = React.useRef<HTMLDivElement>(null);\n  const endRef = React.useRef<HTMLDivElement>(null);\n  const captionRef = React.useRef<HTMLSpanElement>(null);\n\n  const engine = React.useRef<{\n    width: number;\n    height: number;\n    dpr: number;\n    values: Float32Array;\n    heat: Float32Array;\n    start: Spring | null;\n    end: Spring | null;\n    accent: string;\n    ink: string;\n    bornAt: number;\n    lastPaint: number;\n    frame: number;\n    reduced: boolean;\n    caption: string;\n    paint: () => void;\n  } | null>(null);\n  const live = React.useRef({ data, n, span, onValueChange, controlled: value !== undefined });\n  React.useLayoutEffect(() => {\n    live.current = { data, n, span, onValueChange, controlled: value !== undefined };\n  });\n\n  const paint = React.useCallback(() => {\n    const e = engine.current;\n    const canvas = canvasRef.current;\n    if (!e || !canvas) return;\n    const ctx = canvas.getContext(\"2d\");\n    const count = e.values.length;\n    if (!ctx || !e.width || !e.height || !count) return;\n    const now = performance.now();\n    const dt = e.lastPaint ? Math.min((now - e.lastPaint) / 1000, 0.1) : 0;\n    e.lastPaint = now;\n    const decay = e.reduced ? 0 : Math.exp(-dt / TRAIL);\n    const slot = e.width / count;\n    const s = e.start?.get() ?? 0;\n    const t = e.end?.get() ?? count;\n    const grown = e.bornAt ? now - e.bornAt : 0;\n    let busy = false;\n\n    ctx.setTransform(e.dpr, 0, 0, e.dpr, 0, 0);\n    ctx.clearRect(0, 0, e.width, e.height);\n    const rest = new Path2D();\n    const levels: Path2D[] = Array.from({ length: LEVELS }, () => new Path2D());\n    for (let i = 0; i < count; i++) {\n      const born = e.reduced ? 1 : e.bornAt ? 1 - (1 - Math.min(1, Math.max(0, (grown - (i / count) * 480) / 600))) ** 3 : 0;\n      if (born < 1) busy = true;\n      // How much of this day the window covers, and the light it keeps after the window leaves.\n      const inside = Math.max(0, Math.min(i + 1, t) - Math.max(i, s));\n      const heat = Math.max(inside, e.heat[i] * decay);\n      if (heat > 0.004 && heat !== inside) busy = true;\n      e.heat[i] = heat;\n      const x0 = Math.round(i * slot * e.dpr) / e.dpr;\n      const x1 = Math.round((i + 1) * slot * e.dpr) / e.dpr;\n      const w = slot < 2.5 ? x1 - x0 : Math.min(12, slot * 0.62);\n      const x = slot < 2.5 ? x0 : (x0 + x1) / 2 - w / 2;\n      const h = Math.max(e.values[i] > 0 ? LINE : 0, e.values[i] * e.height * born);\n      rest.rect(x, e.height - h, Math.max(w, 1 / e.dpr), h);\n      const level = Math.round(heat * LEVELS);\n      if (level > 0) levels[level - 1].rect(x, e.height - h, Math.max(w, 1 / e.dpr), h);\n    }\n    // Everything through a rule of hairlines counted from the baseline: bars are stacks of lines, the field behind is faint lines.\n    const rule = new Path2D();\n    for (let k = 0; ; k++) {\n      const y = Math.round((e.height - LINE - k * PITCH) * e.dpr) / e.dpr;\n      if (y < -LINE) break;\n      rule.rect(0, y, e.width, LINE);\n    }\n    ctx.save();\n    ctx.clip(rule);\n    ctx.fillStyle = e.ink;\n    ctx.globalAlpha = 0.04;\n    ctx.fillRect(0, 0, e.width, e.height);\n    ctx.fillStyle = e.accent;\n    ctx.globalAlpha = 0.24;\n    ctx.fill(rest);\n    for (let l = 0; l < LEVELS; l++) {\n      ctx.globalAlpha = (l + 1) / LEVELS;\n      ctx.fill(levels[l]);\n    }\n    ctx.restore();\n\n    // The window: a hairline frame around the stretch.\n    const left = Math.round(s * slot * e.dpr) / e.dpr;\n    const right = Math.round(t * slot * e.dpr) / e.dpr;\n    ctx.globalAlpha = 0.035;\n    ctx.fillStyle = e.ink;\n    ctx.fillRect(left, 0, right - left, e.height);\n    ctx.globalAlpha = 0.5;\n    ctx.strokeStyle = e.ink;\n    ctx.lineWidth = 1;\n    ctx.strokeRect(left + 0.5, 0.5, Math.max(0, right - left - 1), e.height - 1);\n    ctx.globalAlpha = 1;\n\n    if (startRef.current) startRef.current.style.transform = `translate3d(${left}px,0,0)`;\n    if (endRef.current) endRef.current.style.transform = `translate3d(${right}px,0,0)`;\n\n    // The caption follows the window while it moves, as plain text.\n    const from = Math.round(clamp(s, 0, count - 1));\n    const to = Math.round(clamp(t, from + 1, count)) - 1;\n    const L = live.current.data;\n    const caption = L[from] && L[to] ? `${L[from].label} – ${L[to].label} · ${to - from + 1} days` : \"\";\n    if (caption !== e.caption && captionRef.current) {\n      e.caption = caption;\n      captionRef.current.textContent = caption;\n    }\n\n    if (busy && !e.frame) {\n      e.frame = requestAnimationFrame(() => {\n        const next = engine.current;\n        if (!next) return;\n        next.frame = 0;\n        next.paint();\n      });\n    }\n    if (!busy) e.lastPaint = 0;\n  }, []);\n\n  // Built first: the layout effects below size and fill it.\n  const initial = React.useRef(range);\n  React.useLayoutEffect(() => {\n    const e = {\n      width: 0,\n      height: 0,\n      dpr: 1,\n      values: new Float32Array(0),\n      heat: new Float32Array(0),\n      start: null as Spring | null,\n      end: null as Spring | null,\n      accent: \"currentColor\",\n      ink: \"currentColor\",\n      bornAt: 0,\n      lastPaint: 0,\n      frame: 0,\n      reduced: false,\n      caption: \"\",\n      paint,\n    };\n    e.start = createSpring(initial.current[0], { stiffness: 380, damping: 39 }, paint, 0.002);\n    e.end = createSpring(initial.current[1], { stiffness: 380, damping: 39 }, paint, 0.002);\n    engine.current = e;\n    return () => {\n      e.start?.stop();\n      e.end?.stop();\n      if (e.frame) cancelAnimationFrame(e.frame);\n      e.frame = 0;\n      engine.current = null;\n    };\n  }, [paint]);\n\n  React.useLayoutEffect(() => {\n    const e = engine.current;\n    if (!e) return;\n    e.values = new Float32Array(data.map((d) => Math.max(0, d.value) / max));\n    if (e.heat.length !== data.length) e.heat = new Float32Array(data.length);\n    paint();\n  }, [data, max, paint]);\n\n  React.useEffect(() => {\n    if (engine.current) engine.current.reduced = reduced;\n  }, [reduced]);\n\n  // A stretch from outside (controlled, or keys) moves the window on its springs.\n  const dragging = React.useRef<Drag | null>(null);\n  React.useEffect(() => {\n    const e = engine.current;\n    if (!e || dragging.current) return;\n    if (reduced) {\n      e.start?.jump(range[0]);\n      e.end?.jump(range[1]);\n    } else {\n      e.start?.set(range[0]);\n      e.end?.set(range[1]);\n    }\n  }, [range, reduced]);\n\n  React.useLayoutEffect(() => {\n    const plot = plotRef.current;\n    const canvas = canvasRef.current;\n    if (!plot || !canvas) return;\n    const measure = () => {\n      const e = engine.current;\n      if (!e) return;\n      const w = plot.clientWidth;\n      const h = canvas.clientHeight;\n      const dpr = Math.min(window.devicePixelRatio || 1, 3);\n      setPlotW((p) => (p === w ? p : w));\n      if (w === e.width && h === e.height && dpr === e.dpr) return;\n      e.width = w;\n      e.height = h;\n      e.dpr = dpr;\n      canvas.width = Math.round(w * dpr);\n      canvas.height = Math.round(h * dpr);\n      paint();\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(plot);\n    return () => observer.disconnect();\n  }, [paint]);\n\n  React.useEffect(() => {\n    const read = () => {\n      const e = engine.current;\n      if (!e) return;\n      if (probeRef.current) e.accent = getComputedStyle(probeRef.current).color;\n      if (inkRef.current) e.ink = getComputedStyle(inkRef.current).color;\n      paint();\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  }, [color, paint]);\n\n  React.useEffect(() => {\n    const el = rootRef.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry.isIntersecting) return;\n        setVisible(true);\n        if (engine.current) engine.current.bornAt = performance.now();\n        paint();\n        observer.disconnect();\n      },\n      { rootMargin: \"0px 0px -10% 0px\" },\n    );\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [paint]);\n\n  const commit = React.useCallback((next: RangeBrushValue) => {\n    const L = live.current;\n    if (!L.controlled) setOwn(next);\n    L.onValueChange?.(next);\n  }, []);\n\n  // ── Gestures: all in day units, written straight to the springs ──\n  const dayAt = (clientX: number) => {\n    const e = engine.current;\n    const r = plotRef.current?.getBoundingClientRect();\n    if (!e || !r || !e.width) return 0;\n    return ((clientX - r.left) / r.width) * e.values.length;\n  };\n\n  const onPointerDown = (ev: React.PointerEvent<HTMLDivElement>) => {\n    const e = engine.current;\n    if (!e || ev.button !== 0 || !e.start || !e.end) return;\n    const day = dayAt(ev.clientX);\n    const slot = e.width / Math.max(1, e.values.length);\n    const s = e.start.get();\n    const t = e.end.get();\n    const reach = EDGE / slot;\n    const mode: Drag[\"mode\"] = Math.abs(day - s) <= reach ? \"start\" : Math.abs(day - t) <= reach ? \"end\" : day > s && day < t ? \"pan\" : \"draw\";\n    ev.currentTarget.setPointerCapture(ev.pointerId);\n    dragging.current = { id: ev.pointerId, mode, x0: day, s0: s, e0: t, anchor: Math.round(day), samples: [] };\n    samplePointer(dragging.current.samples, day, ev.timeStamp);\n    e.start.jump(s);\n    e.end.jump(t);\n  };\n\n  const onPointerMove = (ev: React.PointerEvent<HTMLDivElement>) => {\n    const d = dragging.current;\n    const e = engine.current;\n    if (!d || d.id !== ev.pointerId || !e?.start || !e.end) return;\n    const count = e.values.length;\n    const slot = e.width / Math.max(1, count);\n    const day = dayAt(ev.clientX);\n    samplePointer(d.samples, day, ev.timeStamp);\n    const minS = live.current.span;\n    // Past either end the window gives less and less, measured in pixels so it feels the same at any density.\n    const band = (over: number) => rubberBand(over * slot, e.width) / slot;\n    let s = d.s0;\n    let t = d.e0;\n    if (d.mode === \"pan\") {\n      const width = d.e0 - d.s0;\n      s = d.s0 + (day - d.x0);\n      if (s < 0) s = -band(-s);\n      if (s + width > count) s = count - width + band(s + width - count);\n      t = s + width;\n    } else if (d.mode === \"start\") {\n      s = Math.min(d.s0 + (day - d.x0), t - minS);\n      if (s < 0) s = -band(-s);\n    } else if (d.mode === \"end\") {\n      t = Math.max(d.e0 + (day - d.x0), s + minS);\n      if (t > count) t = count + band(t - count);\n    } else {\n      const a = d.anchor;\n      s = Math.min(a, day);\n      t = Math.max(a, day);\n      if (t - s < minS) {\n        if (day >= a) t = s + minS;\n        else s = t - minS;\n      }\n      if (s < 0) s = -band(-s);\n      if (t > count) t = count + band(t - count);\n    }\n    e.start.jump(s);\n    e.end.jump(t);\n  };\n\n  const onPointerUp = (ev: React.PointerEvent<HTMLDivElement>) => {\n    const d = dragging.current;\n    const e = engine.current;\n    if (!d || d.id !== ev.pointerId || !e?.start || !e.end) return;\n    dragging.current = null;\n    const count = e.values.length;\n    const minS = live.current.span;\n    const v = releaseVelocity(d.samples, ev.timeStamp); // days per ms\n    let s = e.start.get();\n    let t = e.end.get();\n    if (d.mode === \"pan\") {\n      const width = Math.round(t - s);\n      const projected = projectInertia(s, v, 0.16);\n      s = clamp(Math.round(projected), 0, count - width);\n      t = s + width;\n    } else {\n      s = clamp(Math.round(s), 0, count - minS);\n      t = clamp(Math.round(t), s + minS, count);\n    }\n    if (reduced) {\n      e.start.jump(s);\n      e.end.jump(t);\n    } else {\n      // Carry the hand's speed into the settle, but never so much that it slams past where it is going.\n      const speed = v * 1000;\n      if (d.mode !== \"end\") e.start.push(Math.sign(speed) * Math.min(Math.abs(speed), Math.abs(s - e.start.get()) * 10));\n      if (d.mode !== \"start\") e.end.push(Math.sign(speed) * Math.min(Math.abs(speed), Math.abs(t - e.end.get()) * 10));\n      e.start.set(s);\n      e.end.set(t);\n    }\n    if (s !== range[0] || t !== range[1]) commit([s, t]);\n  };\n\n  const onPointerHover = (ev: React.PointerEvent<HTMLDivElement>) => {\n    if (dragging.current || ev.pointerType !== \"mouse\") return;\n    const e = engine.current;\n    if (!e?.start || !e.end) return;\n    const day = dayAt(ev.clientX);\n    const reach = EDGE / (e.width / Math.max(1, e.values.length));\n    const s = e.start.get();\n    const t = e.end.get();\n    ev.currentTarget.style.cursor = Math.abs(day - s) <= reach || Math.abs(day - t) <= reach ? \"ew-resize\" : day > s && day < t ? \"grab\" : \"crosshair\";\n  };\n\n  const keyMove = (which: \"both\" | \"start\" | \"end\") => (ev: React.KeyboardEvent) => {\n    const step = ev.shiftKey ? 7 : 1;\n    const delta = ev.key === \"ArrowLeft\" || ev.key === \"ArrowDown\" ? -step : ev.key === \"ArrowRight\" || ev.key === \"ArrowUp\" ? step : 0;\n    if (!delta) return;\n    ev.preventDefault();\n    ev.stopPropagation();\n    let [s, t] = range;\n    if (which === \"both\") {\n      const width = t - s;\n      s = clamp(s + delta, 0, n - width);\n      t = s + width;\n    } else if (which === \"start\") s = clamp(s + delta, 0, t - span);\n    else t = clamp(t + delta, s + span, n);\n    if (s !== range[0] || t !== range[1]) commit([s, t]);\n  };\n\n  // The figures settle on the chosen stretch, against the same number of days before it.\n  const sum = (a: number, b: number) => data.slice(Math.max(0, a), Math.max(0, b)).reduce((acc, d) => acc + d.value, 0);\n  const total = sum(range[0], range[1]);\n  const width = range[1] - range[0];\n  const before = range[0] - width >= 0 ? sum(range[0] - width, range[0]) : null;\n  const change = before ? (total - before) / before : null;\n  const fmt = (v: number) => new Intl.NumberFormat(locale, format).format(v);\n  const firstLabel = data[range[0]]?.label ?? \"\";\n  // Ticks thin out on narrow plots so their labels never touch: keep one only when it is 34px clear of the last kept.\n  // Memoised with the hidden table, so settling a new stretch re-renders only the header.\n  const ticks = React.useMemo(() => {\n    const out: React.ReactNode[] = [];\n    let lastTick = -Infinity;\n    data.forEach((d, i) => {\n      const x = ((i + 0.5) / Math.max(1, data.length)) * (plotW || 600);\n      if (!d.tick || x - lastTick < 34) return;\n      lastTick = x;\n      out.push(\n        <span\n          key={d.key}\n          className=\"absolute top-0 -translate-x-1/2 whitespace-nowrap text-[10.5px] leading-4 text-muted-foreground\"\n          style={{ left: `clamp(12px, ${((i + 0.5) / Math.max(1, data.length)) * 100}%, calc(100% - 12px))` }}\n        >\n          {d.tick}\n        </span>,\n      );\n    });\n    return out;\n  }, [data, plotW]);\n  const table = React.useMemo(\n    () => (\n      <tbody>\n        {data.map((d) => (\n          <tr key={d.key}>\n            <th scope=\"row\">{d.label}</th>\n            <td>{new Intl.NumberFormat(locale, format).format(d.value)}</td>\n          </tr>\n        ))}\n      </tbody>\n    ),\n    [data, locale, format],\n  );\n  const lastLabel = data[range[1] - 1]?.label ?? \"\";\n\n  return (\n    <div ref={rootRef} className={`w-full rounded-[22px] bg-background shadow-[0_0_0_1px_var(--border)] ${className}`} {...props}>\n      <span ref={probeRef} aria-hidden=\"true\" className=\"hidden\" style={{ color }} />\n      <span ref={inkRef} aria-hidden=\"true\" className=\"hidden text-foreground\" />\n      {/* Its natural width where the parent sizes to its content (a centred flex column), without forcing it on narrow screens. */}\n      <div aria-hidden=\"true\" data-natural-width className=\"grid h-0\" style={{ gridTemplateColumns: \"minmax(0, 600px)\" }} />\n      <div className=\"@container w-full\">\n        <div className=\"p-4 @md:p-5 [--plot:120px] @md:[--plot:150px]\">\n          <p className=\"text-[12px] text-muted-foreground @md:text-[13px]\">{title}</p>\n          <div className=\"mt-0.5 flex flex-wrap items-center gap-x-2\">\n            <p className=\"text-[22px] font-medium leading-tight tracking-[-0.03em] text-foreground tabular-nums @md:text-[26px]\">\n              <NumberRoll value={visible ? total : 0} format={format} locales={locale} duration={900} />\n            </p>\n            {change !== null && (\n              <span\n                className={`inline-flex items-center gap-1 whitespace-nowrap rounded-full px-1.5 py-px text-[11.5px] font-medium tabular-nums @md:text-[12.5px] ${\n                  change >= 0 ? \"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400\" : \"bg-red-500/10 text-red-600 dark:text-red-400\"\n                }`}\n              >\n                <svg viewBox=\"0 0 12 12\" aria-hidden=\"true\" className=\"size-3\" style={{ transform: change >= 0 ? \"none\" : \"rotate(180deg)\" }}>\n                  <path d=\"M6 9.5V2.5M2.8 5.6 6 2.5l3.2 3.1\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n                </svg>\n                <span className=\"sr-only\">{change >= 0 ? \"up\" : \"down\"}</span>\n                <NumberRoll value={Math.abs(change)} format={{ style: \"percent\", maximumFractionDigits: 1 }} locales={locale} duration={900} />\n              </span>\n            )}\n          </div>\n          <p className=\"mt-0.5 text-[11.5px] text-muted-foreground tabular-nums @md:text-[12.5px]\">\n            <span ref={captionRef}>{firstLabel && lastLabel ? `${firstLabel} – ${lastLabel} · ${width} days` : \"\"}</span>\n            {change !== null && <span> · against the {width} days before</span>}\n          </p>\n\n          <div\n            ref={plotRef}\n            onPointerDown={onPointerDown}\n            onPointerMove={(ev) => {\n              onPointerHover(ev);\n              onPointerMove(ev);\n            }}\n            onPointerUp={onPointerUp}\n            onPointerCancel={onPointerUp}\n            className=\"relative mt-4 touch-pan-y select-none @md:mt-5\"\n          >\n            <canvas ref={canvasRef} aria-hidden=\"true\" className=\"block w-full\" style={{ height: \"var(--plot)\" }} />\n            <div aria-hidden=\"true\" className=\"absolute inset-x-0 bottom-0 border-t border-border\" />\n            {/* The window as one tab stop, and each edge as a slider. */}\n            <div\n              role=\"group\"\n              tabIndex={0}\n              aria-label={`${title}, ${firstLabel} to ${lastLabel}. Arrow keys move the range a day, Shift a week.`}\n              onKeyDown={keyMove(\"both\")}\n              className={`pointer-events-none absolute inset-0 rounded-sm ${FOCUS}`}\n            />\n            {([\"start\", \"end\"] as const).map((which) => (\n              <div\n                key={which}\n                ref={which === \"start\" ? startRef : endRef}\n                role=\"slider\"\n                tabIndex={0}\n                aria-label={which === \"start\" ? \"Range start\" : \"Range end\"}\n                aria-valuemin={0}\n                aria-valuemax={n}\n                aria-valuenow={which === \"start\" ? range[0] : range[1]}\n                aria-valuetext={which === \"start\" ? firstLabel : lastLabel}\n                onKeyDown={keyMove(which)}\n                className={`absolute left-0 top-1/2 -ml-[3px] -mt-[12px] h-6 w-1.5 cursor-ew-resize rounded-full bg-background shadow-[0_0_0_1px_color-mix(in_oklab,var(--foreground)_45%,var(--border))] ${FOCUS}`}\n              />\n            ))}\n          </div>\n          <div aria-hidden=\"true\" className=\"relative mt-1.5 h-4\">\n            {ticks}\n          </div>\n\n          <p aria-live=\"polite\" className=\"sr-only\">\n            {firstLabel && lastLabel ? `${firstLabel} to ${lastLabel}: ${fmt(total)}` : \"\"}\n          </p>\n          <div className=\"sr-only\">\n            <table>\n              <caption>\n                {title}, {firstLabel} to {lastLabel}: {fmt(total)}\n              </caption>\n              {table}\n            </table>\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · range-brush · 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/range-brush. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}