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: wrap songbook chords with lyrics and keep diagrams visible

[._.]/ Adam Eivyebe4f5b0bca3
diff --git a/client/src/components/songbook/TabSheetView.jsx b/client/src/components/songbook/TabSheetView.jsx
index 782f4c2929..1528c78554 100644
--- a/client/src/components/songbook/TabSheetView.jsx
+++ b/client/src/components/songbook/TabSheetView.jsx
@@ -1,5 +1,6 @@
+import { createPortal } from 'react-dom';
import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
-import { parseTabSheet, TAB_ARTICULATIONS } from '../../lib/tabNotation.js';
+import { parseTabSheet, TAB_ARTICULATIONS, chordLineSegments, pairedLineChunks, chordLyricRows } from '../../lib/tabNotation.js';
import usePopoverPosition from '../../hooks/usePopoverPosition.js';
import ChordDiagram from './ChordDiagram.jsx';
import { activeCtrlClass, ctrlBtnClass } from './constants.js';
@@ -11,9 +12,8 @@ import { activeCtrlClass, ctrlBtnClass } from './constants.js';
* Takes the (already-transposed) sheet `text` and renders parseTabSheet's
* classified lines:
* - section → styled heading
- * - chords → monospace line with each chord token highlighted at its
- * original column (whitespace-pre keeps alignment)
- * - chordlyric → chord row built from col offsets rendered above the bare lyric
+ * - chords/lyric and chordlyric → paired word groups that wrap both rows together
+ * - standalone chords → highlighted monospace chord line
* - tabstaff → consecutive staff lines grouped in one overflow-x-auto block
* so a wide staff scrolls as a unit without wrapping
* - lyric/text → plain monospace pre-wrap
@@ -43,46 +43,8 @@ import { activeCtrlClass, ctrlBtnClass } from './constants.js';
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;
- 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, chordIndex });
- cursor = col + name.length;
- });
- if (cursor < text.length) segments.push({ text: text.slice(cursor), chord: false });
- return segments;
-};
-
-// 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;
- chords.forEach(({ name, col }, chordIndex) => {
- 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, chordIndex });
- length += name.length;
- });
- return segments;
-};
-
-// 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.
+// A tappable chord token. Paired rows reserve its vertical touch padding;
+// horizontal padding cancels via negative margins to retain column alignment.
const ChordToken = ({ name, tokenKey, expanded, sounding, onTap }) => (
<button
type="button"
@@ -160,13 +122,14 @@ function TabSheetView({
// Group consecutive tabstaff lines into one horizontally-scrollable block so
// 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.
+ // FIRST line had in `lines`; a chord/lyric pair keeps the chord line index
+ // that the play-along highlight addresses.
const blocks = useMemo(() => {
const out = [];
lines.forEach((line, lineIndex) => {
const prev = out[out.length - 1];
- if (line.type === 'tabstaff' && prev?.type === 'tabstaff') prev.lines.push(line);
+ if (line.type === 'lyric' && prev?.type === 'chords') prev.lines.push(line);
+ else if (line.type === 'tabstaff' && prev?.type === 'tabstaff') prev.lines.push(line);
else out.push({ type: line.type, lineIndex, lines: [line] });
});
return out;
@@ -301,6 +264,29 @@ function TabSheetView({
const soundingChordIndex = soundingChord?.lineIndex === block.lineIndex
? soundingChord.chordIndex
: null;
+ if (line.type === 'chordlyric' || (line.type === 'chords' && block.lines.length === 2)) {
+ const rows = line.type === 'chordlyric'
+ ? chordLyricRows(line)
+ : { lyric: block.lines[1].text, chordText: line.text, chords: line.chords };
+ return (
+ <div key={bi} className="flex flex-wrap overflow-x-auto" data-chord-lyric-pair="">
+ {pairedLineChunks(rows.lyric, rows.chordText, rows.chords).map((chunk, ci) => (
+ <div key={ci} className="shrink-0 whitespace-pre" data-chord-lyric-chunk="">
+ <div className="h-[calc(1.5em+1rem)]">
+ <ChordSegments
+ segments={chunk.segments}
+ blockKey={`${bi}:${ci}`}
+ activeKey={popover?.key ?? null}
+ soundingChordIndex={soundingChordIndex}
+ onTap={onChordTap}
+ />
+ </div>
+ <div className="min-h-[1.5em]">{chunk.lyric}</div>
+ </div>
+ ))}
+ </div>
+ );
+ }
switch (line.type) {
case 'section':
// {end_of_*} directives carry an empty label — render nothing visible.
@@ -323,21 +309,6 @@ function TabSheetView({
/>
</div>
);
- case 'chordlyric':
- 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}
- soundingChordIndex={soundingChordIndex}
- onTap={onChordTap}
- />
- </div>
- <div className="whitespace-pre">{line.text || ' '}</div>
- </div>
- );
case 'blank':
return <div key={bi}>{' '}</div>;
case 'directive':
@@ -351,7 +322,7 @@ function TabSheetView({
}
})}
- {popover && (
+ {popover && createPortal(
<div
ref={popoverRef}
role="dialog"
@@ -367,7 +338,12 @@ function TabSheetView({
<span className="text-[10px] uppercase tracking-wide text-gray-500">{instrumentView}</span>
</div>
<ChordDiagram name={popover.name} instrument={instrumentView} />
- </div>
+ <button type="button" className="mt-2 text-sm text-port-accent py-2 w-full" onClick={() => {
+ setPopover(null);
+ anchorElRef.current?.focus();
+ }}>Close chord diagram</button>
+ </div>,
+ document.body,
)}
</div>
);
diff --git a/client/src/components/songbook/TabSheetView.test.jsx b/client/src/components/songbook/TabSheetView.test.jsx
index 9021f63a16..810de7cd06 100644
--- a/client/src/components/songbook/TabSheetView.test.jsx
+++ b/client/src/components/songbook/TabSheetView.test.jsx
@@ -28,7 +28,9 @@ describe('TabSheetView', () => {
it('renders the lyric line under the chords', () => {
render(<TabSheetView text={SAMPLE} />);
- expect(screen.getByText('Nonsense lyric line')).toBeTruthy();
+ expect([...document.querySelectorAll('[data-chord-lyric-pair]')][0].querySelectorAll('[data-chord-lyric-chunk]')[0].lastChild.textContent).toBe('Nonsense ');
+ expect(screen.getByText('lyric')).toBeTruthy();
+ expect(screen.getByText('line')).toBeTruthy();
});
it('groups consecutive tabstaff lines into one horizontally-scrollable block', () => {
@@ -70,15 +72,34 @@ describe('TabSheetView', () => {
expect(screen.queryByRole('button', { name: 'Legend' })).toBeNull();
});
- it('renders chordlyric lines as a chord row above the bare lyric', () => {
- const { container } = render(<TabSheetView text={SAMPLE} />);
- // Bare lyric (brackets stripped)
- expect(screen.getByText('Hello world')).toBeTruthy();
- // Chord row: names padded out to their col offsets ("C" at 0, "G" at 6).
- const chordRow = [...container.querySelectorAll('.whitespace-pre')]
- .find((el) => /^C\s+G$/.test(el.textContent));
- expect(chordRow).toBeTruthy();
- expect(chordRow.textContent.indexOf('G')).toBe(6);
+ it('wraps ChordPro words with their chord row at the original columns', () => {
+ const { container } = render(<TabSheetView text="[C]Hello [G]world" />);
+ const chunks = [...container.querySelectorAll('[data-chord-lyric-chunk]')];
+ expect(chunks.map((chunk) => [chunk.firstChild.textContent, chunk.lastChild.textContent]))
+ .toEqual([['C ', 'Hello '], ['G', 'world']]);
+ });
+
+ it('keeps mid-word chords, rhythm marks and trailing changes intact in pasted pairs', () => {
+ const { container } = render(<TabSheetView text={' Am | G/B F\nPaper lanterns glow'} />);
+ const chunks = [...container.querySelectorAll('[data-chord-lyric-chunk]')];
+ expect(chunks.map((chunk) => chunk.lastChild.textContent).join('')).toBe('Paper lanterns glow');
+ expect(chunks.map((chunk) => chunk.firstChild.textContent).join('')).toBe(' Am | G/B F');
+ expect(screen.getByRole('button', { name: 'Am' }).closest('[data-chord-lyric-chunk]').lastChild.textContent).toBe('Paper ');
+ expect(screen.getByRole('button', { name: 'G/B' }).closest('[data-chord-lyric-chunk]').lastChild.textContent).toBe('lanterns ');
+ fireEvent.click(screen.getByRole('button', { name: 'G/B' }));
+ const dialog = screen.getByRole('dialog', { name: 'G/B chord voicing' });
+ expect(dialog.parentElement).toBe(document.body);
+ expect(dialog.querySelector('svg')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Close chord diagram' }));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'G/B' }));
+ });
+
+ it('makes room for adjacent ChordPro changes without moving their syllables apart', () => {
+ const { container } = render(<TabSheetView text="[Cmaj7]a[Am]b glows" />);
+ const chunks = [...container.querySelectorAll('[data-chord-lyric-chunk]')];
+ expect(chunks[0].firstChild.textContent).toBe('Cmaj7 Am');
+ expect(chunks[0].lastChild.textContent).toBe(`a${'\u00a0'.repeat(5)}b `);
});
it('applies the font size scale', () => {
@@ -168,7 +189,7 @@ describe('TabSheetView', () => {
expect(screen.queryByText('e|--3--2--|')).toBeNull();
// The 2-line SAMPLE staff isn't identifiably guitar — generic label.
expect(screen.getByText(/tablature — switch to Guitar or Ukulele view/)).toBeTruthy();
- const expand = screen.getByRole('button', { name: 'Show tablature staff (section 4)' });
+ const expand = screen.getByRole('button', { name: 'Show tablature staff (section 3)' });
const staffId = expand.getAttribute('aria-controls');
expect(expand.getAttribute('aria-expanded')).toBe('false');
expect(document.getElementById(staffId)).toBeNull();
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index e8387d301e..ba0a3314ad 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -228,7 +228,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `tribeCadence.js` | Re-export of `server/lib/tribeCadence.js` — the single authoritative Tribe care-cadence rules shared by the page, the Care dashboard widget, and the server. |
| `streakGlyph.js` | `streakGlyph(streak)` — the single POST streak emoji (✨ / ⚡ / 🔥 by day count) shared by the POST launcher, Morse trainer, daily widget, and dashboard streak widget. |
| `syncCounts.js` | Directional pending-sync counts for the Instances federation cards. `directionalCounts({ localMax, peerMax, ourCursor, peerCursorForUs })` → `{ toPull, toPush }` (each a non-negative Number, or `null` when unknown) from monotonic change-log seqs; `diffSeq(ahead, behind)` is the BigInt-safe clamp-at-zero subtraction (handles numeric strings past `MAX_SAFE_INTEGER`); `describeDirectional({ toPull, toPush })` renders the plain-language `{ state, text }` ("in sync" / "N to pull · M to push" / "checking…"). No React — `SyncStatusBadge` drives it. |
-| `tabNotation.js` | Guitar-tab / chord-sheet / ChordPro text parser for SongBook (`/songbook`). `parseTabSheet(text)` → `{ lines, meta, errors }` classifying each line (`section`/`chords`/`lyric`/`tabstaff`/`chordlyric`/`blank`/`text`) with chord names + column offsets, plus ChordPro meta (`{title:}`/`{artist:}`/`{key:}`/`{capo:}`); `detectFormat(text)` → `'chordpro' \| 'tab' \| 'plain'`; `normalizePastedTab(text)` cleans HTML remnants/entities, CRLF, tabs→spaces, blank-line runs; `transposeChordName(name, n)` / `transposeText(text, n)` transpose chord symbols (slash chords, sensible sharp/flat spelling, column-preserving on chord lines); `TAB_ARTICULATIONS` documents tab-staff technique characters for the viewer legend; `CHORD_TOKEN_RE` exported for reuse, plus `NOTE_TO_PC` / `spellPitchClass` exported minimally so `chordShapes.js` derives voicings from the same pitch-class tables. Forgiving — never throws, unknown lines classify as `text`. NOT the lead-sheet parser (`scoreNotation.js`). |
+| `tabNotation.js` | Guitar-tab / chord-sheet / ChordPro text parser for SongBook (`/songbook`). `parseTabSheet(text)` → `{ lines, meta, errors }` classifying each line (`section`/`chords`/`lyric`/`tabstaff`/`chordlyric`/`blank`/`text`) with chord names + column offsets, plus ChordPro meta (`{title:}`/`{artist:}`/`{key:}`/`{capo:}`); `detectFormat(text)` → `'chordpro' \| 'tab' \| 'plain'`; `normalizePastedTab(text)` cleans HTML remnants/entities, CRLF, tabs→spaces, blank-line runs; `transposeChordName(name, n)` / `transposeText(text, n)` transpose chord symbols (slash chords, sensible sharp/flat spelling, column-preserving on chord lines); `chordLineSegments`, `pairedLineChunks`, and `chordLyricRows` build aligned, word-wrapping chord/lyric display rows; `TAB_ARTICULATIONS` documents tab-staff technique characters for the viewer legend; `CHORD_TOKEN_RE` exported for reuse, plus `NOTE_TO_PC` / `spellPitchClass` exported minimally so `chordShapes.js` derives voicings from the same pitch-class tables. Forgiving — never throws, unknown lines classify as `text`. NOT the lead-sheet parser (`scoreNotation.js`). |
| `tailnetPeer.js` | `isTailnetPeer(peer)` — is this registered peer reachable ONLY over the tailnet? A faithful port of `server/lib/tailnetPeer.js` (MagicDNS `.ts.net`, the 100.64.0.0/10 CGNAT range with every octet range-checked, and the `fd7a:115c:a1e0::/48` ULA; an explicit non-tailnet `host` overrides a tailnet-looking `address`). FAIL-CLOSED — anything not positively recognized is not tailnet. Used to keep the unattended-render-routing picker from OFFERING a peer the server would refuse under ADR [federated visual prompts](../../../docs/decisions/2026-08-20-federated-visual-prompts.md) rule 5; the server stays authoritative and refuses such a route both on save and on every enqueue. Keep the table in `tailnetPeer.test.js` identical to the server suite’s. |
| `terminalDictation.js` | Voice-dictation/IME bridge for the Shell's xterm.js terminal. Apple dictation streams progressively refined guesses and *replaces* what it already typed; xterm forwards each insertion and drops the matching deletions, so the PTY accumulates a garble (`determin` + `determine` + `determines`…). `attachDictationBridge(terminal, sendData)` binds capture-phase listeners on `terminal.element` — ahead of xterm's own textarea listeners, which it stops — and forwards a diff instead: `TERMINAL_DEL` (`0x7f`) per dropped character, then the added text. `sendData` returns `false` to report a dropped send, which leaves the mirror where the PTY actually is. Paths that reach the PTY some other way (a keystroke xterm handles itself, paste, blur, composition end, screen-reader mode) resync the mirror without emitting. `planFieldEdit(mirror, next, floor)` → `{ data, committed }` is the pure core: `floor` is the prefix we did not write and must never rewind through, and `committed` (what the PTY holds afterward, which is *not* the field's value when the floor blocked a rewind) is what the caller must track. The prefix scan never splits a surrogate pair — cutting between the halves of an astral character would send a lone surrogate that serializes to `U+FFFD`. Wired in `useShellSession`; the test suite pins the seam against a real `Terminal`. |
| `terminalScroll.js` | Scrolling the Shell terminal by touch, wheel, and page controls. xterm 6 binds **no touch handlers at all**, and a TUI’s ALTERNATE screen buffer has no terminal scrollback, so `scrollLines()` clamps to a no-op there. Normal shell scrollback uses `scrollLines()`; alternate-screen wheel gestures are captured before xterm’s mouse listener and translated to standard PageUp/PageDown input, which OpenCode supports for its message viewport, while apps that explicitly enable terminal mouse tracking keep xterm’s native wheel path. `attachTerminalTouchScroll(terminal)` (→ detach fn) reserves one-finger panning while preserving pinch zoom and adds bounded flick momentum to normal shell scrollback; mouse-aware apps receive row-granular wheel events at the touch coordinates, and only apps without wheel support fall back to page keys. `attachTerminalWheelScroll(terminal)` handles native wheel input, and `scrollTerminalPage(terminal, direction)` powers the `SCROLL_KEYS` buttons. `measureTerminalGeometry(terminal)` takes one layout read per gesture; `planTouchScrollSteps(accumPx, rowHeightPx)` is the pure sub-row-remainder core. Wired in `useShellSession`. |
diff --git a/client/src/lib/tabNotation.js b/client/src/lib/tabNotation.js
index 9927e2f2f8..d63be0a580 100644
--- a/client/src/lib/tabNotation.js
+++ b/client/src/lib/tabNotation.js
@@ -521,3 +521,63 @@ export const transposeText = (text, n) => {
})
.join('\n');
};
+
+// 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.
+export const chordLineSegments = (text, chords) => {
+ const segments = [];
+ let cursor = 0;
+ 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, chordIndex });
+ cursor = col + name.length;
+ });
+ if (cursor < text.length) segments.push({ text: text.slice(cursor), chord: false });
+ return segments;
+};
+
+// Wrap only at word boundaries that do not cut through a chord or rhythm mark.
+// Each flex item owns BOTH rows, so browser reflow (including font-size changes)
+// cannot separate a chord from the syllable at its original column.
+export const pairedLineChunks = (lyric, chordText, chords) => {
+ const length = Math.max(lyric.length, chordText.length);
+ const chunks = [];
+ let start = 0;
+ for (let end = 1; end <= length; end += 1) {
+ const wordBoundary = /[ \t]/.test(lyric[end - 1] ?? ' ') && !/[ \t]/.test(lyric[end] ?? ' ');
+ const chordBoundary = /\s/.test(chordText[end - 1] ?? ' ') || /\s/.test(chordText[end] ?? ' ');
+ if (end !== length && !(wordBoundary && chordBoundary)) continue;
+ const localChords = chords.flatMap((chord, chordIndex) =>
+ chord.col >= start && chord.col < end ? [{ ...chord, col: chord.col - start, chordIndex }] : []);
+ const segments = chordLineSegments(chordText.slice(start, end), localChords)
+ .map((segment) => segment.chord
+ ? { ...segment, chordIndex: localChords[segment.chordIndex].chordIndex }
+ : segment);
+ chunks.push({ lyric: lyric.slice(start, end), segments });
+ start = end;
+ }
+ return chunks;
+};
+
+// Adjacent ChordPro symbols may share a lyric column. Insert matching space in
+// both rows when their names collide, keeping subsequent anchors aligned.
+// Nonbreaking lyric padding prevents a new wrap point inside the original word.
+export const chordLyricRows = (line) => {
+ let lyric = line.text;
+ let chordText = '';
+ let shift = 0;
+ const chords = line.chords.map((chord) => {
+ let col = chord.col + shift;
+ if (chordText.length > col) {
+ const pad = chordText.length + 1 - col;
+ lyric = lyric.slice(0, col) + '\u00a0'.repeat(pad) + lyric.slice(col);
+ shift += pad;
+ col += pad;
+ }
+ chordText = chordText.padEnd(col) + chord.name;
+ return { ...chord, col };
+ });
+ return { lyric, chordText, chords };
+};
diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsx
index 9d30a5d371..b3b6e53e41 100644
--- a/client/src/pages/SongBookViewer.test.jsx
+++ b/client/src/pages/SongBookViewer.test.jsx
@@ -119,7 +119,8 @@ describe('SongBookViewer', () => {
expect(await screen.findByText('Example Song')).toBeTruthy();
// Section header + lyric line from parseTabSheet.
expect(await screen.findByText('Chorus')).toBeTruthy();
- expect(screen.getByText('Nonsense words here')).toBeTruthy();
+ expect([...screen.getByText('Nonsense').closest('[data-chord-lyric-pair]').children]
+ .map((chunk) => chunk.lastChild.textContent).join('')).toBe('Nonsense words here');
// Meta badges
expect(screen.getByText('Key C')).toBeTruthy();
expect(screen.getByText('Capo 2')).toBeTruthy();
@@ -965,7 +966,8 @@ K: o - - - - - o -`;
// mode" is asserted on the form going away, not on the sheet appearing.
await waitFor(() => expect(screen.queryByLabelText('Content')).toBeNull());
expect(screen.queryByText(/Discard your unsaved changes/)).toBeNull();
- expect(screen.getByText('Nonsense words here')).toBeTruthy();
+ expect([...screen.getByText('Nonsense').closest('[data-chord-lyric-pair]').children]
+ .map((chunk) => chunk.lastChild.textContent).join('')).toBe('Nonsense words here');
});
it('confirms before the View toggle discards unsaved edits', async () => {