/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / components / CanvasPlot.tsx
457 lines · 14.2 KBCodeBlameHistory
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 1import { useEffect, useLayoutEffect, useRef, useState } from "react";
3export interface Scales {
4 x: (v: number) => number;
5 y: (v: number) => number;
6 invX: (px: number) => number;
7 invY: (py: number) => number;
8 left: number;
9 right: number;
10 top: number;
11 bottom: number;
12 width: number;
13 height: number;
16export interface Theme {
17 surface: string;
18 ink: string;
19 ink2: string;
20 muted: string;
21 grid: string;
22 axis: string;
23 seg: string;
24 series: string[];
27export function readTheme(el: Element): Theme {
28 const cs = getComputedStyle(el);
29 const v = (n: string) => cs.getPropertyValue(n).trim();
30 return {
31 surface: v("--surface"),
32 ink: v("--ink"),
33 ink2: v("--ink2"),
34 muted: v("--muted"),
35 grid: v("--grid"),
36 axis: v("--axis"),
37 seg: v("--seg"),
38 series: [1, 2, 3, 4, 5, 6, 7, 8].map((i) => v(`--series-${i}`)),
39 };
42export interface PointerInfo {
43 xv: number;
44 yv: number;
45 px: number;
46 py: number;
47 scales: Scales;
50interface Props {
51 height: number;
52 xRange: [number, number];
53 yRange: [number, number];
54 xLog?: boolean;
55 yLog?: boolean;
56 xLabel: string;
57 yLabel: string;
58 xFormat?: (v: number) => string;
59 yFormat?: (v: number) => string;
60 hideXTicks?: boolean;
61 draw: (ctx: CanvasRenderingContext2D, s: Scales, theme: Theme) => void;
62 // returns tooltip lines for a hover position (null = no tooltip)
63 hover?: (p: PointerInfo) => { lines: string[]; x?: number; y?: number } | null;
64 onPointer?: (type: "down" | "move" | "up", p: PointerInfo, ev: PointerEvent) => void;
65 onWheel?: (p: PointerInfo, ev: WheelEvent) => void;
66 onDoubleClick?: () => void;
67 onClick?: (p: PointerInfo) => void;
68 cursor?: (p: PointerInfo) => string;
69 ariaLabel: string;
72const PAD = { left: 64, right: 14, top: 10, bottom: 40 };
74export function niceStep(range: number, target: number) {
75 const raw = range / Math.max(1, target);
76 const mag = 10 ** Math.floor(Math.log10(raw));
77 const r = raw / mag;
78 return (r < 1.5 ? 1 : r < 3.5 ? 2 : r < 7.5 ? 5 : 10) * mag;
81function linearTicks(a: number, b: number, target: number): number[] {
82 if (!(b > a)) return [a];
83 const step = niceStep(b - a, target);
84 const out: number[] = [];
85 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);
86 return out;
89function logTicks(a: number, b: number, widthPx: number): { major: number[]; minor: number[] } {
90 const major: number[] = [];
91 const minor: number[] = [];
92 const decades = Math.log10(b / a);
93 const mults = widthPx / Math.max(decades, 0.1) > 160 ? [1, 2, 5] : [1];
94 for (let e = Math.floor(Math.log10(a)); e <= Math.ceil(Math.log10(b)); e++) {
95 for (let m = 1; m < 10; m++) {
96 const v = m * 10 ** e;
97 if (v < a * 0.9999 || v > b * 1.0001) continue;
98 (mults.includes(m) ? major : minor).push(v);
99 }
100 }
101 return { major, minor };
104export function fmtNum(v: number): string {
105 const a = Math.abs(v);
106 if (a >= 1000) return `${+(v / 1000).toPrecision(3)}k`;
107 if (a === 0) return "0";
108 if (a < 0.01) return v.toExponential(0);
109 return `${+v.toPrecision(3)}`;
112export function CanvasPlot(props: Props) {
113 const wrapRef = useRef<HTMLDivElement>(null);
114 const canvasRef = useRef<HTMLCanvasElement>(null);
115 const overlayRef = useRef<HTMLCanvasElement>(null);
116 const scalesRef = useRef<Scales | null>(null);
117 const [width, setWidth] = useState(600);
118 const [tip, setTip] = useState<{ lines: string[]; left: number; top: number } | null>(null);
119 const [cursor, setCursor] = useState("crosshair");
120 const propsRef = useRef(props);
121 propsRef.current = props;
122 const [themeTick, setThemeTick] = useState(0);
124 useLayoutEffect(() => {
125 const el = wrapRef.current!;
126 const ro = new ResizeObserver(() => setWidth(Math.max(200, el.clientWidth)));
127 ro.observe(el);
128 setWidth(Math.max(200, el.clientWidth));
129 const mq = matchMedia("(prefers-color-scheme: dark)");
130 const onScheme = () => setThemeTick((t) => t + 1);
131 mq.addEventListener("change", onScheme);
132 return () => {
133 ro.disconnect();
134 mq.removeEventListener("change", onScheme);
135 };
136 }, []);
138 const { height, xRange, yRange, xLog, yLog } = props;
140 useEffect(() => {
141 const canvas = canvasRef.current!;
142 const overlay = overlayRef.current!;
143 const dpr = window.devicePixelRatio || 1;
144 for (const c of [canvas, overlay]) {
145 c.width = Math.round(width * dpr);
146 c.height = Math.round(height * dpr);
147 c.style.width = `${width}px`;
148 c.style.height = `${height}px`;
149 }
150 const ctx = canvas.getContext("2d")!;
151 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
152 const theme = readTheme(wrapRef.current!);
153 const left = PAD.left;
154 const right = width - PAD.right;
155 const top = PAD.top;
156 const bottom = height - (props.hideXTicks ? 12 : PAD.bottom);
157 const tx = (v: number) => (xLog ? Math.log10(Math.max(v, 1e-30)) : v);
158 const ty = (v: number) => (yLog ? Math.log10(Math.max(v, 1e-30)) : v);
159 const [x0, x1] = [tx(xRange[0]), tx(xRange[1])];
160 const [y0, y1] = [ty(yRange[0]), ty(yRange[1])];
161 const s: Scales = {
162 x: (v) => left + ((tx(v) - x0) / (x1 - x0)) * (right - left),
163 y: (v) => bottom - ((ty(v) - y0) / (y1 - y0)) * (bottom - top),
164 invX: (px) => {
165 const u = x0 + ((px - left) / (right - left)) * (x1 - x0);
166 return xLog ? 10 ** u : u;
167 },
168 invY: (py) => {
169 const u = y0 + ((bottom - py) / (bottom - top)) * (y1 - y0);
170 return yLog ? 10 ** u : u;
171 },
172 left,
173 right,
174 top,
175 bottom,
176 width,
177 height,
178 };
179 scalesRef.current = s;
181 ctx.clearRect(0, 0, width, height);
182 ctx.fillStyle = theme.surface;
183 ctx.fillRect(0, 0, width, height);
184 ctx.font = "11px system-ui, -apple-system, sans-serif";
185 ctx.lineWidth = 1;
187 // grid + ticks
188 const xt = xLog ? logTicks(xRange[0], xRange[1], right - left) : { major: linearTicks(xRange[0], xRange[1], (right - left) / 90), minor: [] };
189 const yt = yLog ? logTicks(yRange[0], yRange[1], (bottom - top) * 2) : { major: linearTicks(yRange[0], yRange[1], (bottom - top) / 40), minor: [] };
190 ctx.strokeStyle = theme.grid;
191 ctx.beginPath();
192 for (const v of xt.major) {
193 const px = Math.round(s.x(v)) + 0.5;
194 ctx.moveTo(px, top);
195 ctx.lineTo(px, bottom);
196 }
197 for (const v of yt.major) {
198 const py = Math.round(s.y(v)) + 0.5;
199 ctx.moveTo(left, py);
200 ctx.lineTo(right, py);
201 }
202 ctx.stroke();
203 ctx.globalAlpha = 0.5;
204 ctx.beginPath();
205 for (const v of xt.minor) {
206 const px = Math.round(s.x(v)) + 0.5;
207 ctx.moveTo(px, top);
208 ctx.lineTo(px, bottom);
209 }
210 ctx.stroke();
211 ctx.globalAlpha = 1;
213 ctx.save();
214 ctx.beginPath();
215 ctx.rect(left, top, right - left, bottom - top);
216 ctx.clip();
217 props.draw(ctx, s, theme);
218 ctx.restore();
220 ctx.strokeStyle = theme.axis;
221 ctx.beginPath();
222 ctx.moveTo(left + 0.5, top);
223 ctx.lineTo(left + 0.5, bottom + 0.5);
224 ctx.lineTo(right, bottom + 0.5);
225 ctx.stroke();
227 ctx.fillStyle = theme.muted;
228 const xf = props.xFormat ?? fmtNum;
229 const yf = props.yFormat ?? fmtNum;
230 if (!props.hideXTicks) {
231 ctx.textAlign = "center";
232 ctx.textBaseline = "top";
233 for (const v of xt.major) ctx.fillText(xf(v), s.x(v), bottom + 5);
234 ctx.fillStyle = theme.ink2;
235 ctx.fillText(props.xLabel, (left + right) / 2, bottom + 22);
236 }
237 ctx.fillStyle = theme.muted;
238 ctx.textAlign = "right";
239 ctx.textBaseline = "middle";
240 for (const v of yt.major) ctx.fillText(yf(v), left - 6, s.y(v));
241 ctx.save();
242 ctx.translate(14, (top + bottom) / 2);
243 ctx.rotate(-Math.PI / 2);
244 ctx.textAlign = "center";
245 ctx.fillStyle = theme.ink2;
246 ctx.fillText(props.yLabel, 0, 0);
247 ctx.restore();
248 // eslint-disable-next-line react-hooks/exhaustive-deps
249 }, [width, height, xRange[0], xRange[1], yRange[0], yRange[1], xLog, yLog, props.draw, themeTick]);
251 // pointer handling
252 useEffect(() => {
253 const el = overlayRef.current!;
254 const info = (ev: MouseEvent): PointerInfo | null => {
255 const s = scalesRef.current;
256 if (!s) return null;
257 const r = el.getBoundingClientRect();
258 const px = ev.clientX - r.left;
259 const py = ev.clientY - r.top;
260 return { xv: s.invX(px), yv: s.invY(py), px, py, scales: s };
261 };
262 const drawCrosshair = (p: PointerInfo | null, mark?: { x?: number; y?: number }) => {
263 const ctx = el.getContext("2d")!;
264 const dpr = window.devicePixelRatio || 1;
265 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
266 ctx.clearRect(0, 0, el.width, el.height);
267 if (!p) return;
268 const s = p.scales;
269 if (p.px < s.left || p.px > s.right || p.py < s.top || p.py > s.bottom) return;
270 const theme = readTheme(wrapRef.current!);
271 ctx.strokeStyle = theme.muted;
272 ctx.setLineDash([3, 3]);
273 ctx.beginPath();
274 const cx = mark?.x !== undefined ? s.x(mark.x) : p.px;
275 ctx.moveTo(Math.round(cx) + 0.5, s.top);
276 ctx.lineTo(Math.round(cx) + 0.5, s.bottom);
277 ctx.stroke();
278 ctx.setLineDash([]);
279 if (mark?.y !== undefined) {
280 ctx.fillStyle = theme.surface;
281 ctx.strokeStyle = theme.ink;
282 ctx.lineWidth = 2;
283 ctx.beginPath();
284 ctx.arc(cx, s.y(mark.y), 5, 0, 2 * Math.PI);
285 ctx.fill();
286 ctx.stroke();
287 }
288 };
289 let down = false;
290 const onMove = (ev: PointerEvent) => {
291 const p = info(ev);
292 if (!p) return;
293 const pr = propsRef.current;
294 if (down) pr.onPointer?.("move", p, ev);
295 else if (pr.cursor) setCursor(pr.cursor(p));
296 const h = pr.hover?.(p) ?? null;
297 const s = p.scales;
298 const inside = p.px >= s.left && p.px <= s.right && p.py >= s.top && p.py <= s.bottom;
299 drawCrosshair(inside && !down ? p : null, h ?? undefined);
300 if (h && inside && !down) {
301 const w = el.clientWidth;
302 setTip({ lines: h.lines, left: p.px > w * 0.6 ? p.px - 12 : p.px + 12, top: Math.max(4, p.py - 10) });
303 el.dataset.tipSide = p.px > w * 0.6 ? "left" : "right";
304 } else setTip(null);
305 };
306 const onDown = (ev: PointerEvent) => {
307 const p = info(ev);
308 if (!p || !propsRef.current.onPointer) return;
309 down = true;
310 el.setPointerCapture(ev.pointerId);
311 propsRef.current.onPointer("down", p, ev);
312 };
313 const onUp = (ev: PointerEvent) => {
314 const p = info(ev);
315 if (down && p) propsRef.current.onPointer?.("up", p, ev);
316 down = false;
317 };
318 const onLeave = () => {
319 if (!down) {
320 drawCrosshair(null);
321 setTip(null);
322 }
323 };
324 const onWheel = (ev: WheelEvent) => {
325 const p = info(ev);
326 if (!p || !propsRef.current.onWheel) return;
327 ev.preventDefault();
328 propsRef.current.onWheel(p, ev);
329 };
330 const onDbl = () => propsRef.current.onDoubleClick?.();
331 const onClick = (ev: MouseEvent) => {
332 const p = info(ev);
333 if (p) propsRef.current.onClick?.(p);
334 };
335 el.addEventListener("pointermove", onMove);
336 el.addEventListener("pointerdown", onDown);
337 el.addEventListener("pointerup", onUp);
338 el.addEventListener("pointerleave", onLeave);
339 el.addEventListener("wheel", onWheel, { passive: false });
340 el.addEventListener("dblclick", onDbl);
341 el.addEventListener("click", onClick);
342 return () => {
343 el.removeEventListener("pointermove", onMove);
344 el.removeEventListener("pointerdown", onDown);
345 el.removeEventListener("pointerup", onUp);
346 el.removeEventListener("pointerleave", onLeave);
347 el.removeEventListener("wheel", onWheel);
348 el.removeEventListener("dblclick", onDbl);
349 el.removeEventListener("click", onClick);
350 };
351 }, []);
353 return (
354 <div ref={wrapRef} className="plot" style={{ height }} role="img" aria-label={props.ariaLabel}>
355 <canvas ref={canvasRef} />
356 <canvas ref={overlayRef} className="plot-overlay" style={{ cursor }} />
357 {tip && (
358 <div
359 className="plot-tip"
360 style={{
361 left: tip.left,
362 top: tip.top,
363 transform: overlayRef.current?.dataset.tipSide === "left" ? "translateX(-100%)" : undefined,
364 }}
365 >
366 {tip.lines.map((l, i) => (
367 <div key={i} className={i === 0 ? "plot-tip-head" : undefined}>
368 {l}
369 </div>
370 ))}
371 </div>
372 )}
373 </div>
374 );
377// ---------- drawing helpers ----------
379export function drawLine(
380 ctx: CanvasRenderingContext2D,
381 s: Scales,
382 xs: ArrayLike<number>,
383 ys: ArrayLike<number>,
384 color: string,
385 width = 2,
386 dash: number[] = [],
387) {
388 ctx.strokeStyle = color;
389 ctx.lineWidth = width;
390 ctx.lineJoin = "round";
391 ctx.setLineDash(dash);
392 ctx.beginPath();
393 let pen = false;
394 for (let i = 0; i < xs.length; i++) {
395 const y = ys[i];
396 if (!Number.isFinite(y)) {
397 pen = false;
398 continue;
399 }
400 const px = s.x(xs[i]);
401 const py = s.y(y);
402 if (pen) ctx.lineTo(px, py);
403 else ctx.moveTo(px, py);
404 pen = true;
405 }
406 ctx.stroke();
407 ctx.setLineDash([]);
410export type MarkerShape = "circle" | "square" | "triangle" | "diamond" | "cross";
411export const SHAPES: MarkerShape[] = ["circle", "square", "triangle", "diamond", "cross"];
413export function drawMarker(
414 ctx: CanvasRenderingContext2D,
415 px: number,
416 py: number,
417 shape: MarkerShape,
418 color: string,
419 ring: string,
420 r = 5,
421) {
422 ctx.beginPath();
423 if (shape === "circle") ctx.arc(px, py, r, 0, 2 * Math.PI);
424 else if (shape === "square") ctx.rect(px - r * 0.9, py - r * 0.9, r * 1.8, r * 1.8);
425 else if (shape === "triangle") {
426 ctx.moveTo(px, py - r * 1.15);
427 ctx.lineTo(px + r * 1.05, py + r * 0.75);
428 ctx.lineTo(px - r * 1.05, py + r * 0.75);
429 ctx.closePath();
430 } else if (shape === "diamond") {
431 ctx.moveTo(px, py - r * 1.25);
432 ctx.lineTo(px + r * 1.05, py);
433 ctx.lineTo(px, py + r * 1.25);
434 ctx.lineTo(px - r * 1.05, py);
435 ctx.closePath();
436 } else {
437 const k = r * 0.45;
438 ctx.moveTo(px - k, py - r);
439 ctx.lineTo(px + k, py - r);
440 ctx.lineTo(px + k, py - k);
441 ctx.lineTo(px + r, py - k);
442 ctx.lineTo(px + r, py + k);
443 ctx.lineTo(px + k, py + k);
444 ctx.lineTo(px + k, py + r);
445 ctx.lineTo(px - k, py + r);
446 ctx.lineTo(px - k, py + k);
447 ctx.lineTo(px - r, py + k);
448 ctx.lineTo(px - r, py - k);
449 ctx.lineTo(px - k, py - k);
450 ctx.closePath();
451 }
452 ctx.fillStyle = color;
453 ctx.fill();
454 ctx.strokeStyle = ring;
455 ctx.lineWidth = 2;
456 ctx.stroke();
↑↓ move↵openescclose