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: fit SongBook autoscroll to a per-song target scroll time (#4100)

[._.]/ Adam Eivy93192c5bd22a
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 4a9dc9efde..b29b69340e 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -122,7 +122,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useUrlParams` | `[searchParams, updateParams]` — `updateParams(patch, { replace })` merges a patch into the query string and deletes keys set to `null`/`undefined`/`''` so a cleared filter leaves the URL clean. Reads the live params off a ref (react-router's functional updater is closure-stale) and is referentially stable. | Any page whose filter/sort/selection state lives in the URL (Catalog, MediaCollections, Media3D) — don't re-roll the merge-and-prune loop. |
| `useValidTab` | Resolve the active tab from the `:tab` URL param against a TABS list, falling back to a default on invalid/missing. | Any tabbed page whose tab lives in the URL — don't re-roll the `new Set(TABS.map(...))` guard. |
| `useAsyncAction` | `running` state + toast-on-error. | Buttons that await an async action. |
-| `useAutoscroll` | rAF autoscroll for a scrollable container: advances `scrollTop` by `pxPerSec`, auto-stops at the bottom, pauses on user wheel/touchmove, live speed changes via ref. Returns `{ playing, toggle, stop, pxPerSec, setPxPerSec }`. | SongBook play view; any teleprompter-style surface. |
+| `useAutoscroll` | rAF autoscroll for a scrollable container: advances `scrollTop` by `pxPerSec`, auto-stops at the bottom, pauses on user wheel/touchmove, live speed changes via ref. `fitToDuration(sec)` solves the speed for a target run time from the measured scroll travel (returns the applied px/s, or `null` when there is nothing to scroll). Returns `{ playing, toggle, stop, pxPerSec, setPxPerSec, fitToDuration }`. | SongBook play view; any teleprompter-style surface. |
| `useWakeLock` | Holds a screen wake lock (`navigator.wakeLock`) while `active` is true; releases on unmount/inactive, re-acquires on visibilitychange; no-op where unsupported. | Hands-free surfaces that must keep the screen on (SongBook autoscroll). |
## Storage & persistence
diff --git a/client/src/hooks/useAutoscroll.js b/client/src/hooks/useAutoscroll.js
index ef00a6b197..42db19c839 100644
--- a/client/src/hooks/useAutoscroll.js
+++ b/client/src/hooks/useAutoscroll.js
@@ -12,11 +12,20 @@ import useMounted from './useMounted';
* - Speed changes apply live (read through a ref) without restarting the loop.
* - rAF is cancelled and listeners detach on pause/unmount; a `mountedRef`
* guards the auto-stop setState so a frame that lands after unmount is inert.
+ * - `fitToDuration(seconds)` solves the speed for a target run time instead of
+ * asking the user to guess px/s (see below).
*
* containerRef — ref to the scrollable element (must have overflow-y-auto).
- * Returns { playing, toggle, stop, pxPerSec, setPxPerSec }.
+ * minPxPerSec / maxPxPerSec bound what `fitToDuration` may set — pass the same
+ * bounds the caller's speed control uses, so a fitted speed is always a value
+ * that control can also represent.
+ *
+ * Returns { playing, toggle, stop, pxPerSec, setPxPerSec, fitToDuration }.
*/
-export default function useAutoscroll(containerRef, { initialPxPerSec = 30 } = {}) {
+export default function useAutoscroll(
+ containerRef,
+ { initialPxPerSec = 30, minPxPerSec = 1, maxPxPerSec = Number.MAX_SAFE_INTEGER } = {},
+) {
const [playing, setPlaying] = useState(false);
const [pxPerSec, setPxPerSec] = useState(initialPxPerSec);
const pxPerSecRef = useRef(pxPerSec);
@@ -74,5 +83,39 @@ export default function useAutoscroll(containerRef, { initialPxPerSec = 30 } = {
const toggle = useCallback(() => setPlaying((p) => !p), []);
const stop = useCallback(() => setPlaying(false), []);
- return { playing, toggle, stop, pxPerSec, setPxPerSec };
+ /**
+ * "Fit to duration": set the speed so the container scrolls from its current
+ * TOP to its bottom in `durationSec`.
+ *
+ * The distance is `scrollHeight - clientHeight` — the scrollable travel — not
+ * the raw `scrollHeight`: the loop stops when `scrollTop` reaches the bottom,
+ * so pricing the visible viewport into the trip would finish early by exactly
+ * one screenful (a short sheet on a tall screen, badly).
+ *
+ * Measured at call time, so it reflects the CURRENT layout (font size,
+ * transpose re-wrap, window size, an orientation flip). Callers re-fit after
+ * anything that reflows the sheet rather than caching the result.
+ *
+ * Rounded to whole px/s and clamped into [minPxPerSec, maxPxPerSec] so the
+ * value is one the caller's speed control can display and step; a clamped fit
+ * therefore takes longer/shorter than asked, which the caller can detect by
+ * comparing the return value against its own bounds.
+ *
+ * @param {number} durationSec target seconds for the full scroll
+ * @returns {number|null} the applied px/s, or null when there is nothing to
+ * fit — no container, a non-positive/non-finite duration, or content that
+ * already fits on screen (zero travel). Null is the "couldn't fit" sentinel,
+ * never a silent no-op at some default speed.
+ */
+ const fitToDuration = useCallback((durationSec) => {
+ const el = containerRef.current;
+ if (!el || !Number.isFinite(durationSec) || durationSec <= 0) return null;
+ const distance = el.scrollHeight - el.clientHeight;
+ if (distance <= 0) return null;
+ const fitted = Math.min(maxPxPerSec, Math.max(minPxPerSec, Math.round(distance / durationSec)));
+ setPxPerSec(fitted);
+ return fitted;
+ }, [containerRef, minPxPerSec, maxPxPerSec]);
+
+ return { playing, toggle, stop, pxPerSec, setPxPerSec, fitToDuration };
}
diff --git a/client/src/hooks/useAutoscroll.test.jsx b/client/src/hooks/useAutoscroll.test.jsx
index c83fbbbe75..098d25aa85 100644
--- a/client/src/hooks/useAutoscroll.test.jsx
+++ b/client/src/hooks/useAutoscroll.test.jsx
@@ -90,6 +90,75 @@ describe('useAutoscroll', () => {
expect(listeners.wheel).toBeUndefined();
});
+ describe('fitToDuration (#4100)', () => {
+ it('solves the speed from the SCROLLABLE travel, not the raw scrollHeight', () => {
+ const { el } = makeContainer(); // 1000 tall in a 200 viewport → 800px of travel
+ const ref = { current: el };
+ const { result } = renderHook(() => useAutoscroll(ref, { initialPxPerSec: 30 }));
+
+ let applied;
+ act(() => { applied = result.current.fitToDuration(40); }); // 800 / 40
+ expect(applied).toBe(20);
+ expect(result.current.pxPerSec).toBe(20);
+
+ // And it really takes that long: run the loop in 0.5s frames (the hook's
+ // own tab-suspend clamp) until it auto-stops at the bottom. 40s wall clock
+ // is the whole point — pricing the viewport in (1000/40 = 25px/s) would
+ // arrive a full screenful early, at 32s.
+ act(() => result.current.toggle());
+ let ts = 0;
+ act(() => flush(ts));
+ while (result.current.playing && ts < 120_000) {
+ ts += 500;
+ act(() => flush(ts));
+ }
+ expect(result.current.playing).toBe(false);
+ expect(ts).toBe(40_000);
+ });
+
+ it('clamps into the caller-supplied speed bounds', () => {
+ const { el } = makeContainer();
+ const ref = { current: el };
+ const { result } = renderHook(() => useAutoscroll(ref, { minPxPerSec: 5, maxPxPerSec: 150 }));
+
+ // 800px in an hour would be 0.2px/s — floored at the slider's minimum.
+ let slow;
+ act(() => { slow = result.current.fitToDuration(3600); });
+ expect(slow).toBe(5);
+ expect(result.current.pxPerSec).toBe(5);
+
+ // 800px in 1s would be 800px/s — capped at the slider's maximum.
+ let fast;
+ act(() => { fast = result.current.fitToDuration(1); });
+ expect(fast).toBe(150);
+ expect(result.current.pxPerSec).toBe(150);
+ });
+
+ it('returns null and leaves the speed alone when there is nothing to scroll', () => {
+ const { el } = makeContainer();
+ el.scrollHeight = 200; // content fits the viewport exactly → zero travel
+ const ref = { current: el };
+ const { result } = renderHook(() => useAutoscroll(ref, { initialPxPerSec: 30 }));
+
+ let applied;
+ act(() => { applied = result.current.fitToDuration(60); });
+ expect(applied).toBe(null);
+ expect(result.current.pxPerSec).toBe(30);
+ });
+
+ it('returns null for a missing container or a non-positive/non-finite duration', () => {
+ const { el } = makeContainer();
+ const detached = renderHook(() => useAutoscroll({ current: null }));
+ act(() => { expect(detached.result.current.fitToDuration(60)).toBe(null); });
+
+ const { result } = renderHook(() => useAutoscroll({ current: el }, { initialPxPerSec: 30 }));
+ for (const bad of [0, -60, NaN, Infinity, null, undefined, '60']) {
+ act(() => { expect(result.current.fitToDuration(bad), String(bad)).toBe(null); });
+ }
+ expect(result.current.pxPerSec).toBe(30);
+ });
+ });
+
it('cancels the rAF loop on unmount', () => {
const { el } = makeContainer();
const ref = { current: el };
diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsx
index 8a1950ce30..3f49c3cd29 100644
--- a/client/src/pages/SongBookViewer.jsx
+++ b/client/src/pages/SongBookViewer.jsx
@@ -8,9 +8,12 @@
* Two URL-param-driven modes (linkable-routes convention):
* - PLAY (default): the rendered sheet (TabSheetView — or DrumSheetView plus a
* drum transport bar when the content format is `drum`, #3115) with an
- * Ultimate-Guitar-style controls bar — autoscroll play/pause + speed
- * (suppressed for a drum chart, which scrolls itself horizontally under its
- * own playhead and would otherwise carry two rival "play" buttons),
+ * Ultimate-Guitar-style controls bar — autoscroll play/pause + speed, plus a
+ * "fit to duration" button for a song carrying a `scrollDurationSec` target
+ * (#4100: solves px/s from the sheet's CURRENT rendered travel, so it re-fits
+ * after a font-size/transpose reflow)
+ * (all suppressed for a drum chart, which scrolls itself horizontally under
+ * its own playhead and would otherwise carry two rival "play" buttons),
* transpose ± (render-time transposeText, never mutates stored text; offset
* persisted per song via safeStorage), font size ±, an instrument-view
* toggle (?view=guitar|ukulele|piano — chord diagrams only, render-only,
@@ -27,7 +30,8 @@
* "All songs" link, a sidebar link, ⌘K, voice nav, Back, tab close) via
* useUnsavedChangesGuard (#3958).
*
- * Keyboard (play mode): space play/pause, +/- speed, [ ] transpose, 0 top.
+ * Keyboard (play mode): space play/pause, +/- speed, [ ] transpose, 0 top,
+ * f fit-to-duration (bound only when the song has a target).
* For a drum chart the same keys drive the kit transport instead: space
* play/stop, +/- BPM ±1, [ ] set the loop ends at the current bar.
* A screen wake lock holds while autoscroll plays — or while the kit plays
@@ -38,7 +42,7 @@ import { useState, useEffect, useMemo, useRef, useCallback } from 'react';
import { useParams, useNavigate, Link } from 'react-router';
import {
ListMusic, ArrowLeft, Save, Trash2, Pencil, Eye, Play, Pause, Plus, Minus,
- ExternalLink, Paperclip, Upload, FileX2,
+ ExternalLink, Paperclip, Upload, FileX2, Timer,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import FilePickerButton from '../components/ui/FilePickerButton';
@@ -67,7 +71,7 @@ import useUnsavedChangesGuard from '../hooks/useUnsavedChangesGuard';
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 { formatBytes, formatDurationSec } from '../utils/formatters';
import { isHttpUrl } from '../utils/urlNormalize';
import { readFileAsBase64, JSON_UPLOAD_MAX_FILE_SIZE } from '../utils/fileUpload';
import {
@@ -82,6 +86,22 @@ const FONT_MAX = 1.75;
const FONT_STEP = 0.125;
const SPEED_MIN = 5;
const SPEED_MAX = 150;
+// "Fit to duration" target bounds — client mirror of `scrollDurationSec` in
+// server/lib/brainValidation.js (songInputSchema). Keep the two in step: a value
+// the input accepts but the schema rejects 400s the whole save.
+const SCROLL_DURATION_MIN = 15;
+const SCROLL_DURATION_MAX = 3600;
+
+// Scroll-duration input (a string, like every number input) → what a save sends:
+// null for "no target" (blank, or anything non-numeric), otherwise a whole
+// second count inside the schema bounds. null is a real value here — it CLEARS a
+// stored target on PATCH — so it must never collapse into "field absent".
+const parseScrollDurationSec = (raw) => {
+ if (raw === '' || raw === null || raw === undefined) return null;
+ const n = Number(raw);
+ if (!Number.isFinite(n)) return null;
+ return Math.max(SCROLL_DURATION_MIN, Math.min(SCROLL_DURATION_MAX, Math.trunc(n)));
+};
// Song record → flat editable draft (tags joined for the text input).
const toDraft = (song) => ({
@@ -95,6 +115,9 @@ const toDraft = (song) => ({
tags: Array.isArray(song.tags) ? song.tags.join(', ') : '',
sourceUrl: song.sourceUrl || '',
notes: song.notes || '',
+ // '' is the form's "no target" — the record stores null (or has no key at all
+ // on a song written before the field existed / synced from an older peer).
+ scrollDurationSec: song.scrollDurationSec ?? '',
format: song.content?.format || 'tab',
text: song.content?.text || '',
});
@@ -111,6 +134,10 @@ const parseTags = (raw) => raw.split(',').map((t) => t.trim()).filter(Boolean);
const TRIMMED_DRAFT_FIELDS = ['title', 'artist', 'key', 'tuning', 'sourceUrl'];
const normalizeDraftField = (draft, k) => {
if (k === 'capo') return Number(draft.capo || 0);
+ // Compare the SAVED value, not the raw text: '210' and '0210' (and '' vs a
+ // sub-minimum '3', which clamps) both save the same, so retyping one isn't
+ // unsaved work. Null (no target) compares equal to itself.
+ if (k === 'scrollDurationSec') return parseScrollDurationSec(draft.scrollDurationSec);
// Joined on a comma — the one character parseTags strips from every tag, so
// two different tag lists can never normalize to the same string.
if (k === 'tags') return parseTags(draft.tags).join(',');
@@ -227,7 +254,12 @@ export default function SongBookViewer() {
// --- Autoscroll + wake lock
const scrollRef = useRef(null);
- const { playing, toggle, stop, pxPerSec, setPxPerSec } = useAutoscroll(scrollRef);
+ // The fit preset may only land on a speed the slider below can also show, so
+ // the hook clamps to the slider's own bounds.
+ const { playing, toggle, stop, pxPerSec, setPxPerSec, fitToDuration } = useAutoscroll(
+ scrollRef,
+ { minPxPerSec: SPEED_MIN, maxPxPerSec: SPEED_MAX },
+ );
// Presence lookup failed → show the record's own synced metadata with
// presence unknown (rendered as plain links; only an explicit present:false
@@ -281,6 +313,20 @@ export default function SongBookViewer() {
if (scrollRef.current) scrollRef.current.scrollTop = 0;
}, [stop]);
+ // --- "Fit to duration" preset (#4100). The song carries a target run time
+ // (scrollDurationSec); the SPEED it implies depends on the rendered height, so
+ // it's solved on demand from the live container rather than stored. A target
+ // the bounds can't honour (a very long time on a short sheet) clamps to the
+ // slider's ends — visible in the slider, so no extra warning.
+ const fitDurationSec = Number.isFinite(song?.scrollDurationSec) ? song.scrollDurationSec : null;
+ const fitToSongDuration = useCallback(() => {
+ // null back from the hook = nothing to fit (the sheet fits on screen), which
+ // must not read as "fitted at some default speed".
+ if (fitToDuration(fitDurationSec) == null) {
+ toast.error('Nothing to autoscroll — this sheet already fits on screen');
+ }
+ }, [fitToDuration, fitDurationSec]);
+
// Play-mode shortcuts. A drum chart rebinds them onto the kit transport (space
// play/stop, +/- BPM, [ ] loop ends, m mutes the click) since transpose/
// scroll-speed don't apply.
@@ -302,6 +348,9 @@ export default function SongBookViewer() {
'[': () => setTranspose(transpose - 1),
']': () => setTranspose(transpose + 1),
'0': scrollToTop,
+ // Only bound when the song HAS a target — otherwise the key would toast
+ // "nothing to fit" at a user who never set one.
+ ...(fitDurationSec != null ? { f: fitToSongDuration } : {}),
};
useKeyboardShortcuts(!editing && !!song, isDrum ? drumShortcuts : sheetShortcuts);
@@ -333,6 +382,9 @@ export default function SongBookViewer() {
tags: parseTags(draft.tags),
sourceUrl: draft.sourceUrl.trim(),
notes: draft.notes,
+ // Always sent, including as an explicit null — clearing the input has to
+ // clear the stored target, and an omitted key would preserve it instead.
+ scrollDurationSec: parseScrollDurationSec(draft.scrollDurationSec),
content: { format: draft.format, text: draft.text },
}, { silent: true });
setSong(updated);
@@ -608,6 +660,20 @@ export default function SongBookViewer() {
<label htmlFor="song-edit-tuning" className={labelClass}>Tuning</label>
<input id="song-edit-tuning" type="text" value={draft.tuning} onChange={(e) => setDraft({ ...draft, tuning: e.target.value })} placeholder="e.g. Drop D" className={inputClass} />
</div>
+ <div>
+ <label htmlFor="song-edit-scroll-duration" className={labelClass}>Scroll time (seconds)</label>
+ <input
+ id="song-edit-scroll-duration"
+ type="number"
+ min={SCROLL_DURATION_MIN}
+ max={SCROLL_DURATION_MAX}
+ step="5"
+ value={draft.scrollDurationSec}
+ onChange={(e) => setDraft({ ...draft, scrollDurationSec: e.target.value })}
+ placeholder="e.g. 210"
+ className={inputClass}
+ />
+ </div>
<div>
<label htmlFor="song-edit-tags" className={labelClass}>Tags (comma-separated)</label>
<input id="song-edit-tags" type="text" value={draft.tags} onChange={(e) => setDraft({ ...draft, tags: e.target.value })} placeholder="e.g. campfire, fingerstyle" className={inputClass} />
@@ -737,6 +803,22 @@ export default function SongBookViewer() {
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>
)}
diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsx
index c50dfa54a3..9e2d6634e6 100644
--- a/client/src/pages/SongBookViewer.test.jsx
+++ b/client/src/pages/SongBookViewer.test.jsx
@@ -578,6 +578,105 @@ K: o - - - - - o -`;
expect('attachments' in patch).toBe(false);
});
+ describe('fit-to-duration autoscroll preset (#4100)', () => {
+ // jsdom lays nothing out, so the scroll container reports 0/0 — stub the two
+ // metrics the preset measures. 2000 tall in a 500 viewport = 1500px of travel.
+ const stubScrollMetrics = (scrollHeight, clientHeight) => {
+ const sh = vi.spyOn(Element.prototype, 'scrollHeight', 'get').mockReturnValue(scrollHeight);
+ const ch = vi.spyOn(Element.prototype, 'clientHeight', 'get').mockReturnValue(clientHeight);
+ return () => { sh.mockRestore(); ch.mockRestore(); };
+ };
+
+ it('hides the Fit button for a song with no scroll-time target', async () => {
+ renderPage();
+ expect(await screen.findByLabelText('Autoscroll speed')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /^Fit autoscroll/ })).toBeNull();
+ });
+
+ it('sets the speed from the sheet travel over the target time', async () => {
+ const restore = stubScrollMetrics(2000, 500);
+ api.getSong.mockResolvedValue(song({ scrollDurationSec: 100 }));
+ renderPage();
+ // The button announces the target in M:SS.
+ const fit = await screen.findByRole('button', { name: 'Fit autoscroll to 1:40' });
+ const speed = screen.getByLabelText('Autoscroll speed');
+ expect(speed.value).toBe('30'); // hook default, untouched until the click
+
+ toast.error.mockClear(); // the shared module mock outlives earlier tests
+ fireEvent.click(fit);
+ // 1500px of travel / 100s = 15px/s. Measuring raw scrollHeight (2000/100 =
+ // 20) would land the sheet at the bottom a full screenful early.
+ expect(speed.value).toBe('15');
+ expect(toast.error).not.toHaveBeenCalled();
+ restore();
+ });
+
+ it('clamps a target the speed slider cannot honour', async () => {
+ const restore = stubScrollMetrics(2000, 500);
+ api.getSong.mockResolvedValue(song({ scrollDurationSec: 3600 }));
+ renderPage();
+ fireEvent.click(await screen.findByRole('button', { name: 'Fit autoscroll to 60:00' }));
+ // 1500px over an hour is 0.4px/s — floored at the slider's own minimum,
+ // never set to an off-scale value the control can't represent.
+ const speed = screen.getByLabelText('Autoscroll speed');
+ expect(speed.value).toBe('5');
+ expect(Number(speed.min)).toBe(5);
+ restore();
+ });
+
+ it('says so instead of silently "fitting" when the sheet fits on screen', async () => {
+ const restore = stubScrollMetrics(400, 400); // zero travel
+ api.getSong.mockResolvedValue(song({ scrollDurationSec: 100 }));
+ renderPage();
+ const fit = await screen.findByRole('button', { name: 'Fit autoscroll to 1:40' });
+ toast.error.mockClear();
+ fireEvent.click(fit);
+ expect(toast.error).toHaveBeenCalledWith('Nothing to autoscroll — this sheet already fits on screen');
+ expect(screen.getByLabelText('Autoscroll speed').value).toBe('30'); // unchanged
+ restore();
+ });
+
+ it('saves a typed scroll time and clears it with an explicit null', async () => {
+ api.updateSong.mockImplementation((_id, patch) => Promise.resolve(song({ ...patch })));
+ renderPage('/songbook/abc?mode=edit');
+ const input = await screen.findByLabelText('Scroll time (seconds)');
+ expect(input.value).toBe(''); // no target on the fixture
+
+ fireEvent.change(input, { target: { value: '210' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(api.updateSong).toHaveBeenCalled());
+ expect(api.updateSong.mock.calls[0][1].scrollDurationSec).toBe(210);
+
+ // Clearing sends null (a real clear), not an omitted key — which the PATCH
+ // merge would read as "leave the stored target alone".
+ fireEvent.change(screen.getByLabelText('Scroll time (seconds)'), { target: { value: '' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(api.updateSong).toHaveBeenCalledTimes(2));
+ const cleared = api.updateSong.mock.calls[1][1];
+ expect('scrollDurationSec' in cleared).toBe(true);
+ expect(cleared.scrollDurationSec).toBe(null);
+ });
+
+ it('treats a retyped scroll time as clean (unsaved-changes guard)', async () => {
+ api.getSong.mockResolvedValue(song({ scrollDurationSec: 210 }));
+ renderPage('/songbook/abc?mode=edit');
+ const input = await screen.findByLabelText('Scroll time (seconds)');
+ expect(input.value).toBe('210');
+ fireEvent.change(input, { target: { value: '120' } });
+ fireEvent.change(input, { target: { value: '210' } });
+ fireEvent.click(screen.getByRole('button', { name: 'View' }));
+ await waitFor(() => expect(screen.queryByLabelText('Content')).toBeNull());
+ expect(screen.queryByText(/Discard your unsaved changes/)).toBeNull();
+ });
+
+ it('prompts before dropping an edited scroll time', async () => {
+ renderPage('/songbook/abc?mode=edit');
+ fireEvent.change(await screen.findByLabelText('Scroll time (seconds)'), { target: { value: '210' } });
+ fireEvent.click(screen.getByRole('button', { name: 'View' }));
+ expect(await screen.findByText('Discard your unsaved changes to this song?')).toBeTruthy();
+ });
+ });
+
describe('unsaved-edit guard (#3902)', () => {
const editSheet = async (value = 'Edited sheet text') => {
const textarea = await screen.findByLabelText('Content');
diff --git a/docs/plans/2026-07-15-songbook.md b/docs/plans/2026-07-15-songbook.md
index 131d407fba..1e838f3ea3 100644
--- a/docs/plans/2026-07-15-songbook.md
+++ b/docs/plans/2026-07-15-songbook.md
@@ -224,6 +224,13 @@ are kept as the original design record.
- **`scrollDurationSec` dropped from `songInputSchema`.** Speculative in v1
(nothing consumed it). The "fit to duration" autoscroll preset that would
re-add it is parked in PLAN.md under "SongBook follow-ups".
+ **Re-added in #4100** now that a UI consumes it: the field is back on
+ `songInputSchema` (nullable, `null` = no target), the Edit form carries a
+ "Scroll time (seconds)" input, and the play-view controls bar grows a Fit
+ button (also the `f` key) that calls `useAutoscroll`'s new
+ `fitToDuration(sec)` — px/s solved from the container's *scrollable travel*
+ (`scrollHeight - clientHeight`, not raw `scrollHeight`, which would finish a
+ screenful early) at click time, clamped to the speed slider's own bounds.
- **`songAttachmentSchema` / `songRecordSchema` deleted** — dead exports;
attachment metadata stays server-managed with no client-suppliable schema.
- **Shared helpers extracted:** entity decoding via `decodeXmlEntities`
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index bcc25742c2..b62a464fed 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -647,7 +647,20 @@ export const songInputSchema = z.object({
tuning: z.string().trim().max(40).optional().default(''),
sourceUrl: z.string().trim().max(2000).optional().default(''),
content: songContentSchema.optional().default({ format: 'tab', text: '' }),
- notes: z.string().max(5000).optional().default('')
+ notes: z.string().max(5000).optional().default(''),
+ // "Fit to duration" autoscroll target: how many seconds the play view should
+ // take to scroll the sheet top-to-bottom. Stored per song and federated with
+ // the record; the px/s it implies is derived CLIENT-side at click time from
+ // the rendered scroll height (which depends on font size, transpose, and the
+ // viewport), so nothing server-side reads this — the bounds only keep it sane
+ // (15s … 1h).
+ //
+ // `null` is the explicit "no target set" value, and it must stay reachable on
+ // a PATCH: songUpdateSchema strips the default, so an OMITTED key preserves
+ // the stored target while an explicit `null` clears it (the absent-vs-empty
+ // rule). A create with no target lands as null rather than undefined so the
+ // field exists in the synced record.
+ scrollDurationSec: z.number().int().min(15).max(3600).nullable().optional().default(null)
});
// PATCH /api/brain/songbook/:id — defaults-free partial. partialWithoutDefaults
diff --git a/server/lib/brainValidation.test.js b/server/lib/brainValidation.test.js
index 07e8438d25..7ea44ac979 100644
--- a/server/lib/brainValidation.test.js
+++ b/server/lib/brainValidation.test.js
@@ -38,6 +38,7 @@ import {
brainSyncPushSchema,
memoryInputSchema,
songInputSchema,
+ songUpdateSchema,
songInstrumentEnum,
songContentFormatEnum
} from './brainValidation.js';
@@ -837,4 +838,54 @@ describe('brainValidation.js', () => {
}
});
});
+
+ // The "fit to duration" autoscroll target (#4100) — the play view derives px/s
+ // from it against the rendered scroll height.
+ describe('songbook scrollDurationSec (#4100)', () => {
+ it('accepts a whole-second target and lands it on the record', () => {
+ const result = songInputSchema.safeParse({ title: 'T', scrollDurationSec: 210 });
+ expect(result.success).toBe(true);
+ expect(result.data.scrollDurationSec).toBe(210);
+ });
+
+ it('defaults to null (no target) when the key is absent on create', () => {
+ const result = songInputSchema.safeParse({ title: 'T' });
+ expect(result.success).toBe(true);
+ expect(result.data).toHaveProperty('scrollDurationSec');
+ expect(result.data.scrollDurationSec).toBe(null);
+ });
+
+ it('rejects out-of-bounds and non-integer targets', () => {
+ for (const bad of [14, 3601, 0, -30, 90.5, '210', true]) {
+ const result = songInputSchema.safeParse({ title: 'T', scrollDurationSec: bad });
+ expect(result.success, `scrollDurationSec ${String(bad)}`).toBe(false);
+ }
+ // The bounds themselves are inclusive.
+ for (const ok of [15, 3600]) {
+ expect(songInputSchema.safeParse({ title: 'T', scrollDurationSec: ok }).success, String(ok)).toBe(true);
+ }
+ });
+
+ // Absent vs. intentionally-empty: an omitted key must stay omitted so the
+ // PATCH merge preserves a stored target, while an explicit null must survive
+ // as null so clearing the input actually clears the record.
+ it('separates "not sent" from an explicit null on update', () => {
+ const untouched = songUpdateSchema.safeParse({ title: 'T' });
+ expect(untouched.success).toBe(true);
+ expect('scrollDurationSec' in untouched.data).toBe(false);
+
+ const cleared = songUpdateSchema.safeParse({ scrollDurationSec: null });
+ expect(cleared.success).toBe(true);
+ expect(cleared.data.scrollDurationSec).toBe(null);
+
+ const set = songUpdateSchema.safeParse({ scrollDurationSec: 90 });
+ expect(set.success).toBe(true);
+ expect(set.data.scrollDurationSec).toBe(90);
+ });
+
+ it('keeps the bounds on the update schema too', () => {
+ expect(songUpdateSchema.safeParse({ scrollDurationSec: 5 }).success).toBe(false);
+ expect(songUpdateSchema.safeParse({ scrollDurationSec: 7200 }).success).toBe(false);
+ });
+ });
});