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