mirror of
https://github.com/got-feedBack/feedBack.git
synced 2026-07-25 06:11:36 +00:00
fix(player): reliable Escape "Back" + resumable, optionally-confirmed song exit (#619)
* fix(player): make Escape a reliable Back; resumable + optionally-confirmed song exit Escape didn't always leave a song: clicking a transport control (play/FF/RW/ restart) left that <button> focused, and _shortcutDispatchBlocked() bails the shortcut dispatcher for any focused INPUT/SELECT/TEXTAREA/BUTTON — so the player-scope Escape=Back shortcut never fired until the user clicked empty canvas to blur the control. Space already had a player-screen carve-out (#593); Escape did not. That asymmetry was the bug. Phase 1 — focus fix: generalize the Space carve-out in _shortcutDispatchBlocked to Escape, on the player AND settings screens (both register Escape=Back; settings had the identical latent bug). The earlier guards still win: text inputs are exempted first, the Section Practice popover already claims Escape, and a true modal (role=dialog aria-modal=true / .feedBack-modal) still traps it. Plugins' player-scope Escape shortcuts are fixed identically. Phase 2 — resume: leaving the player snapshots {song, arrangement, position, speed} to localStorage; a non-blocking "Resume practice" pill offers it back on the next non-player screen / next launch. playSong() gains a {resume} option that restores speed + seeks to the saved position on song:ready instead of the normal autostart. Conservative (ignores <3s / near-end), cleared on natural song-end and once consumed, expires after 24h. Phase 3 — opt-in "Ask before leaving a song" (Gameplay tab, default OFF). A true-modal confirm with monotonic Escape (the second Escape leaves) and Space/Enter = Leave. The player Escape shortcut and the v3 close button route through window.requestExitSong(); auto-exit on song-end and a results screen's own Close stay unguarded. Design rationale: a multi-seat design charrette (engagement, learning-design, operability, codebase-reality) — leaving a song should be reliable and recoverable, not gated; the confirm is opt-in only. Tests: tests/browser/{keyboard-shortcuts,resume-session,exit-confirm}.spec.ts. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QbexxfTt8q2tAn436MqGWF * test(browser): suppress first-run onboarding in keyboard/resume/exit specs The first-run onboarding overlay (#v3-onboarding) is a modal that intercepts pointer/keyboard events; on a fresh profile it covers the player and breaks any test that presses Escape or clicks. Stub GET /api/profile to an onboarded profile in each beforeEach so the app behaves like a returning user (the state these tests assume). Also tighten the Section Practice Escape test to assert the guarantee the fix actually provides — Escape does not exit the song while the popover is open (the line-447 guard wins over the carve-out) — rather than asserting the popover's own close handler fires, which isn't wired for a synthetic bar. Verified locally against a worktree server (Chromium): all 16 new specs pass (5 Escape + 6 resume + 5 exit-confirm) plus the existing #593 Space tests. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QbexxfTt8q2tAn436MqGWF * fix(player): exit-confirm — Escape cancels back to song, pause on open/resume on stay Refinements from tester feedback on the exit-confirm (default stays OFF): - Escape on the open prompt now = Stay (dismiss + return to the song), matching every other modal and the generic _confirmDialog (Esc=cancel). A second Escape therefore returns to the song instead of leaving it. Leaving stays the explicit, default-focused "Leave" button, so Space/Enter/click = "just get me out" (the OP's "Space always hits leave"). - Opening the prompt PAUSES the song (via the canonical togglePlay path, HTML5 + _juceMode) so it isn't running/being scored behind the modal; Stay resumes exactly what we paused. Guards: cancel any count-in on open; resume only if we paused (wasPlaying), only if still the same live song on the player (_audioSeekGen unchanged), and never auto-resume a song the user had paused. - Trap Tab inside the dialog; backdrop click was already Stay. Specs: exit-confirm.spec.ts updated — the monotonic "second Escape leaves" test becomes "second Escape stays", plus a backdrop-click-stays test. The audio pause/resume itself is verified manually on web + desktop (the mock song has no backing track); these specs lock the navigation + keyboard semantics. NOTE: the pause/resume adds a new pause→resume cycle on the desktop JUCE transport (known play/pause-desync path) — smoke-test on the desktop build before merge. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QbexxfTt8q2tAn436MqGWF * fix(player): accurate exit-confirm copy + keep resume snapshot on failed load Two review follow-ups on the Escape/resume/confirm work: - Settings copy said "a second Escape (or Space/Enter) still leaves", but Escape dismisses the confirm (Stay) like every other modal — only Space/Enter/Leave exit. Corrected the Gameplay-tab description so it matches the implementation (and the committed exit-confirm specs). - resumeLastSession() cleared the snapshot BEFORE awaiting playSong(), so a transient load/connect failure permanently lost the Resume pill with no retry. Clear only after the load resolves; on failure keep the snapshot (and drop the pending in-memory resume) so the pill re-offers it on the next non-player screen. All 16 Escape/resume/exit-confirm Playwright specs still pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> Co-authored-by: byrongamatos <xasiklas@gmail.com>
This commit is contained in:
parent
290783b80b
commit
fef870047b
@ -8,6 +8,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- **Resume where you left off — leaving a song now snapshots your place so an exit is recoverable, not a restart-from-zero.** Exiting the player (`showScreen()` teardown, before audio unload) writes `{song, arrangement, position, speed}` to `localStorage` (`feedBack.resumeSession`), and a non-blocking **"Resume practice"** pill offers it back on the next non-player screen (and on the next app launch). Clicking Resume re-enters the song, restores the arrangement + playback speed, and seeks to the saved position via the existing `_audioSeek` funnel; `playSong()` gains a `{ resume: {position, speed} }` option that arms a `song:ready`-consumed restore instead of the normal autostart, so the two never fight over playback. The snapshot is deliberately conservative — ignored for a song you barely started (< 3s) or had basically finished (within 5s of the end), cleared on natural song-end and once consumed, and expired after 24h. The pill is self-contained (inline-styled, body-appended, works identically in the classic and v3 shells with no Tailwind rebuild), never blocks, and a dismiss forgets the current snapshot for the session. This pairs with the Escape focus fix: now that Escape reliably leaves regardless of focus, an *accidental* exit is one tap to undo. Public surface: `window.resumeLastSession()` / `window.feedBack.resumeLastSession`. (The broader nav-state work — returning to a song after wandering into Settings → Tone Builder — is a separate, larger track; this lands the player-session slice.) Tests: `tests/browser/resume-session.spec.ts` (snapshot guards, staleness, pill show/hide/dismiss, resume consumption).
|
||||
- **Optional "Ask before leaving a song" confirm (Gameplay tab, default OFF).** A new client-only toggle (`confirmExitSong` in `localStorage`, in the v3 Gameplay settings + the Gameplay "Reset" set) for players who want a guard against an accidental exit. **Off by default — Escape leaves instantly, zero change for everyone else.** When on, a *user-initiated* exit (the player-scope Escape shortcut, or the player's ✕) opens a small true-modal confirm instead of leaving; auto-exit on song-end and a results screen's own Close are unaffected (they call `closeCurrentSong()` directly, which stays the unguarded actual-exit). The confirm honors the team's refined asks: **opening it pauses the song** (so it isn't running or being scored behind the prompt) and **Stay resumes exactly what was paused**; **Escape = Stay** — the dialog's capture-phase handler *dismisses* it (now consistent with every other modal and the generic `_confirmDialog`'s Esc=cancel), so a second Escape returns you to the (resumed) song rather than leaving; **Space/Enter (or click) Leave** by natively activating the default-focused "Leave" button ("just get me out"). Pause/resume run through the canonical `togglePlay()` path (HTML5 + `_juceMode`), guarded so a count-in, an already-paused song, or a teardown/seek/end behind the modal can't mis-resume. It's a real modal (`role="dialog" aria-modal="true"` / `.feedBack-modal`) with **Tab trapped inside it** and a **backdrop click that also Stays**, so the Escape/Space focus carve-outs treat it as a trap and don't fire player-back / play-pause behind it. The player Escape shortcut and the v3 ✕ route through a shared `window.requestExitSong()` gate (the ✕ also becomes origin-aware, matching Escape). Tests: `tests/browser/exit-confirm.spec.ts` (default-off instant exit, confirm-on opens + stays, second-Escape stays, backdrop stays, Stay/Leave, Enter-leaves); the audio pause/resume is verified manually on web + desktop (the mock song has no backing track).
|
||||
- **Folder Library — a bundled core plugin (`plugins/folder_library/`) that browses the DLC library by its on-disk folder tree.** Surfaces top-level folders → subfolders → songs (root-level songs land in `(Unsorted)`), with in-app folder management (create / rename / delete nested folders), song moves via dialog or drag-and-drop, and sort/filter that mirrors the host library's filter state. Wired into both the classic (v2) library toolbar and the v3 Songs page as a third **Folders** view alongside grid/tree; the plugin's `screen.js` is loaded once by the host and reused (idempotent IIFEs). Supersedes the former standalone "Folder Organizer" community plugin (removed from the README list). Backend (`routes.py`) registers `/api/plugins/folder_library/{tree,folder/create,folder/rename,folder/delete,song/move}`; **all filesystem mutations are confined to `DLC_DIR` and validated against path traversal** (per-segment name validation plus a resolved-containment check on `song/move`), and folder deletion relocates every song — de-duplicating colliding names — so a name clash never destroys a song. A two-level cache keeps re-opening folders fast. Tests: `tests/plugins/folder_library/test_routes.py` (path-safety helpers + move-traversal and delete-no-data-loss end-to-end).
|
||||
- **Full-screen (immersive) plugin screens — opt-in via `"fullscreen": true` in `plugin.json`.** DAW-style plugin UIs (e.g. a practice studio) need the whole viewport, not a scrolling content page below the topbar — embedded in the v3 shell they get cut off at the bottom with dead space up top. A plugin can now declare a top-level `"fullscreen": true`; `plugins/__init__.py` surfaces it as the `fullscreen` boolean on `/api/plugins` (mirroring the `settings_category` plumbing). When such a plugin's screen is active, `static/v3/shell.js` toggles `html.fb-immersive` from `syncActive()` (so it tracks every navigation incl. deep-link), and `static/v3/v3.css` hides the topbar, collapses the sidebar to a functional **icon rail** (kept reachable — Escape is bound only on player/settings scopes, so a fully-hidden sidebar would trap the user), and lets the active plugin screen fill `#v3-main`. Mirrors the existing `ss-follower-pre` chrome-hide pattern. Additive + opt-in: plugins without the flag are unaffected. Tests: `tests/test_plugins.py::test_fullscreen_flag_parsed_from_manifest`.
|
||||
- **Achievements wall sync — background drain worker (epic PR3, client side).** The bundled `achievements` plugin gains a dead-letter sync worker that POSTs queued Feat unlocks (and removals) to the hosted **feedback-achievements** wall service (separate repo). Idle unless a wall URL is configured (`FEEDBACK_ACHIEVEMENTS_WALL_URL`); uses `requests` with the baked-in client-token header, mirroring `lib/lyrics_transcribe`'s outbound pattern (explicit timeout, no raise on non-2xx). **Dead-letter, never drop** (pure `engine.drain_decision`): network error / `429` / `5xx` → keep `pending` (retry); other `4xx` → `dead_letter` (diagnosable, replayable); `2xx` → delete on server ack. A row leaves the queue only on ack or a user opt-out. `remove-me` now enqueues a wall removal keyed by the reused `player_hash`. Verified by an end-to-end staging round-trip (earn a Feat → drains onto the wall with name + short hash → `remove-me` → wall empties) with **no IP** in tables or access logs. Tests: `tests/plugins/achievements/test_sync.py` (decision table + ack/retry/dead-letter retention + four-field payload on the wire). The hosted service itself (FastAPI + SQLite-on-disk, Feats-only, hidden-until-first-global-unlock, profanity filter, in-memory rate limit, Render blueprint, migration tool) lives in the new `feedback-achievements` repo.
|
||||
@ -36,6 +38,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- **v3 library: exact artist/album filters + scroll/page-depth restore** (feedBack#857). The v3 Songs toolbar gains Artist and Album dropdowns (Album populates from the selected artist and stays disabled until one is chosen), backed by new exact, case-insensitive (`COLLATE NOCASE`) `artist` / `album` query params threaded through `MetadataDB._build_where` → `query_page` / `query_artists` / `query_stats` and the `/api/library`, `/api/library/artists`, `/api/library/stats` endpoints (the free-text `q` search stays fuzzy and composes with the exact filters). The artist/album catalog is fetched independently of the active artist/album selection so the dropdowns always list the full set for the current provider/search. The toolbar is now sticky so filter controls stay reachable when browsing deep libraries, and returning from the player restores the previous scroll position **and** the loaded infinite-scroll page depth via a `sessionStorage` snapshot keyed by a filter/sort/view state hash (invalidated whenever those change, so a filter change still resets to the top). Tests: `tests/test_library_filters.py` (backend artist/album filters), `tests/js/v3_songs_scroll.test.js` (state-hash + snapshot helpers).
|
||||
|
||||
### Fixed
|
||||
- **Escape now exits a song (and leaves Settings) even when a transport/rail control button holds keyboard focus.** Clicking a player control (Play / FF / RW / Restart) left that `<button>` focused, and `_shortcutDispatchBlocked()` in `static/app.js` treats any focused `INPUT/SELECT/TEXTAREA/BUTTON` as an "interactive control" and bails before the shortcut registry runs — so the player-scope `Escape → Back` shortcut never fired until the user clicked empty canvas to blur the control ("Escape in song not consistent"). Space already had a player-screen carve-out (#593) that let it fire through a focused control; Escape did not. Generalized that carve-out to Escape, scoped to the player **and** settings screens (both register an `Escape = Back` shortcut, and settings had the identical latent bug). The earlier guards are preserved and still win: text inputs are exempted first (Escape there clears/blurs the field), the Section Practice popover already claims Escape before the carve-out, and a true modal layered over the screen (`[role="dialog"][aria-modal="true"]` / `.feedBack-modal`) still traps Escape so it closes the modal rather than ejecting past it. Escape becomes a reliable, focus-independent "Back" — making it monotonic groundwork for an optional exit-confirm. Plugins that register a player-scope `Escape` shortcut benefit identically (they were broken the same way). Tests: `tests/browser/keyboard-shortcuts.spec.ts` (focused-button repro, text-input no-exit, no-escape-past-modal, Section Practice popover, settings twin-bug).
|
||||
- **The v3 "Up Next" pill can now be turned off — new "Show 'Up Next'" gameplay toggle (default ON).** The v0.3.0 player chrome's persistent upcoming-section pill (`#v3-upnext`, drawn by `static/v3/player-chrome.js`'s `updateUpNext()`) shipped with no off switch, so it always showed during playback whenever a section was upcoming — overlapping the top-right FPS HUD and ignoring the 3D-highway "Show 'Up Next' section card" checkbox (a *different*, in-canvas widget that was demoted to default-off precisely because this pill is the canonical readout). Users reading the pill as the same setting saw "disabled in settings but still there." Adds a real core toggle following the `autoplayExit` idiom: a client-only `showUpNext` `localStorage` pref (absence = enabled), a **Show "Up Next"** switch in the Gameplay settings tab (`static/v3/index.html`), reader/writer + `loadSettings()` hydration + a read-only `window.feedBack.showUpNext` getter in `static/app.js`, and a gate at the top of `updateUpNext()` that hides the pill when off. Disabling mid-playback hides it immediately; re-enabling re-shows it on the next chrome tick (~6 Hz). Added to `RESET_MAP.gameplay.local` in `static/v3/settings.js` so the Gameplay "Reset" restores the default-on state. Default ON = zero change for existing users. No Tailwind rebuild (plain markup + existing classes).
|
||||
- **v3 list/tree view brought to parity with the grid: select mode, parts chips, and song actions — plus a stale-CSS Docker fix.** Re-lands a previously-reverted change. **Frontend (`static/v3/songs.js`):** entering select mode no longer collapses the tree — `loadTree()` now captures the expanded artist groups (`details[open]` keyed by `data-artist`) before the "Loading…" wipe and restores them on rebuild, so toggling select mode (which re-renders via `reload()`) keeps groups open and selection usable; tree rows gain a display-only checkbox + selection ring, the same fav / save-for-later / overflow-menu cluster as the grid card (always shown, all bound by `wireCards()`), and a capture-phase select guard mirroring the grid so clicking a row or arrangement chip in select mode selects instead of playing (`<summary>` headers sit outside `[data-fn]`, so native expand/collapse is untouched). **Docker fix (`static/tailwind.min.css`):** the committed Tailwind stylesheet was stale — `.sm\:flex` (and the other utilities behind #582's `hidden sm:flex` arrangement chips and the new action cluster) were never compiled in, so they rendered `display:none` on the Docker build (which serves the committed CSS as-is; Desktop rebuilds from source so it looked fine). Regenerated with the pinned `tailwindcss@3.4.19` via `scripts/build-tailwind.sh` so Docker matches Desktop and #582's chips render on every Docker deploy. Regression tests: `tests/browser/v3-tree-select.spec.ts`.
|
||||
- **Space bar now plays/pauses on the player screen even when a sidebar nav link or rail button has focus.** When any `<button>` in the player rail (viz, audio, mixer, lyrics, plugins, advanced), a sidebar nav link, or a popover control held keyboard focus, pressing Space was swallowed by `_shortcutDispatchBlocked` → `_isInsideInteractiveControl` (which treats `BUTTON`/`A` as interactive), so the Space shortcut never reached the dispatcher and `togglePlay()` never ran. `_shortcutDispatchBlocked` (`static/app.js`) now extends the same carve-out already used for the Section Practice bar: while the player screen is active, Space is always routed through the shortcut system — the dispatcher calls `e.preventDefault()` before invoking the handler, so the focused element does not also activate. Text inputs (`_isTextInput`) remain exempted first, so typing space in a search/input field still works normally, and focus inside a true modal dialog (`role="dialog" aria-modal="true"` / `.feedBack-modal`) layered over the player is also exempted so Space reaches the modal's focused control (e.g. its Close button) instead of toggling playback behind it — non-modal player popovers/toasts (loop A/B, arrangement pin) stay covered. Regression tests in `tests/browser/keyboard-shortcuts.spec.ts` cover the focused-rail-button play/pause, the text-input exemption, and the modal-dialog exemption.
|
||||
|
||||
365
static/app.js
365
static/app.js
@ -460,6 +460,25 @@ function _shortcutDispatchBlocked(e) {
|
||||
e.target.closest('[role="dialog"][aria-modal="true"], .feedBack-modal'))) {
|
||||
return false;
|
||||
}
|
||||
// Escape is the universal "back" action and must fire like Space above even
|
||||
// when a transport/rail control <button> holds keyboard focus after a click
|
||||
// — otherwise a focused control swallows Esc and the user can't leave the
|
||||
// song until they click empty canvas (feedBack — "Escape in song not
|
||||
// consistent"). It applies on the player (exit the song) AND settings
|
||||
// (return to the previous screen), both of which register an Escape=Back
|
||||
// shortcut. The earlier guards still win: text inputs are exempted at the
|
||||
// top (Esc there clears/blurs the field), and the Section Practice popover
|
||||
// already claimed Esc above. A true modal layered over the screen still
|
||||
// traps Esc — the modal-overlay check keeps Esc closing the modal rather
|
||||
// than ejecting past it to the screen behind.
|
||||
if (e.key === 'Escape') {
|
||||
const ctx = _getCurrentContext();
|
||||
if ((ctx.isPlayer || ctx.isSettings) &&
|
||||
!(e.target && e.target.closest &&
|
||||
e.target.closest('[role="dialog"][aria-modal="true"], .feedBack-modal'))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return _isInsideInteractiveControl(e.target);
|
||||
}
|
||||
|
||||
@ -1033,6 +1052,11 @@ async function showScreen(id) {
|
||||
const audio = document.getElementById('audio');
|
||||
const stopTime = _audioTime();
|
||||
const hadPlayableSong = !!audio.src || !!window._juceAudioUrl || isPlaying;
|
||||
// Snapshot where we were so leaving the player — especially by accident
|
||||
// — is recoverable instead of dumping the user back at bar 1 next time.
|
||||
// Must run BEFORE highway.stop()/audio unload, while getSongInfo() and
|
||||
// the position (stopTime) are still live.
|
||||
if (hadPlayableSong) _snapshotResumeSession(stopTime);
|
||||
highway.stop();
|
||||
// Cancel any queued seeks, in-flight shim closures, AND active
|
||||
// count-in timers before stopping playback so none of these paths
|
||||
@ -3394,6 +3418,8 @@ async function loadSettings() {
|
||||
if (autoplayExitEl) autoplayExitEl.checked = _autoplayExitEnabled();
|
||||
const showUpNextEl = document.getElementById('setting-show-upnext');
|
||||
if (showUpNextEl) showUpNextEl.checked = _showUpNextEnabled();
|
||||
const confirmExitEl = document.getElementById('setting-confirm-exit');
|
||||
if (confirmExitEl) confirmExitEl.checked = _exitConfirmEnabled();
|
||||
// Restore master-difficulty slider from persisted value (defaults
|
||||
// to 100 when the key is absent — no behaviour change for users
|
||||
// who've never touched the slider).
|
||||
@ -5971,6 +5997,201 @@ window.feedBack.on('song:ready', () => {
|
||||
}
|
||||
});
|
||||
|
||||
// ── Resume last session ────────────────────────────────────────────────────
|
||||
// Leaving a song snapshots where you were — song, arrangement, position, and
|
||||
// speed — so an exit (especially an accidental one, now that Escape reliably
|
||||
// leaves regardless of focus) is recoverable instead of restarting from bar 1.
|
||||
// The snapshot is offered back through a non-blocking "Resume" pill; it never
|
||||
// gates, blocks, or auto-acts. Cleared on natural song-end and once consumed.
|
||||
// (This is the player-session slice; the broader nav/state-resume work — e.g.
|
||||
// returning to a song after wandering into Settings → Tone Builder — is a
|
||||
// separate, larger track.)
|
||||
const _RESUME_KEY = 'feedBack.resumeSession';
|
||||
const _RESUME_MAX_AGE_MS = 24 * 60 * 60 * 1000; // a day-old snapshot is stale
|
||||
const _RESUME_MIN_POSITION_S = 3; // ignore barely-started songs
|
||||
const _RESUME_END_GUARD_S = 5; // ignore basically-finished songs
|
||||
let _pendingResume = null; // {position, speed}, consumed at song:ready
|
||||
let _resumePillDismissed = false; // per-session: user waved off the current snapshot
|
||||
|
||||
function _curPlaybackSpeed() {
|
||||
try {
|
||||
return window._juceMode
|
||||
? ((window.jucePlayer && window.jucePlayer._speed) || 1)
|
||||
: (document.getElementById('audio')?.playbackRate || 1);
|
||||
} catch (_) { return 1; }
|
||||
}
|
||||
|
||||
// Snapshot the live session. Called from showScreen()'s teardown before
|
||||
// highway.stop()/audio unload, while getSongInfo() + position are still valid.
|
||||
function _snapshotResumeSession(position) {
|
||||
try {
|
||||
if (!currentFilename) return;
|
||||
const si = (window.highway && typeof highway.getSongInfo === 'function')
|
||||
? (highway.getSongInfo() || {}) : {};
|
||||
const dur = Number(si.duration) || 0;
|
||||
const pos = Number(position) || 0;
|
||||
// Only worth resuming a song you were genuinely mid-way through — not a
|
||||
// glance at the first seconds, and not one that already basically ended.
|
||||
if (pos < _RESUME_MIN_POSITION_S) { _clearResumeSession(); return; }
|
||||
if (dur && pos > dur - _RESUME_END_GUARD_S) { _clearResumeSession(); return; }
|
||||
const snap = {
|
||||
f: currentFilename,
|
||||
a: (typeof si.arrangement_index === 'number' && si.arrangement_index >= 0)
|
||||
? si.arrangement_index : undefined,
|
||||
t: pos,
|
||||
sp: _curPlaybackSpeed(),
|
||||
title: si.title || '',
|
||||
artist: si.artist || '',
|
||||
ts: Date.now(),
|
||||
};
|
||||
localStorage.setItem(_RESUME_KEY, JSON.stringify(snap));
|
||||
// A fresh snapshot earns one offer — undo any earlier dismissal.
|
||||
_resumePillDismissed = false;
|
||||
} catch (_) { /* storage unavailable — resume is best-effort */ }
|
||||
}
|
||||
|
||||
function _readResumeSession() {
|
||||
try {
|
||||
const raw = localStorage.getItem(_RESUME_KEY);
|
||||
if (!raw) return null;
|
||||
const snap = JSON.parse(raw);
|
||||
if (!snap || !snap.f || !(Number(snap.t) > 0)) return null;
|
||||
if (!snap.ts || Date.now() - snap.ts > _RESUME_MAX_AGE_MS) { _clearResumeSession(); return null; }
|
||||
return snap;
|
||||
} catch (_) { return null; }
|
||||
}
|
||||
|
||||
function _clearResumeSession() {
|
||||
try { localStorage.removeItem(_RESUME_KEY); } catch (_) {}
|
||||
}
|
||||
|
||||
// Re-enter the snapshotted song and restore arrangement + position + speed.
|
||||
async function resumeLastSession() {
|
||||
const snap = _readResumeSession();
|
||||
if (!snap) { _hideResumePill(); return false; }
|
||||
_hideResumePill();
|
||||
try {
|
||||
await playSong(snap.f, snap.a, {
|
||||
resume: { position: Number(snap.t) || 0, speed: Number(snap.sp) || 1 },
|
||||
});
|
||||
} catch (err) {
|
||||
// A transient load/connect failure must not strand the user: keep the
|
||||
// snapshot so the pill can re-offer it on the next non-player screen,
|
||||
// rather than consuming the only copy before the song actually loaded.
|
||||
console.warn('[app] resume failed to load; keeping snapshot:', err);
|
||||
_pendingResume = null;
|
||||
return false;
|
||||
}
|
||||
_clearResumeSession(); // consumed only after a successful load
|
||||
return true;
|
||||
}
|
||||
window.resumeLastSession = resumeLastSession;
|
||||
if (window.feedBack) window.feedBack.resumeLastSession = resumeLastSession;
|
||||
|
||||
// Consume a pending resume once the chart is ready: restore speed, seek to the
|
||||
// saved position, then (if autoplay is on) start from there. playSong() does
|
||||
// NOT arm autostart for a resume load, so the two never fight over playback.
|
||||
window.feedBack.on('song:ready', () => {
|
||||
const pend = _pendingResume;
|
||||
if (!pend) return;
|
||||
_pendingResume = null;
|
||||
try {
|
||||
if (pend.speed && pend.speed > 0) {
|
||||
const slider = document.getElementById('speed-slider');
|
||||
if (slider) slider.value = String(Math.round(pend.speed * 100));
|
||||
setSpeed(pend.speed);
|
||||
}
|
||||
} catch (_) { /* speed restore is best-effort */ }
|
||||
Promise.resolve(_audioSeek(Math.max(0, Number(pend.position) || 0), 'resume'))
|
||||
.then(() => { if (_autoplayExitEnabled() && !isPlaying) return togglePlay(); })
|
||||
.catch((err) => console.warn('[app] resume failed:', err));
|
||||
});
|
||||
|
||||
// A song that finishes on its own has nothing to resume — and we never want to
|
||||
// offer "resume" for a song the user just completed.
|
||||
window.feedBack.on('song:ended', _clearResumeSession);
|
||||
|
||||
// ── Resume pill (non-blocking "continue where you left off") ────────────────
|
||||
// Self-contained, inline-styled, body-appended so it works identically in the
|
||||
// classic (v2) and v3 shells with no Tailwind rebuild. It only ever appears off
|
||||
// the player screen, never blocks, and a dismiss forgets the current snapshot
|
||||
// for the session.
|
||||
function _hideResumePill() {
|
||||
const el = document.getElementById('fb-resume-pill');
|
||||
if (el) el.remove();
|
||||
}
|
||||
|
||||
function _maybeShowResumePill() {
|
||||
const active = document.querySelector('.screen.active');
|
||||
if (active && active.id === 'player') { _hideResumePill(); return; }
|
||||
if (_resumePillDismissed) return;
|
||||
const snap = _readResumeSession();
|
||||
if (!snap) { _hideResumePill(); return; }
|
||||
if (document.getElementById('fb-resume-pill')) return; // already shown
|
||||
|
||||
const label = (snap.title || decodeURIComponent(snap.f || 'your last song')).toString();
|
||||
const pill = document.createElement('div');
|
||||
pill.id = 'fb-resume-pill';
|
||||
pill.setAttribute('role', 'status');
|
||||
pill.style.cssText = [
|
||||
'position:fixed', 'left:16px', 'bottom:16px', 'z-index:120',
|
||||
'display:flex', 'align-items:center', 'gap:10px',
|
||||
'max-width:min(90vw,360px)', 'padding:10px 12px',
|
||||
'background:rgba(17,24,39,0.96)', 'color:#e5e7eb',
|
||||
'border:1px solid rgba(148,163,184,0.25)', 'border-radius:10px',
|
||||
'box-shadow:0 6px 24px rgba(0,0,0,0.4)',
|
||||
'font:13px/1.3 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif',
|
||||
].join(';');
|
||||
|
||||
const text = document.createElement('div');
|
||||
text.style.cssText = 'flex:1;min-width:0';
|
||||
const t1 = document.createElement('div');
|
||||
t1.textContent = 'Resume practice';
|
||||
t1.style.cssText = 'font-weight:600;color:#fff';
|
||||
const t2 = document.createElement('div');
|
||||
t2.textContent = label;
|
||||
t2.style.cssText = 'opacity:0.7;white-space:nowrap;overflow:hidden;text-overflow:ellipsis';
|
||||
text.appendChild(t1); text.appendChild(t2);
|
||||
|
||||
const resumeBtn = document.createElement('button');
|
||||
resumeBtn.type = 'button';
|
||||
resumeBtn.textContent = 'Resume ▸';
|
||||
resumeBtn.style.cssText = 'flex:none;padding:6px 10px;border:0;border-radius:7px;background:#4080e0;color:#fff;font-weight:600;cursor:pointer';
|
||||
resumeBtn.addEventListener('click', () => { resumeLastSession(); });
|
||||
|
||||
const dismissBtn = document.createElement('button');
|
||||
dismissBtn.type = 'button';
|
||||
dismissBtn.setAttribute('aria-label', 'Dismiss');
|
||||
dismissBtn.textContent = '✕';
|
||||
dismissBtn.style.cssText = 'flex:none;padding:4px 6px;border:0;border-radius:7px;background:transparent;color:#9ca3af;cursor:pointer;font-size:14px';
|
||||
dismissBtn.addEventListener('click', () => { _resumePillDismissed = true; _hideResumePill(); });
|
||||
|
||||
pill.appendChild(text);
|
||||
pill.appendChild(resumeBtn);
|
||||
pill.appendChild(dismissBtn);
|
||||
(document.body || document.documentElement).appendChild(pill);
|
||||
}
|
||||
if (window.feedBack) window.feedBack._maybeShowResumePill = _maybeShowResumePill;
|
||||
|
||||
// Exposed for tests/debugging (mirrors window._panels / _getCurrentContext).
|
||||
window._snapshotResumeSession = _snapshotResumeSession;
|
||||
window._readResumeSession = _readResumeSession;
|
||||
window._clearResumeSession = _clearResumeSession;
|
||||
|
||||
// Drive the pill off screen transitions (hide over the player, offer it
|
||||
// elsewhere) plus a one-shot check on first load for a prior-session snapshot.
|
||||
window.feedBack.on('screen:changed', (ev) => {
|
||||
const id = (ev && ev.detail && ev.detail.id) || (ev && ev.id);
|
||||
if (id === 'player') _hideResumePill();
|
||||
else _maybeShowResumePill();
|
||||
});
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded',
|
||||
() => { try { _maybeShowResumePill(); } catch (_) {} }, { once: true });
|
||||
} else {
|
||||
try { _maybeShowResumePill(); } catch (_) {}
|
||||
}
|
||||
|
||||
// Editor → Highway handoff (Editor ⇄ 3D Highway region round-trip). The
|
||||
// editor's "Loop in 3D" button stashes a pending loop + return context, then
|
||||
// calls playSong(). Once the chart is ready (playSong's own clearLoop() has
|
||||
@ -6124,8 +6345,17 @@ async function playSong(filename, arrangement, options) {
|
||||
|
||||
currentFilename = filename;
|
||||
// A fresh load arms autoplay; a pending auto-exit from the previous
|
||||
// song is no longer relevant.
|
||||
_pendingAutostart = true;
|
||||
// song is no longer relevant. A *resume* load (options.resume) instead
|
||||
// arms _pendingResume — consumed at song:ready to restore speed + seek to
|
||||
// the saved position, then start — so autostart and resume don't both try
|
||||
// to begin playback from different positions.
|
||||
if (options && options.resume && Number(options.resume.position) > 0) {
|
||||
_pendingResume = options.resume;
|
||||
_pendingAutostart = false;
|
||||
} else {
|
||||
_pendingResume = null;
|
||||
_pendingAutostart = true;
|
||||
}
|
||||
_clearAutoExit();
|
||||
// Remember which screen the player was launched from so Esc /
|
||||
// navigation back from the player (and auto-exit) returns the user
|
||||
@ -6397,6 +6627,135 @@ function closeCurrentSong() {
|
||||
window.closeCurrentSong = closeCurrentSong;
|
||||
if (window.feedBack) window.feedBack.closeCurrentSong = closeCurrentSong;
|
||||
|
||||
// ── "Ask before leaving a song" (Gameplay tab, default OFF) ────────────────
|
||||
// Client-only localStorage pref (`confirmExitSong`); absence = OFF. When ON, a
|
||||
// *user-initiated* exit (Escape, or the player ✕) opens a small confirm instead
|
||||
// of leaving immediately. Auto-exit on song-end and a results screen's own
|
||||
// Close never prompt — they call closeCurrentSong() directly, which stays the
|
||||
// unguarded actual-exit.
|
||||
function _exitConfirmEnabled() {
|
||||
try { return localStorage.getItem('confirmExitSong') === '1'; } catch (_) { return false; }
|
||||
}
|
||||
// Settings checkbox setter (onchange="setConfirmExitSong(this.checked)").
|
||||
window.setConfirmExitSong = function (on) {
|
||||
try { localStorage.setItem('confirmExitSong', on ? '1' : '0'); } catch (_) { /* private mode */ }
|
||||
const el = document.getElementById('setting-confirm-exit');
|
||||
if (el && el.checked !== !!on) el.checked = !!on;
|
||||
};
|
||||
|
||||
let _exitConfirmOpen = false; // guard against stacking confirm modals
|
||||
|
||||
// User-initiated request to leave the player. Honors the confirm toggle; the
|
||||
// actual exit is always closeCurrentSong() (origin-aware teardown).
|
||||
function requestExitSong() {
|
||||
if (!_exitConfirmEnabled()) { closeCurrentSong(); return; }
|
||||
if (_exitConfirmOpen) return; // already asking
|
||||
_openExitConfirm();
|
||||
}
|
||||
window.requestExitSong = requestExitSong;
|
||||
if (window.feedBack) window.feedBack.requestExitSong = requestExitSong;
|
||||
|
||||
// A *true* modal (role="dialog" aria-modal="true" + .feedBack-modal) so the
|
||||
// Escape/Space carve-outs classify it as a focus trap — they won't fire
|
||||
// player-back / play-pause while it's up. Opening it PAUSES the song so it
|
||||
// isn't running (or being scored) behind the prompt; Stay resumes exactly what
|
||||
// we paused. Escape matches every other modal (and the generic _confirmDialog):
|
||||
// it *dismisses* the prompt → Stay → drops you back into the (resumed) song —
|
||||
// so a second Escape does NOT leave. Leaving is the explicit, default-focused
|
||||
// "Leave" button, so Space/Enter (or click) is the keyboard "just get me out".
|
||||
function _openExitConfirm() {
|
||||
_exitConfirmOpen = true;
|
||||
// Freeze the song while the user decides: cancel any pending count-in (so it
|
||||
// can't start playback behind the modal) and pause if we're playing. Stay
|
||||
// resumes only what we paused (wasPlaying), and only if the same song is
|
||||
// still live on the player — guarding a teardown/seek/end behind the prompt.
|
||||
_cancelCountIn();
|
||||
const _resumeGen = _audioSeekGen;
|
||||
const _wasPlaying = isPlaying;
|
||||
if (_wasPlaying) Promise.resolve(togglePlay()).catch(() => {});
|
||||
const overlay = document.createElement('div');
|
||||
overlay.id = 'fb-exit-confirm';
|
||||
overlay.className = 'feedBack-modal';
|
||||
overlay.setAttribute('role', 'dialog');
|
||||
overlay.setAttribute('aria-modal', 'true');
|
||||
overlay.setAttribute('aria-label', 'Leave this song?');
|
||||
overlay.style.cssText = [
|
||||
'position:fixed', 'inset:0', 'z-index:200', 'display:flex',
|
||||
'align-items:center', 'justify-content:center',
|
||||
'background:rgba(0,0,0,0.6)',
|
||||
'font:14px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif',
|
||||
].join(';');
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.style.cssText = [
|
||||
'max-width:min(92vw,360px)', 'padding:18px 18px 14px',
|
||||
'background:#111827', 'color:#e5e7eb',
|
||||
'border:1px solid rgba(148,163,184,0.25)', 'border-radius:12px',
|
||||
'box-shadow:0 12px 40px rgba(0,0,0,0.5)', 'text-align:left',
|
||||
].join(';');
|
||||
const h = document.createElement('div');
|
||||
h.textContent = 'Leave this song?';
|
||||
h.style.cssText = 'font-size:16px;font-weight:700;color:#fff;margin-bottom:6px';
|
||||
const p = document.createElement('div');
|
||||
p.textContent = 'You can pick up where you left off from the Resume pill.';
|
||||
p.style.cssText = 'opacity:0.75;margin-bottom:16px';
|
||||
|
||||
const row = document.createElement('div');
|
||||
row.style.cssText = 'display:flex;gap:8px;justify-content:flex-end';
|
||||
const stayBtn = document.createElement('button');
|
||||
stayBtn.type = 'button';
|
||||
stayBtn.textContent = 'Stay';
|
||||
stayBtn.style.cssText = 'padding:8px 14px;border:1px solid rgba(148,163,184,0.3);border-radius:8px;background:transparent;color:#e5e7eb;cursor:pointer';
|
||||
const leaveBtn = document.createElement('button');
|
||||
leaveBtn.type = 'button';
|
||||
leaveBtn.textContent = 'Leave';
|
||||
leaveBtn.style.cssText = 'padding:8px 14px;border:0;border-radius:8px;background:#4080e0;color:#fff;font-weight:600;cursor:pointer';
|
||||
|
||||
let settled = false;
|
||||
function close(leave) {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
_exitConfirmOpen = false;
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
overlay.remove();
|
||||
if (leave) { closeCurrentSong(); return; }
|
||||
// Stay → resume exactly what we paused, but only if the session is still
|
||||
// the same live song on the player (not torn down / ended / seeked away
|
||||
// behind the modal). If the user was already paused, leave them paused.
|
||||
if (_wasPlaying && !isPlaying &&
|
||||
_audioSeekGen === _resumeGen &&
|
||||
document.querySelector('.screen.active')?.id === 'player') {
|
||||
Promise.resolve(togglePlay()).catch(() => {});
|
||||
}
|
||||
}
|
||||
// Capture-phase so this dialog owns Escape and it can't fall through to the
|
||||
// player-scope back shortcut. Escape = Stay (dismiss the prompt and resume
|
||||
// the song) — consistent with every other modal, so a second Escape does
|
||||
// NOT leave. Space/Enter stay on native activation of the focused button
|
||||
// (Leave by default), so the keyboard "leave" is Space/Enter.
|
||||
function onKey(e) {
|
||||
if (e.key === 'Escape') { e.preventDefault(); e.stopImmediatePropagation(); close(false); }
|
||||
}
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
leaveBtn.addEventListener('click', () => close(true));
|
||||
stayBtn.addEventListener('click', () => close(false));
|
||||
overlay.addEventListener('mousedown', (e) => { if (e.target === overlay) close(false); });
|
||||
|
||||
row.appendChild(stayBtn);
|
||||
row.appendChild(leaveBtn);
|
||||
card.appendChild(h);
|
||||
card.appendChild(p);
|
||||
card.appendChild(row);
|
||||
overlay.appendChild(card);
|
||||
(document.body || document.documentElement).appendChild(overlay);
|
||||
// Trap Tab within the dialog (Stay ↔ Leave) so focus can't fall back to the
|
||||
// player controls underneath while it's open.
|
||||
_trapFocusInModal(overlay);
|
||||
// Default focus on "Leave" so Space/Enter leaves immediately.
|
||||
leaveBtn.focus();
|
||||
}
|
||||
window._openExitConfirm = _openExitConfirm; // exposed for tests/debugging
|
||||
|
||||
const SPEED_PRESET_PCTS = [100, 90, 80, 75, 70, 60, 50];
|
||||
const SPEED_SNAP_THRESHOLD = 0.02;
|
||||
let _speedPresetsWired = false;
|
||||
@ -9652,7 +10011,7 @@ registerShortcut({
|
||||
key: 'Escape',
|
||||
description: 'Back to library',
|
||||
scope: 'player',
|
||||
handler: () => showScreen(_playerOriginScreen || 'home')
|
||||
handler: () => requestExitSong()
|
||||
});
|
||||
|
||||
registerShortcut({
|
||||
|
||||
@ -519,6 +519,20 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Ask before leaving a song -->
|
||||
<div class="fb-srow">
|
||||
<span class="fb-srow-icon"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/></svg></span>
|
||||
<div class="fb-srow-main">
|
||||
<div class="fb-srow-title">Ask before leaving a song</div>
|
||||
<div class="fb-srow-desc">Confirm before Escape (or the player’s ✕) exits a song. Off by default — Escape leaves instantly. With it on, a confirm appears; Space, Enter, or “Leave” exits, while Escape dismisses it.</div>
|
||||
</div>
|
||||
<div class="fb-srow-control">
|
||||
<label class="fb-switch">
|
||||
<input type="checkbox" id="setting-confirm-exit" onchange="setConfirmExitSong(this.checked)">
|
||||
<span class="fb-switch-track"></span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -999,7 +1013,7 @@
|
||||
<button onclick="returnToEditorFromHighway()" id="btn-return-editor" class="v3-pop-btn hidden" title="Return to the editor where you left off">↩ Editor</button>
|
||||
</span>
|
||||
</div>
|
||||
<button onclick="showScreen('home')" class="v3-pop-close" title="Close player">✕ Close player</button>
|
||||
<button onclick="requestExitSong()" class="v3-pop-close" title="Close player">✕ Close player</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@ -29,7 +29,7 @@
|
||||
gameplay: {
|
||||
server: ['master_difficulty', 'av_offset_ms', 'miss_penalty',
|
||||
'fail_behavior', 'countdown_before_song', 'default_arrangement'],
|
||||
local: ['lefty', 'autoplayExit', 'showUpNext', 'arrangementNamingMode', 'countdownBeforeSong'],
|
||||
local: ['lefty', 'autoplayExit', 'showUpNext', 'confirmExitSong', 'arrangementNamingMode', 'countdownBeforeSong'],
|
||||
after: function () {
|
||||
// Left-handed is held on the highway object, not re-derived
|
||||
// from localStorage on load — flip it back to the default.
|
||||
|
||||
124
tests/browser/exit-confirm.spec.ts
Normal file
124
tests/browser/exit-confirm.spec.ts
Normal file
@ -0,0 +1,124 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
// Opt-in "Ask before leaving a song" confirm. Default OFF → Escape/✕ leave
|
||||
// instantly. When ON, a true-modal confirm appears and PAUSES the song; Escape
|
||||
// (like every other modal) DISMISSES it → Stay, so a second Escape returns to
|
||||
// the song rather than leaving, and Space/Enter activate the default-focused
|
||||
// "Leave". (The mock song has no backing audio, so the pause-on-open /
|
||||
// resume-on-Stay is verified manually on web + desktop; these specs lock the
|
||||
// navigation + keyboard semantics.)
|
||||
|
||||
const CONFIRM_KEY = 'confirmExitSong';
|
||||
|
||||
async function installMockSong(page) {
|
||||
await page.evaluate(() => {
|
||||
const messages = [
|
||||
{ type: 'song_info', title: 'Mock Song', artist: 'Mock Artist', arrangement: 'Lead', arrangement_index: 0, duration: 90, tuning: [0, 0, 0, 0, 0, 0], stringCount: 6, arrangements: [{ index: 0, name: 'Lead', notes: 1 }] },
|
||||
{ type: 'ready' },
|
||||
];
|
||||
class MockWebSocket {
|
||||
static CONNECTING = 0; static OPEN = 1; static CLOSING = 2; static CLOSED = 3;
|
||||
readyState = MockWebSocket.CONNECTING;
|
||||
onopen = null; onmessage = null; onerror = null; onclose = null; url;
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
setTimeout(() => {
|
||||
this.readyState = MockWebSocket.OPEN;
|
||||
if (this.onopen) this.onopen(new Event('open'));
|
||||
for (const m of messages) if (this.onmessage) this.onmessage({ data: JSON.stringify(m) });
|
||||
}, 0);
|
||||
}
|
||||
send() {}
|
||||
close() { this.readyState = MockWebSocket.CLOSED; if (this.onclose) this.onclose(new CloseEvent('close')); }
|
||||
}
|
||||
// @ts-ignore
|
||||
window.WebSocket = MockWebSocket;
|
||||
});
|
||||
}
|
||||
|
||||
async function openPlayerWithMockSong(page) {
|
||||
await installMockSong(page);
|
||||
await page.evaluate(async () => { /* @ts-ignore */ await window.playSong('mock-song.sloppak'); });
|
||||
await page.waitForSelector('#player.active', { timeout: 5000 });
|
||||
await expect(page.locator('#hud-title')).toHaveText('Mock Song', { timeout: 5000 });
|
||||
}
|
||||
|
||||
test.describe('Exit-confirm toggle', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
// Suppress the first-run onboarding overlay (a modal that intercepts
|
||||
// pointer/keyboard events) so Escape reaches the player, not the overlay.
|
||||
await page.route('**/api/profile', async (route) => {
|
||||
if (route.request().method() === 'GET') {
|
||||
await route.fulfill({ json: { display_name: 'Test', player_hash: 'test', onboarded: true } });
|
||||
} else { await route.continue(); }
|
||||
});
|
||||
await page.goto('/');
|
||||
await page.waitForSelector('.screen.active', { timeout: 10000 });
|
||||
await page.evaluate((k) => localStorage.removeItem(k), CONFIRM_KEY);
|
||||
});
|
||||
|
||||
test('default OFF: Escape exits the song immediately, no confirm', async ({ page }) => {
|
||||
await openPlayerWithMockSong(page);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('#fb-exit-confirm')).toHaveCount(0);
|
||||
await expect(page.locator('#player.active')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('ON: Escape opens the confirm and the song stays', async ({ page }) => {
|
||||
await page.evaluate(() => { /* @ts-ignore */ window.setConfirmExitSong(true); });
|
||||
await openPlayerWithMockSong(page);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('#fb-exit-confirm')).toBeVisible();
|
||||
await expect(page.locator('#player.active')).toHaveCount(1);
|
||||
// "Leave" is focused so Space/Enter leaves immediately.
|
||||
await expect(page.locator('#fb-exit-confirm button', { hasText: 'Leave' })).toBeFocused();
|
||||
});
|
||||
|
||||
test('ON: a second Escape dismisses the prompt and stays in the song', async ({ page }) => {
|
||||
await page.evaluate(() => { /* @ts-ignore */ window.setConfirmExitSong(true); });
|
||||
await openPlayerWithMockSong(page);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('#fb-exit-confirm')).toBeVisible();
|
||||
// Escape = dismiss (Stay), matching every other modal — NOT leave.
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('#fb-exit-confirm')).toHaveCount(0);
|
||||
await expect(page.locator('#player.active')).toHaveCount(1);
|
||||
});
|
||||
|
||||
test('ON: clicking the backdrop dismisses the prompt and stays', async ({ page }) => {
|
||||
await page.evaluate(() => { /* @ts-ignore */ window.setConfirmExitSong(true); });
|
||||
await openPlayerWithMockSong(page);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('#fb-exit-confirm')).toBeVisible();
|
||||
// mousedown on the overlay backdrop (top-left, away from the centered card)
|
||||
// is Stay — never an accidental leave.
|
||||
await page.locator('#fb-exit-confirm').click({ position: { x: 5, y: 5 } });
|
||||
await expect(page.locator('#fb-exit-confirm')).toHaveCount(0);
|
||||
await expect(page.locator('#player.active')).toHaveCount(1);
|
||||
});
|
||||
|
||||
test('ON: "Stay" keeps you in the song; "Leave" exits', async ({ page }) => {
|
||||
await page.evaluate(() => { /* @ts-ignore */ window.setConfirmExitSong(true); });
|
||||
await openPlayerWithMockSong(page);
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
await page.locator('#fb-exit-confirm button', { hasText: 'Stay' }).click();
|
||||
await expect(page.locator('#fb-exit-confirm')).toHaveCount(0);
|
||||
await expect(page.locator('#player.active')).toHaveCount(1);
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
await page.locator('#fb-exit-confirm button', { hasText: 'Leave' }).click();
|
||||
await expect(page.locator('#fb-exit-confirm')).toHaveCount(0);
|
||||
await expect(page.locator('#player.active')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('ON: Enter on the default-focused "Leave" leaves', async ({ page }) => {
|
||||
await page.evaluate(() => { /* @ts-ignore */ window.setConfirmExitSong(true); });
|
||||
await openPlayerWithMockSong(page);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('#fb-exit-confirm')).toBeVisible();
|
||||
await page.keyboard.press('Enter');
|
||||
await expect(page.locator('#fb-exit-confirm')).toHaveCount(0);
|
||||
await expect(page.locator('#player.active')).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
@ -51,6 +51,14 @@ async function openPlayerWithMockSong(page) {
|
||||
|
||||
test.describe('Keyboard Shortcuts', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
// Suppress the first-run onboarding overlay (#v3-onboarding) — a modal that
|
||||
// intercepts pointer/keyboard events — so the app behaves like a returning
|
||||
// user, which is the state these tests assume.
|
||||
await page.route('**/api/profile', async (route) => {
|
||||
if (route.request().method() === 'GET') {
|
||||
await route.fulfill({ json: { display_name: 'Test', player_hash: 'test', onboarded: true } });
|
||||
} else { await route.continue(); }
|
||||
});
|
||||
await page.goto('/');
|
||||
await page.waitForSelector('.screen.active', { timeout: 10000 });
|
||||
});
|
||||
@ -778,6 +786,183 @@ test('should support condition callbacks', async ({ page }) => {
|
||||
expect(result.clicked).toBe(1);
|
||||
});
|
||||
|
||||
// ── Escape = universal "Back" carve-out ──────────────────────────────────
|
||||
// Escape must escape a focused non-modal control exactly like Space does,
|
||||
// so a focused transport/rail button can't swallow it ("Escape in song not
|
||||
// consistent"). These mirror the #593 Space tests above. Each registers an
|
||||
// Escape spy in the relevant scope (which replaces the built-in handler for
|
||||
// that composite key) so the assertion doesn't depend on showScreen teardown.
|
||||
|
||||
test('Escape exits the song when a player rail button is focused', async ({ page }) => {
|
||||
await openPlayerWithMockSong(page);
|
||||
|
||||
// The bug: a focused <button> is an "interactive control", so Escape was
|
||||
// blocked before reaching the dispatcher and the song wouldn't exit until
|
||||
// the user clicked empty canvas to blur the control.
|
||||
await page.evaluate(() => {
|
||||
// @ts-ignore
|
||||
window.__escBackCount = 0;
|
||||
// @ts-ignore
|
||||
window.registerShortcut({
|
||||
key: 'Escape',
|
||||
description: 'Back to library (test spy)',
|
||||
scope: 'player',
|
||||
// @ts-ignore
|
||||
handler: () => { window.__escBackCount++; },
|
||||
});
|
||||
const btn = document.createElement('button');
|
||||
btn.id = '__test-rail-btn';
|
||||
btn.textContent = 'Restart';
|
||||
document.getElementById('player')!.appendChild(btn);
|
||||
});
|
||||
|
||||
await page.locator('#__test-rail-btn').focus();
|
||||
await expect(page.locator('#__test-rail-btn')).toBeFocused();
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
const backCount = await page.evaluate(() => (window as any).__escBackCount);
|
||||
// Back-to-library fired despite the control button holding focus.
|
||||
expect(backCount).toBe(1);
|
||||
});
|
||||
|
||||
test('Escape in a player-screen text input does NOT exit the song', async ({ page }) => {
|
||||
await openPlayerWithMockSong(page);
|
||||
|
||||
// The text-input exemption (_isTextInput) is checked before the Escape
|
||||
// carve-out, so Escape in a field is the field's own concern (clear/blur),
|
||||
// never a song exit.
|
||||
await page.evaluate(() => {
|
||||
// @ts-ignore
|
||||
window.__escBackCount = 0;
|
||||
// @ts-ignore
|
||||
window.registerShortcut({
|
||||
key: 'Escape',
|
||||
description: 'Back to library (test spy)',
|
||||
scope: 'player',
|
||||
// @ts-ignore
|
||||
handler: () => { window.__escBackCount++; },
|
||||
});
|
||||
const input = document.createElement('input');
|
||||
input.type = 'text';
|
||||
input.id = '__test-player-input';
|
||||
document.getElementById('player')!.appendChild(input);
|
||||
});
|
||||
|
||||
await page.locator('#__test-player-input').focus();
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
const backCount = await page.evaluate(() => (window as any).__escBackCount);
|
||||
expect(backCount).toBe(0);
|
||||
});
|
||||
|
||||
test('Escape inside a modal over the player closes the modal, not back-to-library', async ({ page }) => {
|
||||
await openPlayerWithMockSong(page);
|
||||
|
||||
// A true modal (role="dialog" aria-modal="true" / .feedBack-modal) layered
|
||||
// over the player is a focus trap: Escape there must NOT eject past it to
|
||||
// exit the song — the modal owns Escape. The carve-out's modal-overlay
|
||||
// guard keeps the player-back shortcut from firing.
|
||||
await page.evaluate(() => {
|
||||
// @ts-ignore
|
||||
window.__escBackCount = 0;
|
||||
// @ts-ignore
|
||||
window.registerShortcut({
|
||||
key: 'Escape',
|
||||
description: 'Back to library (test spy)',
|
||||
scope: 'player',
|
||||
// @ts-ignore
|
||||
handler: () => { window.__escBackCount++; },
|
||||
});
|
||||
const modal = document.createElement('div');
|
||||
modal.id = '__test-modal';
|
||||
modal.className = 'feedBack-modal';
|
||||
modal.setAttribute('role', 'dialog');
|
||||
modal.setAttribute('aria-modal', 'true');
|
||||
const btn = document.createElement('button');
|
||||
btn.id = '__test-modal-btn';
|
||||
btn.textContent = 'Close';
|
||||
modal.appendChild(btn);
|
||||
document.body.appendChild(modal);
|
||||
});
|
||||
|
||||
await page.locator('#__test-modal-btn').focus();
|
||||
await expect(page.locator('#__test-modal-btn')).toBeFocused();
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
const backCount = await page.evaluate(() => (window as any).__escBackCount);
|
||||
// Playback is NOT exited behind the modal.
|
||||
expect(backCount).toBe(0);
|
||||
});
|
||||
|
||||
test('Escape does NOT exit the song while the Section Practice popover is open', async ({ page }) => {
|
||||
await openPlayerWithMockSong(page);
|
||||
|
||||
// The Section Practice popover claims Escape earlier in
|
||||
// _shortcutDispatchBlocked (line ~447, before the Escape carve-out), so an
|
||||
// open popover suppresses the player-scope back-to-library Escape — the
|
||||
// popover's own handler owns closing it. This locks that ordering guard.
|
||||
await page.evaluate(() => {
|
||||
// @ts-ignore
|
||||
window.__escBackCount = 0;
|
||||
// @ts-ignore
|
||||
window.registerShortcut({
|
||||
key: 'Escape',
|
||||
description: 'Back to library (test spy)',
|
||||
scope: 'player',
|
||||
// @ts-ignore
|
||||
handler: () => { window.__escBackCount++; },
|
||||
});
|
||||
let bar = document.getElementById('section-practice-bar');
|
||||
if (!bar) {
|
||||
bar = document.createElement('div');
|
||||
bar.id = 'section-practice-bar';
|
||||
document.getElementById('player')!.appendChild(bar);
|
||||
}
|
||||
bar.classList.add('section-practice-bar--open');
|
||||
});
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
const backCount = await page.evaluate(() => (window as any).__escBackCount);
|
||||
// Player-back did NOT fire while the popover was open.
|
||||
expect(backCount).toBe(0);
|
||||
});
|
||||
|
||||
test('Escape goes back from settings when a control is focused (twin-bug)', async ({ page }) => {
|
||||
// The same focus bug existed on the settings screen (the carve-out was
|
||||
// player-only). The fix covers settings too: Escape returns to the
|
||||
// previous screen even when a settings control holds focus.
|
||||
await page.evaluate(() => {
|
||||
// @ts-ignore
|
||||
window.__escSettingsBackCount = 0;
|
||||
// @ts-ignore
|
||||
window.registerShortcut({
|
||||
key: 'Escape',
|
||||
description: 'Go back from settings (test spy)',
|
||||
scope: 'settings',
|
||||
// @ts-ignore
|
||||
handler: () => { window.__escSettingsBackCount++; },
|
||||
});
|
||||
// @ts-ignore
|
||||
window.showScreen('settings');
|
||||
const btn = document.createElement('button');
|
||||
btn.id = '__test-settings-btn';
|
||||
btn.textContent = 'Some setting';
|
||||
document.getElementById('settings')!.appendChild(btn);
|
||||
});
|
||||
|
||||
await page.waitForSelector('#settings.active', { timeout: 5000 });
|
||||
await page.locator('#__test-settings-btn').focus();
|
||||
await expect(page.locator('#__test-settings-btn')).toBeFocused();
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
const backCount = await page.evaluate(() => (window as any).__escSettingsBackCount);
|
||||
expect(backCount).toBe(1);
|
||||
});
|
||||
|
||||
test('should warn on invalid scope', async ({ page }) => {
|
||||
const messages: string[] = [];
|
||||
page.on('console', msg => {
|
||||
|
||||
152
tests/browser/resume-session.spec.ts
Normal file
152
tests/browser/resume-session.spec.ts
Normal file
@ -0,0 +1,152 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
// Resume-last-session: leaving the player snapshots {song, arrangement,
|
||||
// position, speed} so an exit is recoverable via a non-blocking "Resume" pill.
|
||||
// These exercise the deterministic plumbing (snapshot guards, staleness, the
|
||||
// pill, and resume consumption) without depending on real audio timing.
|
||||
|
||||
const RESUME_KEY = 'feedBack.resumeSession';
|
||||
|
||||
// Make playSong()'s WebSocket a no-network mock that emits a song_info + ready.
|
||||
async function installMockSong(page) {
|
||||
await page.evaluate(() => {
|
||||
const messages = [
|
||||
{ type: 'song_info', title: 'Mock Song', artist: 'Mock Artist', arrangement: 'Lead', arrangement_index: 0, duration: 90, tuning: [0, 0, 0, 0, 0, 0], stringCount: 6, arrangements: [{ index: 0, name: 'Lead', notes: 1 }] },
|
||||
{ type: 'ready' },
|
||||
];
|
||||
class MockWebSocket {
|
||||
static CONNECTING = 0; static OPEN = 1; static CLOSING = 2; static CLOSED = 3;
|
||||
readyState = MockWebSocket.CONNECTING;
|
||||
onopen = null; onmessage = null; onerror = null; onclose = null; url;
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
setTimeout(() => {
|
||||
this.readyState = MockWebSocket.OPEN;
|
||||
if (this.onopen) this.onopen(new Event('open'));
|
||||
for (const m of messages) if (this.onmessage) this.onmessage({ data: JSON.stringify(m) });
|
||||
}, 0);
|
||||
}
|
||||
send() {}
|
||||
close() { this.readyState = MockWebSocket.CLOSED; if (this.onclose) this.onclose(new CloseEvent('close')); }
|
||||
}
|
||||
// @ts-ignore
|
||||
window.WebSocket = MockWebSocket;
|
||||
});
|
||||
}
|
||||
|
||||
async function openPlayerWithMockSong(page) {
|
||||
await installMockSong(page);
|
||||
await page.evaluate(async () => {
|
||||
// @ts-ignore
|
||||
await window.playSong('mock-song.sloppak');
|
||||
});
|
||||
await page.waitForSelector('#player.active', { timeout: 5000 });
|
||||
await expect(page.locator('#hud-title')).toHaveText('Mock Song', { timeout: 5000 });
|
||||
}
|
||||
|
||||
test.describe('Resume last session', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
// Suppress the first-run onboarding overlay (a modal that intercepts
|
||||
// pointer/keyboard events) so the player isn't covered.
|
||||
await page.route('**/api/profile', async (route) => {
|
||||
if (route.request().method() === 'GET') {
|
||||
await route.fulfill({ json: { display_name: 'Test', player_hash: 'test', onboarded: true } });
|
||||
} else { await route.continue(); }
|
||||
});
|
||||
await page.goto('/');
|
||||
await page.waitForSelector('.screen.active', { timeout: 10000 });
|
||||
await page.evaluate((k) => localStorage.removeItem(k), RESUME_KEY);
|
||||
});
|
||||
|
||||
test('snapshots song + arrangement + position once you are mid-song', async ({ page }) => {
|
||||
await openPlayerWithMockSong(page);
|
||||
const snap = await page.evaluate(() => {
|
||||
// @ts-ignore
|
||||
window._snapshotResumeSession(30);
|
||||
// @ts-ignore
|
||||
return window._readResumeSession();
|
||||
});
|
||||
expect(snap).not.toBeNull();
|
||||
expect(snap.f).toBe('mock-song.sloppak');
|
||||
expect(snap.a).toBe(0);
|
||||
expect(Math.round(snap.t)).toBe(30);
|
||||
expect(snap.title).toBe('Mock Song');
|
||||
});
|
||||
|
||||
test('does NOT snapshot a barely-started or basically-finished song', async ({ page }) => {
|
||||
await openPlayerWithMockSong(page);
|
||||
const result = await page.evaluate(() => {
|
||||
// @ts-ignore
|
||||
window._snapshotResumeSession(1); // < 3s min → ignored
|
||||
// @ts-ignore
|
||||
const tooEarly = window._readResumeSession();
|
||||
// duration is 90; end-guard is 5s, so 88 > 85 → ignored
|
||||
// @ts-ignore
|
||||
window._snapshotResumeSession(88);
|
||||
// @ts-ignore
|
||||
const tooLate = window._readResumeSession();
|
||||
return { tooEarly, tooLate };
|
||||
});
|
||||
expect(result.tooEarly).toBeNull();
|
||||
expect(result.tooLate).toBeNull();
|
||||
});
|
||||
|
||||
test('a stale (>24h) snapshot is ignored', async ({ page }) => {
|
||||
const got = await page.evaluate((k) => {
|
||||
const old = { f: 'old.sloppak', a: 0, t: 42, sp: 1, title: 'Old', ts: Date.now() - 25 * 60 * 60 * 1000 };
|
||||
localStorage.setItem(k, JSON.stringify(old));
|
||||
// @ts-ignore
|
||||
return window._readResumeSession();
|
||||
}, RESUME_KEY);
|
||||
expect(got).toBeNull();
|
||||
});
|
||||
|
||||
test('the Resume pill appears off-player and hides on the player', async ({ page }) => {
|
||||
await page.evaluate((k) => {
|
||||
const snap = { f: 'mock-song.sloppak', a: 0, t: 30, sp: 1, title: 'Mock Song', artist: 'Mock Artist', ts: Date.now() };
|
||||
localStorage.setItem(k, JSON.stringify(snap));
|
||||
// @ts-ignore
|
||||
window.feedBack._maybeShowResumePill();
|
||||
}, RESUME_KEY);
|
||||
|
||||
await expect(page.locator('#fb-resume-pill')).toBeVisible();
|
||||
await expect(page.locator('#fb-resume-pill')).toContainText('Mock Song');
|
||||
|
||||
// Entering the player hides it (screen:changed → _hideResumePill()).
|
||||
await page.evaluate(() => { /* @ts-ignore */ window.showScreen('player'); });
|
||||
await page.waitForSelector('#player.active', { timeout: 5000 });
|
||||
await expect(page.locator('#fb-resume-pill')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('dismissing the pill removes it and does not re-show it this session', async ({ page }) => {
|
||||
await page.evaluate((k) => {
|
||||
const snap = { f: 'mock-song.sloppak', a: 0, t: 30, sp: 1, title: 'Mock Song', ts: Date.now() };
|
||||
localStorage.setItem(k, JSON.stringify(snap));
|
||||
// @ts-ignore
|
||||
window.feedBack._maybeShowResumePill();
|
||||
}, RESUME_KEY);
|
||||
|
||||
await expect(page.locator('#fb-resume-pill')).toBeVisible();
|
||||
await page.locator('#fb-resume-pill button[aria-label="Dismiss"]').click();
|
||||
await expect(page.locator('#fb-resume-pill')).toHaveCount(0);
|
||||
|
||||
// A re-offer attempt within the same session is suppressed.
|
||||
await page.evaluate(() => { /* @ts-ignore */ window.feedBack._maybeShowResumePill(); });
|
||||
await expect(page.locator('#fb-resume-pill')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('resumeLastSession() re-enters the song and consumes the snapshot', async ({ page }) => {
|
||||
await installMockSong(page);
|
||||
await page.evaluate((k) => {
|
||||
const snap = { f: 'mock-song.sloppak', a: 0, t: 30, sp: 1, title: 'Mock Song', ts: Date.now() };
|
||||
localStorage.setItem(k, JSON.stringify(snap));
|
||||
}, RESUME_KEY);
|
||||
|
||||
await page.evaluate(async () => { /* @ts-ignore */ await window.resumeLastSession(); });
|
||||
|
||||
await page.waitForSelector('#player.active', { timeout: 5000 });
|
||||
// The snapshot is consumed (cleared) so it isn't offered again.
|
||||
const remaining = await page.evaluate((k) => localStorage.getItem(k), RESUME_KEY);
|
||||
expect(remaining).toBeNull();
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user