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
SongBook viewer: instrument-view toggle with per-chord voicing diagrams
[._.]/ Adam Eivy62176952edf3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c0ce06f4bf..50912e53dc 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -12,6 +12,8 @@## Added+- **[issue-2656] SongBook per-instrument view with chord voicings.** The song viewer's play mode gains a Guitar/Ukulele/Piano toggle (URL-addressable via `?view=`, defaulting to the song's own instrument — bass/voice/other render guitar shapes) that swaps how chords are visualized without touching the record. Every chord token in the sheet is now tappable/keyboard-accessible and opens a viewport-clamped popover with the voicing for the active instrument: an SVG fretbox (nut, finger dots, open/muted markers, and a fret-window label for barre shapes) for guitar and ukulele, or spelled note chips (letter-accurate — the 3rd of E is G#, never Ab) for piano. Slash chords voice the base chord and show the bass separately; unknown chords degrade to "no diagram" without crashing. A collapsible "Chords used" strip above the sheet shows a mini diagram for each unique chord in first-appearance order, diagrams follow the transpose control's chord names, and guitar-specific tab staffs collapse to a one-line note (with an inline "show" expand) in the ukulele/piano views. New pure lib `client/src/lib/chordShapes.js` (curated first-position guitar shapes + movable E-/A-form barre templates, an exact lowest-position search for ukulele GCEA, interval math for piano) and `ChordDiagram` component, both unit-tested.+- **[issue-2593] URL-addressable building focus mode in City.** Clicking a building, minimap marker, or search match now focuses it in place at `/city/apps/:appId` instead of leaving City for `/apps/:id` — the camera flies to frame the whole borough (aspect- and HUD-safe-area aware, guarded against intersecting geometry) and the Intel pane is replaced (never overlapped) by a building-detail panel showing status, a process summary with unhealthy processes, and the app's active agents, plus an explicit **Open app** action to the real detail page and a **Close** back to the overview. The focused borough is visually distinguished (accent selection ring + expanded hologram) and its minimap dot exposes `aria-current` to assistive tech. Because the selection lives in the URL, reload/deep-link restores it once positions load, and browser back/forward moves between focused buildings and the overview; stale/deleted ids get an inline "building not found" fallback with a return-to-overview action. Entering Photo, History, or Drop In while focused deterministically clears focus first. On compact viewports the details render as the responsive HUD bottom sheet. New pure helpers `cityFocusCamera` (framing math, unit-tested) and `cityFocusState` (route-param resolution, unit-tested); new `CityFocusCamera` (in-canvas controller) and `CityFocusPanel` components.- **[issue-2610] LLM personality self-profile testing with digital-twin alignment scoring.** New **Digital Twin → Personality** tab (also reachable via ⌘K and voice): pick one or more provider/models and run a single-prompt deep introspective self-evaluation that returns a structured personality profile — agreeableness, humor, error aversion, self-censorship, conciseness, dogmatism, sycophancy, creativity, formality, empathy — each scored 0–100% with the model's own rationale, plus a plain-language summary. An optional follow-up check scores how well that posture aligns with your twin's analyzed traits (Big Five, communication profile, values), with per-dimension notes; it's skipped with a clear message when the twin has no analyzed traits yet. Results render on a radar chart, persist as capped local history (survives restart, delete per entry), and any 2+ past runs can be overlaid on one radar with a side-by-side score table to compare models or track one model over time. The scorer provider/model, history cap, and default alignment toggle are configurable in the tab's Options; both prompts are editable stage templates like any other. Calls fire only from the explicit Run action — never at boot or in the background.diff --git a/PLAN.md b/PLAN.mdindex 3339c5b825..5524b6c681 100644--- a/PLAN.md+++ b/PLAN.md@@ -40,7 +40,8 @@ by `/do:replan --issues`:(`server/lib/brainValidation.js` `songStageEnum`).- [ ] Link songs to existing Rounds/Tracks/MIDI records — a cross-links field onthe `songs` record + UI in `client/src/pages/SongBookViewer.jsx`.-- [ ] Chord diagrams / fretboard rendering and MIDI/score preview embedding in- the SongBook viewer (`client/src/components/songbook/TabSheetView.jsx`).+- [ ] MIDI/score preview embedding in the SongBook viewer+ (`client/src/components/songbook/TabSheetView.jsx`). (Chord diagrams /+ fretboard rendering shipped with the instrument-view toggle, issue #2656.)- [ ] Brain memory-bridge/graph enrollment for `songs` records (nav/⌘K alreadyworks via the nav manifest; this is the knowledge-graph side).diff --git a/client/src/components/songbook/ChordDiagram.jsx b/client/src/components/songbook/ChordDiagram.jsxnew file mode 100644index 0000000000..d546ea38e0--- /dev/null+++ b/client/src/components/songbook/ChordDiagram.jsx@@ -0,0 +1,160 @@+import { memo, useMemo } from 'react';+import { getChordVoicing } from '../../lib/chordShapes.js';++/**+ * Small chord-voicing diagram for the SongBook viewer's instrument views:+ * an inline SVG fretbox for guitar (6-string) and ukulele (4-string) — nut,+ * frets, strings, finger dots, open (o) / muted (x) markers, and a "Nfr"+ * window label when the shape sits above the nut — and a compact note-chip+ * row for piano. Slash chords add a "/G bass" hint (piano prepends the bass+ * chip instead).+ *+ * Sized to fit a ~140px-wide popover (`size="md"`, default) or the+ * chords-used strip (`size="sm"`). Theme-aware: all strokes/text use+ * currentColor from the surrounding text color; dots pick up port-accent.+ * Unknown chords render a muted "no diagram" fallback — never crash.+ */++const SIZES = {+ sm: { cell: 11, row: 12, dot: 3.2, font: 7 },+ md: { cell: 16, row: 15, dot: 4.5, font: 8.5 },+};++const FretboxDiagram = ({ voicing, size }) => {+ const s = SIZES[size] || SIZES.md;+ const { frets, baseFret } = voicing;+ const gaps = frets.length - 1;+ const rows = Math.max(4, ...frets.filter((f) => f > 0));+ const left = baseFret > 1 ? s.font * 2.6 : 6;+ const top = s.row * 0.8;+ const width = left + gaps * s.cell + 6;+ const height = top + rows * s.row + 4;+ const stringX = (i) => left + i * s.cell;++ return (+ <svg+ width={width}+ height={height}+ viewBox={`0 0 ${width} ${height}`}+ aria-hidden="true"+ className="text-gray-400"+ >+ {/* Nut (thick at first position) + frets */}+ {Array.from({ length: rows + 1 }, (_, j) => (+ <line+ key={`f${j}`}+ x1={stringX(0)}+ y1={top + j * s.row}+ x2={stringX(gaps)}+ y2={top + j * s.row}+ stroke="currentColor"+ strokeWidth={j === 0 && baseFret === 1 ? 2.5 : 0.75}+ />+ ))}+ {/* Strings */}+ {frets.map((_, i) => (+ <line+ key={`s${i}`}+ x1={stringX(i)}+ y1={top}+ x2={stringX(i)}+ y2={top + rows * s.row}+ stroke="currentColor"+ strokeWidth={0.75}+ />+ ))}+ {/* Window label when the shape sits above the nut */}+ {baseFret > 1 && (+ <text+ x={left - 4}+ y={top + s.row * 0.5 + s.font * 0.38}+ textAnchor="end"+ fontSize={s.font}+ fill="currentColor"+ >+ {baseFret}fr+ </text>+ )}+ {/* Open / muted markers above the nut */}+ {frets.map((f, i) => {+ if (f > 0) return null;+ return f === 0 ? (+ <circle+ key={`m${i}`}+ cx={stringX(i)}+ cy={top - s.row * 0.42}+ r={s.dot * 0.62}+ fill="none"+ stroke="currentColor"+ strokeWidth={0.9}+ />+ ) : (+ <text+ key={`m${i}`}+ x={stringX(i)}+ y={top - s.row * 0.18}+ textAnchor="middle"+ fontSize={s.font}+ fill="currentColor"+ >+ ×+ </text>+ );+ })}+ {/* Finger dots */}+ <g className="text-port-accent">+ {frets.map((f, i) => (f > 0 ? (+ <circle+ key={`d${i}`}+ cx={stringX(i)}+ cy={top + (f - 0.5) * s.row}+ r={s.dot}+ fill="currentColor"+ />+ ) : null))}+ </g>+ </svg>+ );+};++const PianoChips = ({ voicing, size }) => (+ <span className={`inline-flex flex-wrap items-center ${size === 'sm' ? 'gap-0.5' : 'gap-1'}`}>+ {voicing.bass && (+ <span className={`rounded border border-port-border bg-port-bg text-gray-400 font-mono ${size === 'sm' ? 'px-1 py-0.5 text-[9px]' : 'px-1.5 py-0.5 text-[11px]'}`}>+ {voicing.bass}+ <span className="text-gray-600"> bass</span>+ </span>+ )}+ {voicing.notes.map((note, i) => (+ <span+ key={`${note}-${i}`}+ className={`rounded border border-port-accent/30 bg-port-accent/10 text-port-accent font-mono font-semibold ${size === 'sm' ? 'px-1 py-0.5 text-[9px]' : 'px-1.5 py-0.5 text-[11px]'}`}+ >+ {note}+ </span>+ ))}+ </span>+);++function ChordDiagram({ name, instrument, size = 'md' }) {+ const voicing = useMemo(() => getChordVoicing(name, instrument), [name, instrument]);++ if (!voicing) {+ return <span className="text-[10px] text-gray-500 italic">no diagram</span>;+ }+ if (voicing.instrument === 'piano') {+ return <PianoChips voicing={voicing} size={size} />;+ }+ return (+ <span className="inline-flex flex-col items-center">+ <FretboxDiagram voicing={voicing} size={size} />+ {voicing.bass && (+ <span className="text-[9px] text-gray-500 leading-tight">/{voicing.bass} bass</span>+ )}+ </span>+ );+}++// Pure function of primitive props — memo keeps sheet re-renders (autoscroll+// ticks, popover moves) from redrawing every strip diagram.+export default memo(ChordDiagram);diff --git a/client/src/components/songbook/ChordDiagram.test.jsx b/client/src/components/songbook/ChordDiagram.test.jsxnew file mode 100644index 0000000000..2b7c66661d--- /dev/null+++ b/client/src/components/songbook/ChordDiagram.test.jsx@@ -0,0 +1,55 @@+import { describe, it, expect } from 'vitest';+import { render } from '@testing-library/react';+import ChordDiagram from './ChordDiagram.jsx';++describe('ChordDiagram', () => {+ it('renders a 6-string fretbox for guitar with muted/open markers and dots', () => {+ const { container } = render(<ChordDiagram name="Am" instrument="guitar" />);+ const svg = container.querySelector('svg');+ expect(svg).toBeTruthy();+ // Am = x02210 → 1 muted marker (×), 2 open circles, 3 finger dots.+ expect(container.textContent).toContain('×');+ const dots = svg.querySelectorAll('g circle');+ expect(dots.length).toBe(3);+ // First position — no window label.+ expect(container.textContent).not.toMatch(/fr/);+ });++ it('labels the fret window for shapes above the nut', () => {+ // C#m7 = A-form barre at fret 4.+ const { container } = render(<ChordDiagram name="C#m7" instrument="guitar" />);+ expect(container.textContent).toContain('4fr');+ });++ it('renders a 4-string fretbox for ukulele', () => {+ // G7 = 0212 → 4 strings, 3 dots, 1 open marker.+ const { container } = render(<ChordDiagram name="G7" instrument="ukulele" />);+ const svg = container.querySelector('svg');+ expect(svg).toBeTruthy();+ expect(svg.querySelectorAll('g circle').length).toBe(3);+ expect(container.textContent).not.toContain('×');+ });++ it('renders piano voicings as note chips, prepending the slash bass', () => {+ const { container } = render(<ChordDiagram name="Am/G" instrument="piano" />);+ expect(container.querySelector('svg')).toBeNull();+ expect(container.textContent).toContain('A');+ expect(container.textContent).toContain('C');+ expect(container.textContent).toContain('E');+ expect(container.textContent).toContain('G');+ expect(container.textContent).toContain('bass');+ // Bass chip comes first.+ expect(container.textContent.indexOf('G')).toBeLessThan(container.textContent.indexOf('A'));+ });++ it('shows the slash-bass hint under string-instrument diagrams', () => {+ const { container } = render(<ChordDiagram name="G/B" instrument="guitar" />);+ expect(container.textContent).toContain('/B bass');+ });++ it('degrades to a muted fallback for unknown chords — no crash', () => {+ const { container } = render(<ChordDiagram name="Zq7" instrument="guitar" />);+ expect(container.querySelector('svg')).toBeNull();+ expect(container.textContent).toContain('no diagram');+ });+});diff --git a/client/src/components/songbook/TabSheetView.jsx b/client/src/components/songbook/TabSheetView.jsxindex da8a0dc114..315b946e0b 100644--- a/client/src/components/songbook/TabSheetView.jsx+++ b/client/src/components/songbook/TabSheetView.jsx@@ -1,5 +1,7 @@-import { memo, useMemo } from 'react';+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { ChevronDown, ChevronRight } from 'lucide-react';import { parseTabSheet } from '../../lib/tabNotation.js';+import ChordDiagram from './ChordDiagram.jsx';/*** Rendered tab/chord sheet — the shared display surface for the SongBook@@ -16,8 +18,25 @@ import { parseTabSheet } from '../../lib/tabNotation.js';* - lyric/text → plain monospace pre-wrap** `fontSizeRem` scales the whole sheet (viewer font ± control).+ * `format='plain'` bypasses parsing entirely and renders the raw text+ * verbatim — the explicit opt-out of ALL notation UI (headings, chord+ * highlighting, popovers, and the chords-used strip alike).+ *+ * Instrument-view support (issue #2656): `instrumentView`+ * ('guitar'|'ukulele'|'piano', default 'guitar') drives the chord diagrams —+ * every chord token is a tappable/keyboard-activatable button that opens a+ * viewport-clamped popover with the voicing for the active instrument, and+ * 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.*/+const POPOVER_WIDTH = 172;+const POPOVER_EST_HEIGHT = 200;+// Split a chords line into plain/chord segments using the parser's col offsets.const chordLineSegments = (text, chords) => {const segments = [];@@ -31,42 +50,71 @@ const chordLineSegments = (text, chords) => {return segments;};-// Build the padded chord row for a chordlyric line: each chord name lands at-// its col offset into the lyric; names that would collide keep one space.-const buildChordRow = (chords) => {- let row = '';+// Build the padded chord row for a chordlyric line as segments: each chord+// name lands at its col offset into the lyric; names that would collide keep+// one space.+const chordRowSegments = (chords) => {+ const segments = [];+ let length = 0;for (const { name, col } of chords) {- if (row.length < col) row += ' '.repeat(col - row.length);- else if (row.length > 0) row += ' ';- row += name;+ let pad = '';+ if (length < col) pad = ' '.repeat(col - length);+ else if (length > 0) pad = ' ';+ if (pad) {+ segments.push({ text: pad, chord: false });+ length += pad.length;+ }+ segments.push({ text: name, chord: true });+ length += name.length;}- return row;+ return segments;};-const ChordsLine = ({ line }) => (- <div className="whitespace-pre-wrap">- {chordLineSegments(line.text, line.chords).map((seg, i) =>- seg.chord- ? <span key={i} className="text-port-accent font-semibold">{seg.text}</span>- : <span key={i}>{seg.text}</span>)}- </div>+// A tappable chord token. `inline` keeps vertical padding from growing the+// 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 }) => (+ <button+ type="button"+ onClick={(e) => onTap(name, tokenKey, e.currentTarget)}+ aria-expanded={expanded}+ aria-haspopup="dialog"+ className="inline align-baseline 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"+ >+ {name}+ </button>);-const ChordLyricLine = ({ line }) => (- <div className="overflow-x-auto">- <div className="whitespace-pre text-port-accent font-semibold leading-tight">- {buildChordRow(line.chords)}- </div>- <div className="whitespace-pre">{line.text || ' '}</div>- </div>-);+const ChordSegments = ({ segments, blockKey, activeKey, onTap }) =>+ segments.map((seg, i) => {+ if (!seg.chord) return <span key={i}>{seg.text}</span>;+ const tokenKey = `${blockKey}:${i}`;+ return (+ <ChordToken+ key={i}+ name={seg.text}+ tokenKey={tokenKey}+ expanded={activeKey === tokenKey}+ onTap={onTap}+ />+ );+ });-function TabSheetView({ text, format = 'tab', fontSizeRem = 0.875, className = '' }) {+function TabSheetView({+ text,+ format = 'tab',+ fontSizeRem = 0.875,+ className = '',+ instrumentView = 'guitar',+ showChordStrip = false,+}) {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) so the stored- // format selector has an observable effect.+ // verbatim (no section headings, no chord highlighting — and no chord+ // popovers/strip either) so the stored format selector has an observable+ // effect.() => (plain ? { lines: [] } : parseTabSheet(text)),[text, plain],);@@ -83,6 +131,72 @@ function TabSheetView({ text, format = 'tab', fontSizeRem = 0.875, className = 'return out;}, [lines]);+ // Unique chord names in order of first appearance (chords-used strip).+ const usedChords = useMemo(() => {+ if (!showChordStrip) return [];+ const seen = new Set();+ const out = [];+ for (const line of lines) {+ for (const { name } of line.chords || []) {+ if (name && !/^N\.?C\.?$/.test(name) && !seen.has(name)) {+ seen.add(name);+ out.push(name);+ }+ }+ }+ return out;+ }, [lines, showChordStrip]);+ const [stripOpen, setStripOpen] = useState(true);++ // Chord popover: { name, key, x, y, above } in viewport (fixed) coords.+ const [popover, setPopover] = useState(null);+ const popoverRef = useRef(null);+ // Tabstaff blocks explicitly expanded while in a non-guitar view.+ const [expandedStaffs, setExpandedStaffs] = useState(() => new Set());++ // New text (edit, transpose) invalidates block indices and chord names.+ useEffect(() => {+ setPopover(null);+ setExpandedStaffs(new Set());+ }, [text]);++ const onChordTap = useCallback((name, key, el) => {+ setPopover((prev) => {+ if (prev?.key === key) return null; // tap again to close+ const rect = el.getBoundingClientRect();+ const x = Math.max(+ 8,+ Math.min(rect.left + rect.width / 2 - POPOVER_WIDTH / 2, window.innerWidth - POPOVER_WIDTH - 8),+ );+ // Open below unless the viewport bottom is too close (then flip above).+ const above = window.innerHeight - rect.bottom < POPOVER_EST_HEIGHT && rect.top > POPOVER_EST_HEIGHT;+ return { name, key, x, y: above ? rect.top - 6 : rect.bottom + 6, above };+ });+ }, []);++ // Escape / tap-outside close while the popover is open.+ useEffect(() => {+ if (!popover) return undefined;+ const onKeyDown = (e) => {+ if (e.key === 'Escape') setPopover(null);+ };+ const onPointerDown = (e) => {+ if (popoverRef.current?.contains(e.target)) return;+ // Chord tokens manage their own open/toggle in onClick — closing here on+ // the preceding pointerdown would make a second tap close-then-reopen.+ if (e.target.closest?.('[aria-haspopup="dialog"]')) return;+ setPopover(null);+ };+ document.addEventListener('keydown', onKeyDown);+ document.addEventListener('pointerdown', onPointerDown);+ return () => {+ document.removeEventListener('keydown', onKeyDown);+ document.removeEventListener('pointerdown', onPointerDown);+ };+ }, [popover]);++ // 'plain' bypass — after the hooks above (they must run unconditionally)+ // and before any notation UI: verbatim text, no strip, no popovers.if (plain) {return (<div@@ -96,8 +210,48 @@ function TabSheetView({ text, format = 'tab', fontSizeRem = 0.875, className = '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>+ )}+{blocks.map((block, bi) => {if (block.type === 'tabstaff') {+ // Tab staffs are guitar-specific — collapse them in other views.+ if (instrumentView !== 'guitar' && !expandedStaffs.has(bi)) {+ return (+ <div key={bi} className="my-1 flex items-center gap-2 text-xs text-gray-500 italic font-sans">+ <span>guitar tab — switch to Guitar view</span>+ <button+ type="button"+ onClick={() => setExpandedStaffs((prev) => new Set(prev).add(bi))}+ className="not-italic text-port-accent hover:underline px-1 py-2 -my-2"+ >+ show+ </button>+ </div>+ );+ }return (<div key={bi} className="overflow-x-auto whitespace-pre text-gray-300 my-1">{block.lines.map((line, li) => <div key={li}>{line.text}</div>)}@@ -116,9 +270,30 @@ function TabSheetView({ text, format = 'tab', fontSizeRem = 0.875, className = '): <div key={bi} className="mb-1" />;case 'chords':- return <ChordsLine key={bi} line={line} />;+ return (+ <div key={bi} className="whitespace-pre-wrap">+ <ChordSegments+ segments={chordLineSegments(line.text, line.chords)}+ blockKey={bi}+ activeKey={popover?.key ?? null}+ onTap={onChordTap}+ />+ </div>+ );case 'chordlyric':- return <ChordLyricLine key={bi} line={line} />;+ return (+ <div key={bi} className="overflow-x-auto">+ <div className="whitespace-pre text-port-accent font-semibold leading-tight">+ <ChordSegments+ segments={chordRowSegments(line.chords)}+ blockKey={bi}+ activeKey={popover?.key ?? null}+ onTap={onChordTap}+ />+ </div>+ <div className="whitespace-pre">{line.text || ' '}</div>+ </div>+ );case 'blank':return <div key={bi}>{' '}</div>;case 'directive':@@ -131,10 +306,32 @@ function TabSheetView({ text, format = 'tab', fontSizeRem = 0.875, className = 'return <div key={bi} className="whitespace-pre-wrap">{line.text}</div>;}})}++ {popover && (+ <div+ ref={popoverRef}+ role="dialog"+ aria-label={`${popover.name} chord voicing`}+ className="fixed z-50 bg-port-card border border-port-border rounded-lg shadow-xl p-3 font-sans"+ style={{+ left: popover.x,+ top: popover.y,+ width: POPOVER_WIDTH,+ transform: popover.above ? 'translateY(-100%)' : undefined,+ }}+ >+ <div className="flex items-center justify-between gap-2 mb-1.5">+ <span className="text-sm font-mono font-semibold text-port-accent">{popover.name}</span>+ <span className="text-[10px] uppercase tracking-wide text-gray-500">{instrumentView}</span>+ </div>+ <ChordDiagram name={popover.name} instrument={instrumentView} />+ </div>+ )}</div>);}-// Props are all primitives, so memo makes re-renders of a host page (stage-// flips, autoscroll ticks) skip the full sheet re-render.+// 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.export default memo(TabSheetView);diff --git a/client/src/components/songbook/TabSheetView.test.jsx b/client/src/components/songbook/TabSheetView.test.jsxindex ec0c1a5b6f..732d6f0526 100644--- a/client/src/components/songbook/TabSheetView.test.jsx+++ b/client/src/components/songbook/TabSheetView.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { render, screen } from '@testing-library/react';+import { render, screen, fireEvent } from '@testing-library/react';import TabSheetView from './TabSheetView.jsx';// Invented placeholder content only (privacy convention) — nonsense lyrics.@@ -68,12 +68,99 @@ describe('TabSheetView', () => {expect(container.textContent).toContain('Nonsense line');});- it("format='plain' renders verbatim: no headings, no chord highlighting", () => {- const { container } = render(<TabSheetView text={SAMPLE} format="plain" />);+ it("format='plain' renders verbatim: no headings, no chord highlighting, no chord UI", () => {+ const { container } = render(+ <TabSheetView text={SAMPLE} format="plain" showChordStrip 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.+ 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();+ });++ describe('chord popover (instrument views, #2656)', () => {+ it('renders chord tokens as keyboard-accessible popover buttons', () => {+ render(<TabSheetView text={SAMPLE} />);+ const button = screen.getAllByRole('button', { name: 'C' })[0];+ expect(button.getAttribute('aria-haspopup')).toBe('dialog');+ expect(button.getAttribute('aria-expanded')).toBe('false');+ });++ it('opens a voicing popover for the active instrument on tap and closes on Escape', () => {+ render(<TabSheetView text={SAMPLE} instrumentView="ukulele" />);+ const button = screen.getAllByRole('button', { name: 'C' })[0];+ fireEvent.click(button);+ const dialog = screen.getByRole('dialog', { name: 'C chord voicing' });+ expect(dialog.textContent).toContain('ukulele');+ expect(dialog.querySelector('svg')).toBeTruthy();+ expect(button.getAttribute('aria-expanded')).toBe('true');+ fireEvent.keyDown(document, { key: 'Escape' });+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(button.getAttribute('aria-expanded')).toBe('false');+ });++ it('toggles the popover closed when the same chord is tapped again', () => {+ render(<TabSheetView text={SAMPLE} />);+ const button = screen.getAllByRole('button', { name: 'G' })[0];+ fireEvent.click(button);+ expect(screen.getByRole('dialog')).toBeTruthy();+ fireEvent.click(button);+ expect(screen.queryByRole('dialog')).toBeNull();+ });++ it('shows piano note chips in the popover for the piano view', () => {+ render(<TabSheetView text={SAMPLE} instrumentView="piano" />);+ fireEvent.click(screen.getAllByRole('button', { name: 'G' })[0]);+ const dialog = screen.getByRole('dialog');+ expect(dialog.querySelector('svg')).toBeNull();+ expect(dialog.textContent).toContain('B');+ expect(dialog.textContent).toContain('D');+ });+ });++ 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" />);+ expect(screen.getByText('e|--3--2--|')).toBeTruthy();+ expect(screen.queryByText(/switch to Guitar view/)).toBeNull();+ });++ it('collapses staff blocks to a note with an inline expand in other views', () => {+ render(<TabSheetView text={SAMPLE} instrumentView="piano" />);+ expect(screen.queryByText('e|--3--2--|')).toBeNull();+ expect(screen.getByText(/guitar tab — switch to Guitar view/)).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'show' }));+ expect(screen.getByText('e|--3--2--|')).toBeTruthy();+ expect(screen.getByText('B|--0-----|')).toBeTruthy();+ });});});diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsxindex 7f2f3269a9..8e0c8e4e0a 100644--- a/client/src/pages/SongBookViewer.jsx+++ b/client/src/pages/SongBookViewer.jsx@@ -9,9 +9,11 @@* - PLAY (default): the rendered sheet (TabSheetView) with an* Ultimate-Guitar-style controls bar — autoscroll play/pause + speed,* transpose ± (render-time transposeText, never mutates stored text; offset- * persisted per song via safeStorage), font size ±, stage select, capo/key/- * tuning badges, source link — plus the attachments section (synced meta,- * machine-local bytes → "not on this machine" when absent).+ * 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 — 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* select and live preview. Saves are explicit (single PUT). The whole* `content` object is always sent — the server fills nested content@@ -31,10 +33,11 @@ import toast from '../components/ui/Toast';import PageHeader from '../components/PageHeader';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';import AutoSizeTextarea from '../components/ui/AutoSizeTextarea';+import TabPills from '../components/ui/TabPills';import TabSheetView from '../components/songbook/TabSheetView';import {SONG_STAGES, SONG_STAGE_COLORS, INSTRUMENTS, SONG_FORMATS,- inputClass, labelClass, btnClass,+ inputClass, labelClass, btnClass, instrumentLabel,} from '../components/songbook/constants';import { useAsyncAction } from '../hooks/useAsyncAction';import { useConfirmDelete } from '../hooks/useConfirmDelete';@@ -43,6 +46,7 @@ import useKeyboardShortcuts from '../hooks/useKeyboardShortcuts';import useAutoscroll from '../hooks/useAutoscroll';import useWakeLock from '../hooks/useWakeLock';import { transposeText } from '../lib/tabNotation.js';+import { VOICING_INSTRUMENTS, toVoicingInstrument } from '../lib/chordShapes.js';import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';import { formatBytes } from '../utils/formatters';import { isHttpUrl } from '../utils/urlNormalize';@@ -84,6 +88,9 @@ const toDraft = (song) => ({const parseTags = (raw) => raw.split(',').map((t) => t.trim()).filter(Boolean);+// Instrument-view toggle tabs (chord-diagram rendering — never mutates the record).+const VIEW_TABS = VOICING_INSTRUMENTS.map((viewId) => ({ id: viewId, label: instrumentLabel(viewId) }));+// 44px minimum touch targets on the controls bar (mobile-friendly).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';@@ -95,6 +102,15 @@ export default function SongBookViewer() {const editing = mode === 'edit';const [song, setSong] = useState(null);+ // URL-backed instrument view (?view=guitar|ukulele|piano). Render-only —+ // never PUT back to the record. Defaults to the song's own instrument+ // (bass/voice/other map to guitar), so the param stays off the URL for the+ // song's natural view and deep links like ?view=piano stay shareable.+ const [instrumentView, setInstrumentView] = useDrawerTab(+ 'view',+ toVoicingInstrument(song?.instrument),+ VOICING_INSTRUMENTS,+ );const [loading, setLoading] = useState(true);const [notFound, setNotFound] = useState(false);const [loadError, setLoadError] = useState(false);@@ -522,6 +538,18 @@ export default function SongBookViewer() {</button></div>+ {/* Instrument view (chord diagrams) — render-only, URL-backed */}+ <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>@@ -561,6 +589,8 @@ export default function SongBookViewer() {format={song?.content?.format || 'tab'}fontSizeRem={fontSize}className="max-w-4xl"+ instrumentView={instrumentView}+ showChordStrip/>) : (<p className="text-sm text-gray-500">diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsxindex fabeff0e0b..3ae66ebdc1 100644--- a/client/src/pages/SongBookViewer.test.jsx+++ b/client/src/pages/SongBookViewer.test.jsx@@ -113,6 +113,72 @@ describe('SongBookViewer', () => {expect(screen.queryByRole('link', { name: /Sheet music/ })).toBeNull();});+ describe('instrument-view toggle (#2656)', () => {+ // Sheet with a tab staff so the non-guitar collapse note is observable.+ const TAB_SHEET = `[Chorus]+C G Am F+Nonsense words here+e|--3--2--|+B|--0-----|`;++ it('defaults to the song instrument (guitar) and shows the chords-used strip', async () => {+ renderPage();+ 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();+ });++ it('defaults to the song instrument for piano songs and collapses guitar tab', async () => {+ api.getSong.mockResolvedValue(song({ instrument: 'piano', content: { format: 'tab', text: TAB_SHEET } }));+ renderPage();+ expect(await screen.findByText('Chorus')).toBeTruthy();+ expect(screen.getByRole('combobox', { name: 'Instrument view' }).value).toBe('piano');+ expect(screen.getByText(/guitar tab — switch to Guitar view/)).toBeTruthy();+ expect(screen.queryByText('e|--3--2--|')).toBeNull();+ });++ it('maps non-diagram instruments (bass/voice/other) to the guitar view', async () => {+ api.getSong.mockResolvedValue(song({ instrument: 'bass' }));+ renderPage();+ expect(await screen.findByText('Chorus')).toBeTruthy();+ expect(screen.getByRole('combobox', { name: 'Instrument view' }).value).toBe('guitar');+ });++ it('honors a ?view= deep link over the song instrument', async () => {+ api.getSong.mockResolvedValue(song({ content: { format: 'tab', text: TAB_SHEET } }));+ renderPage('/songbook/abc?view=ukulele');+ expect(await screen.findByText('Chorus')).toBeTruthy();+ expect(screen.getByRole('combobox', { name: 'Instrument view' }).value).toBe('ukulele');+ expect(screen.getByText(/guitar tab — switch to Guitar view/)).toBeTruthy();+ });++ it('switching the view swaps the diagrams without any record write', async () => {+ api.getSong.mockResolvedValue(song({ content: { format: 'tab', text: TAB_SHEET } }));+ renderPage();+ expect(await screen.findByText('Chorus')).toBeTruthy();+ expect(screen.getByText('e|--3--2--|')).toBeTruthy();+ fireEvent.change(screen.getByRole('combobox', { name: 'Instrument view' }), { target: { value: 'piano' } });+ // Tab staff collapses; a chord popover now shows piano chips.+ expect(screen.getByText(/guitar tab — switch to Guitar view/)).toBeTruthy();+ fireEvent.click(screen.getAllByRole('button', { name: 'Am' })[0]);+ const dialog = screen.getByRole('dialog', { name: 'Am chord voicing' });+ expect(dialog.querySelector('svg')).toBeNull(); // piano chips, not a fretbox+ expect(api.updateSong).not.toHaveBeenCalled();+ });++ it('diagrams follow transposed chord names', async () => {+ api.getSong.mockResolvedValue(song());+ renderPage();+ expect(await screen.findByText('Chorus')).toBeTruthy();+ fireEvent.click(screen.getByLabelText('Transpose up'));+ fireEvent.click(screen.getByLabelText('Transpose up'));+ // C G Am F +2 → D A Bm G; the popover opens for the transposed name.+ fireEvent.click(screen.getAllByRole('button', { name: 'Bm' })[0]);+ expect(screen.getByRole('dialog', { name: 'Bm chord voicing' })).toBeTruthy();+ });+ });+it('renders the edit form in ?mode=edit and saves the whole content object', async () => {api.updateSong.mockImplementation((id, patch) => Promise.resolve(song({ ...patch })));renderPage('/songbook/abc?mode=edit');