"use client";import * as React from "react";import { NumberRoll } from "./number-roll";import { createSpring, type Spring } from "./ui-interaction-motion";/* ───────────────────────────────────────────────────────── * LENS BARS: a year of days in one card, and a lens to read them * * arrive the first time it's on screen the bars grow out of * the baseline in a wave from the left, the total rolls * point the pointer is a lens: the bars under it spread apart * and widen (the one you're on to about 18px) while the * rest of the year squeezes aside, so a single day out of * 365 is easy to land on. The day under the pointer never * moves, the bars nearest it light up, and the readout * above rolls to its figure * sweep bars you pass stay lit for a moment and fade back one * after another, a short trail of where you've been * leave the lens relaxes and the year lies flat again (0.3s) * data new figures ease each bar to its new height in a wave * running out from the day you last read * * Drawn on one canvas, so 365 or 3,650 bars cost the same: the lens * is two springs (where, how open) and one pure layout function. * The plot is one tab stop; arrow keys move a day, Shift a week. * ───────────────────────────────────────────────────────── */export interface LensBarsDatum { /** Unique, e.g. "2026-03-14". */ key: string; value: number; /** In the readout, e.g. "Sat, 14 Mar". */ label: string; /** A tick under this bar, e.g. "Mar" on the first of each month. */ tick?: string;}export interface LensBarsProps extends React.HTMLAttributes<HTMLDivElement> { data: LensBarsDatum[]; title?: string; /** Under the total, e.g. "Last 365 days". */ caption?: string; /** The figure in the header. Defaults to the sum of the data. */ total?: number; format?: Intl.NumberFormatOptions; locales?: string | string[]; /** Any CSS colour. Defaults to your first chart colour. */ color?: string; /** Called when the day under the lens changes, with null when it closes. */ onActiveChange?: (datum: LensBarsDatum | null, index: number | null) => void;}const EASE = "cubic-bezier(0.16,1,0.3,1)";const FOCUS = "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40";const LENS_SLOT = 15; // the day under the lens, in pxconst LENS_REACH = 8; // how many days either side the lens reachesconst TRAIL = 0.45; // seconds for a passed bar to fade backconst LINE = 2; // every bar is a stack of 2px hairlines…const PITCH = 4; // …one every 4px, counted up from the baselineconst LEVELS = 16; // light is drawn in this many steps, one path each, so neighbouring bars never seamconst HEADROOM = 34; // above the tallest bar, for the readoutconst 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);/** A round top for the scale: 4,820 → 5,000. */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 SOFT = 1.5; // device px: the filter squeezed days are drawn through/** The share of a tent of radius SOFT, centred on 0, that lies left of `x`. */function tentArea(x: number) { if (x <= -SOFT) return 0; if (x >= SOFT) return SOFT; return x <= 0 ? (x + SOFT) ** 2 / (2 * SOFT) : SOFT - (SOFT - x) ** 2 / (2 * SOFT);}const easeOut = (t: number) => 1 - (1 - t) ** 3;const clamp01 = (t: number) => (t < 0 ? 0 : t > 1 ? 1 : t);/** * Where every bar's edges go with the lens at `focus` (px), open by `open` (0–1). Days near the focus are weighted up to * `zoom` times, then each side of the focus is scaled back into the space it had, so the day under the pointer stays put. * Writes n + 1 edges into `edges` and each bar's closeness to the focus (0–1) into `near`. */function lensLayout(n: number, width: number, focus: number, open: number, zoom: number, edges: Float32Array, near: Float32Array) { const slot = width / n; const reach = LENS_REACH * slot; let acc = 0; edges[0] = 0; for (let i = 0; i < n; i++) { const d = Math.abs((i + 0.5) * slot - focus) / reach; const g = d < 1 ? (1 - d * d) ** 2 : 0; near[i] = g; acc += slot * (1 + (zoom - 1) * open * g); edges[i + 1] = acc; } if (open <= 0.0001) { for (let i = 0; i <= n; i++) edges[i] = i * slot; return; } const at = Math.min(Math.max(focus / slot, 0), n - 1e-6); const i0 = Math.floor(at); const pivot = edges[i0] + (at - i0) * (edges[i0 + 1] - edges[i0]); const left = pivot > 0 ? focus / pivot : 1; const right = acc - pivot > 0 ? (width - focus) / (acc - pivot) : 1; for (let i = 0; i <= n; i++) { const x = edges[i]; edges[i] = x <= pivot ? x * left : focus + (x - pivot) * right; }}export function LensBars({ data, title = "Signups", caption, total, format, locales, color = "var(--chart-1, var(--primary))", onActiveChange, className = "", ...props}: LensBarsProps) { const reduced = useReducedMotion(); const hydrated = useHydrated(); const locale = locales ?? (hydrated ? undefined : "en-US"); const n = data.length; const sum = total ?? data.reduce((s, d) => s + d.value, 0); const max = niceMax(Math.max(0, ...data.map((d) => d.value))); const [active, setActive] = React.useState<number | null>(null); const [keyboard, setKeyboard] = React.useState(false); const [visible, setVisible] = React.useState(false); 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 tagRef = React.useRef<HTMLDivElement>(null); const stemRef = React.useRef<HTMLDivElement>(null); const tickRefs = React.useRef<(HTMLSpanElement | null)[]>([]); const onActiveRef = React.useRef(onActiveChange); React.useEffect(() => { onActiveRef.current = onActiveChange; }); // Everything the frame loop reads lives here, so pointer moves never re-render the chart. const engine = React.useRef<{ width: number; height: number; dpr: number; edges: Float32Array; near: Float32Array; heat: Float32Array; colH: Float32Array; colHeat: Float32Array; colCov: Float32Array; from: Float32Array; to: Float32Array; changedAt: number; changeOrigin: number; bornAt: number; lastPaint: number; frame: number; accent: string; ink: string; tagWidth: number; active: number | null; open: Spring | null; focus: Spring | null; reduced: boolean; paint: () => void; } | null>(null); const paint = React.useCallback(() => { const e = engine.current; const canvas = canvasRef.current; if (!e || !canvas) return; const ctx = canvas.getContext("2d"); if (!ctx || !e.width || !e.height) return; const count = e.to.length; if (!count) return; const now = performance.now(); const dt = e.lastPaint ? Math.min((now - e.lastPaint) / 1000, 0.1) : 0; e.lastPaint = now; const open = e.open?.get() ?? 0; const focus = e.focus?.get() ?? 0; const slot = e.width / count; const zoom = Math.max(1, LENS_SLOT / slot); lensLayout(count, e.width, focus, open, zoom, e.edges, e.near); const plotH = e.height - HEADROOM; const decay = e.reduced ? 0 : Math.exp(-dt / TRAIL); let busy = false; ctx.setTransform(e.dpr, 0, 0, e.dpr, 0, 0); ctx.clearRect(0, 0, e.width, e.height); ctx.fillStyle = e.accent; const grown = e.bornAt ? now - e.bornAt : 0; const changed = now - e.changedAt; // Work out every bar first, then draw in a few paths: the whole series once at its resting light, then the lit bars // in steps of light. Days narrower than 4px are not drawn as bars: each device pixel column takes the average of the // days near it, weighted through a soft 1.5px filter. Slivers, and bars touching at fractional edges, would flip // on and off every frame as the lens slides them; filtered columns change only as smoothly as the layout does. Wider // bars open their gaps gradually from there. // The rest of the year dims only a little while the lens is open, so opening it never flashes the whole chart. const base = 0.55 * (1 - 0.2 * open); const cols = Math.ceil(e.width * e.dpr); if (e.colH.length !== cols) { e.colH = new Float32Array(cols); e.colHeat = new Float32Array(cols); e.colCov = new Float32Array(cols); } else { e.colH.fill(0); e.colHeat.fill(0); e.colCov.fill(0); } const levels: Path2D[] = Array.from({ length: LEVELS }, () => new Path2D()); const rest = new Path2D(); const bar = (path: Path2D, x: number, y: number, w: number, h: number) => { if (w >= 4) path.roundRect(x, y, w, h, [Math.min(3, w / 2), Math.min(3, w / 2), 0, 0]); else path.rect(x, y, w, h); }; for (let i = 0; i < count; i++) { // Arrival: a wave from the left. A change of data: a wave out from the last day read. const born = e.reduced ? 1 : e.bornAt ? easeOut(clamp01((grown - (i / count) * 520) / 640)) : 0; const wait = (Math.abs(i - e.changeOrigin) / count) * 280; const t = e.reduced ? 1 : easeOut(clamp01((changed - wait) / 520)); const value = e.from[i] + (e.to[i] - e.from[i]) * t; if (born < 1 || t < 1) busy = true; // Light falls off smoothly from the lens's centre, and what it passed keeps some for a moment. const lit = open * e.near[i] ** 1.6; const heat = Math.max(lit, e.heat[i] * decay); e.heat[i] = heat; if (heat > 0.004 && heat !== lit) busy = true; const x0 = e.edges[i]; const x1 = e.edges[i + 1]; const span = x1 - x0; const h = Math.max(value > 0 ? LINE : 0, value * plotH * born); if (span < 4) { const a = x0 * e.dpr; const b = x1 * e.dpr; const last = Math.min(cols - 1, Math.ceil(b + SOFT)); for (let c = Math.max(0, Math.floor(a - SOFT)); c <= last; c++) { const cover = tentArea(b - c - 0.5) - tentArea(a - c - 0.5); if (cover <= 0) continue; e.colH[c] += h * cover; e.colHeat[c] += heat * cover; e.colCov[c] += cover; } continue; } // The gap opens from nothing where columns hand over to bars, so no day pops, and stops at 2px: enough to tell // days apart, too little to strobe as the comb slides under the lens. const gap = Math.min(2, (span - 4) * 0.25); const w = Math.min(12, span - gap); const x = (x0 + x1) / 2 - w / 2; const right = x + w; bar(rest, x, e.height - h, Math.max(right - x, 1 / e.dpr), h); const level = Math.round(heat * LEVELS); if (level > 0) bar(levels[level - 1], x, e.height - h, Math.max(right - x, 1 / e.dpr), h); } for (let c = 0; c < cols; c++) { const cover = e.colCov[c]; if (cover <= 0.01) continue; const h = e.colH[c] / cover; if (h <= 0) continue; rest.rect(c / e.dpr, e.height - h, 1 / e.dpr, h); const level = Math.round((e.colHeat[c] / cover) * LEVELS); if (level > 0) levels[level - 1].rect(c / e.dpr, e.height - h, 1 / e.dpr, h); } // The mark: everything is drawn through a rule of hairlines, so a bar is a stack of lines and the plot behind it is // the same lines, faint. Lines are counted from the baseline and land on device pixels, so they stay crisp. const rule = new Path2D(); for (let k = 0; ; k++) { const y = Math.round((e.height - LINE - k * PITCH) * e.dpr) / e.dpr; if (y < HEADROOM - 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, HEADROOM, e.width, e.height - HEADROOM); ctx.fillStyle = e.accent; ctx.globalAlpha = base; ctx.fill(rest); for (let l = 0; l < LEVELS; l++) { // Over the resting fill at `base`, a layer at `heat` brings the bar to base + heat × (1 − base). ctx.globalAlpha = (l + 1) / LEVELS; ctx.fill(levels[l]); } ctx.restore(); ctx.globalAlpha = 1; // The readout rides the top of the plot over the day under the lens, a hairline stem down to its bar. const tag = tagRef.current; const stem = stemRef.current; if (tag && stem && e.active !== null) { const i = e.active; const cx = (e.edges[i] + e.edges[i + 1]) / 2; const half = e.tagWidth / 2; const tx = Math.min(Math.max(cx, half), e.width - half); tag.style.transform = `translate3d(${tx - half}px,0,0)`; const value = e.to[i]; const top = e.height - value * plotH; const stemTop = 28; stem.style.transform = `translate3d(${cx - 0.5}px,${stemTop}px,0) scaleY(${Math.max(0, top - stemTop - 4)})`; } if (tag) tag.style.opacity = String(open); if (stem) stem.style.opacity = String(open * 0.9); // Ticks follow their bars through the lens and fade as the squeeze crowds them onto a neighbour, never blinking. let lastTick = -Infinity; for (let i = 0; i < count; i++) { const el = tickRefs.current[i]; if (!el) continue; const cx = Math.min(Math.max((e.edges[i] + e.edges[i + 1]) / 2, 12), e.width - 12); el.style.transform = `translate3d(${cx}px,0,0) translateX(-50%)`; el.style.opacity = String(clamp01((cx - lastTick - 22) / 12)); lastTick = cx; } if (busy && !e.frame) { e.frame = requestAnimationFrame(() => { const next = engine.current; if (!next) return; next.frame = 0; next.paint(); }); } if (!busy) e.lastPaint = 0; }, []); // Build the engine once, before the layout effects below that size and fill it; springs paint through it. React.useLayoutEffect(() => { const e = { width: 0, height: 0, dpr: 1, edges: new Float32Array(1), near: new Float32Array(0), heat: new Float32Array(0), colH: new Float32Array(0), colHeat: new Float32Array(0), colCov: new Float32Array(0), from: new Float32Array(0), to: new Float32Array(0), changedAt: 0, changeOrigin: 0, bornAt: 0, lastPaint: 0, frame: 0, accent: "currentColor", ink: "currentColor", tagWidth: 0, active: null as number | null, open: null as Spring | null, focus: null as Spring | null, reduced: false, paint, }; e.open = createSpring(0, { stiffness: 420, damping: 41 }, paint, 0.001); e.focus = createSpring(0, { stiffness: 1500, damping: 78 }, paint, 0.05); engine.current = e; return () => { e.open?.stop(); e.focus?.stop(); if (e.frame) cancelAnimationFrame(e.frame); e.frame = 0; engine.current = null; }; }, [paint]); // New data: heights ease from where they are, out from the last day read. React.useLayoutEffect(() => { const e = engine.current; if (!e) return; const next = new Float32Array(data.map((d) => Math.max(0, d.value) / max)); if (e.to.length === next.length) { const now = performance.now(); const changed = now - e.changedAt; // Start from where each bar is now, even mid-ease. for (let i = 0; i < next.length; i++) { const wait = (Math.abs(i - e.changeOrigin) / next.length) * 280; const t = easeOut(clamp01((changed - wait) / 520)); e.from[i] = e.from[i] + (e.to[i] - e.from[i]) * t; } e.changeOrigin = e.active ?? Math.round(((e.focus?.get() ?? 0) / Math.max(1, e.width)) * next.length); e.changedAt = now; e.to = next; } else { e.from = next.slice(); e.to = next; e.edges = new Float32Array(next.length + 1); e.near = new Float32Array(next.length); e.heat = new Float32Array(next.length); e.changedAt = 0; } paint(); }, [data, max, paint]); React.useEffect(() => { const e = engine.current; if (!e) return; e.reduced = reduced; if (reduced) { e.open?.jump(e.open.getTarget()); e.focus?.jump(e.focus.getTarget()); } }, [reduced]); // Size the canvas to its box at the screen's pixel density. 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); 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.useLayoutEffect(() => { const tag = tagRef.current; if (!tag) return; const measure = () => { if (engine.current) engine.current.tagWidth = tag.offsetWidth; paint(); }; measure(); const observer = new ResizeObserver(measure); observer.observe(tag); return () => observer.disconnect(); }, [paint]); // The canvas takes the theme's colours: read them, and again whenever the theme changes. React.useEffect(() => { const probe = probeRef.current; if (!probe) return; const read = () => { const e = engine.current; if (!e) return; e.accent = getComputedStyle(probe).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]); // Grow in the first time it's seen. 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 aim = React.useCallback( (index: number | null, x?: number) => { const e = engine.current; if (!e) return; if (index === null) { e.open?.set(0); } else { // The lens follows the pointer and the keys through one stiff spring, a few milliseconds behind: touch events // arrive unevenly, and a lens pinned to each one jerks the whole comb of bars. A lens opening from shut starts // where it is aimed. const slot = e.width / Math.max(1, n); const to = x ?? (index + 0.5) * slot; const shut = (e.open?.getTarget() ?? 0) === 0 && (e.open?.get() ?? 0) < 0.05; if (shut) e.focus?.jump(to); else e.focus?.set(to); e.open?.set(1); } if (index !== e.active) { if (index !== null) e.active = index; setActive(index); onActiveRef.current?.(index === null ? null : data[index], index); } paint(); }, [data, n, paint], ); const indexAt = (clientX: number) => { const plot = plotRef.current; if (!plot || !n) return null; const r = plot.getBoundingClientRect(); const x = Math.min(Math.max(clientX - r.left, 0), r.width - 0.01); return { index: Math.min(n - 1, Math.floor((x / r.width) * n)), x }; }; // A finger lifts and the lens stays on that day until the next tap somewhere else. const sticky = React.useRef(false); React.useEffect(() => { if (active === null) return; const away = (ev: PointerEvent) => { if (!sticky.current || plotRef.current?.contains(ev.target as Node)) return; sticky.current = false; aim(null); }; document.addEventListener("pointerdown", away); return () => document.removeEventListener("pointerdown", away); }, [active, aim]); const onKeyDown = (ev: React.KeyboardEvent) => { if (!n) return; const from = active ?? n - 1; const step = ev.shiftKey ? 7 : 1; const moves: Record<string, number> = { ArrowLeft: from - step, ArrowRight: from + step, Home: 0, End: n - 1, PageUp: from - 30, PageDown: from + 30 }; if (ev.key === "Escape") { aim(null); return; } if (!(ev.key in moves)) return; ev.preventDefault(); setKeyboard(true); aim(Math.min(n - 1, Math.max(0, active === null ? from : moves[ev.key]))); }; const fmt = (v: number) => new Intl.NumberFormat(locale, format).format(v); const shown = active !== null ? data[active] : null; // The strip under the plot: what a year of days is usually asked first. const average = n ? data.reduce((s, d) => s + d.value, 0) / n : 0; const best = data.reduce((b, d, i) => (d.value > (data[b]?.value ?? -Infinity) ? i : b), 0); const recent = data.slice(-30).reduce((s, d) => s + d.value, 0); const before = data.slice(-60, -30).reduce((s, d) => s + d.value, 0); const trend = n >= 60 && before ? (recent - before) / before : null; const rounded = { ...format, maximumFractionDigits: 0 }; return ( <div ref={rootRef} className={`w-full rounded-[22px] bg-background shadow-[0_0_0_1px_var(--border)] ${className}`} {...props} > {/* 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"> <span ref={probeRef} aria-hidden="true" className="hidden" style={{ color }} /> <span ref={inkRef} aria-hidden="true" className="hidden text-foreground" /> <div className="p-4 @md:p-5 [--plot:150px] @md:[--plot:184px]"> <p className="text-[12px] text-muted-foreground @md:text-[13px]">{title}</p> <p className="mt-0.5 text-[22px] font-medium leading-tight tracking-[-0.03em] text-foreground tabular-nums @md:text-[26px]"> <NumberRoll value={visible ? sum : 0} format={format} locales={locale} duration={1000} /> </p> {caption && <p className="mt-0.5 text-[11.5px] text-muted-foreground @md:text-[12.5px]">{caption}</p>} <div ref={plotRef} role="group" tabIndex={0} aria-label={`${title}, ${n} days. Use the arrow keys to read each day, Shift to move a week.`} onKeyDown={onKeyDown} onBlur={() => { if (keyboard) { setKeyboard(false); aim(null); } }} onPointerMove={(ev) => { if (ev.pointerType === "touch" && ev.buttons === 0) return; const hit = indexAt(ev.clientX); if (!hit) return; setKeyboard(false); aim(hit.index, hit.x); }} onPointerDown={(ev) => { const hit = indexAt(ev.clientX); if (!hit) return; if (ev.pointerType !== "mouse") sticky.current = true; aim(hit.index, hit.x); }} onPointerLeave={(ev) => { if (ev.pointerType === "mouse") aim(null); }} className={`relative mt-4 cursor-crosshair touch-pan-y select-none rounded-lg @md:mt-5 ${FOCUS}`} > <canvas ref={canvasRef} aria-hidden="true" className="block w-full" style={{ height: "calc(var(--plot) + 34px)" }} /> <div aria-hidden="true" className="absolute inset-x-0 bottom-0 border-t border-border" /> <div ref={stemRef} aria-hidden="true" className="pointer-events-none absolute left-0 top-0 h-px w-px origin-top bg-foreground/40" style={{ opacity: 0 }} /> <div ref={tagRef} aria-hidden="true" className="pointer-events-none absolute left-0 top-0 flex h-[24px] items-center gap-1.5 whitespace-nowrap rounded-full bg-background px-2.5 text-[11.5px] shadow-[0_0_0_1px_var(--border)]" style={{ opacity: 0 }} > <span className="text-muted-foreground"> {shown?.label ?? " "} </span> <span className="font-medium tabular-nums text-foreground"> {shown ? fmt(shown.value) : " "} </span> </div> </div> <div aria-hidden="true" className="relative mt-1.5 h-4 overflow-hidden"> {data.map((d, i) => d.tick ? ( <span key={d.key} ref={(el) => { tickRefs.current[i] = el; }} className="absolute left-0 top-0 whitespace-nowrap text-[10.5px] leading-4 text-muted-foreground" style={{ transition: reduced ? "none" : `opacity 200ms ${EASE}` }} > {d.tick} </span> ) : null, )} </div> <div className="mt-3 grid grid-cols-3 gap-3 border-t border-border pt-3 @md:mt-4 @md:pt-4"> <div className="min-w-0"> <p className="truncate text-[11px] text-muted-foreground @md:text-[12px]">Daily average</p> <p className="mt-0.5 text-[15px] font-medium tracking-[-0.02em] text-foreground tabular-nums @md:text-[17px]"> <NumberRoll value={visible ? average : 0} format={rounded} locales={locale} duration={900} /> </p> </div> {/* Pointing at the best day opens the lens on it. */} <button type="button" onPointerEnter={(ev) => ev.pointerType === "mouse" && aim(best)} onPointerLeave={(ev) => ev.pointerType === "mouse" && aim(null)} onFocus={() => aim(best)} onBlur={() => aim(null)} onClick={() => { sticky.current = true; aim(best); }} className={`min-w-0 cursor-pointer rounded-md text-left ${FOCUS}`} > <span className="block truncate text-[11px] text-muted-foreground @md:text-[12px]">Best day · {data[best]?.label}</span> <span className="mt-0.5 block text-[15px] font-medium tracking-[-0.02em] text-foreground tabular-nums @md:text-[17px]"> <NumberRoll value={visible ? (data[best]?.value ?? 0) : 0} format={format} locales={locale} duration={900} /> </span> </button> <div className="min-w-0"> <p className="truncate text-[11px] text-muted-foreground @md:text-[12px]">Last 30 days</p> <p className="mt-0.5 flex flex-wrap items-center gap-x-1.5 text-[15px] font-medium tracking-[-0.02em] text-foreground tabular-nums @md:text-[17px]"> <NumberRoll value={visible ? recent : 0} format={format} locales={locale} duration={900} /> {trend !== null && ( <span className={`inline-flex items-center gap-0.5 rounded-full px-1.5 py-px text-[11px] font-medium tracking-normal @md:text-[11.5px] ${ trend >= 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-2.5" style={{ transform: trend >= 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.6" strokeLinecap="round" strokeLinejoin="round" /> </svg> <span className="sr-only">{trend >= 0 ? "up" : "down"}</span> {new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 0 }).format(Math.abs(trend))} </span> )} </p> </div> </div> <p aria-live="polite" className="sr-only"> {keyboard && shown ? `${shown.label}: ${fmt(shown.value)}` : ""} </p> <div className="sr-only"><table> <caption> {title}: {fmt(sum)} </caption> <tbody> {data.map((d) => ( <tr key={d.key}> <th scope="row">{d.label}</th> <td>{fmt(d.value)}</td> </tr> ))} </tbody> </table></div> </div> </div> </div> );}