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