// A browser's history as a router keeps it, for ssr.mjs: each entry's URL // and state, pushed or in place of the one on screen, and the state on // screen (`here`) reactive, as SvelteKit's `page.state` is, so the shell // sees an entry gone back or forward to. As SvelteKit's router does, an // entry is made a moment after it is asked for, and `here` is set only once // its move settles, later still. A back or forward meanwhile comes after // that move, as a browser's does (SvelteKit sets `page.state` before the // task that made the entry ends; a back is a task of its own), so the move // sets no `here`: it is the entry's the browser went to, never one it left. // `entered` runs as the shell starts, as a page hydrated; a page loaded // again is a new `History` holding the entries, at the one it was on. type Entry = { url: string; state: unknown; replace: boolean }; export class History { readonly entries: Entry[]; at: number; here: unknown = $state(undefined); /** How many times the browser has gone back or forward: a move settling meanwhile sets no `here`. */ private went = 0; /** The router's history as the shell takes it (`Navigation`). */ readonly navigation; constructor(entries: Entry[] = [], at = entries.length - 1) { this.entries = entries; this.at = at; this.here = entries[at]?.state; const self = this; this.navigation = { get here(): unknown { return self.here; }, async go(url: string, state: unknown, replace: boolean) { const entry = { url, state: JSON.parse(JSON.stringify(state)), replace }; await Promise.resolve(); if (replace && self.at >= 0) self.entries[self.at] = entry; else self.entries.splice(++self.at, Infinity, entry); const went = self.went; const { promise, resolve } = Promise.withResolvers(); setTimeout(resolve); await promise; if (self.went === went) self.here = entry.state; }, entered: (run: () => void) => queueMicrotask(run) }; } /** The browser's back (`by` -1), or forward (1). */ go(by: number) { this.went++; this.at += by; this.here = this.entries[this.at].state; } }