import { useEffect, useLayoutEffect, useRef, useState } from "react"; export interface Scales { x: (v: number) => number; y: (v: number) => number; invX: (px: number) => number; invY: (py: number) => number; left: number; right: number; top: number; bottom: number; width: number; height: number; } export interface Theme { surface: string; ink: string; ink2: string; muted: string; grid: string; axis: string; seg: string; series: string[]; } export function readTheme(el: Element): Theme { const cs = getComputedStyle(el); const v = (n: string) => cs.getPropertyValue(n).trim(); return { surface: v("--surface"), ink: v("--ink"), ink2: v("--ink2"), muted: v("--muted"), grid: v("--grid"), axis: v("--axis"), seg: v("--seg"), series: [1, 2, 3, 4, 5, 6, 7, 8].map((i) => v(`--series-${i}`)), }; } export interface PointerInfo { xv: number; yv: number; px: number; py: number; scales: Scales; } interface Props { height: number; xRange: [number, number]; yRange: [number, number]; xLog?: boolean; yLog?: boolean; xLabel: string; yLabel: string; xFormat?: (v: number) => string; yFormat?: (v: number) => string; hideXTicks?: boolean; draw: (ctx: CanvasRenderingContext2D, s: Scales, theme: Theme) => void; // returns tooltip lines for a hover position (null = no tooltip) hover?: (p: PointerInfo) => { lines: string[]; x?: number; y?: number } | null; onPointer?: (type: "down" | "move" | "up", p: PointerInfo, ev: PointerEvent) => void; onWheel?: (p: PointerInfo, ev: WheelEvent) => boolean; // true = handled (page does not scroll) onDoubleClick?: () => void; onClick?: (p: PointerInfo) => void; cursor?: (p: PointerInfo) => string; ariaLabel: string; } const PAD = { left: 64, right: 14, top: 10, bottom: 40 }; export function niceStep(range: number, target: number) { const raw = range / Math.max(1, target); const mag = 10 ** Math.floor(Math.log10(raw)); const r = raw / mag; return (r < 1.5 ? 1 : r < 3.5 ? 2 : r < 7.5 ? 5 : 10) * mag; } function linearTicks(a: number, b: number, target: number): number[] { if (!(b > a)) return [a]; const step = niceStep(b - a, target); const out: number[] = []; for (let v = Math.ceil(a / step) * step; v <= b + step * 1e-9; v += step) out.push(Math.abs(v) < step * 1e-9 ? 0 : v); return out; } function logTicks(a: number, b: number, widthPx: number): { major: number[]; minor: number[] } { const major: number[] = []; const minor: number[] = []; const decades = Math.log10(b / a); const mults = widthPx / Math.max(decades, 0.1) > 160 ? [1, 2, 5] : [1]; for (let e = Math.floor(Math.log10(a)); e <= Math.ceil(Math.log10(b)); e++) { for (let m = 1; m < 10; m++) { const v = m * 10 ** e; if (v < a * 0.9999 || v > b * 1.0001) continue; (mults.includes(m) ? major : minor).push(v); } } return { major, minor }; } export function fmtNum(v: number): string { const a = Math.abs(v); if (a >= 1000) return `${+(v / 1000).toPrecision(3)}k`; if (a === 0) return "0"; if (a < 0.01) return v.toExponential(0); return `${+v.toPrecision(3)}`; } export function CanvasPlot(props: Props) { const wrapRef = useRef(null); const canvasRef = useRef(null); const overlayRef = useRef(null); const scalesRef = useRef(null); const [width, setWidth] = useState(600); const [tip, setTip] = useState<{ lines: string[]; left: number; top: number } | null>(null); const [cursor, setCursor] = useState("crosshair"); const propsRef = useRef(props); propsRef.current = props; const [themeTick, setThemeTick] = useState(0); useLayoutEffect(() => { const el = wrapRef.current!; const ro = new ResizeObserver(() => setWidth(Math.max(200, el.clientWidth))); ro.observe(el); setWidth(Math.max(200, el.clientWidth)); const mq = matchMedia("(prefers-color-scheme: dark)"); const onScheme = () => setThemeTick((t) => t + 1); mq.addEventListener("change", onScheme); return () => { ro.disconnect(); mq.removeEventListener("change", onScheme); }; }, []); const { height, xRange, yRange, xLog, yLog } = props; useEffect(() => { const canvas = canvasRef.current!; const overlay = overlayRef.current!; const dpr = window.devicePixelRatio || 1; for (const c of [canvas, overlay]) { c.width = Math.round(width * dpr); c.height = Math.round(height * dpr); c.style.width = `${width}px`; c.style.height = `${height}px`; } const ctx = canvas.getContext("2d")!; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); const theme = readTheme(wrapRef.current!); const left = PAD.left; const right = width - PAD.right; const top = PAD.top; const bottom = height - (props.hideXTicks ? 12 : PAD.bottom); const tx = (v: number) => (xLog ? Math.log10(Math.max(v, 1e-30)) : v); const ty = (v: number) => (yLog ? Math.log10(Math.max(v, 1e-30)) : v); const [x0, x1] = [tx(xRange[0]), tx(xRange[1])]; const [y0, y1] = [ty(yRange[0]), ty(yRange[1])]; const s: Scales = { x: (v) => left + ((tx(v) - x0) / (x1 - x0)) * (right - left), y: (v) => bottom - ((ty(v) - y0) / (y1 - y0)) * (bottom - top), invX: (px) => { const u = x0 + ((px - left) / (right - left)) * (x1 - x0); return xLog ? 10 ** u : u; }, invY: (py) => { const u = y0 + ((bottom - py) / (bottom - top)) * (y1 - y0); return yLog ? 10 ** u : u; }, left, right, top, bottom, width, height, }; scalesRef.current = s; ctx.clearRect(0, 0, width, height); ctx.fillStyle = theme.surface; ctx.fillRect(0, 0, width, height); ctx.font = "11px system-ui, -apple-system, sans-serif"; ctx.lineWidth = 1; // grid + ticks const xt = xLog ? logTicks(xRange[0], xRange[1], right - left) : { major: linearTicks(xRange[0], xRange[1], (right - left) / 90), minor: [] }; const yt = yLog ? logTicks(yRange[0], yRange[1], (bottom - top) * 2) : { major: linearTicks(yRange[0], yRange[1], (bottom - top) / 40), minor: [] }; ctx.strokeStyle = theme.grid; ctx.beginPath(); for (const v of xt.major) { const px = Math.round(s.x(v)) + 0.5; ctx.moveTo(px, top); ctx.lineTo(px, bottom); } for (const v of yt.major) { const py = Math.round(s.y(v)) + 0.5; ctx.moveTo(left, py); ctx.lineTo(right, py); } ctx.stroke(); ctx.globalAlpha = 0.5; ctx.beginPath(); for (const v of xt.minor) { const px = Math.round(s.x(v)) + 0.5; ctx.moveTo(px, top); ctx.lineTo(px, bottom); } ctx.stroke(); ctx.globalAlpha = 1; ctx.save(); ctx.beginPath(); ctx.rect(left, top, right - left, bottom - top); ctx.clip(); props.draw(ctx, s, theme); ctx.restore(); ctx.strokeStyle = theme.axis; ctx.beginPath(); ctx.moveTo(left + 0.5, top); ctx.lineTo(left + 0.5, bottom + 0.5); ctx.lineTo(right, bottom + 0.5); ctx.stroke(); ctx.fillStyle = theme.muted; const xf = props.xFormat ?? fmtNum; const yf = props.yFormat ?? fmtNum; if (!props.hideXTicks) { ctx.textAlign = "center"; ctx.textBaseline = "top"; for (const v of xt.major) ctx.fillText(xf(v), s.x(v), bottom + 5); ctx.fillStyle = theme.ink2; ctx.fillText(props.xLabel, (left + right) / 2, bottom + 22); } ctx.fillStyle = theme.muted; ctx.textAlign = "right"; ctx.textBaseline = "middle"; for (const v of yt.major) ctx.fillText(yf(v), left - 6, s.y(v)); ctx.save(); ctx.translate(14, (top + bottom) / 2); ctx.rotate(-Math.PI / 2); ctx.textAlign = "center"; ctx.fillStyle = theme.ink2; ctx.fillText(props.yLabel, 0, 0); ctx.restore(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [width, height, xRange[0], xRange[1], yRange[0], yRange[1], xLog, yLog, props.draw, themeTick]); // pointer handling useEffect(() => { const el = overlayRef.current!; const info = (ev: MouseEvent): PointerInfo | null => { const s = scalesRef.current; if (!s) return null; const r = el.getBoundingClientRect(); const px = ev.clientX - r.left; const py = ev.clientY - r.top; return { xv: s.invX(px), yv: s.invY(py), px, py, scales: s }; }; const drawCrosshair = (p: PointerInfo | null, mark?: { x?: number; y?: number }) => { const ctx = el.getContext("2d")!; const dpr = window.devicePixelRatio || 1; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, el.width, el.height); if (!p) return; const s = p.scales; if (p.px < s.left || p.px > s.right || p.py < s.top || p.py > s.bottom) return; const theme = readTheme(wrapRef.current!); ctx.strokeStyle = theme.muted; ctx.setLineDash([3, 3]); ctx.beginPath(); const cx = mark?.x !== undefined ? s.x(mark.x) : p.px; ctx.moveTo(Math.round(cx) + 0.5, s.top); ctx.lineTo(Math.round(cx) + 0.5, s.bottom); ctx.stroke(); ctx.setLineDash([]); if (mark?.y !== undefined) { ctx.fillStyle = theme.surface; ctx.strokeStyle = theme.ink; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(cx, s.y(mark.y), 5, 0, 2 * Math.PI); ctx.fill(); ctx.stroke(); } }; let down = false; let downAt = { x: 0, y: 0 }; let moved = false; const onMove = (ev: PointerEvent) => { const p = info(ev); if (!p) return; const pr = propsRef.current; if (down) { if (Math.abs(ev.clientX - downAt.x) + Math.abs(ev.clientY - downAt.y) > 3) moved = true; pr.onPointer?.("move", p, ev); } else if (pr.cursor) setCursor(pr.cursor(p)); const h = pr.hover?.(p) ?? null; const s = p.scales; const inside = p.px >= s.left && p.px <= s.right && p.py >= s.top && p.py <= s.bottom; drawCrosshair(inside && !down ? p : null, h ?? undefined); if (h && inside && !down) { const w = el.clientWidth; setTip({ lines: h.lines, left: p.px > w * 0.6 ? p.px - 12 : p.px + 12, top: Math.max(4, p.py - 10) }); el.dataset.tipSide = p.px > w * 0.6 ? "left" : "right"; } else setTip(null); }; const onDown = (ev: PointerEvent) => { const p = info(ev); if (!p || !propsRef.current.onPointer) return; down = true; downAt = { x: ev.clientX, y: ev.clientY }; moved = false; el.setPointerCapture(ev.pointerId); propsRef.current.onPointer("down", p, ev); }; const onUp = (ev: PointerEvent) => { const p = info(ev); if (down && p) propsRef.current.onPointer?.("up", p, ev); down = false; }; const onLeave = () => { if (!down) { drawCrosshair(null); setTip(null); } }; const onWheel = (ev: WheelEvent) => { const p = info(ev); if (!p || !propsRef.current.onWheel) return; if (propsRef.current.onWheel(p, ev)) ev.preventDefault(); }; const onDbl = () => propsRef.current.onDoubleClick?.(); const onClick = (ev: MouseEvent) => { const p = info(ev); if (p && !moved) propsRef.current.onClick?.(p); moved = false; }; el.addEventListener("pointermove", onMove); el.addEventListener("pointerdown", onDown); el.addEventListener("pointerup", onUp); el.addEventListener("pointerleave", onLeave); el.addEventListener("wheel", onWheel, { passive: false }); el.addEventListener("dblclick", onDbl); el.addEventListener("click", onClick); return () => { el.removeEventListener("pointermove", onMove); el.removeEventListener("pointerdown", onDown); el.removeEventListener("pointerup", onUp); el.removeEventListener("pointerleave", onLeave); el.removeEventListener("wheel", onWheel); el.removeEventListener("dblclick", onDbl); el.removeEventListener("click", onClick); }; }, []); return (
{tip && (
{tip.lines.map((l, i) => (
{l}
))}
)}
); } // ---------- drawing helpers ---------- export function drawLine( ctx: CanvasRenderingContext2D, s: Scales, xs: ArrayLike, ys: ArrayLike, color: string, width = 2, dash: number[] = [], ) { ctx.strokeStyle = color; ctx.lineWidth = width; ctx.lineJoin = "round"; ctx.setLineDash(dash); ctx.beginPath(); let pen = false; for (let i = 0; i < xs.length; i++) { const y = ys[i]; if (!Number.isFinite(y)) { pen = false; continue; } const px = s.x(xs[i]); const py = s.y(y); if (pen) ctx.lineTo(px, py); else ctx.moveTo(px, py); pen = true; } ctx.stroke(); ctx.setLineDash([]); } export type MarkerShape = "circle" | "square" | "triangle" | "diamond" | "cross"; export const SHAPES: MarkerShape[] = ["circle", "square", "triangle", "diamond", "cross"]; export function drawMarker( ctx: CanvasRenderingContext2D, px: number, py: number, shape: MarkerShape, color: string, ring: string, r = 5, ) { ctx.beginPath(); if (shape === "circle") ctx.arc(px, py, r, 0, 2 * Math.PI); else if (shape === "square") ctx.rect(px - r * 0.9, py - r * 0.9, r * 1.8, r * 1.8); else if (shape === "triangle") { ctx.moveTo(px, py - r * 1.15); ctx.lineTo(px + r * 1.05, py + r * 0.75); ctx.lineTo(px - r * 1.05, py + r * 0.75); ctx.closePath(); } else if (shape === "diamond") { ctx.moveTo(px, py - r * 1.25); ctx.lineTo(px + r * 1.05, py); ctx.lineTo(px, py + r * 1.25); ctx.lineTo(px - r * 1.05, py); ctx.closePath(); } else { const k = r * 0.45; ctx.moveTo(px - k, py - r); ctx.lineTo(px + k, py - r); ctx.lineTo(px + k, py - k); ctx.lineTo(px + r, py - k); ctx.lineTo(px + r, py + k); ctx.lineTo(px + k, py + k); ctx.lineTo(px + k, py + r); ctx.lineTo(px - k, py + r); ctx.lineTo(px - k, py + k); ctx.lineTo(px - r, py + k); ctx.lineTo(px - r, py - k); ctx.lineTo(px - k, py - k); ctx.closePath(); } ctx.fillStyle = color; ctx.fill(); ctx.strokeStyle = ring; ctx.lineWidth = 2; ctx.stroke(); }