/** * The per-scope history model (API §8.2) — a framework-free entries+cursor stack * with a version counter for `useSyncExternalStore`, its serialized entry shape * (`SerializedLocation`/`NavSnapshot` + equality/clone), and the seed precedence. * Source of truth for back/forward; the adapter is a projection sink around it. */ import type { NodePath } from '@astrale-os/sdk/graph/path' import type { Key } from '@astrale-os/sdk/schema' /** The serializable projection persisted in history / URLs / snapshots. */ export interface SerializedLocation { readonly node: NodePath readonly view?: Key.View readonly params?: Readonly> } /** A versioned history snapshot — round-trips through `NavScope.restore`. */ export interface NavSnapshot { readonly v: 1 readonly entries: readonly SerializedLocation[] readonly cursor: number } /** Structural equality of two serialized locations (node + view + params). */ export function sameLocation(a: SerializedLocation, b: SerializedLocation): boolean { return a.node === b.node && a.view === b.view && sameParams(a.params, b.params) } function sameParams( a?: Readonly>, b?: Readonly>, ): boolean { if (a === b) return true const ak = a ? Object.keys(a) : [] const bk = b ? Object.keys(b) : [] if (ak.length !== bk.length) return false return ak.every((k) => a?.[k] === b?.[k]) } /** A deep-enough clone for a serialized entry (params copied). */ export function cloneLocation(loc: SerializedLocation): SerializedLocation { return { node: loc.node, ...(loc.view !== undefined ? { view: loc.view } : {}), ...(loc.params !== undefined ? { params: { ...loc.params } } : {}), } } export class NavHistory { private entries: SerializedLocation[] private cursor: number private version = 0 private readonly listeners = new Set<() => void>() constructor(entries: SerializedLocation[], cursor: number) { this.entries = entries this.cursor = cursor } subscribe(listener: () => void): () => void { this.listeners.add(listener) return () => this.listeners.delete(listener) } getVersion(): number { return this.version } get current(): SerializedLocation | null { return this.entries[this.cursor] ?? null } get canBack(): boolean { return this.cursor > 0 } get canForward(): boolean { return this.cursor >= 0 && this.cursor < this.entries.length - 1 } snapshot(): NavSnapshot { return Object.freeze({ v: 1 as const, entries: Object.freeze(this.entries.map(cloneLocation)), cursor: this.cursor, }) } /** Push (or replace the current entry with) a location. No-op on same location. */ push(loc: SerializedLocation, replace: boolean): boolean { const cur = this.current if (cur !== null && sameLocation(cur, loc)) return false if (replace && cur !== null) { this.entries = [...this.entries] this.entries[this.cursor] = loc } else { this.entries = [...this.entries.slice(0, this.cursor + 1), loc] this.cursor = this.entries.length - 1 } this.emit() return true } back(): boolean { if (!this.canBack) return false this.cursor-- this.emit() return true } forward(): boolean { if (!this.canForward) return false this.cursor++ this.emit() return true } /** * Reconcile an externally-observed location (browser back/forward, URL edit): * step the cursor when it matches an adjacent entry, else push it fresh. */ syncExternal(loc: SerializedLocation): boolean { const cur = this.current if (cur !== null && sameLocation(cur, loc)) return false const back = this.entries[this.cursor - 1] if (back !== undefined && sameLocation(back, loc)) { this.cursor-- this.emit() return true } const fwd = this.entries[this.cursor + 1] if (fwd !== undefined && sameLocation(fwd, loc)) { this.cursor++ this.emit() return true } return this.push(loc, false) } /** Replace the whole stack (restore revalidation prune). */ reset(entries: readonly SerializedLocation[], cursor: number): void { this.entries = [...entries] this.cursor = cursor this.emit() } private emit(): void { this.version++ for (const listener of this.listeners) listener() } } /** * Seed the initial entries+cursor from the three sources, in precedence order: * a `restore` snapshot (revalidated later against the memory), then the * adapter's current read, then `initial`; empty (idle) when none yields one. * A live adapter read that disagrees with a restored cursor is appended as the * current entry (a deep link overrides the saved position but keeps its back * history). */ export function seedEntries( fromAdapter: SerializedLocation | null, restore: { readonly entries: readonly SerializedLocation[]; readonly cursor: number } | undefined, initialSerialized: SerializedLocation | null, ): { entries: SerializedLocation[]; cursor: number } { if (restore !== undefined && restore.entries.length > 0) { const entries = restore.entries.map(cloneLocation) let cursor = Math.min(Math.max(restore.cursor, 0), entries.length - 1) if (fromAdapter !== null && !sameLocation(fromAdapter, entries[cursor])) { entries.splice(cursor + 1) entries.push(cloneLocation(fromAdapter)) cursor = entries.length - 1 } return { entries, cursor } } if (fromAdapter !== null) return { entries: [cloneLocation(fromAdapter)], cursor: 0 } if (initialSerialized !== null) return { entries: [initialSerialized], cursor: 0 } return { entries: [], cursor: -1 } }