saladday1's picture
code: sync from git
2471af3 verified
Raw History Blame
2.89 kB
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<HTMLDivElement>(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 (
<div ref={box} className="w-full" style={{ height }}>
{g && (
<svg width={width} height={height} aria-hidden className="block overflow-visible">
<defs>
<linearGradient id={`sp-${id}`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0" style={{ stopColor: catColor(cat), stopOpacity: 0.42 }} />
<stop offset="1" style={{ stopColor: catColor(cat), stopOpacity: 0 }} />
</linearGradient>
</defs>
<path d={g.fill} fill={`url(#sp-${id})`} />
<path d={g.stroke} fill="none" stroke={catColor(cat)} strokeWidth={2} />
{g.dots.map((p, i) => (
<circle key={i} cx={p.x} cy={p.y} r={4.5} fill={catColor(cat)} stroke={ring} strokeWidth={2} />
))}
</svg>
)}
</div>
)
}