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

fix: preserve drum preview user activation (#3222)

[._.]/ Adam Eivyff1ed4c0ddb2
diff --git a/client/src/components/songbook/DrumPreview.jsx b/client/src/components/songbook/DrumPreview.jsx
index 551b95ad10..6318bd3b7b 100644
--- a/client/src/components/songbook/DrumPreview.jsx
+++ b/client/src/components/songbook/DrumPreview.jsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useLayoutEffect, useMemo, useState } from 'react';
import useDrumPlayer from '../../hooks/useDrumPlayer.js';
import useWakeLock from '../../hooks/useWakeLock.js';
import { chartHasMusic, parseDrumChart } from '../../lib/drumNotation.js';
@@ -21,12 +21,18 @@ export default function DrumPreview({
settingsMirror,
}) {
const [snapshot, setSnapshot] = useState(text);
- const [playAfterReload, setPlayAfterReload] = useState(false);
const player = useDrumPlayer(snapshot, { songId });
const chartChanged = text !== snapshot;
const liveHasMusic = useMemo(() => chartHasMusic(parseDrumChart(text)), [text]);
useWakeLock(player.playing);
+ // Keep the idle player current before the browser can paint another
+ // interaction target. Play can then start directly from its trusted click
+ // (required by Safari/iOS) while edits made during playback stay frozen.
+ useLayoutEffect(() => {
+ if (!player.playing && snapshot !== text) setSnapshot(text);
+ }, [player.playing, snapshot, text]);
+
const setBpm = useCallback((next) => {
player.setBpm(next);
settingsMirror?.setBpm(next);
@@ -53,25 +59,8 @@ export default function DrumPreview({
}, [player.setClickEnabled, settingsMirror]);
const toggle = useCallback(() => {
- if (player.playing) {
- player.toggle();
- return;
- }
- if (text !== snapshot) {
- setSnapshot(text);
- setPlayAfterReload(true);
- return;
- }
- player.toggle();
- }, [player.playing, player.toggle, snapshot, text]);
-
- // A snapshot update rebuilds the idle player. Start only after that render so
- // toggle() cannot launch the stale chart or run before its tempo seed lands.
- useEffect(() => {
- if (!playAfterReload || snapshot !== text || !player.chartSettingsReady) return;
- setPlayAfterReload(false);
player.toggle();
- }, [playAfterReload, player.chartSettingsReady, player.toggle, snapshot, text]);
+ }, [player.toggle]);
const displayedText = player.playing ? snapshot : text;
diff --git a/client/src/components/songbook/DrumPreview.test.jsx b/client/src/components/songbook/DrumPreview.test.jsx
index 6e3efc420b..6e24802ddc 100644
--- a/client/src/components/songbook/DrumPreview.test.jsx
+++ b/client/src/components/songbook/DrumPreview.test.jsx
@@ -1,12 +1,11 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { fireEvent, render, screen } from '@testing-library/react';
const mockPlayer = vi.hoisted(() => ({
playing: false,
toggle: vi.fn(),
stop: vi.fn(),
hasMusic: true,
- chartSettingsReady: true,
bpm: 96,
setBpm: vi.fn(),
setBpmPercent: vi.fn(),
@@ -50,7 +49,6 @@ const CHART_B = 'tempo: 96\nHH: xxxx\nK: o-o-';
describe('DrumPreview', () => {
beforeEach(() => {
mockPlayer.playing = false;
- mockPlayer.chartSettingsReady = true;
mockPlayer.toggle.mockReset();
mockPlayer.stop.mockReset();
useDrumPlayer.mockClear();
@@ -76,16 +74,12 @@ describe('DrumPreview', () => {
expect(useWakeLock).toHaveBeenLastCalledWith(true);
});
- it('waits for the latest snapshot settings before starting after a change', async () => {
+ it('updates the idle snapshot before starting directly from the Play click', () => {
const { rerender } = render(<DrumPreview text={CHART_A} />);
- mockPlayer.chartSettingsReady = false;
rerender(<DrumPreview text={CHART_B} />);
- fireEvent.click(screen.getByRole('button', { name: 'Play preview' }));
- await waitFor(() => expect(useDrumPlayer.mock.calls.at(-1)[0]).toBe(CHART_B));
- expect(mockPlayer.toggle).not.toHaveBeenCalled();
- mockPlayer.chartSettingsReady = true;
- rerender(<DrumPreview text={CHART_B} />);
+ expect(useDrumPlayer.mock.calls.at(-1)[0]).toBe(CHART_B);
+ fireEvent.click(screen.getByRole('button', { name: 'Play preview' }));
expect(mockPlayer.toggle).toHaveBeenCalledTimes(1);
expect(screen.queryByText('Chart changed — press Play to reload.')).toBeNull();
});
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 9aa15190fd..8d8f2df888 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -180,5 +180,5 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useCanvasDprSize` | DevicePixelRatio-aware canvas sizing shared by the piano-roll renderers (`<PianoRoll>`, `<MidiPianoRoll>`): sizes the bitmap to container-width × height at the DPR, applies the transform, and redraws via a `drawRef` on mount + every `ResizeObserver` resize (observer created once per height, never churned by draw-closure changes). Returns a ref holding the current CSS width so draw code doesn't measure the DOM per frame. | Both piano-roll canvases. |
| `useCanvasRollPalette` | Resolves the roll canvas palette (theme-following `--port-accent` + roll bg via `rollPalette`) into a ref, re-resolving on theme switch (`data-port-theme` MutationObserver) and repainting through a `drawRef`. Hands back a ref, not state, so a theme swap redraws the imperative canvas without a React re-render. | Both piano-roll canvases need theme-aware accent/bg colors that canvas `fillStyle` can't read from CSS vars. |
| `useMidiNotes` | Fetch + parse a transcribed `.mid` file into the piano-roll view-model (`parseMidiFile` in `lib/midiNotes.js`), with a module-level per-URL cache so remounts (collapse, tab switches) don't refetch/reparse. Returns `{ status: 'idle'\|'loading'\|'ready'\|'error', data, error, reload }`; a generation counter drops stale in-flight responses on URL change/unmount. Plain `fetch` of the static file URL — errors surface inline, never as toasts (#2477). | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |
-| `useDrumPlayer` | Drum play-along transport for a SongBook `drum` chart (#3115): parses the chart (`lib/drumNotation.js`), owns one `createDrumPlayer` per chart plus the practice settings and the sheet playhead. Returns the chart/transport controls plus `chartSettingsReady`, which becomes true after a replacement chart's persisted/written tempo seed lands. The practice tempo persists per song in `safeStorage` (never into the record); a timing-critical edit (tempo / count-in / loop) STOPS playback rather than re-timing already-scheduled audio, while the click toggle applies live; the player + its interval + scheduled hits tear down on stop, chart change and unmount. | The SongBook viewer and snapshot-based drum previews. Don't hand-wire `createDrumPlayer` + BPM persistence + playhead state again. |
+| `useDrumPlayer` | Drum play-along transport for a SongBook `drum` chart (#3115): parses the chart (`lib/drumNotation.js`), owns one `createDrumPlayer` per chart plus the practice settings and the sheet playhead. Returns `{ chart, barCount, writtenTempo, bpm, setBpm, setBpmPercent, countInBars, setCountInBars, loopEnabled, setLoopEnabled, loopFrom, loopTo, setLoopRange, clickEnabled, setClickEnabled, playing, activeStep, currentBar, toggle, stop }`. The practice tempo persists per song in `safeStorage` (never into the record); a timing-critical edit (tempo / count-in / loop) STOPS playback rather than re-timing already-scheduled audio, while the click toggle applies live; the player + its interval + scheduled hits tear down on stop, chart change and unmount. | The SongBook viewer and snapshot-based drum previews. Don't hand-wire `createDrumPlayer` + BPM persistence + playhead state again. |
| `useMidiPlayer` | React wrapper over `lib/midiPlayback.js` (#2490): one synth player per parsed MIDI view-model, torn down when the data changes/unmounts so oscillators never outlive the roll. Returns `{ playing, toggle, seek(sec), getPosition }` — `getPosition` is the stable ref the `<MidiPianoRoll>` rAF playhead reads; no AudioContext is touched until the first toggle. A resume failure resets `playing` instead of lying. | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |
diff --git a/client/src/hooks/useDrumPlayer.js b/client/src/hooks/useDrumPlayer.js
index 7d885fd258..acd62ff0c3 100644
--- a/client/src/hooks/useDrumPlayer.js
+++ b/client/src/hooks/useDrumPlayer.js
@@ -55,10 +55,6 @@ export default function useDrumPlayer(text, { songId } = {}) {
const storageKey = songId ? `songbook:drumBpm:${songId}` : null;
const [bpm, setBpmState] = useState(writtenTempo);
- // A chart change seeds tempo in an effect. Consumers that need to start the
- // replacement player automatically must wait for this marker, otherwise they
- // can launch it with the previous chart's BPM before the seed render lands.
- const [settingsChart, setSettingsChart] = useState(chart);
const [countInBars, setCountInBarsState] = useState(1);
const [loopEnabled, setLoopEnabledState] = useState(false);
const [loopFrom, setLoopFromState] = useState(1);
@@ -87,8 +83,7 @@ export default function useDrumPlayer(text, { songId } = {}) {
useEffect(() => {
const stored = storageKey ? clampBpm(safeReadStorage(storageKey)) : null;
setBpmState(stored ?? writtenTempo);
- setSettingsChart(chart);
- }, [chart, storageKey, writtenTempo]);
+ }, [storageKey, writtenTempo]);
// A chart change invalidates the loop range (the bar count differs).
useEffect(() => {
@@ -222,7 +217,6 @@ export default function useDrumPlayer(text, { songId } = {}) {
return {
chart,
- chartSettingsReady: settingsChart === chart,
barCount,
hasMusic,
writtenTempo,
diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsx
index f8b947b2cd..9e2a829a71 100644
--- a/client/src/pages/SongBookViewer.test.jsx
+++ b/client/src/pages/SongBookViewer.test.jsx
@@ -318,13 +318,13 @@ K: o - - - - - o -`;
expect(screen.getByLabelText('Play along')).toBeTruthy();
});
- it('keeps the edit preview on its sounding snapshot while the draft changes', async () => {
+ it('keeps the idle edit preview synchronized before Play', async () => {
api.getSong.mockResolvedValue(drumSong());
renderPage('/songbook/abc?mode=edit');
const editor = await screen.findByLabelText('Content');
fireEvent.change(editor, { target: { value: `${DRUM_CHART}\nC: x - x -` } });
- expect(screen.getByText('Chart changed — press Play to reload.')).toBeTruthy();
+ expect(screen.queryByText('Chart changed — press Play to reload.')).toBeNull();
expect(screen.getByLabelText('Play along')).toBeTruthy();
});