the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Layout: screens never squeezed over each other; a layout lint to keep it so
Jameson Hodgee2ac7891af2a
diff --git a/package.json b/package.jsonindex 528d0c0..529abe5 100644--- a/package.json+++ b/package.json@@ -9,6 +9,7 @@"preview": "vite preview --host 127.0.0.1","test": "bun run wasm && cargo test --workspace && bun test tests","typecheck": "tsc --noEmit",+ "lint:layout": "bun run wasm && bun tools/layout-lint.ts","wasm": "cargo build -p chimera-wasm --release --target wasm32-unknown-unknown && cp target/wasm32-unknown-unknown/release/chimera_wasm.wasm src/wasm/chimera.wasm"},"dependencies": {diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 3021be7..2ed8389 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -125,7 +125,7 @@ function StartPrompt() {sing: ["Every sound here is produced by simulating air moving through a throat, mouth and nose.", "Start and hear a song", "Then play the keys: each note sings the next syllable of the lyrics."],}[mode as "bestiary" | "beatbox" | "speak" | "sing"] ?? ["Every sound here is produced by simulating air moving through a throat, mouth and nose.", "Breathe in and start", "Then drag the tongue, lips or jaw, or play the keys."];return (- <div className="start-prompt">+ <div className="start-prompt" data-layout="overlay"><p>{copy[0]}</p><buttonclassName="primary large"diff --git a/src/ui/components/BeatboxPanel.tsx b/src/ui/components/BeatboxPanel.tsxindex 0fa802b..5f98cb4 100644--- a/src/ui/components/BeatboxPanel.tsx+++ b/src/ui/components/BeatboxPanel.tsx@@ -233,7 +233,7 @@ export function BeatOverlay() {if (!playing || !cell) return null;const s = BEAT_SOUNDS.find((x) => x.id === cell.id);return (- <div className="beat-overlay" aria-hidden="true" key={now}>+ <div className="beat-overlay" data-layout="overlay" aria-hidden="true" key={now}><span className="beat-sym">{cell.id}</span><span className="beat-name">{s?.name}</span>{s && <span className="beat-air">{AIR[s.airstream]}</span>}diff --git a/src/ui/components/BestiaryPanel.tsx b/src/ui/components/BestiaryPanel.tsxindex cfbe547..d70a72b 100644--- a/src/ui/components/BestiaryPanel.tsx+++ b/src/ui/components/BestiaryPanel.tsx@@ -98,7 +98,13 @@ function Params({ def }: { def: CreatureDef }) {}),});}- return <EncoderPages key={def.id} label={`${def.name} controls`} pages={pages} />;+ return (+ <>+ {/* a sentence, too long for the header: it wraps here instead of being cut off there */}+ {def.role && <p className="cparams-role">{def.role}</p>}+ <EncoderPages key={def.id} label={`${def.name} controls`} pages={pages} />+ </>+ );}/** Bestiary's right column: the creatures, the waterfall, the calls, the controls, the airway, the keys. */@@ -116,7 +122,7 @@ export function BestiaryRight() {<Screen className="s-calls" title="Calls">{def && <Calls def={def} />}</Screen>- <Screen className="s-cparams" title="Controls" sub={def?.role}>+ <Screen className="s-cparams" title="Controls">{def && <Params def={def} />}</Screen><Screen className="s-airway" title="Airway" sub="Each tube unrolled">diff --git a/src/ui/components/CreatureView.tsx b/src/ui/components/CreatureView.tsxindex 257a1c6..c15c19a 100644--- a/src/ui/components/CreatureView.tsx+++ b/src/ui/components/CreatureView.tsx@@ -5,7 +5,7 @@ import { creatureById } from "../../wasm/engine.ts";import type { CreatureDef } from "../../wasm/types.ts";import { liveTelemetry, previewTelemetry } from "../creatureLive.ts";import { V, SLOTS, heat, pressureLevel } from "../colors.ts";-import { beamPts, dot, hfont, label, ring, seg, type Pt } from "../render/vector.ts";+import { beamPts, dot, hfont, label, labelWidth, ring, seg, wrapLabel, type Pt } from "../render/vector.ts";type P = [number, number];@@ -69,14 +69,10 @@ function pointAt(t: TubeGeom, s: number): P {return [t.pts[i - 1][0] + (t.pts[i][0] - t.pts[i - 1][0]) * u, t.pts[i - 1][1] + (t.pts[i][1] - t.pts[i - 1][1]) * u];}-/** text cut to fit a width (in the Hershey font at this size and spacing), ending in an ellipsis */+/** text cut to fit a width (measured as label() draws it), ending in an ellipsis */function fit(ctx: CanvasRenderingContext2D, text: string, maxW: number, size: number, ls: number): string {- ctx.save();- ctx.font = hfont(size);- const width = (s: string) => ctx.measureText(s).width + s.length * size * ls;let t = text;- while (t.length > 2 && width(t) > maxW) t = t.slice(0, -2) + "…";- ctx.restore();+ while (t.length > 2 && labelWidth(ctx, t, { size, ls }) > maxW) t = t.slice(0, -2) + "…";return t;}@@ -218,7 +214,13 @@ export function CreatureView() {const color = SLOTS[i];const cx = 16 + (i % perRow) * cw, cy = h - slotH + 12 + Math.floor(i / perRow) * rowH;dot(ctx, cx + 5, cy, 4, color);- label(ctx, fit(ctx, p.label.toUpperCase(), cw - 22, 10, 0.16), cx + 15, cy + 4, { size: 10, color, ls: 0.16, alpha: 0.85 });+ // a long name takes a second line above, where the first row of slots has room, before an ellipsis+ const lo = { size: 10, color, ls: 0.16, alpha: 0.85 };+ const lines = wrapLabel(ctx, p.label.toUpperCase(), cw - 22, lo);+ if (lines.length > 1 && i < perRow) {+ label(ctx, lines[0], cx + 15, cy - 9, lo);+ label(ctx, fit(ctx, lines.slice(1).join(" "), cw - 22, 10, 0.16), cx + 15, cy + 4, lo);+ } else label(ctx, fit(ctx, p.label.toUpperCase(), cw - 22, 10, 0.16), cx + 15, cy + 4, lo);const f = fmtParam(paramValue(p.key, p.default), p);label(ctx, f.value, cx, cy + 14 + big, { size: big, color, weight: "m", ls: 0.02 });if (f.unit) label(ctx, f.unit.toUpperCase(), cx, cy + 32 + big, { size: 10, color, ls: 0.14, alpha: 0.7 });diff --git a/src/ui/components/Keys.tsx b/src/ui/components/Keys.tsxindex bd77f5d..12876ed 100644--- a/src/ui/components/Keys.tsx+++ b/src/ui/components/Keys.tsx@@ -70,7 +70,7 @@ export function Keys() {return (<div className="keys-row"><MidiButton />- <div className="keys" aria-label="Keyboard. Computer keys A to semicolon play notes; Z and X change octave.">+ <div className="keys" data-layout="layered" aria-label="Keyboard. Computer keys A to semicolon play notes; Z and X change octave."><div className="white-row">{whites.map((m) => (<button key={m} className={`key white${held.includes(m) ? " down" : ""}`} onPointerDown={press(m)} onPointerUp={release(m)} onPointerCancel={release(m)} aria-label={`Note ${m}`} />diff --git a/src/ui/components/ScoreView.tsx b/src/ui/components/ScoreView.tsxindex 4971442..b90679e 100644--- a/src/ui/components/ScoreView.tsx+++ b/src/ui/components/ScoreView.tsx@@ -4,7 +4,7 @@ import { engine } from "../../audio/AudioEngine.ts";import { currentPlan, onPlan, type SpokenPlan } from "../speech.ts";import { activation, type Gesture } from "../../wasm/engine.ts";import { V } from "../colors.ts";-import { beam, beamPts, label, seg, type Pt } from "../render/vector.ts";+import { beam, beamPts, blockLineH, label, labelBlock, seg, wrapLabel, type Pt } from "../render/vector.ts";/** rows of the score, coloured like the articulators on the face (lips pink, tongue green, soft palate white, glottis amber) */const ROWS: { name: string; keys: string[]; color: string }[] = [@@ -43,7 +43,13 @@ export function ScoreView() {label(ctx, "PITCH", 14, top + rowH * (ROWS.length + 0.62), { size: 9, color: V.amber, ls: 0.16, alpha: 0.85 });for (let i = 1; i <= ROWS.length + 1; i++) seg(ctx, left, top + rowH * i, right, top + rowH * i, V.frame, 1);if (!sp) {- label(ctx, "SPEAK SOMETHING TO SEE ITS GESTURES: WHICH ARTICULATOR MOVES, WHEN, AND HOW THEY OVERLAP.", left, top + rowH * 2.6, { size: 10, color: V.blueMid, ls: 0.12 });+ // on black over the rules, wrapped to the score's width+ const msg = "SPEAK SOMETHING TO SEE ITS GESTURES: WHICH ARTICULATOR MOVES, WHEN, AND HOW THEY OVERLAP.";+ const cy = (top + bottom) / 2;+ const bh = wrapLabel(ctx, msg, right - left - 16, { size: 10, ls: 0.12 }).length * blockLineH(10) + 8;+ ctx.fillStyle = "#000";+ ctx.fillRect(left, cy - bh / 2, right - left, bh);+ labelBlock(ctx, msg, left + 8, cy, right - left - 16, { size: 10, color: V.blueMid, ls: 0.12 });return;}const plan = sp.plan;diff --git a/src/ui/components/Stroboscope.tsx b/src/ui/components/Stroboscope.tsxindex c85165c..f519c7e 100644--- a/src/ui/components/Stroboscope.tsx+++ b/src/ui/components/Stroboscope.tsx@@ -4,7 +4,7 @@ import { engine } from "../../audio/AudioEngine.ts";import { sameBody } from "../body.ts";import { useStore } from "../store.ts";import { V } from "../colors.ts";-import { beam, beamPts, label, ring, seg, type Pt } from "../render/vector.ts";+import { beam, beamPts, label, labelBlock, ring, seg, type Pt } from "../render/vector.ts";/*** The vocal folds from above, as through an endoscope, replayed slowly from the phase-locked@@ -88,7 +88,8 @@ export function Stroboscope() {label(ctx, `OPEN ${Math.round((opened / n) * 100)}%`, tx0, h - 4, { size: 9, color: V.blueMid, ls: 0.16 });label(ctx, `${(a * 100).toFixed(1)} MM²`, tx1, h - 4, { size: 9, color: V.blueMid, align: "right", ls: 0.12 });} else {- label(ctx, "START AUDIO TO SEE THEM VIBRATE", tx0, h / 2, { size: 9, color: V.blueMid, ls: 0.16 });+ // in the area band, clear of the FLOW label below it+ labelBlock(ctx, "START AUDIO TO SEE THEM VIBRATE", tx0, (yA0 + yA1) / 2, tx1 - tx0, { size: 9, color: V.blueMid, ls: 0.16 });}});return <canvas ref={ref} className="instrument-canvas" aria-label="Vocal folds seen from above, replayed slowly, with the glottal area and flow" role="img" />;diff --git a/src/ui/render/anatomy.ts b/src/ui/render/anatomy.tsindex c8304fb..7a77a16 100644--- a/src/ui/render/anatomy.ts+++ b/src/ui/render/anatomy.ts@@ -77,6 +77,9 @@ interface Echo {const ECHO_AGES = [0.09, 0.06, 0.03];+/** top of the cranium in body cm (profile.ts's skin outline peaks at 22.9), with a little air */+const CROWN = 23.4;+export class AnatomyRenderer {private particles: Particle[] = [];private scale = 20;@@ -102,14 +105,19 @@ export class AnatomyRenderer {resize(w: number, h: number): void {this.w = w;this.h = h;- // the readouts need room beside the head; a narrow screen moves them above and below it- this.compact = w < 560 || w / h < 0.95;+ // the readouts need room beside the head; a narrow screen (a phone) moves them above and below it.+ // A tall desktop screen keeps them beside it: the head is then fitted to the width and centred,+ // leaving room above and below, where the compact rows ran over the skull.+ this.compact = w < 560;const padX = 12, padT = this.compact ? 62 : 8, padB = this.compact ? 92 : 8;- this.scale = Math.max(1, Math.min((w - 2 * padX) / (VIEW.x1 - VIEW.x0), (h - padT - padB) / (VIEW.y1 - VIEW.y0)));+ // VIEW crops the top of the skull at the canvas edge; with readout rows above the head, the+ // whole crown must fit under them, or the cut-off part draws over the readouts+ const y1 = this.compact ? CROWN : VIEW.y1;+ this.scale = Math.max(1, Math.min((w - 2 * padX) / (VIEW.x1 - VIEW.x0), (h - padT - padB) / (y1 - VIEW.y0)));// left-aligned when there is room to spare, so the readouts get the space in front of the faceconst spare = w - 2 * padX - (VIEW.x1 - VIEW.x0) * this.scale;- this.ox = padX + Math.min(spare / 2, Math.max(0, spare - 220)) - VIEW.x0 * this.scale;- this.oy = padT + Math.max(0, (h - padT - padB - (VIEW.y1 - VIEW.y0) * this.scale) / 2) + VIEW.y1 * this.scale;+ this.ox = padX + (this.compact ? spare / 2 : Math.min(spare / 2, Math.max(0, spare - 220))) - VIEW.x0 * this.scale;+ this.oy = padT + Math.max(0, (h - padT - padB - (y1 - VIEW.y0) * this.scale) / 2) + y1 * this.scale;for (const p of this.particles) p.px = NaN;}diff --git a/src/ui/render/anatomy3d.ts b/src/ui/render/anatomy3d.tsindex 68370da..187f540 100644--- a/src/ui/render/anatomy3d.ts+++ b/src/ui/render/anatomy3d.ts@@ -641,7 +641,7 @@ export class Anatomy3D {resize(w: number, h: number): void {this.w = w;this.h = h;- this.compact = w < 560 || w / h < 0.95;+ this.compact = w < 560;this.camera.aspect = w / h;// on a wide screen the head sits left of centre, leaving the right for the readoutsif (this.compact) this.camera.clearViewOffset();diff --git a/src/ui/render/vector.ts b/src/ui/render/vector.tsindex 358ff49..2d178e6 100644--- a/src/ui/render/vector.ts+++ b/src/ui/render/vector.ts@@ -127,6 +127,43 @@ export function label(ctx: CanvasRenderingContext2D, text: string, x: number, y:ctx.restore();}+/** Width of a label as label() would draw it (same font and letter spacing). */+export function labelWidth(ctx: CanvasRenderingContext2D, text: string, o: LabelOpts = {}): number {+ const size = o.size ?? 11;+ ctx.save();+ ctx.font = hfont(size, o.weight);+ if (hasLetterSpacing) (ctx as CanvasRenderingContext2D & { letterSpacing: string }).letterSpacing = `${((o.ls ?? 0.14) * size).toFixed(2)}px`;+ const wd = ctx.measureText(text).width;+ ctx.restore();+ return wd;+}++/** Words of a label broken into lines no wider than maxW. */+export function wrapLabel(ctx: CanvasRenderingContext2D, text: string, maxW: number, o: LabelOpts = {}): string[] {+ const lines: string[] = [];+ for (const word of text.split(/\s+/)) {+ const last = lines[lines.length - 1];+ if (last !== undefined && labelWidth(ctx, `${last} ${word}`, o) <= maxW) lines[lines.length - 1] = `${last} ${word}`;+ else lines.push(word);+ }+ return lines;+}++/** line height of labelBlock() */+export const blockLineH = (size = 11) => size * 1.6;++/**+ * A message wrapped to maxW with its lines centred on y (placeholders like "start audio to see+ * them vibrate"), so it never runs off a narrow screen.+ */+export function labelBlock(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, maxW: number, o: LabelOpts = {}): void {+ const size = o.size ?? 11;+ const lines = wrapLabel(ctx, text, maxW, o);+ const lh = blockLineH(size);+ const y0 = y - ((lines.length - 1) * lh) / 2 + size * 0.35;+ lines.forEach((line, i) => label(ctx, line, x, y0 + i * lh, o));+}+/** Chaikin corner cutting (closed shapes), for soft tissue the engine gives as coarse polygons */export function chaikin(p: Pt[], it = 2): Pt[] {let q = p.length > 1 && p[0][0] === p[p.length - 1][0] && p[0][1] === p[p.length - 1][1] ? p.slice(0, -1) : p.slice();diff --git a/src/ui/styles.css b/src/ui/styles.cssindex 0e5ddc1..b5d7e35 100644--- a/src/ui/styles.css+++ b/src/ui/styles.css@@ -1167,8 +1167,9 @@ body {.app {display: grid;grid-template-columns: minmax(0, 1fr);- grid-template-rows: auto auto;- align-content: start;+ /* the wall fills the window under the top bar, and grows (the page scrolls) when a short+ window can't fit what the screens hold, rather than squeezing them over each other */+ grid-template-rows: auto minmax(min-content, 1fr);min-height: 100vh;gap: 8px;padding: 6px 16px 16px;@@ -1342,19 +1343,22 @@ button.ghost:hover,display: grid;grid-template-columns: minmax(0, 700fr) minmax(0, 696fr);gap: 12px;- height: max(760px, calc(100vh - 70px));+ min-height: 560px;}+/* Each mode's screens sit in rows. A row of controls (encoders, pads, text) is "auto": as tall as+ they are. A row of canvases is minmax(min-content, share): they split what is left by share,+ never shorter than their header and minimum body. (Giving control rows a share too made a short+ window inflate every row in proportion to the tallest one's content.) */.right {display: grid;gap: 12px;- min-height: 0;min-width: 0;}.right-play {grid-template-columns: minmax(0, 284fr) minmax(0, 58fr) minmax(0, 342fr);- grid-template-rows: minmax(0, 200fr) minmax(0, 200fr) minmax(0, 224fr) minmax(0, 172fr);+ grid-template-rows: minmax(min-content, 200fr) minmax(min-content, 200fr) auto minmax(min-content, 172fr);grid-template-areas: "tube tube folds" "spec spec spec" "vowels voice voice" "keys keys keys";}@@ -1423,10 +1427,23 @@ button.ghost:hover,.screen-body {position: relative;- flex: 1;+ flex: 1 1 auto;+ display: flex;+ flex-direction: column;min-height: 110px;}+/* Only canvases (and scrollers) are laid over the body with position: absolute; anything made of+ DOM elements sits in flow and fills the body, so the screen grows to fit it. Absolutely+ positioned DOM content has no height of its own and ran over its neighbours when squeezed. */+.screen-body > .enc-pages,+.screen-body > .say,+.screen-body > .lyrics,+.screen-body > .pads,+.screen-body > .transport {+ flex: 1 1 auto;+}+.screen-body > canvas,.screen-body > .anatomy,.screen-body > .creature-canvas {@@ -1511,8 +1528,6 @@ button.ghost:hover,/* ---------- encoders (OP-1 style) */.enc-pages {- position: absolute;- inset: 0;display: flex;flex-direction: column;padding: 2px 10px 10px;@@ -1554,7 +1569,6 @@ button.ghost:hover,display: grid;grid-template-columns: repeat(4, minmax(0, 1fr));align-items: center;- min-height: 0;}.enc-row.cols-2 {@@ -1587,8 +1601,8 @@ button.ghost:hover,.enc-dial {position: relative;- width: 76px;- height: 76px;+ width: min(76px, 100%);+ aspect-ratio: 1;touch-action: pan-y;cursor: ns-resize;}@@ -1644,14 +1658,8 @@ button.ghost:hover,justify-content: center;}-/* a screen holding encoders is as tall as they need (tabs, two-line labels, dial, value, unit) */-.screen .screen-body:has(> .enc-pages) {- min-height: 176px;-}-.s-cparams .enc-dial {- width: 62px;- height: 62px;+ width: min(62px, 100%);}.s-cparams .enc-value {@@ -1799,6 +1807,13 @@ input[type="range"]::-moz-range-thumb {box-shadow: 0 0 4px rgba(79, 182, 242, 0.5);}+/* the tagline gives way so the top bar stays one row on a laptop screen */+@media (max-width: 1419px) {+ .tagline {+ display: none;+ }+}+/* ---------- narrow screens: one column, the face first */@media (max-width: 1100px) {.wall {@@ -1817,9 +1832,6 @@ input[type="range"]::-moz-range-thumb {.right-play .screen-body {min-height: 190px;}- .s-voice .screen-body {- min-height: 230px;- }}/* phones: the keys strip stacks under its MIDI button; flex: 1 from a zero basis collapsed it@@ -1835,10 +1847,6 @@ input[type="range"]::-moz-range-thumb {.app {padding: 6px 8px 12px;}- /* encoders go two by two here: two rows of them */- .screen .screen-body:has(> .enc-pages) {- min-height: 350px;- }.right-play {grid-template-columns: minmax(0, 1fr);grid-template-areas: "tube" "folds" "spec" "vowels" "voice" "keys";@@ -1850,15 +1858,12 @@ input[type="range"]::-moz-range-thumb {grid-template-columns: repeat(2, minmax(0, 1fr));row-gap: 10px;}- .s-voice .screen-body {- min-height: 380px;- }}/* ---------- Speak */.right-speak {grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);- grid-template-rows: minmax(0, 192fr) minmax(0, 236fr) minmax(0, 214fr) minmax(0, 190fr);+ grid-template-rows: auto minmax(min-content, 236fr) auto minmax(min-content, 190fr);grid-template-areas: "say say" "score score" "chart chart" "tube folds";}@@ -1867,8 +1872,6 @@ input[type="range"]::-moz-range-thumb {.s-chart { grid-area: chart; }.say {- position: absolute;- inset: 0;padding: 6px 14px 10px;display: grid;grid-template-rows: auto auto minmax(0, 1fr);@@ -1969,15 +1972,10 @@ input[type="range"]::-moz-range-thumb {padding: 0 8px;}-.s-chart .screen-body {- overflow: auto;-}-+/* the chart is as tall as its table; it scrolls sideways when the screen is narrower than it */.s-chart .chart-scroll {- position: absolute;- inset: 0;padding: 2px 12px 8px;- overflow: auto;+ overflow-x: auto;}.ipa-chart {@@ -2084,12 +2082,16 @@ input[type="range"]::-moz-range-thumb {.say-actions {flex-direction: row;}+ /* room to wrap here, rather than cut the transcription short */+ .say .transcription {+ white-space: normal;+ }}/* ---------- Sing */.right-sing {grid-template-columns: minmax(0, 342fr) minmax(0, 342fr);- grid-template-rows: minmax(0, 320fr) minmax(0, 134fr) minmax(0, 206fr) minmax(0, 172fr);+ grid-template-rows: minmax(min-content, 320fr) auto auto minmax(min-content, 172fr);grid-template-areas: "roll roll" "lyrics lyrics" "spec voice" "keys keys";}@@ -2112,8 +2114,6 @@ input[type="range"]::-moz-range-thumb {}.lyrics {- position: absolute;- inset: 0;padding: 6px 14px 10px;display: grid;grid-template-rows: auto minmax(0, 1fr);@@ -2225,7 +2225,7 @@ input[type="range"]::-moz-range-thumb {/* ---------- Beatbox */.right-beatbox {grid-template-columns: minmax(0, 392fr) minmax(0, 292fr);- grid-template-rows: minmax(0, 236fr) minmax(0, 176fr) minmax(0, 318fr) minmax(0, 102fr);+ grid-template-rows: minmax(min-content, 236fr) minmax(min-content, 176fr) auto auto;grid-template-areas: "seq seq" "wf wf" "pads transport" "keys keys";}@@ -2328,12 +2328,10 @@ input[type="range"]::-moz-range-thumb {/* pads: framed, the symbol large */.s-pads .pads {- position: absolute;- inset: 0;padding: 6px 14px 12px;display: grid;grid-template-columns: repeat(2, minmax(0, 1fr));- grid-auto-rows: minmax(0, 1fr);+ grid-auto-rows: minmax(min-content, 1fr);gap: 6px;}@@ -2400,11 +2398,9 @@ input[type="range"]::-moz-range-thumb {/* transport */.s-transport .transport {- position: absolute;- inset: 0;padding: 4px 14px 10px;display: grid;- grid-template-rows: auto minmax(0, 1fr) auto auto;+ grid-template-rows: auto minmax(min-content, 1fr) auto auto;gap: 8px;margin: 0;}@@ -2424,13 +2420,16 @@ input[type="range"]::-moz-range-thumb {}.transport-encoders {- position: relative;- min-height: 132px;+ display: flex;+ flex-direction: column;+}++.transport-encoders > .enc-pages {+ flex: 1 1 auto;}.s-transport .enc-dial {- width: 60px;- height: 60px;+ width: min(60px, 100%);}.s-transport .enc-value {@@ -2554,7 +2553,7 @@ input[type="range"]::-moz-range-thumb {/* ---------- Bestiary */.right-bestiary {grid-template-columns: minmax(0, 342fr) minmax(0, 342fr);- grid-template-rows: minmax(0, 196fr) minmax(0, 196fr) minmax(0, 232fr) minmax(0, 120fr) minmax(0, 88fr);+ grid-template-rows: minmax(min-content, 196fr) minmax(min-content, 196fr) auto minmax(min-content, 150fr) auto;grid-template-areas: "gallery gallery" "wf wf" "calls cparams" "airway airway" "keys keys";}@@ -2563,6 +2562,12 @@ input[type="range"]::-moz-range-thumb {.s-cparams { grid-area: cparams; }.s-airway { grid-area: airway; }+/* the airway's share is small; a lower floor keeps its row from stretching the others in a short window */+.s-airway .screen-body {+ min-height: 80px;+}++/* the gallery is drawings that scale with the screen, laid over its body like a canvas */.s-gallery .specimens {position: absolute;inset: 0;@@ -2708,6 +2713,15 @@ input[type="range"]::-moz-range-thumb {color: var(--blue-dim);}+.cparams-role {+ margin: 2px 14px 0;+ font-size: 9px;+ line-height: 1.5;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: var(--blue-mid);+}+.s-cparams .enc-label {font-size: 9px;letter-spacing: 0.12em;diff --git a/tools/layout-lint.ts b/tools/layout-lint.tsnew file mode 100644index 0000000..6ca2ad1--- /dev/null+++ b/tools/layout-lint.ts@@ -0,0 +1,279 @@+/**+ * Layout lint: loads every mode at phone, tablet and desktop sizes in headless Chromium, before and+ * after audio starts, and fails on layout mistakes a screenshot review keeps missing:+ *+ * - overlap two pieces of text or controls drawn over each other (DOM text, buttons, inputs,+ * dials, and text drawn on canvases, which the page reports by wrapping fillText)+ * - clipped content cut off by an overflow: hidden box (a panel too short for what it holds)+ * - spill content that runs outside its screen's frame+ * - screens two screens, or a screen and the top bar, overlapping+ * - canvas-edge canvas text running off its canvas+ * - h-scroll the page scrolls sideways+ * - small-text DOM text under 8 px or canvas text under 7 px+ *+ * Opt-outs, for things meant to sit on top of other things:+ * - data-layout="overlay" on an element: it and its contents are exempt from overlap checks+ * (the start prompt and the beat letter float over the face on purpose)+ * - data-layout="layered" on an element: its contents may overlap each other, but not anything+ * outside it (piano keys: the black keys sit on the white ones)+ * - data-layout="scatter" on a canvas: its text may overlap other text on the same canvas+ * (a chart that plots labels at data positions)+ * Text truncated with an ellipsis or a line clamp is reported as a warning, not an error.+ *+ * Usage: bun tools/layout-lint.ts [--url http://...] [--out out/layout] [--only 1440x900] [--mode play]+ * Without --url it starts its own Vite dev server (build the wasm first: bun run wasm).+ * Screenshots of every failing view are saved under --out.+ */+import { chromium, type Page } from "playwright-core";+import { mkdirSync, rmSync } from "node:fs";++const arg = (name: string) => {+ const i = process.argv.indexOf(`--${name}`);+ return i > 0 ? process.argv[i + 1] : undefined;+};++export const VIEWPORTS: { w: number; h: number }[] = [+ { w: 375, h: 812 }, // phone+ { w: 768, h: 1024 }, // tablet, portrait+ { w: 1024, h: 768 }, // tablet, landscape; small laptop+ { w: 1280, h: 720 },+ { w: 1366, h: 768 },+ { w: 1440, h: 900 },+ { w: 1920, h: 1080 },+ { w: 2560, h: 1440 },+];+const MODES = ["play", "speak", "sing", "bestiary", "beatbox"] as const;++interface Problem {+ kind: string;+ detail: string;+ warn?: boolean;+}++/** runs in the page: collects the boxes and returns the problems */+function inspect(): Problem[] {+ type R = { x0: number; y0: number; x1: number; y1: number };+ type Atom = { el: Element; r: R; name: string; overlay: boolean; canvas?: HTMLCanvasElement; scatter?: boolean };+ const TOL = 1.5;+ const problems: Problem[] = [];+ const rect = (b: DOMRect): R => ({ x0: b.left, y0: b.top, x1: b.right, y1: b.bottom });+ const meet = (a: R, b: R): R => ({ x0: Math.max(a.x0, b.x0), y0: Math.max(a.y0, b.y0), x1: Math.min(a.x1, b.x1), y1: Math.min(a.y1, b.y1) });+ const w = (r: R) => r.x1 - r.x0;+ const h = (r: R) => r.y1 - r.y0;+ const empty = (r: R) => w(r) <= 0.5 || h(r) <= 0.5;+ const fmt = (r: R) => `[${Math.round(r.x0)},${Math.round(r.y0)} ${Math.round(w(r))}×${Math.round(h(r))}]`;+ const where = (el: Element): string => {+ const screen = el.closest(".screen")?.getAttribute("aria-label") ?? (el.closest(".topbar") ? "top bar" : "page");+ return screen;+ };+ const nameOf = (el: Element, text?: string): string => {+ const t = (text ?? (el as HTMLElement).innerText ?? el.getAttribute("aria-label") ?? "").replace(/\s+/g, " ").trim().slice(0, 40);+ const cls = typeof el.className === "string" && el.className ? "." + el.className.trim().split(/\s+/)[0] : "";+ return `${el.tagName.toLowerCase()}${cls}${t ? ` "${t}"` : ""} in ${where(el)}`;+ };+ const visible = (el: Element) => el.checkVisibility({ opacityProperty: true, visibilityProperty: true });+ const overlay = (el: Element) => !!el.closest('[data-layout="overlay"]');++ // the part of a box its overflow-clipping ancestors let through; `hidden` is what overflow:hidden cut off+ const clipOf = (el: Element, r: R, self: boolean) => {+ let vis = r;+ let cutBy: Element | null = null;+ let truncated = false;+ for (let a = self ? el : el.parentElement; a && a !== document.documentElement; a = a.parentElement) {+ const cs = getComputedStyle(a);+ if (cs.textOverflow === "ellipsis" || (cs.webkitLineClamp && cs.webkitLineClamp !== "none")) truncated = true;+ if (cs.overflowX === "visible" && cs.overflowY === "visible") continue;+ const before = vis;+ vis = meet(vis, rect(a.getBoundingClientRect()));+ const scrolls = /auto|scroll/.test(cs.overflowX + cs.overflowY);+ if (!scrolls && !cutBy && (w(before) - w(vis) > TOL || h(before) - h(vis) > TOL)) cutBy = a;+ }+ return { vis, cutBy, truncated };+ };++ const atoms: Atom[] = [];+ // text is clipped by its own element too; a control's own box is not+ const consider = (el: Element, r: R, name: string, extra: Partial<Atom> = {}, self = false) => {+ if (empty(r)) return;+ const { vis, cutBy, truncated } = clipOf(el, r, self);+ if (cutBy) problems.push({ kind: truncated ? "truncated" : "clipped", warn: truncated, detail: `${name} ${fmt(r)} is cut off by ${nameOf(cutBy, "")}` });+ if (empty(vis)) return; // scrolled out of view+ atoms.push({ el, r: vis, name, overlay: overlay(el), ...extra });+ };++ // DOM text, one box per line of each text node+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {+ const text = n.textContent ?? "";+ const el = n.parentElement;+ if (!el || !text.trim() || !visible(el) || el.closest("script,style,option")) continue;+ if (el.closest("textarea")) continue; // the textarea itself is the box+ const size = parseFloat(getComputedStyle(el).fontSize);+ if (size < 8) problems.push({ kind: "small-text", detail: `${nameOf(el, text)} is ${size}px` });+ const range = document.createRange();+ range.selectNodeContents(n);+ for (const b of range.getClientRects()) consider(el, rect(b), nameOf(el, text), {}, true);+ }+ // controls and drawings without text of their own+ for (const el of document.querySelectorAll("button, input, textarea, select, svg, img")) {+ if (el.closest("svg") !== el && el.tagName.toLowerCase() === "svg") continue;+ if (el.parentElement?.closest("svg")) continue;+ if (!visible(el)) continue;+ consider(el, rect(el.getBoundingClientRect()), nameOf(el));+ }+ // canvas text, recorded by the fillText hook installed before the page loaded+ const log = (window as unknown as { __canvasText?: Map<HTMLCanvasElement, { text: string; x0: number; y0: number; x1: number; y1: number; size: number }[]> }).__canvasText;+ if (log) {+ for (const [canvas, items] of log) {+ if (!canvas.isConnected || !visible(canvas)) continue;+ const cb = canvas.getBoundingClientRect();+ if (cb.width < 2 || cb.height < 2) continue;+ const sx = cb.width / canvas.width, sy = cb.height / canvas.height;+ const scatter = canvas.closest('[data-layout="scatter"]') !== null;+ for (const t of items) {+ const r: R = { x0: cb.left + t.x0 * sx, y0: cb.top + t.y0 * sy, x1: cb.left + t.x1 * sx, y1: cb.top + t.y1 * sy };+ const name = `canvas text "${t.text.slice(0, 40)}" in ${where(canvas)}`;+ if (t.size * sy < 7) problems.push({ kind: "small-text", detail: `${name} is ${(t.size * sy).toFixed(1)}px` });+ const inside = meet(r, rect(cb));+ if (w(r) - w(inside) > 2 || h(r) - h(inside) > 2) problems.push({ kind: "canvas-edge", detail: `${name} ${fmt(r)} runs off its canvas ${fmt(rect(cb))}` });+ consider(canvas, inside, name, { canvas, scatter });+ }+ }+ }++ // overlaps between unrelated atoms+ for (let i = 0; i < atoms.length; i++) {+ for (let j = i + 1; j < atoms.length; j++) {+ const a = atoms[i], b = atoms[j];+ if (a.overlay || b.overlay) continue;+ if (a.el === b.el && !a.canvas) continue;+ if (a.canvas && a.canvas === b.canvas && (a.scatter || b.scatter)) continue;+ if (a.el !== b.el && (a.el.contains(b.el) || b.el.contains(a.el))) continue;+ const layer = a.el.closest('[data-layout="layered"]');+ if (layer && layer === b.el.closest('[data-layout="layered"]')) continue;+ const m = meet(a.r, b.r);+ if (w(m) > TOL && h(m) > TOL) problems.push({ kind: "overlap", detail: `${a.name} ${fmt(a.r)} overlaps ${b.name} ${fmt(b.r)}` });+ }+ }++ // content outside its screen's frame+ for (const a of atoms) {+ const screen = a.el.closest(".screen");+ if (!screen || a.overlay) continue;+ const s = rect(screen.getBoundingClientRect());+ const m = meet(a.r, s);+ if (w(a.r) - w(m) > TOL || h(a.r) - h(m) > TOL) problems.push({ kind: "spill", detail: `${a.name} ${fmt(a.r)} runs outside its screen ${fmt(s)}` });+ }++ // a screen's parts inside its frame (a body taller than the screen pokes out of it)+ for (const screen of document.querySelectorAll(".screen")) {+ if (!visible(screen)) continue;+ const s = rect(screen.getBoundingClientRect());+ for (const part of screen.children) {+ const r = rect(part.getBoundingClientRect());+ if (r.x1 - s.x1 > TOL || r.y1 - s.y1 > TOL || s.x0 - r.x0 > TOL || s.y0 - r.y0 > TOL) problems.push({ kind: "spill", detail: `${nameOf(part, "")} ${fmt(r)} pokes out of its screen ${fmt(s)}` });+ }+ }++ // screens against each other and the top bar+ const frames = [...document.querySelectorAll(".screen, .topbar")].filter(visible);+ for (let i = 0; i < frames.length; i++) {+ for (let j = i + 1; j < frames.length; j++) {+ const m = meet(rect(frames[i].getBoundingClientRect()), rect(frames[j].getBoundingClientRect()));+ if (w(m) > TOL && h(m) > TOL) problems.push({ kind: "screens", detail: `${nameOf(frames[i], "")} overlaps ${nameOf(frames[j], "")}` });+ }+ }++ const sw = document.documentElement.scrollWidth;+ if (sw > window.innerWidth + 1) problems.push({ kind: "h-scroll", detail: `the page is ${sw}px wide in a ${window.innerWidth}px window` });+ return problems;+}++/** before any page script: record the text each canvas draws in its latest frame */+function hookCanvasText() {+ type Item = { text: string; x0: number; y0: number; x1: number; y1: number; size: number; frame: number };+ const log = new Map<HTMLCanvasElement, Item[]>();+ (window as unknown as { __canvasText: typeof log }).__canvasText = log;+ let frame = 0;+ const raf = window.requestAnimationFrame.bind(window);+ window.requestAnimationFrame = (cb) => raf((t) => {+ frame++;+ cb(t);+ });+ const fill = CanvasRenderingContext2D.prototype.fillText;+ CanvasRenderingContext2D.prototype.fillText = function (this: CanvasRenderingContext2D, text: string, x: number, y: number, maxWidth?: number) {+ fill.call(this, text, x, y, maxWidth as number);+ if (!text.trim() || this.globalAlpha < 0.05) return;+ const m = this.measureText(text);+ const t = this.getTransform();+ // the box in canvas pixels (the transforms used here only scale and translate)+ const xs = [x - m.actualBoundingBoxLeft, x + m.actualBoundingBoxRight].map((v) => t.a * v + t.e);+ const ys = [y - m.actualBoundingBoxAscent, y + m.actualBoundingBoxDescent].map((v) => t.d * v + t.f);+ const size = parseFloat(/(\d+(?:\.\d+)?)px/.exec(this.font)?.[1] ?? "10") * Math.abs(t.d);+ let items = log.get(this.canvas as HTMLCanvasElement);+ if (!items || (items.length && items[0].frame !== frame)) log.set(this.canvas as HTMLCanvasElement, (items = []));+ items.push({ text, x0: Math.min(...xs), y0: Math.min(...ys), x1: Math.max(...xs), y1: Math.max(...ys), size, frame });+ };+}++async function settle(page: Page) {+ await page.evaluate(() => document.fonts.ready);+ await page.waitForTimeout(350);+}++async function main() {+ const out = arg("out") ?? "out/layout";+ rmSync(out, { recursive: true, force: true });+ mkdirSync(out, { recursive: true });+ let url = arg("url");+ let server: { close(): Promise<void> } | undefined;+ if (!url) {+ const { createServer } = await import("vite");+ const s = await createServer({ server: { port: 0, strictPort: false, host: "127.0.0.1" }, logLevel: "error" });+ await s.listen();+ server = s;+ url = s.resolvedUrls!.local[0];+ }+ const only = arg("only");+ const onlyMode = arg("mode");+ const viewports = only ? VIEWPORTS.filter((v) => `${v.w}x${v.h}` === only).concat(VIEWPORTS.some((v) => `${v.w}x${v.h}` === only) ? [] : [{ w: +only.split("x")[0], h: +only.split("x")[1] }]) : VIEWPORTS;+ const modes = onlyMode ? [onlyMode] : MODES;++ const browser = await chromium.launch({ headless: true, args: ["--autoplay-policy=no-user-gesture-required"] });+ let errors = 0, warnings = 0;+ for (const { w, h } of viewports) {+ const page = await browser.newPage({ viewport: { width: w, height: h }, deviceScaleFactor: 1 });+ await page.addInitScript(hookCanvasText);+ page.on("pageerror", (e) => {+ console.log(` pageerror at ${w}x${h}: ${e.message}`);+ errors++;+ });+ await page.goto(url, { waitUntil: "networkidle" });+ for (const started of [false, true]) {+ if (started) {+ await page.locator(".topbar button.primary").click();+ await page.waitForSelector(".load", { timeout: 15000 });+ }+ for (const mode of modes) {+ await page.getByRole("radio", { name: new RegExp(`^${mode}$`, "i") }).click();+ await settle(page);+ const problems = (await page.evaluate(inspect)) as Problem[];+ const tag = `${w}x${h} ${mode}${started ? " (running)" : ""}`;+ const errs = problems.filter((p) => !p.warn), warns = problems.filter((p) => p.warn);+ errors += errs.length;+ warnings += warns.length;+ if (!problems.length) continue;+ console.log(`\n${tag}: ${errs.length} error(s), ${warns.length} warning(s)`);+ for (const p of [...errs, ...warns]) console.log(` ${p.warn ? "warn " : "ERROR"} ${p.kind.padEnd(11)} ${p.detail}`);+ if (errs.length) await page.screenshot({ path: `${out}/${w}x${h}-${mode}${started ? "-running" : ""}.png`, fullPage: true });+ }+ }+ await page.close();+ }+ await browser.close();+ await server?.close();+ console.log(`\nlayout lint: ${errors} error(s), ${warnings} warning(s) across ${viewports.length} sizes × ${modes.length} modes × idle/running`);+ process.exit(errors ? 1 : 0);+}++await main();