Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
pin the songbook chord shapes above the sheet and collapse the audio bar by default
[._.]/ Adam Eivy6c726d85476a
diff --git a/client/src/components/songbook/ChordPreview.jsx b/client/src/components/songbook/ChordPreview.jsxindex deabff2ee4..cae10d8805 100644--- a/client/src/components/songbook/ChordPreview.jsx+++ b/client/src/components/songbook/ChordPreview.jsx@@ -26,7 +26,6 @@ export default function ChordPreview({format = 'tab',fontSizeRem,instrumentView,- showChordStrip = false,sheetClassName = '',settingsMirror,}) {@@ -106,7 +105,6 @@ export default function ChordPreview({format={format}fontSizeRem={fontSizeRem}instrumentView={instrumentView}- showChordStrip={showChordStrip}soundingChord={player.sounding}/></div>diff --git a/client/src/components/songbook/ChordsUsedCard.jsx b/client/src/components/songbook/ChordsUsedCard.jsxnew file mode 100644index 0000000000..9b2569c58e--- /dev/null+++ b/client/src/components/songbook/ChordsUsedCard.jsx@@ -0,0 +1,41 @@+import { useMemo } from 'react';+import ChordDiagram from './ChordDiagram.jsx';+import CollapsibleBar from './CollapsibleBar.jsx';+import { sheetUsedChords } from '../../lib/chordShapes.js';++/**+ * "Chords used" — every chord the sheet names, in order of first appearance,+ * each with a mini diagram for the active instrument view.+ *+ * It lived inside `<TabSheetView>` (a strip above the sheet) until it moved out+ * here so the viewer can pin it in the header band ABOVE the scroller: the+ * shapes you are reaching for are the thing you want on screen at bar 60, not+ * only at bar 1. Collapsible (and persisted by the host) because it is the+ * tallest of the header cards.+ *+ * The diagram row scrolls internally — a 12-chord song must not push the sheet+ * itself off a phone screen.+ */+export default function ChordsUsedCard({ text, instrument = 'guitar', open, onToggle }) {+ const chords = useMemo(() => sheetUsedChords(text), [text]);+ if (chords.length === 0) return null;+ return (+ <CollapsibleBar+ id="song-chords-used"+ label={`Chords used (${chords.length})`}+ summary={chords.join(' · ')}+ open={open}+ onToggle={onToggle}+ bodyClassName="border-b border-port-border bg-port-card/40 px-3 py-2 max-h-[30vh] overflow-y-auto"+ >+ <div className="flex flex-wrap items-end gap-x-4 gap-y-2">+ {chords.map((name) => (+ <div key={name} className="flex flex-col items-center gap-0.5">+ <span className="text-[11px] font-mono font-semibold text-port-accent">{name}</span>+ <ChordDiagram name={name} instrument={instrument} size="sm" />+ </div>+ ))}+ </div>+ </CollapsibleBar>+ );+}diff --git a/client/src/components/songbook/ChordsUsedCard.test.jsx b/client/src/components/songbook/ChordsUsedCard.test.jsxnew file mode 100644index 0000000000..3a8cced19e--- /dev/null+++ b/client/src/components/songbook/ChordsUsedCard.test.jsx@@ -0,0 +1,51 @@+import { describe, it, expect } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';+import { useState } from 'react';+import ChordsUsedCard from './ChordsUsedCard.jsx';++// Invented placeholder content only (privacy convention) — nonsense lyrics.+const SAMPLE = `[Verse 1]+C G+Nonsense lyric line+[C]Hello [G]world`;++// The card is a controlled disclosure — the viewer owns (and persists) the+// open flag — so the tests drive it through a tiny host rather than reaching+// into the component's internals.+const Host = ({ text = SAMPLE, defaultOpen = true, instrument }) => {+ const [open, setOpen] = useState(defaultOpen);+ return (+ <ChordsUsedCard+ text={text}+ instrument={instrument}+ open={open}+ onToggle={() => setOpen((v) => !v)}+ />+ );+};++describe('ChordsUsedCard', () => {+ it('lists unique chords in first-appearance order with a diagram each', () => {+ const { container } = render(<Host />);+ // C, G on the chords line + [C]/[G] chordlyric — unique set is {C, G}.+ expect(screen.getByRole('button', { name: /Chords used \(2\)/ })).toBeTruthy();+ expect(container.querySelectorAll('svg').length).toBeGreaterThan(1);+ });++ it('renders nothing for a sheet with no chords — no empty header band', () => {+ const { container } = render(<Host text={'Just a lyric line\nand another'} />);+ expect(container.firstChild).toBeNull();+ });++ it('hides the diagrams when collapsed and names the chords in the header instead', () => {+ render(<Host />);+ const toggle = screen.getByRole('button', { name: /Chords used/ });+ expect(toggle.getAttribute('aria-expanded')).toBe('true');+ // Collapsed: the body is hidden (kept mounted) and the summary names the+ // chords, so a closed card still says what the song asks for.+ fireEvent.click(toggle);+ expect(toggle.getAttribute('aria-expanded')).toBe('false');+ expect(document.getElementById('song-chords-used').hidden).toBe(true);+ expect(toggle.textContent).toContain('C · G');+ });+});diff --git a/client/src/components/songbook/CollapsibleBar.jsx b/client/src/components/songbook/CollapsibleBar.jsxnew file mode 100644index 0000000000..212781c7fe--- /dev/null+++ b/client/src/components/songbook/CollapsibleBar.jsx@@ -0,0 +1,48 @@+import { ChevronDown, ChevronRight } from 'lucide-react';++/**+ * A collapsible header band for the SongBook viewer's play mode — the shared+ * chrome behind the Audio, Play along, and Chords used cards that sit ABOVE the+ * sheet scroller (`shrink-0`, so they persist while the sheet scrolls under+ * them).+ *+ * The header row is deliberately terse (one line, `text-xs`): three stacked+ * cards must cost almost nothing when collapsed, which is the whole point of+ * moving them out of the scroller. `summary` renders beside the label only+ * while collapsed, truncated to one line, so a closed card still says what it+ * holds.+ *+ * The body stays MOUNTED and is hidden with the `hidden` attribute rather than+ * unmounted: the cards wrap live transports whose inner setup disclosure+ * (`ChordTransportBar`'s "More") is local state, and collapsing the card while+ * a play-along runs must not throw that away.+ */+export default function CollapsibleBar({+ id,+ label,+ summary = '',+ open,+ onToggle,+ bodyClassName = '',+ children,+}) {+ const Chevron = open ? ChevronDown : ChevronRight;+ return (+ <div className="shrink-0">+ <button+ type="button"+ onClick={onToggle}+ aria-expanded={open}+ aria-controls={id}+ className="w-full flex items-center gap-1.5 border-b border-port-border bg-port-card/60 px-3 py-2 text-xs text-gray-400 hover:text-white"+ >+ <Chevron size={13} className="shrink-0" />+ <span className="font-semibold shrink-0">{label}</span>+ {summary && !open+ ? <span className="min-w-0 truncate text-gray-500">{summary}</span>+ : null}+ </button>+ <div id={id} hidden={!open} className={bodyClassName}>{children}</div>+ </div>+ );+}diff --git a/client/src/components/songbook/TabSheetView.jsx b/client/src/components/songbook/TabSheetView.jsxindex d8f31c1e43..825b6b351f 100644--- a/client/src/components/songbook/TabSheetView.jsx+++ b/client/src/components/songbook/TabSheetView.jsx@@ -1,7 +1,5 @@import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';-import { ChevronDown, ChevronRight } from 'lucide-react';import { parseTabSheet, TAB_ARTICULATIONS } from '../../lib/tabNotation.js';-import { splitJoinedChords } from '../../lib/chordShapes.js';import usePopoverPosition from '../../hooks/usePopoverPosition.js';import ChordDiagram from './ChordDiagram.jsx';import { activeCtrlClass, ctrlBtnClass } from './constants.js';@@ -32,9 +30,9 @@ import { activeCtrlClass, ctrlBtnClass } from './constants.js';* because `text` arrives already transposed the diagrams follow the transposed* names for free. Tab staffs are guitar-specific, so non-guitar views collapse* each staff block to a one-line note with an inline "show" expand.- * `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.+ * The "chords used" strip is NOT here: it moved out to+ * `<ChordsUsedCard>` so the viewer can pin it in the header band above the+ * scroller, where it stays visible past bar 1.** Play-along support (issue #4104): `soundingChord` — `{ lineIndex, chordIndex }`* or null — lights the chord token the synth preview is currently sounding, the@@ -151,14 +149,13 @@ function TabSheetView({fontSizeRem = 0.875,className = '',instrumentView = 'guitar',- showChordStrip = false,soundingChord = null,}) {const plain = format === 'plain';const { lines } = useMemo(// 'plain' is the explicit opt-out of notation parsing: render every line// verbatim (no section headings, no chord highlighting — and no chord- // popovers/strip either) so the stored format selector has an observable+ // popovers either) so the stored format selector has an observable// effect.() => (plain ? { lines: [] } : parseTabSheet(text)),[text, plain],@@ -182,28 +179,6 @@ function TabSheetView({const legendId = useId();const staffIdPrefix = useId();- // Unique chord names in order of first appearance (chords-used strip).- // Dash-joined quick changes split into their segments FIRST, so "Am-Am7"- // plus a standalone "Am" contributes Am and Am7 exactly once each (and an- // N.C. segment can't ride a joined token past the filter).- const usedChords = useMemo(() => {- if (!showChordStrip) return [];- const seen = new Set();- const out = [];- for (const line of lines) {- for (const { name } of line.chords || []) {- for (const part of splitJoinedChords(name)) {- if (part && !/^N\.?C\.?$/.test(part) && !seen.has(part)) {- seen.add(part);- out.push(part);- }- }- }- }- return out;- }, [lines, showChordStrip]);- const [stripOpen, setStripOpen] = useState(true);-// Chord popover: { name, key }; placement is owned by usePopoverPosition,// which re-measures on open and reflows (rAF-coalesced, capture-phase) on// ancestor scroll/resize — so autoscroll can't detach the dialog from its@@ -273,31 +248,6 @@ function TabSheetView({return (<div className={`font-mono text-gray-200 ${className}`} style={{ fontSize: `${fontSizeRem}rem`, lineHeight: 1.5 }}>- {showChordStrip && usedChords.length > 0 && (- <div className="mb-3 border border-port-border rounded-lg bg-port-card/50 font-sans">- <button- type="button"- onClick={() => setStripOpen((open) => !open)}- aria-expanded={stripOpen}- className="w-full flex items-center gap-1.5 px-3 py-2 min-h-[44px] text-xs text-gray-400 hover:text-white"- >- {stripOpen ? <ChevronDown size={13} /> : <ChevronRight size={13} />}- <span className="font-semibold">Chords used</span>- <span className="text-gray-500">({usedChords.length})</span>- </button>- {stripOpen && (- <div className="flex flex-wrap items-end gap-x-4 gap-y-2 px-3 pb-3">- {usedChords.map((name) => (- <div key={name} className="flex flex-col items-center gap-0.5">- <span className="text-[11px] font-mono font-semibold text-port-accent">{name}</span>- <ChordDiagram name={name} instrument={instrumentView} size="sm" />- </div>- ))}- </div>- )}- </div>- )}-{hasTabstaff && (<div className="mb-1.5 flex justify-end font-sans"><button@@ -426,8 +376,7 @@ function TabSheetView({);}-// Props are all primitives (`format`/`instrumentView`/`showChordStrip`-// included) apart from `soundingChord`, which the host memoizes and which only+// Props are all primitives (`format`/`instrumentView` 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.diff --git a/client/src/components/songbook/TabSheetView.test.jsx b/client/src/components/songbook/TabSheetView.test.jsxindex 2752657a37..9021f63a16 100644--- a/client/src/components/songbook/TabSheetView.test.jsx+++ b/client/src/components/songbook/TabSheetView.test.jsx@@ -102,18 +102,16 @@ describe('TabSheetView', () => {it("format='plain' renders verbatim: no headings, no chord highlighting, no chord UI", () => {const { container } = render(- <TabSheetView text={SAMPLE} format="plain" showChordStrip instrumentView="piano" />,+ <TabSheetView text={SAMPLE} format="plain" instrumentView="piano" />,);// The raw [Verse 1] marker stays literal text (not a styled heading)...expect(container.textContent).toContain('[Verse 1]');expect(container.querySelector('.uppercase.tracking-wide')).toBeNull();// ...and no chord token gets the accent highlight.expect(container.querySelector('.text-port-accent.font-semibold')).toBeNull();- // plain is the opt-out of ALL notation UI: no popover buttons, no- // chords-used strip, and tab staffs stay verbatim (no collapse note) even- // in a non-guitar view.+ // plain is the opt-out of ALL notation UI: no popover buttons, and tab+ // staffs stay verbatim (no collapse note) even in a non-guitar view.expect(container.querySelector('[aria-haspopup="dialog"]')).toBeNull();- expect(screen.queryByText('Chords used')).toBeNull();expect(container.textContent).toContain('e|--3--2--|');expect(screen.queryByText(/switch to Guitar view/)).toBeNull();});@@ -158,27 +156,6 @@ describe('TabSheetView', () => {});});- describe('chords-used strip', () => {- it('is off by default and lists unique chords in first-appearance order when enabled', () => {- const { rerender } = render(<TabSheetView text={SAMPLE} />);- expect(screen.queryByText('Chords used')).toBeNull();- rerender(<TabSheetView text={SAMPLE} showChordStrip />);- // C, G on the chords line + [C]/[G] chordlyric — unique set is {C, G}.- expect(screen.getByText('Chords used')).toBeTruthy();- expect(screen.getByText('(2)')).toBeTruthy();- });-- it('collapses and re-expands', () => {- const { container } = render(<TabSheetView text={SAMPLE} showChordStrip />);- const toggle = screen.getByRole('button', { name: /Chords used/ });- expect(toggle.getAttribute('aria-expanded')).toBe('true');- expect(container.querySelectorAll('svg').length).toBeGreaterThan(0);- fireEvent.click(toggle);- expect(toggle.getAttribute('aria-expanded')).toBe('false');- expect(container.querySelectorAll('svg')).toHaveLength(1); // chevron only- });- });-describe('tabstaff collapse in non-guitar views', () => {it('keeps tab staffs visible in the guitar view', () => {render(<TabSheetView text={SAMPLE} instrumentView="guitar" />);diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 1af8a41242..0dfebc4109 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -124,6 +124,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useLiveSuggest` | Post-typing debounce for an imperative panel trigger: `{ registerTrigger, scheduleSuggest }` re-arms one `debounceMs` timer per keystroke and fires the registered fn only while `enabled` and still mounted. | An editor that asks a sibling AI panel to suggest once the writer pauses (WorkEditor ↔ LiveContinuationPanel). || `useLockToggle` | Optimistic-PATCH lock toggle. | New "lock this field/stage/arc" button — use this, do not re-implement. || `usePersistedOptions` | Registry for "saved default + per-run override" form options: one spec row per option (`{ defaultValue, read, clamp, persistOnEdit }`) owns the state, per-field dirty flag, hydrate-if-untouched pass and edited-only override collection. Returns `{ values, edit, hydrate, collectOverrides, inputProps }`, all identity-stable and ref-backed so a caller's `useCallback` needs one dep instead of one per option. | Any panel where each option must load a saved default, persist edits, and send ONLY edited fields as per-run overrides (AutopilotPanel) — use this instead of hand-copying the state/editedRef/hydrate/collect scaffold per option. |+| `usePersistedDisclosure` | Disclosure open/closed state persisted under a localStorage key (`'1'`/`'0'` via safeStorage); absent falls through to the caller's `defaultOpen` rather than reading as closed. Returns `[open, toggle]`. | A collapsible card whose open state should survive a remount/reload (the SongBook viewer's Audio / Play along / Chords used header cards). || `usePopoverPosition` | Viewport-clamped `{ left, top, width }` for a fixed-position portal popover anchored to a trigger; re-measures on open and rAF-coalesced on capture-phase scroll/resize. Returns `{ triggerRef, popoverRef, style, reposition }`; pass `anchorRef` to follow a parent-owned trigger. | Any portal-into-`<body>` menu/popover placed relative to a button (ThemeSwitcher, CollectionPickerShell) — use this instead of re-rolling the measure/flip/clamp/reflow plumbing. || `useScrollLock` | Body-scroll lock with ref-count. | Modals, drawers, lightboxes. || `useSidebarResize` | Drag-to-resize split-pane width persisted to `localStorage`; returns `{ containerRef, width, maxWidth, onMouseDown, reset }` and caps the drag at `maxFraction` of the measured container. | A desktop sidebar/split pane with a draggable divider (WorkEditor's storyboard sidebar). |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 0dd1150ebf..458c4937b1 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -60,6 +60,7 @@ export { default as useMoltworldWs } from './useMoltworldWs.js';export { default as useCharacterAugmentation } from './useCharacterAugmentation.js';export { default as useMounted } from './useMounted.js';export { default as usePendingListRows } from './usePendingListRows.js';+export { default as usePersistedDisclosure } from './usePersistedDisclosure.js';export { default as usePopoverPosition } from './usePopoverPosition.js';export { default as useAgyModels } from './useAgyModels.js';export * from './useAgyModels.js';diff --git a/client/src/hooks/usePersistedDisclosure.js b/client/src/hooks/usePersistedDisclosure.jsnew file mode 100644index 0000000000..6b88e48feb--- /dev/null+++ b/client/src/hooks/usePersistedDisclosure.js@@ -0,0 +1,31 @@+import { useCallback, useState } from 'react';+import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';++/**+ * Disclosure open/closed state remembered across mounts (and reloads) under a+ * localStorage key.+ *+ * `'1'` / `'0'` rather than JSON so the stored bytes are readable and a+ * corrupted entry is unambiguous. Absent — never toggled — is NOT "closed": it+ * falls through to the caller's `defaultOpen`, so a card that ships collapsed+ * can later ship expanded without every install that never touched it being+ * pinned to the old default.+ *+ * `storageKey` is read once, at mount. A caller that swaps the key per record+ * wants a `key` on the component instead; the keys here name a card, not a row.+ */+export default function usePersistedDisclosure(storageKey, defaultOpen = false) {+ const [open, setOpen] = useState(() => {+ const raw = safeReadStorage(storageKey);+ if (raw !== '1' && raw !== '0') return defaultOpen;+ return raw === '1';+ });+ const toggle = useCallback(() => {+ setOpen((prev) => {+ const next = !prev;+ safeWriteStorage(storageKey, next ? '1' : '0');+ return next;+ });+ }, [storageKey]);+ return [open, toggle];+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 9d015f867d..044a6f5622 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -180,7 +180,7 @@ 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; a React surface owning its own context/stream uses `hooks/useAudioSessionClaim.js`, which adds the release-on-unmount backstop. Constructor resolved lazily (`window` → `globalThis`) so node-env test runs import cleanly; tests inject a fake via `vi.stubGlobal('AudioContext', …)` before first call. || `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. |+| `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')`, `sheetUsedChords(text)` (every chord a sheet names, unique, in first-appearance order — the viewer's "Chords used" card), `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. || `wireframeCore.js` | The Kestrel Neon "core assembly": icosahedron geometry (`ICOSAHEDRON_VERTICES` / `ICOSAHEDRON_EDGES`, 12 vertices, 30 edges), `rotatePoint` / `projectIcosahedron` (Y-then-X rotation + perspective), and `drawWireframeCore(ctx, frame)` — one 2D-canvas frame of the depth-shaded wireframe with its orbit rings, vertex dots, and corner angle readout. Every color is an `[r, g, b]` triple so the caller sources them from `AGENT_STATES` and resolved theme tokens; no DOM reads. Consumed by `cos/CoreCoSAvatar.jsx`. || `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. |diff --git a/client/src/lib/chordShapes.js b/client/src/lib/chordShapes.jsindex df4677aa6b..7fc0cb1a21 100644--- a/client/src/lib/chordShapes.js+++ b/client/src/lib/chordShapes.js@@ -13,6 +13,7 @@// 'ukulele' → { instrument, frets: [4 × …], baseFret, bass }// 'piano' → { instrument, notes: ['A','C','E'], bass }// splitJoinedChords(name) → dash-joined "Am-Am7" → ['Am', 'Am7']+// sheetUsedChords(text) → unique chord names in first-appearance order// toVoicingInstrument(instrument) → song instrument → diagram instrument// VOICING_INSTRUMENTS → ['guitar', 'ukulele', 'piano']//@@ -21,7 +22,7 @@// window (1 = baseFret); at baseFret 1 they are absolute. Forgiving — unknown// or unparseable chords return null, never throw.-import { CHORD_TOKEN_RE, NOTE_TO_PC, spellPitchClass } from './tabNotation.js';+import { CHORD_TOKEN_RE, NOTE_TO_PC, parseTabSheet, spellPitchClass } from './tabNotation.js';export const VOICING_INSTRUMENTS = ['guitar', 'ukulele', 'piano'];@@ -130,6 +131,28 @@ export const splitJoinedChords = (name) => {return parts.every((p) => isChordToken(p)) ? parts : [raw];};+// Every chord a sheet names, unique, in order of first appearance — the data+// behind the viewer's "Chords used" card. Dash-joined quick changes split into+// their segments FIRST, so "Am-Am7" plus a standalone "Am" contributes Am and+// Am7 exactly once each (and an N.C. segment can't ride a joined token past the+// filter). N.C. is a rest marker, not a voicing, so it never appears.+export const sheetUsedChords = (text) => {+ const { lines } = parseTabSheet(String(text ?? ''));+ const seen = new Set();+ const out = [];+ for (const line of lines) {+ for (const { name } of line.chords || []) {+ for (const part of splitJoinedChords(name)) {+ if (part && !/^N\.?C\.?$/.test(part) && !seen.has(part)) {+ seen.add(part);+ out.push(part);+ }+ }+ }+ }+ return out;+};+// ---------------------------------------------------------------------------// Piano voicing — interval math with letter-accurate spelling// ---------------------------------------------------------------------------diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsxindex fc88bc7ab9..b78fa12796 100644--- a/client/src/pages/SongBookViewer.jsx+++ b/client/src/pages/SongBookViewer.jsx@@ -24,6 +24,15 @@* the sheet) —* plus the attachments section (synced meta, machine-local* bytes → "not on this machine" when absent).+ *+ * The header band above the sheet is THREE collapsible cards, each with its+ * own remembered open state (`usePersistedDisclosure`) and a one-line summary+ * while closed: **Audio** (the sounding transport — drum kit or chord+ * play-along, collapsed by default, since it is the tallest band and a+ * set-once one), **Sheet controls** (autoscroll/transpose/size/view/stage),+ * and **Chords used** (the sheet's chord shapes, lifted out of+ * `<TabSheetView>` so they stay on screen instead of scrolling away after+ * bar 1).* - EDIT (?mode=edit): metadata form + font-mono content textarea with format* select and live preview. Saves are explicit (single PATCH). The whole* `content` object is always sent — the server fills nested content@@ -62,6 +71,8 @@ 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 ChordsUsedCard from '../components/songbook/ChordsUsedCard';+import CollapsibleBar from '../components/songbook/CollapsibleBar';import PracticeLogger from '../components/songbook/PracticeLogger';import { SongLinkChips, SongLinksEditor } from '../components/songbook/SongLinks';import {@@ -73,6 +84,7 @@ import { useAsyncAction } from '../hooks/useAsyncAction';import { useConfirmDelete } from '../hooks/useConfirmDelete';import useDrawerTab from '../hooks/useDrawerTab';import useKeyboardShortcuts from '../hooks/useKeyboardShortcuts';+import usePersistedDisclosure from '../hooks/usePersistedDisclosure';import useAutoscroll from '../hooks/useAutoscroll';import useDrumPlayer from '../hooks/useDrumPlayer';import useChordPlayer from '../hooks/useChordPlayer';@@ -338,6 +350,27 @@ export default function SongBookViewer() {{ songId: id },);+ // --- Header cards. Each play-mode band above the sheet is a disclosure whose+ // state is remembered globally (a practice posture carries across songs, the+ // way font size does). Audio ships COLLAPSED: it is the tallest band and the+ // one you set once, so the sheet starts higher up a phone screen.+ const [audioOpen, toggleAudio] = usePersistedDisclosure('songbook:audioOpen', false);+ const [controlsOpen, toggleControls] = usePersistedDisclosure('songbook:controlsOpen', true);+ const [chordsOpen, toggleChords] = usePersistedDisclosure('songbook:chordsOpen', true);++ // What a collapsed card says about itself — the couple of values you would+ // otherwise have to open it to read.+ const transport = isDrum ? drum : chord;+ const audioSummary = [+ transport.playing ? 'playing' : null,+ `${transport.bpm} BPM`,+ ].filter(Boolean).join(' · ');+ const controlsSummary = [+ playing ? 'scrolling' : null,+ transpose ? `${transpose > 0 ? '+' : ''}${transpose} semitones` : null,+ isDrum ? null : instrumentLabel(instrumentView),+ ].filter(Boolean).join(' · ');+// 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);@@ -835,184 +868,225 @@ export default function SongBookViewer() {) : (/* ============================== PLAY MODE ============================== */<>- {/* Drum play-along transport — its own bar above the shared controls,- so the kit's tempo/loop/click sit together rather than interleaved- with the sheet controls. */}- {isDrum && (- <DrumTransportBar- playing={drum.playing}- onToggle={drum.toggle}- hasMusic={drum.hasMusic}- bpm={drum.bpm}- onBpmChange={drum.setBpm}- onPercent={drum.setBpmPercent}- writtenTempo={drum.writtenTempo}- countInBars={drum.countInBars}- onCountInChange={drum.setCountInBars}- loopEnabled={drum.loopEnabled}- onLoopToggle={drum.setLoopEnabled}- loopFrom={drum.loopFrom}- loopTo={drum.loopTo}- onLoopRangeChange={drum.setLoopRange}- barCount={drum.barCount}- clickEnabled={drum.clickEnabled}- onClickToggle={drum.setClickEnabled}- clickVolume={drum.clickVolume}- onClickVolumeChange={drum.setClickVolume}- kitId={drum.kitId}- onKitChange={drum.setKitId}- beatsPerBar={drum.beatsPerBar}- pulse={drum.pulse}- currentBar={drum.currentBar}- />- )}+ {/* Audio playback — the transport that actually SOUNDS (kit synth or+ chord strums). Collapsed by default: it is the tallest header+ band and the one you set once per session, so the sheet starts+ higher up the screen and the summary keeps tempo visible while+ it is closed. */}+ {(isDrum || chord.chordCount > 0) && (+ <CollapsibleBar+ id="song-audio-controls"+ label="Audio"+ summary={audioSummary}+ open={audioOpen}+ onToggle={toggleAudio}+ >+ {/* Drum play-along transport — its own bar above the shared controls,+ so the kit's tempo/loop/click sit together rather than interleaved+ with the sheet controls. */}+ {isDrum && (+ <DrumTransportBar+ playing={drum.playing}+ onToggle={drum.toggle}+ hasMusic={drum.hasMusic}+ bpm={drum.bpm}+ onBpmChange={drum.setBpm}+ onPercent={drum.setBpmPercent}+ writtenTempo={drum.writtenTempo}+ countInBars={drum.countInBars}+ onCountInChange={drum.setCountInBars}+ loopEnabled={drum.loopEnabled}+ onLoopToggle={drum.setLoopEnabled}+ loopFrom={drum.loopFrom}+ loopTo={drum.loopTo}+ onLoopRangeChange={drum.setLoopRange}+ barCount={drum.barCount}+ clickEnabled={drum.clickEnabled}+ onClickToggle={drum.setClickEnabled}+ clickVolume={drum.clickVolume}+ onClickVolumeChange={drum.setClickVolume}+ kitId={drum.kitId}+ onKitChange={drum.setKitId}+ beatsPerBar={drum.beatsPerBar}+ pulse={drum.pulse}+ currentBar={drum.currentBar}+ />+ )}- {/* 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}- // Play mode is the only host that binds a key for this transport.- keyHint="(p)"- />+ {/* 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}+ // Play mode is the only host that binds a key for this transport.+ keyHint="(p)"+ />+ )}+ </CollapsibleBar>)}- <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- would be a rival transport with a rival meaning of "play". */}- {!isDrum && (- <div className="flex items-center gap-2">- <button- type="button"- onClick={toggle}- className={`${ctrlBtnClass} ${playing ? 'text-port-accent border-port-accent/50' : ''}`}- aria-label={playing ? 'Pause autoscroll' : 'Play autoscroll'}- title={playing ? 'Pause autoscroll (space)' : 'Play autoscroll (space)'}- >- {playing ? <Pause size={18} /> : <Play size={18} />}- </button>- <label htmlFor="song-speed" className="sr-only">Autoscroll speed</label>- <input- id="song-speed"- type="range"- min={SPEED_MIN}- max={SPEED_MAX}- value={pxPerSec}- onChange={(e) => setPxPerSec(Number(e.target.value))}- className="w-24 sm:w-32 accent-port-accent"- title="Autoscroll speed (+/-)"- />- {/* Fit to duration — only for a song that carries a target run- time (set in Edit). Solves the speed from the sheet as it is- rendered right now, so re-fitting after a font-size or- transpose change is a single click. */}- {fitDurationSec != null && (+ {/* Sheet controls — what you drive the SHEET with (autoscroll,+ transpose, size, instrument view, stage). Open by default: this is+ the band you reach for mid-song. Named for the sheet, not "play+ along", which is the transport's own Play button one card up. */}+ <CollapsibleBar+ id="song-sheet-controls"+ label="Sheet controls"+ summary={controlsSummary}+ open={controlsOpen}+ onToggle={toggleControls}+ >+ <div className="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+ would be a rival transport with a rival meaning of "play". */}+ {!isDrum && (+ <div className="flex items-center gap-2"><buttontype="button"- onClick={fitToSongDuration}- className={`${ctrlBtnClass} gap-1.5 px-2 text-xs`}- aria-label={`Fit autoscroll to ${formatDurationSec(fitDurationSec)}`}- title={`Fit autoscroll to ${formatDurationSec(fitDurationSec)} (f)`}+ onClick={toggle}+ className={`${ctrlBtnClass} ${playing ? 'text-port-accent border-port-accent/50' : ''}`}+ aria-label={playing ? 'Pause autoscroll' : 'Play autoscroll'}+ title={playing ? 'Pause autoscroll (space)' : 'Play autoscroll (space)'}>- <Timer size={16} />- <span className="hidden sm:inline font-mono">{formatDurationSec(fitDurationSec)}</span>+ {playing ? <Pause size={18} /> : <Play size={18} />}</button>- )}- </div>- )}+ <label htmlFor="song-speed" className="sr-only">Autoscroll speed</label>+ <input+ id="song-speed"+ type="range"+ min={SPEED_MIN}+ max={SPEED_MAX}+ value={pxPerSec}+ onChange={(e) => setPxPerSec(Number(e.target.value))}+ className="w-24 sm:w-32 accent-port-accent"+ title="Autoscroll speed (+/-)"+ />+ {/* Fit to duration — only for a song that carries a target run+ time (set in Edit). Solves the speed from the sheet as it is+ rendered right now, so re-fitting after a font-size or+ transpose change is a single click. */}+ {fitDurationSec != null && (+ <button+ type="button"+ onClick={fitToSongDuration}+ className={`${ctrlBtnClass} gap-1.5 px-2 text-xs`}+ aria-label={`Fit autoscroll to ${formatDurationSec(fitDurationSec)}`}+ title={`Fit autoscroll to ${formatDurationSec(fitDurationSec)} (f)`}+ >+ <Timer size={16} />+ <span className="hidden sm:inline font-mono">{formatDurationSec(fitDurationSec)}</span>+ </button>+ )}+ </div>+ )}++ {/* Transpose — meaningless on a kit grid, so hidden for drum charts */}+ {!isDrum && (+ <div className="flex items-center gap-1" role="group" aria-label="Transpose">+ <button type="button" onClick={() => setTranspose(transpose - 1)} className={ctrlBtnClass} aria-label={`Transpose down (currently ${transpose > 0 ? '+' : ''}${transpose} semitones)`} title="Transpose down ([)">+ <Minus size={16} />+ </button>+ <span className="min-w-[3.5rem] text-center text-sm text-gray-300 font-mono" title="Transpose (semitones)" role="status" aria-live="polite" aria-atomic="true">+ <span className="sr-only">Transpose </span>+ <span>{transpose > 0 ? `+${transpose}` : transpose}</span>+ <span className="sr-only"> semitones</span>+ </span>+ <button type="button" onClick={() => setTranspose(transpose + 1)} className={ctrlBtnClass} aria-label={`Transpose up (currently ${transpose > 0 ? '+' : ''}${transpose} semitones)`} title="Transpose up (])">+ <Plus size={16} />+ </button>+ </div>+ )}- {/* Transpose — meaningless on a kit grid, so hidden for drum charts */}- {!isDrum && (- <div className="flex items-center gap-1" role="group" aria-label="Transpose">- <button type="button" onClick={() => setTranspose(transpose - 1)} className={ctrlBtnClass} aria-label={`Transpose down (currently ${transpose > 0 ? '+' : ''}${transpose} semitones)`} title="Transpose down ([)">- <Minus size={16} />+ {/* Font size — on a drum chart the same control zooms the kit grid+ (DrumSheetView scales the whole strip off fontSizeRem), so it's+ labelled for what it actually does there. */}+ <div className="flex items-center gap-1" role="group" aria-label={isDrum ? 'Grid size' : 'Font size'}>+ <span className="sr-only" role="status" aria-live="polite" aria-atomic="true">{isDrum ? `Grid size ${fontSize.toFixed(3)} rem` : `Font size ${fontSize.toFixed(3)} rem`}</span>+ <button type="button" onClick={() => setFontSize(fontSize - FONT_STEP)} className={`${ctrlBtnClass} text-xs font-bold`} aria-label={`${isDrum ? 'Zoom out' : 'Smaller text'} (currently ${fontSize.toFixed(3)} rem)`}>+ A−</button>- <span className="min-w-[3.5rem] text-center text-sm text-gray-300 font-mono" title="Transpose (semitones)" role="status" aria-live="polite" aria-atomic="true">- <span className="sr-only">Transpose </span>- <span>{transpose > 0 ? `+${transpose}` : transpose}</span>- <span className="sr-only"> semitones</span>- </span>- <button type="button" onClick={() => setTranspose(transpose + 1)} className={ctrlBtnClass} aria-label={`Transpose up (currently ${transpose > 0 ? '+' : ''}${transpose} semitones)`} title="Transpose up (])">- <Plus size={16} />+ <button type="button" onClick={() => setFontSize(fontSize + FONT_STEP)} className={`${ctrlBtnClass} text-sm font-bold`} aria-label={`${isDrum ? 'Zoom in' : 'Larger text'} (currently ${fontSize.toFixed(3)} rem)`}>+ A+</button></div>- )}- {/* Font size — on a drum chart the same control zooms the kit grid- (DrumSheetView scales the whole strip off fontSizeRem), so it's- labelled for what it actually does there. */}- <div className="flex items-center gap-1" role="group" aria-label={isDrum ? 'Grid size' : 'Font size'}>- <span className="sr-only" role="status" aria-live="polite" aria-atomic="true">{isDrum ? `Grid size ${fontSize.toFixed(3)} rem` : `Font size ${fontSize.toFixed(3)} rem`}</span>- <button type="button" onClick={() => setFontSize(fontSize - FONT_STEP)} className={`${ctrlBtnClass} text-xs font-bold`} aria-label={`${isDrum ? 'Zoom out' : 'Smaller text'} (currently ${fontSize.toFixed(3)} rem)`}>- A−- </button>- <button type="button" onClick={() => setFontSize(fontSize + FONT_STEP)} className={`${ctrlBtnClass} text-sm font-bold`} aria-label={`${isDrum ? 'Zoom in' : 'Larger text'} (currently ${fontSize.toFixed(3)} rem)`}>- A+- </button>- </div>+ {/* Instrument view (chord diagrams) — render-only, URL-backed. A drum+ chart has no chords to voice, so the picker hides. */}+ {!isDrum && (+ <TabPills+ variant="pills"+ size="sm"+ tabs={VIEW_TABS}+ activeTab={instrumentView}+ onChange={setInstrumentView}+ ariaLabel="Instrument view"+ mobileDropdown+ mobileSelectId="song-instrument-view"+ />+ )}- {/* Instrument view (chord diagrams) — render-only, URL-backed. A drum- chart has no chords to voice, so the picker hides. */}- {!isDrum && (- <TabPills- variant="pills"- size="sm"- tabs={VIEW_TABS}- activeTab={instrumentView}- onChange={setInstrumentView}- ariaLabel="Instrument view"- mobileDropdown- mobileSelectId="song-instrument-view"- />- )}+ {/* Stage */}+ <div>+ <label htmlFor="song-stage" className="sr-only">Learning stage</label>+ <select+ id="song-stage"+ value={song.stage || 'new'}+ onChange={(e) => onStageChange(e.target.value)}+ className={`text-xs rounded-full border px-2 py-2 min-h-[44px] focus:outline-none focus-visible:ring-2 focus-visible:ring-port-accent ${stageClass}`}+ >+ {SONG_STAGES.map((s) => <option key={s.id} value={s.id} className="bg-port-card text-white">{s.label}</option>)}+ </select>+ </div>- {/* Stage */}- <div>- <label htmlFor="song-stage" className="sr-only">Learning stage</label>- <select- id="song-stage"- value={song.stage || 'new'}- onChange={(e) => onStageChange(e.target.value)}- className={`text-xs rounded-full border px-2 py-2 min-h-[44px] focus:outline-none focus-visible:ring-2 focus-visible:ring-port-accent ${stageClass}`}- >- {SONG_STAGES.map((s) => <option key={s.id} value={s.id} className="bg-port-card text-white">{s.label}</option>)}- </select>+ {/* Badges + source */}+ <div className="flex flex-wrap items-center gap-2 text-xs text-gray-400 ml-auto">+ {song.key && <span className="px-2 py-1 rounded-full bg-port-bg border border-port-border">Key {song.key}</span>}+ {song.capo > 0 && <span className="px-2 py-1 rounded-full bg-port-bg border border-port-border">Capo {song.capo}</span>}+ {song.tuning && <span className="px-2 py-1 rounded-full bg-port-bg border border-port-border">{song.tuning}</span>}+ {isHttpUrl(song.sourceUrl) && (+ <a+ href={song.sourceUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="flex items-center gap-1 px-2 py-1 rounded-full bg-port-bg border border-port-border text-port-accent hover:border-port-accent/50"+ >+ <ExternalLink size={12} />+ Source+ </a>+ )}+ </div></div>+ </CollapsibleBar>- {/* Badges + source */}- <div className="flex flex-wrap items-center gap-2 text-xs text-gray-400 ml-auto">- {song.key && <span className="px-2 py-1 rounded-full bg-port-bg border border-port-border">Key {song.key}</span>}- {song.capo > 0 && <span className="px-2 py-1 rounded-full bg-port-bg border border-port-border">Capo {song.capo}</span>}- {song.tuning && <span className="px-2 py-1 rounded-full bg-port-bg border border-port-border">{song.tuning}</span>}- {isHttpUrl(song.sourceUrl) && (- <a- href={song.sourceUrl}- target="_blank"- rel="noopener noreferrer"- className="flex items-center gap-1 px-2 py-1 rounded-full bg-port-bg border border-port-border text-port-accent hover:border-port-accent/50"- >- <ExternalLink size={12} />- Source- </a>- )}- </div>- </div>+ {/* Chords used — pinned in the header band rather than scrolled away+ with the sheet: the shapes you are reaching for matter at bar 60,+ not only at bar 1. Follows the transposed text and the instrument+ view, and a `plain` sheet (the opt-out of all notation UI) and a+ drum chart have no chords to show. */}+ {!isDrum && contentFormat !== 'plain' && (+ <ChordsUsedCard+ text={renderedText}+ instrument={instrumentView}+ open={chordsOpen}+ onToggle={toggleChords}+ />+ )}<div ref={scrollRef} className="flex-1 overflow-y-auto px-3 py-3 sm:px-4 sm:py-4">{/* Cross-links to the Round / music Track this song relates to@@ -1043,7 +1117,6 @@ export default function SongBookViewer() {fontSizeRem={fontSize}className="max-w-4xl"instrumentView={instrumentView}- showChordStripsoundingChord={chord.sounding}/>) : (diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsxindex 0a6f0ad789..4711713ae1 100644--- a/client/src/pages/SongBookViewer.test.jsx+++ b/client/src/pages/SongBookViewer.test.jsx@@ -70,6 +70,11 @@ const waitForEditMode = async () => {await screen.findByLabelText('Content');await settleSongLinksEditor();};+// The play-mode Audio card ships COLLAPSED (its body is `hidden`, so nothing+// inside is in the accessibility tree) — a test that drives the transport opens+// it the way a user would.+const openAudioCard = () => fireEvent.click(screen.getByRole('button', { name: /^Audio/ }));+const renderEditPage = async (path = '/songbook/abc?mode=edit', options) => {const page = renderPage(path, options);await waitForEditMode();@@ -319,7 +324,7 @@ E|--3-----|`;expect(await screen.findByText('Chorus')).toBeTruthy();const select = screen.getByRole('combobox', { name: 'Instrument view' });expect(select.value).toBe('guitar');- expect(screen.getByText('Chords used')).toBeTruthy();+ expect(screen.getByRole('button', { name: /Chords used/ })).toBeTruthy();});it('defaults to the song instrument for piano songs and collapses guitar tab', async () => {@@ -391,6 +396,57 @@ E|--3-----|`;});});+ describe('play-mode header cards', () => {+ it('ships the Audio card collapsed, and opening it reveals the transport', async () => {+ renderPage();+ const audio = await screen.findByRole('button', { name: /^Audio/ });+ expect(audio.getAttribute('aria-expanded')).toBe('false');+ // Collapsed means OUT of the accessibility tree, not merely unpainted —+ // otherwise the transport keeps answering role queries and taps.+ expect(document.getElementById('song-audio-controls').hidden).toBe(true);+ expect(screen.queryByRole('button', { name: 'Play along' })).toBeNull();+ fireEvent.click(audio);+ expect(document.getElementById('song-audio-controls').hidden).toBe(false);+ expect(screen.getByRole('button', { name: 'Play along' })).toBeTruthy();+ });++ it('remembers each card between mounts', async () => {+ const first = renderPage();+ fireEvent.click(await screen.findByRole('button', { name: /^Audio/ }));+ fireEvent.click(screen.getByRole('button', { name: /^Sheet controls/ }));+ first.unmount();++ renderPage();+ expect((await screen.findByRole('button', { name: /^Audio/ })).getAttribute('aria-expanded')).toBe('true');+ expect(screen.getByRole('button', { name: /^Sheet controls/ }).getAttribute('aria-expanded')).toBe('false');+ });++ it('pins Chords used above the sheet scroller, so it survives scrolling', async () => {+ const { container } = renderPage();+ expect(await screen.findByText('Chorus')).toBeTruthy();+ const card = document.getElementById('song-chords-used');+ const scroller = container.querySelector('.flex-1.overflow-y-auto');+ expect(scroller).toBeTruthy();+ expect(scroller.contains(card)).toBe(false);+ });++ it('keeps the chord diagrams following the transposed names', async () => {+ renderPage();+ expect(await screen.findByRole('button', { name: /Chords used/ })).toBeTruthy();+ const card = document.getElementById('song-chords-used');+ expect(card.textContent).toContain('C');+ fireEvent.click(screen.getByRole('button', { name: /Transpose up \(currently 0/ }));+ expect(document.getElementById('song-chords-used').textContent).toContain('C#');+ });++ it('shows no Chords used card for a sheet with no chords', async () => {+ api.getSong.mockResolvedValue(song({ content: { format: 'tab', text: 'Just a lyric line' } }));+ renderPage();+ expect(await screen.findByText('Just a lyric line')).toBeTruthy();+ expect(screen.queryByRole('button', { name: /Chords used/ })).toBeNull();+ });+ });+describe('drum charts (#3115)', () => {// Invented groove (privacy convention).const DRUM_CHART = `time: 4/4@@ -462,6 +518,7 @@ K: o - - - - - o -`;api.getSong.mockResolvedValue(drumSong());renderPage();expect(await screen.findByLabelText('Practice tempo (BPM)')).toBeTruthy();+ openAudioCard();fireEvent.click(screen.getByRole('button', { name: '50%' }));await waitFor(() => expect(screen.getByLabelText('Practice tempo (BPM)').value).toBe('48'));fireEvent.click(screen.getByRole('button', { name: '100%' }));