Skip to content

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

feat: embed a chord-sheet play-along in the SongBook tab sheet viewer (#4104)

[._.]/ Adam Eivye039d7d463e0
diff --git a/.changelog/next/added-issue-4104.md b/.changelog/next/added-issue-4104.md
new file mode 100644
index 0000000000..722e2df68c
--- /dev/null
+++ b/.changelog/next/added-issue-4104.md
@@ -0,0 +1 @@
+- SongBook: chord-sheet play-along — a strummed synth backing at a practice tempo, with a count-in, a metronome, and the sounding chord lit in the tab/chord sheet (viewer, editor preview, and importer preview)
diff --git a/client/src/components/songbook/ChordPreview.jsx b/client/src/components/songbook/ChordPreview.jsx
new file mode 100644
index 0000000000..4d64ade4d3
--- /dev/null
+++ b/client/src/components/songbook/ChordPreview.jsx
@@ -0,0 +1,85 @@
+import { useLayoutEffect, useState } from 'react';
+import useChordPlayer from '../../hooks/useChordPlayer.js';
+import useWakeLock from '../../hooks/useWakeLock.js';
+import ChordTransportBar from './ChordTransportBar.jsx';
+import TabSheetView from './TabSheetView.jsx';
+
+/**
+ * Audible chord-sheet preview — the transport bar plus the rendered sheet with
+ * the sounding chord lit. The chord-sheet counterpart of `<DrumPreview>`, shared
+ * by the SongBook editor's live preview and the importer's.
+ *
+ * Playback uses a snapshot captured when Play is pressed. The live source can
+ * therefore keep changing without tearing down the schedule mid-run, and the
+ * sheet stays on the sounding snapshot too so the highlight keeps pointing at
+ * the chord you're actually hearing.
+ */
+export default function ChordPreview({
+ text,
+ songId,
+ format = 'tab',
+ fontSizeRem,
+ instrumentView,
+ showChordStrip = false,
+ sheetClassName = '',
+}) {
+ const [snapshot, setSnapshot] = useState(text);
+ // `plain` is the sheet's explicit opt-out of ALL notation UI, chord tokens
+ // included — so it opts out of the play-along too rather than sounding chords
+ // the sheet is deliberately not highlighting.
+ const player = useChordPlayer(format === 'plain' ? '' : snapshot, { songId });
+ const chartChanged = text !== snapshot;
+ useWakeLock(player.playing);
+
+ // Keep the idle player current before the browser can paint another
+ // interaction target. Play can then start directly from its trusted click
+ // (required by Safari/iOS) while edits made during playback stay frozen.
+ useLayoutEffect(() => {
+ if (!player.playing && snapshot !== text) setSnapshot(text);
+ }, [player.playing, snapshot, text]);
+
+ const displayedText = player.playing ? snapshot : text;
+
+ return (
+ <div className="min-w-0">
+ {/* No bar at all for a sheet with nothing to play — a lyrics-only draft
+ shouldn't grow a dead transport above it. */}
+ {player.chordCount > 0 && (
+ <ChordTransportBar
+ playing={player.playing}
+ onToggle={player.toggle}
+ hasChords={player.hasChords}
+ bpm={player.bpm}
+ onBpmChange={player.setBpm}
+ onPercent={player.setBpmPercent}
+ writtenTempo={player.writtenTempo}
+ beatsPerBar={player.beatsPerBar}
+ onBeatsPerBarChange={player.setBeatsPerBar}
+ countInBars={player.countInBars}
+ onCountInChange={player.setCountInBars}
+ clickEnabled={player.clickEnabled}
+ onClickToggle={player.setClickEnabled}
+ chordCount={player.chordCount}
+ pulse={player.pulse}
+ />
+ )}
+ {/* Only ever true while playing — the layout effect above resyncs the
+ snapshot the moment the player goes idle. */}
+ {chartChanged && (
+ <p className="px-3 py-1.5 text-xs text-port-warning bg-port-warning/10" role="status">
+ Sheet changed — press Play to reload.
+ </p>
+ )}
+ <div className={sheetClassName}>
+ <TabSheetView
+ text={displayedText}
+ format={format}
+ fontSizeRem={fontSizeRem}
+ instrumentView={instrumentView}
+ showChordStrip={showChordStrip}
+ soundingChord={player.sounding}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/songbook/ChordTransportBar.jsx b/client/src/components/songbook/ChordTransportBar.jsx
new file mode 100644
index 0000000000..07c1fb71aa
--- /dev/null
+++ b/client/src/components/songbook/ChordTransportBar.jsx
@@ -0,0 +1,122 @@
+/**
+ * ChordTransportBar — the play-along controls for a SongBook chord/tab sheet
+ * (#4104), and the chord-sheet sibling of `DrumTransportBar`.
+ *
+ * Purely presentational over `useChordPlayer`: play/stop, a metronome toggle, a
+ * practice-tempo cluster, percent-of-reference quick buttons, a beats-per-chord
+ * select, a count-in select, and a live beat/chord readout. All state and audio
+ * live in the hook — this file only renders and calls back. The controls
+ * themselves come from `TransportControls.jsx`, shared with the drum bar.
+ *
+ * PHONE-FIRST LAYOUT, same split as the drum bar: a PRIMARY row that is always
+ * visible (the ones you touch mid-practice) and a SECONDARY row of setup
+ * controls that collapses behind a "More" disclosure under `sm`.
+ *
+ * BEATS PER CHORD is the control the drum bar has no equivalent of. A chord
+ * sheet carries no rhythm — the schedule reads one chord token as one bar — so
+ * this is where you tell it how long that bar is. It is a timing setting, so it
+ * sits with setup rather than beside Play.
+ */
+
+import { useState } from 'react';
+import { SlidersHorizontal, Volume2, VolumeX } from 'lucide-react';
+import { CHORD_BEATS_MIN, CHORD_BEATS_MAX } from '../../lib/chordPlayback.js';
+import { ctrlBtnClass, activeCtrlClass, smallSelectClass } from './constants.js';
+import {
+ BeatDots, CountInSelect, PercentButtons, PlayStopButton, TempoControls,
+} from './TransportControls.jsx';
+
+const BEATS_OPTIONS = Array.from(
+ { length: CHORD_BEATS_MAX - CHORD_BEATS_MIN + 1 },
+ (_, i) => CHORD_BEATS_MIN + i,
+);
+
+export default function ChordTransportBar({
+ playing, onToggle, hasChords = true,
+ bpm, onBpmChange, onPercent, writtenTempo,
+ beatsPerBar, onBeatsPerBarChange,
+ countInBars, onCountInChange,
+ clickEnabled, onClickToggle,
+ chordCount = 0, pulse = null,
+}) {
+ // Setup controls: collapsed by default on a phone, always shown from `sm` up.
+ const [showSetup, setShowSetup] = useState(false);
+
+ return (
+ <div className="shrink-0 border-b border-port-border bg-port-card/60 px-3 py-2 space-y-2">
+ {/* --- Primary: the controls you touch while playing -------------------- */}
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
+ {/* A sheet can hold chord-shaped tokens that none of them voice ("N.C."
+ alone), so the gate is "something will sound", not "there are
+ tokens". */}
+ <PlayStopButton
+ playing={playing}
+ onToggle={onToggle}
+ hasMusic={hasChords}
+ hint="(p)"
+ emptyHint="Nothing to play — this sheet has no playable chords"
+ />
+
+ <button
+ type="button"
+ onClick={() => onClickToggle(!clickEnabled)}
+ aria-pressed={clickEnabled}
+ className={`${ctrlBtnClass} ${clickEnabled ? activeCtrlClass : ''}`}
+ aria-label={clickEnabled ? 'Turn the metronome off' : 'Turn the metronome on'}
+ title={clickEnabled
+ ? 'Mute the metronome click — the count-in still sounds'
+ : 'Unmute the metronome click'}
+ >
+ {clickEnabled ? <Volume2 size={16} /> : <VolumeX size={16} />}
+ </button>
+
+ <TempoControls idPrefix="chord" bpm={bpm} onBpmChange={onBpmChange} />
+
+ {/* Where you are: the visual pulse plus the chord counter */}
+ <div className="flex items-center gap-2">
+ <BeatDots beatsPerBar={beatsPerBar} beat={pulse?.beat ?? null} countingIn={!!pulse?.countingIn} />
+ <span className="text-xs text-gray-400 tabular-nums whitespace-nowrap">
+ {pulse?.countingIn
+ ? 'count-in'
+ : `${(pulse?.index ?? 0) + 1}/${Math.max(1, chordCount)}`}
+ </span>
+ </div>
+
+ <button
+ type="button"
+ onClick={() => setShowSetup((v) => !v)}
+ aria-expanded={showSetup}
+ aria-controls="chord-setup-controls"
+ className={`${ctrlBtnClass} sm:hidden ml-auto ${showSetup ? activeCtrlClass : ''}`}
+ aria-label={showSetup ? 'Hide practice settings' : 'Show practice settings'}
+ title="Practice speed, beats per chord, count-in"
+ >
+ <SlidersHorizontal size={16} />
+ </button>
+ </div>
+
+ {/* --- Secondary: setup you touch between run-throughs ------------------ */}
+ <div
+ id="chord-setup-controls"
+ className={`${showSetup ? 'flex' : 'hidden'} sm:flex flex-wrap items-center gap-x-4 gap-y-2`}
+ >
+ <PercentButtons bpm={bpm} writtenTempo={writtenTempo} onPercent={onPercent} />
+
+ <div className="flex items-center gap-2">
+ <label htmlFor="chord-beats" className="text-xs text-gray-400">Beats per chord</label>
+ <select
+ id="chord-beats"
+ value={beatsPerBar}
+ onChange={(e) => onBeatsPerBarChange(e.target.value)}
+ className={smallSelectClass}
+ title="How long each chord is held — a chord sheet doesn't write it down"
+ >
+ {BEATS_OPTIONS.map((n) => <option key={n} value={n}>{n}</option>)}
+ </select>
+ </div>
+
+ <CountInSelect idPrefix="chord" countInBars={countInBars} onCountInChange={onCountInChange} />
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/songbook/ChordTransportBar.test.jsx b/client/src/components/songbook/ChordTransportBar.test.jsx
new file mode 100644
index 0000000000..c31b037638
--- /dev/null
+++ b/client/src/components/songbook/ChordTransportBar.test.jsx
@@ -0,0 +1,96 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import ChordTransportBar from './ChordTransportBar.jsx';
+
+const base = {
+ playing: false,
+ onToggle: () => {},
+ hasChords: true,
+ bpm: 90,
+ onBpmChange: () => {},
+ onPercent: () => {},
+ writtenTempo: 90,
+ beatsPerBar: 4,
+ onBeatsPerBarChange: () => {},
+ countInBars: 1,
+ onCountInChange: () => {},
+ clickEnabled: false,
+ onClickToggle: () => {},
+ chordCount: 4,
+ pulse: null,
+};
+
+const renderBar = (props = {}) => render(<ChordTransportBar {...base} {...props} />);
+
+describe('ChordTransportBar', () => {
+ it('renders the transport controls with their current values', () => {
+ renderBar();
+ expect(screen.getByLabelText('Play along')).toBeTruthy();
+ expect(screen.getByLabelText('Practice tempo (BPM)').value).toBe('90');
+ expect(screen.getByLabelText('Beats per chord').value).toBe('4');
+ expect(screen.getByLabelText('Count-in').value).toBe('1');
+ // The metronome is off by default, so the button offers to turn it ON.
+ expect(screen.getByLabelText('Turn the metronome on')).toBeTruthy();
+ });
+
+ it('disables Play when the sheet has nothing playable, and says why', () => {
+ renderBar({ hasChords: false });
+ const play = screen.getByLabelText('Play along');
+ expect(play.disabled).toBe(true);
+ expect(play.getAttribute('title')).toContain('Nothing to play');
+ });
+
+ it('steps the tempo by five and passes the raw input value through', () => {
+ const onBpmChange = vi.fn();
+ renderBar({ onBpmChange });
+ fireEvent.click(screen.getByLabelText('Faster by 5 BPM'));
+ expect(onBpmChange).toHaveBeenLastCalledWith(95);
+ fireEvent.click(screen.getByLabelText('Slower by 5 BPM'));
+ expect(onBpmChange).toHaveBeenLastCalledWith(85);
+ });
+
+ it('reports the beats-per-chord and count-in selections', () => {
+ const onBeatsPerBarChange = vi.fn();
+ const onCountInChange = vi.fn();
+ renderBar({ onBeatsPerBarChange, onCountInChange });
+ fireEvent.change(screen.getByLabelText('Beats per chord'), { target: { value: '3' } });
+ expect(onBeatsPerBarChange).toHaveBeenCalledWith('3');
+ fireEvent.change(screen.getByLabelText('Count-in'), { target: { value: '2' } });
+ expect(onCountInChange).toHaveBeenCalledWith('2');
+ });
+
+ it('toggles the metronome to the opposite of its current state', () => {
+ const onClickToggle = vi.fn();
+ const { rerender } = renderBar({ onClickToggle });
+ fireEvent.click(screen.getByLabelText('Turn the metronome on'));
+ expect(onClickToggle).toHaveBeenLastCalledWith(true);
+ rerender(<ChordTransportBar {...base} onClickToggle={onClickToggle} clickEnabled />);
+ fireEvent.click(screen.getByLabelText('Turn the metronome off'));
+ expect(onClickToggle).toHaveBeenLastCalledWith(false);
+ });
+
+ it.each([
+ ['stopped', { pulse: null }, 'Stopped', '1/4'],
+ ['counting in', { pulse: { index: null, beat: 2, countingIn: true } }, 'Counting in, beat 2', 'count-in'],
+ ['mid-sheet', { pulse: { index: 2, beat: 3, countingIn: false } }, 'Beat 3', '3/4'],
+ ])('reads out the pulse and position while %s', (_label, props, beatLabel, position) => {
+ renderBar(props);
+ expect(screen.getByLabelText(beatLabel)).toBeTruthy();
+ expect(screen.getByText(position)).toBeTruthy();
+ });
+
+ it('collapses the setup controls behind a disclosure on a phone', () => {
+ renderBar();
+ const toggle = screen.getByLabelText('Show practice settings');
+ const panel = document.getElementById(toggle.getAttribute('aria-controls'));
+ expect(toggle.getAttribute('aria-expanded')).toBe('false');
+ // Hidden under `sm`, always laid out from `sm` up — so the panel exists in
+ // the DOM either way and the phone state is a class, not a mount.
+ expect(panel.className).toContain('hidden');
+ expect(panel.className).toContain('sm:flex');
+
+ fireEvent.click(toggle);
+ expect(screen.getByLabelText('Hide practice settings').getAttribute('aria-expanded')).toBe('true');
+ expect(panel.className).toContain('flex');
+ });
+});
diff --git a/client/src/components/songbook/DrumTransportBar.jsx b/client/src/components/songbook/DrumTransportBar.jsx
index d207d20a59..ad7209a956 100644
--- a/client/src/components/songbook/DrumTransportBar.jsx
+++ b/client/src/components/songbook/DrumTransportBar.jsx
@@ -23,47 +23,13 @@
*/
import { useMemo, useState } from 'react';
-import {
- Play, Square, Repeat, Minus, Plus, SlidersHorizontal, Volume2, VolumeX,
-} from 'lucide-react';
-import { METRONOME_BPM_MIN, METRONOME_BPM_MAX } from '../../lib/metronome.js';
+import { Repeat, SlidersHorizontal, Volume2, VolumeX } from 'lucide-react';
import { DRUM_KIT_LIST, resolveDrumKit } from '../../lib/drumKits.js';
import { clampClickVolume, DEFAULT_CLICK_VOLUME } from '../../lib/drumPlayback.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];
-const COUNT_IN_OPTIONS = [0, 1, 2];
-// The tempo steppers move in fives — a phone user nudging 96→76 shouldn't need
-// twenty taps, and the ±1 fine trim is on the keyboard (+/-) and the input.
-const BPM_STEP = 5;
-
-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';
-
-// The pulse row: one dot per notated beat of the bar, the current one lit. This
-// is the metronome you can SEE — the audible click is easy to lose under a kit,
-// and on a phone the dots double as "yes, it's actually running".
-const BeatDots = ({ beatsPerBar, beat, countingIn }) => (
- <div
- className="flex items-center gap-1"
- role="status"
- aria-live="off"
- aria-label={countingIn ? `Counting in, beat ${beat || 1}` : (beat ? `Beat ${beat}` : 'Stopped')}
- >
- {Array.from({ length: beatsPerBar }, (_, i) => {
- const lit = beat === i + 1;
- return (
- <span
- key={i}
- aria-hidden="true"
- className={`rounded-full ${lit ? 'w-2.5 h-2.5' : 'w-1.5 h-1.5'} ${
- !lit ? 'bg-port-border' : (countingIn ? 'bg-port-warning' : 'bg-port-accent')
- }`}
- />
- );
- })}
- </div>
-);
+import { ctrlBtnClass, activeCtrlClass, smallSelectClass } from './constants.js';
+import {
+ BeatDots, CountInSelect, PercentButtons, PlayStopButton, TempoControls,
+} from './TransportControls.jsx';
export default function DrumTransportBar({
playing, onToggle, hasMusic = true,
@@ -88,28 +54,18 @@ export default function DrumTransportBar({
() => Array.from({ length: Math.max(1, barCount) }, (_, i) => i + 1),
[barCount],
);
- // Which percent button (if any) the current BPM corresponds to — so the active
- // practice speed is visible rather than inferred.
- const activePercent = PERCENTS.find((p) => Math.round((writtenTempo * p) / 100) === bpm);
-
return (
<div className="shrink-0 border-b border-port-border bg-port-card/60 px-3 py-2 space-y-2">
{/* --- Primary: the controls you touch while playing -------------------- */}
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
- <button
- type="button"
- onClick={onToggle}
- // An all-rest chart parses into bars but has nothing to sound — a Play
- // button that silently does nothing reads as broken.
- disabled={!hasMusic}
- className={`${ctrlBtnClass} disabled:opacity-40 disabled:hover:bg-transparent ${playing ? activeCtrlClass : ''}`}
- aria-label={playing ? 'Stop play-along' : 'Play along'}
- title={hasMusic
- ? (playing ? 'Stop (space)' : 'Play along (space)')
- : 'Nothing to play — this chart has no hits yet'}
- >
- {playing ? <Square size={16} /> : <Play size={18} />}
- </button>
+ {/* An all-rest chart parses into bars but has nothing to sound. */}
+ <PlayStopButton
+ playing={playing}
+ onToggle={onToggle}
+ hasMusic={hasMusic}
+ hint="(space)"
+ emptyHint="Nothing to play — this chart has no hits yet"
+ />
{/* Metronome — a primary control: it's the thing you toggle between
"play me the groove" and "just count me in", and the level you
@@ -148,53 +104,7 @@ export default function DrumTransportBar({
/>
</div>
- {/* Practice tempo — steppers everywhere, slider only where there's room.
- The visible "BPM" carries the unit: an unlabelled number between a
- minus and a plus, trailed by a slider, reads as a level. */}
- <div className="flex items-center gap-1" role="group" aria-label="Practice tempo">
- <button
- type="button"
- onClick={() => onBpmChange(bpm - BPM_STEP)}
- className={ctrlBtnClass}
- aria-label={`Slower by ${BPM_STEP} BPM`}
- title={`−${BPM_STEP} BPM (− fine-tunes by 1)`}
- >
- <Minus size={16} />
- </button>
- <label htmlFor="drum-bpm" className="sr-only">Practice tempo (BPM)</label>
- <input
- id="drum-bpm"
- type="number"
- inputMode="numeric"
- min={METRONOME_BPM_MIN}
- max={METRONOME_BPM_MAX}
- value={bpm}
- onChange={(e) => onBpmChange(e.target.value)}
- className="w-14 bg-port-bg border border-port-border rounded px-1 py-2 min-h-[44px] text-sm text-center text-white focus:border-port-accent focus:outline-none"
- title="Practice tempo (BPM)"
- />
- <button
- type="button"
- onClick={() => onBpmChange(bpm + BPM_STEP)}
- className={ctrlBtnClass}
- aria-label={`Faster by ${BPM_STEP} BPM`}
- title={`+${BPM_STEP} BPM (+ fine-tunes by 1)`}
- >
- <Plus size={16} />
- </button>
- <span aria-hidden="true" className="text-xs text-gray-500 ml-0.5">BPM</span>
- <label htmlFor="drum-bpm-slider" className="sr-only">Practice tempo slider</label>
- <input
- id="drum-bpm-slider"
- type="range"
- min={METRONOME_BPM_MIN}
- max={METRONOME_BPM_MAX}
- value={bpm}
- onChange={(e) => onBpmChange(e.target.value)}
- className="hidden md:block w-32 ml-1 accent-port-accent"
- title="Practice tempo (+/-)"
- />
- </div>
+ <TempoControls idPrefix="drum" bpm={bpm} onBpmChange={onBpmChange} />
{/* Where you are: the visual pulse plus the bar counter */}
<div className="flex items-center gap-2">
@@ -224,24 +134,7 @@ export default function DrumTransportBar({
id="drum-setup-controls"
className={`${showSetup ? 'flex' : 'hidden'} sm:flex flex-wrap items-center gap-x-4 gap-y-2`}
>
- <div className="flex items-center gap-1" role="group" aria-label="Percent of written tempo">
- {PERCENTS.map((p) => (
- <button
- key={p}
- type="button"
- onClick={() => onPercent(p)}
- aria-pressed={activePercent === p}
- className={`px-2 min-h-[44px] rounded-lg border text-xs ${
- activePercent === p
- ? activeCtrlClass
- : 'border-port-border text-gray-400 hover:text-white hover:bg-port-border/50'
- }`}
- title={`${p}% of the written ${writtenTempo} BPM`}
- >
- {p}%
- </button>
- ))}
- </div>
+ <PercentButtons bpm={bpm} writtenTempo={writtenTempo} onPercent={onPercent} />
{/* Which synthesized kit sounds the chart. A taste setting rather than a
practice one, so it sits with the setup controls — but it applies
@@ -261,19 +154,7 @@ export default function DrumTransportBar({
</select>
</div>
- <div className="flex items-center gap-2">
- <label htmlFor="drum-countin" className="text-xs text-gray-400">Count-in</label>
- <select
- id="drum-countin"
- value={countInBars}
- onChange={(e) => onCountInChange(e.target.value)}
- className={smallSelectClass}
- >
- {COUNT_IN_OPTIONS.map((n) => (
- <option key={n} value={n}>{n === 0 ? 'none' : `${n} bar${n === 1 ? '' : 's'}`}</option>
- ))}
- </select>
- </div>
+ <CountInSelect idPrefix="drum" countInBars={countInBars} onCountInChange={onCountInChange} />
<div className="flex items-center gap-2">
<button
diff --git a/client/src/components/songbook/TabSheetView.jsx b/client/src/components/songbook/TabSheetView.jsx
index bfd8a4118d..40638cf730 100644
--- a/client/src/components/songbook/TabSheetView.jsx
+++ b/client/src/components/songbook/TabSheetView.jsx
@@ -35,19 +35,31 @@ import { activeCtrlClass, ctrlBtnClass } from './constants.js';
* `showChordStrip` adds a collapsible "chords used" strip (unique chords in
* order of first appearance, each with a mini diagram) above the sheet — the
* viewer enables it; editor/import previews keep it off.
+ *
+ * Play-along support (issue #4104): `soundingChord` — `{ lineIndex, chordIndex }`
+ * or null — lights the chord token the synth preview is currently sounding, the
+ * chord-sheet equivalent of `<DrumSheetView>`'s playhead. The coordinates are
+ * the ones `sheetChordOccurrences` (lib/chordPlayback.js) hands out, i.e.
+ * positions in `parseTabSheet(text).lines`, so the schedule and the sheet agree
+ * on which token is which without either knowing how the other is built. Purely
+ * presentational: the audio, the transport and the clock all live in
+ * `useChordPlayer` / `<ChordTransportBar>`.
*/
const POPOVER_WIDTH = 172;
// Split a chords line into plain/chord segments using the parser's col offsets.
+// Chord segments carry their index within the line's `chords` array — the other
+// half of the `{ lineIndex, chordIndex }` coordinate the play-along highlight
+// addresses tokens by.
const chordLineSegments = (text, chords) => {
const segments = [];
let cursor = 0;
- for (const { name, col } of chords) {
+ chords.forEach(({ name, col }, chordIndex) => {
if (col > cursor) segments.push({ text: text.slice(cursor, col), chord: false });
- segments.push({ text: text.slice(col, col + name.length), chord: true });
+ segments.push({ text: text.slice(col, col + name.length), chord: true, chordIndex });
cursor = col + name.length;
- }
+ });
if (cursor < text.length) segments.push({ text: text.slice(cursor), chord: false });
return segments;
};
@@ -58,7 +70,7 @@ const chordLineSegments = (text, chords) => {
const chordRowSegments = (chords) => {
const segments = [];
let length = 0;
- for (const { name, col } of chords) {
+ chords.forEach(({ name, col }, chordIndex) => {
let pad = '';
if (length < col) pad = ' '.repeat(col - length);
else if (length > 0) pad = ' ';
@@ -66,9 +78,9 @@ const chordRowSegments = (chords) => {
segments.push({ text: pad, chord: false });
length += pad.length;
}
- segments.push({ text: name, chord: true });
+ segments.push({ text: name, chord: true, chordIndex });
length += name.length;
- }
+ });
return segments;
};
@@ -76,22 +88,28 @@ const chordRowSegments = (chords) => {
// line box (it paints outside instead), so the enlarged touch target doesn't
// disturb the monospace sheet layout; horizontal padding cancels via negative
// margins.
-const ChordToken = ({ name, tokenKey, expanded, onTap }) => (
+const ChordToken = ({ name, tokenKey, expanded, sounding, onTap }) => (
<button
type="button"
onClick={(e) => onTap(name, tokenKey, e.currentTarget)}
aria-expanded={expanded}
aria-haspopup="dialog"
+ // The sounding token is marked in the DOM as well as painted: the highlight
+ // is a background tint, which a test can't read and a high-contrast theme
+ // may flatten.
+ data-sounding={sounding ? '' : undefined}
// font-mono is explicit (not inherited): PortOS themes set --port-font-ui
// directly on every <button>, which would render chord names proportional
// and break the sheet's column alignment.
- className="inline align-baseline font-mono text-port-accent font-semibold rounded px-1 -mx-1 py-2 hover:bg-port-accent/10 focus-visible:outline focus-visible:outline-1 focus-visible:outline-port-accent"
+ className={`inline align-baseline font-mono text-port-accent font-semibold rounded px-1 -mx-1 py-2 focus-visible:outline focus-visible:outline-1 focus-visible:outline-port-accent ${
+ sounding ? 'bg-port-accent/25 ring-1 ring-port-accent' : 'hover:bg-port-accent/10'
+ }`}
>
{name}
</button>
);
-const ChordSegments = ({ segments, blockKey, activeKey, onTap }) =>
+const ChordSegments = ({ segments, blockKey, activeKey, soundingChordIndex, onTap }) =>
segments.map((seg, i) => {
if (!seg.chord) return <span key={i}>{seg.text}</span>;
const tokenKey = `${blockKey}:${i}`;
@@ -101,6 +119,10 @@ const ChordSegments = ({ segments, blockKey, activeKey, onTap }) =>
name={seg.text}
tokenKey={tokenKey}
expanded={activeKey === tokenKey}
+ // `soundingChordIndex` is null when nothing on THIS line is sounding,
+ // and a chord index is legitimately 0 — so compare explicitly rather
+ // than leaning on truthiness.
+ sounding={soundingChordIndex != null && soundingChordIndex === seg.chordIndex}
onTap={onTap}
/>
);
@@ -130,6 +152,7 @@ function TabSheetView({
className = '',
instrumentView = 'guitar',
showChordStrip = false,
+ soundingChord = null,
}) {
const plain = format === 'plain';
const { lines } = useMemo(
@@ -142,14 +165,16 @@ function TabSheetView({
);
// Group consecutive tabstaff lines into one horizontally-scrollable block so
- // the six strings of a staff scroll together.
+ // the six strings of a staff scroll together. Each block keeps the index its
+ // FIRST line had in `lines` — a non-staff block holds exactly one line, so
+ // that index is the `lineIndex` the play-along highlight addresses.
const blocks = useMemo(() => {
const out = [];
- for (const line of lines) {
+ lines.forEach((line, lineIndex) => {
const prev = out[out.length - 1];
if (line.type === 'tabstaff' && prev?.type === 'tabstaff') prev.lines.push(line);
- else out.push({ type: line.type, lines: [line] });
- }
+ else out.push({ type: line.type, lineIndex, lines: [line] });
+ });
return out;
}, [lines]);
const hasTabstaff = lines.some((line) => line.type === 'tabstaff');
@@ -319,6 +344,11 @@ function TabSheetView({
);
}
const line = block.lines[0];
+ // Null unless the sounding chord belongs to THIS line — so a chord index
+ // can never light the same-numbered token on a different line.
+ const soundingChordIndex = soundingChord?.lineIndex === block.lineIndex
+ ? soundingChord.chordIndex
+ : null;
switch (line.type) {
case 'section':
// {end_of_*} directives carry an empty label — render nothing visible.
@@ -336,6 +366,7 @@ function TabSheetView({
segments={chordLineSegments(line.text, line.chords)}
blockKey={bi}
activeKey={popover?.key ?? null}
+ soundingChordIndex={soundingChordIndex}
onTap={onChordTap}
/>
</div>
@@ -348,6 +379,7 @@ function TabSheetView({
segments={chordRowSegments(line.chords)}
blockKey={bi}
activeKey={popover?.key ?? null}
+ soundingChordIndex={soundingChordIndex}
onTap={onChordTap}
/>
</div>
@@ -390,6 +422,8 @@ function TabSheetView({
}
// Props are all primitives (`format`/`instrumentView`/`showChordStrip`
-// included), so memo makes re-renders of a host page (stage flips, autoscroll
-// ticks) skip the full sheet re-render.
+// included) apart from `soundingChord`, which the host memoizes and which only
+// changes when the sounding chord does (once a bar, not once a frame) — so memo
+// makes re-renders of a host page (stage flips, autoscroll ticks) skip the full
+// sheet re-render.
export default memo(TabSheetView);
diff --git a/client/src/components/songbook/TabSheetView.test.jsx b/client/src/components/songbook/TabSheetView.test.jsx
index 0906cb8c12..1094fbacd8 100644
--- a/client/src/components/songbook/TabSheetView.test.jsx
+++ b/client/src/components/songbook/TabSheetView.test.jsx
@@ -1,6 +1,8 @@
import { describe, it, expect } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import TabSheetView from './TabSheetView.jsx';
+import { parseTabSheet } from '../../lib/tabNotation.js';
+import { sheetChordOccurrences } from '../../lib/chordPlayback.js';
// Invented placeholder content only (privacy convention) — nonsense lyrics.
const SAMPLE = `[Verse 1]
@@ -207,3 +209,51 @@ describe('TabSheetView', () => {
});
});
});
+
+// --- Play-along highlight (#4104) -------------------------------------------
+// The coordinates come from `sheetChordOccurrences` (lib/chordPlayback.js), so
+// these use that function rather than hand-counted indices — a test that
+// mirrored the addressing would keep agreeing with a broken renderer.
+describe('TabSheetView — sounding-chord highlight', () => {
+ // Two chord lines: line 0 is "C G", line 2 is the ChordPro inline row.
+ const SHEET = 'C G\nNonsense lyric line\n[Am]Hello [F]world';
+ const occurrences = sheetChordOccurrences(parseTabSheet(SHEET).lines);
+ const lit = (container) => [...container.querySelectorAll('[data-sounding]')]
+ .map((el) => el.textContent.trim());
+
+ it('lights nothing when no chord is sounding', () => {
+ const { container } = render(<TabSheetView text={SHEET} />);
+ expect(lit(container)).toEqual([]);
+ });
+
+ it.each([0, 1, 2, 3])('lights exactly the token occurrence %i addresses', (i) => {
+ const { lineIndex, chordIndex, name } = occurrences[i];
+ const { container } = render(
+ <TabSheetView text={SHEET} soundingChord={{ lineIndex, chordIndex }} />,
+ );
+ expect(lit(container)).toEqual([name]);
+ });
+
+ it('never lights the same-numbered token on a different line', () => {
+ // Chord index 0 exists on both chord lines; only the addressed line lights.
+ const { container } = render(
+ <TabSheetView text={SHEET} soundingChord={{ lineIndex: 2, chordIndex: 0 }} />,
+ );
+ expect(lit(container)).toEqual(['Am']);
+ expect(lit(container)).not.toContain('C');
+ });
+
+ it('ignores a stale coordinate that no longer addresses a chord', () => {
+ const { container } = render(
+ <TabSheetView text={SHEET} soundingChord={{ lineIndex: 99, chordIndex: 0 }} />,
+ );
+ expect(lit(container)).toEqual([]);
+ });
+
+ it('lights nothing in plain format, which opts out of all notation UI', () => {
+ const { container } = render(
+ <TabSheetView text={SHEET} format="plain" soundingChord={{ lineIndex: 0, chordIndex: 0 }} />,
+ );
+ expect(lit(container)).toEqual([]);
+ });
+});
diff --git a/client/src/components/songbook/TransportControls.jsx b/client/src/components/songbook/TransportControls.jsx
new file mode 100644
index 0000000000..5c100afc24
--- /dev/null
+++ b/client/src/components/songbook/TransportControls.jsx
@@ -0,0 +1,166 @@
+/**
+ * Shared presentational pieces for the SongBook play-along transports — the
+ * drum-kit bar (`DrumTransportBar`) and the chord-sheet bar
+ * (`ChordTransportBar`) render the same play button, practice-tempo cluster,
+ * percent-of-written buttons, count-in select and beat pulse.
+ *
+ * Extracted rather than copied so the two bars can't drift on touch-target size,
+ * label wording or the ±5 stepper behaviour. Everything here is stateless: the
+ * hosting bar owns the values and the callbacks.
+ *
+ * Every control pairs `<label htmlFor>` with an `id` built off the host's
+ * `idPrefix`, so two bars can be mounted on one page without colliding.
+ */
+
+import { Play, Square, Minus, Plus } from 'lucide-react';
+import { METRONOME_BPM_MIN, METRONOME_BPM_MAX } from '../../lib/metronome.js';
+import { ctrlBtnClass, activeCtrlClass, smallSelectClass } from './constants.js';
+
+// The tempo steppers move in fives — a phone user nudging 96→76 shouldn't need
+// twenty taps, and the ±1 fine trim is on the keyboard and the number input.
+export const BPM_STEP = 5;
+
+// Practice speeds as a percentage of the reference tempo.
+export const PERCENTS = [50, 75, 90, 100, 110];
+
+export const COUNT_IN_OPTIONS = [0, 1, 2];
+
+/**
+ * Play/stop. `hasMusic` false disables it: a transport that silently does
+ * nothing reads as broken, so the reason lives in the title instead.
+ */
+export const PlayStopButton = ({ playing, onToggle, hasMusic = true, hint, emptyHint }) => (
+ <button
+ type="button"
+ onClick={onToggle}
+ disabled={!hasMusic}
+ className={`${ctrlBtnClass} disabled:opacity-40 disabled:hover:bg-transparent ${playing ? activeCtrlClass : ''}`}
+ aria-label={playing ? 'Stop play-along' : 'Play along'}
+ title={hasMusic ? (playing ? `Stop ${hint}` : `Play along ${hint}`) : emptyHint}
+ >
+ {playing ? <Square size={16} /> : <Play size={18} />}
+ </button>
+);
+
+/**
+ * Practice tempo — steppers everywhere, slider only where there's room. The
+ * visible "BPM" carries the unit: an unlabelled number between a minus and a
+ * plus, trailed by a slider, reads as a level.
+ */
+export const TempoControls = ({ idPrefix, bpm, onBpmChange }) => (
+ <div className="flex items-center gap-1" role="group" aria-label="Practice tempo">
+ <button
+ type="button"
+ onClick={() => onBpmChange(bpm - BPM_STEP)}
+ className={ctrlBtnClass}
+ aria-label={`Slower by ${BPM_STEP} BPM`}
+ title={`−${BPM_STEP} BPM (− fine-tunes by 1)`}
+ >
+ <Minus size={16} />
+ </button>
+ <label htmlFor={`${idPrefix}-bpm`} className="sr-only">Practice tempo (BPM)</label>
+ <input
+ id={`${idPrefix}-bpm`}
+ type="number"
+ inputMode="numeric"
+ min={METRONOME_BPM_MIN}
+ max={METRONOME_BPM_MAX}
+ value={bpm}
+ onChange={(e) => onBpmChange(e.target.value)}
+ className="w-14 bg-port-bg border border-port-border rounded px-1 py-2 min-h-[44px] text-sm text-center text-white focus:border-port-accent focus:outline-none"
+ title="Practice tempo (BPM)"
+ />
+ <button
+ type="button"
+ onClick={() => onBpmChange(bpm + BPM_STEP)}
+ className={ctrlBtnClass}
+ aria-label={`Faster by ${BPM_STEP} BPM`}
+ title={`+${BPM_STEP} BPM (+ fine-tunes by 1)`}
+ >
+ <Plus size={16} />
+ </button>
+ <span aria-hidden="true" className="text-xs text-gray-500 ml-0.5">BPM</span>
+ <label htmlFor={`${idPrefix}-bpm-slider`} className="sr-only">Practice tempo slider</label>
+ <input
+ id={`${idPrefix}-bpm-slider`}
+ type="range"
+ min={METRONOME_BPM_MIN}
+ max={METRONOME_BPM_MAX}
+ value={bpm}
+ onChange={(e) => onBpmChange(e.target.value)}
+ className="hidden md:block w-32 ml-1 accent-port-accent"
+ title="Practice tempo (+/-)"
+ />
+ </div>
+);
+
+/**
+ * Percent of the reference tempo. The active one is `aria-pressed` so the
+ * practice speed is visible rather than inferred.
+ */
+export const PercentButtons = ({ bpm, writtenTempo, onPercent }) => {
+ const active = PERCENTS.find((p) => Math.round((writtenTempo * p) / 100) === bpm);
+ return (
+ <div className="flex items-center gap-1" role="group" aria-label="Percent of written tempo">
+ {PERCENTS.map((p) => (
+ <button
+ key={p}
+ type="button"
+ onClick={() => onPercent(p)}
+ aria-pressed={active === p}
+ className={`px-2 min-h-[44px] rounded-lg border text-xs ${
+ active === p
+ ? activeCtrlClass
+ : 'border-port-border text-gray-400 hover:text-white hover:bg-port-border/50'
+ }`}
+ title={`${p}% of the written ${writtenTempo} BPM`}
+ >
+ {p}%
+ </button>
+ ))}
+ </div>
+ );
+};
+
+export const CountInSelect = ({ idPrefix, countInBars, onCountInChange }) => (
+ <div className="flex items-center gap-2">
+ <label htmlFor={`${idPrefix}-countin`} className="text-xs text-gray-400">Count-in</label>
+ <select
+ id={`${idPrefix}-countin`}
+ value={countInBars}
+ onChange={(e) => onCountInChange(e.target.value)}
+ className={smallSelectClass}
+ >
+ {COUNT_IN_OPTIONS.map((n) => (
+ <option key={n} value={n}>{n === 0 ? 'none' : `${n} bar${n === 1 ? '' : 's'}`}</option>
+ ))}
+ </select>
+ </div>
+);
+
+/**
+ * The pulse row: one dot per beat of the bar, the current one lit. This is the
+ * metronome you can SEE — the audible click is easy to lose under a backing,
+ * and on a phone the dots double as "yes, it's actually running".
+ */
+export const BeatDots = ({ beatsPerBar, beat, countingIn }) => (
+ <div
+ className="flex items-center gap-1"
+ role="status"
+ aria-live="off"
+ aria-label={countingIn ? `Counting in, beat ${beat || 1}` : (beat ? `Beat ${beat}` : 'Stopped')}
+ >
+ {Array.from({ length: beatsPerBar }, (_, i) => {
+ const lit = beat === i + 1;
+ return (
+ <span
+ key={i}
+ aria-hidden="true"
+ className={`rounded-full ${lit ? 'w-2.5 h-2.5' : 'w-1.5 h-1.5'} ${
+ !lit ? 'bg-port-border' : (countingIn ? 'bg-port-warning' : 'bg-port-accent')
+ }`}
+ />
+ );
+ })}
+ </div>
+);
diff --git a/client/src/components/songbook/constants.js b/client/src/components/songbook/constants.js
index d2aea45c36..3d085f9aef 100644
--- a/client/src/components/songbook/constants.js
+++ b/client/src/components/songbook/constants.js
@@ -150,3 +150,6 @@ export const btnClass = 'flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg
// 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';
+// A compact `<select>` inside a transport bar (count-in, loop range, kit) —
+// same 44px touch target as the buttons beside it.
+export 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';
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index b29b69340e..fd0a16113c 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -207,5 +207,6 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useCanvasDprSize` | DevicePixelRatio-aware canvas sizing shared by the piano-roll renderers (`<PianoRoll>`, `<MidiPianoRoll>`): sizes the bitmap to container-width × height at the DPR, applies the transform, and redraws via a `drawRef` on mount + every `ResizeObserver` resize (observer created once per height, never churned by draw-closure changes). Returns a ref holding the current CSS width so draw code doesn't measure the DOM per frame. | Both piano-roll canvases. |
| `useCanvasRollPalette` | Resolves the roll canvas palette (theme-following `--port-accent` + roll bg via `rollPalette`) into a ref, re-resolving on theme switch (`data-port-theme` MutationObserver) and repainting through a `drawRef`. Hands back a ref, not state, so a theme swap redraws the imperative canvas without a React re-render. | Both piano-roll canvases need theme-aware accent/bg colors that canvas `fillStyle` can't read from CSS vars. |
| `useMidiNotes` | Fetch + parse a transcribed `.mid` file into the piano-roll view-model (`parseMidiFile` in `lib/midiNotes.js`), with a module-level per-URL cache so remounts (collapse, tab switches) don't refetch/reparse. Returns `{ status: 'idle'\|'loading'\|'ready'\|'error', data, error, reload }`; a generation counter drops stale in-flight responses on URL change/unmount. Plain `fetch` of the static file URL — errors surface inline, never as toasts (#2477). | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |
+| `useChordPlayer` | Chord-sheet play-along transport for a SongBook `tab`/`chordpro` sheet (#4104) — the chord counterpart of `useDrumPlayer`: parses the (already-transposed) text, owns one `createChordPlayer`, the practice settings (tempo + beats-per-chord persisted per song, count-in, machine-global click) and the sounding-chord highlight read off the audio clock. Returns `{ chordCount, hasChords, writtenTempo, bpm, setBpm, setBpmPercent, beatsPerBar, setBeatsPerBar, countInBars, setCountInBars, clickEnabled, setClickEnabled, playing, pulse, sounding, getPlayhead, toggle, stop }`. Timing edits stop playback rather than re-time a running schedule. | `<ChordTransportBar>` + `<ChordPreview>` (SongBook viewer/editor/importer). |
| `useDrumPlayer` | Drum play-along transport for a SongBook `drum` chart (#3115): parses the chart (`lib/drumNotation.js`), owns one `createDrumPlayer` per chart plus the practice settings and the sheet playhead. Returns `{ chart, barCount, writtenTempo, bpm, setBpm, setBpmPercent, countInBars, setCountInBars, loopEnabled, setLoopEnabled, loopFrom, loopTo, setLoopRange, clickEnabled, setClickEnabled, clickVolume, setClickVolume, kitId, setKitId, playing, activeStep, currentBar, toggle, stop }`. The practice tempo persists per song in `safeStorage` (never into the record) while the selected kit (`songbook:drumKit`), the click toggle (`songbook:drumClick`) and the click level (`songbook:drumClickVolume`) persist per MACHINE; a timing-critical edit (tempo / count-in / loop) STOPS playback rather than re-timing already-scheduled audio, while the click toggle, the click level and the kit swap apply live (raising the level off silence also unmutes, so the slider is never a dead control); the player + its interval + scheduled hits tear down on stop, chart change and unmount. | The SongBook viewer and snapshot-based drum previews. Don't hand-wire `createDrumPlayer` + BPM persistence + playhead state again. |
| `useMidiPlayer` | React wrapper over `lib/midiPlayback.js` (#2490): one synth player per parsed MIDI view-model, torn down when the data changes/unmounts so oscillators never outlive the roll. Returns `{ playing, toggle, seek(sec), getPosition }` — `getPosition` is the stable ref the `<MidiPianoRoll>` rAF playhead reads; no AudioContext is touched until the first toggle. A resume failure resets `playing` instead of lying. | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 0bd337b8c2..221995eb4f 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -146,6 +146,7 @@ export * from './useAutoRefetch.js';
export * from './useCmdKSearch.js';
export * from './useCooldownTick.js';
export { default as useDrawerTab } from './useDrawerTab.js';
+export { default as useChordPlayer } from './useChordPlayer.js';
export { default as useDrumPlayer } from './useDrumPlayer.js';
export * from './useHfTokenStatus.js';
export * from './useKeyboardHelp.js';
diff --git a/client/src/hooks/useChordPlayer.js b/client/src/hooks/useChordPlayer.js
new file mode 100644
index 0000000000..5e088e1e15
--- /dev/null
+++ b/client/src/hooks/useChordPlayer.js
@@ -0,0 +1,237 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { parseTabSheet } from '../lib/tabNotation.js';
+import {
+ buildChordSchedule, createChordPlayer, resolveChordPlayhead, sheetChordOccurrences,
+ DEFAULT_CHORD_TEMPO, DEFAULT_CHORD_BEATS_PER_BAR, CHORD_BEATS_MIN, CHORD_BEATS_MAX,
+ CHORD_COUNT_IN_MAX,
+} from '../lib/chordPlayback.js';
+import { clampBpm } from '../lib/metronome.js';
+import { useLocalStorageBool } from './useLocalStorageBool.js';
+import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';
+
+/**
+ * Chord-sheet play-along transport for a SongBook `tab` / `chordpro` sheet
+ * (#4104) — the React wrapper over `lib/chordPlayback.js`, and the chord-sheet
+ * counterpart of `useDrumPlayer`. Owns the player lifecycle, the practice
+ * settings (tempo / beats-per-chord / count-in / click) and the sounding-chord
+ * highlight, so a host only renders controls.
+ *
+ * Practice tempo and beats-per-chord are PER-SONG, per-machine preferences (a
+ * chord sheet carries no tempo of its own, and how long a chord is held is a
+ * reading of the sheet rather than a property of it) — they persist to
+ * `safeStorage` under the song id, exactly like the viewer's transpose offset,
+ * and are never written into the record. The click is global to the machine: a
+ * reference pulse you balance against your own playing, not a song property.
+ *
+ * A timing-critical edit (tempo, beats-per-chord, count-in) while playing STOPS
+ * playback rather than re-timing a running schedule — already-scheduled audio
+ * can't be moved. The click toggle is the exception: it gates future scheduling
+ * only, so it applies live.
+ *
+ * THE HIGHLIGHT COMES FROM THE AUDIO CLOCK, not the player's `onChord` callback
+ * — an event callback stands still through the count-in and cannot say WHERE in
+ * a chord you are. One animation-frame loop polls the clock and commits to state
+ * only when the sounding chord (or the beat) actually turns over, so the page
+ * re-renders on chord changes rather than 60×/second.
+ *
+ * @param {string} text — the sheet source, already transposed by the caller.
+ * @param {{ songId?: string }} [options] — `songId` keys the persisted settings.
+ */
+export default function useChordPlayer(text, { songId } = {}) {
+ const { lines } = useMemo(() => parseTabSheet(text), [text]);
+ const occurrences = useMemo(() => sheetChordOccurrences(lines), [lines]);
+ const chordCount = occurrences.length;
+ // A sheet can hold chord tokens that none of them voice ("N.C." alone) — Play
+ // gates on something actually sounding, not on the token count.
+ const hasChords = useMemo(
+ () => buildChordSchedule(lines).events.some((ev) => !ev.rest),
+ [lines],
+ );
+
+ const bpmKey = songId ? `songbook:chordBpm:${songId}` : null;
+ const beatsKey = songId ? `songbook:chordBeats:${songId}` : null;
+
+ const [bpm, setBpmState] = useState(DEFAULT_CHORD_TEMPO);
+ const [beatsPerBar, setBeatsPerBarState] = useState(DEFAULT_CHORD_BEATS_PER_BAR);
+ const [countInBars, setCountInBarsState] = useState(1);
+ // Off by default: a strummed backing already lands on its own downbeats, so a
+ // click over it is the deliberate choice rather than the resting state. The
+ // hook's own default keeps "never chosen" distinct from "chosen off".
+ const [clickEnabled, setClickEnabled] = useLocalStorageBool('songbook:chordClick', false);
+ const [playing, setPlaying] = useState(false);
+ const [pulse, setPulse] = useState(null);
+
+ const playerRef = useRef(null);
+ // Intent mirror of `playing`: during a first play the player's own flag only
+ // flips after `await ctx.resume()`, so a rapid double-toggle read off the
+ // player would start playback twice instead of netting out to a cancel.
+ const playingRef = useRef(false);
+ const setPlayingBoth = useCallback((v) => {
+ playingRef.current = v;
+ setPlaying(v);
+ }, []);
+
+ // Seed the per-song settings. `null` from safeReadStorage is "never set" —
+ // distinct from a stored value — so a fresh song takes the defaults.
+ useEffect(() => {
+ setBpmState(clampBpm(bpmKey ? safeReadStorage(bpmKey) : null) ?? DEFAULT_CHORD_TEMPO);
+ }, [bpmKey]);
+ useEffect(() => {
+ const stored = Number(beatsKey ? safeReadStorage(beatsKey) : null);
+ setBeatsPerBarState(
+ Number.isFinite(stored) && stored >= CHORD_BEATS_MIN && stored <= CHORD_BEATS_MAX
+ ? Math.trunc(stored)
+ : DEFAULT_CHORD_BEATS_PER_BAR,
+ );
+ }, [beatsKey]);
+
+ // One player per sheet; torn down when the sheet changes or the host unmounts,
+ // so no interval or scheduled tone outlives the view. Settings arrive from the
+ // sync effect below, which runs right after this one.
+ useEffect(() => {
+ if (!chordCount) {
+ playerRef.current = null;
+ return undefined;
+ }
+ const player = createChordPlayer(lines, { onEnded: () => setPlayingBoth(false) });
+ playerRef.current = player;
+ return () => {
+ player.stop();
+ playerRef.current = null;
+ setPlayingBoth(false);
+ };
+ }, [lines, chordCount, setPlayingBoth]);
+
+ // Push the timing settings into whatever player is mounted. The player's own
+ // setters rebuild only while idle, and every timing setter below stops
+ // playback first — so this never re-times live audio.
+ useEffect(() => {
+ const player = playerRef.current;
+ if (!player) return;
+ player.setBpm(bpm);
+ player.setBeatsPerBar(beatsPerBar);
+ player.setCountIn(countInBars);
+ }, [lines, bpm, beatsPerBar, countInBars]);
+
+ // The click touches no timing, so it gets its own effect rather than joining
+ // the one above — folding it in would rebuild the schedule to deliver what is
+ // really a one-line assignment.
+ useEffect(() => {
+ playerRef.current?.setClick(clickEnabled);
+ }, [lines, clickEnabled]);
+
+ // Live read off the audio clock — the source both consumers below share.
+ const getPlayhead = useCallback(() => {
+ const player = playerRef.current;
+ if (!player || !playingRef.current) return null;
+ return resolveChordPlayhead(player.schedule(), player.position());
+ }, []);
+
+ // The sounding chord + beat readout, polled per frame and committed only when
+ // it changes (see the header note).
+ useEffect(() => {
+ if (!playing || typeof requestAnimationFrame !== 'function') {
+ setPulse(null);
+ return undefined;
+ }
+ let raf = requestAnimationFrame(function tick() {
+ raf = requestAnimationFrame(tick);
+ const head = getPlayhead();
+ const next = head && {
+ index: head.countIn ? null : head.index,
+ beat: head.beat,
+ countingIn: !!head.countIn,
+ };
+ setPulse((prev) => (
+ prev?.index === next?.index && prev?.beat === next?.beat && prev?.countingIn === next?.countingIn
+ ? prev
+ : next
+ ));
+ });
+ return () => cancelAnimationFrame(raf);
+ }, [playing, getPlayhead]);
+
+ // Which sheet token to light. `null` while counting in and while stopped — a
+ // stale highlight left on the last chord reads as "still playing".
+ const sounding = useMemo(() => {
+ if (!playing || pulse?.index == null) return null;
+ const occurrence = occurrences[pulse.index];
+ return occurrence ? { index: pulse.index, ...occurrence } : null;
+ }, [playing, pulse?.index, occurrences]);
+
+ const stop = useCallback(() => {
+ playerRef.current?.stop();
+ setPlayingBoth(false);
+ }, [setPlayingBoth]);
+
+ const toggle = useCallback(() => {
+ const player = playerRef.current;
+ if (!player) return;
+ if (playingRef.current) { stop(); return; }
+ // The same gate the Play button carries — a sheet with no voiceable chord
+ // has nothing to sound, and a key binding must not route around a disabled
+ // button.
+ if (!hasChords) return;
+ setPlayingBoth(true);
+ // play() resolves once playback has STARTED; an autoplay-policy failure
+ // lands here — reset the button rather than lying "playing".
+ Promise.resolve(player.play()).catch((err) => {
+ console.error(`🎸 Chord play-along failed to start: ${err.message}`);
+ setPlayingBoth(false);
+ });
+ }, [setPlayingBoth, stop, hasChords]);
+
+ // Timing-critical edits stop playback first (see the header note); the sync
+ // effect above then hands the new value to the now-idle player.
+ const stopIfPlaying = useCallback(() => {
+ if (playingRef.current) stop();
+ }, [stop]);
+
+ const setBpm = useCallback((next) => {
+ const clamped = clampBpm(next);
+ if (clamped == null) return;
+ stopIfPlaying();
+ setBpmState(clamped);
+ if (bpmKey) safeWriteStorage(bpmKey, String(clamped));
+ }, [stopIfPlaying, bpmKey]);
+
+ // Percent of the default reference tempo (the practice-slower control). A
+ // chord sheet has no written tempo, so DEFAULT_CHORD_TEMPO is the 100% mark.
+ const setBpmPercent = useCallback((percent) => {
+ setBpm(Math.round((DEFAULT_CHORD_TEMPO * percent) / 100));
+ }, [setBpm]);
+
+ const setBeatsPerBar = useCallback((next) => {
+ const n = Math.trunc(Number(next));
+ if (!Number.isFinite(n) || n < CHORD_BEATS_MIN || n > CHORD_BEATS_MAX) return;
+ stopIfPlaying();
+ setBeatsPerBarState(n);
+ if (beatsKey) safeWriteStorage(beatsKey, String(n));
+ }, [stopIfPlaying, beatsKey]);
+
+ const setCountInBars = useCallback((next) => {
+ stopIfPlaying();
+ setCountInBarsState(Math.max(0, Math.min(CHORD_COUNT_IN_MAX, Math.trunc(Number(next)) || 0)));
+ }, [stopIfPlaying]);
+
+ return {
+ chordCount,
+ hasChords,
+ writtenTempo: DEFAULT_CHORD_TEMPO,
+ bpm,
+ setBpm,
+ setBpmPercent,
+ beatsPerBar,
+ setBeatsPerBar,
+ countInBars,
+ setCountInBars,
+ clickEnabled,
+ setClickEnabled,
+ playing,
+ pulse,
+ sounding,
+ getPlayhead,
+ toggle,
+ stop,
+ };
+}
diff --git a/client/src/hooks/useChordPlayer.test.jsx b/client/src/hooks/useChordPlayer.test.jsx
new file mode 100644
index 0000000000..05dd5bb0fb
--- /dev/null
+++ b/client/src/hooks/useChordPlayer.test.jsx
@@ -0,0 +1,76 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+import useChordPlayer from './useChordPlayer.js';
+import { DEFAULT_CHORD_TEMPO, DEFAULT_CHORD_BEATS_PER_BAR } from '../lib/chordPlayback.js';
+
+// No AudioContext is created here: the hook only builds schedules until play()
+// is pressed, so this suite covers the settings/derivation half. The audible
+// half lives in lib/chordPlayer.test.js against the shared Web Audio fake.
+
+// Invented placeholder sheet (privacy convention).
+const SHEET = 'C G\nNonsense lyric line';
+
+describe('useChordPlayer', () => {
+ beforeEach(() => { window.localStorage.clear(); });
+
+ it('counts the sheet\'s chords and starts idle', () => {
+ const { result } = renderHook(() => useChordPlayer(SHEET));
+ expect(result.current.chordCount).toBe(2);
+ expect(result.current.hasChords).toBe(true);
+ expect(result.current.playing).toBe(false);
+ expect(result.current.sounding).toBeNull();
+ expect(result.current.bpm).toBe(DEFAULT_CHORD_TEMPO);
+ expect(result.current.beatsPerBar).toBe(DEFAULT_CHORD_BEATS_PER_BAR);
+ });
+
+ it('reports a sheet whose only chord tokens are unvoiceable as having nothing to play', () => {
+ // The tokens parse (so the transport bar appears) but none of them sound —
+ // "there are tokens" and "something will sound" must not collapse together.
+ const { result } = renderHook(() => useChordPlayer('N.C. N.C.'));
+ expect(result.current.chordCount).toBe(2);
+ expect(result.current.hasChords).toBe(false);
+ });
+
+ it('stands up no player for a sheet with no chords', () => {
+ const { result } = renderHook(() => useChordPlayer('just some words here'));
+ expect(result.current.chordCount).toBe(0);
+ expect(result.current.hasChords).toBe(false);
+ // The toggle is inert rather than throwing on a missing player.
+ act(() => { result.current.toggle(); });
+ expect(result.current.playing).toBe(false);
+ });
+
+ it('persists tempo and beats-per-chord per song, and reads them back', () => {
+ const { result, unmount } = renderHook(() => useChordPlayer(SHEET, { songId: 'song-1' }));
+ act(() => { result.current.setBpm(112); });
+ act(() => { result.current.setBeatsPerBar(3); });
+ expect(result.current.bpm).toBe(112);
+ expect(result.current.beatsPerBar).toBe(3);
+ unmount();
+
+ const reopened = renderHook(() => useChordPlayer(SHEET, { songId: 'song-1' }));
+ expect(reopened.result.current.bpm).toBe(112);
+ expect(reopened.result.current.beatsPerBar).toBe(3);
+
+ // …and a DIFFERENT song is untouched by it.
+ const other = renderHook(() => useChordPlayer(SHEET, { songId: 'song-2' }));
+ expect(other.result.current.bpm).toBe(DEFAULT_CHORD_TEMPO);
+ expect(other.result.current.beatsPerBar).toBe(DEFAULT_CHORD_BEATS_PER_BAR);
+ });
+
+ it('rejects out-of-range settings rather than storing them', () => {
+ const { result } = renderHook(() => useChordPlayer(SHEET, { songId: 'song-3' }));
+ act(() => { result.current.setBeatsPerBar(99); });
+ expect(result.current.beatsPerBar).toBe(DEFAULT_CHORD_BEATS_PER_BAR);
+ act(() => { result.current.setBpm('nonsense'); });
+ expect(result.current.bpm).toBe(DEFAULT_CHORD_TEMPO);
+ act(() => { result.current.setCountInBars(99); });
+ expect(result.current.countInBars).toBe(4);
+ });
+
+ it('sets the tempo from a percent of the reference tempo', () => {
+ const { result } = renderHook(() => useChordPlayer(SHEET));
+ act(() => { result.current.setBpmPercent(50); });
+ expect(result.current.bpm).toBe(Math.round(DEFAULT_CHORD_TEMPO / 2));
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 24fa277d26..bacceaa2c8 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -130,7 +130,8 @@ grep -i "what you want to do" client/src/lib/README.md
|---|---|
| `audioContext.js` | `getAudioContext()` + `resumeAudioContext(c)` + `acquireAudioSession(type)` + `getNoiseBuffer(c)` (the app-wide 1s white-noise buffer every noise voice loops over — chiptune drums, the drum kit's snare/hats/cymbals; don't grow a third copy) — the ONE app-wide lazy Web Audio `AudioContext` singleton every playback feature shares (`songPlayback`, `scorePlayback`, `metronome`, `midiPlayback`). Browsers cap live contexts and one context = one sample clock, so simultaneous features stay aligned. **Every playback entry point resumes via `resumeAudioContext(c)`, never by hand** (it takes any context, so per-mount ones use it too) — it gates on `state !== 'running'`, not `state === 'suspended'`, because iOS Safari also parks a context in the non-standard `'interrupted'` (a call/Siri/screen lock) which a suspended-only check walks past into silent "playback". **`acquireAudioSession(type)` ARBITRATES `navigator.audioSession.type`, which is document-wide, and returns an idempotent release** — `playback` keeps the hardware ring/silent switch from muting a pure-synth page but REFUSES capture, and the VoiceWidget is mounted on every page, so a last-writer-wins assignment trades one platform's silence for a dead mic. Each feature claims for exactly as long as it needs (`play-and-record` while a `getUserMedia` stream is open, `playback` while a player sounds) and the arbiter declares the union — capture always wins, since `play-and-record` also ignores the silent switch. Output-only players don't call it directly: pass `audioSession: 'playback'` to `createLookaheadTransport`, which claims on play and releases on teardown. Constructor resolved lazily (`window` → `globalThis`) so node-env test runs import cleanly; tests inject a fake via `vi.stubGlobal('AudioContext', …)` before first call. |
| `cityPlaybackFrame.js` | Map a recorded CyberCity snapshot frame onto the prop shape CityScene/CityHud consume for the timeline scrubber (`mergeFrameIntoCityProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. |
-| `chordShapes.js` | Chord-name → per-instrument voicing derivation for the SongBook viewer's instrument-view toggle (#2656). `getChordVoicing(name, instrument)` → guitar `{ frets: [6 × (-1/0/n)], baseFret, bass }`, ukulele (4-string GCEA, exact lowest-position search), or piano `{ notes: ['A','C','E'], bass }` with letter-accurate degree spelling (the 3rd of E is G#, never Ab); guitar shapes come from a curated first-position table + movable E-/A-form barre templates offset by `baseFret` (aug/dim7 exploit shape symmetry). Slash chords voice the base chord and carry `bass` separately. `parseChordName(name)`, `splitJoinedChords('Am-Am7')`, `toVoicingInstrument(songInstrument)`, `VOICING_INSTRUMENTS`. Reuses `tabNotation.js`'s `CHORD_TOKEN_RE`/`NOTE_TO_PC`/`spellPitchClass` (exported from there for this module) instead of duplicating the tables. Unknown/unparseable chords → null, never throws. |
+| `chordPlayback.js` | Chord-sheet play-along for the SongBook `tab`/`chordpro` formats (#4104) — the chord-sheet sibling of `drumPlayback.js` and the fourth consumer of `lookaheadTransport.js`. `sheetChordOccurrences(lines)` flattens `parseTabSheet(text).lines` into the ordered chord tokens, each addressed `{ lineIndex, chordIndex }` so `<TabSheetView>` can light exactly the token that is sounding; `chordMidiNotes(name)` voices one chord (bass note + chord tones, via `chordShapes.chordTones`); `buildChordSchedule(lines, { bpm, beatsPerBar, countInBars })` is the PURE chord→`[{ index, name, lineIndex, chordIndex, midis, startSec, durSec, rest }]` mapping (a chord sheet writes no rhythm, so ONE chord token = ONE bar, and a dash-joined "Am-Am7" splits its bar between its segments) plus the count-in clicks; `resolveChordPlayhead(schedule, posSec)` converts an audio-clock position to `{ countIn, index, beat }`; `createChordPlayer(lines, …)` strums it through `scorePlayback`'s `scheduleTone` with a live metronome toggle. |
+| `chordShapes.js` | Chord-name → per-instrument voicing derivation for the SongBook viewer's instrument-view toggle (#2656). `getChordVoicing(name, instrument)` → guitar `{ frets: [6 × (-1/0/n)], baseFret, bass }`, ukulele (4-string GCEA, exact lowest-position search), or piano `{ notes: ['A','C','E'], bass }` with letter-accurate degree spelling (the 3rd of E is G#, never Ab); guitar shapes come from a curated first-position table + movable E-/A-form barre templates offset by `baseFret` (aug/dim7 exploit shape symmetry). Slash chords voice the base chord and carry `bass` separately. `parseChordName(name)`, `splitJoinedChords('Am-Am7')`, `toVoicingInstrument(songInstrument)`, `VOICING_INSTRUMENTS`. `chordTones(name)` returns the instrument-free half — the parse plus `semitones` above the root — so `chordPlayback.js` sounds a sheet without re-typing the interval tables. Reuses `tabNotation.js`'s `CHORD_TOKEN_RE`/`NOTE_TO_PC`/`spellPitchClass` (exported from there for this module) instead of duplicating the tables. Unknown/unparseable chords → null, never throws. |
| `canvasRoll.js` | Shared canvas helpers for the two piano-roll renderers (`<PianoRoll>` falling-note + `<MidiPianoRoll>` DAW-style, #2477). `layerColor(index)` — the per-layer/track palette (8 hues, wraps both directions) used by note bars, keyboards, and legends; `roundRect(ctx, x, y, w, h, r)` — rounded-rect path with `ctx.roundRect` feature-detect and arcTo fallback; `rollPalette()` — resolves the theme-following `{ bg, accent, accentRgb }` from `--port-accent` via `getComputedStyle` (canvas can't read CSS vars); `ROLL_BG` — the shared near-black bg literal. Pure canvas math/palette, no React. |
| `chiptunePlayback.js` | Looping WebAudio preview for LLM-generated chiptune scores (#2911) — `buildChiptuneSchedule(score)` (pure pattern/order → absolute-time flatten, MIRRORS `server/lib/chiptuneScore.js` timing semantics), `parseChiptunePitch("C5")` → MIDI, and `createChiptunePlayer(getScore, { onLoop })` — a seamless-loop player over `createLookaheadTransport` (pulse-duty via PeriodicWave, triangle bass, noise-buffer/sine-sweep drums), exposing `position()` (monotonic across loop passes) + `loopSec()` for playhead UIs. No React — `ChiptunePanel` drives it. |
| `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune, perNote }` per-take summary (`perNote` is the ordered grade list a saved take persists, mirroring the server sanitizer); `gradesFromPerNote(timeline, perNote)` is its inverse — rebuilds the noteIndex→grade map to repaint a saved take's grading on open without re-grading audio; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. |
diff --git a/client/src/lib/chordPlayback.js b/client/src/lib/chordPlayback.js
new file mode 100644
index 0000000000..e69b9c7b3b
--- /dev/null
+++ b/client/src/lib/chordPlayback.js
@@ -0,0 +1,382 @@
+// Chord-sheet play-along for the SongBook `tab` / `chordpro` formats (#4104) —
+// the MIDI/score preview `<TabSheetView>` embeds, and the chord-sheet sibling of
+// `drumPlayback.js`. Turns the chord tokens a sheet already carries into a
+// strummed, tempo-adjustable backing you can practice against, with the sounding
+// chord lit in the sheet.
+//
+// Like every other synth player in this tree it is a thin scheduler over the
+// shared `lookaheadTransport.js` (clock, node lifecycle, teardown) and sounds
+// through `scheduleTone` from `scorePlayback.js`, so the preview has the same
+// voice as the lead-sheet and MIDI previews rather than a fourth synth.
+//
+// A CHORD SHEET CARRIES NO RHYTHM. Chords-over-lyrics notation says WHICH chords
+// and IN WHAT ORDER, never how long each is held — so the schedule reads one
+// chord token as one bar, the convention a player falls back on when reading a
+// sheet cold. A dash-joined quick change ("Am-Am7") splits its own bar between
+// its segments, which is exactly what that notation means. Tab staffs, lyrics
+// and prose contribute nothing.
+//
+// `buildChordSchedule` is PURE (no Web Audio) so the timing math is unit-testable
+// in a node env, mirroring `buildDrumSchedule` / `buildSchedule`.
+
+import { getAudioContext as ctx } from './audioContext.js';
+import { createLookaheadTransport, SYNTH_TIMING } from './lookaheadTransport.js';
+import { makeSafeCall, midiToFreq, scheduleTone } from './scorePlayback.js';
+import { chordTones, splitJoinedChords } from './chordShapes.js';
+
+const { SCHEDULE_AHEAD } = SYNTH_TIMING;
+const safeCall = makeSafeCall('chord playback');
+
+// Tempo a sheet with no `tempo:` marking plays at. A chord sheet has no tempo
+// field at all, so this is always the reference the percent buttons work off.
+export const DEFAULT_CHORD_TEMPO = 90;
+// One chord token = one bar of this many beats (see the header note).
+export const DEFAULT_CHORD_BEATS_PER_BAR = 4;
+export const CHORD_BEATS_MIN = 2;
+export const CHORD_BEATS_MAX = 12;
+export const CHORD_COUNT_IN_MAX = 4;
+
+// Where the voicing sits. The root lands in the octave starting at MIDI 48 (C3)
+// — comfortably under a sung melody — and the bass note an octave and a half
+// below that, so the chord reads as a chord rather than a cluster.
+const ROOT_BASE_MIDI = 48;
+const BASS_BASE_MIDI = 36;
+
+// A strum, not a block chord: each note of the voicing starts this much after
+// the one below it. Small enough to still hear as one chord.
+const STRUM_SEC = 0.022;
+// Per-note gain. Deliberately under `scorePlayback`'s single-voice default —
+// four or five tones stack here where the melody synth sounds one.
+const CHORD_TONE_PEAK = 0.085;
+const BASS_TONE_PEAK = 0.1;
+// Count-in / downbeat click: a short high blip, so it cuts through the chords.
+const CLICK_FREQ = 1320;
+const CLICK_ACCENT_FREQ = 1760;
+const CLICK_DUR_SEC = 0.045;
+const CLICK_PEAK = 0.14;
+
+const clampInt = (value, min, max, fallback) => {
+ const n = Math.trunc(Number(value));
+ return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : fallback;
+};
+
+// --- Schedule building (pure) ----------------------------------------------
+
+/**
+ * The ordered chord occurrences a parsed sheet holds — the play-along's source
+ * material AND the identity the sheet highlights against.
+ *
+ * `lineIndex` / `chordIndex` address the token in `parseTabSheet(text).lines`,
+ * so a renderer can light the exact token that is sounding without the schedule
+ * knowing anything about how the sheet is laid out. A dash-joined token yields
+ * one occurrence per segment, all pointing at that same token.
+ *
+ * @param {Array} lines — `parseTabSheet(text).lines`.
+ * @returns {Array<{ lineIndex, chordIndex, segment, segments, name }>}
+ */
+export const sheetChordOccurrences = (lines) => {
+ const out = [];
+ (Array.isArray(lines) ? lines : []).forEach((line, lineIndex) => {
+ (Array.isArray(line?.chords) ? line.chords : []).forEach((chord, chordIndex) => {
+ const parts = splitJoinedChords(chord?.name);
+ parts.forEach((name, segment) => {
+ out.push({ lineIndex, chordIndex, segment, segments: parts.length, name });
+ });
+ });
+ });
+ return out;
+};
+
+// A chord name → the MIDI notes that sound it, low to high. `null` (an
+// unvoiceable token — "N.C.", an exotic quality) is a REST, not silence-shaped
+// noise: the bar still passes, so the sheet keeps its place.
+export const chordMidiNotes = (name) => {
+ const tones = chordTones(name);
+ if (!tones) return null;
+ const rootMidi = ROOT_BASE_MIDI + tones.rootPc;
+ const bassPc = tones.bassPc ?? tones.rootPc;
+ return [BASS_BASE_MIDI + bassPc, ...tones.semitones.map((semis) => rootMidi + semis)];
+};
+
+/**
+ * Flatten a parsed sheet's chords into absolute-time strum events.
+ *
+ * @param {Array} lines — `parseTabSheet(text).lines`.
+ * @param {object} [options]
+ * @param {number} [options.bpm] — practice tempo (default 90).
+ * @param {number} [options.beatsPerBar] — beats one chord is held for (default 4).
+ * @param {number} [options.countInBars] — click-only lead-in bars (0–4).
+ * @returns {{ events, clicks, bpm, beatSec, barSec, beatsPerBar, countInSec, totalSec }}
+ */
+export const buildChordSchedule = (lines, options = {}) => {
+ const bpm = Number.isFinite(options.bpm) && options.bpm > 0 ? options.bpm : DEFAULT_CHORD_TEMPO;
+ const beatsPerBar = clampInt(options.beatsPerBar, CHORD_BEATS_MIN, CHORD_BEATS_MAX, DEFAULT_CHORD_BEATS_PER_BAR);
+ const countInBars = clampInt(options.countInBars, 0, CHORD_COUNT_IN_MAX, 0);
+ const beatSec = 60 / bpm;
+ const barSec = beatSec * beatsPerBar;
+ const countInSec = countInBars * barSec;
+
+ // The count-in is its own list rather than an entry in `events`: `events` is
+ // indexed 1:1 with the sheet's chord tokens (that index IS the highlight), and
+ // interleaving clicks would make the index mean two different things.
+ const clicks = [];
+ for (let bar = 0; bar < countInBars; bar += 1) {
+ for (let beat = 0; beat < beatsPerBar; beat += 1) {
+ clicks.push({
+ beat: beat + 1,
+ accent: beat === 0,
+ startSec: (bar * beatsPerBar + beat) * beatSec,
+ });
+ }
+ }
+
+ let cursor = countInSec;
+ const events = sheetChordOccurrences(lines).map((occurrence, index) => {
+ // A dash-joined token's segments share the token's one bar.
+ const durSec = barSec / occurrence.segments;
+ const startSec = cursor;
+ cursor += durSec;
+ const midis = chordMidiNotes(occurrence.name);
+ return { index, ...occurrence, midis: midis || [], rest: !midis, startSec, durSec };
+ });
+
+ return {
+ events,
+ clicks,
+ bpm,
+ beatSec,
+ barSec,
+ beatsPerBar,
+ countInSec,
+ totalSec: events.length ? cursor : 0,
+ };
+};
+
+/**
+ * A built schedule + a live clock position → what the UI should show (pure).
+ *
+ * Read off the audio clock rather than the player's `onChord` events, for the
+ * same reason `resolvePlayhead` exists on the drum side: an event callback
+ * stands still through the count-in and through a stretch with no voiceable
+ * chord, so anything that has to keep moving reads the clock instead.
+ *
+ * Returns `null` when there is nothing to place; otherwise
+ * `{ countIn: true, beat }` during the lead-in, else
+ * `{ countIn: false, index, beat }` — `index` into `schedule.events`.
+ */
+export const resolveChordPlayhead = (schedule, posSec) => {
+ const events = Array.isArray(schedule?.events) ? schedule.events : [];
+ const { beatSec, beatsPerBar, countInSec = 0, totalSec = 0 } = schedule || {};
+ if (!events.length || !(beatSec > 0)) return null;
+ const pos = Number.isFinite(posSec) ? posSec : 0;
+
+ if (pos < countInSec) {
+ // The transport's pre-roll lead is negative — clamp it to the first beat
+ // rather than counting backwards past the start of the count-in.
+ const elapsedBeats = Math.floor(Math.max(0, pos) / beatSec);
+ return { countIn: true, beat: (elapsedBeats % Math.max(1, beatsPerBar)) + 1 };
+ }
+
+ const elapsed = Math.min(Math.max(0, pos), Math.max(0, totalSec - 1e-6));
+ // Events are contiguous and in order, so the last one that has started is the
+ // sounding one. A linear scan is fine — a long sheet is a few hundred chords,
+ // and this runs once per animation frame.
+ let index = 0;
+ for (let i = 0; i < events.length; i += 1) {
+ if (events[i].startSec > elapsed) break;
+ index = i;
+ }
+ return {
+ countIn: false,
+ index,
+ beat: Math.floor((elapsed - countInSec) / beatSec) % Math.max(1, beatsPerBar) + 1,
+ };
+};
+
+// --- Player -----------------------------------------------------------------
+
+/**
+ * Build a chord-sheet play-along over parsed sheet lines.
+ *
+ * @param {Array} lines — `parseTabSheet(text).lines`.
+ * @param {object} [options]
+ * @param {number} [options.bpm] — practice tempo.
+ * @param {number} [options.beatsPerBar] — beats per chord.
+ * @param {number} [options.countInBars] — click-only lead-in bars.
+ * @param {boolean} [options.clickEnabled] — a downbeat click under every chord.
+ * @param {(index:number|null)=>void} [options.onChord] — the now-sounding chord
+ * index (null when playback ends/stops), for the sheet highlight.
+ * @param {()=>void} [options.onEnded] — fired once when the sheet finishes.
+ * @returns {{ play, pause, stop, isPlaying, position, setBpm, setBeatsPerBar,
+ * setCountIn, setClick, schedule }}
+ */
+export const createChordPlayer = (lines, options = {}) => {
+ const { onChord, onEnded } = options;
+ let bpm = Number.isFinite(options.bpm) && options.bpm > 0 ? options.bpm : null;
+ let beatsPerBar = options.beatsPerBar;
+ let countInBars = options.countInBars || 0;
+ // Gates FUTURE scheduling only, so — unlike the timing settings — it applies
+ // live without a rebuild.
+ let clickEnabled = !!options.clickEnabled;
+
+ const build = () => buildChordSchedule(lines, { bpm, beatsPerBar, countInBars });
+ let schedule = build();
+ let master = null;
+
+ // Separate cursors for the three walks: the tone scheduler and the click
+ // scheduler both run AHEAD of the audio clock (a lookahead window), while the
+ // highlight trails BEHIND it. One shared cursor would drag the trailing walk
+ // forward and light a chord before you hear it.
+ let toneIdx = 0;
+ let clickIdx = 0;
+ let headIdx = 0;
+ let lastNotified = -1;
+ const resetCursors = () => {
+ toneIdx = 0;
+ clickIdx = 0;
+ headIdx = 0;
+ lastNotified = -1;
+ };
+
+ // Every click for the current schedule: the count-in's own beats, then a
+ // metronome beat through the music. Derived rather than baked into the
+ // schedule so toggling the click mid-play needs no rebuild — the toggle gates
+ // whether the MUSIC clicks sound, and the count-in's always do.
+ const clickTimes = () => {
+ const out = schedule.clicks.map((click) => ({ ...click, countIn: true }));
+ const musicSec = Math.max(0, schedule.totalSec - schedule.countInSec);
+ const beats = Math.round(musicSec / schedule.beatSec);
+ for (let beat = 0; beat < beats; beat += 1) {
+ out.push({
+ beat: (beat % schedule.beatsPerBar) + 1,
+ accent: beat % schedule.beatsPerBar === 0,
+ countIn: false,
+ startSec: schedule.countInSec + beat * schedule.beatSec,
+ });
+ }
+ return out;
+ };
+ let clicks = clickTimes();
+
+ const soundChord = (c, ev, at, track) => {
+ ev.midis.forEach((midi, i) => {
+ const freq = midiToFreq(midi);
+ if (!freq) return;
+ // The bass note (index 0) is not part of the strum sweep and carries a
+ // little more level — it is the chord's foundation, not its top voice.
+ const offset = i === 0 ? 0 : STRUM_SEC * (i - 1);
+ const durSec = Math.max(0.05, ev.durSec - offset);
+ track(scheduleTone(c, freq, at + offset, durSec, master, i === 0 ? BASS_TONE_PEAK : CHORD_TONE_PEAK));
+ });
+ };
+
+ const scheduleWindow = (now, startTime, track) => {
+ if (!master) return;
+ const c = ctx();
+ const horizon = now + SCHEDULE_AHEAD;
+
+ while (toneIdx < schedule.events.length) {
+ const ev = schedule.events[toneIdx];
+ const at = startTime + ev.startSec;
+ if (at >= horizon) break;
+ toneIdx += 1;
+ if (at < now - 0.05) continue; // already past (first tick after a stall)
+ if (!ev.rest) soundChord(c, ev, Math.max(at, now), track);
+ }
+
+ while (clickIdx < clicks.length) {
+ const click = clicks[clickIdx];
+ const at = startTime + click.startSec;
+ if (at >= horizon) break;
+ // The cursor advances even when the click is muted — skipping the walk
+ // wholesale would leave it behind and dump a backlog the moment the
+ // toggle came back on.
+ clickIdx += 1;
+ if (at < now - 0.05) continue;
+ // Count-in clicks are NOT gated on `clickEnabled` — "click off, count me
+ // in" is the mode that combination means, the same call drumPlayback makes.
+ if (!click.countIn && !clickEnabled) continue;
+ track(scheduleTone(
+ c, click.accent ? CLICK_ACCENT_FREQ : CLICK_FREQ,
+ Math.max(at, now), CLICK_DUR_SEC, master, CLICK_PEAK,
+ ));
+ }
+
+ if (!onChord) return;
+ let newest = -1;
+ while (headIdx < schedule.events.length
+ && startTime + schedule.events[headIdx].startSec <= now) {
+ newest = schedule.events[headIdx].index;
+ headIdx += 1;
+ }
+ if (newest >= 0 && newest !== lastNotified) {
+ lastNotified = newest;
+ safeCall(onChord, newest);
+ }
+ };
+
+ const transport = createLookaheadTransport({
+ // Output-only, so it holds the iOS `playback` session while it sounds —
+ // without it the hardware ring/silent switch mutes a pure-synth page.
+ audioSession: 'playback',
+ getTotalSec: () => schedule.totalSec,
+ scheduleWindow,
+ prepare: () => {
+ schedule = build();
+ if (!schedule.events.length || schedule.totalSec <= 0) { safeCall(onEnded); return false; }
+ clicks = clickTimes();
+ resetCursors();
+ const c = ctx();
+ master = c.createGain();
+ master.gain.value = 1;
+ master.connect(c.destination);
+ return true;
+ },
+ seekCursors: (offsetSec) => {
+ resetCursors();
+ if (offsetSec <= 0) return;
+ // Resume (pause → play) positions every cursor past what already sounded.
+ // The tone cursor keeps the chord still ringing at the offset so a resume
+ // mid-chord re-sounds it rather than dropping into silence.
+ while (toneIdx < schedule.events.length
+ && schedule.events[toneIdx].startSec + schedule.events[toneIdx].durSec <= offsetSec) toneIdx += 1;
+ headIdx = toneIdx;
+ while (clickIdx < clicks.length && clicks[clickIdx].startSec < offsetSec) clickIdx += 1;
+ },
+ onStop: () => { safeCall(onChord, null); },
+ onEnded: () => { safeCall(onEnded); },
+ onTeardown: () => {
+ // Outside the request lifecycle — a disconnect on an already-torn-down
+ // node must not throw into the transport's teardown path.
+ if (master) {
+ try { master.disconnect(); } catch { /* already gone */ }
+ }
+ master = null;
+ },
+ });
+
+ // A timing change rebuilds the schedule while idle; while playing the caller
+ // restarts, since already-scheduled audio can't be re-timed.
+ const rebuildIfIdle = () => {
+ if (transport.isPlaying()) return;
+ schedule = build();
+ clicks = clickTimes();
+ resetCursors();
+ };
+
+ return {
+ play: transport.play,
+ pause: transport.pause,
+ stop: transport.stop,
+ isPlaying: transport.isPlaying,
+ position: transport.position,
+ setBpm: (next) => {
+ bpm = Number.isFinite(next) && next > 0 ? next : null;
+ rebuildIfIdle();
+ },
+ setBeatsPerBar: (next) => { beatsPerBar = next; rebuildIfIdle(); },
+ setCountIn: (bars) => { countInBars = clampInt(bars, 0, CHORD_COUNT_IN_MAX, 0); rebuildIfIdle(); },
+ setClick: (enabled) => { clickEnabled = !!enabled; },
+ schedule: () => schedule,
+ };
+};
diff --git a/client/src/lib/chordPlayback.test.js b/client/src/lib/chordPlayback.test.js
new file mode 100644
index 0000000000..a1bf2e5261
--- /dev/null
+++ b/client/src/lib/chordPlayback.test.js
@@ -0,0 +1,166 @@
+import { describe, it, expect } from 'vitest';
+import { parseTabSheet } from './tabNotation.js';
+import {
+ buildChordSchedule, chordMidiNotes, resolveChordPlayhead, sheetChordOccurrences,
+ DEFAULT_CHORD_TEMPO, DEFAULT_CHORD_BEATS_PER_BAR,
+} from './chordPlayback.js';
+
+// Invented placeholder sheets only (privacy convention). Every assertion here is
+// pure math over the parsed sheet — no AudioContext is created in this suite.
+
+const lines = (text) => parseTabSheet(text).lines;
+
+// Two chord lines, four tokens.
+const SHEET = `[Verse 1]
+C G
+Nonsense lyric line
+
+Am F`;
+
+const near = (a, b) => expect(a).toBeCloseTo(b, 6);
+
+describe('sheetChordOccurrences', () => {
+ it('flattens chord tokens in reading order with their line/chord coordinates', () => {
+ const found = sheetChordOccurrences(lines(SHEET));
+ expect(found.map((o) => o.name)).toEqual(['C', 'G', 'Am', 'F']);
+ // Line 1 is the "C G" line; the blank + lyric lines carry no chords, so the
+ // second chord line is line 4 of the source.
+ expect(found.map((o) => o.lineIndex)).toEqual([1, 1, 4, 4]);
+ expect(found.map((o) => o.chordIndex)).toEqual([0, 1, 0, 1]);
+ });
+
+ it('splits a dash-joined quick change into segments that share one token', () => {
+ const found = sheetChordOccurrences(lines('Am-Am7 F'));
+ expect(found.map((o) => o.name)).toEqual(['Am', 'Am7', 'F']);
+ // Both halves address the SAME token, so the sheet lights it for both.
+ expect(found.slice(0, 2).map((o) => o.chordIndex)).toEqual([0, 0]);
+ expect(found.slice(0, 2).map((o) => o.segments)).toEqual([2, 2]);
+ expect(found[2].chordIndex).toBe(1);
+ });
+
+ it('reads ChordPro inline chords as well as chord lines', () => {
+ expect(sheetChordOccurrences(lines('[C]Hello [G]world')).map((o) => o.name))
+ .toEqual(['C', 'G']);
+ });
+
+ it('ignores tab staffs, lyrics and prose', () => {
+ expect(sheetChordOccurrences(lines('e|--3--2--|\njust some words here'))).toEqual([]);
+ });
+
+ it('never throws on a missing or malformed line list', () => {
+ expect(sheetChordOccurrences(null)).toEqual([]);
+ expect(sheetChordOccurrences([{ type: 'text', text: 'x' }])).toEqual([]);
+ });
+});
+
+describe('chordMidiNotes', () => {
+ it('voices a triad as a bass note under the chord tones', () => {
+ // C major: bass C2 (36) then C3 (48) E3 (52) G3 (55).
+ expect(chordMidiNotes('C')).toEqual([36, 48, 52, 55]);
+ });
+
+ it('honours a slash bass without changing the chord above it', () => {
+ const plain = chordMidiNotes('C');
+ const slashed = chordMidiNotes('C/G');
+ expect(slashed.slice(1)).toEqual(plain.slice(1));
+ expect(slashed[0]).toBe(36 + 7); // G2
+ });
+
+ it('keeps an extension above the octave rather than folding it into a cluster', () => {
+ // add9 is 14 semitones up, not 2.
+ expect(chordMidiNotes('Cadd9')).toContain(48 + 14);
+ });
+
+ it('returns null for a token with no voicing, so the bar becomes a rest', () => {
+ expect(chordMidiNotes('N.C.')).toBeNull();
+ expect(chordMidiNotes('not a chord')).toBeNull();
+ });
+});
+
+describe('buildChordSchedule — timing', () => {
+ it('gives every chord token one bar at the requested tempo', () => {
+ const { events, beatSec, barSec, totalSec } = buildChordSchedule(lines(SHEET), { bpm: 120 });
+ near(beatSec, 0.5);
+ near(barSec, 2);
+ expect(events.map((e) => e.name)).toEqual(['C', 'G', 'Am', 'F']);
+ expect(events.map((e) => e.startSec)).toEqual([0, 2, 4, 6]);
+ near(totalSec, 8);
+ });
+
+ it('splits a dash-joined token\'s bar between its segments', () => {
+ const { events } = buildChordSchedule(lines('Am-Am7 F'), { bpm: 120 });
+ expect(events.map((e) => e.durSec)).toEqual([1, 1, 2]);
+ expect(events.map((e) => e.startSec)).toEqual([0, 1, 2]);
+ });
+
+ it('honours beatsPerBar and clamps an out-of-range value to the default', () => {
+ near(buildChordSchedule(lines('Am'), { bpm: 60, beatsPerBar: 3 }).barSec, 3);
+ // 99 is outside CHORD_BEATS_MAX — clamped, never accepted as-is.
+ expect(buildChordSchedule(lines('Am'), { beatsPerBar: 99 }).beatsPerBar).toBe(12);
+ expect(buildChordSchedule(lines('Am'), { beatsPerBar: 'nonsense' }).beatsPerBar)
+ .toBe(DEFAULT_CHORD_BEATS_PER_BAR);
+ });
+
+ it('falls back to the default tempo for a missing or nonsense bpm', () => {
+ expect(buildChordSchedule(lines('Am'), {}).bpm).toBe(DEFAULT_CHORD_TEMPO);
+ expect(buildChordSchedule(lines('Am'), { bpm: 0 }).bpm).toBe(DEFAULT_CHORD_TEMPO);
+ });
+
+ it('offsets the music by the count-in and emits one click per count-in beat', () => {
+ const { events, clicks, countInSec } = buildChordSchedule(lines('C G'), {
+ bpm: 120, countInBars: 1,
+ });
+ near(countInSec, 2);
+ expect(clicks).toHaveLength(4);
+ expect(clicks[0].accent).toBe(true);
+ expect(clicks.slice(1).every((c) => !c.accent)).toBe(true);
+ expect(events[0].startSec).toBe(2);
+ });
+
+ it('clamps the count-in rather than accepting an unbounded lead-in', () => {
+ expect(buildChordSchedule(lines('Am'), { countInBars: 99 }).clicks.length)
+ .toBe(4 * 4); // CHORD_COUNT_IN_MAX bars × 4 beats
+ expect(buildChordSchedule(lines('Am'), { countInBars: -3 }).clicks).toEqual([]);
+ });
+
+ it('marks an unvoiceable token as a rest that still occupies its bar', () => {
+ const { events, totalSec } = buildChordSchedule(lines('C N.C. G'), { bpm: 120 });
+ expect(events.map((e) => e.rest)).toEqual([false, true, false]);
+ expect(events[1].midis).toEqual([]);
+ near(totalSec, 6); // the rest still takes a full bar
+ });
+
+ it('reports zero length for a sheet with no chords at all', () => {
+ const { events, totalSec } = buildChordSchedule(lines('just some words here'));
+ expect(events).toEqual([]);
+ expect(totalSec).toBe(0);
+ });
+});
+
+describe('resolveChordPlayhead', () => {
+ const schedule = buildChordSchedule(lines(SHEET), { bpm: 120, countInBars: 1 });
+
+ it('reports the count-in beat before the music starts', () => {
+ expect(resolveChordPlayhead(schedule, 0)).toEqual({ countIn: true, beat: 1 });
+ expect(resolveChordPlayhead(schedule, 1.2)).toEqual({ countIn: true, beat: 3 });
+ });
+
+ it('clamps the transport\'s negative pre-roll to the first count-in beat', () => {
+ expect(resolveChordPlayhead(schedule, -0.4)).toEqual({ countIn: true, beat: 1 });
+ });
+
+ it('reports the sounding chord index once the music is running', () => {
+ expect(resolveChordPlayhead(schedule, 2.1).index).toBe(0);
+ expect(resolveChordPlayhead(schedule, 4.1).index).toBe(1);
+ expect(resolveChordPlayhead(schedule, 8.1).index).toBe(3);
+ });
+
+ it('holds on the last chord past the end rather than running off the list', () => {
+ expect(resolveChordPlayhead(schedule, 999).index).toBe(3);
+ });
+
+ it('returns null when there is nothing to place', () => {
+ expect(resolveChordPlayhead(buildChordSchedule(lines('words only')), 1)).toBeNull();
+ expect(resolveChordPlayhead(null, 1)).toBeNull();
+ });
+});
diff --git a/client/src/lib/chordPlayer.test.js b/client/src/lib/chordPlayer.test.js
new file mode 100644
index 0000000000..11fd2990bb
--- /dev/null
+++ b/client/src/lib/chordPlayer.test.js
@@ -0,0 +1,152 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { parseTabSheet } from './tabNotation.js';
+import { createChordPlayer } from './chordPlayback.js';
+import { createFakeAudio } from '../test/fakeAudioContext.js';
+
+// The AUDIBLE half of chordPlayback.js — buildChordSchedule's pure math is
+// covered in chordPlayback.test.js with no Web Audio at all. This suite drives
+// the real lookahead transport against the shared Web Audio fake, so the wiring
+// (tones actually scheduled, the strum offset, the click gate, the highlight
+// callback, teardown) is pinned rather than assumed.
+//
+// One fake pair for the whole file — lib/audioContext.js caches the context.
+const { FakeAudioContext, audio } = createFakeAudio();
+
+// Advance the audio clock relatively, ticking the lookahead interval alongside.
+const drive = (deltaSec) => {
+ const target = audio.now + deltaSec;
+ for (let t = audio.now + 0.05; t <= target + 1e-9; t += 0.05) {
+ audio.now = Number(t.toFixed(4));
+ vi.advanceTimersByTime(50);
+ }
+};
+
+// Invented placeholder sheet (privacy convention): two chords, one per bar.
+const SHEET = parseTabSheet('C G\nNonsense lyric line').lines;
+
+// The metronome blip is the only voice above 1kHz — no chord tone reaches it
+// (the voicing tops out around MIDI 62, ~294 Hz).
+const clicks = () => audio.oscillators.filter((o) => o.frequency?.values[0] >= 1000);
+const chordTones = () => audio.oscillators.filter((o) => o.frequency?.values[0] < 1000);
+
+describe('createChordPlayer', () => {
+ beforeEach(() => {
+ audio.reset();
+ vi.stubGlobal('AudioContext', FakeAudioContext);
+ vi.useFakeTimers();
+ });
+ afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });
+
+ it('sounds every note of every chord and finishes with onEnded', async () => {
+ const ended = vi.fn();
+ // 240 bpm, 4 beats per chord → 1s per chord, 2s total.
+ const player = createChordPlayer(SHEET, { bpm: 240, onEnded: ended });
+ await player.play();
+ drive(3);
+ // Two triads, each voiced as bass + three chord tones.
+ expect(chordTones()).toHaveLength(8);
+ expect(ended).toHaveBeenCalledTimes(1);
+ expect(player.isPlaying()).toBe(false);
+ });
+
+ it('strums rather than blocking the chord — each tone starts after the one below', async () => {
+ const player = createChordPlayer(parseTabSheet('Am').lines, { bpm: 240 });
+ await player.play();
+ drive(1.5);
+ const starts = chordTones().map((o) => o.started);
+ expect(starts).toHaveLength(4);
+ // The bass shares the downbeat; the chord tones sweep up from it.
+ expect(starts[1]).toBeCloseTo(starts[0], 6);
+ expect(starts[2]).toBeGreaterThan(starts[1]);
+ expect(starts[3]).toBeGreaterThan(starts[2]);
+ // …but the whole strum stays well inside one chord (it must read as a chord).
+ expect(starts.at(-1) - starts[0]).toBeLessThan(0.1);
+ });
+
+ it('reports the sounding chord index for the sheet highlight, then clears it', async () => {
+ const onChord = vi.fn();
+ const player = createChordPlayer(SHEET, { bpm: 240, onChord });
+ await player.play();
+ drive(0.5);
+ expect(onChord).toHaveBeenLastCalledWith(0);
+ drive(1);
+ expect(onChord).toHaveBeenLastCalledWith(1);
+ drive(2);
+ // A finished run must not leave the last chord lit.
+ expect(onChord).toHaveBeenLastCalledWith(null);
+ });
+
+ it('stays silent through a chord with no voicing but keeps its place', async () => {
+ const player = createChordPlayer(parseTabSheet('C N.C. G').lines, { bpm: 240 });
+ await player.play();
+ drive(4);
+ // Only the two real chords sound — the N.C. bar passes in silence.
+ expect(chordTones()).toHaveLength(8);
+ });
+
+ it('counts in with clicks even when the metronome is off', async () => {
+ const player = createChordPlayer(SHEET, { bpm: 240, countInBars: 1, clickEnabled: false });
+ await player.play();
+ drive(1.5);
+ // One bar of count-in = 4 blips, every one of them ahead of the first chord.
+ expect(clicks()).toHaveLength(4);
+ const firstChord = Math.min(...chordTones().map((o) => o.started));
+ expect(clicks().every((c) => c.started < firstChord)).toBe(true);
+ player.stop();
+ });
+
+ it('adds a click on every beat of the music only while the metronome is on', async () => {
+ const off = createChordPlayer(SHEET, { bpm: 240, clickEnabled: false });
+ await off.play();
+ drive(3);
+ expect(clicks()).toHaveLength(0);
+
+ audio.reset();
+ const on = createChordPlayer(SHEET, { bpm: 240, clickEnabled: true });
+ await on.play();
+ drive(3);
+ // 2 chords × 4 beats.
+ expect(clicks()).toHaveLength(8);
+ });
+
+ it('rebuilds on a tempo change made while idle, and leaves live audio alone', async () => {
+ const player = createChordPlayer(SHEET, { bpm: 240 });
+ expect(player.schedule().totalSec).toBeCloseTo(2, 6);
+ player.setBpm(120);
+ expect(player.schedule().totalSec).toBeCloseTo(4, 6);
+
+ await player.play();
+ drive(0.5);
+ const during = player.schedule().totalSec;
+ player.setBpm(240);
+ // The running schedule is untouched — a live rebase would desync the
+ // highlight from what is already scheduled to sound.
+ expect(player.schedule().totalSec).toBe(during);
+ player.stop();
+ });
+
+ it('schedules nothing more once stopped', async () => {
+ const player = createChordPlayer(SHEET, { bpm: 240 });
+ await player.play();
+ drive(0.5);
+ const sounded = audio.oscillators.length;
+ expect(sounded).toBeGreaterThan(0);
+ player.stop();
+ expect(player.isPlaying()).toBe(false);
+ // Every scheduled voice carries a stop time, and the drained interval adds
+ // no more — a transport that kept its timer would keep sounding the sheet.
+ expect(audio.oscillators.every((o) => o.stopped !== null)).toBe(true);
+ drive(3);
+ expect(audio.oscillators).toHaveLength(sounded);
+ });
+
+ it('never starts for a sheet with no chords', async () => {
+ const ended = vi.fn();
+ const player = createChordPlayer(parseTabSheet('just some words here').lines, { onEnded: ended });
+ await player.play();
+ drive(1);
+ expect(audio.oscillators).toHaveLength(0);
+ expect(player.isPlaying()).toBe(false);
+ expect(ended).toHaveBeenCalled();
+ });
+});
diff --git a/client/src/lib/chordShapes.js b/client/src/lib/chordShapes.js
index 18130efe7f..df4677aa6b 100644
--- a/client/src/lib/chordShapes.js
+++ b/client/src/lib/chordShapes.js
@@ -7,6 +7,7 @@
//
// API:
// parseChordName(name) → { root, rootPc, quality, bass, bassPc } | null
+// chordTones(name) → { …parsed, semitones: [0, 4, 7] } | null
// getChordVoicing(name, instrument)→ instrument-shaped voicing | null
// 'guitar' → { instrument, frets: [6 × (-1 muted | 0 open | n)], baseFret, bass }
// 'ukulele' → { instrument, frets: [4 × …], baseFret, bass }
@@ -104,6 +105,20 @@ export const parseChordName = (name) => {
};
};
+// The chord's TONES as semitones above the root, alongside everything
+// `parseChordName` resolved. This is the instrument-free half of a voicing —
+// `chordPlayback.js` sounds a chord sheet from it, so the interval tables stay
+// in this one module instead of being re-typed beside the synth.
+//
+// The array is in degree order (root, 3rd, 5th, …), never deduped or folded
+// into an octave: a 9th is 14 semitones up, and collapsing it to 2 would voice
+// the chord as a cluster.
+export const chordTones = (name) => {
+ const parsed = parseChordName(name);
+ if (!parsed) return null;
+ return { ...parsed, semitones: QUALITY_DEGREES[parsed.quality].map(([, semis]) => semis) };
+};
+
// Dash-joined chord runs ("Am-Am7", a quick change written as one token) are
// several voicings. Split when EVERY dash-separated segment is itself a chord
// token — mirroring tabNotation, where bare dash runs are rhythm filler and a
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index f3bb2bf8b9..08f0e2b92c 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -101,6 +101,7 @@ export * from './audioContext.js';
export * from './cityPlaybackFrame.js';
export * from './canvasRoll.js';
export * from './chiptunePlayback.js';
+export * from './chordPlayback.js';
export * from './chordShapes.js';
export * from './colorMatch.js';
export * from './drumKits.js';
diff --git a/client/src/pages/SongBookImport.jsx b/client/src/pages/SongBookImport.jsx
index 6e4f200804..5ccdb568cb 100644
--- a/client/src/pages/SongBookImport.jsx
+++ b/client/src/pages/SongBookImport.jsx
@@ -4,7 +4,7 @@
* Two URL-param-driven tabs (?tab=paste|url, TabPills):
* - PASTE: font-mono textarea (+ clipboard Paste / Sample / Clear buttons).
* Content runs through normalizePastedTab; detectFormat + parseTabSheet
- * drive a live preview (the same TabSheetView the viewer renders) and
+ * drive a live preview (the same ChordPreview/DrumPreview the viewer renders) and
* prefill title/artist/key/capo from ChordPro meta.
* - URL: input validated with isUrl; Fetch POSTs to the server-side extractor
* which returns a draft ({ title, artist, content, sourceUrl }) — nothing is
@@ -21,7 +21,7 @@ import { ListMusic, ArrowLeft, ClipboardPaste, Eraser, Wand2, Globe, FileText, S
import toast from '../components/ui/Toast';
import PageHeader from '../components/PageHeader';
import TabPills from '../components/ui/TabPills';
-import TabSheetView from '../components/songbook/TabSheetView';
+import ChordPreview from '../components/songbook/ChordPreview';
import DrumPreview from '../components/songbook/DrumPreview';
import {
SONG_STAGES, INSTRUMENTS, DRUM_FORMAT, DRUM_INSTRUMENT,
@@ -334,17 +334,18 @@ export default function SongBookImport() {
{contentText && (
<div className="mb-4">
<div className="text-xs text-gray-400 mb-1">Preview</div>
- <div className={`bg-port-card border border-port-border rounded-lg max-h-[50vh] overflow-y-auto overflow-x-auto ${previewIsDrum ? '' : 'p-3'}`}>
+ <div className="bg-port-card border border-port-border rounded-lg max-h-[50vh] overflow-y-auto overflow-x-auto">
{previewIsDrum ? (
<DrumPreview
text={contentText}
sheetClassName="p-3"
/>
) : (
- <TabSheetView
+ <ChordPreview
text={contentText}
format={contentFormat}
instrumentView={toVoicingInstrument(instrument)}
+ sheetClassName="p-3"
/>
)}
</div>
diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsx
index 8d62c23803..90d2bbbda6 100644
--- a/client/src/pages/SongBookViewer.jsx
+++ b/client/src/pages/SongBookViewer.jsx
@@ -18,7 +18,10 @@
* persisted per song via safeStorage), font size ±, an instrument-view
* toggle (?view=guitar|ukulele|piano — chord diagrams only, render-only,
* defaults to the song's instrument), stage select, capo/key/tuning badges,
- * source link, cross-link chips to the related Round / music Track (#4103) —
+ * source link, cross-link chips to the related Round / music Track (#4103),
+ * a chord-sheet play-along transport for a sheet that carries chords (#4104:
+ * strummed synth backing at a practice tempo, with the sounding chord lit in
+ * the sheet) —
* plus the attachments section (synced meta, machine-local
* bytes → "not on this machine" when absent).
* - EDIT (?mode=edit): metadata form + font-mono content textarea with format
@@ -32,11 +35,12 @@
* useUnsavedChangesGuard (#3958).
*
* Keyboard (play mode): space play/pause, +/- speed, [ ] transpose, 0 top,
- * f fit-to-duration (bound only when the song has a target).
+ * f fit-to-duration (bound only when the song has a target), p chord play-along
+ * (NOT space — the two are complementary, so autoscroll keeps the space key).
* For a drum chart the same keys drive the kit transport instead: space
* play/stop, +/- BPM ±1, [ ] set the loop ends at the current bar.
- * A screen wake lock holds while autoscroll plays — or while the kit plays
- * (useWakeLock).
+ * A screen wake lock holds while autoscroll plays — or while the kit or the
+ * chord play-along does (useWakeLock).
*/
import { useState, useEffect, useMemo, useRef, useCallback } from 'react';
@@ -56,6 +60,8 @@ import TabSheetView from '../components/songbook/TabSheetView';
import DrumSheetView from '../components/songbook/DrumSheetView';
import DrumPreview from '../components/songbook/DrumPreview';
import DrumTransportBar from '../components/songbook/DrumTransportBar';
+import ChordPreview from '../components/songbook/ChordPreview';
+import ChordTransportBar from '../components/songbook/ChordTransportBar';
import PracticeLogger from '../components/songbook/PracticeLogger';
import { SongLinkChips, SongLinksEditor } from '../components/songbook/SongLinks';
import {
@@ -69,6 +75,7 @@ import useDrawerTab from '../hooks/useDrawerTab';
import useKeyboardShortcuts from '../hooks/useKeyboardShortcuts';
import useAutoscroll from '../hooks/useAutoscroll';
import useDrumPlayer from '../hooks/useDrumPlayer';
+import useChordPlayer from '../hooks/useChordPlayer';
import useWakeLock from '../hooks/useWakeLock';
import useUnsavedChangesGuard from '../hooks/useUnsavedChangesGuard';
import { transposeText } from '../lib/tabNotation.js';
@@ -288,9 +295,10 @@ export default function SongBookViewer() {
// Keyed on the content STRING (not the song object) so unrelated record
// updates (stage flips, attachment meta) don't re-run the transpose pass.
const contentText = song?.content?.text || '';
+ const contentFormat = song?.content?.format || 'tab';
// A drum chart renders on the kit grid and plays back through the drum
// transport; transpose and chord voicings are meaningless for it.
- const isDrum = (song?.content?.format || 'tab') === DRUM_FORMAT;
+ const isDrum = contentFormat === DRUM_FORMAT;
const renderedText = useMemo(
() => (transpose && !isDrum ? transposeText(contentText, transpose) : contentText),
[contentText, transpose, isDrum],
@@ -319,13 +327,28 @@ export default function SongBookViewer() {
// a non-drum song, so it stands up no player and touches no audio.
const drum = useDrumPlayer(isDrum ? contentText : '', { songId: id });
- // The wake lock holds while either play-mode hands-free surface is running.
- // Edit-preview audio owns its lifecycle inside DrumPreview.
- useWakeLock(playing || drum.playing);
+ // --- Chord-sheet play-along (#4104): the same shape one format over. Fed the
+ // TRANSPOSED text, so what you hear matches what the sheet shows. Called
+ // unconditionally (hooks rule) — a drum chart, and a `plain` sheet (the
+ // explicit opt-out of all notation UI, chord tokens included), parse to zero
+ // chords and stand up no player.
+ const chord = useChordPlayer(
+ isDrum || contentFormat === 'plain' ? '' : renderedText,
+ { songId: id },
+ );
+
+ // The wake lock holds while any play-mode hands-free surface is running.
+ // Edit-preview audio owns its lifecycle inside DrumPreview / ChordPreview.
+ useWakeLock(playing || drum.playing || chord.playing);
- // Leaving play mode (Edit) or unmounting must not leave the kit sounding — the
- // hook tears the player down on unmount, but a mode flip keeps it mounted.
- useEffect(() => { if (editing) drum.stop(); }, [editing, drum.stop]);
+ // Leaving play mode (Edit) or unmounting must not leave a transport sounding —
+ // the hooks tear their players down on unmount, but a mode flip keeps them
+ // mounted, and the edit preview stands up its own player beside them.
+ useEffect(() => {
+ if (!editing) return;
+ drum.stop();
+ chord.stop();
+ }, [editing, drum.stop, chord.stop]);
const scrollToTop = useCallback(() => {
stop();
@@ -367,6 +390,10 @@ export default function SongBookViewer() {
'[': () => setTranspose(transpose - 1),
']': () => setTranspose(transpose + 1),
'0': scrollToTop,
+ // The chord play-along gets `p`, not space: space already drives autoscroll
+ // here, and the two are complementary (scroll the sheet while the backing
+ // sounds) rather than rival meanings of "play".
+ p: chord.toggle,
// Only bound when the song HAS a target — otherwise the key would toast
// "nothing to fit" at a user who never set one.
...(fitDurationSec != null ? { f: fitToSongDuration } : {}),
@@ -768,7 +795,7 @@ export default function SongBookViewer() {
</div>
<div>
<div className="text-xs text-gray-400 mb-1">Preview</div>
- <div className={`bg-port-card border border-port-border rounded-lg overflow-hidden ${draftIsDrum ? '' : 'p-3 overflow-x-auto'}`}>
+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">
{draftIsDrum ? (
<DrumPreview
text={draft.text}
@@ -778,11 +805,13 @@ export default function SongBookViewer() {
settingsMirror={drum}
/>
) : (
- <TabSheetView
+ <ChordPreview
text={draft.text}
+ songId={id}
format={draft.format}
fontSizeRem={fontSize}
instrumentView={toVoicingInstrument(draft.instrument)}
+ sheetClassName="p-3 overflow-x-auto"
/>
)}
</div>
@@ -824,6 +853,29 @@ export default function SongBookViewer() {
/>
)}
+ {/* Chord-sheet play-along transport (#4104) — the same slot one format
+ over, and only for a sheet that actually carries chords (a lyrics-
+ only or plain sheet has nothing to sound, so no bar appears). */}
+ {!isDrum && chord.chordCount > 0 && (
+ <ChordTransportBar
+ playing={chord.playing}
+ onToggle={chord.toggle}
+ hasChords={chord.hasChords}
+ bpm={chord.bpm}
+ onBpmChange={chord.setBpm}
+ onPercent={chord.setBpmPercent}
+ writtenTempo={chord.writtenTempo}
+ beatsPerBar={chord.beatsPerBar}
+ onBeatsPerBarChange={chord.setBeatsPerBar}
+ countInBars={chord.countInBars}
+ onCountInChange={chord.setCountInBars}
+ clickEnabled={chord.clickEnabled}
+ onClickToggle={chord.setClickEnabled}
+ chordCount={chord.chordCount}
+ pulse={chord.pulse}
+ />
+ )}
+
<div className="shrink-0 border-b border-port-border bg-port-card/60 px-3 py-2 flex flex-wrap items-center gap-x-4 gap-y-2">
{/* Autoscroll — a drum chart scrolls HORIZONTALLY under its own
playhead (DrumSheetView), so a second vertical-scroll play button
@@ -968,11 +1020,12 @@ export default function SongBookViewer() {
) : song.content?.text ? (
<TabSheetView
text={renderedText}
- format={song?.content?.format || 'tab'}
+ format={contentFormat}
fontSizeRem={fontSize}
className="max-w-4xl"
instrumentView={instrumentView}
showChordStrip
+ soundingChord={chord.sounding}
/>
) : (
<p className="text-sm text-gray-500">