/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / components / CanvasPlot.tsx
464 lines · 14.5 KBBlameHistoryRaw
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) => boolean; // true = handled (page does not scroll)
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 let downAt = { x: 0, y: 0 };
291 let moved = false;
292 const onMove = (ev: PointerEvent) => {
293 const p = info(ev);
294 if (!p) return;
295 const pr = propsRef.current;
296 if (down) {
297 if (Math.abs(ev.clientX - downAt.x) + Math.abs(ev.clientY - downAt.y) > 3) moved = true;
298 pr.onPointer?.("move", p, ev);
299 }
300 else if (pr.cursor) setCursor(pr.cursor(p));
301 const h = pr.hover?.(p) ?? null;
302 const s = p.scales;
303 const inside = p.px >= s.left && p.px <= s.right && p.py >= s.top && p.py <= s.bottom;
304 drawCrosshair(inside && !down ? p : null, h ?? undefined);
305 if (h && inside && !down) {
306 const w = el.clientWidth;
307 setTip({ lines: h.lines, left: p.px > w * 0.6 ? p.px - 12 : p.px + 12, top: Math.max(4, p.py - 10) });
308 el.dataset.tipSide = p.px > w * 0.6 ? "left" : "right";
309 } else setTip(null);
310 };
311 const onDown = (ev: PointerEvent) => {
312 const p = info(ev);
313 if (!p || !propsRef.current.onPointer) return;
314 down = true;
315 downAt = { x: ev.clientX, y: ev.clientY };
316 moved = false;
317 el.setPointerCapture(ev.pointerId);
318 propsRef.current.onPointer("down", p, ev);
319 };
320 const onUp = (ev: PointerEvent) => {
321 const p = info(ev);
322 if (down && p) propsRef.current.onPointer?.("up", p, ev);
323 down = false;
324 };
325 const onLeave = () => {
326 if (!down) {
327 drawCrosshair(null);
328 setTip(null);
329 }
330 };
331 const onWheel = (ev: WheelEvent) => {
332 const p = info(ev);
333 if (!p || !propsRef.current.onWheel) return;
334 if (propsRef.current.onWheel(p, ev)) ev.preventDefault();
335 };
336 const onDbl = () => propsRef.current.onDoubleClick?.();
337 const onClick = (ev: MouseEvent) => {
338 const p = info(ev);
339 if (p && !moved) propsRef.current.onClick?.(p);
340 moved = false;
341 };
342 el.addEventListener("pointermove", onMove);
343 el.addEventListener("pointerdown", onDown);
344 el.addEventListener("pointerup", onUp);
345 el.addEventListener("pointerleave", onLeave);
346 el.addEventListener("wheel", onWheel, { passive: false });
347 el.addEventListener("dblclick", onDbl);
348 el.addEventListener("click", onClick);
349 return () => {
350 el.removeEventListener("pointermove", onMove);
351 el.removeEventListener("pointerdown", onDown);
352 el.removeEventListener("pointerup", onUp);
353 el.removeEventListener("pointerleave", onLeave);
354 el.removeEventListener("wheel", onWheel);
355 el.removeEventListener("dblclick", onDbl);
356 el.removeEventListener("click", onClick);
357 };
358 }, []);
360 return (
361 <div ref={wrapRef} className="plot" style={{ height }} role="img" aria-label={props.ariaLabel}>
362 <canvas ref={canvasRef} />
363 <canvas ref={overlayRef} className="plot-overlay" style={{ cursor }} />
364 {tip && (
365 <div
366 className="plot-tip"
367 style={{
368 left: tip.left,
369 top: tip.top,
370 transform: overlayRef.current?.dataset.tipSide === "left" ? "translateX(-100%)" : undefined,
371 }}
372 >
373 {tip.lines.map((l, i) => (
374 <div key={i} className={i === 0 ? "plot-tip-head" : undefined}>
375 {l}
376 </div>
377 ))}
378 </div>
379 )}
380 </div>
381 );
384// ---------- drawing helpers ----------
386export function drawLine(
387 ctx: CanvasRenderingContext2D,
388 s: Scales,
389 xs: ArrayLike<number>,
390 ys: ArrayLike<number>,
391 color: string,
392 width = 2,
393 dash: number[] = [],
394) {
395 ctx.strokeStyle = color;
396 ctx.lineWidth = width;
397 ctx.lineJoin = "round";
398 ctx.setLineDash(dash);
399 ctx.beginPath();
400 let pen = false;
401 for (let i = 0; i < xs.length; i++) {
402 const y = ys[i];
403 if (!Number.isFinite(y)) {
404 pen = false;
405 continue;
406 }
407 const px = s.x(xs[i]);
408 const py = s.y(y);
409 if (pen) ctx.lineTo(px, py);
410 else ctx.moveTo(px, py);
411 pen = true;
412 }
413 ctx.stroke();
414 ctx.setLineDash([]);
417export type MarkerShape = "circle" | "square" | "triangle" | "diamond" | "cross";
418export const SHAPES: MarkerShape[] = ["circle", "square", "triangle", "diamond", "cross"];
420export function drawMarker(
421 ctx: CanvasRenderingContext2D,
422 px: number,
423 py: number,
424 shape: MarkerShape,
425 color: string,
426 ring: string,
427 r = 5,
428) {
429 ctx.beginPath();
430 if (shape === "circle") ctx.arc(px, py, r, 0, 2 * Math.PI);
431 else if (shape === "square") ctx.rect(px - r * 0.9, py - r * 0.9, r * 1.8, r * 1.8);
432 else if (shape === "triangle") {
433 ctx.moveTo(px, py - r * 1.15);
434 ctx.lineTo(px + r * 1.05, py + r * 0.75);
435 ctx.lineTo(px - r * 1.05, py + r * 0.75);
436 ctx.closePath();
437 } else if (shape === "diamond") {
438 ctx.moveTo(px, py - r * 1.25);
439 ctx.lineTo(px + r * 1.05, py);
440 ctx.lineTo(px, py + r * 1.25);
441 ctx.lineTo(px - r * 1.05, py);
442 ctx.closePath();
443 } else {
444 const k = r * 0.45;
445 ctx.moveTo(px - k, py - r);
446 ctx.lineTo(px + k, py - r);
447 ctx.lineTo(px + k, py - k);
448 ctx.lineTo(px + r, py - k);
449 ctx.lineTo(px + r, py + k);
450 ctx.lineTo(px + k, py + k);
451 ctx.lineTo(px + k, py + r);
452 ctx.lineTo(px - k, py + r);
453 ctx.lineTo(px - k, py + k);
454 ctx.lineTo(px - r, py + k);
455 ctx.lineTo(px - r, py - k);
456 ctx.lineTo(px - k, py - k);
457 ctx.closePath();
458 }
459 ctx.fillStyle = color;
460 ctx.fill();
461 ctx.strokeStyle = ring;
462 ctx.lineWidth = 2;
463 ctx.stroke();
↑↓ move↵openescclose