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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
simplify the drum-note explainer: one row lookup, shared control styling, reused Escape hook
[._.]/ Adam Eivy17e3949db9e0
diff --git a/client/src/components/songbook/DrumSheetView.jsx b/client/src/components/songbook/DrumSheetView.jsxindex 0930bf3ab1..e6a87f48ad 100644--- a/client/src/components/songbook/DrumSheetView.jsx+++ b/client/src/components/songbook/DrumSheetView.jsx@@ -44,12 +44,17 @@* 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). It takes over the tap gesture, so- * an editing host gets cell rects instead of the explain readout+ * editor (#3115 out-of-scope); adds a rect per cell+ * explain — tap/arrow-key note explanation + Legend button (default on).+ * Independent of `onStepClick`: an editor host is where "what+ * does this glyph mean" matters most, so it can keep both and+ * have a tap toggle the cell AND explain it*/-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { parseDrumChart, kitPiece, describeDrumCell, describeKitPiece, DRUM_GLYPH_LEGEND } from '../../lib/drumNotation.js';+import { memo, useEffect, useId, useMemo, useRef, useState } from 'react';+import { parseDrumChart, kitPiece, describeDrumCell, describeDrumPosition, DRUM_GLYPH_LEGEND } from '../../lib/drumNotation.js';+import useEscapeKey from '../../hooks/useEscapeKey.js';+import { ctrlBtnClass, activeCtrlClass } from './constants.js';// --- Geometry (internal SVG units; the strip scales via width/height + viewBox)const CELL = 20; // one grid step — every other measure derives from this@@ -67,6 +72,12 @@ const GRID_TOP = PAD + HEADER_H;// 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;+// The lane geometry a tap has to be aimed at, exported so the tests target the+// real values instead of mirroring (and silently outliving) them: a stale copy+// of GRID_TOP in a test would keep agreeing with a stale inverse in+// `selectFromPoint` while every tap in the app reported the wrong note.+export const SHEET_GEOMETRY = { CELL, ROW_H, PAD, HEADER_H, GRID_TOP, BAR_GAP };+// 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;@@ -91,18 +102,6 @@ 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@@ -182,7 +181,7 @@ const LabelColumn = ({ pieces, height, scale }) => (// 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 }) => (+const HitReadout = ({ info, position, onClose }) => (<divrole="status"aria-live="polite"@@ -198,7 +197,7 @@ const HitReadout = ({ info, bar, count, onClose }) => (<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 “{count}”</span>+ <span className="text-gray-500">{position}</span>{!info.rest && <span className="text-gray-500">≈{info.velocityPercent}% volume</span>}</div><p className="mt-1 text-gray-300">{info.detail}</p>@@ -223,8 +222,8 @@ const HitReadout = ({ info, bar, count, onClose }) => (// 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">+const KitLegend = ({ id, pieces }) => (+ <div id={id} 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">@@ -238,7 +237,7 @@ const KitLegend = ({ pieces }) => ())}</dl><dl className="mt-2 space-y-1 border-t border-port-border pt-2">- {pieces.map((id) => describeKitPiece(id)).filter(Boolean).map((piece) => (+ {pieces.map(kitPiece).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>@@ -268,6 +267,7 @@ function DrumSheetView({getPlayhead,playing = false,onStepClick,+ explain = true,className = '',}) {const chart = useMemo(() => parseDrumChart(text), [text]);@@ -275,9 +275,13 @@ function DrumSheetView({const laneRef = useRef(null);const lineRef = useRef(null);const columnRef = useRef(null);+ // Set by the arrow walk so the reveal effect knows a selection came from the+ // keyboard and may be off screen (see that effect).+ const revealRef = useRef(false);// The note whose explanation is showing — `{ bar, step, piece }` or null.const [selection, setSelection] = useState(null);const [legendOpen, setLegendOpen] = useState(false);+ const legendId = useId();const scale = Math.min(SCALE_MAX, Math.max(SCALE_MIN, (fontSizeRem || BASE_FONT_REM) / BASE_FONT_REM));const { pieces, subdivision, stepsPerBar } = chart;@@ -298,46 +302,41 @@ 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 = [];+ // "Which cells does row `piece` of bar `bar` hold" — ONE lookup table for the+ // three consumers that ask (the glyph pass, the tap hit-test, and the arrow+ // walk), so "what counts as a struck cell" can't be answered two ways.+ const { cellsFor, hits } = useMemo(() => {+ const rows = new Map();+ const struck = [];for (const bar of chart.bars) {+ for (const row of bar.rows) rows.set(`${bar.index}:${row.piece}`, row.cells);+ // Resolved once per bar, not per cell. Reading order — time, then top of+ // the kit down — so ←/→ walk the groove the way it's played and reach+ // exactly the notes a tap can.+ const barRows = chart.pieces.map((piece) => rows.get(`${bar.index}:${piece}`));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 });- }+ barRows.forEach((cells, ri) => {+ if (cells && !cells[step].rest) struck.push({ bar: bar.index, step, piece: chart.pieces[ri] });+ });}}- return out;+ return { cellsFor: (bar, piece) => rows.get(`${bar}:${piece}`), hits: struck };}, [chart]);+ // --- Tap / arrow-key note explanation --------------------------------------+// 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();+ const selectFromPoint = (clientX, clientY) => {+ const box = laneRef.current.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 piece = pieces[Math.floor((uy - GRID_TOP) / ROW_H)];const span = barW + BAR_GAP;const rel = ux - PAD;const bar = Math.floor(rel / span) + 1;@@ -345,19 +344,22 @@ function DrumSheetView({// `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 cells = cellsFor(bar, piece);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;- });+ const found = [step, step - 1, step + 1]+ .find((s) => s >= 0 && s < stepsPerBar && cells && !cells[s].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;+ const onLaneKeyDown = (e) => {+ const delta = (e.key === 'ArrowRight' || e.key === 'ArrowDown') ? 1+ : (e.key === 'ArrowLeft' || e.key === 'ArrowUp') ? -1 : 0;+ if (!delta || !hits.length) return;+ e.preventDefault(); // arrows would otherwise scroll the lane out from under the walk+ revealRef.current = true;setSelection((prev) => {const i = prev? hits.findIndex((h) => h.bar === prev.bar && h.step === prev.step && h.piece === prev.piece)@@ -365,28 +367,19 @@ function DrumSheetView({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.+ useEscapeKey(!!selection, () => setSelection(null));++ // Bring an arrow-walked note into view. Gated on the keyboard flag, not just on+ // `selection`: reading `scrollLeft`/`clientWidth` right after React commits the+ // selection box forces a synchronous layout of the whole strip, and for a TAP+ // it can never help — the note the finger landed on is on screen by definition.+ // Skipped while playing too, where the rAF follow loop owns `scrollLeft`.useEffect(() => {const el = scrollRef.current;+ if (!revealRef.current) return;+ revealRef.current = false;if (!selection || !el || playing) return;const left = (barX(selection.bar) + selection.step * CELL) * scale;const right = left + CELL * scale;@@ -444,11 +437,12 @@ function DrumSheetView({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(() => {+ // The lane's grid + glyphs — ~2000 elements on a long chart, memoized on the+ // chart and its geometry ALONE. Selecting a note re-renders this component (the+ // readout is React state), and returning one stable <g> ELEMENT (not just a+ // stable array, which still costs a fiber visit per child) lets React bail out+ // at that single node. The selection box is drawn outside it.+ const lane = useMemo(() => {const out = [];let lastLabel = null;@@ -500,20 +494,18 @@ function DrumSheetView({}// 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 cells = cellsFor(bar.index, id);+ if (!cells) return;const cy = rowCenterY(ri);- row.cells.forEach((cell, s) => {+ 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.+ // 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) {@@ -525,8 +517,10 @@ function DrumSheetView({});}});- return out;- }, [chart, pieces, subdivision, stepsPerBar, gridBottom, barX, barW, onStepClick]);+ // Every other value this reads (pieces / subdivision / stepsPerBar /+ // gridBottom / barX / barW) derives from `chart`, so it is not a dep.+ return <g>{out}</g>;+ }, [chart, cellsFor, onStepClick]);if (!chart.bars.length) {return (@@ -539,8 +533,13 @@ function DrumSheetView({);}- const info = selection && describeDrumCell(selection.piece, cellAt(selection.bar, selection.piece, selection.step));+ // One guard for both selection-derived values: a row index of -1 means the+ // selection no longer belongs to this chart (the frame between a live edit and+ // the reset effect below), and there is nothing to box or to describe.const selectedRow = selection ? pieces.indexOf(selection.piece) : -1;+ const info = selectedRow < 0+ ? null+ : describeDrumCell(selection.piece, cellsFor(selection.bar, selection.piece)?.[selection.step]);return (<div className={className} style={{ fontSize: `${fontSizeRem}rem` }}>@@ -558,7 +557,8 @@ function DrumSheetView({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'}`}+ aria-controls={legendId}+ className={`ml-auto px-3 ${ctrlBtnClass} ${legendOpen ? activeCtrlClass : ''}`}>Legend</button>@@ -609,7 +609,7 @@ function DrumSheetView({<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}+ {lane}<line data-playhead="line" ref={lineRef} x1={0} y1={PAD} x2={0} y2={gridBottom}style={{ ...ACTIVE_STROKE, display: 'none' }} strokeWidth={1.6} /></svg>@@ -619,12 +619,11 @@ function DrumSheetView({{info && (<HitReadoutinfo={info}- bar={selection.bar}- count={countLabel(selection.step, subdivision)}+ position={describeDrumPosition(selection.bar, selection.step, subdivision)}onClose={() => setSelection(null)}/>)}- {legendOpen && <KitLegend pieces={pieces} />}+ {legendOpen && <KitLegend id={legendId} pieces={pieces} />}{chart.errors.length > 0 && <ErrorSummary errors={chart.errors} />}</div>diff --git a/client/src/components/songbook/DrumSheetView.test.jsx b/client/src/components/songbook/DrumSheetView.test.jsxindex 053958bf5c..6f25085185 100644--- a/client/src/components/songbook/DrumSheetView.test.jsx+++ b/client/src/components/songbook/DrumSheetView.test.jsx@@ -1,7 +1,7 @@import { describe, it, expect, vi, afterEach } from 'vitest';import { renderToStaticMarkup } from 'react-dom/server';import { render, cleanup, act, screen, fireEvent } from '@testing-library/react';-import DrumSheetView from './DrumSheetView.jsx';+import DrumSheetView, { SHEET_GEOMETRY } from './DrumSheetView.jsx';// Invented grooves only (privacy convention).const ROCK_BEAT = `time: 4/4@@ -142,15 +142,13 @@ describe('DrumSheetView', () => {// --- 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;+ // The lane hit-tests taps arithmetically off the click coordinates, so a test+ // has to aim at a cell in the sheet's own internal units — taken from the+ // component, never mirrored, or a geometry change would leave these agreeing+ // with a stale inverse while every real tap reported the wrong note. 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, PAD, GRID_TOP, ROW_H, BAR_GAP } = SHEET_GEOMETRY;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,@@ -247,17 +245,26 @@ describe('DrumSheetView', () => {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} />);+ it('drops the whole explain affordance when a host opts out', () => {+ const { container } = render(<DrumSheetView text={'subdivision: 1\n\nHH: x---'} explain={false} />);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();+ tap(container, 0, 0);expect(readout()).toBeNull();});+ it('keeps explaining notes for an editing host that also wires onStepClick', () => {+ // Authoring the notation is where "what does this glyph mean" matters most,+ // so a cell-edit handler must not silently cost the host its readout.+ const onStepClick = vi.fn();+ const { container } = render(<DrumSheetView text={'subdivision: 1\n\nHH: x---'} onStepClick={onStepClick} />);+ // A real tap lands on the host's cell rect and bubbles to the lane, so both+ // gestures resolve from the one click.+ fireEvent.click(container.querySelectorAll('rect')[1], cellPoint(0, 0));+ expect(onStepClick).toHaveBeenCalledWith(1, 0, 'HH');+ expect(readout()).toHaveTextContent('Hi-Hat — Normal hit');+ });+// --- The playhead (rAF, DOM-only — never React state) ----------------------const playhead = (container) => ({diff --git a/client/src/components/songbook/DrumTransportBar.jsx b/client/src/components/songbook/DrumTransportBar.jsxindex e0d1b54c38..48b355f2ff 100644--- a/client/src/components/songbook/DrumTransportBar.jsx+++ b/client/src/components/songbook/DrumTransportBar.jsx@@ -24,6 +24,7 @@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';+import { ctrlBtnClass, activeCtrlClass } from './constants.js';// Practice speeds as a percentage of the chart's written tempo.const PERCENTS = [50, 75, 90, 100, 110];@@ -32,10 +33,7 @@ const COUNT_IN_OPTIONS = [0, 1, 2];// 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,@@ -94,7 +92,7 @@ export default function DrumTransportBar({// 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 : ''}`}+ className={`${ctrlBtnClass} disabled:opacity-40 disabled:hover:bg-transparent ${playing ? activeCtrlClass : ''}`}aria-label={playing ? 'Stop play-along' : 'Play along'}title={hasMusic? (playing ? 'Stop (space)' : 'Play along (space)')@@ -109,7 +107,7 @@ export default function DrumTransportBar({type="button"onClick={() => onClickToggle(!clickEnabled)}aria-pressed={clickEnabled}- className={`${ctrlBtnClass} ${clickEnabled ? activeClass : ''}`}+ className={`${ctrlBtnClass} ${clickEnabled ? activeCtrlClass : ''}`}aria-label={clickEnabled ? 'Turn the metronome off' : 'Turn the metronome on'}title="Metronome click over the kit">@@ -177,7 +175,7 @@ export default function DrumTransportBar({onClick={() => setShowSetup((v) => !v)}aria-expanded={showSetup}aria-controls="drum-setup-controls"- className={`${ctrlBtnClass} sm:hidden ml-auto ${showSetup ? activeClass : ''}`}+ className={`${ctrlBtnClass} sm:hidden ml-auto ${showSetup ? activeCtrlClass : ''}`}aria-label={showSetup ? 'Hide practice settings' : 'Show practice settings'}title="Practice speed, count-in, loop">@@ -199,7 +197,7 @@ export default function DrumTransportBar({aria-pressed={activePercent === p}className={`px-2 min-h-[44px] rounded-lg border text-xs ${activePercent === p- ? activeClass+ ? activeCtrlClass: 'border-port-border text-gray-400 hover:text-white hover:bg-port-border/50'}`}title={`${p}% of the written ${writtenTempo} BPM`}@@ -228,7 +226,7 @@ export default function DrumTransportBar({type="button"onClick={() => onLoopToggle(!loopEnabled)}aria-pressed={loopEnabled}- className={`${ctrlBtnClass} ${loopEnabled ? activeClass : ''}`}+ className={`${ctrlBtnClass} ${loopEnabled ? activeCtrlClass : ''}`}aria-label={loopEnabled ? 'Disable loop' : 'Enable loop'}title="Loop a bar range ([ and ] set the ends)">diff --git a/client/src/components/songbook/constants.js b/client/src/components/songbook/constants.jsindex d4005eb354..18c399cabc 100644--- a/client/src/components/songbook/constants.js+++ b/client/src/components/songbook/constants.js@@ -64,3 +64,9 @@ export const inputClass = 'w-full bg-port-bg border border-port-border rounded-lexport const labelClass = 'block text-xs text-gray-400 mb-1';// Secondary button (bordered, subtle hover; disabled fades).export const btnClass = 'flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50';+// A sheet/transport control: 44px minimum touch target, matching the viewer's own+// controls bar. `activeCtrlClass` is the lit state for the toggles among them+// (play, metronome, loop, the sheet's Legend) — shared so a new control can't+// invent a fourth "this is on" look.+export 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';+export const activeCtrlClass = 'text-port-accent border-port-accent/50';diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex a219a4e533..afafb0c1ae 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)`. 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`). |+| `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), `describeDrumPosition(bar, step, subdivision)` → `bar 6, count “2 e”` (count-along syllables, exact `+n/N` fallback for an unconventional subdivision), `DRUM_GLYPH_LEGEND` (all six cell characters) and each `KIT_PIECES` row's `technique` (how that piece is struck). 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.jsindex 4914534847..a00f64e38d 100644--- a/client/src/lib/drumNotation.js+++ b/client/src/lib/drumNotation.js@@ -40,16 +40,21 @@// the General MIDI percussion note (documented reference for anyone wiring a// MIDI export later — the synth in drumPlayback.js reads `sound`, not `midi`).// `sound` picks the synth voice; `glyph` picks the notehead shape.+// `technique` is how the piece is struck, in the words a drummer would use at+// the kit — the sheet's tap-a-note readout and legend show it, because a+// hand-rolled notation has no engraving convention to look up. Handedness-+// neutral: which foot works the kick and which side the floor tom sits on depend+// on the kit and the player, so it says what to strike and how, never which limb.export const KIT_PIECES = [- { id: 'CR', label: 'Crash', aliases: ['crash', 'cr', 'cc'], midi: 49, sound: 'crash', glyph: 'cross' },- { id: 'RD', label: 'Ride', aliases: ['ride', 'rd'], midi: 51, sound: 'ride', glyph: 'cross' },- { id: 'HH', label: 'Hi-Hat', aliases: ['hihat', 'hi-hat', 'hh', 'hat'], midi: 42, sound: 'hihat', glyph: 'cross' },- { id: 'T1', label: 'Tom 1', aliases: ['tom1', 'tom', 't1', 'hitom'], midi: 48, sound: 'tom1', glyph: 'head' },- { id: 'T2', label: 'Tom 2', aliases: ['tom2', 't2', 'midtom'], midi: 47, sound: 'tom2', glyph: 'head' },- { id: 'S', label: 'Snare', aliases: ['snare', 's', 'sd'], midi: 38, sound: 'snare', glyph: 'head' },- { id: 'FT', label: 'Floor Tom', aliases: ['floor', 'floortom', 'ft', 't3'], midi: 43, sound: 'floor', glyph: 'head' },- { id: 'K', label: 'Kick', aliases: ['kick', 'k', 'bd', 'bass'], midi: 36, sound: 'kick', glyph: 'head' },- { id: 'HF', label: 'Hi-Hat (foot)', aliases: ['hihatfoot', 'hhfoot', 'hf', 'foot'], midi: 44, sound: 'hihatFoot', glyph: 'cross' },+ { id: 'CR', label: 'Crash', aliases: ['crash', 'cr', 'cc'], midi: 49, sound: 'crash', glyph: 'cross', technique: 'The crash cymbal — strike the edge with the shoulder of the stick and let it ring out.' },+ { id: 'RD', label: 'Ride', aliases: ['ride', 'rd'], midi: 51, sound: 'ride', glyph: 'cross', technique: 'The ride cymbal — stick tip on the bow for a clear "ping", nearer the edge for a wash, on the bell for a clang.' },+ { id: 'HH', label: 'Hi-Hat', aliases: ['hihat', 'hi-hat', 'hh', 'hat'], midi: 42, sound: 'hihat', glyph: 'cross', technique: 'The hi-hat pair, played with a stick — tip on the edge, cymbals held shut by the pedal unless the note is open.' },+ { id: 'T1', label: 'Tom 1', aliases: ['tom1', 'tom', 't1', 'hitom'], midi: 48, sound: 'tom1', glyph: 'head', technique: 'The highest tom — stick tip near the middle of the head.' },+ { id: 'T2', label: 'Tom 2', aliases: ['tom2', 't2', 'midtom'], midi: 47, sound: 'tom2', glyph: 'head', technique: 'The middle tom — stick tip near the middle of the head.' },+ { id: 'S', label: 'Snare', aliases: ['snare', 's', 'sd'], midi: 38, sound: 'snare', glyph: 'head', technique: 'The snare drum — a full stroke in the middle of the head for the sharpest crack.' },+ { id: 'FT', label: 'Floor Tom', aliases: ['floor', 'floortom', 'ft', 't3'], midi: 43, sound: 'floor', glyph: 'head', technique: 'The floor tom, the biggest and lowest of the toms — stick tip near the middle of the head.' },+ { id: 'K', label: 'Kick', aliases: ['kick', 'k', 'bd', 'bass'], midi: 36, sound: 'kick', glyph: 'head', technique: 'The bass drum, played with the kick pedal rather than a stick.' },+ { id: 'HF', label: 'Hi-Hat (foot)', aliases: ['hihatfoot', 'hhfoot', 'hf', 'foot'], midi: 44, sound: 'hihatFoot', glyph: 'cross', technique: 'The hi-hat pedal with no stick — press it to clap the cymbals shut for a short "chick".' },];// Row order index for a piece id — the renderer and the `kit:` override both@@ -71,14 +76,16 @@ export const kitPiece = (id) => KIT_PIECES.find((p) => p.id === id) || null;// --- Cell glyphs -----------------------------------------------------------// The six cell characters and what each means. `velocity` is the relative hit// strength drumPlayback scales its voice gain by; `open` lengthens the hi-hat-// decay; `flam` sounds a grace note just before the beat.+// decay; `flam` sounds a grace note just before the beat. `char` is the entry's+// own key, carried on the value so a cell (which is a shared reference to one of+// these) can name the character it came from without a reverse lookup.export const CELL_GLYPHS = {- '-': { id: 'rest', rest: true, velocity: 0, label: 'rest' },- x: { id: 'normal', rest: false, velocity: 0.8, label: 'normal' },- X: { id: 'accent', rest: false, velocity: 1, accent: true, label: 'accent' },- o: { id: 'open', rest: false, velocity: 0.85, open: true, label: 'open' },- g: { id: 'ghost', rest: false, velocity: 0.35, ghost: true, label: 'ghost' },- f: { id: 'flam', rest: false, velocity: 0.9, flam: true, label: 'flam' },+ '-': { id: 'rest', char: '-', rest: true, velocity: 0 },+ x: { id: 'normal', char: 'x', rest: false, velocity: 0.8 },+ X: { id: 'accent', char: 'X', rest: false, velocity: 1, accent: true },+ o: { id: 'open', char: 'o', rest: false, velocity: 0.85, open: true },+ g: { id: 'ghost', char: 'g', rest: false, velocity: 0.35, ghost: true },+ f: { id: 'flam', char: 'f', rest: false, velocity: 0.9, flam: true },};// A cell char → its descriptor, or null when it isn't a known glyph. `.` and@@ -93,31 +100,14 @@ const cellFor = (ch) => {// --- 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".',-};+// itself — that's what `<DrumSheetView>`'s tap-a-note readout and its legend+// read. Kept here, beside the notation it describes (and derived from the same+// two tables), so prose and notation can't drift apart.// 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.+// `openHead` is the one entry with no glyph of its own: it covers `open` landing+// on a DRUM, which has nothing to open, so it sounds (and draws) as a normal hit+// — calling a kick's `o` "open" 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.' },@@ -128,24 +118,11 @@ const ARTICULATIONS = {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] || '' };-};+// The six cell characters for a legend panel. Each shows the articulation as+// written for a cymbal (the `open` wording names the hi-hat pedal), which is the+// form the glyph is defined by; `describeDrumCell` is what re-reads it per piece.+export const DRUM_GLYPH_LEGEND = Object.values(CELL_GLYPHS)+ .map((glyph) => ({ char: glyph.char, ...ARTICULATIONS[glyph.id] }));/*** Explain ONE cell of a parsed chart in plain language — what the glyph means,@@ -153,29 +130,52 @@ export const describeKitPiece = (id) => {** @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}+ * @returns {{ 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['-'];+ const glyph = CELL_GLYPHS[cell?.char] || 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;+ const articulation = ARTICULATIONS[+ glyph.id === 'open' && piece.glyph !== 'cross' ? 'openHead' : glyph.id+ ];return {- pieceId: piece.id,pieceLabel: piece.label,- char: CHAR_BY_GLYPH_ID.get(glyph.id) || '-',- rest: !!glyph.rest,+ char: glyph.char,+ rest: glyph.rest,articulation: articulation.name,detail: articulation.detail,- technique: PIECE_TECHNIQUE[piece.id] || '',- velocityPercent: glyph.rest ? 0 : Math.round(glyph.velocity * 100),+ technique: piece.technique,+ velocityPercent: Math.round(glyph.velocity * 100),};};+// 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'] };++/**+ * Where a cell falls, as a drummer would say it: `bar 6, count “2 e”`.+ *+ * @param {number} bar - 1-based bar number (post repeat-expansion).+ * @param {number} step - 0-based grid step within the bar.+ * @param {number} subdivision - Grid steps per notated beat.+ * @returns {string}+ */+export const describeDrumPosition = (bar, step, subdivision) => {+ const beat = Math.floor(step / subdivision) + 1;+ const within = step % subdivision;+ const syllable = within ? SUBDIVISION_SYLLABLES[subdivision]?.[within] : '';+ const count = within+ ? `${beat} ${syllable || `+${within}/${subdivision}`}`+ : `${beat}`;+ return `bar ${bar}, count “${count}”`;+};+// --- 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.jsindex 17b88987ac..cc33d55761 100644--- a/client/src/lib/drumNotation.test.js+++ b/client/src/lib/drumNotation.test.js@@ -1,7 +1,7 @@import { describe, it, expect } from 'vitest';import {parseDrumChart, isDrumNotation, drumChartHasMusic, kitPiece,- describeDrumCell, describeKitPiece, DRUM_GLYPH_LEGEND,+ describeDrumCell, describeDrumPosition, DRUM_GLYPH_LEGEND,KIT_PIECES, CELL_GLYPHS, DEFAULT_DRUM_TEMPO, SUBDIVISION_MAX,} from './drumNotation.js';@@ -338,7 +338,7 @@ describe('describeDrumCell', () => {});});-describe('DRUM_GLYPH_LEGEND / describeKitPiece', () => {+describe('notation legend coverage', () => {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) {@@ -348,11 +348,26 @@ describe('DRUM_GLYPH_LEGEND / describeKitPiece', () => {});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();+ // The sheet's legend prints `technique` for whatever pieces a chart uses, so+ // a tenth piece added without one would render a blank row.+ for (const piece of KIT_PIECES) expect(piece.technique.length).toBeGreaterThan(10);+ });+});++describe('describeDrumPosition', () => {+ it('counts subdivisions the way a drummer says them', () => {+ expect(describeDrumPosition(6, 0, 4)).toBe('bar 6, count “1”');+ expect(describeDrumPosition(1, 5, 4)).toBe('bar 1, count “2 e”');+ expect(describeDrumPosition(1, 6, 4)).toBe('bar 1, count “2 &”');+ expect(describeDrumPosition(1, 7, 4)).toBe('bar 1, count “2 a”');+ expect(describeDrumPosition(2, 3, 2)).toBe('bar 2, count “2 &”');+ expect(describeDrumPosition(2, 4, 3)).toBe('bar 2, count “2 trip”');+ });++ it('falls back to an exact fraction where no syllable is conventional', () => {+ // Better an unfamiliar-but-correct "+2/5" than borrowing a syllable from a+ // different subdivision and misnaming the position.+ expect(describeDrumPosition(1, 2, 5)).toBe('bar 1, count “1 +2/5”');+ expect(describeDrumPosition(1, 5, 5)).toBe('bar 1, count “2”');});});