"use client";
import { drawCode, hitToken, kw, line, num, pu, t, type Rect } from "./code";
import { C, clamp, cubicBezier, dashed, Exhibit, lerp, monoFont, rrect } from "./kit";
export type EaseProps = {
/** cubic-bezier control points [x1, y1, x2, y2]. */
bezier?: [number, number, number, number];
/** Transition duration in ms (100–1000). */
duration?: number;
};
type Id = "dur" | "x1" | "y1" | "x2" | "y2";
const LAYOUT = { x: 64, y: 92, lh: 21, size: 13, numX: 46, numSize: 9, indent: 2 };
const G = { x: 64, y: 264, s: 198 };
const PH = { x: 418, y: 204, w: 136, h: 262 };
/** A transition's cubic-bezier, drawn as a curve, as 60 Hz frame ticks and as a sheet sliding up a phone. */
export function Ease({ bezier = [0.32, 0.72, 0, 1], duration = 400 }: EaseProps) {
return (
<Exhibit
title="Ease"
hint="drag a number or a handle · tap to replay"
formula="B(s) = 3(1−s)²s·P₁ + 3(1−s)s²·P₂ + s³ · y = B_y(B_x⁻¹(t))"
spec="P₀ (0,0) · P₃ (1,1) · ticks at 60 Hz"
label="A CSS transition with its cubic-bezier curve, the frames it produces at 60 hertz, and a phone whose sheet slides up with that easing. Drag the numbers or the curve's handles, or tap to replay. With the keyboard, move the probe onto a number or handle, hold Space and use the arrow keys."
cursor="default"
params={{ bezier, duration }}
create={(params) => {
let seen = params.current;
const v = { dur: duration, x1: bezier[0], y1: bezier[1], x2: bezier[2], y2: bezier[3] };
let hits: Record<string, Rect> = {};
let drag: { id: Id; from: number; x: number } | null = null;
let handle: 1 | 2 | 0 = 0;
let clock = 0;
let idle = 0;
let prog = 0;
let tNow = 0;
let frames = 24;
let dmax = 0;
const gx = (x: number) => G.x + x * G.s;
const gy = (y: number) => G.y + G.s - y * G.s;
return {
frame(ctx, dt, p) {
const pc = params.current;
if (pc !== seen && (pc.duration !== seen.duration || pc.bezier.join() !== seen.bezier.join())) {
v.dur = pc.duration;
[v.x1, v.y1, v.x2, v.y2] = pc.bezier;
clock = 0;
}
seen = pc;
if (drag && p.down) {
const per = drag.id === "dur" ? 2 : 0.005;
const lo = drag.id === "dur" ? 100 : drag.id[0] === "x" ? 0 : -0.5;
const hi = drag.id === "dur" ? 1000 : drag.id[0] === "x" ? 1 : 1.5;
const n = clamp(drag.from + (p.x - drag.x) * per, lo, hi);
v[drag.id] = drag.id === "dur" ? Math.round(n / 10) * 10 : Math.round(n * 100) / 100;
}
if (handle && p.down) {
const x = Math.round(clamp((p.x - G.x) / G.s) * 100) / 100;
const y = Math.round(clamp((G.y + G.s - p.y) / G.s, -0.5, 1.5) * 100) / 100;
if (handle === 1) [v.x1, v.y1] = [x, y];
else [v.x2, v.y2] = [x, y];
}
const ease = cubicBezier(v.x1, v.y1, v.x2, v.y2);
// Replay on tap, and by itself every few seconds while idle.
clock += dt;
if (!p.inside && !p.down) {
idle += dt;
if (idle > 3.2) {
idle = 0;
clock = 0;
}
} else idle = 0;
const tt = clamp((clock * 1000) / v.dur);
tNow = tt;
prog = ease(tt);
const f = (n: number) => n.toFixed(2);
const hover = p.inside ? hitToken(hits, p.x, p.y) : null;
hits = drawCode(
ctx,
[
line(0, t(".sheet[data-open] "), pu("{")),
line(1, kw("transform"), pu(": "), t("translateY(0)"), pu(";")),
line(1, kw("transition"), pu(": "), t("transform "), num(`${v.dur}ms`, "dur")),
line(2, t("cubic-bezier("), num(f(v.x1), "x1"), pu(", "), num(f(v.y1), "y1"), pu(", "), num(f(v.x2), "x2"), pu(", "), num(f(v.y2), "y2"), t(")"), pu(";")),
line(0, pu("}")),
],
LAYOUT,
drag?.id ?? hover
);
// Curve and handles.
dashed(ctx, G.x + 0.5, G.y, G.x + 0.5, G.y + G.s, "#34342f");
dashed(ctx, G.x + G.s + 0.5, G.y, G.x + G.s + 0.5, G.y + G.s, "#34342f");
dashed(ctx, G.x, G.y + G.s + 0.5, G.x + G.s, G.y + G.s + 0.5, "#34342f");
ctx.font = monoFont(9);
ctx.fillStyle = C.dim;
ctx.textAlign = "right";
ctx.fillText("1", 46, G.y);
ctx.fillText("0", 46, G.y + G.s);
ctx.textAlign = "center";
ctx.fillText("t →", G.x + G.s / 2, G.y + G.s + 14);
ctx.textAlign = "left";
ctx.strokeStyle = "#6b6960";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(gx(0), gy(0));
ctx.lineTo(gx(v.x1), gy(v.y1));
ctx.moveTo(gx(1), gy(1));
ctx.lineTo(gx(v.x2), gy(v.y2));
ctx.stroke();
ctx.strokeStyle = C.bright;
ctx.lineWidth = 1.6;
ctx.beginPath();
for (let i = 0; i <= 80; i++) {
const s = i / 80;
const bx = 3 * (1 - s) * (1 - s) * s * v.x1 + 3 * (1 - s) * s * s * v.x2 + s * s * s;
const by = 3 * (1 - s) * (1 - s) * s * v.y1 + 3 * (1 - s) * s * s * v.y2 + s * s * s;
if (i) ctx.lineTo(gx(bx), gy(by));
else ctx.moveTo(gx(bx), gy(by));
}
ctx.stroke();
const near = (x: number, y: number) => p.inside && Math.hypot(p.x - gx(x), p.y - gy(y)) < 12;
for (const [h, x, y] of [[1, v.x1, v.y1], [2, v.x2, v.y2]] as const) {
ctx.strokeStyle = handle === h || near(x, y) ? C.accent : C.bright;
ctx.fillStyle = C.bg;
ctx.lineWidth = 1.3;
ctx.beginPath();
ctx.arc(gx(x), gy(y), 4.5, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
}
ctx.fillStyle = C.accent;
ctx.beginPath();
ctx.arc(gx(tt), gy(prog), 3, 0, Math.PI * 2);
ctx.fill();
// One tick per 60 Hz frame, placed at that frame's progress.
frames = Math.max(1, Math.round((v.dur / 1000) * 60));
dmax = 0;
let prev = 0;
ctx.fillStyle = "#8a877d";
for (let i = 0; i <= frames; i++) {
const y = ease(i / frames);
if (i) dmax = Math.max(dmax, y - prev);
prev = y;
ctx.fillRect(320, gy(y), 12, 1);
}
dashed(ctx, 326.5, G.y, 326.5, G.y + G.s, "#34342f");
ctx.fillStyle = C.accent;
ctx.beginPath();
ctx.arc(326, gy(prog), 3, 0, Math.PI * 2);
ctx.fill();
// Phone with a sheet riding the curve.
ctx.strokeStyle = "#4a4943";
ctx.lineWidth = 1;
rrect(ctx, PH.x + 0.5, PH.y + 0.5, PH.w, PH.h, 22);
ctx.stroke();
rrect(ctx, PH.x + 5.5, PH.y + 5.5, PH.w - 10, PH.h - 10, 18);
ctx.stroke();
ctx.fillStyle = "#2a2a26";
rrect(ctx, PH.x + PH.w / 2 - 18, PH.y + 14, 36, 9, 4.5);
ctx.fill();
ctx.fillStyle = "#2f2f2a";
ctx.fillRect(PH.x + 18, PH.y + 34, 52, 6);
ctx.fillRect(PH.x + 18, PH.y + 46, 76, 3);
ctx.save();
rrect(ctx, PH.x + 6, PH.y + 6, PH.w - 12, PH.h - 12, 17);
ctx.clip();
const open = PH.y + 60;
const closed = PH.y + PH.h;
const top = lerp(closed, open, prog);
ctx.fillStyle = "#1d1d1a";
ctx.strokeStyle = "#4a4943";
rrect(ctx, PH.x + 8.5, top + 0.5, PH.w - 17, PH.h, 14);
ctx.fill();
ctx.stroke();
const sx = PH.x + 20;
ctx.fillStyle = "#4a4943";
ctx.fillRect(PH.x + PH.w / 2 - 12, top + 8, 24, 2.5);
ctx.fillStyle = C.bright;
ctx.fillRect(sx, top + 26, 46, 4);
ctx.fillStyle = "#3e3d38";
ctx.fillRect(sx, top + 36, 76, 2.5);
for (let r = 0; r < 3; r++) {
const ry = top + 60 + r * 30;
ctx.fillStyle = "#3e3d38";
ctx.beginPath();
ctx.arc(sx + 5, ry, 5.5, 0, Math.PI * 2);
ctx.fill();
ctx.fillRect(sx + 18, ry - 4, 52, 3);
ctx.fillRect(sx + 18, ry + 2, 34, 2.5);
if (r < 2) ctx.fillRect(sx, ry + 15, 96, 1);
}
ctx.fillStyle = "#4a4943";
rrect(ctx, sx, top + 162, 98, 20, 10);
ctx.fill();
ctx.fillStyle = C.bright;
ctx.fillRect(sx + 37, top + 171, 24, 2);
ctx.restore();
},
down(p) {
const id = hitToken(hits, p.x, p.y) as Id | null;
if (id) {
drag = { id, from: v[id], x: p.x };
return;
}
if (Math.hypot(p.x - gx(v.x1), p.y - gy(v.y1)) < 12) handle = 1;
else if (Math.hypot(p.x - gx(v.x2), p.y - gy(v.y2)) < 12) handle = 2;
},
up() {
if (drag || handle) clock = 0;
drag = null;
handle = 0;
},
tap() {
clock = 0;
},
stats: () => ["", `${frames} frames · Δmax ${Math.round(dmax * 100)}% · t ${tNow.toFixed(2)}`],
};
}}
/>
);
}
import { C, clamp, monoFont, scramble } from "./kit";
/** One token of syntax-coloured code drawn on the canvas. */
export type Tok = { t: string; k: "kw" | "num" | "str" | "punc" | "txt" | "com"; id?: string };
export type CodeLine = { indent: number; toks: Tok[] };
export const t = (s: string): Tok => ({ t: s, k: "txt" });
export const kw = (s: string): Tok => ({ t: s, k: "kw" });
export const num = (s: string, id?: string): Tok => ({ t: s, k: "num", id });
export const str = (s: string): Tok => ({ t: s, k: "str" });
export const pu = (s: string): Tok => ({ t: s, k: "punc" });
export const com = (s: string): Tok => ({ t: s, k: "com" });
export const line = (indent: number, ...toks: Tok[]): CodeLine => ({ indent, toks });
const COL: Record<Tok["k"], string> = { kw: C.bright, num: C.accent, str: C.text, punc: "#8a877d", txt: C.text, com: C.dim };
const SCRAMBLED = "#4f4d46";
export type Rect = { x: number; y: number; w: number; h: number };
export type CodeLayout = { x: number; y: number; lh: number; size: number; numX: number; numSize: number; indent: number };
/** Draws code with line numbers. Returns the box of every token that has an id, for hit testing. */
export function drawCode(ctx: CanvasRenderingContext2D, lines: CodeLine[], L: CodeLayout, active?: string | null) {
const hits: Record<string, Rect> = {};
ctx.textBaseline = "middle";
ctx.font = monoFont(L.size);
const cw = ctx.measureText("M").width;
lines.forEach((ln, i) => {
const y = L.y + i * L.lh;
ctx.font = monoFont(L.numSize);
ctx.fillStyle = "#4a4943";
ctx.textAlign = "right";
ctx.fillText(String(i + 1), L.numX, y);
ctx.textAlign = "left";
let x = L.x + ln.indent * L.indent * cw;
for (const tk of ln.toks) {
ctx.font = monoFont(L.size, tk.k === "kw" ? 600 : 400);
ctx.fillStyle = tk.id && tk.id === active ? "#7fb8ff" : COL[tk.k];
ctx.fillText(tk.t, x, y);
const w = tk.t.length * cw;
if (tk.id) {
hits[tk.id] = { x: x - 3, y: y - L.lh / 2, w: w + 6, h: L.lh };
if (tk.id === active) {
ctx.fillStyle = C.accent;
ctx.fillRect(x, y + L.size * 0.62, w, 1);
}
}
x += w;
}
});
return hits;
}
/**
* Code seen through a slit: lines inside the window around `slit` decode into
* real source, lines at the window's edge flicker between code and noise, and
* everything else stays scrambled.
*/
export function drawSlitCode(ctx: CanvasRenderingContext2D, lines: CodeLine[], L: CodeLayout, slit: number, win: number, time: number) {
ctx.textBaseline = "middle";
ctx.font = monoFont(L.size);
const cw = ctx.measureText("M").width;
const tick = Math.floor(time * 14);
lines.forEach((ln, i) => {
const y = L.y + i * L.lh;
const d = Math.abs(y - slit) / Math.max(1, win * L.lh);
const flick = clamp((d - 0.7) / 0.3);
ctx.font = monoFont(L.numSize);
ctx.textAlign = "right";
ctx.fillStyle = d < 1 ? (y > slit && d < 0.55 ? C.accent : C.text) : "#4a4943";
ctx.fillText(String(i + 1), L.numX, y);
ctx.textAlign = "left";
let x = L.x + ln.indent * L.indent * cw;
let ci = 0;
for (const tk of ln.toks) {
ctx.font = monoFont(L.size, tk.k === "kw" && d < 1 ? 600 : 400);
if (d >= 1) {
ctx.fillStyle = SCRAMBLED;
ctx.fillText(scramble(tk.t, i * 977 + ci), x, y);
} else if (flick <= 0) {
ctx.fillStyle = COL[tk.k];
ctx.fillText(tk.t, x, y);
} else {
// Edge of the window: each character independently decodes or not.
const noise = scramble(tk.t, i * 131 + ci + tick * 7919);
for (let c = 0; c < tk.t.length; c++) {
const h = Math.sin((i * 97 + ci + c) * 12.9898 + tick * 4.1) * 43758.5453;
const coded = h - Math.floor(h) < flick;
ctx.fillStyle = coded ? SCRAMBLED : COL[tk.k];
ctx.fillText(coded ? noise[c] : tk.t[c], x + c * cw, y);
}
}
x += tk.t.length * cw;
ci += tk.t.length;
}
});
return cw;
}
/** Index of the hit token under (x, y), if any. */
export function hitToken(hits: Record<string, Rect>, x: number, y: number) {
for (const id in hits) {
const r = hits[id];
if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) return id;
}
return null;
}
"use client";
import { useEffect, useRef, useState, type MutableRefObject } from "react";
/** Every exhibit draws in a 600 × 600 coordinate space, whatever its rendered size. */
export const S = 600;
export const C = {
bg: "#10100e",
panel: "#161613",
line: "#34342f",
text: "#b9b4a8",
dim: "#6b6960",
bright: "#ece8dc",
accent: "#2b8cff",
};
export const MONO = '"Geist Mono", ui-monospace, SFMono-Regular, Menlo, monospace';
let fam = "";
export function monoFont(px: number, weight = 400) {
if (!fam && typeof window !== "undefined") fam = getComputedStyle(document.documentElement).getPropertyValue("--font-geist-mono").trim() || MONO;
return `${weight} ${px}px ${fam || MONO}, ui-monospace, monospace`;
}
/** Pointer (or keyboard probe) state, in exhibit coordinates. */
export type Ptr = {
x: number;
y: number;
inside: boolean;
down: boolean;
/** Velocity in px/s, smoothed. */
vx: number;
vy: number;
/** Seconds since the last press began. */
held: number;
/** "key" when the keyboard probe is driving it. */
source: "pointer" | "key";
};
export type Sim = {
/** Advance and draw one frame. dt is in seconds and capped at 1/30. */
frame: (ctx: CanvasRenderingContext2D, dt: number, p: Ptr, time: number) => void;
/** Footer texts that change: [top-right, bottom-right]. Polled about 8× a second. */
stats?: () => [string, string];
down?: (p: Ptr) => void;
up?: (p: Ptr) => void;
/** Pointer released without moving much: a tap or click. */
tap?: (p: Ptr) => void;
dispose?: () => void;
};
export type ExhibitProps<P> = {
title: string;
hint: string;
formula: string;
spec: string;
label: string;
cursor?: string;
params: P;
create: (params: MutableRefObject<P>) => Sim;
/** Extra line the screen-reader summary appends after the stats. */
className?: string;
};
export const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
/**
* Frame shared by every Interaction Lab original: a square panel with a canvas,
* an SVG overlay for the bracketed title, hint, formula and live stats, and a
* keyboard probe so every exhibit can be driven without a pointer.
*/
export function Exhibit<P>({ title, hint, formula, spec, label, cursor = "crosshair", params, create, className }: ExhibitProps<P>) {
const wrap = useRef<HTMLDivElement>(null);
const canvas = useRef<HTMLCanvasElement>(null);
const paramsRef = useRef(params);
paramsRef.current = params;
const [stats, setStats] = useState<[string, string]>(["", ""]);
const [probe, setProbe] = useState<{ x: number; y: number; down: boolean } | null>(null);
const [said, setSaid] = useState("");
const api = useRef<{ ptr: Ptr; sim: Sim | null; engaged: number; keyMove: (dx: number, dy: number) => void; press: (on: boolean) => void; tap: () => void }>(null!);
useEffect(() => {
const cv = canvas.current!;
const el = wrap.current!;
const ctx = cv.getContext("2d")!;
const sim = create(paramsRef);
const ptr: Ptr = { x: S / 2, y: S / 2, inside: false, down: false, vx: 0, vy: 0, held: 0, source: "pointer" };
let raf = 0;
let last = 0;
let visible = true;
let engaged = 0; // seconds of activity left before a reduced-motion pause
let pressAt = { x: 0, y: 0 };
let lastMove = { x: 0, y: 0, t: 0 };
let statT = 0;
let time = 0;
const size = () => {
const r = el.getBoundingClientRect();
const dpr = Math.min(window.devicePixelRatio || 1, 2);
cv.width = Math.max(1, Math.round(r.width * dpr));
cv.height = Math.max(1, Math.round(r.height * dpr));
};
size();
const ro = new ResizeObserver(size);
ro.observe(el);
const loop = (now: number) => {
raf = 0;
const dt = Math.min(1 / 30, last ? (now - last) / 1000 : 1 / 60);
last = now;
time += dt;
if (ptr.down) ptr.held += dt;
if (now - lastMove.t > 80) {
ptr.vx *= 0.8;
ptr.vy *= 0.8;
}
ctx.setTransform(cv.width / S, 0, 0, cv.height / S, 0, 0);
ctx.fillStyle = C.bg;
ctx.fillRect(0, 0, S, S);
sim.frame(ctx, dt, ptr, time);
statT += dt;
if (statT > 0.12 && sim.stats) {
statT = 0;
const s = sim.stats();
setStats((o) => (o[0] === s[0] && o[1] === s[1] ? o : s));
}
engaged -= dt;
schedule();
};
const schedule = () => {
if (raf || !visible || document.hidden) return;
if (reduced() && engaged <= 0 && !ptr.inside && !ptr.down) return;
last = last && performance.now() - last > 200 ? 0 : last;
raf = requestAnimationFrame(loop);
};
const wake = () => {
engaged = 3;
schedule();
};
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
if (visible) {
last = 0;
schedule();
}
});
io.observe(el);
const onVis = () => {
last = 0;
schedule();
};
document.addEventListener("visibilitychange", onVis);
const toLocal = (e: PointerEvent) => {
const r = el.getBoundingClientRect();
return { x: ((e.clientX - r.left) / r.width) * S, y: ((e.clientY - r.top) / r.height) * S };
};
const move = (x: number, y: number) => {
const t = performance.now();
const dts = Math.max(1, t - lastMove.t) / 1000;
if (lastMove.t && t - lastMove.t < 100) {
ptr.vx = ptr.vx * 0.6 + ((x - ptr.x) / dts) * 0.4;
ptr.vy = ptr.vy * 0.6 + ((y - ptr.y) / dts) * 0.4;
}
lastMove = { x, y, t };
ptr.x = x;
ptr.y = y;
};
const onMove = (e: PointerEvent) => {
const l = toLocal(e);
ptr.source = "pointer";
ptr.inside = true;
move(l.x, l.y);
wake();
};
const onDown = (e: PointerEvent) => {
if (e.button !== 0) return;
el.setPointerCapture(e.pointerId);
const l = toLocal(e);
ptr.source = "pointer";
ptr.inside = true;
move(l.x, l.y);
ptr.down = true;
ptr.held = 0;
pressAt = l;
sim.down?.(ptr);
wake();
};
const onUp = (e: PointerEvent) => {
if (!ptr.down) return;
const l = toLocal(e);
ptr.down = false;
sim.up?.(ptr);
if (Math.hypot(l.x - pressAt.x, l.y - pressAt.y) < 6) sim.tap?.(ptr);
if (e.pointerType !== "mouse") ptr.inside = false;
wake();
};
const onLeave = (e: PointerEvent) => {
if (ptr.down && el.hasPointerCapture(e.pointerId)) return;
ptr.inside = false;
wake();
};
el.addEventListener("pointermove", onMove);
el.addEventListener("pointerdown", onDown);
el.addEventListener("pointerup", onUp);
el.addEventListener("pointercancel", onUp);
el.addEventListener("pointerleave", onLeave);
api.current = {
ptr,
sim,
engaged,
keyMove: (dx, dy) => {
if (ptr.source !== "key" || !ptr.inside) {
ptr.source = "key";
ptr.inside = true;
}
const nx = Math.max(8, Math.min(S - 8, ptr.x + dx));
const ny = Math.max(8, Math.min(S - 8, ptr.y + dy));
ptr.vx = (nx - ptr.x) * 30;
ptr.vy = (ny - ptr.y) * 30;
ptr.x = nx;
ptr.y = ny;
lastMove.t = performance.now();
wake();
},
press: (on) => {
ptr.source = "key";
ptr.inside = true;
if (on && !ptr.down) {
ptr.down = true;
ptr.held = 0;
pressAt = { x: ptr.x, y: ptr.y };
sim.down?.(ptr);
} else if (!on && ptr.down) {
ptr.down = false;
sim.up?.(ptr);
if (Math.hypot(ptr.x - pressAt.x, ptr.y - pressAt.y) < 6) sim.tap?.(ptr);
}
wake();
},
tap: () => {
ptr.source = "key";
ptr.inside = true;
ptr.down = true;
ptr.held = 0;
sim.down?.(ptr);
ptr.down = false;
sim.up?.(ptr);
sim.tap?.(ptr);
wake();
},
};
// Draw one frame even when motion is reduced, so the exhibit is never blank.
engaged = reduced() ? 0.05 : 0;
raf = requestAnimationFrame(loop);
return () => {
cancelAnimationFrame(raf);
ro.disconnect();
io.disconnect();
document.removeEventListener("visibilitychange", onVis);
el.removeEventListener("pointermove", onMove);
el.removeEventListener("pointerdown", onDown);
el.removeEventListener("pointerup", onUp);
el.removeEventListener("pointercancel", onUp);
el.removeEventListener("pointerleave", onLeave);
sim.dispose?.();
};
// create is stable per exhibit; remount with a key to rebuild.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const announce = useRef<number>(0);
const sync = () => {
const p = api.current?.ptr;
if (!p) return;
setProbe({ x: p.x, y: p.y, down: p.down });
window.clearTimeout(announce.current);
announce.current = window.setTimeout(() => {
const s = api.current?.sim?.stats?.();
if (s) setSaid([s[0], s[1]].filter(Boolean).join(". "));
}, 700);
};
const onKeyDown = (e: React.KeyboardEvent) => {
const a = api.current;
if (!a) return;
const step = e.shiftKey ? 48 : 12;
const k = e.key;
if (k === "ArrowLeft" || k === "ArrowRight" || k === "ArrowUp" || k === "ArrowDown") {
e.preventDefault();
a.keyMove(k === "ArrowLeft" ? -step : k === "ArrowRight" ? step : 0, k === "ArrowUp" ? -step : k === "ArrowDown" ? step : 0);
sync();
} else if (k === " ") {
e.preventDefault();
if (!e.repeat) a.press(true);
sync();
} else if (k === "Enter") {
e.preventDefault();
if (!e.repeat) a.tap();
sync();
} else if (k === "Escape") {
if (a.ptr.down) a.press(false);
a.ptr.inside = false;
setProbe(null);
}
};
const onKeyUp = (e: React.KeyboardEvent) => {
if (e.key === " ") {
e.preventDefault();
api.current?.press(false);
sync();
}
};
return (
<section
className={"lab lab-exhibit relative aspect-square w-full touch-none select-none overflow-hidden [-webkit-touch-callout:none] " + (className ?? "")}
style={{ background: C.bg, boxShadow: `inset 0 0 0 1px ${C.panel}` }}
tabIndex={0}
role="group"
aria-roledescription="interactive demo"
aria-label={`${title}. ${label}`}
onKeyDown={onKeyDown}
onKeyUp={onKeyUp}
onBlur={() => {
api.current?.press(false);
if (api.current) api.current.ptr.inside = api.current.ptr.source === "pointer" && api.current.ptr.inside;
setProbe(null);
}}
>
<div ref={wrap} className="absolute inset-0 touch-none" style={{ cursor }}>
<canvas ref={canvas} aria-hidden="true" className="absolute inset-0 block h-full w-full" />
<svg viewBox={`0 0 ${S} ${S}`} aria-hidden="true" className="lab-mono pointer-events-none absolute inset-0 block h-full w-full">
<text x={hint ? 40 : 300} y="44" fill={C.accent} fontSize="13" letterSpacing="0.14em" textAnchor={hint ? "start" : "middle"}>{`[ ${title.toUpperCase()} ]`}</text>
<text x="560" y="44" fill={C.dim} fontSize="11" textAnchor="end" letterSpacing="0.06em">
{hint}
</text>
<line x1="40" x2="560" y1="524.5" y2="524.5" stroke={C.line} strokeDasharray="2 4" />
<text x="40" y="548" fill={C.text} fontSize="11" letterSpacing="0.06em" style={{ whiteSpace: "pre" }}>
{formula}
</text>
<text x="560" y="548" fill={C.text} fontSize="11" textAnchor="end" letterSpacing="0.06em" style={{ whiteSpace: "pre" }}>
{stats[0]}
</text>
<text x="40" y="568" fill={C.dim} fontSize="11" letterSpacing="0.06em" style={{ whiteSpace: "pre" }}>
{spec}
</text>
<text x="560" y="568" fill={C.dim} fontSize="11" textAnchor="end" letterSpacing="0.06em" style={{ whiteSpace: "pre" }}>
{stats[1]}
</text>
{probe && (
<g transform={`translate(${probe.x} ${probe.y})`} stroke={C.accent} strokeWidth="1.5" fill="none">
<circle r={probe.down ? 9 : 6} />
<path d="M-14 0h6M8 0h6M0 -14v6M0 8v6" />
</g>
)}
</svg>
</div>
<span aria-hidden="true" className="lab-corners pointer-events-none absolute inset-[6px]">
<span className="absolute left-0 top-0 size-3 border-l border-t" style={{ borderColor: C.accent }} />
<span className="absolute right-0 top-0 size-3 border-r border-t" style={{ borderColor: C.accent }} />
<span className="absolute bottom-0 left-0 size-3 border-b border-l" style={{ borderColor: C.accent }} />
<span className="absolute bottom-0 right-0 size-3 border-b border-r" style={{ borderColor: C.accent }} />
</span>
<span className="sr-only" aria-live="polite">
{said}
</span>
</section>
);
}
/* ---------- shared drawing + simulation helpers ---------- */
export const clamp = (v: number, a = 0, b = 1) => (v < a ? a : v > b ? b : v);
export const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
/** Small deterministic PRNG so every mount starts from the same picture. */
export function rng(seed = 1) {
let s = seed >>> 0 || 1;
return () => {
s ^= s << 13;
s ^= s >>> 17;
s ^= s << 5;
return (s >>> 0) / 4294967296;
};
}
/**
* Halftone: draws one square dot per grid cell, sized by the cell value (0–1).
* Cells are bucketed by brightness so the whole field is a handful of fills.
*/
export function halftone(
ctx: CanvasRenderingContext2D,
field: ArrayLike<number>,
gw: number,
gh: number,
pitch: number,
ox: number,
oy: number,
colors: string[],
opts: { min?: number; size?: (v: number, i: number) => number; tone?: (v: number, i: number) => number } = {}
) {
const min = opts.min ?? 0.04;
const n = colors.length;
const paths = colors.map(() => new Path2D());
for (let y = 0; y < gh; y++) {
for (let x = 0; x < gw; x++) {
const i = y * gw + x;
const v = field[i];
if (v < min) continue;
const s = opts.size ? opts.size(v, i) : pitch * (0.35 + 0.55 * clamp(v));
if (s <= 0.2) continue;
const tone = opts.tone ? opts.tone(v, i) : v;
const b = Math.min(n - 1, Math.max(0, Math.floor(clamp(tone) * n)));
const cx = ox + x * pitch + pitch / 2;
const cy = oy + y * pitch + pitch / 2;
paths[b].rect(cx - s / 2, cy - s / 2, s, s);
}
}
for (let b = 0; b < n; b++) {
ctx.fillStyle = colors[b];
ctx.fill(paths[b]);
}
}
/** Gray-Scott reaction–diffusion on a w × h grid (Karl Sims' discrete form). */
export class GrayScott {
w: number;
h: number;
u: Float32Array;
v: Float32Array;
nu: Float32Array;
nv: Float32Array;
mask: Uint8Array | null = null;
steps = 0;
constructor(w: number, h: number) {
this.w = w;
this.h = h;
const n = w * h;
this.u = new Float32Array(n).fill(1);
this.v = new Float32Array(n);
this.nu = new Float32Array(n);
this.nv = new Float32Array(n);
}
seed(r: () => number, count = 40, radius = 3) {
const { w, h } = this;
for (let s = 0; s < count; s++) {
const cx = Math.floor(r() * w);
const cy = Math.floor(r() * h);
this.blot(cx, cy, radius, 1);
}
}
/** Add (amount > 0) or erase (amount < 0) chemical V in a disc. */
blot(cx: number, cy: number, radius: number, amount: number) {
const { w, h, u, v } = this;
const r2 = radius * radius;
for (let y = Math.max(0, Math.floor(cy - radius)); y <= Math.min(h - 1, Math.ceil(cy + radius)); y++) {
for (let x = Math.max(0, Math.floor(cx - radius)); x <= Math.min(w - 1, Math.ceil(cx + radius)); x++) {
const d2 = (x - cx) ** 2 + (y - cy) ** 2;
if (d2 > r2) continue;
const i = y * w + x;
if (this.mask && !this.mask[i]) continue;
if (amount > 0) {
u[i] = 0.5;
v[i] = Math.max(v[i], 0.25 * amount + 0.25);
} else {
u[i] = 1;
v[i] = 0;
}
}
}
}
step(F: number, k: number, n = 1, Du = 1, Dv = 0.5) {
const { w, h, mask } = this;
for (let s = 0; s < n; s++) {
const u = this.u;
const v = this.v;
const nu = this.nu;
const nv = this.nv;
for (let y = 0; y < h; y++) {
const ym = (y === 0 ? h - 1 : y - 1) * w;
const yp = (y === h - 1 ? 0 : y + 1) * w;
const yc = y * w;
for (let x = 0; x < w; x++) {
const i = yc + x;
if (mask && !mask[i]) {
nu[i] = 1;
nv[i] = 0;
continue;
}
const xm = x === 0 ? w - 1 : x - 1;
const xp = x === w - 1 ? 0 : x + 1;
const uc = u[i];
const vc = v[i];
const lu =
0.2 * (u[yc + xm] + u[yc + xp] + u[ym + x] + u[yp + x]) + 0.05 * (u[ym + xm] + u[ym + xp] + u[yp + xm] + u[yp + xp]) - uc;
const lv =
0.2 * (v[yc + xm] + v[yc + xp] + v[ym + x] + v[yp + x]) + 0.05 * (v[ym + xm] + v[ym + xp] + v[yp + xm] + v[yp + xp]) - vc;
const uvv = uc * vc * vc;
nu[i] = uc + Du * lu - uvv + F * (1 - uc);
nv[i] = vc + Dv * lv + uvv - (F + k) * vc;
}
}
this.u = nu;
this.nu = u;
this.v = nv;
this.nv = v;
this.steps++;
}
}
}
/** Scrambles a line into same-length noise, stable for a given seed. */
const NOISE = "abcdefghijklmnopqrstuvwxyz{}[]();:.,<>/\\|=+-_*~^";
export function scramble(s: string, seed: number) {
let out = "";
let h = seed * 2654435761;
for (let i = 0; i < s.length; i++) {
const c = s[i];
h = (h ^ (h >>> 13)) * 1274126177;
h ^= h >>> 16;
out += c === " " ? " " : NOISE[(h >>> 0) % NOISE.length];
}
return out;
}
/** Thin dashed line in 600-space. */
export function dashed(ctx: CanvasRenderingContext2D, x1: number, y1: number, x2: number, y2: number, color = C.line, dash: number[] = [2, 4]) {
ctx.save();
ctx.strokeStyle = color;
ctx.lineWidth = 1;
ctx.setLineDash(dash);
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
ctx.restore();
}
/** CSS cubic-bezier(x1, y1, x2, y2) as a function of progress x (0–1). */
export function cubicBezier(x1: number, y1: number, x2: number, y2: number) {
const bx = (s: number) => 3 * (1 - s) * (1 - s) * s * x1 + 3 * (1 - s) * s * s * x2 + s * s * s;
const by = (s: number) => 3 * (1 - s) * (1 - s) * s * y1 + 3 * (1 - s) * s * s * y2 + s * s * s;
return (x: number) => {
if (x <= 0) return 0;
if (x >= 1) return 1;
let lo = 0;
let hi = 1;
let s = x;
for (let i = 0; i < 30; i++) {
s = (lo + hi) / 2;
if (bx(s) < x) lo = s;
else hi = s;
}
return by(s);
};
}
/** Rounded rectangle path helper. */
export function rrect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
ctx.beginPath();
ctx.roundRect(x, y, w, h, r);
}