import { useEffect, useId, useMemo, useRef, useState } from "react" import { area, curveMonotoneX, line } from "d3-shape" import { DAY, toTime } from "@/lib/format" import { catColor } from "@/lib/category" /** * A smooth running total from creation dates, drawn edge to edge: the area fades out downwards, * and `dots` (dates) sit on the curve. Used inside cards, so it has no axes; the card states * the numbers. */ export function Spark({ events, from, to, cat, height, dots = [], ring = "var(--card)" }: { events: [string, number][]; from: string; to: string; cat: string; height: number dots?: string[]; ring?: string }) { const id = useId().replace(/:/g, "") const box = useRef(null) const [width, setW] = useState(0) useEffect(() => { const el = box.current if (!el) return const ro = new ResizeObserver(() => setW(el.clientWidth)) ro.observe(el) return () => ro.disconnect() }, []) const g = useMemo(() => { if (!width) return null const t0 = toTime(from), t1 = Math.max(toTime(to), t0 + DAY) const ev = events.map(([d, n]) => [toTime(d), n] as const).sort((a, b) => a[0] - b[0]) const steps = 60 const pts: [number, number][] = [] let i = 0, run = 0 for (let k = 0; k <= steps; k++) { const t = t0 + ((t1 - t0) * k) / steps while (i < ev.length && ev[i][0] <= t) run += ev[i++][1] pts.push([t, run]) } const max = Math.max(1, run) const X = (t: number) => 2 + ((t - t0) / (t1 - t0)) * (width - 4) const Y = (v: number) => height - 3 - (v / max) * (height - 14) const at = (t: number) => ev.reduce((a, [et, n]) => (et <= t ? a + n : a), 0) return { fill: area<[number, number]>().x((p) => X(p[0])).y0(height).y1((p) => Y(p[1])).curve(curveMonotoneX)(pts) ?? "", stroke: line<[number, number]>().x((p) => X(p[0])).y((p) => Y(p[1])).curve(curveMonotoneX)(pts) ?? "", dots: dots.filter((d) => toTime(d) >= t0).map((d) => ({ x: X(toTime(d)), y: Y(at(toTime(d))) })), } }, [events, from, to, width, height, dots]) return (
{g && ( {g.dots.map((p, i) => ( ))} )}
) }