fix(nav): a navigation closes every overlay before it pushes

The overlay history stack let a navigation land ABOVE open overlays and
"buried" their entries with a counter. Measured in Chrome: Shift+W over
About navigated under the still-open dialog, the next Back both undid the
navigation and closed About, and the Back after that did nothing; Shift+W
on Home with the player open did nothing at all. The counter could also be
spent by a different overlay closing first, and callers that could not
report whether they pushed were assumed to have.

setPage and openChannel now close every open overlay and push only once
the history is back in sync (one entry per live overlay, no programmatic
back() in flight, no reconcile queued), so nothing is ever buried and the
whole mechanism goes: navigateOverOverlays, closeThenNavigate, buryUnder,
setPage's boolean, and the three test files that pinned them. The palette
closes only itself before running a row, so a theme picked over the player
keeps the player. Shift+W on Home with the player open now closes it
(owner decision 2026-09-09).

The wait is on state, not on "a popstate": the old 250 ms fallback could
run with back()s still in flight. An overlay that refuses to close within
1.5 s drops the command instead of being navigated out from under.
This commit is contained in:
2026-09-13 00:17:09 +02:00
parent 32fe0768b6
commit 92c305bab9
14 changed files with 449 additions and 465 deletions
+93 -105
View File
@@ -150,6 +150,15 @@ export function useHistorySubview<T>(
// listener mistook the leaving modal's back() for a genuine user Back and closed itself, and
// (b) a mangled history where the pointer ended up BEHIND the surviving entry, so a later browser
// Back walked off the app entirely instead of closing the modal. Coalescing removes both.
//
// A navigation never lands UNDER an open overlay: `setPage` and `openChannel` close every overlay
// first and push only once their entries are back (`closeOverlaysThenNavigate`). The design before
// E11 let the push land above the overlays and "buried" their entries with a counter, and that
// counter was a whole family of bugs — a burial spent by a different overlay closing first, a
// navigation that could not report whether it pushed and was assumed to have, one browser Back that
// both undid the navigation AND closed the dialog above it, and the dead Back press after that (the
// last two measured in Chrome, E11 S1). With nothing ever buried, the stack and the history agree by
// construction.
type Overlay = { token: number; cb: () => void };
const overlayStack: Overlay[] = [];
let overlayCounter = 0;
@@ -157,64 +166,25 @@ let overlayCounter = 0;
let historyDepth = 0;
// Programmatic history.back() calls still awaiting their popstate — each must be ignored.
let pendingProgrammatic = 0;
// Overlay entries a navigation has PUSHED PAST. They are still real history entries and their
// overlays may still be mounted, but they are no longer on top, so reclaiming one with history.back()
// would pop the navigation instead. Reconcile consumes them silently. See closeThenNavigate.
let buriedEntries = 0;
let reconcileScheduled = false;
let listenerInstalled = false;
/** Run a navigation and mark the live overlay entries buried under it — but ONLY if it really
* pushed an entry. A navigation that reports `false` pushed nothing, so its overlays are still on
* top and must stay reclaimable: `setPage` early-returns when the requested page is already
* current, and Home is the default landing page, so "Shift+W while already on Home with the player
* open" navigated nowhere yet still buried the player's entry. The player's unmount then consumed
* the mark instead of issuing history.back(), orphaning its browser entry — and the next Back
* popped onto an identical `sfPage` with an empty overlay stack, i.e. a press that did nothing
* (round 2). One rule for both entry points below — but read the next paragraph before trusting it
* at the `closeThenNavigate` one, where most callers cannot report at all.
*
* It fails OPEN: only a literal `false` skips the mark, so a `navigate` that reports nothing is
* assumed to have pushed. That is what the code did unconditionally before, so nothing regressed by
* adding the rule — it just does not yet reach everywhere. Today only `navigateOverOverlays`
* (App's Shift+W → `setPage`) is fully covered. Of `closeThenNavigate`'s callers, only a palette
* row written as a bare `() => setPage(page)` forwards the boolean: `CommandItem.run` is typed
* `() => void`, so the block-bodied and non-navigating rows report nothing — and neither does
* `openChannel`, which has its OWN no-push branch (it `replaceState`s when the entry already
* carries `_chan`) and is reached both from a palette row and from PlayerModal's channel-name jump.
* Each of those still marks a live sibling overlay's entry buried under a push that never happened,
* costing one dead browser-Back press when that overlay is closed by its own control.
*
* Closing it is three changes, not one — widen `CommandItem.run` to `() => boolean | void`, return
* the verdict from the block-bodied rows, and give `openChannel` the boolean `setPage` now has — so
* it is deferred to the project backlog rather than bolted on here.
*
* Marking AFTER the call is safe: `navigate()` is synchronous and only `reconcileHistory` (a
* microtask) and the popstate listener ever move `historyDepth`. */
function buryUnder(navigate: () => boolean | void): void {
if (navigate() !== false) buriedEntries = historyDepth;
}
// Re-checked after every reconcile — see `afterClosing`.
const syncWaiters = new Set<() => void>();
// Push/pop history entries until their count matches the live overlay count. Runs once per tick.
function reconcileHistory(): void {
reconcileScheduled = false;
const want = overlayStack.length;
// A genuine user Back decrements historyDepth on its own, so a burial can outlive the entries it
// described; never claim more buried entries than there are entries.
if (buriedEntries > historyDepth) buriedEntries = historyDepth;
while (historyDepth < want) {
historyDepth++;
window.history.pushState({ ...window.history.state, _ov: ++overlayCounter }, "");
}
while (historyDepth > want && buriedEntries > 0) {
historyDepth--; // buried: the browser entry stays, but it is not ours to reclaim
buriedEntries--;
}
while (historyDepth > want) {
historyDepth--;
pendingProgrammatic++;
window.history.back();
}
syncWaiters.forEach((cb) => cb());
}
function scheduleReconcile(): void {
@@ -240,74 +210,92 @@ function ensureOverlayListener(): void {
});
}
/** Close an overlay that holds a `useBackToClose` entry and THEN navigate — in that order, waiting
* for the browser to confirm it.
*
* The trap: closing unmounts the overlay, whose cleanup reconciles the history by issuing a
* programmatic `history.back()`. A `pushState` made before that lands (i.e. anything `setPage` /
* `openChannel` does synchronously) is simply undone by it, so the navigation silently does
* nothing. PlayerModal hit this first — clicking a video's channel name only closed the player —
* and the command palette hit it again the day it was written, which is why the fix lives here
* instead of being re-derived at each call site.
*
* Only call this from INSIDE an overlay that uses `useBackToClose`: the popstate we wait for is
* that overlay's own entry being reclaimed, and without one it never arrives. */
export function closeThenNavigate(close: () => void, navigate: () => boolean | void): void {
let done = false;
// Armed BEFORE the close, so it is a plain const and there is no declaration order to reason about.
// Degrades honestly if no popstate is coming at all — an overlay closed in the same tick it opened
// never pushed an entry, so there is nothing to reclaim and the command would hang forever.
// Navigating a beat late beats a control that silently does nothing.
const fallback = setTimeout(() => run(), 250);
const run = () => {
if (done) return;
done = true;
window.removeEventListener("popstate", onPop);
clearTimeout(fallback);
// Every overlay entry still counted is now BURIED under the entry the navigation just pushed, so
// a later unmount must NOT reclaim it with history.back() — that pops the navigation instead and
// silently bounces the user back where they started (a palette opened over the player: closing
// the palette landed its popstate, the navigation unmounted the player too, and the player's
// reconcile ate the new page entry). MARK them rather than zeroing the depth: round 1 set
// `historyDepth = 0` outright, which also desynced the counter from overlays the navigation does
// NOT unmount — About/ReleaseNotes live outside the page column — so one Back both navigated and
// closed them (round 2). `buryUnder` skips the mark when the command reports it navigated
// nowhere — which here is only the palette's bare `() => setPage(page)` module rows; see the
// fail-open limit documented on `buryUnder` for the rows that cannot report.
buryUnder(navigate);
};
const onPop = () => {
// The same reconcile can issue MORE than one back(); a pushState made between them would be
// popped by the next. Wait for the last one to land.
if (pendingProgrammatic > 0) return;
run();
};
window.addEventListener("popstate", onPop);
close();
/** The history holds exactly one entry per live overlay and no programmatic back() is still in
* flight — so a pushState made now cannot be undone by one. */
function historyInSync(): boolean {
return historyDepth === overlayStack.length && pendingProgrammatic === 0 && !reconcileScheduled;
}
/** Navigate from OUTSIDE any overlay — a global keyboard shortcut — when one may be open.
// How long an overlay gets to actually close before its command is dropped. Closing is one React
// render (measured back()→popstate: 1–13 ms in Chrome); nothing in the app refuses a close today,
// but a future "discard your changes?" guard must not be navigated out from under.
const CLOSE_TIMEOUT_MS = 1500;
/** Close `targets` (via `close`), then `run` once they have unmounted AND the history has caught up.
*
* `closeThenNavigate` is for a control that lives INSIDE the overlay and can close it, and it waits
* for that overlay's own entry to come back. A global key has neither: it does not know which
* overlay is open, or whether one is at all. It just navigates, and the page change unmounts
* whatever the module column was holding — whose reconcile then reclaims the entry the navigation
* had just pushed. Shift+W over an open player closed the player and snapped back to the page it
* started on, which reads as a dead shortcut.
* The trap: closing unmounts an overlay, whose cleanup reconciles by issuing a programmatic
* `history.back()`. A pushState made before that lands is undone by it, so a command that navigates
* silently does nothing but close. PlayerModal hit it first; the command palette the day it was
* written.
*
* Same fix as `closeThenNavigate`, one step shorter: bury the live overlay entries FIRST, so a
* later unmount consumes the marks instead of issuing `history.back()`. There is no popstate to
* wait for, because nothing is being closed on purpose. An overlay the navigation does NOT unmount
* (the palette and the cheat sheet live above the page column) keeps its entry buried too — the
* same trade `closeThenNavigate` already makes, and the reason closing the palette afterwards no
* longer pops the page out from under the user.
* It waits for a STATE, not an event. The helper before E11 waited for "a popstate" plus a 250 ms
* fallback — but one reconcile can issue several back()s, an overlay closed in the tick it opened
* issues none, and the fallback then ran with back()s still in flight. Here the reconcile and every
* popstate re-check one predicate.
*
* `navigate` reports whether it actually pushed — see `buryUnder`, which is why `setPage` returns a
* boolean rather than this guessing from `history.length` (a `back()` followed by a `pushState`
* leaves it unchanged) or from the entry's `sfScroll` id (`openChannel` pushes without minting
* one). */
export function navigateOverOverlays(navigate: () => boolean | void): void {
buryUnder(navigate);
* `run` goes out on a fresh task, never inside the popstate dispatch that settled it: listeners
* registered before ours (NavigationProvider's) have read that event already, but ones after it
* have not, and a page applied from the OLD entry after our push would undo the navigation. */
function afterClosing(targets: readonly Overlay[], close: () => void, run: () => void): void {
let done = false;
let queued = false;
const gone = () => targets.every((o) => !overlayStack.includes(o));
const ready = () => !done && gone() && historyInSync();
const stop = () => {
done = true;
syncWaiters.delete(check);
window.removeEventListener("popstate", check);
clearTimeout(timeout);
};
function check(): void {
if (queued || !ready()) return;
queued = true;
setTimeout(() => {
queued = false;
if (!ready()) return;
stop();
run();
}, 0);
}
const timeout = setTimeout(() => {
if (done) return;
stop();
// Still mounted: the overlay refused to close, so drop the command rather than navigate under
// it. Gone but out of sync: a back() never reported back — run late rather than never.
if (gone()) run();
}, CLOSE_TIMEOUT_MS);
syncWaiters.add(check);
window.addEventListener("popstate", check);
close();
check();
}
/** Navigate over whatever overlays are open: close them all (topmost first, the order Back peels
* them in), then navigate once their entries are back. Synchronous when nothing is open — the
* ordinary rail click.
*
* `setPage` and `openChannel` call it themselves, so no call site can forget it: a global shortcut,
* a toast's "View" clicked inside the player, a palette row, the player's channel link. Closing is
* what a page change already did to the module-owned overlays (it unmounts them); for the ones above
* the page column (About, the cheat sheet, the palette) it means the destination is what the user
* sees, not a dialog still standing over it. A navigation that turns out to go nowhere — Shift+W on
* Home with the player open — still closes, so the key always ends with the answer on screen (owner
* decision 2026-09-09). */
export function closeOverlaysThenNavigate(navigate: () => void): void {
if (overlayStack.length === 0 && historyInSync()) {
navigate();
return;
}
const targets = [...overlayStack];
afterClosing(targets, () => [...targets].reverse().forEach((o) => o.cb()), navigate);
}
/** Close the overlay a control lives in, then run its command once that overlay's entry is back —
* the command palette's rows. Overlays underneath are left alone: a theme picked over the player
* must not close the player, and a row that navigates closes it through `setPage` anyway. */
export function closeTopOverlayThenRun(close: () => void, run: () => void): void {
const top = overlayStack[overlayStack.length - 1];
afterClosing(top ? [top] : [], close, run);
}
/** While the calling component is mounted, Back (or the browser/mouse back button) closes it via