Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(songs): Synthesia-style piano-roll view for the layered MIDI player

[._.]/ Adam Eivyf8ba943b9467
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2c5e654b89..e5d0595383 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Added
+- **Song piano-roll (Synthesia) view:** the Song reader's layered MIDI player now has a **Staff ↔ Piano** toggle. Piano mode renders every selected layer as colored notes falling onto a piano keyboard and lights up each key as its note crosses the hit line — the aggregate of all checked voices played "on the piano" at once. Each layer gets a stable color shared by the falling notes, the keyboard glow, and a swatch on its layer checkbox; the fall stays sample-aligned to the audio by reading the player's live position. The keyboard geometry and per-note MIDI mapping live in a pure, unit-tested helper (`pianoKeyboard.js`); the multi-score player gained `position()`/`duration()` accessors.
- **CyberCity town redesign (part 2):** exploration mode now has a playable character — a theme-tinted articulated cyber-runner (two-segment limbs, emissive visor/core/soles, jet vents) with idle/walk/run animations, turning toward movement, banking into turns, and a hover pose during flyover. Third person is the new default exploration camera: a damped follow boom that shortens when it would clip a building; **V** (or city settings) swaps to the classic first-person view. Grounded movement now stops at the bay shoreline while the Data Harbor piers stay walkable. All the math lives in a pure, fully unit-tested rig module (`cityPlayerRig.js`).
- **CyberCity town redesign (part 1):** the city is now a coherent game town built from a master plan (`cityPlan.js` — single source of every district's parcel, with invariant tests). The north edge is a bay: animated water, a shoreline that clips the ground grid, and a new **Data Harbor** pier district visualizing the install's storage — one disk-stack silo per PostgreSQL table (height = rows, radius = size, orbiting ring on pgvector tables, migration obelisk) and one container rack per `data/` domain (lit slats = disk usage), with clickable holographic detail cards and a distinct "DB OFFLINE" state, fed by a new `GET /api/city/introspection` endpoint. Town fabric: an octagonal ring road with spokes to every district and a grand avenue to the harbor, an elevated transit loop with orbiting trams, instanced street lamps with light pools, plaza holo-trees, and deterministic per-app rooftop fixtures. Everything follows the existing theme-driven day/night system and quality presets.
diff --git a/client/src/components/songs/PianoRoll.jsx b/client/src/components/songs/PianoRoll.jsx
new file mode 100644
index 0000000000..3f61d58828
--- /dev/null
+++ b/client/src/components/songs/PianoRoll.jsx
@@ -0,0 +1,207 @@
+import { useCallback, useEffect, useMemo, useRef } from 'react';
+import { parseScore } from '../../lib/scoreNotation';
+import { buildSchedule } from '../../lib/scorePlayback';
+import {
+ buildKeyboardLayout,
+ keyboardRange,
+ midiNoteName,
+ BLACK_KEY_HEIGHT_RATIO,
+} from '../../lib/pianoKeyboard';
+
+// Synthesia-style piano-roll visualizer for the song system's layered MIDI
+// player. Renders every selected lead-sheet part as colored notes falling onto
+// a piano keyboard, lighting up the keys as each note crosses the hit line —
+// the aggregate of all layers played "on the piano" at once.
+//
+// Layout, key geometry and the per-note `midi` come from pure helpers
+// (pianoKeyboard.js / scorePlayback.js); this component only draws to a <canvas>
+// and runs the rAF clock. The live playhead comes from `getPosition()` (the
+// multi-score player's position() in score-seconds) so the fall stays
+// sample-aligned with the audio rather than running its own timer.
+
+// Per-layer colors, assigned by part index in the parent so the keyboard, the
+// falling notes and the layer checkboxes all agree. Bright, distinct hues that
+// read on the near-black canvas.
+const LAYER_COLORS = ['#3b82f6', '#22c55e', '#f59e0b', '#ec4899', '#a855f7', '#06b6d4', '#ef4444', '#14b8a6'];
+export const layerColor = (index) => LAYER_COLORS[((index % LAYER_COLORS.length) + LAYER_COLORS.length) % LAYER_COLORS.length];
+
+const VISIBLE_SECONDS = 3.4; // how far ahead the falling notes are shown (fall speed)
+const KEYBOARD_HEIGHT = 64; // px of keyboard at the bottom
+const NOTE_RADIUS = 3;
+const WHITE_KEY_FILL = '#e7e7ea';
+const WHITE_KEY_EDGE = '#9a9aa2';
+const BLACK_KEY_FILL = '#1b1b20';
+const BLACK_KEY_EDGE = '#000000';
+const HIT_LINE = '#3b82f6';
+const GRID_LINE = 'rgba(255,255,255,0.05)';
+const BG = '#0c0c0e';
+
+const roundRect = (ctx, x, y, w, h, r) => {
+ const rr = Math.max(0, Math.min(r, w / 2, h / 2));
+ if (ctx.roundRect) { ctx.beginPath(); ctx.roundRect(x, y, w, h, rr); return; }
+ ctx.beginPath();
+ ctx.moveTo(x + rr, y);
+ ctx.arcTo(x + w, y, x + w, y + h, rr);
+ ctx.arcTo(x + w, y + h, x, y + h, rr);
+ ctx.arcTo(x, y + h, x, y, rr);
+ ctx.arcTo(x, y, x + w, y, rr);
+ ctx.closePath();
+};
+
+/**
+ * @param {object} props
+ * @param {Array<{id:string,label:string,color:string,score:string}>} props.parts
+ * — the selected layers (raw lead-sheet text); parsed + scheduled here.
+ * @param {number} props.tempo — BPM applied to every part (mirrors the player).
+ * @param {()=>number} props.getPosition — live playhead in score-seconds (stable
+ * reference; reads the player's position()).
+ * @param {boolean} props.playing — drives the rAF loop; a static frame is drawn
+ * when paused.
+ * @param {number} [props.height=300]
+ */
+export default function PianoRoll({ parts, tempo, getPosition, playing, height = 300 }) {
+ const wrapRef = useRef(null);
+ const canvasRef = useRef(null);
+ const widthRef = useRef(0);
+ // Keep the latest getPosition without making it a draw() dependency (the parent
+ // hands a fresh closure each render; the rAF loop should not restart for that).
+ const getPositionRef = useRef(getPosition);
+ getPositionRef.current = getPosition;
+
+ // Parse + schedule every part once per parts/tempo change → flat note list.
+ const { notes, range } = useMemo(() => {
+ const all = [];
+ (parts || []).forEach((p) => {
+ const { events } = buildSchedule(parseScore(p.score), tempo);
+ events.forEach((ev) => {
+ if (ev.rest || !Number.isFinite(ev.midi)) return;
+ all.push({ midi: ev.midi, startSec: ev.startSec, durSec: ev.durSec, color: p.color });
+ });
+ });
+ return { notes: all, range: keyboardRange(all.map((n) => n.midi)) };
+ }, [parts, tempo]);
+
+ const draw = useCallback(() => {
+ const canvas = canvasRef.current;
+ const width = widthRef.current;
+ if (!canvas || !width) return;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return;
+
+ const pos = Math.max(0, getPositionRef.current?.() ?? 0);
+ const hitLineY = height - KEYBOARD_HEIGHT;
+ const pps = hitLineY / VISIBLE_SECONDS; // pixels per second of fall
+ const layout = buildKeyboardLayout({ lowMidi: range.lowMidi, highMidi: range.highMidi, width });
+ const keyByMidi = new Map(layout.keys.map((k) => [k.midi, k]));
+
+ ctx.clearRect(0, 0, width, height);
+ ctx.fillStyle = BG;
+ ctx.fillRect(0, 0, width, hitLineY);
+
+ // Faint vertical octave gridlines (on every C) to anchor the eye.
+ ctx.fillStyle = GRID_LINE;
+ layout.keys.forEach((k) => {
+ if (!k.isBlack && k.midi % 12 === 0) ctx.fillRect(k.x, 0, 1, hitLineY);
+ });
+
+ // Falling notes, clipped to the area above the keyboard so they vanish into
+ // the keys as they're played.
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(0, 0, width, hitLineY);
+ ctx.clip();
+ const active = new Map(); // midi → color of a currently-sounding note
+ notes.forEach((n) => {
+ const key = keyByMidi.get(n.midi);
+ if (!key) return;
+ const h = Math.max(2, n.durSec * pps);
+ const bottom = hitLineY - (n.startSec - pos) * pps;
+ const top = bottom - h;
+ if (n.startSec <= pos && pos < n.startSec + n.durSec) active.set(n.midi, n.color);
+ if (top >= hitLineY || bottom <= 0) return; // outside the visible fall window
+ const pad = key.isBlack ? 1 : 1.5;
+ roundRect(ctx, key.x + pad, top, Math.max(2, key.w - pad * 2), h, NOTE_RADIUS);
+ ctx.fillStyle = n.color;
+ ctx.globalAlpha = 0.92;
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ });
+ ctx.restore();
+
+ // Hit line.
+ ctx.fillStyle = HIT_LINE;
+ ctx.fillRect(0, hitLineY - 1, width, 2);
+
+ // Keyboard — white keys first, then black overlaid. Active keys glow in the
+ // sounding note's layer color.
+ const blackH = KEYBOARD_HEIGHT * BLACK_KEY_HEIGHT_RATIO;
+ layout.keys.filter((k) => !k.isBlack).forEach((k) => {
+ const lit = active.get(k.midi);
+ ctx.fillStyle = lit || WHITE_KEY_FILL;
+ ctx.fillRect(k.x, hitLineY, k.w, KEYBOARD_HEIGHT);
+ ctx.strokeStyle = WHITE_KEY_EDGE;
+ ctx.lineWidth = 1;
+ ctx.strokeRect(k.x + 0.5, hitLineY + 0.5, k.w - 1, KEYBOARD_HEIGHT - 1);
+ // Octave label on each C.
+ if (k.midi % 12 === 0 && k.w > 14) {
+ ctx.fillStyle = lit ? '#0c0c0e' : '#71717a';
+ ctx.font = '9px ui-sans-serif, system-ui, sans-serif';
+ ctx.textAlign = 'center';
+ ctx.fillText(midiNoteName(k.midi), k.x + k.w / 2, hitLineY + KEYBOARD_HEIGHT - 5);
+ }
+ });
+ layout.keys.filter((k) => k.isBlack).forEach((k) => {
+ const lit = active.get(k.midi);
+ ctx.fillStyle = lit || BLACK_KEY_FILL;
+ roundRect(ctx, k.x, hitLineY, k.w, blackH, 2);
+ ctx.fill();
+ ctx.strokeStyle = BLACK_KEY_EDGE;
+ ctx.lineWidth = 1;
+ ctx.stroke();
+ });
+ }, [notes, range, height]);
+
+ // Size the canvas to the container (devicePixelRatio-aware) and redraw.
+ useEffect(() => {
+ const el = wrapRef.current;
+ if (!el) return undefined;
+ const resize = () => {
+ const w = Math.floor(el.clientWidth);
+ if (!w) return;
+ widthRef.current = w;
+ const canvas = canvasRef.current;
+ if (!canvas) return;
+ const dpr = (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
+ canvas.width = Math.round(w * dpr);
+ canvas.height = Math.round(height * dpr);
+ canvas.style.width = `${w}px`;
+ canvas.style.height = `${height}px`;
+ const ctx = canvas.getContext('2d');
+ if (ctx) ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ draw();
+ };
+ resize();
+ const ro = new ResizeObserver(resize);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [height, draw]);
+
+ // rAF clock: animate the fall while playing, otherwise draw a single frame.
+ useEffect(() => {
+ draw();
+ if (!playing) return undefined;
+ let raf = 0;
+ const loop = () => { draw(); raf = requestAnimationFrame(loop); };
+ raf = requestAnimationFrame(loop);
+ return () => cancelAnimationFrame(raf);
+ }, [playing, draw]);
+
+ return (
+ <div ref={wrapRef} className="w-full">
+ <canvas ref={canvasRef} className="block w-full rounded-lg bg-[#0c0c0e]" aria-hidden="true" />
+ <p className="sr-only">
+ Piano-roll visualization of the selected song layers falling onto a piano keyboard.
+ </p>
+ </div>
+ );
+}
diff --git a/client/src/components/songs/PianoRoll.test.jsx b/client/src/components/songs/PianoRoll.test.jsx
new file mode 100644
index 0000000000..d694cb62ba
--- /dev/null
+++ b/client/src/components/songs/PianoRoll.test.jsx
@@ -0,0 +1,73 @@
+import { render, cleanup } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import PianoRoll, { layerColor } from './PianoRoll.jsx';
+
+describe('layerColor', () => {
+ it('cycles through the palette and wraps at both ends', () => {
+ expect(layerColor(0)).not.toBe(layerColor(1));
+ expect(layerColor(8)).toBe(layerColor(0)); // palette length is 8 → wraps
+ expect(layerColor(-1)).toBe(layerColor(7)); // negative wraps positively
+ });
+});
+
+// jsdom has no canvas/ResizeObserver and reports 0 widths — stub the minimum the
+// component needs so draw() runs and we can assert it painted.
+const makeCtx = () => ({
+ clearRect: vi.fn(), fillRect: vi.fn(), strokeRect: vi.fn(), fillText: vi.fn(),
+ save: vi.fn(), restore: vi.fn(), beginPath: vi.fn(), closePath: vi.fn(),
+ rect: vi.fn(), clip: vi.fn(), roundRect: vi.fn(), fill: vi.fn(), stroke: vi.fn(),
+ moveTo: vi.fn(), arcTo: vi.fn(), setTransform: vi.fn(),
+ fillStyle: '', strokeStyle: '', lineWidth: 1, font: '', textAlign: '', globalAlpha: 1,
+});
+
+describe('<PianoRoll>', () => {
+ let ctx;
+ beforeEach(() => {
+ ctx = makeCtx();
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(ctx);
+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });
+ Object.defineProperty(HTMLElement.prototype, 'clientWidth', { configurable: true, get() { return 800; } });
+ });
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete HTMLElement.prototype.clientWidth;
+ });
+
+ it('paints the keyboard and falling notes for the given parts', () => {
+ render(
+ <PianoRoll
+ parts={[{ id: 'm', label: 'Melody', color: '#3b82f6', score: 'time: 4/4\ntempo: 120\n| C4q E4q G4q |' }]}
+ tempo={120}
+ getPosition={() => 0}
+ playing={false}
+ />,
+ );
+ expect(ctx.clearRect).toHaveBeenCalled();
+ expect(ctx.fillRect).toHaveBeenCalled(); // keyboard keys + background painted
+ expect(ctx.fill).toHaveBeenCalled(); // a falling note bar was drawn
+ });
+
+ it('reads the live position each frame from getPosition (so the fall is audio-synced)', () => {
+ const getPosition = vi.fn(() => 0);
+ render(
+ <PianoRoll
+ parts={[{ id: 'm', label: 'Melody', color: '#22c55e', score: 'time: 4/4\ntempo: 120\n| C4q |' }]}
+ tempo={120}
+ getPosition={getPosition}
+ playing={false}
+ />,
+ );
+ expect(getPosition).toHaveBeenCalled();
+ });
+
+ it('renders the default keyboard without crashing when there are no parts', () => {
+ expect(() => render(
+ <PianoRoll parts={[]} tempo={120} getPosition={() => 0} playing={false} />,
+ )).not.toThrow();
+ // Background + default 2-octave keyboard still draw.
+ expect(ctx.clearRect).toHaveBeenCalled();
+ expect(ctx.fillRect).toHaveBeenCalled();
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 46c98261ae..278792fe08 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -91,8 +91,9 @@ grep -i "what you want to do" client/src/lib/README.md
| `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps; `tuningQuality(cents)` → `{ level, label }` buckets a cents deviation into `in-tune`/`close`/`off`/`none` (thresholds `IN_TUNE_CENTS`/`CLOSE_CENTS`) for the tuner color readout. |
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
| `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`. |
+| `pianoKeyboard.js` | Piano-keyboard geometry for the song system's Synthesia-style piano-roll visualizer (`<PianoRoll>`). Pure math, no canvas/React. `keyboardRange(midis, { minSemitones })` → `{ lowMidi, highMidi }` padded out to whole C–B octaves (min 2) so the keyboard always starts on a C / ends on a B and never collapses for a one-note part; `buildKeyboardLayout({ lowMidi, highMidi, width })` → `{ keys:[{midi,isBlack,x,w}], whiteWidth, blackWidth }` (white keys tiled edge-to-edge, black keys overlaid centered on the boundary, narrower); plus `isBlackKey(midi)`, `midiNoteName(midi)` (sharps spelling), and the `BLACK_KEY_RATIO`/`BLACK_KEY_HEIGHT_RATIO` constants. Pairs with `scorePlayback`'s per-note `midi` field. |
| `scoreNotation.js` | Parser for the PortOS lead-sheet notation — a dependency-free text format for melody + chords + lyrics that the `<ScoreSheet>` SVG renderer draws (no abcjs / VexFlow / OSMD). `parseScore(text)` → `{ clef, key, keySig, time, tempo, measures, errors }`; plus `parsePitch`, `diatonicStep`, `durationBeats`, `keySignature`, `DURATIONS`, and `scoreHasMusic(text)`. Forgiving: bad tokens collect into `errors` and are skipped, never thrown. Pure — the renderer only does geometry. |
-| `scorePlayback.js` | Melody synth playback for the lead-sheet notation — companion to `songPlayback.js` (which stacks recorded vocal takes), this synthesizes the WRITTEN melody as soft `OscillatorNode` reference tones on a lazy shared `AudioContext` (no MIDI.js / Tone.js). `buildSchedule(score, bpm?)` is the pure notes→`{ freq, startSec, durSec }` mapping (A4=440, quarter-beat = `(60/bpm)·(beatValue/4)` so it honors the time signature); `noteToFrequency`/`midiToFreq`/`pitchToMidi` convert pitches; `createScorePlayer(score, { bpm, onNote, onEnded })` plays/pauses/stops with a lookahead scheduler and emits the now-sounding note index for the `<ScoreSheet>` playhead; `createMultiScorePlayer(parts, { bpm, onNote, onEnded })` synthesizes several parts (melody + checked harmony) together on one master bus (level backs off as voices stack) with a per-part `onNote(partId, index)` playhead. |
+| `scorePlayback.js` | Melody synth playback for the lead-sheet notation — companion to `songPlayback.js` (which stacks recorded vocal takes), this synthesizes the WRITTEN melody as soft `OscillatorNode` reference tones on a lazy shared `AudioContext` (no MIDI.js / Tone.js). `buildSchedule(score, bpm?)` is the pure notes→`{ midi, freq, startSec, durSec }` mapping (A4=440, quarter-beat = `(60/bpm)·(beatValue/4)` so it honors the time signature; `midi` feeds the `<PianoRoll>` key mapping); `noteToFrequency`/`midiToFreq`/`pitchToMidi` convert pitches; `createScorePlayer(score, { bpm, onNote, onEnded })` plays/pauses/stops with a lookahead scheduler and emits the now-sounding note index for the `<ScoreSheet>` playhead; `createMultiScorePlayer(parts, { bpm, onNote, onEnded })` synthesizes several parts (melody + checked harmony) together on one master bus (level backs off as voices stack) with a per-part `onNote(partId, index)` playhead, plus `position()`/`duration()` (score-seconds) for the continuous piano-roll visualizer. |
| `singToScore.js` | Sing-to-score transcription for the song system — turns a sung pitch track into lead-sheet notation. `segmentPitchTrack(track, opts)` groups `[{ tMs, hz, clarity }]` frames into note/rest segments (median pitch per stable span, rests where clarity drops, sub-threshold note/rest filtering); `quantizeSegments(segments, { bpm, beatValue })` snaps each duration to the nearest grid value (w/h/q/e/s) at the song tempo; `segmentsToScoreDsl(quantized, { keySig, beatsPerBar, beatValue })` spells notes enharmonically from the key signature and emits measure-grouped `\| … \|` body text; `transcribePitchTrack(track, { bpm, key, beatsPerBar, beatValue })` runs all three. Round-trips cleanly back through `parseScore`. Reuses `frequencyToNote` (pitchDetect) + the duration/key tables (scoreNotation) — no DSP/notation library. |
| `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`, and `rhythmShapeLabel(id)` (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). Pure data; pickers and docs read the same source so they can't drift. |
| `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 92c75b84e0..98e0030bc8 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -57,6 +57,7 @@ export * from './voiceLabel.js';
export * from './cityPlaybackFrame.js';
export * from './colorMatch.js';
export * from './metronome.js';
+export * from './pianoKeyboard.js';
export * from './pitchDetect.js';
export * from './scoreNotation.js';
export * from './scorePlayback.js';
diff --git a/client/src/lib/pianoKeyboard.js b/client/src/lib/pianoKeyboard.js
new file mode 100644
index 0000000000..c9b4d81ff7
--- /dev/null
+++ b/client/src/lib/pianoKeyboard.js
@@ -0,0 +1,98 @@
+// Piano-keyboard geometry for the song system's Synthesia-style piano-roll
+// visualizer (<PianoRoll>). Pure math, no canvas/React — turns a set of MIDI
+// note numbers into a left-to-right key layout (white keys tiled edge-to-edge,
+// black keys overlaid on the boundaries) so the renderer only does drawing and
+// the layout is unit-testable. Companion to scorePlayback.js, whose
+// buildSchedule now carries a `midi` per note.
+
+// Pitch classes (semitone within an octave) that map to WHITE keys. Everything
+// else is a black key.
+const WHITE_PITCH_CLASSES = new Set([0, 2, 4, 5, 7, 9, 11]);
+const NOTE_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
+
+// Positive modulo so negative MIDI numbers (below C-1) still classify correctly.
+const pitchClass = (midi) => ((midi % 12) + 12) % 12;
+
+// True when this MIDI note is a black (sharp/flat) key.
+export const isBlackKey = (midi) => !WHITE_PITCH_CLASSES.has(pitchClass(midi));
+
+// Scientific note name for a MIDI number (sharps spelling). MIDI 60 → "C4".
+export const midiNoteName = (midi) => {
+ if (!Number.isFinite(midi)) return '';
+ return `${NOTE_NAMES[pitchClass(midi)]}${Math.floor(midi / 12) - 1}`;
+};
+
+// Black-key width as a fraction of a white-key width (real pianos ≈ 0.6).
+export const BLACK_KEY_RATIO = 0.62;
+// Black keys are shorter than white keys — fraction of the keyboard height.
+export const BLACK_KEY_HEIGHT_RATIO = 0.62;
+
+/**
+ * Pad a set of MIDI numbers out to whole C–B octaves, with a minimum span, so
+ * the keyboard always starts on a C and ends on a B and never collapses to a
+ * sliver for a one-note part.
+ *
+ * @param {number[]} midis — note numbers in play (rests already filtered out).
+ * @param {object} [opts]
+ * @param {number} [opts.minSemitones=24] — minimum keyboard span (2 octaves).
+ * @returns {{ lowMidi:number, highMidi:number }} inclusive, lowMidi is a C,
+ * highMidi is a B.
+ */
+export const keyboardRange = (midis, { minSemitones = 24 } = {}) => {
+ const finite = (midis || []).filter((m) => Number.isFinite(m));
+ // Default to a comfortable C4-centered window when there are no notes.
+ let min = finite.length ? Math.min(...finite) : 60;
+ let max = finite.length ? Math.max(...finite) : 71;
+
+ // Snap the low end down to the C at or below it.
+ const lowMidi = min - pitchClass(min);
+ // Octaves from lowMidi that cover max, then take that block's B (…+12·n−1).
+ let octaves = Math.ceil((max - lowMidi + 1) / 12);
+ // Enforce the minimum span (in whole octaves).
+ octaves = Math.max(octaves, Math.ceil(minSemitones / 12));
+ const highMidi = lowMidi + octaves * 12 - 1;
+ return { lowMidi, highMidi };
+};
+
+/**
+ * Build the pixel layout for a keyboard spanning [lowMidi, highMidi] across a
+ * given width. White keys tile edge-to-edge; black keys are overlaid centered
+ * on the boundary between the two white keys they sit between.
+ *
+ * @param {object} args
+ * @param {number} args.lowMidi — first (white) key, a C from keyboardRange.
+ * @param {number} args.highMidi — last (white) key, a B from keyboardRange.
+ * @param {number} args.width — total pixel width to fill.
+ * @returns {{ keys: Array<{midi:number,isBlack:boolean,x:number,w:number}>,
+ * whiteWidth:number, blackWidth:number, lowMidi:number, highMidi:number }}
+ * keys are ordered white-first then black so a renderer can draw whites then
+ * overlay blacks; each carries its own x/width.
+ */
+export const buildKeyboardLayout = ({ lowMidi, highMidi, width }) => {
+ const whites = [];
+ for (let m = lowMidi; m <= highMidi; m += 1) if (!isBlackKey(m)) whites.push(m);
+ const whiteCount = whites.length || 1;
+ const whiteWidth = width / whiteCount;
+ const blackWidth = whiteWidth * BLACK_KEY_RATIO;
+
+ // White-key x by MIDI for positioning the black keys on their boundaries.
+ const whiteX = new Map();
+ const whiteKeys = whites.map((midi, i) => {
+ const x = i * whiteWidth;
+ whiteX.set(midi, x);
+ return { midi, isBlack: false, x, w: whiteWidth };
+ });
+
+ const blackKeys = [];
+ for (let m = lowMidi; m <= highMidi; m += 1) {
+ if (!isBlackKey(m)) continue;
+ // A black key always sits just above the white key one semitone below it;
+ // center it on that white key's right edge (the boundary to the next white).
+ const xBelow = whiteX.get(m - 1);
+ if (xBelow == null) continue;
+ const boundary = xBelow + whiteWidth;
+ blackKeys.push({ midi: m, isBlack: true, x: boundary - blackWidth / 2, w: blackWidth });
+ }
+
+ return { keys: [...whiteKeys, ...blackKeys], whiteWidth, blackWidth, lowMidi, highMidi };
+};
diff --git a/client/src/lib/pianoKeyboard.test.js b/client/src/lib/pianoKeyboard.test.js
new file mode 100644
index 0000000000..f2e4f13529
--- /dev/null
+++ b/client/src/lib/pianoKeyboard.test.js
@@ -0,0 +1,97 @@
+import { describe, it, expect } from 'vitest';
+import {
+ isBlackKey,
+ midiNoteName,
+ keyboardRange,
+ buildKeyboardLayout,
+ BLACK_KEY_RATIO,
+} from './pianoKeyboard.js';
+
+describe('isBlackKey', () => {
+ it('classifies the seven white keys of an octave', () => {
+ // C D E F G A B = MIDI 60,62,64,65,67,69,71
+ expect([60, 62, 64, 65, 67, 69, 71].every((m) => !isBlackKey(m))).toBe(true);
+ });
+ it('classifies the five black keys of an octave', () => {
+ // C# D# F# G# A# = 61,63,66,68,70
+ expect([61, 63, 66, 68, 70].every((m) => isBlackKey(m))).toBe(true);
+ });
+ it('handles notes below C-1 with positive-modulo classification', () => {
+ expect(isBlackKey(-11)).toBe(true); // C#-ish class 1
+ expect(isBlackKey(-12)).toBe(false); // C class 0
+ });
+});
+
+describe('midiNoteName', () => {
+ it('names middle C and the tuning A', () => {
+ expect(midiNoteName(60)).toBe('C4');
+ expect(midiNoteName(69)).toBe('A4');
+ });
+ it('uses sharps for black keys', () => {
+ expect(midiNoteName(61)).toBe('C#4');
+ expect(midiNoteName(70)).toBe('A#4');
+ });
+});
+
+describe('keyboardRange', () => {
+ it('snaps to whole C–B octaves around the notes', () => {
+ // notes E4(64)..G4(67) → low snaps down to C4(60), high up to B (enforced min 2 oct)
+ const { lowMidi, highMidi } = keyboardRange([64, 65, 67]);
+ expect(lowMidi % 12).toBe(0); // a C
+ expect((highMidi + 1) % 12).toBe(0); // a B (next up is a C)
+ expect(highMidi - lowMidi + 1).toBeGreaterThanOrEqual(24); // min 2 octaves
+ });
+ it('enforces the minimum span for a single note', () => {
+ const { lowMidi, highMidi } = keyboardRange([60]);
+ expect(highMidi - lowMidi + 1).toBe(24); // 2 full octaves
+ expect(lowMidi).toBe(60);
+ });
+ it('grows to cover a wide range, ending on a B', () => {
+ const { lowMidi, highMidi } = keyboardRange([48, 84]); // C3..C6
+ expect(lowMidi).toBe(48); // C3
+ expect((highMidi + 1) % 12).toBe(0); // ends on a B
+ expect(highMidi).toBe(95); // B6 — full octave block above the C6 note
+ });
+ it('always includes the highest note', () => {
+ const { lowMidi, highMidi } = keyboardRange([48, 84]);
+ expect(lowMidi).toBeLessThanOrEqual(48);
+ expect(highMidi).toBeGreaterThanOrEqual(84);
+ });
+ it('defaults to a C4-centered window with no notes', () => {
+ const { lowMidi, highMidi } = keyboardRange([]);
+ expect(lowMidi).toBe(60);
+ expect(highMidi - lowMidi + 1).toBe(24);
+ });
+});
+
+describe('buildKeyboardLayout', () => {
+ it('tiles white keys edge-to-edge across the width', () => {
+ const { keys, whiteWidth } = buildKeyboardLayout({ lowMidi: 60, highMidi: 71, width: 700 });
+ const whites = keys.filter((k) => !k.isBlack);
+ expect(whites).toHaveLength(7); // C D E F G A B
+ expect(whiteWidth).toBeCloseTo(100, 6);
+ expect(whites[0].x).toBe(0);
+ expect(whites[6].x).toBeCloseTo(600, 6);
+ // No gaps: each white starts where the previous ends.
+ for (let i = 1; i < whites.length; i += 1) {
+ expect(whites[i].x).toBeCloseTo(whites[i - 1].x + whiteWidth, 6);
+ }
+ });
+
+ it('overlays black keys centered on the white-key boundary, narrower', () => {
+ const { keys, whiteWidth, blackWidth } = buildKeyboardLayout({ lowMidi: 60, highMidi: 71, width: 700 });
+ const blacks = keys.filter((k) => k.isBlack);
+ expect(blacks).toHaveLength(5); // C# D# F# G# A#
+ expect(blackWidth).toBeCloseTo(whiteWidth * BLACK_KEY_RATIO, 6);
+ // C#(61) sits on the boundary between C(0) and D(1): center at 1·whiteWidth.
+ const cSharp = blacks.find((k) => k.midi === 61);
+ expect(cSharp.x + cSharp.w / 2).toBeCloseTo(whiteWidth, 6);
+ });
+
+ it('orders white keys before black keys for draw order', () => {
+ const { keys } = buildKeyboardLayout({ lowMidi: 60, highMidi: 71, width: 700 });
+ const firstBlack = keys.findIndex((k) => k.isBlack);
+ const lastWhite = keys.map((k) => k.isBlack).lastIndexOf(false);
+ expect(lastWhite).toBeLessThan(firstBlack);
+ });
+});
diff --git a/client/src/lib/scorePlayback.js b/client/src/lib/scorePlayback.js
index 54adf5f2dc..1aa5457387 100644
--- a/client/src/lib/scorePlayback.js
+++ b/client/src/lib/scorePlayback.js
@@ -64,6 +64,7 @@ export const buildSchedule = (score, bpmOverride) => {
events.push({
index,
rest: !!note.rest,
+ midi: note.rest ? null : pitchToMidi(note.pitch),
freq: note.rest ? null : noteToFrequency(note.pitch),
startBeat: beat,
durBeats,
@@ -466,11 +467,21 @@ export const createMultiScorePlayer = (parts, options = {}) => {
if (!playing) rebuild();
};
+ // Current playback head in score-seconds, for a continuous visualizer (the
+ // piano-roll). While playing it's the live audio clock (clamped to the score
+ // length); paused/stopped it's the remembered resume offset. Note: during the
+ // LEAD-in this can read slightly below 0 — callers clamp for display.
+ const position = () => (playing
+ ? Math.min(Math.max(0, ctx().currentTime - startTime), totalSec)
+ : offsetSec);
+
return {
play,
pause,
stop,
isPlaying: () => playing,
setTempo,
+ position,
+ duration: () => totalSec,
};
};
diff --git a/client/src/lib/scorePlayback.test.js b/client/src/lib/scorePlayback.test.js
index c93b701b8a..80bd6548fe 100644
--- a/client/src/lib/scorePlayback.test.js
+++ b/client/src/lib/scorePlayback.test.js
@@ -56,6 +56,14 @@ describe('buildSchedule', () => {
expect(totalSec).toBeCloseTo(2.0, 6);
});
+ it('carries the MIDI note number per pitched note (null for rests)', () => {
+ const score = parseScore('time: 4/4\ntempo: 120\n| C4q rq A4h |');
+ const { events } = buildSchedule(score);
+ expect(events[0].midi).toBe(60); // C4 → MIDI 60 (feeds the piano-roll)
+ expect(events[1].midi).toBeNull(); // rest carries no key
+ expect(events[2].midi).toBe(69); // A4 → MIDI 69
+ });
+
it('advances time through rests but carries no frequency', () => {
const score = parseScore('time: 4/4\ntempo: 60\n| C4q rq C4h |');
const { events, totalSec } = buildSchedule(score);
@@ -245,6 +253,21 @@ describe('createMultiScorePlayer', () => {
expect(player.isPlaying()).toBe(false);
});
+ it('reports duration (longest voice) and a live score-position for the piano roll', async () => {
+ const player = createMultiScorePlayer(
+ [{ id: 'melody', score: MELODY }, { id: 'bass', score: BASS }],
+ { bpm: 120 },
+ );
+ expect(player.duration()).toBeCloseTo(2.0, 6); // 4 quarters @120 = the longest voice
+ expect(player.position()).toBe(0); // idle → resume offset 0
+ await player.play();
+ audio.now = 1.0; // advance the fake audio clock
+ expect(player.position()).toBeGreaterThan(0.5);
+ expect(player.position()).toBeLessThanOrEqual(player.duration());
+ player.stop();
+ expect(player.position()).toBe(0); // reset to the top
+ });
+
it('reports ended for an empty selection without scheduling audio', async () => {
const ended = vi.fn();
const player = createMultiScorePlayer([], { onEnded: ended });
diff --git a/client/src/pages/SongEditor.jsx b/client/src/pages/SongEditor.jsx
index d311fc43a6..c0bcd4a264 100644
--- a/client/src/pages/SongEditor.jsx
+++ b/client/src/pages/SongEditor.jsx
@@ -39,6 +39,7 @@ import SongTraining from '../components/songs/SongTraining';
import SongScoreEditor from '../components/songs/SongScoreEditor';
import SongScoreParts from '../components/songs/SongScoreParts';
import ScoreSheet from '../components/songs/ScoreSheet';
+import PianoRoll, { layerColor } from '../components/songs/PianoRoll';
import RoundStack from '../components/songs/RoundStack';
import { scoreHasMusic, parseScore } from '../lib/scoreNotation';
import { createMultiScorePlayer, DEFAULT_BPM } from '../lib/scorePlayback';
@@ -909,7 +910,16 @@ function LayeredSheetMusic({ tabs }) {
const uid = useId();
const tabsKey = tabs.map((t) => t.key).join('|');
+ // 'staff' = SVG sheet music; 'piano' = Synthesia-style falling-note piano roll.
+ const [view, setView] = useState('staff');
const [viewKey, setViewKey] = useState(tabs[0].key);
+
+ // Stable per-part colors (by tab order) shared by the piano roll and the layer
+ // swatches so every surface agrees on which color is which voice.
+ const colorByKey = useMemo(
+ () => new Map(tabs.map((t, i) => [t.key, layerColor(i)])),
+ [tabsKey], // eslint-disable-line react-hooks/exhaustive-deps
+ );
// Default: every part checked, so Play gives the full stack out of the box.
// Reconcile across tab-set changes — keep checks for parts that still exist,
// include any newly-added part, and never leave the selection empty.
@@ -933,6 +943,9 @@ function LayeredSheetMusic({ tabs }) {
const playerRef = useRef(null);
const [isPlaying, setIsPlaying] = useState(false);
const [activeByPart, setActiveByPart] = useState({}); // partKey → now-sounding note index
+ // Live playhead in score-seconds for the piano roll; stable so its rAF loop
+ // doesn't restart on every render (reads the player ref, 0 when torn down).
+ const getPosition = useCallback(() => playerRef.current?.position?.() ?? 0, []);
const selectionKey = tabs.filter((t) => selected.has(t.key)).map((t) => t.key).join('|');
// Notation content of every tab — changes when a score's TEXT changes even if
@@ -990,6 +1003,13 @@ function LayeredSheetMusic({ tabs }) {
// hand control back to <ScoreSheet>'s own — here unused — internal player).
const shownActive = selected.has(current.key) ? (activeByPart[current.key] ?? -1) : -1;
+ // Selected layers the piano roll renders together — raw score text (it parses)
+ // plus the shared per-layer color.
+ const pianoParts = useMemo(
+ () => tabs.filter((t) => selected.has(t.key)).map((t) => ({ id: t.key, label: t.label, color: colorByKey.get(t.key), score: t.score })),
+ [tabs, selectionKey, colorByKey], // eslint-disable-line react-hooks/exhaustive-deps
+ );
+
const transportBtn = 'flex items-center gap-1 rounded-md border border-port-border bg-port-card px-2 py-1 text-white hover:border-port-accent transition-colors disabled:opacity-40 disabled:hover:border-port-border';
return (
@@ -1019,9 +1039,24 @@ function LayeredSheetMusic({ tabs }) {
/>
<span>BPM</span>
</label>
+
+ {/* Staff ↔ Piano-roll (Synthesia) view toggle — both share this transport. */}
+ <div className="ml-auto flex items-center rounded-md border border-port-border overflow-hidden" role="group" aria-label="Sheet view">
+ {[['staff', 'Staff'], ['piano', 'Piano']].map(([key, label]) => (
+ <button
+ key={key}
+ type="button"
+ onClick={() => setView(key)}
+ aria-pressed={view === key}
+ className={`px-2.5 py-1 transition-colors ${view === key ? 'bg-port-accent text-white' : 'bg-port-card text-gray-300 hover:text-white'}`}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
</div>
- {/* One checkbox per part — the mix that Play sounds. */}
+ {/* One checkbox per part — the mix that Play sounds. Swatch = piano color. */}
<fieldset className="flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs">
<legend className="sr-only">Parts to play together</legend>
<span className="text-gray-500">Layers:</span>
@@ -1034,29 +1069,42 @@ function LayeredSheetMusic({ tabs }) {
onChange={() => toggleSelected(t.key)}
className="accent-port-accent"
/>
+ <span
+ aria-hidden="true"
+ className="inline-block w-2.5 h-2.5 rounded-sm shrink-0"
+ style={{ backgroundColor: selected.has(t.key) ? colorByKey.get(t.key) : 'transparent', border: `1px solid ${colorByKey.get(t.key)}` }}
+ />
{t.label}
</label>
))}
</fieldset>
- {/* Pill row picks which staff is shown (independent of what plays). */}
- <div className="flex flex-wrap gap-1.5">
- {tabs.map((t) => (
- <button
- key={t.key}
- type="button"
- onClick={() => setViewKey(t.key)}
- aria-pressed={t.key === current.key}
- className={`px-2.5 py-1 text-xs rounded-full border transition-colors ${t.key === current.key ? 'bg-port-accent text-white border-port-accent' : 'border-port-border text-gray-300 hover:text-white hover:border-port-accent/60'}`}
- >
- {t.label}
- </button>
- ))}
- </div>
+ {view === 'staff' ? (
+ <>
+ {/* Pill row picks which staff is shown (independent of what plays). */}
+ <div className="flex flex-wrap gap-1.5">
+ {tabs.map((t) => (
+ <button
+ key={t.key}
+ type="button"
+ onClick={() => setViewKey(t.key)}
+ aria-pressed={t.key === current.key}
+ className={`px-2.5 py-1 text-xs rounded-full border transition-colors ${t.key === current.key ? 'bg-port-accent text-white border-port-accent' : 'border-port-border text-gray-300 hover:text-white hover:border-port-accent/60'}`}
+ >
+ {t.label}
+ </button>
+ ))}
+ </div>
- <div className="bg-port-card border border-port-border rounded-lg p-4 overflow-x-auto">
- <ScoreSheet key={current.key} text={current.score} controls={false} activeNoteIndex={shownActive} />
- </div>
+ <div className="bg-port-card border border-port-border rounded-lg p-4 overflow-x-auto">
+ <ScoreSheet key={current.key} text={current.score} controls={false} activeNoteIndex={shownActive} />
+ </div>
+ </>
+ ) : (
+ <div className="bg-port-card border border-port-border rounded-lg p-2">
+ <PianoRoll parts={pianoParts} tempo={tempo} getPosition={getPosition} playing={isPlaying} />
+ </div>
+ )}
</section>
);
}