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

explain drum-chart notation on tap: piece, articulation, technique and count for any note

[._.]/ Adam Eivyf31a22e41344
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8175b6ab96..a2aaf2659d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -36,6 +36,8 @@
- **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.
+- **Tap a note on a drum chart to find out what it's asking for.** The kit grid is PortOS's own notation, so there was nowhere to look up what an × with a chevron over it on the crash row actually means. Tapping any note now opens a readout naming the piece, the articulation ("Crash — Accent"), where it falls ("bar 6, count \"2 e\""), how hard it's struck relative to a full stroke, and how to strike that piece. The tapped note is boxed on the sheet so it's clear which one is being described, a near-miss on a tight groove still answers rather than dismissing, and tapping empty grid closes it. A new Legend button lists all six cell characters plus how to play each piece the chart uses, and the sheet takes keyboard focus so ←/→ walk the hits for anyone not using a touchscreen.
+
## 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/client/src/components/songbook/DrumSheetView.jsx b/client/src/components/songbook/DrumSheetView.jsx
index 1fe871c3a7..0930bf3ab1 100644
--- a/client/src/components/songbook/DrumSheetView.jsx
+++ b/client/src/components/songbook/DrumSheetView.jsx
@@ -28,6 +28,15 @@
* *attributes* don't evaluate `var()`, so `fill="var(--x)"` would silently paint
* nothing. Same rule as ScoreSheet.
*
+ * TAP A NOTE TO LEARN IT. This notation is hand-rolled, so nothing outside this
+ * repo explains what an × with a chevron over it is asking for. Tapping a glyph
+ * opens a readout (`describeDrumCell` in drumNotation.js) naming the piece, the
+ * articulation, and how to strike it; the Legend button is the same content
+ * for the whole kit, and the lane is focusable so ←/→ walk the hits without a
+ * pointer. Hit-testing is arithmetic on the click coordinates rather than a
+ * per-cell <rect>, because a 32-bar chart would otherwise carry ~2500 invisible
+ * tap targets purely so a tap could report where it landed.
+ *
* Props:
* text — the raw chart source (parsed here; the parser never throws)
* fontSizeRem — scales the whole strip with the viewer's A−/A+ control
@@ -35,12 +44,12 @@
* 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
+ * editor (#3115 out-of-scope). It takes over the tap gesture, so
+ * an editing host gets cell rects instead of the explain readout
*/
-import { memo, useEffect, useMemo, useRef } from 'react';
-import { parseDrumChart, kitPiece } from '../../lib/drumNotation.js';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { parseDrumChart, kitPiece, describeDrumCell, describeKitPiece, DRUM_GLYPH_LEGEND } from '../../lib/drumNotation.js';
// --- Geometry (internal SVG units; the strip scales via width/height + viewBox)
const CELL = 20; // one grid step — every other measure derives from this
@@ -79,8 +88,21 @@ 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 SELECT_BOX = { stroke: 'rgb(var(--port-accent))', fill: 'rgb(var(--port-accent) / 0.14)' };
const UI_FONT = 'ui-sans-serif, system-ui, sans-serif';
+// Count-along syllables for a step inside its beat — how a drummer says the
+// position out loud ("2 e & a"). A subdivision with no conventional syllable
+// falls back to an exact "beat +n/N" rather than borrowing the wrong one.
+const SUBDIVISION_SYLLABLES = { 2: ['', '&'], 3: ['', 'trip', 'let'], 4: ['', 'e', '&', 'a'] };
+const countLabel = (step, subdivision) => {
+ const beat = Math.floor(step / subdivision) + 1;
+ const within = step % subdivision;
+ if (!within) return `${beat}`;
+ const syllable = SUBDIVISION_SYLLABLES[subdivision]?.[within];
+ return syllable ? `${beat} ${syllable}` : `${beat} +${within}/${subdivision}`;
+};
+
// 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
// "♩ = 96" — an unlisted denominator falls back to a plain "1/N" fraction rather
@@ -155,6 +177,77 @@ const LabelColumn = ({ pieces, height, scale }) => (
</svg>
);
+// What the tapped glyph means. Sits UNDER the strip rather than floating beside
+// the note: the lane is a horizontal scroller that auto-follows the playhead, so
+// an anchored bubble would slide off its own note mid-groove — the in-lane
+// highlight box says WHICH note, and this card says what it is. `aria-live` so a
+// keyboard walk through the hits is announced as the selection moves.
+const HitReadout = ({ info, bar, count, onClose }) => (
+ <div
+ role="status"
+ aria-live="polite"
+ className="mt-2 rounded-lg border border-port-accent/40 bg-port-accent/5 px-3 py-2 text-xs"
+ >
+ <div className="flex items-start gap-2">
+ <span
+ aria-hidden="true"
+ className="shrink-0 rounded border border-port-border bg-port-bg px-1.5 py-0.5 font-mono text-sm text-port-accent"
+ >
+ {info.char}
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
+ <span className="font-semibold text-white">{info.pieceLabel} — {info.articulation}</span>
+ <span className="text-gray-500">bar {bar}, count &ldquo;{count}&rdquo;</span>
+ {!info.rest && <span className="text-gray-500">≈{info.velocityPercent}% volume</span>}
+ </div>
+ <p className="mt-1 text-gray-300">{info.detail}</p>
+ {info.technique && <p className="mt-0.5 text-gray-400">{info.technique}</p>}
+ </div>
+ {/* A text × rather than a lucide icon: an `<svg>` anywhere in this
+ component inflates the glyph counts that assert what the NOTATION drew
+ (see DrumSheetView.test.jsx `count(html, 'circle')`). */}
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Close note explanation"
+ className="shrink-0 rounded px-1.5 leading-none text-base text-gray-500 hover:text-gray-200 focus:outline-none focus-visible:ring-1 focus-visible:ring-port-accent"
+ >
+ <span aria-hidden="true">×</span>
+ </button>
+ </div>
+ </div>
+);
+
+// The whole vocabulary at once — every cell character, plus how to strike each
+// piece THIS chart uses. The keyboard/screen-reader route to the same content
+// the tap readout gives, and the answer to "what are my options" when writing a
+// chart in Edit mode.
+const KitLegend = ({ pieces }) => (
+ <div className="mt-2 rounded-lg border border-port-border bg-port-bg/60 px-3 py-2 text-xs">
+ <dl className="grid gap-x-4 gap-y-1 sm:grid-cols-2">
+ {DRUM_GLYPH_LEGEND.map((glyph) => (
+ <div key={glyph.char} className="flex items-start gap-2">
+ <dt className="shrink-0 rounded border border-port-border bg-port-card px-1.5 font-mono text-sm text-port-accent">
+ {glyph.char}
+ </dt>
+ <dd className="min-w-0 text-gray-300">
+ <span className="font-semibold text-white">{glyph.name}</span> — {glyph.detail}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ <dl className="mt-2 space-y-1 border-t border-port-border pt-2">
+ {pieces.map((id) => describeKitPiece(id)).filter(Boolean).map((piece) => (
+ <div key={piece.id} className="flex items-start gap-2">
+ <dt className="w-20 shrink-0 font-semibold text-white">{piece.label}</dt>
+ <dd className="min-w-0 text-gray-400">{piece.technique}</dd>
+ </div>
+ ))}
+ </dl>
+ </div>
+);
+
// 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
// draw the bars that parsed.
@@ -179,8 +272,12 @@ function DrumSheetView({
}) {
const chart = useMemo(() => parseDrumChart(text), [text]);
const scrollRef = useRef(null);
+ const laneRef = useRef(null);
const lineRef = useRef(null);
const columnRef = useRef(null);
+ // The note whose explanation is showing — `{ bar, step, piece }` or null.
+ const [selection, setSelection] = useState(null);
+ const [legendOpen, setLegendOpen] = useState(false);
const scale = Math.min(SCALE_MAX, Math.max(SCALE_MIN, (fontSizeRem || BASE_FONT_REM) / BASE_FONT_REM));
const { pieces, subdivision, stepsPerBar } = chart;
@@ -201,6 +298,103 @@ function DrumSheetView({
};
}, [chart]);
+ // --- Tap / arrow-key note explanation --------------------------------------
+ // An editing host owns the tap gesture (see the prop doc), so the explain
+ // readout and `onStepClick` are mutually exclusive.
+ const explain = !onStepClick;
+
+ const cellAt = useCallback(
+ (bar, piece, step) => chart.bars[bar - 1]?.rows.find((r) => r.piece === piece)?.cells[step] || null,
+ [chart],
+ );
+
+ // Every struck cell in reading order (time, then top of the kit down) — the
+ // ←/→ walk steps through this, so the keyboard path reaches exactly the notes
+ // a tap can.
+ const hits = useMemo(() => {
+ const out = [];
+ for (const bar of chart.bars) {
+ for (let step = 0; step < chart.stepsPerBar; step += 1) {
+ for (const piece of chart.pieces) {
+ const cell = bar.rows.find((r) => r.piece === piece)?.cells[step];
+ if (cell && !cell.rest) out.push({ bar: bar.index, step, piece });
+ }
+ }
+ }
+ return out;
+ }, [chart]);
+
+ // Click coordinates → the note the finger meant. The tapped cell first, then
+ // one step either side in the SAME row: a cell is 20px wide at 1× zoom, well
+ // under a fingertip, so a near-miss on a groove should still answer rather
+ // than dismiss. A tap that lands on no hit at all closes the readout, which is
+ // the natural "tap the background to dismiss" gesture.
+ const selectFromPoint = useCallback((clientX, clientY) => {
+ const svg = laneRef.current;
+ if (!svg) return;
+ const box = svg.getBoundingClientRect();
+ // Into internal SVG units: the lane is drawn `laneW × height` and displayed
+ // at `scale` times that, with no other transform in between.
+ const ux = (clientX - box.left) / scale;
+ const uy = (clientY - box.top) / scale;
+ const piece = chart.pieces[Math.floor((uy - GRID_TOP) / ROW_H)];
+ const span = barW + BAR_GAP;
+ const rel = ux - PAD;
+ const bar = Math.floor(rel / span) + 1;
+ const within = rel - (bar - 1) * span;
+ // `uy < GRID_TOP` floors negative → no piece; `within >= barW` is the gap
+ // between bars. Either way there's nothing under the finger.
+ if (!piece || bar < 1 || bar > barCount || within < 0 || within >= barW) { setSelection(null); return; }
+ const step = Math.floor(within / CELL);
+ const found = [step, step - 1, step + 1].find((s) => {
+ const cell = s >= 0 && s < stepsPerBar ? cellAt(bar, piece, s) : null;
+ return cell && !cell.rest;
+ });
+ // `found` can legitimately be step 0, so test for the miss explicitly.
+ setSelection(found === undefined ? null : { bar, step: found, piece });
+ }, [barCount, barW, cellAt, chart, scale, stepsPerBar]);
+
+ // ←/→ (and ↑/↓, since reading order usually means the next row down) walk the
+ // hits. From no selection, → starts at the first note and ← at the last.
+ const moveSelection = useCallback((delta) => {
+ if (!hits.length) return;
+ setSelection((prev) => {
+ const i = prev
+ ? hits.findIndex((h) => h.bar === prev.bar && h.step === prev.step && h.piece === prev.piece)
+ : -1;
+ if (i < 0) return hits[delta > 0 ? 0 : hits.length - 1];
+ return hits[Math.min(hits.length - 1, Math.max(0, i + delta))];
+ });
+ }, [hits]);
+
+ const onLaneKeyDown = (e) => {
+ if (!explain) return;
+ const delta = (e.key === 'ArrowRight' || e.key === 'ArrowDown') ? 1
+ : (e.key === 'ArrowLeft' || e.key === 'ArrowUp') ? -1 : 0;
+ if (!delta) return;
+ e.preventDefault(); // arrows would otherwise scroll the lane out from under the walk
+ moveSelection(delta);
+ };
+
+ useEffect(() => {
+ if (!selection) return undefined;
+ const onKey = (e) => { if (e.key === 'Escape') setSelection(null); };
+ document.addEventListener('keydown', onKey);
+ return () => document.removeEventListener('keydown', onKey);
+ }, [selection]);
+
+ // Bring an arrow-walked note into view — skipped while playing, where the rAF
+ // follow loop owns `scrollLeft` and would fight this write every frame.
+ useEffect(() => {
+ const el = scrollRef.current;
+ if (!selection || !el || playing) return;
+ const left = (barX(selection.bar) + selection.step * CELL) * scale;
+ const right = left + CELL * scale;
+ // Land one cell inside the edge so the next note along is visible too.
+ if (left < el.scrollLeft) el.scrollLeft = Math.max(0, left - CELL * scale);
+ else if (right > el.scrollLeft + el.clientWidth) el.scrollLeft = right - el.clientWidth + CELL * scale;
+ }, [selection, playing, barX, scale]);
+
// 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.
@@ -240,13 +434,100 @@ function DrumSheetView({
return () => { cancelAnimationFrame(raf); hide(); };
}, [playing, getPlayhead, barCount, barX, laneW, scale]);
- // A new chart starts from the top. Content-keyed, so a host that can show two
- // DIFFERENT records with identical charts in one mounted sheet should key this
- // component by record id (SongBookViewer does).
+ // A new chart starts from the top, with no note selected — the old selection
+ // pointed at a bar/step that may not exist any more (live editing). Content-
+ // keyed, so a host that can show two DIFFERENT records with identical charts
+ // in one mounted sheet should key this component by record id
+ // (SongBookViewer does).
useEffect(() => {
if (scrollRef.current) scrollRef.current.scrollLeft = 0;
+ setSelection(null);
}, [chart]);
+ // The lane's grid + glyphs — ~2000 elements on a long chart, so memoized on
+ // the chart and its geometry ALONE. Selecting a note re-renders this component
+ // (the readout below is React state), and with a stable array React skips
+ // diffing the whole strip; the selection box is drawn outside it.
+ const els = useMemo(() => {
+ const out = [];
+ 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.
+ out.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) {
+ out.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;
+ out.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;
+ out.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) {
+ out.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(out, 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. When they
+ // ARE present the editing host owns the tap, and the explain readout is off.
+ if (onStepClick) {
+ pieces.forEach((id, ri) => {
+ for (let s = 0; s < stepsPerBar; s += 1) {
+ out.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 out;
+ }, [chart, pieces, subdivision, stepsPerBar, gridBottom, barX, barW, onStepClick]);
+
if (!chart.bars.length) {
return (
<div className={`text-sm text-gray-500 ${className}`}>
@@ -258,81 +539,8 @@ function DrumSheetView({
);
}
- 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)} />,
- );
- }
- });
- }
- });
+ const info = selection && describeDrumCell(selection.piece, cellAt(selection.bar, selection.piece, selection.step));
+ const selectedRow = selection ? pieces.indexOf(selection.piece) : -1;
return (
<div className={className} style={{ fontSize: `${fontSizeRem}rem` }}>
@@ -345,8 +553,24 @@ function DrumSheetView({
<span>{BEAT_GLYPH[chart.time.beatValue] || `1/${chart.time.beatValue}`} = {chart.tempo}</span>
<span>{chart.subdivision} per beat</span>
<span>{chart.bars.length} bar{chart.bars.length === 1 ? '' : 's'}</span>
+ {explain && (
+ <button
+ type="button"
+ onClick={() => setLegendOpen((open) => !open)}
+ aria-expanded={legendOpen}
+ className={`ml-auto flex min-h-[32px] items-center gap-1 rounded-full border px-2 py-1 focus:outline-none focus-visible:ring-1 focus-visible:ring-port-accent ${legendOpen ? 'border-port-accent/60 text-port-accent' : 'border-port-border hover:text-gray-300'}`}
+ >
+ Legend
+ </button>
+ )}
</div>
+ {/* The hint sits ABOVE the strip: on a phone the readout appears below the
+ lane, and a hint underneath it would be the last thing found. */}
+ {explain && !info && (
+ <p className="mb-1.5 text-xs text-gray-600">Tap any note to learn what it means.</p>
+ )}
+
<div className="flex items-start">
<LabelColumn pieces={pieces} height={height} scale={scale} />
{/* One scroller for the whole song. `overscroll-contain` keeps a swipe
@@ -356,12 +580,20 @@ function DrumSheetView({
{/* 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
+ ref={laneRef}
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' }}
+ 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(', ')}${explain ? '. Tap a note, or use the arrow keys, for an explanation of it' : ''}`}
+ // Explain mode hit-tests taps arithmetically (see selectFromPoint),
+ // so the whole lane is one listener instead of a rect per cell. The
+ // lane also takes focus so ←/→ can walk the hits — the tap gesture's
+ // keyboard equivalent, alongside the Legend button.
+ onClick={explain ? (e) => selectFromPoint(e.clientX, e.clientY) : undefined}
+ onKeyDown={explain ? onLaneKeyDown : undefined}
+ tabIndex={explain ? 0 : undefined}
+ style={{ display: 'block', cursor: explain ? 'pointer' : undefined }}
>
{/* 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
@@ -371,6 +603,12 @@ function DrumSheetView({
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' }} />
+ {/* Which note the readout is describing. Under the glyphs so the box
+ frames the note rather than washing over it. */}
+ {selectedRow >= 0 && (
+ <rect data-selected-cell="" x={barX(selection.bar) + selection.step * CELL} y={GRID_TOP + selectedRow * ROW_H}
+ width={CELL} height={ROW_H} rx={3} style={SELECT_BOX} strokeWidth={1.4} />
+ )}
{els}
<line data-playhead="line" ref={lineRef} x1={0} y1={PAD} x2={0} y2={gridBottom}
style={{ ...ACTIVE_STROKE, display: 'none' }} strokeWidth={1.6} />
@@ -378,6 +616,16 @@ function DrumSheetView({
</div>
</div>
+ {info && (
+ <HitReadout
+ info={info}
+ bar={selection.bar}
+ count={countLabel(selection.step, subdivision)}
+ onClose={() => setSelection(null)}
+ />
+ )}
+ {legendOpen && <KitLegend pieces={pieces} />}
+
{chart.errors.length > 0 && <ErrorSummary errors={chart.errors} />}
</div>
);
@@ -385,5 +633,6 @@ function DrumSheetView({
// 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.
+// and the lane is never rebuilt. Selecting a note DOES re-render (it's local
+// state), which is why the lane's element array is itself memoized.
export default memo(DrumSheetView);
diff --git a/client/src/components/songbook/DrumSheetView.test.jsx b/client/src/components/songbook/DrumSheetView.test.jsx
index 83327b0918..053958bf5c 100644
--- a/client/src/components/songbook/DrumSheetView.test.jsx
+++ b/client/src/components/songbook/DrumSheetView.test.jsx
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
-import { render, cleanup, act } from '@testing-library/react';
+import { render, cleanup, act, screen, fireEvent } from '@testing-library/react';
import DrumSheetView from './DrumSheetView.jsx';
// Invented grooves only (privacy convention).
@@ -140,6 +140,124 @@ describe('DrumSheetView', () => {
expect(count(interactive, 'rect')).toBe(5); // + one per cell of the single row
});
+ // --- Tap a note to learn it ------------------------------------------------
+
+ // The lane hit-tests taps arithmetically off the click coordinates, so these
+ // mirror DrumSheetView's internal geometry (CELL / PAD / GRID_TOP / ROW_H /
+ // BAR_GAP). jsdom reports a zeroed bounding box and the default font size maps
+ // to 1× scale, so a client point IS an internal SVG point here.
+ const CELL = 20;
+ const PAD = 6;
+ const GRID_TOP = 26;
+ const ROW_H = 20;
+ const BAR_GAP = 6;
+ const cellPoint = (row, step, { bar = 1, stepsPerBar = 4 } = {}) => ({
+ clientX: PAD + (bar - 1) * (stepsPerBar * CELL + BAR_GAP) + step * CELL + CELL / 2,
+ clientY: GRID_TOP + row * ROW_H + ROW_H / 2,
+ });
+ const lane = (container) => container.querySelector('[role="img"]');
+ const tap = (container, ...args) => fireEvent.click(lane(container), cellPoint(...args));
+ const readout = () => screen.queryByRole('status');
+
+ it('explains the tapped note — piece, articulation, technique and position', () => {
+ // The motivating question: what IS an X with a chevron over it on the crash?
+ const { container } = render(<DrumSheetView text={'subdivision: 1\n\nCR: -X--'} />);
+ expect(readout()).toBeNull();
+ tap(container, 0, 1);
+ expect(readout()).toHaveTextContent('Crash — Accent');
+ expect(readout()).toHaveTextContent(/harder/i);
+ expect(readout()).toHaveTextContent(/shoulder of the stick/i);
+ expect(readout()).toHaveTextContent('bar 1, count “2”');
+ expect(readout()).toHaveTextContent('100% volume');
+ });
+
+ it('reads the same `o` as OPEN on the hi-hat row and a normal hit on the kick row', () => {
+ const { container } = render(<DrumSheetView text={'subdivision: 1\n\nHH: o---\nK: o---'} />);
+ tap(container, 0, 0);
+ expect(readout()).toHaveTextContent('Hi-Hat — Open');
+ tap(container, 1, 0);
+ expect(readout()).toHaveTextContent('Kick — Normal hit');
+ });
+
+ it('names the position the way a drummer counts it', () => {
+ const { container } = render(<DrumSheetView text={'subdivision: 4\n\nS: ---x'} />);
+ tap(container, 0, 3, { stepsPerBar: 16 });
+ expect(readout()).toHaveTextContent('count “1 a”');
+ });
+
+ it('forgives a near-miss on a groove but dismisses a tap on empty grid', () => {
+ const { container } = render(<DrumSheetView text={'subdivision: 1\n\nS: -x--'} />);
+ // A cell is 20px wide — narrower than a fingertip — so the step either side
+ // of the hit still answers.
+ tap(container, 0, 0);
+ expect(readout()).toHaveTextContent('Snare — Normal hit');
+ // Two steps away there is nothing to explain, and tapping the background is
+ // how you dismiss.
+ tap(container, 0, 3);
+ expect(readout()).toBeNull();
+ });
+
+ it('ignores a tap in the gap between bars or above the first kit row', () => {
+ const { container } = render(<DrumSheetView text={'subdivision: 1\n\nS: xxxx\n\nS: xxxx'} />);
+ fireEvent.click(lane(container), { clientX: PAD + 4 * CELL + BAR_GAP / 2, clientY: GRID_TOP + ROW_H / 2 });
+ expect(readout()).toBeNull();
+ fireEvent.click(lane(container), { clientX: PAD + CELL / 2, clientY: GRID_TOP - 5 });
+ expect(readout()).toBeNull();
+ });
+
+ it('marks WHICH note the readout is describing, inside the lane', () => {
+ const { container } = render(<DrumSheetView text={'subdivision: 1\n\nHH: x-x-'} />);
+ expect(container.querySelector('[data-selected-cell]')).toBeNull();
+ tap(container, 0, 2);
+ const box = container.querySelector('[data-selected-cell]');
+ expect(Number(box.getAttribute('x'))).toBe(PAD + 2 * CELL);
+ expect(Number(box.getAttribute('y'))).toBe(GRID_TOP);
+ });
+
+ it('walks the hits with the arrow keys, skipping the rests between them', () => {
+ const { container } = render(<DrumSheetView text={'subdivision: 1\n\nHH: x-x-'} />);
+ fireEvent.keyDown(lane(container), { key: 'ArrowRight' });
+ expect(readout()).toHaveTextContent('count “1”');
+ fireEvent.keyDown(lane(container), { key: 'ArrowRight' });
+ expect(readout()).toHaveTextContent('count “3”');
+ // Already on the last hit — stays put rather than wrapping past the end.
+ fireEvent.keyDown(lane(container), { key: 'ArrowRight' });
+ expect(readout()).toHaveTextContent('count “3”');
+ fireEvent.keyDown(lane(container), { key: 'ArrowLeft' });
+ expect(readout()).toHaveTextContent('count “1”');
+ });
+
+ it('dismisses the readout with Escape or its close button', () => {
+ const { container } = render(<DrumSheetView text={'subdivision: 1\n\nHH: x---'} />);
+ tap(container, 0, 0);
+ fireEvent.keyDown(document, { key: 'Escape' });
+ expect(readout()).toBeNull();
+ tap(container, 0, 0);
+ fireEvent.click(screen.getByLabelText('Close note explanation'));
+ expect(readout()).toBeNull();
+ });
+
+ it('shows the whole vocabulary in a legend, kit pieces included', () => {
+ render(<DrumSheetView text={'subdivision: 1\n\nHH: x---\nK: o---'} />);
+ expect(screen.queryByText(/Ghost note/)).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Legend' }));
+ expect(screen.getByText(/Ghost note/)).toBeInTheDocument();
+ expect(screen.getByText(/bass drum/i)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Legend' }));
+ expect(screen.queryByText(/Ghost note/)).toBeNull();
+ });
+
+ it('leaves the tap gesture to an editing host when onStepClick is set', () => {
+ const onStepClick = vi.fn();
+ const { container } = render(<DrumSheetView text={'subdivision: 1\n\nHH: x---'} onStepClick={onStepClick} />);
+ expect(lane(container).getAttribute('tabindex')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Legend' })).toBeNull();
+ // The per-cell rects still route to the host, and no readout appears.
+ fireEvent.click(container.querySelectorAll('rect')[1]);
+ expect(onStepClick).toHaveBeenCalled();
+ expect(readout()).toBeNull();
+ });
+
// --- The playhead (rAF, DOM-only — never React state) ----------------------
const playhead = (container) => ({
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 1fce1090bf..a219a4e533 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`), `drumChartHasMusic(text)` and its already-parsed twin `chartHasMusic(chart)`. 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)`. Also the plain-language explainers the sheet's tap-a-note readout and Legend panel read — `describeDrumCell(pieceId, cell)` → `{ pieceLabel, char, articulation, detail, technique, velocityPercent, rest }` (piece-aware: `o` is "Open" on a hi-hat/cymbal but a normal hit on a drum; a null/unknown cell describes as a rest, an unknown piece returns null), `describeKitPiece(id)` (how that piece is struck) and `DRUM_GLYPH_LEGEND` (all six cell characters). 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 a913921da9..4914534847 100644
--- a/client/src/lib/drumNotation.js
+++ b/client/src/lib/drumNotation.js
@@ -90,6 +90,92 @@ const cellFor = (ch) => {
return CELL_GLYPHS[ch] || null;
};
+// --- Plain-language explanations --------------------------------------------
+// A hand-rolled grid notation has no engraving convention to look up, so the
+// sheet has to be able to answer "what IS this glyph and how do I play it?"
+// itself — that's what `<DrumSheetView>`'s tap-a-note popover and its legend
+// read. Kept here, beside the notation it describes, so the two can't drift.
+//
+// Handedness-neutral wording throughout: which foot works the kick and which
+// side the floor tom sits on depend on the kit and the player, so the text says
+// what to strike and how, never which hand or foot does it.
+
+// How each kit piece is struck.
+const PIECE_TECHNIQUE = {
+ CR: 'The crash cymbal — strike the edge with the shoulder of the stick and let it ring out.',
+ RD: 'The ride cymbal — stick tip on the bow for a clear "ping", nearer the edge for a wash, on the bell for a clang.',
+ HH: 'The hi-hat pair, played with a stick — tip on the edge, cymbals held shut by the pedal unless the note is open.',
+ T1: 'The highest tom — stick tip near the middle of the head.',
+ T2: 'The middle tom — stick tip near the middle of the head.',
+ S: 'The snare drum — a full stroke in the middle of the head for the sharpest crack.',
+ FT: 'The floor tom, the biggest and lowest of the toms — stick tip near the middle of the head.',
+ K: 'The bass drum, played with the kick pedal rather than a stick.',
+ HF: 'The hi-hat pedal with no stick — press it to clap the cymbals shut for a short "chick".',
+};
+
+// What each cell character asks for, independent of which piece it lands on.
+// `openCross` / `openHead` split the one glyph whose meaning depends on the
+// piece: an `o` opens a hi-hat or lets a cymbal ring, but a drum has nothing to
+// open, so there it just sounds as a normal hit (and the renderer draws it as
+// one) — saying "open" for a kick would describe a technique that doesn't exist.
+const ARTICULATIONS = {
+ rest: { name: 'Rest', detail: 'Nothing is played on this step — count it, don\'t fill it.' },
+ normal: { name: 'Normal hit', detail: 'An unaccented stroke at your regular playing volume.' },
+ accent: { name: 'Accent', detail: 'Strike noticeably harder than the notes around it. The ">" chevron drawn above the glyph is the accent mark.' },
+ open: { name: 'Open', detail: 'Let the cymbals ring instead of choking them: ease off the hi-hat pedal as you strike, and close again on the next unopened note. The circle drawn around the "×" is the open mark.' },
+ openHead: { name: 'Normal hit', detail: 'The "o" open mark only changes hi-hats and cymbals — on a drum there is nothing to open, so this sounds and draws as a normal hit.' },
+ ghost: { name: 'Ghost note', detail: 'A very light tap that sits under the groove rather than in it, drawn as a small hollow glyph.' },
+ flam: { name: 'Flam', detail: 'Two strokes so close together they read as one thick hit: the small grace glyph just before the beat lands a hair early, then the main note on the beat.' },
+};
+
+// Glyph id → the character an author types for it (the CELL_GLYPHS key).
+const CHAR_BY_GLYPH_ID = new Map(Object.entries(CELL_GLYPHS).map(([ch, g]) => [g.id, ch]));
+
+// The six cell characters for a legend panel — the same articulation text the
+// per-note popover shows, minus anything piece-specific.
+export const DRUM_GLYPH_LEGEND = Object.entries(CELL_GLYPHS).map(([char, glyph]) => ({
+ char,
+ id: glyph.id,
+ ...ARTICULATIONS[glyph.id],
+}));
+
+// How to play one piece, for a legend panel. Unknown ids return null so a caller
+// can fall back to the raw id rather than printing "undefined".
+export const describeKitPiece = (id) => {
+ const piece = kitPiece(id);
+ if (!piece) return null;
+ return { id: piece.id, label: piece.label, technique: PIECE_TECHNIQUE[piece.id] || '' };
+};
+
+/**
+ * Explain ONE cell of a parsed chart in plain language — what the glyph means,
+ * how the piece is struck, and how loud the hit is relative to a full stroke.
+ *
+ * @param {string} pieceId - Canonical kit-piece id (`'CR'`, `'S'`, …).
+ * @param {object} cell - A cell from `parseDrumChart` (a `CELL_GLYPHS` entry).
+ * @returns {{ pieceId, pieceLabel, char, rest, articulation, detail, technique, velocityPercent }|null}
+ * `null` only when the piece id is unknown — an unknown/missing cell is
+ * described as a rest, matching how the parser already treats one.
+ */
+export const describeDrumCell = (pieceId, cell) => {
+ const piece = kitPiece(pieceId);
+ if (!piece) return null;
+ const glyph = cell && CELL_GLYPHS[CHAR_BY_GLYPH_ID.get(cell.id)] ? cell : CELL_GLYPHS['-'];
+ // `open` is the one piece-dependent glyph (see ARTICULATIONS).
+ const key = glyph.id === 'open' && piece.glyph !== 'cross' ? 'openHead' : glyph.id;
+ const articulation = ARTICULATIONS[key] || ARTICULATIONS.normal;
+ return {
+ pieceId: piece.id,
+ pieceLabel: piece.label,
+ char: CHAR_BY_GLYPH_ID.get(glyph.id) || '-',
+ rest: !!glyph.rest,
+ articulation: articulation.name,
+ detail: articulation.detail,
+ technique: PIECE_TECHNIQUE[piece.id] || '',
+ velocityPercent: glyph.rest ? 0 : Math.round(glyph.velocity * 100),
+ };
+};
+
// --- Header ----------------------------------------------------------------
const DEFAULT_HEADER = { beats: 4, beatValue: 4, tempo: 90, subdivision: 4, kit: null };
diff --git a/client/src/lib/drumNotation.test.js b/client/src/lib/drumNotation.test.js
index f36ca4d229..17b88987ac 100644
--- a/client/src/lib/drumNotation.test.js
+++ b/client/src/lib/drumNotation.test.js
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest';
import {
parseDrumChart, isDrumNotation, drumChartHasMusic, kitPiece,
+ describeDrumCell, describeKitPiece, DRUM_GLYPH_LEGEND,
KIT_PIECES, CELL_GLYPHS, DEFAULT_DRUM_TEMPO, SUBDIVISION_MAX,
} from './drumNotation.js';
@@ -279,3 +280,79 @@ describe('drumChartHasMusic', () => {
expect(drumChartHasMusic('')).toBe(false);
});
});
+
+describe('describeDrumCell', () => {
+ const cellOf = (text, piece, step = 0) => {
+ const chart = parseDrumChart(text);
+ return chart.bars[0].rows.find((r) => r.piece === piece).cells[step];
+ };
+
+ it('names the piece, the articulation, and how to strike it', () => {
+ const info = describeDrumCell('CR', cellOf('subdivision: 1\n\nCR: X---', 'CR'));
+ expect(info.pieceLabel).toBe('Crash');
+ expect(info.char).toBe('X');
+ expect(info.articulation).toBe('Accent');
+ expect(info.detail).toMatch(/harder/i);
+ expect(info.technique).toMatch(/crash cymbal/i);
+ expect(info.rest).toBe(false);
+ // The accent's own mark is explained — the whole point of tapping an X with
+ // a chevron over it.
+ expect(info.detail).toContain('>');
+ });
+
+ it('reports the hit strength playback actually uses', () => {
+ expect(describeDrumCell('S', cellOf('subdivision: 1\n\nS: x---', 'S')).velocityPercent)
+ .toBe(Math.round(CELL_GLYPHS.x.velocity * 100));
+ expect(describeDrumCell('S', cellOf('subdivision: 1\n\nS: g---', 'S')).velocityPercent)
+ .toBe(Math.round(CELL_GLYPHS.g.velocity * 100));
+ expect(describeDrumCell('S', CELL_GLYPHS['-']).velocityPercent).toBe(0);
+ });
+
+ it('explains `o` as OPEN on a cymbal and as a normal hit on a drum', () => {
+ // The renderer only rings the × on cross-glyph pieces, so calling a kick's
+ // `o` "open" would describe a technique the sheet never drew.
+ const hat = describeDrumCell('HH', cellOf('subdivision: 1\n\nHH: o---', 'HH'));
+ expect(hat.articulation).toBe('Open');
+ expect(hat.detail).toMatch(/ring/i);
+
+ const kick = describeDrumCell('K', cellOf('subdivision: 1\n\nK: o---', 'K'));
+ expect(kick.articulation).toBe('Normal hit');
+ expect(kick.detail).toMatch(/only changes hi-hats and cymbals/i);
+ expect(kick.char).toBe('o');
+ });
+
+ it('describes ghosts, flams and rests', () => {
+ expect(describeDrumCell('S', cellOf('subdivision: 1\n\nS: g---', 'S')).articulation).toBe('Ghost note');
+ expect(describeDrumCell('S', cellOf('subdivision: 1\n\nS: f---', 'S')).articulation).toBe('Flam');
+ const rest = describeDrumCell('S', cellOf('subdivision: 1\n\nS: -x--', 'S'));
+ expect(rest.articulation).toBe('Rest');
+ expect(rest.rest).toBe(true);
+ });
+
+ it('falls back to a rest for a missing cell, and null for an unknown piece', () => {
+ // A stale selection into an edited chart hands us a null cell — describe it
+ // as a rest (what the parser would have made of it) rather than throwing.
+ expect(describeDrumCell('S', null).articulation).toBe('Rest');
+ expect(describeDrumCell('S', { id: 'not-a-glyph' }).articulation).toBe('Rest');
+ expect(describeDrumCell('CB', CELL_GLYPHS.x)).toBeNull();
+ });
+});
+
+describe('DRUM_GLYPH_LEGEND / describeKitPiece', () => {
+ it('covers every cell character exactly once, with text', () => {
+ expect(DRUM_GLYPH_LEGEND.map((g) => g.char).sort()).toEqual(Object.keys(CELL_GLYPHS).sort());
+ for (const glyph of DRUM_GLYPH_LEGEND) {
+ expect(glyph.name).toBeTruthy();
+ expect(glyph.detail).toBeTruthy();
+ }
+ });
+
+ it('has playing instructions for every kit piece', () => {
+ for (const piece of KIT_PIECES) {
+ const described = describeKitPiece(piece.id);
+ expect(described.label).toBe(piece.label);
+ expect(described.technique.length).toBeGreaterThan(10);
+ }
+ expect(describeKitPiece('CB')).toBeNull();
+ });
+});