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

render drum charts as one continuous horizontal strip with a clock-driven playhead

[._.]/ Adam Eivy8a1c50a64fd6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 42851a4281..775125ac43 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -30,6 +30,10 @@
- **[issue-3177] Added a Game studio for assembling managed-app asset bundles.** Create a Game workspace, bind reusable Sprite records and Music tracks, compile an immutable versioned manifest with SHA-256 asset references, and request persisted AI feedback with any configured provider, model, and supported effort. The new `/game/:id` workspace is reachable from Create, Cmd+K, and voice navigation.
- **Game workspaces now stay compact and verify assets before launch.** Bundle, Assets, and Feedback live in separate deep-linkable tabs; large sprite sets use a dense contained grid; imported prop atlases participate in bundles; and a preflight names every missing, stale, or hash-mismatched asset. A game can be started from its workspace only after the current manifest and all bound asset bytes pass verification.
+## SongBook
+
+- **Drum charts now play the whole song as one continuous, phone-readable strip.** The kit sheet was a vertical stack of per-bar grids — on a phone, two transport rows and a controls row pushed all but a bar and a half below the fold, and reading a groove meant scrolling down between bars. The whole song is now a single horizontal lane that scrolls under a playhead as it plays, with the kit-piece labels frozen in their own column so "which row is the snare" survives scrolling to bar 30, and A−/A+ zooming the grid. The playhead glides off the audio clock instead of hopping between hits, so it keeps moving across rests and through a bar with no hits at all. The transport is split for a phone: play, tempo (with ± steppers), the metronome and a live beat-pulse/bar readout stay visible, while practice speed, count-in and the loop range collapse behind a settings button until there's room for them. The metronome now defaults on and remembers being switched off, and a drum chart no longer shows the vertical autoscroll transport — its rival "play" button that scrolled the page instead of the song.
+
## Quota burn
- **[issue-3179] Quota-burn no longer spends window budget on runs that never happened** — a scheduled quota-burn run counted against the family's per-window dispatch cap as soon as it was considered, even when it was subsequently skipped and no agent was ever started. Those phantom dispatches ate the budget, so a family configured for e.g. 5 burns per reset window could fire far fewer — and a family capped at 1 could never fire at all, because the skipped run consumed the only slot before the next gate re-read it. A burn is now counted once its agent has actually run, and a burn that is queued or in progress holds its slot in the meantime, so the cap stays accurate without letting a second app or a repeated "Run" overshoot it.
diff --git a/PLAN.md b/PLAN.md
index 953657efe9..9f7f10a656 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -322,3 +322,7 @@ is not reliably announced.
### Let the Image Gen "Test Render" panel pick its provider
- [ ] `client/src/components/settings/ImageGenTab.jsx` — Test Connection now probes the provider whose sub-tab is open, but the Test tab's `handleRenderTest` still renders with `saved.mode` (the saved default backend). So a user who wants to smoke-test an Agy or Grok render must first make it their default, which is the same friction the Test Connection fix just removed. Add a provider `<select>` to the Test Render panel (default: the saved backend, options limited to enabled backends via `isModeUsable`/`pickUsableMode`'s client mirror), thread the chosen mode into `generateImage({ mode })`, and update the panel copy from "the active backend" to name the selected one. Out of scope for the Test Connection fix (needs new UI, not a re-target of an existing call). Surfaced by the /simplify altitude review.
+
+### Share one beat-pulse indicator between the Metronome and the drum transport
+
+- [ ] `client/src/components/songs/Metronome.jsx:109-129` and `client/src/components/songbook/DrumTransportBar.jsx` (`BeatDots`) draw the same widget twice: a dot per notated beat, the current one lit, count-in dots in `bg-port-warning`, unlit dots `bg-port-border`, with a "Count-in… / bar N" readout beside it. The Metronome's copy is inline JSX, not an exported component, so the drum transport couldn't call it — and the two have already drifted (the drum one uses `bg-port-accent` where the Metronome uses `bg-port-success`, and sizes the lit dot differently). Extract one `<BeatPulse beatsPerBar beat countingIn />` (`client/src/components/ui/`, catalogued + barrelled) and render it from both, picking whichever lit-dot color/size reads better and applying it to each. Deferred from the drum continuous-strip change: extracting from `Metronome.jsx` means editing an unrelated feature's component, which was outside that diff. Surfaced by the /simplify reuse review.
diff --git a/client/src/components/songbook/DrumSheetView.jsx b/client/src/components/songbook/DrumSheetView.jsx
index d9a6ea7ba2..40807cc027 100644
--- a/client/src/components/songbook/DrumSheetView.jsx
+++ b/client/src/components/songbook/DrumSheetView.jsx
@@ -1,57 +1,85 @@
/**
- * DrumSheetView — renders PortOS drum-kit notation (drumNotation.js) as a
- * labelled, bar-gridded kit sheet in hand-rolled SVG, with no engraving library
+ * DrumSheetView — renders PortOS drum-kit notation (drumNotation.js) as ONE
+ * continuous horizontal kit strip in hand-rolled SVG, with no engraving library
* (the same explicit choice `ScoreSheet.jsx` makes: no VexFlow / abcjs / OSMD).
*
- * Geometry is driven off ONE constant — the grid cell size. Every row is a kit
- * piece, every column a grid step, so positioning a hit is a single multiply.
- * Beat boundaries get a heavier grid line so a 16th-note row still reads in
- * fours, and each hit's glyph follows its cell: a cross for cymbals/hats, a
- * filled notehead for drums, a ring for an open hi-hat, a small hollow head for
- * a ghost, a doubled head for a flam, all with the accent's own chevron.
+ * A phone is the primary SongBook surface, and a drummer reads a groove the way
+ * it is played: left to right, without end. So the whole song is a single lane
+ * that scrolls horizontally under a playhead, rather than a stack of per-bar
+ * grids that push the kit off the bottom of a phone screen (the pre-#3115
+ * layout put ~1.5 bars above the fold on a 390px viewport). The kit labels live
+ * in their own frozen column beside the scroller so "which row is the snare"
+ * survives scrolling to bar 30.
+ *
+ * Geometry is driven off ONE constant — the grid cell size — in fixed internal
+ * SVG units; the viewer's A−/A+ control scales the whole strip through the
+ * `fontSizeRem` prop instead of recomputing any of it.
+ *
+ * THE PLAYHEAD NEVER GOES THROUGH REACT. `getPlayhead()` (useDrumPlayer) reads
+ * the audio clock, and one animation-frame loop writes the results straight to
+ * the DOM: a column rect on the current step, a line at the exact sub-step
+ * position, and the scroller's `scrollLeft`. So a 16th-note groove repaints two
+ * attributes per frame instead of re-rendering a ~2000-element SVG 8×/second.
+ * The clock is also the only source that keeps moving through a rest — the
+ * player's `onStep` events stall there (see `resolvePlayhead`).
*
* Ink comes from the PortOS theme CSS variables (`--port-text` / `--port-accent`
* / `--port-text-muted`) applied through the `style` prop — SVG presentation
* *attributes* don't evaluate `var()`, so `fill="var(--x)"` would silently paint
* nothing. Same rule as ScoreSheet.
*
- * Each bar is its own SVG so bars wrap responsively and a wide bar scrolls as a
- * UNIT on a narrow screen (mobile-responsive is non-negotiable) instead of
- * squeezing its columns into illegibility.
- *
* Props:
* text — the raw chart source (parsed here; the parser never throws)
- * fontSizeRem — scales the labels/legend text with the viewer's font control
- * activeStep — `{ bar, step }` | null — draws the playhead column
+ * fontSizeRem — scales the whole strip with the viewer's A−/A+ control
+ * getPlayhead — `() => { countIn, bar, stepFloat } | null`; absent → a static
+ * sheet with no playhead and no auto-follow
+ * playing — gates the animation frame loop
* onStepClick — optional `(barIndex, step, pieceId)` for a future tap-a-cell
* editor (#3115 out-of-scope); when absent the grid renders as
* a plain image
*/
-import { memo, useMemo } from 'react';
+import { memo, useEffect, useMemo, useRef } from 'react';
import { parseDrumChart, kitPiece } from '../../lib/drumNotation.js';
-// --- Geometry (internal SVG units; each bar's <svg> scales via viewBox) ------
-const CELL = 22; // one grid step — every other measure derives from this
+// --- Geometry (internal SVG units; the strip scales via width/height + viewBox)
+const CELL = 20; // one grid step — every other measure derives from this
const ROW_H = CELL; // one kit-piece row
-const LABEL_W = 74; // room for the row labels ("Hi-Hat", "Floor Tom")
-const PAD = 6; // padding inside a bar's svg
+const LABEL_W = 56; // the frozen label column ("Hi-Hat", "Floor Tom")
+const PAD = 6; // padding inside the svgs
const HEAD_R = CELL * 0.3; // notehead radius
const GHOST_R = CELL * 0.2;
const CROSS_R = CELL * 0.26;
-const HEADER_H = 18; // bar-number / label strip above the grid
-
-// Ink — theme CSS vars, applied via `style` (see the header note).
-const INK = 'rgb(var(--port-text))';
-const GRID = 'rgb(var(--port-text-muted) / 0.35)';
-const GRID_BEAT = 'rgb(var(--port-text-muted) / 0.7)';
-const LABEL = 'rgb(var(--port-text-muted))';
-const ACTIVE = 'rgb(var(--port-accent))';
-const ACTIVE_FILL = 'rgb(var(--port-accent) / 0.18)';
-const UI_FONT = 'ui-sans-serif, system-ui, sans-serif';
+const HEADER_H = 20; // bar-number / section-label strip above the grid
+const BAR_GAP = 6; // breathing room between bars, inside the lane
+
+const GRID_TOP = PAD + HEADER_H;
+// Vertical centre of kit row `ri` — shared by the lane and the frozen label
+// column, which have to stay in lockstep or the labels drift off their rows.
+const rowCenterY = (ri) => GRID_TOP + ri * ROW_H + ROW_H / 2;
-const strokeStyle = (color) => ({ stroke: color });
-const fillStyle = (color) => ({ fill: color });
+// Zoom: the A−/A+ font control drives the whole strip. 0.875rem is the viewer's
+// default, so that maps to 1×.
+const BASE_FONT_REM = 0.875;
+const SCALE_MIN = 0.7;
+const SCALE_MAX = 2.4;
+
+// Where the playhead sits in the viewport while the sheet scrolls under it —
+// far enough left that the bar you're about to play is the one you can read.
+const FOLLOW_FRACTION = 0.35;
+
+// Ink — theme CSS vars, applied via `style` (see the header note). Hoisted as
+// shared objects, not built per element: the lane is ~2000 nodes on a long
+// chart, and a fresh `{ fill }` literal each also defeats React's diff.
+const INK = { fill: 'rgb(var(--port-text))' };
+const INK_STROKE = { stroke: 'rgb(var(--port-text))' };
+const INK_HOLLOW = { fill: 'none', stroke: 'rgb(var(--port-text))' };
+const GRID = { stroke: 'rgb(var(--port-text-muted) / 0.35)' };
+const GRID_BEAT = { stroke: 'rgb(var(--port-text-muted) / 0.7)' };
+const LABEL = { fill: 'rgb(var(--port-text-muted))' };
+const ACTIVE_STROKE = { stroke: 'rgb(var(--port-accent))' };
+const ACTIVE_FILL = { fill: 'rgb(var(--port-accent) / 0.18)' };
+const UI_FONT = 'ui-sans-serif, system-ui, sans-serif';
// Time-signature denominator → the note glyph for one BEAT at that value, for the
// tempo marking. The tempo counts notated beats, so 6/8 must read "♪ = 96", not
@@ -59,22 +87,21 @@ const fillStyle = (color) => ({ fill: color });
// than a wrong glyph.
const BEAT_GLYPH = { 1: '𝅝', 2: '𝅗𝅥', 4: '♩', 8: '♪', 16: '𝅘𝅥𝅯' };
-// One hit's glyph. `cross` pieces (cymbals, hats) draw an ×; `head` pieces
-// (drums) draw a notehead. The cell's own flags then modify it: a ring for an
-// open hi-hat, a small hollow head for a ghost, a leading grace head for a flam,
-// and a chevron above an accent.
-const renderHit = (cell, piece, cx, cy, ink, key) => {
- const out = [];
+// One hit's glyph, pushed into the caller's element array. `cross` pieces
+// (cymbals, hats) draw an ×; `head` pieces (drums) draw a notehead. The cell's
+// own flags then modify it: a ring for an open hi-hat, a small hollow head for a
+// ghost, a leading grace head for a flam, and a chevron above an accent.
+const pushHit = (out, cell, piece, cx, cy, key) => {
const cross = kitPiece(piece)?.glyph === 'cross';
if (cell.flam) {
// Grace note just ahead of the beat — small and offset left.
const gx = cx - CELL * 0.3;
out.push(cross
- ? <line key={`${key}-fl1`} x1={gx - GHOST_R} y1={cy - GHOST_R} x2={gx + GHOST_R} y2={cy + GHOST_R} style={strokeStyle(ink)} strokeWidth={1.1} />
- : <circle key={`${key}-fl1`} cx={gx} cy={cy} r={GHOST_R} style={{ fill: 'none', stroke: ink }} strokeWidth={1.1} />);
+ ? <line key={`${key}-fl1`} x1={gx - GHOST_R} y1={cy - GHOST_R} x2={gx + GHOST_R} y2={cy + GHOST_R} style={INK_STROKE} strokeWidth={1.1} />
+ : <circle key={`${key}-fl1`} cx={gx} cy={cy} r={GHOST_R} style={INK_HOLLOW} strokeWidth={1.1} />);
if (cross) {
- out.push(<line key={`${key}-fl2`} x1={gx - GHOST_R} y1={cy + GHOST_R} x2={gx + GHOST_R} y2={cy - GHOST_R} style={strokeStyle(ink)} strokeWidth={1.1} />);
+ out.push(<line key={`${key}-fl2`} x1={gx - GHOST_R} y1={cy + GHOST_R} x2={gx + GHOST_R} y2={cy - GHOST_R} style={INK_STROKE} strokeWidth={1.1} />);
}
}
@@ -82,150 +109,51 @@ const renderHit = (cell, piece, cx, cy, ink, key) => {
const r = cell.ghost ? GHOST_R : CROSS_R;
const w = cell.accent ? 2.2 : 1.6;
out.push(
- <line key={`${key}-a`} x1={cx - r} y1={cy - r} x2={cx + r} y2={cy + r} style={strokeStyle(ink)} strokeWidth={w} strokeLinecap="round" />,
- <line key={`${key}-b`} x1={cx - r} y1={cy + r} x2={cx + r} y2={cy - r} style={strokeStyle(ink)} strokeWidth={w} strokeLinecap="round" />,
+ <line key={`${key}-a`} x1={cx - r} y1={cy - r} x2={cx + r} y2={cy + r} style={INK_STROKE} strokeWidth={w} strokeLinecap="round" />,
+ <line key={`${key}-b`} x1={cx - r} y1={cy + r} x2={cx + r} y2={cy - r} style={INK_STROKE} strokeWidth={w} strokeLinecap="round" />,
);
// Open hi-hat: the conventional circle around the ×.
if (cell.open) {
- out.push(<circle key={`${key}-o`} cx={cx} cy={cy} r={r + 2.6} style={{ fill: 'none', stroke: ink }} strokeWidth={1.2} />);
+ out.push(<circle key={`${key}-o`} cx={cx} cy={cy} r={r + 2.6} style={INK_HOLLOW} strokeWidth={1.2} />);
}
} else if (cell.ghost) {
// Ghost note — the parenthesized/hollow head convention.
- out.push(<circle key={`${key}-h`} cx={cx} cy={cy} r={GHOST_R} style={{ fill: 'none', stroke: ink }} strokeWidth={1.2} />);
+ out.push(<circle key={`${key}-h`} cx={cx} cy={cy} r={GHOST_R} style={INK_HOLLOW} strokeWidth={1.2} />);
} else {
- out.push(<circle key={`${key}-h`} cx={cx} cy={cy} r={HEAD_R} style={fillStyle(ink)} />);
+ out.push(<circle key={`${key}-h`} cx={cx} cy={cy} r={HEAD_R} style={INK} />);
}
if (cell.accent) {
// Accent chevron above the head (the > articulation mark, rotated to sit
- // horizontally over the note).
- const y = cy - CELL * 0.42;
+ // horizontally over the note). Kept inside the row: at much more than 0.36
+ // of a cell up, the chevron crosses the lane line into the row above.
+ const y = cy - CELL * 0.36;
out.push(
<path key={`${key}-ac`}
d={`M ${cx - HEAD_R - 1} ${y - 2.4} L ${cx + HEAD_R + 1} ${y} L ${cx - HEAD_R - 1} ${y + 2.4}`}
- style={{ fill: 'none', stroke: ink }} strokeWidth={1.3} strokeLinecap="round" strokeLinejoin="round" />,
+ style={INK_HOLLOW} strokeWidth={1.3} strokeLinecap="round" strokeLinejoin="round" />,
);
}
- return out;
};
-// One bar → its own <svg>. Kept a component (not a helper returning elements) so
-// React can key/diff bars independently as the playhead moves.
-const Bar = ({ bar, pieces, subdivision, activeStep, onStepClick }) => {
- const steps = bar.rows[0]?.cells.length || 0;
- const gridW = steps * CELL;
- const width = LABEL_W + gridW + PAD * 2;
- const height = HEADER_H + pieces.length * ROW_H + PAD * 2;
- const gridLeft = PAD + LABEL_W;
- const gridTop = PAD + HEADER_H;
- const gridBottom = gridTop + pieces.length * ROW_H;
- // Only the bar the playhead is IN highlights a column.
- const active = activeStep && activeStep.bar === bar.index ? activeStep.step : null;
-
- const els = [];
-
- // Bar number + label strip.
- els.push(
- <text key="num" x={PAD} y={PAD + 12} fontSize={11} fontWeight="600" style={fillStyle(LABEL)} fontFamily={UI_FONT}>
- {bar.index}
- </text>,
- );
- if (bar.label) {
- els.push(
- <text key="label" x={gridLeft} y={PAD + 12} fontSize={11} style={fillStyle(LABEL)} fontFamily={UI_FONT}>
- {bar.label}
- {bar.repeat > 1 ? ` (${bar.repeatPass}/${bar.repeat})` : ''}
- </text>,
- );
- }
-
- // Playhead column — drawn first so glyphs and grid lines sit on top of it.
- if (active != null && active >= 0 && active < steps) {
- els.push(
- <rect key="ph" x={gridLeft + active * CELL} y={gridTop} width={CELL} height={gridBottom - gridTop}
- style={fillStyle(ACTIVE_FILL)} />,
- );
- }
-
- // Row labels + horizontal lane lines.
- pieces.forEach((id, ri) => {
- const y = gridTop + ri * ROW_H;
- els.push(
- <text key={`rl${id}`} x={PAD} y={y + ROW_H / 2 + 3.5} fontSize={10} style={fillStyle(LABEL)} fontFamily={UI_FONT}>
+// The frozen kit-piece labels beside the scroller. Its own <svg> so it can't
+// scroll away, sharing the lane's row geometry exactly.
+const LabelColumn = ({ pieces, height, scale }) => (
+ <svg
+ viewBox={`0 0 ${LABEL_W} ${height}`}
+ width={LABEL_W * scale}
+ height={height * scale}
+ aria-hidden="true"
+ className="shrink-0"
+ style={{ display: 'block' }}
+ >
+ {pieces.map((id, ri) => (
+ <text key={id} x={LABEL_W - 5} y={rowCenterY(ri) + 3.5} fontSize={9.5} textAnchor="end" style={LABEL} fontFamily={UI_FONT}>
{kitPiece(id)?.label || id}
- </text>,
- <line key={`rh${id}`} x1={gridLeft} y1={y} x2={gridLeft + gridW} y2={y} style={strokeStyle(GRID)} strokeWidth={1} />,
- );
- });
- els.push(
- <line key="rh-last" x1={gridLeft} y1={gridBottom} x2={gridLeft + gridW} y2={gridBottom} style={strokeStyle(GRID)} strokeWidth={1} />,
- );
-
- // Vertical step lines — every `subdivision`-th is a beat boundary (heavier),
- // and the bar's own edges are heavier still.
- for (let s = 0; s <= steps; s += 1) {
- const x = gridLeft + s * CELL;
- const isEdge = s === 0 || s === steps;
- const isBeat = s % subdivision === 0;
- els.push(
- <line key={`v${s}`} x1={x} y1={gridTop} x2={x} y2={gridBottom}
- style={strokeStyle(isBeat ? GRID_BEAT : GRID)} strokeWidth={isEdge ? 1.8 : (isBeat ? 1.2 : 0.6)} />,
- );
- }
-
- // Beat numbers under the grid.
- for (let s = 0; s < steps; s += subdivision) {
- els.push(
- <text key={`bn${s}`} x={gridLeft + s * CELL + CELL / 2} y={gridTop - 3} fontSize={9}
- style={fillStyle(LABEL)} fontFamily={UI_FONT} textAnchor="middle">
- {s / subdivision + 1}
- </text>,
- );
- }
-
- // Hits.
- const rowByPiece = new Map(bar.rows.map((r) => [r.piece, r]));
- pieces.forEach((id, ri) => {
- const row = rowByPiece.get(id);
- if (!row) return;
- const cy = gridTop + ri * ROW_H + ROW_H / 2;
- row.cells.forEach((cell, s) => {
- if (cell.rest) return;
- const cx = gridLeft + s * CELL + CELL / 2;
- els.push(...renderHit(cell, id, cx, cy, s === active ? ACTIVE : INK, `h${id}-${s}`));
- });
- });
-
- // Optional tap targets (a future click-to-toggle editor); absent by default so
- // the sheet is a plain image with no stray interactive nodes.
- if (onStepClick) {
- pieces.forEach((id, ri) => {
- for (let s = 0; s < steps; s += 1) {
- els.push(
- <rect key={`t${id}-${s}`} x={gridLeft + s * CELL} y={gridTop + ri * ROW_H} width={CELL} height={ROW_H}
- fill="transparent" style={{ cursor: 'pointer' }} onClick={() => onStepClick(bar.index, s, id)} />,
- );
- }
- });
- }
-
- return (
- // The bar scrolls as a unit on a narrow viewport: the svg keeps its intrinsic
- // width and the wrapper scrolls, rather than the viewBox squeezing columns.
- <div className="overflow-x-auto max-w-full">
- <svg
- viewBox={`0 0 ${width} ${height}`}
- width={width}
- height={height}
- role="img"
- aria-label={`Drum bar ${bar.index}${bar.label ? `: ${bar.label}` : ''}`}
- style={{ display: 'block', maxWidth: '100%', height: 'auto' }}
- >
- {els}
- </svg>
- </div>
- );
-};
+ </text>
+ ))}
+ </svg>
+);
// Chart problems (unknown pieces, over-long rows, bad headers). Rendered
// ALONGSIDE the sheet, never instead of it — a chart with one bad row must still
@@ -241,8 +169,81 @@ const ErrorSummary = ({ errors }) => (
</div>
);
-function DrumSheetView({ text, fontSizeRem = 0.875, activeStep = null, onStepClick, className = '' }) {
+function DrumSheetView({
+ text,
+ fontSizeRem = 0.875,
+ getPlayhead,
+ playing = false,
+ onStepClick,
+ className = '',
+}) {
const chart = useMemo(() => parseDrumChart(text), [text]);
+ const scrollRef = useRef(null);
+ const lineRef = useRef(null);
+ const columnRef = useRef(null);
+
+ const scale = Math.min(SCALE_MAX, Math.max(SCALE_MIN, (fontSizeRem || BASE_FONT_REM) / BASE_FONT_REM));
+ const { pieces, subdivision, stepsPerBar } = chart;
+ const gridBottom = GRID_TOP + pieces.length * ROW_H;
+ const height = gridBottom + PAD;
+
+ // Every bar is exactly `stepsPerBar` wide (the parser pads every row to that
+ // length), so a bar's lane position is arithmetic — no per-bar measuring.
+ // Memoized as one object so the rAF loop can depend on the whole geometry.
+ const { barCount, barW, barX, laneW } = useMemo(() => {
+ const w = chart.stepsPerBar * CELL;
+ const x = (barIndex) => PAD + (barIndex - 1) * (w + BAR_GAP);
+ return {
+ barCount: chart.bars.length,
+ barW: w,
+ barX: x,
+ laneW: Math.max(PAD * 2, x(chart.bars.length + 1) - BAR_GAP + PAD),
+ };
+ }, [chart]);
+
+ // One rAF loop for both playhead marks and the auto-follow scroll. All DOM
+ // READS happen before any write — reading scrollLeft/clientWidth after
+ // dirtying the tree in the same frame forces a synchronous layout.
+ useEffect(() => {
+ const line = lineRef.current;
+ const column = columnRef.current;
+ if (!line || !column) return undefined;
+ const hide = () => {
+ line.style.display = 'none';
+ column.style.display = 'none';
+ };
+ if (!playing || !getPlayhead || typeof requestAnimationFrame !== 'function') {
+ hide();
+ return undefined;
+ }
+ let raf = requestAnimationFrame(function tick() {
+ raf = requestAnimationFrame(tick);
+ const pos = getPlayhead();
+ // The count-in has no position on the sheet — park the marks rather than
+ // sliding them through bar 1 before bar 1 is playing.
+ if (!pos || pos.countIn || pos.bar > barCount) { hide(); return; }
+
+ const el = scrollRef.current;
+ const viewportW = el?.clientWidth ?? 0;
+ const x = barX(pos.bar) + pos.stepFloat * CELL;
+
+ line.style.display = '';
+ column.style.display = '';
+ line.setAttribute('transform', `translate(${x} 0)`);
+ column.setAttribute('x', barX(pos.bar) + Math.floor(pos.stepFloat) * CELL);
+
+ if (!el) return;
+ const max = laneW * scale - viewportW;
+ if (max <= 0) return;
+ el.scrollLeft = Math.min(max, Math.max(0, x * scale - viewportW * FOLLOW_FRACTION));
+ });
+ return () => { cancelAnimationFrame(raf); hide(); };
+ }, [playing, getPlayhead, barCount, barX, laneW, scale]);
+
+ // A new chart is a new song — start reading it from the top.
+ useEffect(() => {
+ if (scrollRef.current) scrollRef.current.scrollLeft = 0;
+ }, [chart]);
if (!chart.bars.length) {
return (
@@ -255,32 +256,124 @@ function DrumSheetView({ text, fontSizeRem = 0.875, activeStep = null, onStepCli
);
}
+ const els = [];
+ let lastLabel = null;
+
+ chart.bars.forEach((bar) => {
+ const x = barX(bar.index);
+
+ // Bar number, always; the section label only where it CHANGES. A four-bar
+ // block repeating its own name over every bar is noise on a phone.
+ els.push(
+ <text key={`n${bar.index}`} x={x + 1} y={GRID_TOP - 8} fontSize={9} fontWeight="600" style={LABEL} fontFamily={UI_FONT}>
+ {bar.index}
+ </text>,
+ );
+ if (bar.label && bar.label !== lastLabel) {
+ els.push(
+ <text key={`l${bar.index}`} x={x + 14} y={GRID_TOP - 8} fontSize={9.5} style={LABEL} fontFamily={UI_FONT}>
+ {bar.label}{bar.repeat > 1 ? ` ×${bar.repeat}` : ''}
+ </text>,
+ );
+ }
+ lastLabel = bar.label;
+
+ // Lane lines for this bar's span (one per kit row, plus the bottom edge).
+ for (let ri = 0; ri <= pieces.length; ri += 1) {
+ const y = GRID_TOP + ri * ROW_H;
+ els.push(<line key={`h${bar.index}-${ri}`} x1={x} y1={y} x2={x + barW} y2={y} style={GRID} strokeWidth={1} />);
+ }
+
+ // Vertical step lines — every `subdivision`-th is a beat boundary (heavier),
+ // and the bar's own edges are heavier still.
+ for (let s = 0; s <= stepsPerBar; s += 1) {
+ const isEdge = s === 0 || s === stepsPerBar;
+ const isBeat = s % subdivision === 0;
+ els.push(
+ <line key={`v${bar.index}-${s}`} x1={x + s * CELL} y1={GRID_TOP} x2={x + s * CELL} y2={gridBottom}
+ style={isBeat ? GRID_BEAT : GRID} strokeWidth={isEdge ? 1.8 : (isBeat ? 1.2 : 0.6)} />,
+ );
+ }
+
+ // Beat numbers under the bar-number strip. Beat 1 is skipped: the bar number
+ // already sits in that corner, and "1₁" at every bar line is noise.
+ for (let s = subdivision; s < stepsPerBar; s += subdivision) {
+ els.push(
+ <text key={`b${bar.index}-${s}`} x={x + s * CELL + CELL / 2} y={GRID_TOP - 1.5} fontSize={8}
+ style={LABEL} fontFamily={UI_FONT} textAnchor="middle">
+ {s / subdivision + 1}
+ </text>,
+ );
+ }
+
+ // Hits.
+ const rowByPiece = new Map(bar.rows.map((r) => [r.piece, r]));
+ pieces.forEach((id, ri) => {
+ const row = rowByPiece.get(id);
+ if (!row) return;
+ const cy = rowCenterY(ri);
+ row.cells.forEach((cell, s) => {
+ if (cell.rest) return;
+ pushHit(els, cell, id, x + s * CELL + CELL / 2, cy, `h${bar.index}-${id}-${s}`);
+ });
+ });
+
+ // Optional tap targets (a future click-to-toggle editor); absent by default
+ // so the sheet is a plain image with no stray interactive nodes.
+ if (onStepClick) {
+ pieces.forEach((id, ri) => {
+ for (let s = 0; s < stepsPerBar; s += 1) {
+ els.push(
+ <rect key={`t${bar.index}-${id}-${s}`} x={x + s * CELL} y={GRID_TOP + ri * ROW_H} width={CELL} height={ROW_H}
+ fill="transparent" style={{ cursor: 'pointer' }} onClick={() => onStepClick(bar.index, s, id)} />,
+ );
+ }
+ });
+ }
+ });
+
return (
<div className={className} style={{ fontSize: `${fontSizeRem}rem` }}>
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 mb-2 text-xs text-gray-500">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 mb-1.5 text-xs text-gray-500">
<span>{chart.time.beats}/{chart.time.beatValue}</span>
{/* The tempo counts NOTATED beats — the time-signature denominator — so
6/8 is eighth = bpm, not quarter = bpm. Label the actual beat unit
rather than always printing ♩, which would misstate the tempo the
playback schedule uses (drumPlayback.buildDrumSchedule). */}
<span>{BEAT_GLYPH[chart.time.beatValue] || `1/${chart.time.beatValue}`} = {chart.tempo}</span>
- <span>
- {chart.subdivision} per beat
- </span>
+ <span>{chart.subdivision} per beat</span>
<span>{chart.bars.length} bar{chart.bars.length === 1 ? '' : 's'}</span>
</div>
- <div className="flex flex-col gap-3">
- {chart.bars.map((bar) => (
- <Bar
- key={`${bar.index}`}
- bar={bar}
- pieces={chart.pieces}
- subdivision={chart.subdivision}
- activeStep={activeStep}
- onStepClick={onStepClick}
- />
- ))}
+ <div className="flex items-start">
+ <LabelColumn pieces={pieces} height={height} scale={scale} />
+ {/* One scroller for the whole song. `overscroll-contain` keeps a swipe
+ that runs off the end of the strip from turning into a page/back
+ gesture on a phone. */}
+ <div ref={scrollRef} className="flex-1 min-w-0 overflow-x-auto overscroll-x-contain">
+ {/* The label column is aria-hidden (a visual freeze of these same row
+ names), so the kit rows are named in the strip's own label. */}
+ <svg
+ viewBox={`0 0 ${laneW} ${height}`}
+ width={laneW * scale}
+ height={height * scale}
+ role="img"
+ aria-label={`Drum chart — ${chart.bars.length} bar${chart.bars.length === 1 ? '' : 's'}, ${chart.time.beats}/${chart.time.beatValue} at ${chart.tempo} BPM. Kit rows: ${pieces.map((id) => kitPiece(id)?.label || id).join(', ')}`}
+ style={{ display: 'block' }}
+ >
+ {/* Playhead column — first in the tree so the grid and glyphs paint
+ over it; the line is last so it paints over them. Both are
+ positioned by the rAF loop and hidden until it runs. A full-height
+ line rather than a line-plus-marker: the header strip is already
+ two rows of small text deep, and any glyph big enough to read
+ would sit on top of the beat numbers. */}
+ <rect data-playhead="column" ref={columnRef} x={0} y={GRID_TOP} width={CELL} height={gridBottom - GRID_TOP}
+ style={{ ...ACTIVE_FILL, display: 'none' }} />
+ {els}
+ <line data-playhead="line" ref={lineRef} x1={0} y1={PAD} x2={0} y2={gridBottom}
+ style={{ ...ACTIVE_STROKE, display: 'none' }} strokeWidth={1.6} />
+ </svg>
+ </div>
</div>
{chart.errors.length > 0 && <ErrorSummary errors={chart.errors} />}
@@ -288,6 +381,7 @@ function DrumSheetView({ text, fontSizeRem = 0.875, activeStep = null, onStepCli
);
}
-// Props are primitives plus a shallow `activeStep` object, so memo keeps a host
-// page's unrelated re-renders (stage flips, BPM edits) from redrawing the sheet.
+// Every prop is a primitive or the stable `getPlayhead` callback, and the
+// playhead itself never arrives as a prop — so during playback memo bails out
+// and the lane is never rebuilt.
export default memo(DrumSheetView);
diff --git a/client/src/components/songbook/DrumSheetView.test.jsx b/client/src/components/songbook/DrumSheetView.test.jsx
index 00d269b86e..83327b0918 100644
--- a/client/src/components/songbook/DrumSheetView.test.jsx
+++ b/client/src/components/songbook/DrumSheetView.test.jsx
@@ -1,5 +1,6 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi, afterEach } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
+import { render, cleanup, act } from '@testing-library/react';
import DrumSheetView from './DrumSheetView.jsx';
// Invented grooves only (privacy convention).
@@ -14,11 +15,13 @@ K: o - - - - - o -`;
const count = (html, tag) => (html.match(new RegExp(`<${tag}[ />]`, 'g')) || []).length;
+afterEach(cleanup);
+
describe('DrumSheetView', () => {
it('renders a bar-gridded kit sheet with no NaN geometry', () => {
const html = renderToStaticMarkup(<DrumSheetView text={ROCK_BEAT} />);
expect(html).not.toMatch(/NaN/);
- expect(html).toContain('aria-label="Drum bar 1: Bar 1 — basic rock beat"');
+ expect(html).toContain('Bar 1 — basic rock beat');
expect(html).toContain('Hi-Hat');
expect(html).toContain('Snare');
expect(html).toContain('Kick');
@@ -76,36 +79,42 @@ describe('DrumSheetView', () => {
expect(count(flam, 'circle')).toBe(count(plain, 'circle') + 1);
});
- it('renders one bar block per bar, including repeat expansions', () => {
+ // --- Continuous lane -------------------------------------------------------
+
+ it('lays the whole song out in ONE horizontal lane, not a grid per bar', () => {
const html = renderToStaticMarkup(<DrumSheetView text={'# A x3\nHH: xxxx'} />);
- expect(count(html, 'svg')).toBe(3);
- expect(html).toContain('(1/3)');
- expect(html).toContain('(3/3)');
+ // Two svgs total regardless of bar count: the frozen label column + the lane.
+ expect(count(html, 'svg')).toBe(2);
+ // And exactly one scroller for the song.
+ expect((html.match(/overflow-x-auto/g) || []).length).toBe(1);
});
- it('gives every bar its own scroll container so wide bars scroll as a unit', () => {
- const html = renderToStaticMarkup(<DrumSheetView text={'# A\nHH: xxxxxxxxxxxxxxxx\n\n# B\nHH: xxxx'} />);
- expect((html.match(/overflow-x-auto/g) || []).length).toBe(2);
+ it('numbers every bar but only repeats a section label where it changes', () => {
+ const html = renderToStaticMarkup(<DrumSheetView text={'# Verse x3\nHH: xxxx\n\n# Chorus\nS: xxxx'} />);
+ expect((html.match(/Verse/g) || []).length).toBe(1); // 3 bars, 1 label
+ expect((html.match(/Chorus/g) || []).length).toBe(1);
+ expect(html).toContain('>4<'); // bar 4 still numbered
});
- it('highlights the active step column in the active bar only', () => {
- const chart = '# A\nHH: xxxx\n\n# B\nHH: xxxx';
- const none = renderToStaticMarkup(<DrumSheetView text={chart} />);
- const lit = renderToStaticMarkup(<DrumSheetView text={chart} activeStep={{ bar: 2, step: 1 }} />);
- expect(count(none, 'rect')).toBe(0);
- expect(count(lit, 'rect')).toBe(1); // exactly one playhead column
- expect(lit).toContain('--port-accent');
+ it('keeps the kit labels in their own column so they survive scrolling', () => {
+ const html = renderToStaticMarkup(<DrumSheetView text={ROCK_BEAT} />);
+ const labelSvg = html.slice(html.indexOf('<svg'), html.indexOf('overflow-x-auto'));
+ expect(labelSvg).toContain('Hi-Hat');
+ expect(labelSvg).toContain('aria-hidden="true"');
+ // …and names them on the lane instead, since the column is aria-hidden.
+ expect(html).toMatch(/aria-label="Drum chart[^"]*Hi-Hat/);
});
- it('ignores an out-of-range activeStep instead of drawing off-grid', () => {
- const html = renderToStaticMarkup(<DrumSheetView text={'subdivision: 1\n\nHH: xxxx'} activeStep={{ bar: 1, step: 99 }} />);
- expect(count(html, 'rect')).toBe(0);
- expect(html).not.toMatch(/NaN/);
+ it('scales the whole lane off the viewer font control', () => {
+ const small = renderToStaticMarkup(<DrumSheetView text={ROCK_BEAT} fontSizeRem={0.875} />);
+ const large = renderToStaticMarkup(<DrumSheetView text={ROCK_BEAT} fontSizeRem={1.75} />);
+ const laneWidth = (html) => Number(/<svg[^>]*viewBox="0 0 (\d+(?:\.\d+)?)[^"]*"[^>]*width="(\d+(?:\.\d+)?)"/.exec(html.slice(html.indexOf('overflow-x-auto')))?.[2]);
+ expect(laneWidth(large)).toBeCloseTo(laneWidth(small) * 2, 1);
});
it('renders the sheet AND an errors summary for a partly-bad chart', () => {
const html = renderToStaticMarkup(<DrumSheetView text={'CB: xxxx\nHH: xxxx'} />);
- expect(html).toContain('aria-label="Drum bar 1"'); // the good row still drew
+ expect(html).toContain('aria-label="Drum chart'); // the good row still drew
expect(html).toContain('unknown kit piece');
expect(html).toContain('1 chart note');
});
@@ -125,8 +134,66 @@ describe('DrumSheetView', () => {
it('adds tap targets only when onStepClick is provided', () => {
const chart = 'subdivision: 1\n\nHH: xxxx';
- expect(count(renderToStaticMarkup(<DrumSheetView text={chart} />), 'rect')).toBe(0);
+ // The playhead column is the one rect a static sheet carries.
+ expect(count(renderToStaticMarkup(<DrumSheetView text={chart} />), 'rect')).toBe(1);
const interactive = renderToStaticMarkup(<DrumSheetView text={chart} onStepClick={() => {}} />);
- expect(count(interactive, 'rect')).toBe(4); // one per cell of the single row
+ expect(count(interactive, 'rect')).toBe(5); // + one per cell of the single row
+ });
+
+ // --- The playhead (rAF, DOM-only — never React state) ----------------------
+
+ const playhead = (container) => ({
+ line: container.querySelector('[data-playhead="line"]'),
+ column: container.querySelector('[data-playhead="column"]'),
+ });
+
+ // One animation frame, driven by hand so the assertions don't race the clock.
+ const oneFrame = (fn) => {
+ const frames = [];
+ vi.spyOn(globalThis, 'requestAnimationFrame').mockImplementation((cb) => {
+ frames.push(cb);
+ return frames.length;
+ });
+ vi.spyOn(globalThis, 'cancelAnimationFrame').mockImplementation(() => {});
+ const out = fn();
+ act(() => { frames.shift()?.(0); });
+ vi.restoreAllMocks();
+ return out;
+ };
+
+ it('places both playhead marks off the audio clock without re-rendering the lane', () => {
+ const chart = 'subdivision: 1\n\nHH: xxxx\n\nHH: xxxx';
+ const getPlayhead = vi.fn(() => ({ countIn: false, bar: 2, stepFloat: 1.5 }));
+ let container;
+ oneFrame(() => {
+ ({ container } = render(<DrumSheetView text={chart} playing getPlayhead={getPlayhead} />));
+ });
+ const { line, column } = playhead(container);
+ expect(getPlayhead).toHaveBeenCalled();
+ expect(line.style.display).not.toBe('none');
+ // Bar 2 starts one 4-step bar (plus the inter-bar gap) into the lane, so the
+ // marks sit right of bar 1 rather than at the origin…
+ const x = Number(/translate\(([\d.]+)/.exec(line.getAttribute('transform'))[1]);
+ expect(x).toBeGreaterThan(4 * 20);
+ // …and the column quantizes to the step the line is partway through.
+ expect(Number(column.getAttribute('x'))).toBe(x - 0.5 * 20);
+ });
+
+ it('parks the playhead during the count-in instead of sliding through bar 1', () => {
+ let container;
+ oneFrame(() => {
+ ({ container } = render(
+ <DrumSheetView text={'subdivision: 1\n\nHH: xxxx'} playing getPlayhead={() => ({ countIn: true, beat: 2 })} />,
+ ));
+ });
+ const { line, column } = playhead(container);
+ expect(line.style.display).toBe('none');
+ expect(column.style.display).toBe('none');
+ });
+
+ it('does not run a frame loop while stopped', () => {
+ const getPlayhead = vi.fn(() => ({ countIn: false, bar: 1, stepFloat: 0 }));
+ render(<DrumSheetView text={'subdivision: 1\n\nHH: xxxx'} getPlayhead={getPlayhead} />);
+ expect(getPlayhead).not.toHaveBeenCalled();
});
});
diff --git a/client/src/components/songbook/DrumTransportBar.jsx b/client/src/components/songbook/DrumTransportBar.jsx
index 998b581a4c..e0d1b54c38 100644
--- a/client/src/components/songbook/DrumTransportBar.jsx
+++ b/client/src/components/songbook/DrumTransportBar.jsx
@@ -1,26 +1,66 @@
/**
* DrumTransportBar — the play-along controls for a SongBook `drum` chart (#3115).
*
- * Purely presentational over `useDrumPlayer`: play/stop, a practice-tempo number
- * input + slider (clamped by `clampBpm`, 20–320), percent-of-written quick
- * buttons that recompute BPM from the chart's `tempo:` marking, a count-in
- * select, a loop toggle with a from/to bar range, and a metronome-click toggle.
- * All state and audio live in the hook — this file only renders and calls back.
+ * Purely presentational over `useDrumPlayer`: play/stop, a practice-tempo
+ * stepper + number input (slider on wider screens, clamped by `clampBpm`,
+ * 20–320), percent-of-written quick buttons that recompute BPM from the chart's
+ * `tempo:` marking, a count-in select, a loop toggle with a from/to bar range,
+ * a metronome-click toggle, and a live beat/bar readout. All state and audio
+ * live in the hook — this file only renders and calls back.
+ *
+ * PHONE-FIRST LAYOUT. A phone is the primary SongBook surface, and the previous
+ * one-flat-wrapping-row bar cost three stacked rows (~330px) before the sheet
+ * even started. So the controls split in two:
+ * - a PRIMARY row that is always visible — the ones you touch mid-practice
+ * (play, tempo, click) plus the beat readout; and
+ * - a SECONDARY row of setup controls (practice percent, count-in, loop range)
+ * that collapses behind a "More" disclosure under `sm` and sits inline above
+ * it from `sm` up, where there's room.
*
* Every control pairs `<label htmlFor>` with an `id`, and the buttons keep 44px
- * touch targets; the bar wraps so it stays usable on a phone.
+ * touch targets.
*/
-import { Play, Square, Repeat, Timer } from 'lucide-react';
+import { useMemo, useState } from 'react';
+import { Play, Square, Repeat, Timer, Minus, Plus, SlidersHorizontal } from 'lucide-react';
import { METRONOME_BPM_MIN, METRONOME_BPM_MAX } from '../../lib/metronome.js';
// Practice speeds as a percentage of the chart's written tempo.
const PERCENTS = [50, 75, 90, 100, 110];
const COUNT_IN_OPTIONS = [0, 1, 2];
+// The tempo steppers move in fives — a phone user nudging 96→76 shouldn't need
+// twenty taps, and the ±1 fine trim is on the keyboard (+/-) and the input.
+const BPM_STEP = 5;
// 44px minimum touch targets, matching the viewer's own controls bar.
const ctrlBtnClass = 'flex items-center justify-center min-w-[44px] min-h-[44px] rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50';
const smallSelectClass = 'bg-port-bg border border-port-border rounded px-2 py-2 min-h-[44px] text-xs text-white focus:border-port-accent focus:outline-none';
+const activeClass = 'text-port-accent border-port-accent/50';
+
+// The pulse row: one dot per notated beat of the bar, the current one lit. This
+// is the metronome you can SEE — the audible click is easy to lose under a kit,
+// and on a phone the dots double as "yes, it's actually running".
+const BeatDots = ({ beatsPerBar, beat, countingIn }) => (
+ <div
+ className="flex items-center gap-1"
+ role="status"
+ aria-live="off"
+ aria-label={countingIn ? `Counting in, beat ${beat || 1}` : (beat ? `Beat ${beat}` : 'Stopped')}
+ >
+ {Array.from({ length: beatsPerBar }, (_, i) => {
+ const lit = beat === i + 1;
+ return (
+ <span
+ key={i}
+ aria-hidden="true"
+ className={`rounded-full ${lit ? 'w-2.5 h-2.5' : 'w-1.5 h-1.5'} ${
+ !lit ? 'bg-port-border' : (countingIn ? 'bg-port-warning' : 'bg-port-accent')
+ }`}
+ />
+ );
+ })}
+ </div>
+);
export default function DrumTransportBar({
playing, onToggle, hasMusic = true,
@@ -28,140 +68,197 @@ export default function DrumTransportBar({
countInBars, onCountInChange,
loopEnabled, onLoopToggle, loopFrom, loopTo, onLoopRangeChange, barCount,
clickEnabled, onClickToggle,
+ beatsPerBar = 4, pulse = null, currentBar = null,
}) {
- const barOptions = Array.from({ length: Math.max(1, barCount) }, (_, i) => i + 1);
+ // Setup controls: collapsed by default on a phone, always shown from `sm` up.
+ const [showSetup, setShowSetup] = useState(false);
+
+ // `pulse` turns over on every beat, so the bar-range options must not be
+ // rebuilt with it — a 32-bar song is 64 <option>s per beat otherwise.
+ const barOptions = useMemo(
+ () => Array.from({ length: Math.max(1, barCount) }, (_, i) => i + 1),
+ [barCount],
+ );
// Which percent button (if any) the current BPM corresponds to — so the active
// practice speed is visible rather than inferred.
const activePercent = PERCENTS.find((p) => Math.round((writtenTempo * p) / 100) === bpm);
return (
- <div className="shrink-0 border-b border-port-border bg-port-card/60 px-3 py-2 flex flex-wrap items-center gap-x-4 gap-y-2">
- {/* Transport */}
- <div className="flex items-center gap-1" role="group" aria-label="Drum play-along">
- <button
- type="button"
- onClick={onToggle}
- // An all-rest chart parses into bars but has nothing to sound — a Play
- // button that silently does nothing reads as broken.
- disabled={!hasMusic}
- className={`${ctrlBtnClass} disabled:opacity-40 disabled:hover:bg-transparent ${playing ? 'text-port-accent border-port-accent/50' : ''}`}
- aria-label={playing ? 'Stop play-along' : 'Play along'}
- title={hasMusic
- ? (playing ? 'Stop (space)' : 'Play along (space)')
- : 'Nothing to play — this chart has no hits yet'}
- >
- {playing ? <Square size={16} /> : <Play size={18} />}
- </button>
- </div>
+ <div className="shrink-0 border-b border-port-border bg-port-card/60 px-3 py-2 space-y-2">
+ {/* --- Primary: the controls you touch while playing -------------------- */}
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
+ <div className="flex items-center gap-1.5" role="group" aria-label="Drum play-along">
+ <button
+ type="button"
+ onClick={onToggle}
+ // An all-rest chart parses into bars but has nothing to sound — a Play
+ // button that silently does nothing reads as broken.
+ disabled={!hasMusic}
+ className={`${ctrlBtnClass} disabled:opacity-40 disabled:hover:bg-transparent ${playing ? activeClass : ''}`}
+ aria-label={playing ? 'Stop play-along' : 'Play along'}
+ title={hasMusic
+ ? (playing ? 'Stop (space)' : 'Play along (space)')
+ : 'Nothing to play — this chart has no hits yet'}
+ >
+ {playing ? <Square size={16} /> : <Play size={18} />}
+ </button>
- {/* Practice tempo */}
- <div className="flex items-center gap-2">
- <label htmlFor="drum-bpm" className="text-xs text-gray-400">BPM</label>
- <input
- id="drum-bpm"
- type="number"
- min={METRONOME_BPM_MIN}
- max={METRONOME_BPM_MAX}
- value={bpm}
- onChange={(e) => onBpmChange(e.target.value)}
- className="w-16 bg-port-bg border border-port-border rounded px-2 py-2 min-h-[44px] text-sm text-white focus:border-port-accent focus:outline-none"
- />
- <label htmlFor="drum-bpm-slider" className="sr-only">Practice tempo</label>
- <input
- id="drum-bpm-slider"
- type="range"
- min={METRONOME_BPM_MIN}
- max={METRONOME_BPM_MAX}
- value={bpm}
- onChange={(e) => onBpmChange(e.target.value)}
- className="w-24 sm:w-32 accent-port-accent"
- title="Practice tempo (+/-)"
- />
- </div>
+ {/* Metronome click — a primary control: it's the thing you toggle
+ between "play me the groove" and "just count me in". */}
+ <button
+ type="button"
+ onClick={() => onClickToggle(!clickEnabled)}
+ aria-pressed={clickEnabled}
+ className={`${ctrlBtnClass} ${clickEnabled ? activeClass : ''}`}
+ aria-label={clickEnabled ? 'Turn the metronome off' : 'Turn the metronome on'}
+ title="Metronome click over the kit"
+ >
+ <Timer size={16} />
+ </button>
+ </div>
- {/* Percent of written tempo */}
- <div className="flex items-center gap-1" role="group" aria-label="Percent of written tempo">
- {PERCENTS.map((p) => (
+ {/* Practice tempo — steppers everywhere, slider only where there's room */}
+ <div className="flex items-center gap-1">
<button
- key={p}
type="button"
- onClick={() => onPercent(p)}
- aria-pressed={activePercent === p}
- className={`px-2 min-h-[44px] rounded-lg border text-xs ${
- activePercent === p
- ? 'border-port-accent/50 text-port-accent'
- : 'border-port-border text-gray-400 hover:text-white hover:bg-port-border/50'
- }`}
- title={`${p}% of the written ${writtenTempo} BPM`}
+ onClick={() => onBpmChange(bpm - BPM_STEP)}
+ className={ctrlBtnClass}
+ aria-label={`Slower by ${BPM_STEP} BPM`}
+ title={`−${BPM_STEP} BPM (− fine-tunes by 1)`}
>
- {p}%
+ <Minus size={16} />
</button>
- ))}
- </div>
+ <label htmlFor="drum-bpm" className="sr-only">Practice tempo (BPM)</label>
+ <input
+ id="drum-bpm"
+ type="number"
+ inputMode="numeric"
+ min={METRONOME_BPM_MIN}
+ max={METRONOME_BPM_MAX}
+ value={bpm}
+ onChange={(e) => onBpmChange(e.target.value)}
+ className="w-14 bg-port-bg border border-port-border rounded px-1 py-2 min-h-[44px] text-sm text-center text-white focus:border-port-accent focus:outline-none"
+ title="Practice tempo (BPM)"
+ />
+ <button
+ type="button"
+ onClick={() => onBpmChange(bpm + BPM_STEP)}
+ className={ctrlBtnClass}
+ aria-label={`Faster by ${BPM_STEP} BPM`}
+ title={`+${BPM_STEP} BPM (+ fine-tunes by 1)`}
+ >
+ <Plus size={16} />
+ </button>
+ <label htmlFor="drum-bpm-slider" className="sr-only">Practice tempo slider</label>
+ <input
+ id="drum-bpm-slider"
+ type="range"
+ min={METRONOME_BPM_MIN}
+ max={METRONOME_BPM_MAX}
+ value={bpm}
+ onChange={(e) => onBpmChange(e.target.value)}
+ className="hidden md:block w-32 ml-1 accent-port-accent"
+ title="Practice tempo (+/-)"
+ />
+ </div>
- {/* Count-in */}
- <div className="flex items-center gap-2">
- <label htmlFor="drum-countin" className="text-xs text-gray-400">Count-in</label>
- <select
- id="drum-countin"
- value={countInBars}
- onChange={(e) => onCountInChange(e.target.value)}
- className={smallSelectClass}
- >
- {COUNT_IN_OPTIONS.map((n) => (
- <option key={n} value={n}>{n === 0 ? 'none' : `${n} bar${n === 1 ? '' : 's'}`}</option>
- ))}
- </select>
- </div>
+ {/* Where you are: the visual pulse plus the bar counter */}
+ <div className="flex items-center gap-2">
+ <BeatDots beatsPerBar={beatsPerBar} beat={pulse?.beat ?? null} countingIn={!!pulse?.countingIn} />
+ <span className="text-xs text-gray-400 tabular-nums whitespace-nowrap">
+ {pulse?.countingIn ? 'count-in' : `${currentBar || 1}/${Math.max(1, barCount)}`}
+ </span>
+ </div>
- {/* Loop */}
- <div className="flex items-center gap-2">
+ {/* Disclosure for the setup controls — phone only; from `sm` up they're
+ always rendered below. */}
<button
type="button"
- onClick={() => onLoopToggle(!loopEnabled)}
- aria-pressed={loopEnabled}
- className={`${ctrlBtnClass} ${loopEnabled ? 'text-port-accent border-port-accent/50' : ''}`}
- aria-label={loopEnabled ? 'Disable loop' : 'Enable loop'}
- title="Loop a bar range ([ and ] set the ends)"
+ onClick={() => setShowSetup((v) => !v)}
+ aria-expanded={showSetup}
+ aria-controls="drum-setup-controls"
+ className={`${ctrlBtnClass} sm:hidden ml-auto ${showSetup ? activeClass : ''}`}
+ aria-label={showSetup ? 'Hide practice settings' : 'Show practice settings'}
+ title="Practice speed, count-in, loop"
>
- <Repeat size={16} />
+ <SlidersHorizontal size={16} />
</button>
- {loopEnabled && (
- <>
- <label htmlFor="drum-loop-from" className="sr-only">Loop from bar</label>
- <select
- id="drum-loop-from"
- value={loopFrom}
- onChange={(e) => onLoopRangeChange(Number(e.target.value), loopTo)}
- className={smallSelectClass}
- >
- {barOptions.map((n) => <option key={n} value={n}>{n}</option>)}
- </select>
- <span className="text-xs text-gray-500">–</span>
- <label htmlFor="drum-loop-to" className="sr-only">Loop to bar</label>
- <select
- id="drum-loop-to"
- value={loopTo}
- onChange={(e) => onLoopRangeChange(loopFrom, Number(e.target.value))}
- className={smallSelectClass}
- >
- {barOptions.map((n) => <option key={n} value={n}>{n}</option>)}
- </select>
- </>
- )}
</div>
- {/* Metronome click */}
- <button
- type="button"
- onClick={() => onClickToggle(!clickEnabled)}
- aria-pressed={clickEnabled}
- className={`${ctrlBtnClass} ${clickEnabled ? 'text-port-accent border-port-accent/50' : ''}`}
- aria-label={clickEnabled ? 'Turn the click off' : 'Turn the click on'}
- title="Metronome click over the kit"
+ {/* --- Secondary: setup you touch between run-throughs ------------------ */}
+ <div
+ id="drum-setup-controls"
+ className={`${showSetup ? 'flex' : 'hidden'} sm:flex flex-wrap items-center gap-x-4 gap-y-2`}
>
- <Timer size={16} />
- </button>
+ <div className="flex items-center gap-1" role="group" aria-label="Percent of written tempo">
+ {PERCENTS.map((p) => (
+ <button
+ key={p}
+ type="button"
+ onClick={() => onPercent(p)}
+ aria-pressed={activePercent === p}
+ className={`px-2 min-h-[44px] rounded-lg border text-xs ${
+ activePercent === p
+ ? activeClass
+ : 'border-port-border text-gray-400 hover:text-white hover:bg-port-border/50'
+ }`}
+ title={`${p}% of the written ${writtenTempo} BPM`}
+ >
+ {p}%
+ </button>
+ ))}
+ </div>
+
+ <div className="flex items-center gap-2">
+ <label htmlFor="drum-countin" className="text-xs text-gray-400">Count-in</label>
+ <select
+ id="drum-countin"
+ value={countInBars}
+ onChange={(e) => onCountInChange(e.target.value)}
+ className={smallSelectClass}
+ >
+ {COUNT_IN_OPTIONS.map((n) => (
+ <option key={n} value={n}>{n === 0 ? 'none' : `${n} bar${n === 1 ? '' : 's'}`}</option>
+ ))}
+ </select>
+ </div>
+
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => onLoopToggle(!loopEnabled)}
+ aria-pressed={loopEnabled}
+ className={`${ctrlBtnClass} ${loopEnabled ? activeClass : ''}`}
+ aria-label={loopEnabled ? 'Disable loop' : 'Enable loop'}
+ title="Loop a bar range ([ and ] set the ends)"
+ >
+ <Repeat size={16} />
+ </button>
+ {loopEnabled && (
+ <>
+ <label htmlFor="drum-loop-from" className="sr-only">Loop from bar</label>
+ <select
+ id="drum-loop-from"
+ value={loopFrom}
+ onChange={(e) => onLoopRangeChange(Number(e.target.value), loopTo)}
+ className={smallSelectClass}
+ >
+ {barOptions.map((n) => <option key={n} value={n}>{n}</option>)}
+ </select>
+ <span className="text-xs text-gray-500">–</span>
+ <label htmlFor="drum-loop-to" className="sr-only">Loop to bar</label>
+ <select
+ id="drum-loop-to"
+ value={loopTo}
+ onChange={(e) => onLoopRangeChange(loopFrom, Number(e.target.value))}
+ className={smallSelectClass}
+ >
+ {barOptions.map((n) => <option key={n} value={n}>{n}</option>)}
+ </select>
+ </>
+ )}
+ </div>
+ </div>
</div>
);
}
diff --git a/client/src/components/songbook/DrumTransportBar.test.jsx b/client/src/components/songbook/DrumTransportBar.test.jsx
new file mode 100644
index 0000000000..610d50c7fd
--- /dev/null
+++ b/client/src/components/songbook/DrumTransportBar.test.jsx
@@ -0,0 +1,88 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { render, screen, fireEvent, cleanup } from '@testing-library/react';
+import DrumTransportBar from './DrumTransportBar.jsx';
+
+// The phone-first split (primary controls always visible, setup behind a
+// disclosure under `sm`) is the whole point of this bar — pin it, plus the
+// callbacks the viewer wires to `useDrumPlayer`.
+
+const props = (extra = {}) => ({
+ playing: false,
+ onToggle: vi.fn(),
+ bpm: 96,
+ onBpmChange: vi.fn(),
+ onPercent: vi.fn(),
+ writtenTempo: 96,
+ countInBars: 1,
+ onCountInChange: vi.fn(),
+ loopEnabled: false,
+ onLoopToggle: vi.fn(),
+ loopFrom: 1,
+ loopTo: 4,
+ onLoopRangeChange: vi.fn(),
+ barCount: 4,
+ clickEnabled: true,
+ onClickToggle: vi.fn(),
+ beatsPerBar: 4,
+ pulse: null,
+ currentBar: 1,
+ ...extra,
+});
+
+afterEach(cleanup);
+
+describe('DrumTransportBar', () => {
+ it('keeps play, tempo and the metronome in the always-visible primary row', () => {
+ render(<DrumTransportBar {...props()} />);
+ // No disclosure needed for any of these.
+ expect(screen.getByLabelText('Play along')).toBeTruthy();
+ expect(screen.getByLabelText('Practice tempo (BPM)').value).toBe('96');
+ expect(screen.getByLabelText('Turn the metronome off')).toBeTruthy();
+ });
+
+ it('collapses the setup controls under sm and expands them on the disclosure', () => {
+ render(<DrumTransportBar {...props()} />);
+ const toggle = screen.getByLabelText('Show practice settings');
+ const setup = document.getElementById('drum-setup-controls');
+ // jsdom applies no media queries, so the contract is the class pair: hidden
+ // by default, `sm:flex` restoring it once there's room.
+ expect(toggle.getAttribute('aria-expanded')).toBe('false');
+ expect(setup.className).toContain('hidden');
+ expect(setup.className).toContain('sm:flex');
+
+ fireEvent.click(toggle);
+ expect(screen.getByLabelText('Hide practice settings').getAttribute('aria-expanded')).toBe('true');
+ expect(document.getElementById('drum-setup-controls').className).toContain('flex');
+ expect(document.getElementById('drum-setup-controls').className).not.toContain('hidden');
+ });
+
+ it('steps the tempo in fives from the buttons', () => {
+ const p = props();
+ render(<DrumTransportBar {...p} />);
+ fireEvent.click(screen.getByLabelText('Faster by 5 BPM'));
+ expect(p.onBpmChange).toHaveBeenCalledWith(101);
+ fireEvent.click(screen.getByLabelText('Slower by 5 BPM'));
+ expect(p.onBpmChange).toHaveBeenCalledWith(91);
+ });
+
+ it.each([
+ ['stopped', { pulse: null }, 'Stopped', '1/4'],
+ ['mid-bar', { pulse: { bar: 2, beat: 3, countingIn: false }, currentBar: 2 }, 'Beat 3', '2/4'],
+ ['counting in', { pulse: { bar: null, beat: 1, countingIn: true } }, 'Counting in, beat 1', 'count-in'],
+ ])('reads the pulse while %s', (_name, extra, label, readout) => {
+ render(<DrumTransportBar {...props(extra)} />);
+ expect(screen.getByRole('status').getAttribute('aria-label')).toBe(label);
+ expect(screen.getByText(readout)).toBeTruthy();
+ });
+
+ it('draws a dot per notated beat of the bar, whatever the time signature', () => {
+ render(<DrumTransportBar {...props({ beatsPerBar: 6 })} />);
+ expect(screen.getByRole('status').querySelectorAll('span')).toHaveLength(6);
+ });
+
+ it('marks the percent button matching the current BPM', () => {
+ render(<DrumTransportBar {...props({ bpm: 48, writtenTempo: 96 })} />);
+ expect(screen.getByRole('button', { name: '50%' }).getAttribute('aria-pressed')).toBe('true');
+ expect(screen.getByRole('button', { name: '100%' }).getAttribute('aria-pressed')).toBe('false');
+ });
+});
diff --git a/client/src/hooks/useDrumPlayer.js b/client/src/hooks/useDrumPlayer.js
index 0767d9622e..acd62ff0c3 100644
--- a/client/src/hooks/useDrumPlayer.js
+++ b/client/src/hooks/useDrumPlayer.js
@@ -1,22 +1,25 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { parseDrumChart, drumChartHasMusic } from '../lib/drumNotation.js';
-import { createDrumPlayer, resolveLoopRange } from '../lib/drumPlayback.js';
+import { parseDrumChart, chartHasMusic } from '../lib/drumNotation.js';
+import { createDrumPlayer, resolveLoopRange, resolvePlayhead } from '../lib/drumPlayback.js';
import { clampBpm } from '../lib/metronome.js';
+import { useLocalStorageBool } from './useLocalStorageBool.js';
import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';
/**
* Drum play-along transport for a SongBook `drum` chart (#3115) — React wrapper
* over `lib/drumPlayback.js`. Owns the player lifecycle, the practice settings
- * (tempo / count-in / loop range / click) and the sheet playhead, so
+ * (tempo / count-in / loop range / click) and the playback position, so
* `SongBookViewer` only renders controls.
*
* Practice tempo is a PER-MACHINE preference, not synced content: it persists to
* `safeStorage` under the song id (exactly like the viewer's transpose offset)
- * and is never written into the record.
+ * and is never written into the record. The metronome is the same kind of
+ * preference but global to the machine, so it uses the shared
+ * `useLocalStorageBool`.
*
* A timing-critical edit (tempo, count-in, loop range) while playing STOPS
* playback rather than re-timing a running schedule — already-scheduled audio
- * can't be moved, so a live rebase would desync the playhead from what you hear.
+ * can't be moved, so a live rebase would desync the position from what you hear.
* The user presses play again at the new setting. The click toggle is the
* exception: it only gates FUTURE scheduling, so it applies live.
*
@@ -24,6 +27,15 @@ import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';
* order the seeding effects happen to run in can't leave the player holding a
* stale tempo (the per-song stored tempo lands after the player is created).
*
+ * POSITION COMES FROM THE AUDIO CLOCK, never from the player's `onStep` event
+ * callback — see `resolvePlayhead`. Two consumers, two rates:
+ * - `getPlayhead()` is a stable on-demand read for the sheet's own animation
+ * frame loop (a continuous line can't go through React state 8×/second);
+ * - `pulse` is the same position quantized to `{ bar, beat, countingIn }` for
+ * the transport's readout, polled per frame but only ever committed to state
+ * when the beat actually turns over — so the whole page re-renders on beats,
+ * not on steps.
+ *
* The player, its interval and its scheduled audio are torn down on stop, on a
* chart/song change, and on unmount — nothing survives the view.
*
@@ -35,9 +47,11 @@ export default function useDrumPlayer(text, { songId } = {}) {
const barCount = chart.bars.length;
// Bars can parse while every cell is a rest — there'd be nothing to hear, so
// the transport gates Play on real hits rather than on the bar count.
- const hasMusic = useMemo(() => drumChartHasMusic(text), [text]);
+ const hasMusic = useMemo(() => chartHasMusic(chart), [chart]);
// The chart's own `tempo:` marking — the 100% reference for the percent buttons.
const writtenTempo = clampBpm(chart.tempo) ?? 90;
+ const beatsPerBar = chart.time?.beats || 4;
+ const subdivision = chart.subdivision || 1;
const storageKey = songId ? `songbook:drumBpm:${songId}` : null;
const [bpm, setBpmState] = useState(writtenTempo);
@@ -45,9 +59,12 @@ export default function useDrumPlayer(text, { songId } = {}) {
const [loopEnabled, setLoopEnabledState] = useState(false);
const [loopFrom, setLoopFromState] = useState(1);
const [loopTo, setLoopToState] = useState(1);
- const [clickEnabled, setClickEnabledState] = useState(false);
+ // The click is a play-along METRONOME, so it defaults on — practising a groove
+ // against no pulse is the unusual case, and "never chosen" must not read as
+ // "chosen off" (the hook's own default handles that distinction).
+ const [clickEnabled, setClickEnabled] = useLocalStorageBool('songbook:drumClick', true);
const [playing, setPlaying] = useState(false);
- const [activeStep, setActiveStep] = useState(null);
+ const [pulse, setPulse] = useState(null);
const playerRef = useRef(null);
// Intent mirror of `playing`: during a first play the player's own flag only
@@ -83,15 +100,13 @@ export default function useDrumPlayer(text, { songId } = {}) {
return undefined;
}
const player = createDrumPlayer(chart, {
- onStep: (info) => setActiveStep(info),
- onEnded: () => { setPlayingBoth(false); setActiveStep(null); },
+ onEnded: () => setPlayingBoth(false),
});
playerRef.current = player;
return () => {
player.stop();
playerRef.current = null;
setPlayingBoth(false);
- setActiveStep(null);
};
}, [chart, setPlayingBoth]);
@@ -107,10 +122,39 @@ export default function useDrumPlayer(text, { songId } = {}) {
player.setClick(clickEnabled);
}, [chart, bpm, countInBars, loopEnabled, loopFrom, loopTo, clickEnabled]);
+ // Live playhead read — the source both consumers below share. Stable identity
+ // so a caller's animation-frame loop can depend on it without restarting.
+ const getPlayhead = useCallback(() => {
+ const player = playerRef.current;
+ if (!player || !playingRef.current) return null;
+ return resolvePlayhead(player.schedule(), player.position());
+ }, []);
+
+ // The transport's beat/bar readout, polled off the same clock and committed
+ // only when it changes (see the header note).
+ useEffect(() => {
+ if (!playing || typeof requestAnimationFrame !== 'function') {
+ setPulse(null);
+ return undefined;
+ }
+ let raf = requestAnimationFrame(function tick() {
+ raf = requestAnimationFrame(tick);
+ const head = getPlayhead();
+ const next = head && (head.countIn
+ ? { bar: null, beat: head.beat, countingIn: true }
+ : { bar: head.bar, beat: Math.floor(head.stepFloat / subdivision) + 1, countingIn: false });
+ setPulse((prev) => (
+ prev?.bar === next?.bar && prev?.beat === next?.beat && prev?.countingIn === next?.countingIn
+ ? prev
+ : next
+ ));
+ });
+ return () => cancelAnimationFrame(raf);
+ }, [playing, getPlayhead, subdivision]);
+
const stop = useCallback(() => {
playerRef.current?.stop();
setPlayingBoth(false);
- setActiveStep(null);
}, [setPlayingBoth]);
const toggle = useCallback(() => {
@@ -126,7 +170,6 @@ export default function useDrumPlayer(text, { songId } = {}) {
Promise.resolve(player.play()).catch((err) => {
console.error(`🥁 Drum play-along failed to start: ${err.message}`);
setPlayingBoth(false);
- setActiveStep(null);
});
}, [setPlayingBoth, stop, hasMusic]);
@@ -168,18 +211,16 @@ export default function useDrumPlayer(text, { songId } = {}) {
setLoopToState(range.to);
}, [barCount, stopIfPlaying]);
- // Click only gates FUTURE scheduling — safe to flip mid-groove.
- const setClickEnabled = useCallback((enabled) => setClickEnabledState(!!enabled), []);
-
// The bar the `[` / `]` loop-endpoint shortcuts act on: the playhead's bar
// while playing, else the current loop start.
- const currentBar = activeStep?.bar || loopFrom;
+ const currentBar = pulse?.bar || loopFrom;
return {
chart,
barCount,
hasMusic,
writtenTempo,
+ beatsPerBar,
bpm,
setBpm,
setBpmPercent,
@@ -193,8 +234,9 @@ export default function useDrumPlayer(text, { songId } = {}) {
clickEnabled,
setClickEnabled,
playing,
- activeStep,
+ pulse,
currentBar,
+ getPlayhead,
toggle,
stop,
};
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index e87150cd12..1fce1090bf 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -126,7 +126,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `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). |
| `editorialChecks.js` | Pure helpers for the Editorial Checks page (`/pipeline/editorial-checks`, #1285): `groupChecksByScope(checks)` buckets catalog rows into ordered Noun/Scene/Issue/Series sections; `groupFindingsByCheck(comments, rowsById)` groups check-sourced review comments per check with open/total + severity counts; `openFindingsTotal(groups)` sums open findings; `findingManuscriptLink(seriesId, comment)` builds the `?comment=` deep-link into the manuscript editor; the triage filter/sort helpers (#1600) `deriveFindingFacets(groups)` (enumerate present severities/statuses/scopes/checks/issues), `applyFindingsView(groups, filters, sort)` (filter + recount + sort findings and groups), `normalizeFindingSort`, `findingIssueKey`, and the `FINDING_SORT_OPTIONS` table; the per-check maturity/quality helpers (#1629) `checkDismissalRate(group)` and `checkMaturity(group)` (→ `{ findings, dismissalRate, falsePositiveRate, level }`, `level` ∈ new/unproven/noisy/reliable) plus the `CHECK_MATURITY_MIN_SAMPLE`/`CHECK_NOISY_DISMISSAL_RATE` thresholds; plus `scopeLabel` and the `CHECK_SCOPE_ORDER`/`CHECK_SCOPE_LABELS` tables. No React/window — the page and its tests share them. |
| `editorialHealth.js` | Pure presentation helpers for the editorial health panel (`/pipeline/editorial-checks`, #1316): `scoreBand(score)` bands a 0–100 health score into a label + Tailwind tone; `deltaDisplay(delta)` formats the revision-to-revision score change (arrow + tone); `sparklineGeometry(points, box)` projects the trend's score points into SVG polyline coords; `orderedCategories(openByCategory)` sorts the per-category open-finding breakdown; `orderedChecks(openByCheck, labelFor)` sorts the per-check breakdown resolving each id to its catalog label (#1597); `checkCountSeries(points, checkId)` extracts one check's count series across the trend points; `countSparklineGeometry(values, box)` projects a non-negative count series into SVG polyline coords normalized to its own max (per-check finding-count sparkline); `diffCountMaps(current, previous)` lists the buckets whose open-finding count changed between two snapshots (#1630); `snapshotDiff(point, previous)` builds a trend snapshot's drill-down (its own breakdown + per-severity/category/check diff vs the prior revision, null-aware for pre-#1597 per-check telemetry, #1630); plus the `SEVERITY_ORDER`/`SEVERITY_LABELS` and `READINESS_GATE_LABELS`/`READINESS_GATE_ORDER` tables. No React/window — the panel and its tests share them. |
-| `drumNotation.js` | Parser for the PortOS drum-kit notation (#3115) — a dependency-free GRID DSL (`HH: x x x x`) for the SongBook `drum` content format, drawn by `<DrumSheetView>` (hand-rolled SVG, no engraving lib). `parseDrumChart(text)` → `{ time, tempo, subdivision, stepsPerBar, bars:[{index,label,repeat,repeatPass,rows:[{piece,cells}]}], pieces, errors }` — `key: value` headers (`time`/`tempo`/`subdivision`/`kit` row-order override), blank-line-separated bar blocks with a `# label x2` repeat suffix expanded into real bars, nine kit pieces (`CR RD HH T1 T2 S FT K HF`, long aliases accepted), six cell glyphs (`-` rest, `x` normal, `X` accent, `o` open, `g` ghost, `f` flam) with spacing optional. Forgiving: short rows pad with rests, over-long rows truncate, unknown pieces/cells collect into `errors` — never throws. Plus `KIT_PIECES` (label / GM `midi` / synth `sound` / `glyph`), `kitPiece(id)`, `CELL_GLYPHS` (per-glyph velocity + flags), `isDrumNotation(text)` (import-page format sniff, runs BEFORE `tabNotation.detectFormat`), and `drumChartHasMusic(text)`. NOT the lead-sheet parser (`scoreNotation.js`). |
+| `drumNotation.js` | Parser for the PortOS drum-kit notation (#3115) — a dependency-free GRID DSL (`HH: x x x x`) for the SongBook `drum` content format, drawn by `<DrumSheetView>` (hand-rolled SVG, no engraving lib). `parseDrumChart(text)` → `{ time, tempo, subdivision, stepsPerBar, bars:[{index,label,repeat,repeatPass,rows:[{piece,cells}]}], pieces, errors }` — `key: value` headers (`time`/`tempo`/`subdivision`/`kit` row-order override), blank-line-separated bar blocks with a `# label x2` repeat suffix expanded into real bars, nine kit pieces (`CR RD HH T1 T2 S FT K HF`, long aliases accepted), six cell glyphs (`-` rest, `x` normal, `X` accent, `o` open, `g` ghost, `f` flam) with spacing optional. Forgiving: short rows pad with rests, over-long rows truncate, unknown pieces/cells collect into `errors` — never throws. Plus `KIT_PIECES` (label / GM `midi` / synth `sound` / `glyph`), `kitPiece(id)`, `CELL_GLYPHS` (per-glyph velocity + flags), `isDrumNotation(text)` (import-page format sniff, runs BEFORE `tabNotation.detectFormat`), `drumChartHasMusic(text)` and its already-parsed twin `chartHasMusic(chart)`. NOT the lead-sheet parser (`scoreNotation.js`). |
| `drumPlayback.js` | Synthesized drum-kit play-along for the SongBook `drum` format (#3115) — the third consumer of `lookaheadTransport.js` alongside `scorePlayback`/`midiPlayback`. `buildDrumSchedule(chart, { bpm, loop, countInBars })` is the PURE chart→`[{ bar, step, piece, sound, velocity, startSec, durSec, countIn }]` mapping (one notated beat = `60/bpm`, one grid step = beat/`subdivision`; per-glyph velocity; a looped bar range is sliced and rebased while keeping the CHART's bar numbers for the playhead) — unit-tested with no Web Audio; `resolveLoopRange(barCount, loop)` clamps/normalizes a 1-based inclusive bar range; the count-in is scheduled as real `countIn: true` events on the same clock so there is no second timer. `createDrumPlayer(chart, { bpm, countInBars, loopBars, clickEnabled, onStep, onEnded })` sounds it on the shared `AudioContext` from a SYNTHESIZED kit (no shipped samples — bandpassed noise burst for snare/hats/cymbals, pitch-dropping sine for kick/toms, open-hat tail, flam grace note) with an optional layered metronome click, loops the range scheduler-exactly (count-in only on the first pass), and reports `onStep({ bar, step, countIn })` for the `<DrumSheetView>` playhead. Pure (no React) — `SongBookViewer` owns the transport UI. |
| `lookaheadTransport.js` | Shared lookahead-transport state machine for the synth players (#2493) — `createLookaheadTransport({ getTotalSec, scheduleWindow, prepare?, seekCursors?, onStop?, onEnded?, onTeardown? })` owns the Web Audio clock + live-node lifecycle (playing / interval / startTime / offsetSec / nodes / playToken, the suspended-context resume with the teardown-race guard, `track()` node pruning, and the play / pause / stop / seek / position transitions); each player supplies only the scheduling + notify callbacks and stays a thin scheduler over it, so a fix to the token-guard race or teardown lands in one place. Also the single source of the `SYNTH_TIMING` lookahead constants (`LEAD`/`LOOKAHEAD_MS`/`SCHEDULE_AHEAD`) `scorePlayback`/`midiPlayback` share. No React, no score/MIDI concepts — imports only the shared `AudioContext`. |
| `lossSparkline.js` | `lossSparklineGeometry(series, box)` — projects an unbounded training-loss series (`{step,loss}[]`) into SVG polyline coords, normalized to its own min/max (unlike `editorialHealth.sparklineGeometry`'s fixed 0–100 axis). Returns `{ points, coords, last, min, max }`. Drives the Render Queue's training-row loss curve (#1408). No React. |
diff --git a/client/src/lib/drumNotation.js b/client/src/lib/drumNotation.js
index e74878866f..a913921da9 100644
--- a/client/src/lib/drumNotation.js
+++ b/client/src/lib/drumNotation.js
@@ -323,7 +323,12 @@ export const isDrumNotation = (text) => {
return pieceRows >= 1 && /^\s*subdivision\s*:/im.test(String(text || ''));
};
-// True when the chart contains at least one struck cell — lets the UI show an
-// empty-state hint instead of an all-rest grid.
-export const drumChartHasMusic = (text) => parseDrumChart(text).bars
+// True when an ALREADY-PARSED chart contains at least one struck cell — lets the
+// UI show an empty-state hint instead of an all-rest grid. Split from the
+// text-taking form below so a caller that already holds a parsed chart doesn't
+// pay for a second full parse of the same source.
+export const chartHasMusic = (chart) => (chart?.bars || [])
.some((bar) => bar.rows.some((row) => row.cells.some((cell) => !cell.rest)));
+
+// Same question, from raw source.
+export const drumChartHasMusic = (text) => chartHasMusic(parseDrumChart(text));
diff --git a/client/src/lib/drumPlayback.js b/client/src/lib/drumPlayback.js
index ab79723562..3c2acd658b 100644
--- a/client/src/lib/drumPlayback.js
+++ b/client/src/lib/drumPlayback.js
@@ -137,6 +137,55 @@ export const buildDrumSchedule = (chart, options = {}) => {
};
};
+/**
+ * A built schedule + a live clock position → where the playhead sits, as a
+ * CONTINUOUS grid coordinate (pure; no Web Audio).
+ *
+ * THIS is the playhead the UI reads. The `onStep` callback reports the last
+ * event that SOUNDED, which is enough to light a column but not to place a
+ * position: it stalls across rests and never moves at all through a bar with no
+ * hits. Anything that has to keep moving with the music — the sheet's line, the
+ * transport's pulse — converts the audio clock here instead.
+ *
+ * Returns `null` when there's nothing to place. Otherwise:
+ * - during the count-in (and the negative pre-roll lead) —
+ * `{ countIn: true, beat }`, the 1-based beat WITHIN the count-in bar;
+ * - during the music — `{ countIn: false, bar, stepFloat }`, where `bar` is the
+ * chart's own 1-based bar number (so a loop range still points at the right
+ * bar of the full sheet) and `stepFloat` is a fractional grid step into it.
+ *
+ * @param {object} schedule — `buildDrumSchedule` output.
+ * @param {number} posSec — transport position in piece-seconds (may be negative).
+ */
+export const resolvePlayhead = (schedule, posSec) => {
+ const bars = Array.isArray(schedule?.bars) ? schedule.bars : [];
+ const { barSec, stepSec, beatSec, countInSec = 0 } = schedule || {};
+ if (!bars.length || !(barSec > 0) || !(stepSec > 0)) return null;
+ const pos = Number.isFinite(posSec) ? posSec : 0;
+
+ if (pos < countInSec) {
+ const beatsPerBar = beatSec > 0 ? Math.max(1, Math.round(barSec / beatSec)) : 1;
+ // The lead-in before t=0 is negative — clamp it to the first beat rather
+ // than counting backwards past the start of the count-in.
+ const elapsedBeats = Math.floor(Math.max(0, pos) / (beatSec || barSec));
+ return { countIn: true, beat: (elapsedBeats % beatsPerBar) + 1 };
+ }
+
+ const musicSec = bars.length * barSec;
+ let elapsed = pos - countInSec;
+ // A looping player runs past the end of its schedule forever, replaying the
+ // selected range — fold the position back onto one pass.
+ if (schedule.loop && musicSec > 0) elapsed = ((elapsed % musicSec) + musicSec) % musicSec;
+ elapsed = Math.min(Math.max(0, elapsed), Math.max(0, musicSec - 1e-6));
+
+ const barIdx = Math.min(bars.length - 1, Math.floor(elapsed / barSec));
+ return {
+ countIn: false,
+ bar: bars[barIdx].index,
+ stepFloat: (elapsed - barIdx * barSec) / stepSec,
+ };
+};
+
// --- Kit voices -------------------------------------------------------------
const VOICE_PEAK = 0.5; // per-hit gain ceiling before the per-cell velocity scale
@@ -368,6 +417,12 @@ export const createDrumPlayer = (chart, options = {}) => {
// Playhead: report the LATEST position whose onset has already passed. Keyed
// by bar+step so a bar's simultaneous hits fire one callback, not one per
// piece — and the key includes the pass, so a looped single bar re-lights.
+ //
+ // Event-driven, so it stands still through a rest — a caller that needs a
+ // position rather than "the last thing that sounded" reads the clock via
+ // `position()` + `resolvePlayhead` and passes no `onStep` at all, which
+ // skips this walk entirely.
+ if (!onStep) return;
let latest = null;
for (;;) {
if (headCursor.idx >= schedule.events.length) {
@@ -447,6 +502,11 @@ export const createDrumPlayer = (chart, options = {}) => {
pause: transport.pause,
stop: transport.stop,
isPlaying: transport.isPlaying,
+ // Live audio-clock position in piece-seconds. The `onStep` callback only
+ // fires on EVENTS (so it stalls across a rest and skips a silent bar
+ // entirely) — a continuously-scrolling sheet needs the clock itself, read
+ // per animation frame rather than pushed through React state.
+ position: transport.position,
setBpm: (next) => {
bpm = Number.isFinite(next) && next > 0 ? next : null;
rebuildIfIdle();
diff --git a/client/src/lib/drumPlayback.test.js b/client/src/lib/drumPlayback.test.js
index f99514a90d..afb5be59ad 100644
--- a/client/src/lib/drumPlayback.test.js
+++ b/client/src/lib/drumPlayback.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import { parseDrumChart, CELL_GLYPHS } from './drumNotation.js';
-import { buildDrumSchedule, resolveLoopRange } from './drumPlayback.js';
+import { buildDrumSchedule, resolveLoopRange, resolvePlayhead } from './drumPlayback.js';
// Invented grooves only (privacy convention). Every assertion here is pure math
// over the parsed chart — no AudioContext is created anywhere in this suite.
@@ -206,3 +206,54 @@ describe('resolveLoopRange', () => {
expect(resolveLoopRange(5, { from: 3 })).toEqual({ from: 3, to: 5 });
});
});
+
+describe('resolvePlayhead', () => {
+ // 2 bars at subdivision 1, 120 bpm → 0.5s/beat, 2s/bar, 4s total.
+ const chart = parseDrumChart(TWO_BARS);
+ const schedule = buildDrumSchedule(chart, { bpm: 120 });
+
+ it('places a mid-bar position as a FRACTIONAL step, not a quantized one', () => {
+ // 2.75s in = bar 2 (starts at 2s), 0.75s into it = 1.5 steps.
+ const head = resolvePlayhead(schedule, 2.75);
+ expect(head).toMatchObject({ countIn: false, bar: 2 });
+ near(head.stepFloat, 1.5);
+ });
+
+ it('keeps moving through a bar with no hits at all', () => {
+ // The onStep callback would stall here (no events to report); the clock
+ // does not. A rest-only bar 2 still resolves to a position inside bar 2.
+ const silent = buildDrumSchedule(parseDrumChart('time: 4/4\ntempo: 120\nsubdivision: 1\n\n# A\nK: o---\n\n# B\nK: ----'), { bpm: 120 });
+ expect(resolvePlayhead(silent, 3).bar).toBe(2);
+ });
+
+ it('reports the count-in as a beat within its bar', () => {
+ const withCount = buildDrumSchedule(chart, { bpm: 120, countInBars: 1 });
+ expect(resolvePlayhead(withCount, 0)).toMatchObject({ countIn: true, beat: 1 });
+ expect(resolvePlayhead(withCount, 1.2)).toMatchObject({ countIn: true, beat: 3 });
+ // The transport's pre-roll lead runs NEGATIVE before t=0 — that's still the
+ // first beat of the count-in, never a beat counted backwards.
+ expect(resolvePlayhead(withCount, -0.1)).toMatchObject({ countIn: true, beat: 1 });
+ // …and the music starts at the end of the count-in, rebased to bar 1.
+ expect(resolvePlayhead(withCount, 2)).toMatchObject({ countIn: false, bar: 1, stepFloat: 0 });
+ });
+
+ it('reports the CHART bar number for a looped range, not the slice index', () => {
+ // Loop bars 2–2: the schedule holds one bar, but the sheet must light bar 2.
+ const looped = buildDrumSchedule(chart, { bpm: 120, loop: { from: 2, to: 2 } });
+ expect(resolvePlayhead(looped, 0.5)).toMatchObject({ bar: 2 });
+ // A looping player runs past its own length forever — pass 3 folds back on.
+ expect(resolvePlayhead(looped, 6.5)).toMatchObject({ bar: 2 });
+ near(resolvePlayhead(looped, 6.5).stepFloat, 1);
+ });
+
+ it('clamps a one-shot position at the final step instead of running off the end', () => {
+ const head = resolvePlayhead(schedule, 99);
+ expect(head.bar).toBe(2);
+ expect(head.stepFloat).toBeLessThanOrEqual(4);
+ });
+
+ it('returns null when there is nothing to place', () => {
+ expect(resolvePlayhead(null, 1)).toBeNull();
+ expect(resolvePlayhead(buildDrumSchedule(parseDrumChart(''), {}), 1)).toBeNull();
+ });
+});
diff --git a/client/src/pages/SongBookImport.test.jsx b/client/src/pages/SongBookImport.test.jsx
index e36cb2fa7a..03b5656723 100644
--- a/client/src/pages/SongBookImport.test.jsx
+++ b/client/src/pages/SongBookImport.test.jsx
@@ -117,7 +117,7 @@ describe('SongBookImport', () => {
// isDrumNotation runs BEFORE detectFormat — a grid row would otherwise
// classify as plain text.
expect(await screen.findByText('drum')).toBeTruthy();
- expect(screen.getByLabelText('Drum bar 1')).toBeTruthy();
+ expect(screen.getByLabelText(/^Drum chart —/)).toBeTruthy();
expect(screen.getAllByText('Hi-Hat').length).toBeGreaterThan(0);
});
@@ -153,7 +153,7 @@ describe('SongBookImport', () => {
fireEvent.click(screen.getByRole('tab', { name: 'From URL' }));
fireEvent.change(screen.getByLabelText('Tab / chord-sheet URL'), { target: { value: 'https://example.com/g' } });
fireEvent.click(screen.getByRole('button', { name: 'Fetch' }));
- await waitFor(() => expect(screen.getByLabelText('Drum bar 1')).toBeTruthy());
+ await waitFor(() => expect(screen.getByLabelText(/^Drum chart —/)).toBeTruthy());
// And for content the sniff can't read, the instrument still wins.
api.importSongFromUrl.mockResolvedValue({
diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsx
index 8e2c6e69d5..c22e42306c 100644
--- a/client/src/pages/SongBookViewer.jsx
+++ b/client/src/pages/SongBookViewer.jsx
@@ -8,7 +8,9 @@
* Two URL-param-driven modes (linkable-routes convention):
* - PLAY (default): the rendered sheet (TabSheetView — or DrumSheetView plus a
* drum transport bar when the content format is `drum`, #3115) with an
- * Ultimate-Guitar-style controls bar — autoscroll play/pause + speed,
+ * Ultimate-Guitar-style controls bar — autoscroll play/pause + speed
+ * (suppressed for a drum chart, which scrolls itself horizontally under its
+ * own playhead and would otherwise carry two rival "play" buttons),
* transpose ± (render-time transposeText, never mutates stored text; offset
* persisted per song via safeStorage), font size ±, an instrument-view
* toggle (?view=guitar|ukulele|piano — chord diagrams only, render-only,
@@ -577,33 +579,40 @@ export default function SongBookViewer() {
barCount={drum.barCount}
clickEnabled={drum.clickEnabled}
onClickToggle={drum.setClickEnabled}
+ beatsPerBar={drum.beatsPerBar}
+ pulse={drum.pulse}
+ currentBar={drum.currentBar}
/>
)}
<div className="shrink-0 border-b border-port-border bg-port-card/60 px-3 py-2 flex flex-wrap items-center gap-x-4 gap-y-2">
- {/* Autoscroll */}
- <div className="flex items-center gap-2">
- <button
- type="button"
- onClick={toggle}
- className={`${ctrlBtnClass} ${playing ? 'text-port-accent border-port-accent/50' : ''}`}
- aria-label={playing ? 'Pause autoscroll' : 'Play autoscroll'}
- title={playing ? 'Pause autoscroll (space)' : 'Play autoscroll (space)'}
- >
- {playing ? <Pause size={18} /> : <Play size={18} />}
- </button>
- <label htmlFor="song-speed" className="sr-only">Autoscroll speed</label>
- <input
- id="song-speed"
- type="range"
- min={SPEED_MIN}
- max={SPEED_MAX}
- value={pxPerSec}
- onChange={(e) => setPxPerSec(Number(e.target.value))}
- className="w-24 sm:w-32 accent-port-accent"
- title="Autoscroll speed (+/-)"
- />
- </div>
+ {/* Autoscroll — a drum chart scrolls HORIZONTALLY under its own
+ playhead (DrumSheetView), so a second vertical-scroll play button
+ would be a rival transport with a rival meaning of "play". */}
+ {!isDrum && (
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={toggle}
+ className={`${ctrlBtnClass} ${playing ? 'text-port-accent border-port-accent/50' : ''}`}
+ aria-label={playing ? 'Pause autoscroll' : 'Play autoscroll'}
+ title={playing ? 'Pause autoscroll (space)' : 'Play autoscroll (space)'}
+ >
+ {playing ? <Pause size={18} /> : <Play size={18} />}
+ </button>
+ <label htmlFor="song-speed" className="sr-only">Autoscroll speed</label>
+ <input
+ id="song-speed"
+ type="range"
+ min={SPEED_MIN}
+ max={SPEED_MAX}
+ value={pxPerSec}
+ onChange={(e) => setPxPerSec(Number(e.target.value))}
+ className="w-24 sm:w-32 accent-port-accent"
+ title="Autoscroll speed (+/-)"
+ />
+ </div>
+ )}
{/* Transpose — meaningless on a kit grid, so hidden for drum charts */}
{!isDrum && (
@@ -620,12 +629,14 @@ export default function SongBookViewer() {
</div>
)}
- {/* Font size */}
- <div className="flex items-center gap-1" role="group" aria-label="Font size">
- <button type="button" onClick={() => setFontSize(fontSize - FONT_STEP)} className={`${ctrlBtnClass} text-xs font-bold`} aria-label="Smaller text">
+ {/* Font size — on a drum chart the same control zooms the kit grid
+ (DrumSheetView scales the whole strip off fontSizeRem), so it's
+ labelled for what it actually does there. */}
+ <div className="flex items-center gap-1" role="group" aria-label={isDrum ? 'Grid size' : 'Font size'}>
+ <button type="button" onClick={() => setFontSize(fontSize - FONT_STEP)} className={`${ctrlBtnClass} text-xs font-bold`} aria-label={isDrum ? 'Zoom out' : 'Smaller text'}>
A−
</button>
- <button type="button" onClick={() => setFontSize(fontSize + FONT_STEP)} className={`${ctrlBtnClass} text-sm font-bold`} aria-label="Larger text">
+ <button type="button" onClick={() => setFontSize(fontSize + FONT_STEP)} className={`${ctrlBtnClass} text-sm font-bold`} aria-label={isDrum ? 'Zoom in' : 'Larger text'}>
A+
</button>
</div>
@@ -677,13 +688,16 @@ export default function SongBookViewer() {
</div>
</div>
- <div ref={scrollRef} className="flex-1 overflow-y-auto px-4 py-4">
+ <div ref={scrollRef} className="flex-1 overflow-y-auto px-3 py-3 sm:px-4 sm:py-4">
{song.content?.text && isDrum ? (
+ // Full width, not max-w-4xl: the kit strip IS the horizontal
+ // scroller, so capping it just shortens the window you read
+ // through on a wide screen.
<DrumSheetView
text={contentText}
fontSizeRem={fontSize}
- activeStep={drum.activeStep}
- className="max-w-4xl"
+ getPlayhead={drum.getPlayhead}
+ playing={drum.playing}
/>
) : song.content?.text ? (
<TabSheetView
diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsx
index 4df9c4027b..3f31bd4225 100644
--- a/client/src/pages/SongBookViewer.test.jsx
+++ b/client/src/pages/SongBookViewer.test.jsx
@@ -207,35 +207,39 @@ K: o - - - - - o -`;
api.getSong.mockResolvedValue(drumSong());
renderPage();
expect(await screen.findByText('Example Song')).toBeTruthy();
- // The kit sheet drew (labelled rows, per-bar svg).
- expect(screen.getByLabelText('Drum bar 1: Groove')).toBeTruthy();
- // One row label per bar that uses the piece (the block repeats x2).
+ // The kit sheet drew — one continuous lane for the whole song.
+ expect(screen.getByLabelText(/^Drum chart —/)).toBeTruthy();
+ // The frozen label column names every kit row the chart uses.
expect(screen.getAllByText('Hi-Hat').length).toBeGreaterThan(0);
// Transport controls are present.
expect(screen.getByLabelText('Play along')).toBeTruthy();
- expect(screen.getByLabelText('Practice tempo')).toBeTruthy();
+ expect(screen.getByLabelText('Practice tempo (BPM)')).toBeTruthy();
expect(screen.getByLabelText('Enable loop')).toBeTruthy();
- expect(screen.getByLabelText('Turn the click on')).toBeTruthy();
+ // The metronome defaults ON for a play-along, so the button offers to
+ // turn it off.
+ expect(screen.getByLabelText('Turn the metronome off')).toBeTruthy();
});
- it('hides transpose and the chord instrument-view picker for a drum chart', async () => {
+ it('hides transpose, chord voicings AND the rival autoscroll transport for a drum chart', async () => {
api.getSong.mockResolvedValue(drumSong());
renderPage();
expect(await screen.findByLabelText('Play along')).toBeTruthy();
expect(screen.queryByLabelText('Transpose up')).toBeNull();
expect(screen.queryByLabelText('Transpose down')).toBeNull();
expect(screen.queryByRole('combobox', { name: 'Instrument view' })).toBeNull();
- // Autoscroll stays available.
- expect(screen.getByLabelText('Autoscroll speed')).toBeTruthy();
+ // The kit strip scrolls horizontally under its own playhead — a vertical
+ // autoscroll play button beside it would be a second, conflicting "play".
+ expect(screen.queryByLabelText('Autoscroll speed')).toBeNull();
+ expect(screen.queryByLabelText('Play autoscroll')).toBeNull();
});
it('seeds BPM from the chart tempo and persists an edit per song (never the record)', async () => {
api.getSong.mockResolvedValue(drumSong());
renderPage();
- await screen.findByLabelText('BPM');
- await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('96'));
- fireEvent.change(screen.getByLabelText('BPM'), { target: { value: '72' } });
- await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('72'));
+ await screen.findByLabelText('Practice tempo (BPM)');
+ await waitFor(() => expect(screen.getByLabelText('Practice tempo (BPM)').value).toBe('96'));
+ fireEvent.change(screen.getByLabelText('Practice tempo (BPM)'), { target: { value: '72' } });
+ await waitFor(() => expect(screen.getByLabelText('Practice tempo (BPM)').value).toBe('72'));
expect(globalThis.localStorage.getItem('songbook:drumBpm:abc')).toBe('72');
// A practice tempo is a per-machine preference — never a record write.
expect(api.updateSong).not.toHaveBeenCalled();
@@ -245,28 +249,28 @@ K: o - - - - - o -`;
globalThis.localStorage.setItem('songbook:drumBpm:abc', '60');
api.getSong.mockResolvedValue(drumSong());
renderPage();
- await screen.findByLabelText('BPM');
- await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('60'));
+ await screen.findByLabelText('Practice tempo (BPM)');
+ await waitFor(() => expect(screen.getByLabelText('Practice tempo (BPM)').value).toBe('60'));
});
it('recomputes BPM from a percent-of-written button', async () => {
api.getSong.mockResolvedValue(drumSong());
renderPage();
- expect(await screen.findByLabelText('BPM')).toBeTruthy();
+ expect(await screen.findByLabelText('Practice tempo (BPM)')).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: '50%' }));
- await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('48'));
+ await waitFor(() => expect(screen.getByLabelText('Practice tempo (BPM)').value).toBe('48'));
fireEvent.click(screen.getByRole('button', { name: '100%' }));
- await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('96'));
+ await waitFor(() => expect(screen.getByLabelText('Practice tempo (BPM)').value).toBe('96'));
});
it('clamps a BPM outside the metronome band', async () => {
api.getSong.mockResolvedValue(drumSong());
renderPage();
- const bpm = await screen.findByLabelText('BPM');
+ const bpm = await screen.findByLabelText('Practice tempo (BPM)');
fireEvent.change(bpm, { target: { value: '9999' } });
- await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('320'));
- fireEvent.change(screen.getByLabelText('BPM'), { target: { value: '1' } });
- await waitFor(() => expect(screen.getByLabelText('BPM').value).toBe('20'));
+ await waitFor(() => expect(screen.getByLabelText('Practice tempo (BPM)').value).toBe('320'));
+ fireEvent.change(screen.getByLabelText('Practice tempo (BPM)'), { target: { value: '1' } });
+ await waitFor(() => expect(screen.getByLabelText('Practice tempo (BPM)').value).toBe('20'));
});
it('disables Play for an all-rest chart, and space cannot route around it', async () => {
@@ -280,6 +284,19 @@ K: o - - - - - o -`;
expect(screen.getByLabelText('Play along').disabled).toBe(true);
});
+ it('defaults the metronome ON and remembers it being turned off', async () => {
+ api.getSong.mockResolvedValue(drumSong());
+ const { unmount } = renderPage();
+ // A play-along without a pulse is the unusual case, so the click starts on
+ // — and "never chosen" (no stored value) must not read as "chosen off".
+ fireEvent.click(await screen.findByLabelText('Turn the metronome off'));
+ expect(globalThis.localStorage.getItem('songbook:drumClick')).toBe('0');
+ unmount();
+
+ renderPage();
+ expect(await screen.findByLabelText('Turn the metronome on')).toBeTruthy();
+ });
+
it('reveals the loop bar range only when looping is on', async () => {
api.getSong.mockResolvedValue(drumSong());
renderPage();
@@ -297,7 +314,7 @@ K: o - - - - - o -`;
renderPage('/songbook/abc?mode=edit');
expect(await screen.findByLabelText('Title')).toBeTruthy();
expect(screen.getByLabelText('Format').value).toBe('drum');
- expect(screen.getByLabelText('Drum bar 1: Groove')).toBeTruthy();
+ expect(screen.getByLabelText(/^Drum chart —/)).toBeTruthy();
});
it('keeps an unknown stored instrument/format selectable and preserves it on save', async () => {