Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(web): Add the next split router (#7430)

dev-rb70dc84166e82
diff --git a/apps/web/biome.jsonc b/apps/web/biome.jsonc
index 11d131fa47..0368154192 100644
--- a/apps/web/biome.jsonc
+++ b/apps/web/biome.jsonc
@@ -48,6 +48,30 @@
}
}
},
+ {
+ "includes": [
+ "src/lib/split-router/next/routes/**",
+ "src/lib/split-router/next/router/run.ts",
+ "src/lib/split-router/next/router/url-gate.ts"
+ ],
+ "linter": {
+ "rules": {
+ "style": {
+ "noRestrictedImports": {
+ "level": "error",
+ "options": {
+ "patterns": [
+ {
+ "group": ["solid-js", "solid-js/**"],
+ "message": "The split router's route table and navigation machines are pure; keep Solid out of them."
+ }
+ ]
+ }
+ }
+ }
+ }
+ }
+ },
{
"includes": ["src/lib/service-clients/**/generated/**"],
"linter": {
diff --git a/apps/web/src/lib/split-router/next/history/browser.ts b/apps/web/src/lib/split-router/next/history/browser.ts
new file mode 100644
index 0000000000..999f5084b9
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/history/browser.ts
@@ -0,0 +1,116 @@
+import type { ExternalLocation } from '../routes/types';
+import {
+ createList,
+ hostPath,
+ normalizeBase,
+ readSlice,
+ revertChange,
+ stateForWrite,
+ toMountLocation,
+} from './shared';
+import type { ExternalChange, HistoryAdapter } from './types';
+
+export type BrowserHistoryOptions = {
+ base?: string;
+ /** Rewrites incoming mount-relative paths, such as legacy URLs. Current-format paths must come back unchanged. */
+ transformPath?: (path: string) => string;
+ window?: Window;
+};
+
+type Position = { index: number; state: unknown; location: ExternalLocation };
+
+/** Owns `window.history` directly. Never mount it alongside another router. */
+export function createBrowserHistory(
+ options: BrowserHistoryOptions = {}
+): HistoryAdapter {
+ const win = options.window ?? window;
+ const base = normalizeBase(options.base);
+ const listeners = createList<(change: ExternalChange) => void>();
+
+ const hasListeners = () => listeners.items().length > 0;
+
+ const read = (): ExternalLocation => {
+ const { pathname, search, hash } = win.location;
+ const current = `${pathname}${search}${hash}`;
+ const mounted = toMountLocation(current, base, options.transformPath);
+ const location = mounted ?? { path: '/', search: '', hash: '' };
+ const value = readSlice(win.history.state)?.value;
+
+ return value ? { ...location, state: value } : location;
+ };
+
+ const href = (location: Omit<ExternalLocation, 'state'>) =>
+ hostPath(base, location);
+
+ const position = (index: number): Position => ({
+ index,
+ state: win.history.state,
+ location: read(),
+ });
+
+ let last = position(readSlice(win.history.state)?.index ?? 0);
+
+ const goAndWait = (delta: number) =>
+ new Promise<void>((resolve) => {
+ win.addEventListener('popstate', () => resolve(), { once: true });
+ win.history.go(delta);
+ });
+
+ const putBack = (previous: Position) => {
+ win.history.replaceState(previous.state, '', href(previous.location));
+ last = previous;
+ };
+
+ const onPopState = () => {
+ const landed = readSlice(win.history.state);
+ const previous = last;
+ last = position(landed?.index ?? previous.index + 1);
+
+ const change: ExternalChange = {
+ location: last.location,
+ revert: () =>
+ revertChange(landed, previous.index, {
+ go: goAndWait,
+ replace: () => putBack(previous),
+ }),
+ };
+
+ for (const listener of listeners.items()) listener(change);
+ };
+
+ return {
+ read,
+
+ write(location, { mode }) {
+ const replace = mode === 'replace';
+ const index = replace ? last.index : last.index + 1;
+ const url = href(location);
+ const state = stateForWrite({
+ index,
+ location,
+ replace,
+ current: win.history.state,
+ });
+
+ if (replace) win.history.replaceState(state, '', url);
+ else win.history.pushState(state, '', url);
+
+ last = position(index);
+ },
+
+ subscribe(listener) {
+ if (!hasListeners()) win.addEventListener('popstate', onPopState);
+
+ const remove = listeners.add(listener);
+
+ return () => {
+ remove();
+ if (hasListeners()) return;
+
+ win.removeEventListener('popstate', onPopState);
+ };
+ },
+
+ href,
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/history/memory.ts b/apps/web/src/lib/split-router/next/history/memory.ts
new file mode 100644
index 0000000000..2c9061c5f6
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/history/memory.ts
@@ -0,0 +1,86 @@
+import { formatLocation, parseLocation } from '../routes/codec';
+import type { ExternalLocation, WriteMode } from '../routes/types';
+import { createList } from './shared';
+import type { ExternalChange, HistoryAdapter, InterceptHandler } from './types';
+
+export type MemoryHistory = HistoryAdapter & {
+ intercept(handler: InterceptHandler): () => void;
+ entries(): readonly ExternalLocation[];
+ index(): number;
+ go(delta: number): void;
+ back(): void;
+ forward(): void;
+ /** Another part of the app navigating; interceptors run first. */
+ navigate(to: string, options?: { replace?: boolean }): Promise<boolean>;
+};
+
+export function createMemoryHistory(
+ initial: string | ExternalLocation = '/'
+): MemoryHistory {
+ const first =
+ typeof initial === 'string' ? parseLocation(initial) : { ...initial };
+ let entries: ExternalLocation[] = [first];
+ let index = 0;
+ const listeners = createList<(change: ExternalChange) => void>();
+ const interceptors = createList<InterceptHandler>();
+
+ const apply = (location: ExternalLocation, mode: WriteMode) => {
+ if (mode === 'replace') {
+ entries = entries.with(index, location);
+ return;
+ }
+
+ entries = [...entries.slice(0, index + 1), location];
+ index += 1;
+ };
+
+ const emit = (revert: () => void) => {
+ const change: ExternalChange = { location: entries[index]!, revert };
+ for (const listener of listeners.items()) listener(change);
+ };
+
+ const go = (delta: number) => {
+ const lastIndex = entries.length - 1;
+ const target = Math.max(0, Math.min(lastIndex, index + delta));
+ if (target === index) return;
+
+ const previous = index;
+ index = target;
+ emit(() => {
+ index = previous;
+ });
+ };
+
+ return {
+ read: () => entries[index]!,
+ write: (location, { mode }) => apply(location, mode),
+ subscribe: listeners.add,
+ href: (location) => formatLocation(location),
+ intercept: interceptors.add,
+
+ entries: () => entries,
+ index: () => index,
+ go,
+ back: () => go(-1),
+ forward: () => go(1),
+
+ async navigate(to, navigateOptions = {}) {
+ const location = parseLocation(to);
+
+ for (const handler of interceptors.items()) {
+ const allowed = await handler(location);
+ if (!allowed) return false;
+ }
+
+ const previous = entries[index]!;
+ const mode: WriteMode = navigateOptions.replace ? 'replace' : 'push';
+ apply(location, mode);
+ // Like a browser, a pushed entry can't be removed; revert overwrites it.
+ emit(() => {
+ entries = entries.with(index, previous);
+ });
+
+ return true;
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/history/shared.ts b/apps/web/src/lib/split-router/next/history/shared.ts
new file mode 100644
index 0000000000..fc07e8cc03
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/history/shared.ts
@@ -0,0 +1,130 @@
+import {
+ formatLocation,
+ parseLocation,
+ readHistoryState,
+} from '../routes/codec';
+import type { ExternalLocation } from '../routes/types';
+import { isRecord, type MaybePromise } from '../utils';
+
+/** Where the adapters keep their slice of `history.state`. */
+export const STATE_KEY = '__splitRouter';
+
+/** The adapter's slice of `history.state`: its position in the session and the router's state. */
+export type HistorySlice = {
+ index: number;
+ value?: ExternalLocation['state'];
+};
+
+type StoredSlice = { index: number; value?: unknown };
+
+function isHistoryIndex(value: unknown): value is number {
+ if (typeof value !== 'number') return false;
+
+ return Number.isSafeInteger(value) && value >= 0;
+}
+
+function isStoredSlice(value: unknown): value is StoredSlice {
+ return isRecord(value) && isHistoryIndex(value.index);
+}
+
+export function readSlice(state: unknown): HistorySlice | undefined {
+ const stored = isRecord(state) ? state[STATE_KEY] : undefined;
+ if (!isStoredSlice(stored)) return;
+
+ return { index: stored.index, value: readHistoryState(stored.value) };
+}
+
+/**
+ * History state for a write. A push carries only our slice: hosts such as
+ * Solid Router stamp their own bookkeeping after a push, and inheriting the
+ * previous entry's would corrupt it. A replace keeps the host's state.
+ */
+export function stateForWrite(options: {
+ index: number;
+ location: ExternalLocation;
+ replace: boolean;
+ current: unknown;
+}): Record<string, unknown> {
+ const own = {
+ [STATE_KEY]: { index: options.index, value: options.location.state },
+ };
+ if (!options.replace) return own;
+
+ const hostState = isRecord(options.current) ? options.current : {};
+
+ return { ...hostState, ...own };
+}
+
+export function normalizeBase(base: string | undefined): string {
+ return (base ?? '').replace(/\/+$/, '');
+}
+
+/** `/app` holds `/app` and `/app/…`, never `/application`. */
+function isUnderBase(path: string, base: string): boolean {
+ if (!base) return true;
+
+ const lowerPath = path.toLowerCase();
+ const lowerBase = base.toLowerCase();
+ if (!lowerPath.startsWith(lowerBase)) return false;
+
+ const rest = lowerPath.slice(lowerBase.length);
+
+ return rest === '' || rest.startsWith('/');
+}
+
+/** The mount-relative location for a host path, or undefined outside the base. */
+export function toMountLocation(
+ hostPath: string,
+ base: string,
+ transformPath?: (path: string) => string
+): Omit<ExternalLocation, 'state'> | undefined {
+ const parsed = parseLocation(hostPath);
+ if (!isUnderBase(parsed.path, base)) return;
+
+ const relative = parsed.path.slice(base.length) || '/';
+ const path = transformPath?.(relative) ?? relative;
+
+ return { ...parsed, path };
+}
+
+export function hostPath(
+ base: string,
+ location: Omit<ExternalLocation, 'state'>
+): string {
+ return `${base}${formatLocation(location)}`;
+}
+
+/** Undo a reported change: step back when both positions are known, otherwise overwrite it. */
+export function revertChange(
+ landed: HistorySlice | undefined,
+ previousIndex: number,
+ host: { go(delta: number): MaybePromise<void>; replace(): MaybePromise<void> }
+): MaybePromise<void> {
+ const canStep = landed !== undefined && landed.index !== previousIndex;
+ if (canStep) return host.go(previousIndex - landed.index);
+
+ return host.replace();
+}
+
+type List<T> = {
+ add(item: T): () => void;
+ /** A copy, so items can be removed while iterating. */
+ items(): readonly T[];
+};
+
+export function createList<T>(): List<T> {
+ const items: T[] = [];
+
+ return {
+ add(item) {
+ items.push(item);
+
+ return () => {
+ const index = items.indexOf(item);
+ if (index >= 0) items.splice(index, 1);
+ };
+ },
+
+ items: () => [...items],
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/history/solid-router.ts b/apps/web/src/lib/split-router/next/history/solid-router.ts
new file mode 100644
index 0000000000..a69e739751
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/history/solid-router.ts
@@ -0,0 +1,351 @@
+import {
+ type BeforeLeaveEventArgs,
+ type Location,
+ type Navigator,
+ useBeforeLeave,
+ useLocation,
+ useNavigate,
+} from '@solidjs/router';
+import { createEffect, createRoot, on, untrack } from 'solid-js';
+import { formatLocation, sameExternalLocation } from '../routes/codec';
+import type { ExternalLocation } from '../routes/types';
+import type { MaybePromise } from '../utils';
+import {
+ createList,
+ type HistorySlice,
+ hostPath,
+ normalizeBase,
+ readSlice,
+ revertChange,
+ stateForWrite,
+ toMountLocation,
+} from './shared';
+import type { ExternalChange, HistoryAdapter, InterceptHandler } from './types';
+
+export type SolidRouterLocationLike = Pick<
+ Location,
+ 'pathname' | 'search' | 'hash' | 'state'
+>;
+
+export type SolidRouterNavigate = Navigator;
+
+export type SolidBeforeLeaveEvent = Pick<
+ BeforeLeaveEventArgs,
+ 'to' | 'defaultPrevented' | 'preventDefault' | 'retry'
+>;
+
+export type SolidRouterHistoryOptions = {
+ location: SolidRouterLocationLike;
+ navigate: SolidRouterNavigate;
+ /** Whether a mount-relative path belongs to the router rather than another route. */
+ owns: (path: string) => boolean;
+ /** Solid Router's `useBeforeLeave`; enables `intercept`. */
+ beforeLeave?: (listener: (event: SolidBeforeLeaveEvent) => void) => void;
+ /** The `base` passed to the Solid Router. */
+ base?: string;
+ /** `HashRouter` renders `#/path`. */
+ mode?: 'path' | 'hash';
+ /**
+ * Rewrites incoming mount-relative paths: the Router's `transformUrl`, which
+ * Solid applies only when matching routes, and upgrades of legacy URLs.
+ * Current-format paths must come back unchanged.
+ */
+ transformPath?: (path: string) => string;
+ /** The host path a Back or Forward landed on; defaults to `window.location`. */
+ landedPath?: () => string;
+};
+
+type Position = { index: number; location: ExternalLocation };
+
+type BeforeLeave = NonNullable<SolidRouterHistoryOptions['beforeLeave']>;
+
+async function settleIntercept(
+ verdict: Promise<boolean>,
+ event: SolidBeforeLeaveEvent,
+ onAllowed?: () => void
+): Promise<void> {
+ try {
+ if (!(await verdict)) return;
+
+ onAllowed?.();
+ event.retry(true);
+ } catch (error) {
+ console.error('Split router navigation guard failed', error);
+ }
+}
+
+/** Where the browser is now; Solid Router asks before-leave listeners before its `location` catches up. */
+function windowPath(mode: SolidRouterHistoryOptions['mode']): string {
+ const { pathname, search, hash } = window.location;
+ if (mode === 'hash') return hash.slice(1) || '/';
+
+ return `${pathname}${search}${hash}`;
+}
+
+export function createSolidRouterHistory(
+ options: SolidRouterHistoryOptions
+): HistoryAdapter {
+ const { location, navigate, owns, beforeLeave } = options;
+ const base = normalizeBase(options.base);
+ const listeners = createList<(change: ExternalChange) => void>();
+ let reverting: (() => void)[] = [];
+ let writing = false;
+ let queued: { location: ExternalLocation; pushed: boolean } | undefined;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let stopObserving: (() => void) | undefined;
+
+ const hasListeners = () => listeners.items().length > 0;
+ const hostState = () => untrack(() => location.state);
+ const ownSlice = () => readSlice(hostState());
+
+ const toMount = (path: string) =>
+ toMountLocation(path, base, options.transformPath);
+
+ const read = (): ExternalLocation =>
+ untrack(() => {
+ const path = toMount(location.pathname)?.path ?? '/';
+ const value = ownSlice()?.value;
+ const current = { path, search: location.search, hash: location.hash };
+
+ return value ? { ...current, state: value } : current;
+ });
+
+ let last: Position = { index: ownSlice()?.index ?? 0, location: read() };
+
+ const navigateTo = (
+ next: ExternalLocation,
+ index: number,
+ replace: boolean
+ ) => {
+ const state = stateForWrite({
+ index,
+ location: next,
+ replace,
+ current: hostState(),
+ });
+ // Before navigating: the write may land synchronously and must be recognized.
+ last = { index, location: next };
+ writing = true;
+
+ try {
+ navigate(formatLocation(next), { replace, scroll: false, state });
+ } finally {
+ writing = false;
+ }
+ };
+
+ const dropQueued = () => {
+ clearTimeout(timer);
+ timer = undefined;
+ queued = undefined;
+ };
+
+ const flush = () => {
+ const write = queued;
+ dropQueued();
+ if (!write) return;
+
+ const index = write.pushed ? last.index + 1 : last.index;
+ navigateTo(write.location, index, !write.pushed);
+ };
+
+ const settleReverts = () => {
+ const reverted = reverting;
+ reverting = [];
+ for (const resolve of reverted) resolve();
+ };
+
+ // Either way the revert lands as a location change.
+ const revertTo = (previous: Position, landed: HistorySlice | undefined) =>
+ new Promise<void>((resolve) => {
+ reverting.push(resolve);
+ revertChange(landed, previous.index, {
+ go: (delta) => navigate(delta),
+ replace: () => navigateTo(previous.location, previous.index, true),
+ });
+ });
+
+ const reportChange = () => {
+ const next = read();
+ const landed = ownSlice();
+ const samePosition = landed?.index === last.index;
+ const ownWriteLanded =
+ samePosition && sameExternalLocation(next, last.location);
+ // Our own write landing must not drop a newer write queued behind it.
+ if (ownWriteLanded) return;
+
+ // Anything else supersedes writes that haven't been sent yet.
+ dropQueued();
+
+ const outsideBase = !toMount(untrack(() => location.pathname));
+ if (outsideBase) return;
+ if (!owns(next.path)) return;
+
+ const previous = last;
+ last = { index: landed?.index ?? previous.index + 1, location: next };
+
+ const change: ExternalChange = {
+ location: next,
+ revert: () => revertTo(previous, landed),
+ };
+
+ for (const listener of listeners.items()) listener(change);
+ };
+
+ const onLocationChange = () => {
+ reportChange();
+ settleReverts();
+ };
+
+ const trackedLocation = () => [
+ location.pathname,
+ location.search,
+ location.hash,
+ location.state,
+ ];
+
+ const observe = () =>
+ createRoot((dispose) => {
+ createEffect(on(trackedLocation, onLocationChange, { defer: true }));
+
+ return dispose;
+ });
+
+ const stopObservingIfIdle = () => {
+ if (hasListeners()) return;
+
+ // With nobody listening, a queued write could only drag the host back in.
+ dropQueued();
+ stopObserving?.();
+ stopObserving = undefined;
+ // Unobserved, a revert's landing would never be seen.
+ settleReverts();
+ };
+
+ const ownedMount = (to: string) => {
+ const mount = toMount(to);
+ const owned = mount !== undefined && owns(mount.path);
+
+ return owned ? mount : undefined;
+ };
+
+ const landedPath = options.landedPath ?? (() => windowPath(options.mode));
+
+ /** Leaving the router's routes; a write still queued would pull the host back in. */
+ const leave = (
+ verdict: MaybePromise<boolean>,
+ event: SolidBeforeLeaveEvent
+ ) => {
+ if (verdict === true) {
+ dropQueued();
+ return;
+ }
+
+ event.preventDefault();
+ if (verdict === false) return;
+
+ void settleIntercept(verdict, event, dropQueued);
+ };
+
+ /** Back or Forward within the router's routes is the router's to follow; out of them, guards decide. */
+ const interceptTraversal = (
+ handler: InterceptHandler,
+ event: SolidBeforeLeaveEvent
+ ) => {
+ const staysInRouter = ownedMount(landedPath()) !== undefined;
+ if (staysInRouter) return;
+
+ leave(handler(undefined), event);
+ };
+
+ const interceptNavigation = (
+ handler: InterceptHandler,
+ event: SolidBeforeLeaveEvent,
+ to: string
+ ) => {
+ const mount = ownedMount(to);
+ if (!mount) {
+ leave(handler(undefined), event);
+ return;
+ }
+
+ const verdict = handler(mount);
+ if (verdict === true) return;
+
+ event.preventDefault();
+ if (verdict === false) return;
+
+ void settleIntercept(verdict, event);
+ };
+
+ const interceptLeave = (
+ handler: InterceptHandler,
+ event: SolidBeforeLeaveEvent
+ ) => {
+ const ignored = writing || event.defaultPrevented;
+ if (ignored) return;
+
+ const { to } = event;
+ if (typeof to === 'number') {
+ interceptTraversal(handler, event);
+ return;
+ }
+
+ interceptNavigation(handler, event, to);
+ };
+
+ const listenBeforeLeave = (listen: BeforeLeave, handler: InterceptHandler) =>
+ createRoot((dispose) => {
+ listen((event) => interceptLeave(handler, event));
+
+ return dispose;
+ });
+
+ return {
+ read,
+
+ write(next, { mode }) {
+ const alreadyPushed = queued?.pushed ?? false;
+ const pushed = alreadyPushed || mode === 'push';
+ queued = { location: next, pushed };
+ // A later task, not a microtask: starting Solid Router's transition while
+ // a pane is mounting can skip that pane's onMount callbacks.
+ timer ??= setTimeout(flush, 0);
+ },
+
+ subscribe(listener) {
+ const remove = listeners.add(listener);
+ stopObserving ??= observe();
+
+ return () => {
+ remove();
+ stopObservingIfIdle();
+ };
+ },
+
+ href(next) {
+ const host = hostPath(base, next);
+
+ return options.mode === 'hash' ? `#${host}` : host;
+ },
+
+ intercept: beforeLeave
+ ? (handler) => listenBeforeLeave(beforeLeave, handler)
+ : undefined,
+ };
+}
+
+/** The Solid Router adapter wired to the router mounted above the caller. */
+export function useSolidRouterHistory(
+ options: Omit<
+ SolidRouterHistoryOptions,
+ 'location' | 'navigate' | 'beforeLeave'
+ >
+): HistoryAdapter {
+ return createSolidRouterHistory({
+ ...options,
+ location: useLocation(),
+ navigate: useNavigate(),
+ beforeLeave: useBeforeLeave,
+ });
+}
diff --git a/apps/web/src/lib/split-router/next/history/types.ts b/apps/web/src/lib/split-router/next/history/types.ts
new file mode 100644
index 0000000000..5acd5ab6ec
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/history/types.ts
@@ -0,0 +1,34 @@
+import type { ExternalLocation, WriteMode } from '../routes/types';
+import type { MaybePromise } from '../utils';
+
+export type ExternalChange = {
+ location: ExternalLocation;
+ /**
+ * Put the host back where it was. Settles once it is: pane commands wait for
+ * it, so writes after it apply to the entry it returns to. It must always settle.
+ */
+ revert(): MaybePromise<void>;
+};
+
+/**
+ * Return false to stop the host applying a navigation it started. `location`
+ * is undefined when the host is leaving the router's routes.
+ */
+export type InterceptHandler = (
+ location: ExternalLocation | undefined
+) => MaybePromise<boolean>;
+
+/** Connects the router to whatever owns the real URL. */
+export interface HistoryAdapter {
+ read(): ExternalLocation;
+ /** May apply later, or merge with other writes. */
+ write(location: ExternalLocation, options: { mode: WriteMode }): void;
+ /**
+ * Location changes, in order. Reports may include this adapter's own writes
+ * and reverts landing; the router ignores locations it already shows.
+ */
+ subscribe(listener: (change: ExternalChange) => void): () => void;
+ /** A string for `<a href>` and copying, including base path and hash prefix. */
+ href(location: Omit<ExternalLocation, 'state'>): string;
+ intercept?(handler: InterceptHandler): () => void;
+}
diff --git a/apps/web/src/lib/split-router/next/index.ts b/apps/web/src/lib/split-router/next/index.ts
new file mode 100644
index 0000000000..aa4e0a0435
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/index.ts
@@ -0,0 +1,102 @@
+export {
+ type BrowserHistoryOptions,
+ createBrowserHistory,
+} from './history/browser';
+export { createMemoryHistory, type MemoryHistory } from './history/memory';
+export {
+ createSolidRouterHistory,
+ type SolidRouterHistoryOptions,
+ useSolidRouterHistory,
+} from './history/solid-router';
+export type {
+ ExternalChange,
+ HistoryAdapter,
+ InterceptHandler,
+} from './history/types';
+export { createMemoryPaneStore } from './panes/memory-store';
+export type {
+ OpenIntent,
+ OpenTarget,
+ PaneStore,
+ Placement,
+} from './panes/types';
+export type { ClaimHolder } from './router/claims';
+export { createSplitRouter, type SplitRouter } from './router/create-router';
+export { PANE_LEVEL } from './router/leave-guards';
+export type {
+ SplitRouterMiddleware,
+ SplitRouterMiddlewareContext,
+ SplitRouterMiddlewareResult,
+} from './router/middleware';
+export type { PendingNavigation } from './router/runner';
+export type {
+ ClaimOwner,
+ LeaveGuard,
+ LeaveGuardContext,
+ NavigationCause,
+ NavigationResult,
+ RouteMatchInfo,
+ SplitCloseAction,
+ SplitNavigateOptions,
+ SplitPanePolicy,
+ SplitRouterOptions,
+} from './router/types';
+export { defineRoute, defineRoutes } from './routes/define';
+export {
+ createSearchParamsCodec,
+ type SearchParamsCodec,
+ type SearchParamsCodecOptions,
+} from './routes/search-params';
+export type {
+ DefinedSplitRoute,
+ DefinedSplitRoutes,
+ Entry,
+ ExternalLocation,
+ InferSplitRouteBranchParams,
+ InferSplitRouteNavigationParams,
+ InferSplitRouteParams,
+ InferSplitRouteState,
+ InferSplitRouteStateInput,
+ PaneArrival,
+ PaneId,
+ PreloadIntent,
+ SerializedSearchParams,
+ SplitLocation,
+ SplitNavigationTarget,
+ SplitRouteClaim,
+ SplitRouteDefinition,
+ SplitRouteInfo,
+ SplitRouteMatch,
+ SplitRouteNavigationTarget,
+ SplitRouteParams,
+ SplitRouteState,
+ SplitRoutes,
+ SplitRouteUnion,
+ SplitSearchState,
+ SplitSearchUpdate,
+ WriteMode,
+} from './routes/types';
+export { SplitRouterProvider, useSplitRouter } from './solid/context';
+export {
+ type CreateSearchParamsOptions,
+ createSearchParams,
+ type SetSearchParams,
+} from './solid/create-search-params';
+export {
+ type SplitNavigate,
+ type SplitRouteNavigateOptions,
+ useArrival,
+ useCanGo,
+ useEntryProps,
+ useMatches,
+ useNavigate,
+ usePane,
+ useParams,
+ usePendingNavigation,
+ useRouteParams,
+ useRouteState,
+} from './solid/hooks';
+export { Outlet, type OutletProps } from './solid/outlet';
+export { PaneScope } from './solid/pane-scope';
+export { useBeforeLeave } from './solid/use-before-leave';
+export { useClaim } from './solid/use-claim';
diff --git a/apps/web/src/lib/split-router/next/panes/diff.ts b/apps/web/src/lib/split-router/next/panes/diff.ts
new file mode 100644
index 0000000000..d2b400fe4e
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/panes/diff.ts
@@ -0,0 +1,142 @@
+import { currentEntry, findEntry } from './history';
+import type { PaneEntry, PaneId, PaneSnapshot } from './types';
+
+/** A pane decoded from a URL, with its id when history state recorded one. */
+export type IncomingPane<E extends PaneEntry = PaneEntry> = {
+ paneId?: PaneId;
+ entry: E;
+};
+
+type PaneDiff<E extends PaneEntry = PaneEntry> =
+ | { kind: 'keep'; pane: PaneId }
+ /** `index` is set when the entry is already in the pane's history. */
+ | { kind: 'change'; pane: PaneId; from: E; to: E; index?: number }
+ | { kind: 'create'; pane: PaneId; entry: E };
+
+export type ChangedPane<E extends PaneEntry = PaneEntry> = Exclude<
+ PaneDiff<E>,
+ { kind: 'keep' }
+>;
+
+export type PanesDiff<E extends PaneEntry = PaneEntry> = {
+ /** One per incoming pane, in order. */
+ panes: readonly PaneDiff<E>[];
+ removed: readonly PaneId[];
+};
+
+export type LivePanes<E extends PaneEntry = PaneEntry> = {
+ panes: readonly PaneId[];
+ read(pane: PaneId): PaneSnapshot<E> | undefined;
+};
+
+export type DiffOptions<E extends PaneEntry = PaneEntry> = {
+ createPaneId(): PaneId;
+ /** Whether two entries show the same thing; a pane already showing it is kept. */
+ same(current: E, incoming: E): boolean;
+ /** What to show when `incoming` is already in a pane's history as `stored`. */
+ adopt?(stored: E, incoming: E): E;
+};
+
+/**
+ * How incoming panes line up with the open ones. Panes match by id, then
+ * by position; panes already showing their entry are kept so nothing remounts.
+ */
+export function diffPanes<E extends PaneEntry>(
+ live: LivePanes<E>,
+ incoming: readonly IncomingPane<E>[],
+ options: DiffOptions<E>
+): PanesDiff<E> {
+ const used: PaneId[] = [];
+ const isLive = (pane: PaneId) => live.panes.includes(pane);
+ const isUsed = (pane: PaneId) => used.includes(pane);
+
+ const showsSame = (pane: PaneId, entry: E) => {
+ const snapshot = live.read(pane);
+ if (!snapshot) return false;
+
+ return options.same(currentEntry(snapshot), entry);
+ };
+
+ const matchPane = (
+ { paneId, entry }: IncomingPane<E>,
+ position: number
+ ): PaneId | undefined => {
+ const liveAndFree = paneId && isLive(paneId) && !isUsed(paneId);
+ if (liveAndFree) return paneId;
+
+ const positional = live.panes[position];
+ const slotTaken = positional === undefined || isUsed(positional);
+ if (slotTaken) return;
+ if (!paneId) return positional;
+ if (isLive(paneId)) return;
+
+ // An id from history that no longer exists: reuse the pane in its slot
+ // only when it already shows the same thing.
+ return showsSame(positional, entry) ? positional : undefined;
+ };
+
+ const idForNewPane = (paneId: PaneId | undefined): PaneId => {
+ const reusable = paneId && !isLive(paneId) && !isUsed(paneId);
+
+ return reusable ? paneId : options.createPaneId();
+ };
+
+ const createPane = ({ paneId, entry }: IncomingPane<E>): PaneDiff<E> => {
+ const id = idForNewPane(paneId);
+ used.push(id);
+
+ return { kind: 'create', pane: id, entry };
+ };
+
+ const updatePane = (
+ pane: PaneId,
+ snapshot: PaneSnapshot<E>,
+ entry: E
+ ): PaneDiff<E> => {
+ used.push(pane);
+
+ const current = currentEntry(snapshot);
+ const stored = findEntry(snapshot, entry.id);
+ const movesCursor = stored !== undefined && stored.index !== snapshot.index;
+ const unchanged = !movesCursor && options.same(current, entry);
+ if (unchanged) return { kind: 'keep', pane };
+
+ if (!stored) return { kind: 'change', pane, from: current, to: entry };
+
+ const adopted = options.adopt?.(stored.entry, entry) ?? entry;
+
+ return {
+ kind: 'change',
+ pane,
+ from: current,
+ index: stored.index,
+ to: adopted,
+ };
+ };
+
+ const diffPane = (pane: IncomingPane<E>, position: number): PaneDiff<E> => {
+ const matched = matchPane(pane, position);
+ if (!matched) return createPane(pane);
+
+ const snapshot = live.read(matched);
+ if (!snapshot) return createPane(pane);
+
+ return updatePane(matched, snapshot, pane.entry);
+ };
+
+ const panes = incoming.map(diffPane);
+
+ return {
+ panes,
+ removed: live.panes.filter((pane) => !isUsed(pane)),
+ };
+}
+
+/** The panes a diff creates or changes, in order. */
+export function changedPanes<E extends PaneEntry>(
+ diff: PanesDiff<E>
+): ChangedPane<E>[] {
+ return diff.panes.filter(
+ (pane): pane is ChangedPane<E> => pane.kind !== 'keep'
+ );
+}
diff --git a/apps/web/src/lib/split-router/next/panes/history.ts b/apps/web/src/lib/split-router/next/panes/history.ts
new file mode 100644
index 0000000000..daed67f784
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/panes/history.ts
@@ -0,0 +1,135 @@
+import { match } from 'ts-pattern';
+import type {
+ HistoryTarget,
+ PaneChange,
+ PaneEntry,
+ PaneSnapshot,
+} from './types';
+
+export function currentEntry<E extends PaneEntry>(
+ snapshot: PaneSnapshot<E>
+): E {
+ return snapshot.entries[snapshot.index]!;
+}
+
+/** The entry as it stays in history after leaving it: one-shot props are dropped. */
+function leaveEntry<E extends PaneEntry>(entry: E): E {
+ const unchanged = entry.keepProps || entry.props === undefined;
+ if (unchanged) return entry;
+
+ const { props: _props, ...rest } = entry;
+
+ return rest as E;
+}
+
+export function applyHistoryChange<E extends PaneEntry>(
+ snapshot: PaneSnapshot<E>,
+ change: PaneChange<E>
+): PaneSnapshot<E> {
+ const { entries, index } = snapshot;
+ const afterLeave = () => entries.with(index, leaveEntry(entries[index]!));
+
+ return match<PaneChange<E>, PaneSnapshot<E>>(change)
+ .with({ type: 'push' }, ({ entry }) => ({
+ entries: [...afterLeave().slice(0, index + 1), entry],
+ index: index + 1,
+ }))
+ .with({ type: 'replace' }, ({ entry }) => ({
+ entries: entries.with(index, entry),
+ index,
+ }))
+ .with({ type: 'go' }, (go) => {
+ const outOfRange = go.index < 0 || go.index >= entries.length;
+ if (outOfRange) {
+ throw new Error(`Pane history has no entry at ${go.index}`);
+ }
+
+ const staying = go.index === index;
+ const base = staying ? entries : afterLeave();
+
+ return { entries: base.with(go.index, go.entry), index: go.index };
+ })
+ .with({ type: 'reset' }, (reset) => ({
+ entries: [...reset.entries],
+ index: reset.index,
+ }))
+ .exhaustive();
+}
+
+function hasIndex(entries: readonly unknown[], index: number): boolean {
+ return index >= 0 && index < entries.length;
+}
+
+/** Moves `delta` steps, counting only entries `visit` accepts. */
+export function findStep<E extends PaneEntry>(
+ snapshot: PaneSnapshot<E>,
+ delta: number,
+ visit: (entry: E) => boolean = () => true
+): HistoryTarget<E> | undefined {
+ const moves = Number.isSafeInteger(delta) && delta !== 0;
+ if (!moves) return;
+
+ const direction = delta < 0 ? -1 : 1;
+ let remaining = Math.abs(delta);
+
+ for (
+ let index = snapshot.index + direction;
+ hasIndex(snapshot.entries, index);
+ index += direction
+ ) {
+ const entry = snapshot.entries[index]!;
+ if (!visit(entry)) continue;
+
+ remaining -= 1;
+ if (remaining === 0) return { entry, index };
+ }
+}
+
+/** The nearest earlier entry matching `predicate` that `visit` accepts. */
+export function findBack<E extends PaneEntry>(
+ snapshot: PaneSnapshot<E>,
+ predicate: (entry: E) => boolean,
+ visit: (entry: E) => boolean = () => true
+): HistoryTarget<E> | undefined {
+ for (let index = snapshot.index - 1; index >= 0; index -= 1) {
+ const entry = snapshot.entries[index]!;
+ const found = visit(entry) && predicate(entry);
+ if (found) return { entry, index };
+ }
+}
+
+export function findEntry<E extends PaneEntry>(
+ snapshot: PaneSnapshot<E>,
+ entryId: string
+): HistoryTarget<E> | undefined {
+ const index = snapshot.entries.findIndex((entry) => entry.id === entryId);
+ if (index < 0) return;
+
+ return { entry: snapshot.entries[index]!, index };
+}
+
+/** Removes matching entries, keeping the cursor on the nearest survivor. */
+export function removeEntries<E extends PaneEntry>(
+ snapshot: PaneSnapshot<E>,
+ predicate: (entry: E) => boolean
+): PaneSnapshot<E> | undefined {
+ let index = snapshot.index;
+ const entries: E[] = [];
+
+ snapshot.entries.forEach((entry, position) => {
+ if (!predicate(entry)) {
+ entries.push(entry);
+ return;
+ }
+
+ const beforeCursor = position < snapshot.index;
+ if (beforeCursor) index -= 1;
+ });
+
+ if (entries.length === 0) return;
+
+ const lastIndex = entries.length - 1;
+ const cursor = Math.min(Math.max(index, 0), lastIndex);
+
+ return { entries, index: cursor };
+}
diff --git a/apps/web/src/lib/split-router/next/panes/index.ts b/apps/web/src/lib/split-router/next/panes/index.ts
new file mode 100644
index 0000000000..9da7e7ac4b
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/panes/index.ts
@@ -0,0 +1,16 @@
+export { createMemoryPaneStore } from './memory-store';
+export { createPanes, type Panes, type PanesOptions } from './panes';
+export type {
+ CloseAction,
+ HistoryTarget,
+ OpenIntent,
+ OpenTarget,
+ PaneArrival,
+ PaneChange,
+ PaneEntry,
+ PaneId,
+ PanePolicy,
+ PaneSnapshot,
+ PaneStore,
+ Placement,
+} from './types';
diff --git a/apps/web/src/lib/split-router/next/panes/memory-store.ts b/apps/web/src/lib/split-router/next/panes/memory-store.ts
new file mode 100644
index 0000000000..316b689032
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/panes/memory-store.ts
@@ -0,0 +1,47 @@
+import { type Accessor, createSignal, type Setter, untrack } from 'solid-js';
+import { applyHistoryChange } from './history';
+import type { PaneEntry, PaneId, PaneSnapshot, PaneStore } from './types';
+
+type Stored<E extends PaneEntry> = {
+ pane: PaneId;
+ read: Accessor<PaneSnapshot<E>>;
+ write: Setter<PaneSnapshot<E>>;
+};
+
+export function createMemoryPaneStore<
+ E extends PaneEntry = PaneEntry,
+>(): PaneStore<E> {
+ // The id list in `createPanes` is what makes new panes visible to readers.
+ const stored: Stored<E>[] = [];
+ const find = (pane: PaneId) => stored.find((item) => item.pane === pane);
+
+ return {
+ create(pane, entry) {
+ const snapshot: PaneSnapshot<E> = { entries: [entry], index: 0 };
+ const existing = find(pane);
+
+ if (existing) {
+ existing.write(() => snapshot);
+ return;
+ }
+
+ const [read, write] = createSignal(snapshot);
+ stored.push({ pane, read, write });
+ },
+
+ remove(pane) {
+ const index = stored.findIndex((item) => item.pane === pane);
+ if (index >= 0) stored.splice(index, 1);
+ },
+
+ read: (pane) => find(pane)?.read(),
+
+ apply(pane, change) {
+ const item = find(pane);
+ if (!item) throw new Error(`Pane "${pane}" has no history`);
+
+ const next = applyHistoryChange(untrack(item.read), change);
+ item.write(() => next);
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/panes/panes.ts b/apps/web/src/lib/split-router/next/panes/panes.ts
new file mode 100644
index 0000000000..49c6b54d7e
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/panes/panes.ts
@@ -0,0 +1,254 @@
+import { batch, createSignal, untrack } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { match } from 'ts-pattern';
+import { createId } from '../utils';
+import {
+ type ChangedPane,
+ changedPanes,
+ type DiffOptions,
+ diffPanes,
+ type IncomingPane,
+ type LivePanes,
+ type PanesDiff,
+} from './diff';
+import { currentEntry } from './history';
+import type {
+ CloseAction,
+ OpenIntent,
+ PaneArrival,
+ PaneChange,
+ PaneEntry,
+ PaneId,
+ PanePolicy,
+ PaneStore,
+ Placement,
+} from './types';
+
+function sameIds(left: readonly PaneId[], right: readonly PaneId[]): boolean {
+ const sameLength = left.length === right.length;
+
+ return sameLength && left.every((id, index) => id === right[index]);
+}
+
+function isOpenedSince(
+ decided: readonly PaneId[],
+ pane: PaneId | undefined
+): boolean {
+ return pane !== undefined && !decided.includes(pane);
+}
+
+function skipOpenedSince(
+ decided: readonly PaneId[],
+ current: readonly PaneId[],
+ start: number
+): number {
+ let index = start;
+ while (isOpenedSince(decided, current[index])) index += 1;
+
+ return index;
+}
+
+/**
+ * Where a pane placed at `insertAt` among `decided` goes in `current`: after
+ * the same pane as before, behind panes opened since, so concurrent opens keep
+ * their order.
+ */
+export function insertionIndex(
+ decided: readonly PaneId[],
+ insertAt: number,
+ current: readonly PaneId[]
+): number {
+ const at = Math.max(0, Math.min(insertAt, decided.length));
+ const after = at > 0 ? decided[at - 1] : undefined;
+ if (after === undefined) return skipOpenedSince(decided, current, 0);
+
+ const afterIndex = current.indexOf(after);
+ if (afterIndex < 0) return Math.min(at, current.length);
+
+ return skipOpenedSince(decided, current, afterIndex + 1);
+}
+
+const newPaneId = () => createId('pane') as PaneId;
+
+function historyChangeFor<E extends PaneEntry>(
+ entry: E,
+ index: number | undefined
+): PaneChange<E> {
+ if (index === undefined) return { type: 'push', entry };
+
+ return { type: 'go', index, entry };
+}
+
+export type PanesOptions<E extends PaneEntry, D> = {
+ store: PaneStore<E>;
+ policy: PanePolicy<E, D>;
+ createPaneId?: () => PaneId;
+ /** Runs for each pane that is removed. */
+ onRemove?: (pane: PaneId) => void;
+};
+
+/**
+ * The open panes, in order, with each one's history and how it arrived. It
+ * knows nothing about routes or rendering: callers decide what a pane shows
+ * and commit the result here, and the policy decides placement and closing.
+ */
+export function createPanes<E extends PaneEntry, D>(
+ options: PanesOptions<E, D>
+) {
+ const { store, policy } = options;
+ const [ids, setIds] = createSignal<readonly PaneId[]>([], {
+ equals: sameIds,
+ });
+ const [arrivals, setArrivals] = createStore<
+ Record<string, PaneArrival | undefined>
+ >({});
+ const createPaneId = options.createPaneId ?? newPaneId;
+
+ const current = (pane: PaneId): E | undefined => {
+ const snapshot = store.read(pane);
+ if (!snapshot) return;
+
+ return currentEntry(snapshot);
+ };
+
+ const arrange = (next: readonly PaneId[], changes: () => void) => {
+ batch(() => {
+ changes();
+ setIds(next);
+ });
+ };
+
+ const addPane = (pane: PaneId, entry: E) => {
+ store.create(pane, entry);
+ setArrivals(pane, 'fresh');
+ };
+
+ const forget = (pane: PaneId) => {
+ store.remove(pane);
+ setArrivals(pane, undefined);
+ options.onRemove?.(pane);
+ };
+
+ const arrivalFor = (
+ change: ChangedPane<E> & { kind: 'change' }
+ ): PaneArrival => {
+ if (change.index === undefined) return 'fresh';
+
+ const { index } = untrack(() => store.read(change.pane))!;
+ if (change.index === index) return 'replace';
+
+ return change.index < index ? 'back' : 'forward';
+ };
+
+ const applyChange = (change: ChangedPane<E>, entry: E) => {
+ match<ChangedPane<E>, void>(change)
+ .with({ kind: 'create' }, ({ pane }) => addPane(pane, entry))
+ .with({ kind: 'change' }, (changed) => {
+ setArrivals(changed.pane, arrivalFor(changed));
+ store.apply(changed.pane, historyChangeFor(entry, changed.index));
+ })
+ .exhaustive();
+ };
+
+ return {
+ ids,
+ read: (pane: PaneId) => store.read(pane),
+ current,
+ arrival: (pane: PaneId): PaneArrival => arrivals[pane] ?? 'fresh',
+ createPaneId,
+
+ /** Records a change to one pane's history. */
+ commit(pane: PaneId, change: PaneChange<E>, arrival?: PaneArrival) {
+ batch(() => {
+ store.apply(pane, change);
+ if (arrival) setArrivals(pane, arrival);
+ });
+ },
+
+ /** Adds a pane at `insertAt` as chosen against `decided`, the panes at the time. */
+ insert(
+ pane: PaneId,
+ entry: E,
+ insertAt: number,
+ decided: readonly PaneId[] = untrack(ids)
+ ) {
+ const next = [...untrack(ids)];
+ const at = insertionIndex(decided, insertAt, next);
+ next.splice(at, 0, pane);
+ arrange(next, () => addPane(pane, entry));
+ },
+
+ remove(pane: PaneId) {
+ const next = untrack(ids).filter((id) => id !== pane);
+ arrange(next, () => forget(pane));
+ },
+
+ /** False when `pane` isn't open or already sits at `to`. */
+ move(pane: PaneId, to: number): boolean {
+ const before = untrack(ids);
+ if (!before.includes(pane)) return false;
+
+ const next = before.filter((id) => id !== pane);
+ const at = Math.max(0, Math.min(to, next.length));
+ next.splice(at, 0, pane);
+ if (sameIds(before, next)) return false;
+
+ setIds(next);
+
+ return true;
+ },
+
+ /** How `incoming` lines up with the open panes. */
+ diff(
+ incoming: readonly IncomingPane<E>[],
+ diffOptions: Omit<DiffOptions<E>, 'createPaneId'>
+ ): PanesDiff<E> {
+ const live: LivePanes<E> = {
+ panes: untrack(ids),
+ read: (pane) => untrack(() => store.read(pane)),
+ };
+
+ return diffPanes(live, incoming, { ...diffOptions, createPaneId });
+ },
+
+ /** Applies `diff`; `entries` are what its changed panes show, in order. */
+ applyDiff(diff: PanesDiff<E>, entries: readonly E[]) {
+ const next = diff.panes.map((item) => item.pane);
+
+ arrange(next, () => {
+ for (const pane of diff.removed) forget(pane);
+
+ changedPanes(diff).forEach((change, position) => {
+ applyChange(change, entries[position]!);
+ });
+ });
+ },
+
+ placeNewPane(request: {
+ destination: D;
+ source?: PaneId;
+ intent?: OpenIntent;
+ holder?: PaneId;
+ allowDuplicate?: boolean;
+ opening?: number;
+ }): Placement {
+ return policy.placeNewPane({
+ ...request,
+ intent: request.intent ?? {},
+ allowDuplicate: request.allowDuplicate ?? false,
+ opening: request.opening ?? 0,
+ panes: untrack(ids),
+ });
+ },
+
+ closeAction(pane: PaneId): CloseAction<E, D> {
+ return policy.closeAction({ pane, panes: untrack(ids) });
+ },
+
+ activate: (pane: PaneId) => policy.activate(pane),
+ };
+}
+
+export type Panes<E extends PaneEntry = PaneEntry, D = unknown> = ReturnType<
+ typeof createPanes<E, D>
+>;
diff --git a/apps/web/src/lib/split-router/next/panes/types.ts b/apps/web/src/lib/split-router/next/panes/types.ts
new file mode 100644
index 0000000000..be2d7b3f74
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/panes/types.ts
@@ -0,0 +1,98 @@
+/** One independent navigation history; stable for the pane's lifetime. */
+export type PaneId = string & { readonly PaneId: unique symbol };
+
+/** How a pane reached its current entry. */
+export type PaneArrival = 'fresh' | 'back' | 'forward' | 'replace';
+
+/** What a pane's history holds. `props` are handed over once unless `keepProps` is set. */
+export type PaneEntry = {
+ readonly id: string;
+ readonly props?: unknown;
+ readonly keepProps?: boolean;
+};
+
+export type PaneSnapshot<E extends PaneEntry = PaneEntry> = {
+ readonly entries: readonly E[];
+ readonly index: number;
+};
+
+export type PaneChange<E extends PaneEntry = PaneEntry> =
+ | { type: 'push'; entry: E }
+ | { type: 'replace'; entry: E }
+ /** Move to `index`; `entry` replaces the landed slot when a redirect changed it. */
+ | { type: 'go'; index: number; entry: E }
+ | { type: 'reset'; entries: readonly E[]; index: number };
+
+export type HistoryTarget<E extends PaneEntry = PaneEntry> = {
+ entry: E;
+ index: number;
+};
+
+/**
+ * Where each pane's entries live. `createPanes` reads it and commits changes
+ * to it; implementations never move on their own. Reads of a live pane must be reactive.
+ */
+export interface PaneStore<E extends PaneEntry = PaneEntry> {
+ create(pane: PaneId, entry: E): void;
+ remove(pane: PaneId): void;
+ read(pane: PaneId): PaneSnapshot<E> | undefined;
+ apply(pane: PaneId, change: PaneChange<E>): void;
+}
+
+/** Where a destination lands: an existing pane, or a new pane at an index. */
+export type Placement = { pane: PaneId } | { insertAt: number };
+
+/** The caller's hints for placing a new pane. Policies extend this interface through declaration merging. */
+export interface OpenIntent {
+ readonly [key: string]: unknown;
+}
+
+export type OpenTarget =
+ | { pane: PaneId }
+ | { newPane: true; source?: PaneId; intent?: OpenIntent };
+
+/** What closing a pane does once it is allowed to close. */
+export type CloseAction<E extends PaneEntry = PaneEntry, D = unknown> =
+ | { type: 'remove' }
+ | { type: 'keep' }
+ /** Show `destination` instead; `replace` leaves no back entry to the closed one. */
+ | { type: 'navigate'; destination: D; replace?: boolean }
+ /** Go back to the nearest earlier entry matching `to`; with none, do `otherwise` (keep by default). A refused jump keeps the pane. */
+ | {
+ type: 'back-to';
+ to: (entry: E) => boolean;
+ otherwise?: CloseAction<E, D>;
+ };
+
+/**
+ * The app's decisions about panes: where a new one goes, what closing one
+ * means, and what activating one does. The router asks; it never decides.
+ */
+export interface PanePolicy<E extends PaneEntry = PaneEntry, D = unknown> {
+ /**
+ * Where an open that asks for a new pane lands, for example the source
+ * pane when there are enough. Returning `holder` brings it up; placing a
+ * new pane beside it shows the destination twice.
+ */
+ placeNewPane(request: {
+ destination: D;
+ source?: PaneId;
+ intent: OpenIntent;
+ panes: readonly PaneId[];
+ /** The pane already showing the destination, if any. */
+ holder?: PaneId;
+ /** The caller accepts a second view of what `holder` shows. */
+ allowDuplicate: boolean;
+ /** New panes still opening; `panes` doesn't include them yet. */
+ opening: number;
+ }): Placement;
+
+ /** What closing a pane means, for example returning the last pane to a list instead of removing it. */
+ closeAction(request: {
+ pane: PaneId;
+ panes: readonly PaneId[];
+ }): CloseAction<E, D>;
+
+ /** Called when an open lands on a pane that already shows the destination, and by `router.activatePane`. */
+ activate(pane: PaneId): void;
+}
diff --git a/apps/web/src/lib/split-router/next/router/claims.ts b/apps/web/src/lib/split-router/next/router/claims.ts
new file mode 100644
index 0000000000..0465a7f068
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/claims.ts
@@ -0,0 +1,243 @@
+import { createStore, produce } from 'solid-js/store';
+import type { SplitRoutesManifest } from '../routes/manifest';
+import { claimOf } from '../routes/queries';
+import type { Entry, PaneId, SplitLocation, WriteMode } from '../routes/types';
+import type { Runner } from './runner';
+import type { ClaimOwner, NavigationResult, RouterPanes } from './types';
+
+export type ClaimHolder = {
+ owner: ClaimOwner;
+ /** The pane showing this holder, if any. Navigation in that pane never yields to it. */
+ pane?: PaneId;
+ claim: string;
+ activate(): void;
+};
+
+type ClaimSource = () => readonly ClaimHolder[];
+
+/** Who currently shows each resource: panes, inline previews and popovers. */
+type ClaimsRegistry = {
+ holderOf(claim: string, excludePane?: PaneId): ClaimHolder | undefined;
+ register(source: ClaimSource): () => void;
+};
+
+/** Who is about to show an entry, for choosing the holder that shows it instead. */
+type ClaimCheck = {
+ /** The pane the entry would show in; holders there don't count. */
+ pane?: PaneId;
+ /** What that pane showed; a claim it already held is not a new acquisition. */
+ from?: Entry;
+ allowDuplicate?: boolean;
+ /** A pane the placement policy was told shows the entry and opened a new pane beside. */
+ besides?: PaneId;
+};
+
+/** A visit or open about to apply. */
+type Acquisition = ClaimCheck & {
+ /** How the holder takes the entry's search when it is brought up instead. */
+ mode: WriteMode;
+};
+
+export type Claims = ReturnType<typeof createClaims>;
+
+/** The claim an entry holds, if its route declares one. */
+function entryClaim(
+ routes: SplitRoutesManifest,
+ entry: Pick<Entry, 'location'> | undefined
+): string | undefined {
+ if (!entry) return;
+
+ return claimOf(routes, entry.location.route);
+}
+
+/** A pane showing the resource itself, not a preview shown inside a pane. */
+function isPaneHolder(
+ holder: ClaimHolder | undefined
+): holder is ClaimHolder & { pane: PaneId } {
+ if (!holder) return false;
+
+ return holder.pane !== undefined && holder.owner === holder.pane;
+}
+
+function isInPane(holder: ClaimHolder, pane: PaneId): boolean {
+ const shownInPane = holder.pane === pane;
+
+ return shownInPane || holder.owner === pane;
+}
+
+function holdsClaim(
+ holder: ClaimHolder,
+ claim: string,
+ excludePane: PaneId | undefined
+): boolean {
+ if (holder.claim !== claim) return false;
+ if (excludePane === undefined) return true;
+
+ return !isInPane(holder, excludePane);
+}
+
+function createRegistry(): ClaimsRegistry {
+ const [state, setState] = createStore<{ sources: ClaimSource[] }>({
+ sources: [],
+ });
+
+ const addSource = (source: ClaimSource) => {
+ setState(
+ produce((draft) => {
+ draft.sources.push(source);
+ })
+ );
+ };
+
+ const removeSource = (source: ClaimSource) => {
+ setState(
+ produce((draft) => {
+ const index = draft.sources.indexOf(source);
+ if (index >= 0) draft.sources.splice(index, 1);
+ })
+ );
+ };
+
+ return {
+ holderOf(claim, excludePane) {
+ for (const source of state.sources) {
+ const holder = source().find((candidate) =>
+ holdsClaim(candidate, claim, excludePane)
+ );
+ if (holder) return holder;
+ }
+ },
+
+ register(source) {
+ addSource(source);
+
+ return () => removeSource(source);
+ },
+ };
+}
+
+/**
+ * Who shows each resource a route claims. A visit or open landing on a claim
+ * shown elsewhere brings that holder up instead, unless the caller allows a
+ * duplicate or the placement policy opened beside it. Which routes claim, and
+ * where duplicates may open, is the app's to decide.
+ */
+export function createClaims(options: {
+ routes: SplitRoutesManifest;
+ panes: RouterPanes;
+ runner: Runner;
+ /** Carries `destination`'s search to `pane`, which already shows it, once the current commit is done. */
+ carrySearch(pane: PaneId, destination: Entry, mode: WriteMode): void;
+}) {
+ const { routes, panes, runner } = options;
+ const registry = createRegistry();
+
+ const paneHolders = (): ClaimHolder[] =>
+ panes.ids().flatMap((pane) => {
+ const claim = entryClaim(routes, panes.current(pane));
+ if (!claim) return [];
+
+ const activate = () => panes.activate(pane);
+
+ return [{ owner: pane, pane, claim, activate }];
+ });
+
+ const unregisterPanes = registry.register(paneHolders);
+
+ /** The holder that shows `entry` instead, if any. */
+ const holderFor = (
+ check: ClaimCheck,
+ entry: Pick<Entry, 'location'>
+ ): ClaimHolder | undefined => {
+ if (check.allowDuplicate) return;
+
+ const claim = entryClaim(routes, entry);
+ if (!claim) return;
+
+ // Changing params or search without changing the pane's claim is not a new acquisition.
+ const alreadyHeld = claim === entryClaim(routes, check.from);
+ if (alreadyHeld) return;
+
+ const holder = registry.holderOf(claim, check.pane);
+ if (!holder) return;
+
+ const openedBeside =
+ check.besides !== undefined && isInPane(holder, check.besides);
+ if (openedBeside) return;
+
+ return holder;
+ };
+
+ /** Whether the pane's run would move it off `claim`. */
+ const leavesClaim = (pane: PaneId, claim: string) => {
+ const navigation = runner.inFlight(pane);
+ if (!navigation) return false;
+
+ const target = navigation.targets.find(
+ (candidate) => candidate.pane === pane
+ );
+ if (!target) return true;
+
+ return entryClaim(routes, target.to) !== claim;
+ };
+
+ /** Keeps the holder's pane on the resource, hands it the search, and brings it up. */
+ const yieldTo = (
+ holder: ClaimHolder,
+ destination: Entry,
+ mode: WriteMode
+ ): NavigationResult => {
+ if (isPaneHolder(holder)) {
+ const departing = leavesClaim(holder.pane, holder.claim);
+ if (departing) runner.abort(holder.pane);
+
+ options.carrySearch(holder.pane, destination, mode);
+ }
+
+ holder.activate();
+
+ return { status: 'activated', owner: holder.owner };
+ };
+
+ return {
+ registry,
+
+ /** Runs `apply` unless another pane or preview already shows `entry`. */
+ applyUnlessHeld(
+ acquisition: Acquisition,
+ entry: Entry,
+ apply: () => NavigationResult
+ ): NavigationResult {
+ const holder = holderFor(acquisition, entry);
+ if (!holder) return apply();
+
+ return yieldTo(holder, entry, acquisition.mode);
+ },
+
+ /** Brings up `pane`, which already shows what was opened. */
+ reveal(pane: PaneId): NavigationResult {
+ panes.activate(pane);
+
+ return { status: 'activated', owner: pane };
+ },
+
+ /** Back and Forward in `pane` skip entries shown elsewhere, unless duplicates are allowed. */
+ canVisit(pane: PaneId, allowDuplicate?: boolean) {
+ return (entry: Entry) => {
+ const holder = holderFor({ pane, allowDuplicate }, entry);
+
+ return holder === undefined;
+ };
+ },
+
+ /** The pane showing `location`'s resource, not a preview inside some pane. */
+ paneShowing(location: SplitLocation): PaneId | undefined {
+ const holder = holderFor({}, { location });
+ if (!isPaneHolder(holder)) return;
+
+ return holder.pane;
+ },
+
+ dispose: unregisterPanes,
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/router/create-router.ts b/apps/web/src/lib/split-router/next/router/create-router.ts
new file mode 100644
index 0000000000..89332f3562
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/create-router.ts
@@ -0,0 +1,147 @@
+import { createSignal, untrack } from 'solid-js';
+import { createPanes } from '../panes/panes';
+import { createRoutesManifest, resolveBranch } from '../routes/manifest';
+import type {
+ Entry,
+ PaneId,
+ PreloadIntent,
+ SplitLocation,
+} from '../routes/types';
+import { UNCANCELLABLE } from '../utils';
+import { createClaims } from './claims';
+import { createLeaveGuards } from './leave-guards';
+import { createPaneList } from './pane-list';
+import { createPaneNavigation } from './pane-navigation';
+import { createPhaseScopes } from './phases';
+import { preloadLocation } from './preload';
+import { createRunner } from './runner';
+import type { RouteMatchInfo, SplitRouterOptions } from './types';
+import { createUrl } from './url';
+import { createUrlNavigation } from './url-navigation';
+
+export function createSplitRouter(options: SplitRouterOptions) {
+ const routes = createRoutesManifest(options.routes);
+ const { history } = options;
+ const [ready, setReady] = createSignal(false);
+ let disposed = false;
+
+ const guards = createLeaveGuards();
+
+ const panes = createPanes<Entry, SplitLocation>({
+ store: options.paneStore,
+ policy: options.policy,
+ createPaneId: options.createPaneId,
+ onRemove: guards.forget,
+ });
+
+ const url = createUrl({ routes, history, panes });
+
+ const phaseOptions = {
+ routes,
+ middleware: options.middleware ?? [],
+ guards,
+ current: (pane: PaneId) => untrack(() => panes.current(pane)),
+ preloadBudgetMs: options.preloadBudgetMs ?? 150,
+ };
+
+ const runner = createRunner({
+ phases: (waiting) => createPhaseScopes(phaseOptions, waiting),
+ live: () => untrack(panes.ids),
+ });
+
+ const claims = createClaims({
+ routes,
+ panes,
+ runner,
+ carrySearch: (pane, destination, mode) =>
+ paneNavigation.carrySearch(pane, destination, mode),
+ });
+
+ const paneNavigation = createPaneNavigation({
+ routes,
+ panes,
+ url,
+ runner,
+ claims,
+ });
+
+ const paneList = createPaneList({
+ routes,
+ panes,
+ url,
+ runner,
+ claims,
+ navigation: paneNavigation,
+ });
+
+ const urlNavigation = createUrlNavigation({
+ routes,
+ history,
+ panes,
+ url,
+ runner,
+ guards,
+ markReady: () => setReady(true),
+ });
+
+ const disconnect = urlNavigation.connect();
+
+ const matches = (pane: PaneId): RouteMatchInfo[] => {
+ const entry = panes.current(pane);
+ if (!entry) return [];
+
+ const { route } = entry.location;
+
+ return resolveBranch(routes, route).map((node, depth) => ({
+ id: node.definition.id,
+ params: route.matches[depth]!.params,
+ info: node.definition.info,
+ }));
+ };
+
+ const preload = (
+ location: SplitLocation,
+ intent: PreloadIntent = 'hover'
+ ): Promise<unknown> | undefined => {
+ const context = { location, intent, signal: UNCANCELLABLE };
+
+ return untrack(() => preloadLocation(routes, context));
+ };
+
+ const dispose = (): void => {
+ if (disposed) return;
+
+ disposed = true;
+ disconnect();
+ runner.dispose();
+ claims.dispose();
+ };
+
+ return {
+ routes,
+ claims: claims.registry,
+ ready,
+ panes: panes.ids,
+ navigate: paneNavigation.navigate,
+ updateSearch: paneNavigation.updateSearch,
+ goBackTo: paneNavigation.goBackTo,
+ removeEntries: paneNavigation.removeEntries,
+ rewriteCurrent: paneNavigation.rewriteCurrent,
+ canGo: paneNavigation.canGo,
+ open: paneList.open,
+ close: paneList.close,
+ move: paneList.move,
+ entry: panes.current,
+ arrival: panes.arrival,
+ pending: runner.pending,
+ matches,
+ preload,
+ href: url.href,
+ activatePane: panes.activate,
+ registerGuard: guards.register,
+ settled: runner.settled,
+ dispose,
+ };
+}
+
+export type SplitRouter = ReturnType<typeof createSplitRouter>;
diff --git a/apps/web/src/lib/split-router/next/router/entries.ts b/apps/web/src/lib/split-router/next/router/entries.ts
new file mode 100644
index 0000000000..eb0af774a0
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/entries.ts
@@ -0,0 +1,163 @@
+import deepEqual from 'fast-deep-equal';
+import { leafNode, type SplitRoutesManifest } from '../routes/manifest';
+import { filterRouteSearch, parseRouteEntryState } from '../routes/queries';
+import { locationOf } from '../routes/search';
+import type { Entry, SplitLocation, WriteMode } from '../routes/types';
+import { createId } from '../utils';
+
+export type EntryOptions = {
+ /** A value, or an update from the current state when the route's state schema is unchanged. */
+ state?: unknown;
+ props?: unknown;
+ keepProps?: boolean;
+ meta?: Readonly<Record<string, unknown>>;
+};
+
+/** Two entries show the same thing: same location and same route state. */
+export function sameVisit(left: Entry, right: Entry): boolean {
+ return (
+ deepEqual(left.location, right.location) &&
+ deepEqual(left.state, right.state)
+ );
+}
+
+function sameStateSchema(
+ routes: SplitRoutesManifest,
+ left: SplitLocation,
+ right: SplitLocation
+): boolean {
+ const leftSchema = leafNode(routes, left.route).state;
+ const rightSchema = leafNode(routes, right.route).state;
+
+ return leftSchema === rightSchema;
+}
+
+function currentState(
+ routes: SplitRoutesManifest,
+ location: SplitLocation,
+ from: Entry | undefined
+): unknown {
+ if (!from) return;
+ if (!sameStateSchema(routes, from.location, location)) return;
+
+ return from.state;
+}
+
+function applyStateUpdate(update: unknown, current: unknown): unknown {
+ if (typeof update !== 'function') return update;
+
+ return (update as (current: unknown) => unknown)(current);
+}
+
+function cloneState(value: unknown): unknown {
+ try {
+ return structuredClone(value);
+ } catch (error) {
+ console.warn(
+ 'Split route state could not be cloned; continuing without state',
+ error
+ );
+ }
+}
+
+function resolveState(
+ routes: SplitRoutesManifest,
+ location: SplitLocation,
+ from: Entry | undefined,
+ update: unknown
+): unknown {
+ const existing = currentState(routes, location, from);
+ const value = applyStateUpdate(update, existing);
+ const parsed = parseRouteEntryState(routes, location.route, value);
+
+ if (!parsed.success) {
+ const leaf = location.route.matches[location.route.matches.length - 1]!;
+ throw new Error(`Split route "${leaf.id}" rejected navigation state`);
+ }
+
+ if (parsed.value === undefined) return;
+
+ return cloneState(parsed.value);
+}
+
+export function createEntry(
+ routes: SplitRoutesManifest,
+ location: SplitLocation,
+ from: Entry | undefined,
+ options: EntryOptions
+): Entry {
+ const entry: Entry = { id: createId('entry'), location };
+
+ if (Object.hasOwn(options, 'state')) {
+ const state = resolveState(routes, location, from, options.state);
+ if (state !== undefined) entry.state = state;
+ }
+
+ if (options.props !== undefined) entry.props = options.props;
+ if (options.keepProps) entry.keepProps = true;
+ if (options.meta) entry.meta = options.meta;
+
+ return entry;
+}
+
+/** A search change as a new visit: a new id, and props only when they are kept. */
+function searchEntry(from: Entry, location: SplitLocation): Entry {
+ const { props, keepProps, ...rest } = from;
+ const entry: Entry = { ...rest, id: createId('entry'), location };
+ if (keepProps) return { ...entry, props, keepProps };
+
+ return entry;
+}
+
+/** A pushed search change is a new entry; a replaced one rewrites the current entry. */
+export function searchVisitEntry(
+ from: Entry,
+ location: SplitLocation,
+ mode: WriteMode
+): Entry {
+ if (mode === 'push') return searchEntry(from, location);
+
+ return { ...from, location };
+}
+
+/**
+ * `owner`'s location with the search `destination` asked for, in the
+ * namespaces `owner`'s route owns. Undefined when that changes nothing.
+ */
+export function mergeDestinationSearch(
+ routes: SplitRoutesManifest,
+ owner: Entry,
+ destination: Entry
+): SplitLocation | undefined {
+ const incoming = destination.location.search;
+ if (!incoming) return;
+
+ const { route } = owner.location;
+ const merged = { ...owner.location.search, ...incoming };
+ const search = filterRouteSearch(routes, route, merged);
+ if (deepEqual(search, owner.location.search)) return;
+
+ return locationOf(route, search);
+}
+
+/** Re-parse state after a redirect only when the destination's state schema differs. */
+export function withValidState(
+ routes: SplitRoutesManifest,
+ entry: Entry,
+ original: Entry
+): Entry {
+ if (entry.state === undefined) return entry;
+ if (sameStateSchema(routes, entry.location, original.location)) return entry;
+
+ const parsed = parseRouteEntryState(
+ routes,
+ entry.location.route,
+ entry.state
+ );
+ const state = parsed.success ? parsed.value : undefined;
+ if (state !== undefined) return { ...entry, state };
+
+ const { state: _state, ...withoutState } = entry;
+
+ return withoutState;
+}
diff --git a/apps/web/src/lib/split-router/next/router/leave-guards.ts b/apps/web/src/lib/split-router/next/router/leave-guards.ts
new file mode 100644
index 0000000000..0c84ea9e7c
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/leave-guards.ts
@@ -0,0 +1,86 @@
+import type { PaneId } from '../routes/types';
+import { isPromise, type MaybePromise, mapMaybe, settleMaybe } from '../utils';
+import type { LeaveGuard, LeaveGuardContext } from './types';
+
+type RegisteredGuard = { pane: PaneId; depth: number; guard: LeaveGuard };
+
+/** One guard bound to what it is asked about. */
+export type Check = () => MaybePromise<boolean>;
+
+export type LeaveGuards = ReturnType<typeof createLeaveGuards>;
+
+/**
+ * Where guards from a pane's chrome sit: above its first route, as inside a
+ * `<PaneScope>`. Only removing the pane or leaving the router asks them.
+ */
+export const PANE_LEVEL = -1;
+
+export function createLeaveGuards() {
+ const registered: RegisteredGuard[] = [];
+
+ return {
+ /** `depth` is the outlet depth of the view that registers the guard. */
+ register(pane: PaneId, depth: number, guard: LeaveGuard): () => void {
+ const item = { pane, depth, guard };
+ registered.push(item);
+
+ return () => {
+ const index = registered.indexOf(item);
+ if (index >= 0) registered.splice(index, 1);
+ };
+ },
+
+ forget(pane: PaneId): void {
+ for (let index = registered.length - 1; index >= 0; index -= 1) {
+ if (registered[index]!.pane === pane) registered.splice(index, 1);
+ }
+ },
+
+ /** Guards of `pane` at or below `fromDepth`, i.e. those a navigation from there unmounts. */
+ select(pane: PaneId, fromDepth: number): LeaveGuard[] {
+ const unmounted = (item: RegisteredGuard) =>
+ item.pane === pane && item.depth >= fromDepth;
+
+ return registered.filter(unmounted).map((item) => item.guard);
+ },
+ };
+}
+
+export function checksFor(
+ guards: readonly LeaveGuard[],
+ context: LeaveGuardContext
+): Check[] {
+ return guards.map((guard) => () => guard(context));
+}
+
+function allowOnError(error: unknown): boolean {
+ console.error('Split router leave guard failed', error);
+
+ return true;
+}
+
+function resumeChecks(
+ verdict: Promise<boolean>,
+ checks: readonly Check[],
+ next: number
+): MaybePromise<boolean> {
+ return mapMaybe(
+ verdict,
+ (allowed) => allowed && runChecks(checks.slice(next))
+ );
+}
+
+/** Runs checks in order until one refuses; a failing guard is logged and allows. */
+export function runChecks(checks: readonly Check[]): MaybePromise<boolean> {
+ for (const [position, check] of checks.entries()) {
+ const verdict = settleMaybe(check, allowOnError);
+
+ if (isPromise(verdict)) {
+ return resumeChecks(verdict, checks, position + 1);
+ }
+
+ if (!verdict) return false;
+ }
+
+ return true;
+}
diff --git a/apps/web/src/lib/split-router/next/router/middleware.ts b/apps/web/src/lib/split-router/next/router/middleware.ts
new file mode 100644
index 0000000000..09ec46bd55
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/middleware.ts
@@ -0,0 +1,158 @@
+import { formatPanePath } from '../routes/codec';
+import type { SplitRoutesManifest } from '../routes/manifest';
+import { filterRouteSearch } from '../routes/queries';
+import { locationOf } from '../routes/search';
+import { resolveTarget } from '../routes/targets';
+import type { Entry } from '../routes/types';
+import {
+ andThen,
+ CANCELLED,
+ isAbortError,
+ type MaybePromise,
+ type Outcome,
+ settleMaybe,
+} from '../utils';
+import type { NavigationCause } from './types';
+
+export type SplitRouterMiddlewareResult =
+ | { type: 'redirect'; to: string }
+ | { type: 'cancel' };
+
+export type SplitRouterMiddlewareContext = {
+ /** The entry the pane is leaving, if any. */
+ from: Readonly<Entry> | undefined;
+ /** The proposed entry; it has not been applied yet. */
+ to: Readonly<Entry>;
+ /** Canonical single-pane path for `to`. */
+ path: string;
+ cause: NavigationCause;
+ /** Raw incoming query on initial and external navigation, unchanged across redirects. */
+ externalSearch?: string;
+ signal: AbortSignal;
+ redirect(to: string): SplitRouterMiddlewareResult;
+ cancel(): SplitRouterMiddlewareResult;
+};
+
+export type SplitRouterMiddleware = (
+ context: SplitRouterMiddlewareContext
+) => MaybePromise<SplitRouterMiddlewareResult | undefined | void>;
+
+type MiddlewareRequest = {
+ from?: Entry;
+ to: Entry;
+ cause: NavigationCause;
+ externalSearch?: string;
+ signal: AbortSignal;
+};
+
+type MiddlewareRun = {
+ readonly routes: SplitRoutesManifest;
+ readonly handlers: readonly SplitRouterMiddleware[];
+ readonly request: MiddlewareRequest;
+ readonly visited: string[];
+};
+
+function recordVisit(visited: string[], path: string, entry: Entry): void {
+ const signature = JSON.stringify([path, entry.location.search ?? null]);
+
+ if (visited.includes(signature)) {
+ throw new Error(`Split router middleware redirect loop at ${signature}`);
+ }
+
+ visited.push(signature);
+}
+
+function middlewareContext(
+ request: MiddlewareRequest,
+ entry: Entry,
+ path: string
+): SplitRouterMiddlewareContext {
+ return {
+ from: request.from,
+ to: entry,
+ path,
+ cause: request.cause,
+ externalSearch: request.externalSearch,
+ signal: request.signal,
+ redirect: (to) => ({ type: 'redirect', to }),
+ cancel: () => ({ type: 'cancel' }),
+ };
+}
+
+function redirectEntry(
+ routes: SplitRoutesManifest,
+ entry: Entry,
+ to: string
+): Entry {
+ const location = resolveTarget(routes, entry.location, to, { depth: 0 });
+
+ if (!location) {
+ throw new Error(
+ `Split router middleware redirected to an invalid route: ${to}`
+ );
+ }
+
+ // Unlike a navigation, a redirect keeps search across root routes, filtered to what the new route owns.
+ const search =
+ location.search ??
+ filterRouteSearch(routes, location.route, entry.location.search);
+
+ return { ...entry, location: locationOf(location.route, search) };
+}
+
+function runEntry(run: MiddlewareRun, entry: Entry): Outcome<Entry> {
+ run.request.signal.throwIfAborted();
+
+ const path = formatPanePath(run.routes, entry.location.route);
+ recordVisit(run.visited, path, entry);
+
+ return runHandler(run, entry, path, 0);
+}
+
+function runHandler(
+ run: MiddlewareRun,
+ entry: Entry,
+ path: string,
+ index: number
+): Outcome<Entry> {
+ const handler = run.handlers[index];
+ if (!handler) return entry;
+
+ const result = handler(middlewareContext(run.request, entry, path));
+
+ return andThen(result, (settled): Outcome<Entry> => {
+ // A handler can settle after the navigation was called off.
+ run.request.signal.throwIfAborted();
+
+ if (!settled) return runHandler(run, entry, path, index + 1);
+ if (settled.type === 'cancel') return CANCELLED;
+
+ return runEntry(run, redirectEntry(run.routes, entry, settled.to));
+ });
+}
+
+/**
+ * Runs one proposed entry through every handler, following redirects and
+ * rejecting loops. Errors fall back to the proposed entry; aborts propagate.
+ */
+export function runMiddleware(
+ routes: SplitRoutesManifest,
+ handlers: readonly SplitRouterMiddleware[],
+ request: MiddlewareRequest
+): Outcome<Entry> {
+ const run: MiddlewareRun = { routes, handlers, request, visited: [] };
+
+ return settleMaybe(
+ () => runEntry(run, request.to),
+ (error) => {
+ if (isAbortError(error, request.signal)) throw error;
+
+ console.error(
+ 'Split router middleware failed; continuing navigation',
+ error
+ );
+
+ return request.to;
+ }
+ );
+}
diff --git a/apps/web/src/lib/split-router/next/router/pane-list.ts b/apps/web/src/lib/split-router/next/router/pane-list.ts
new file mode 100644
index 0000000000..917367c6fc
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/pane-list.ts
@@ -0,0 +1,267 @@
+import { match } from 'ts-pattern';
+import type { OpenTarget, Placement } from '../panes/types';
+import { canonicalRoute, type SplitRoutesManifest } from '../routes/manifest';
+import type {
+ Entry,
+ PaneId,
+ SplitLocation,
+ SplitNavigationTarget,
+ SplitRouteState,
+} from '../routes/types';
+import { type MaybePromise, mapMaybe } from '../utils';
+import type { Claims } from './claims';
+import { createEntry } from './entries';
+import type { PaneNavigation } from './pane-navigation';
+import type { Runner } from './runner';
+import {
+ CANCELLED_RESULT,
+ type Navigation,
+ type NavigationResult,
+ type RouterPanes,
+ type SplitCloseAction,
+ type SplitNavigateOptions,
+} from './types';
+import type { Url } from './url';
+
+const KEEP: SplitCloseAction = { type: 'keep' };
+
+const isCommitted = (result: NavigationResult) => result.status === 'committed';
+
+const committed = (pane: PaneId): NavigationResult => ({
+ status: 'committed',
+ pane,
+});
+
+/** A policy's location checked against the route table; undefined when it isn't one. */
+function canonicalLocation(
+ routes: SplitRoutesManifest,
+ location: SplitLocation
+): SplitLocation | undefined {
+ let route: SplitRouteState | undefined;
+
+ try {
+ route = canonicalRoute(routes, location.route);
+ } catch {
+ route = undefined;
+ }
+
+ if (!route) {
+ console.error('Split router close action leads to no route', location);
+ return;
+ }
+
+ return { ...location, route };
+}
+
+/** Which panes there are: opening, closing and moving them, as the policy decides. */
+export function createPaneList(options: {
+ routes: SplitRoutesManifest;
+ panes: RouterPanes;
+ url: Url;
+ runner: Runner;
+ claims: Claims;
+ navigation: PaneNavigation;
+}) {
+ const { routes, panes, url, runner, claims, navigation } = options;
+ let opening = 0;
+
+ /** The entry an open's relative target resolves against. */
+ const openBase = (target: OpenTarget): Entry | undefined => {
+ const pane = 'pane' in target ? target.pane : target.source;
+ if (!pane) return;
+
+ return panes.current(pane);
+ };
+
+ /** Where an open lands; `holder` is the pane the policy was told shows the destination. */
+ const placementFor = (
+ location: SplitLocation,
+ target: OpenTarget,
+ navigateOptions: SplitNavigateOptions
+ ): { placement: Placement; holder?: PaneId } => {
+ if ('pane' in target) return { placement: target };
+
+ const holder = claims.paneShowing(location);
+ const placement = panes.placeNewPane({
+ destination: location,
+ source: target.source,
+ intent: target.intent,
+ holder,
+ allowDuplicate: navigateOptions.allowDuplicate,
+ opening,
+ });
+
+ return { placement, holder };
+ };
+
+ function openIn(
+ pane: PaneId,
+ location: SplitLocation,
+ navigateOptions: SplitNavigateOptions
+ ): MaybePromise<NavigationResult> {
+ const from = panes.current(pane);
+ if (!from) return CANCELLED_RESULT;
+
+ const result = navigation.visitLocation(
+ pane,
+ from,
+ location,
+ navigateOptions
+ );
+
+ return mapMaybe(result, (outcome): NavigationResult => {
+ if (outcome.status !== 'unchanged') return outcome;
+
+ return claims.reveal(pane);
+ });
+ }
+
+ /**
+ * Counted until it lands, so placement sees panes still on their way.
+ * `besides` is a pane the policy chose to open beside rather than bring up.
+ */
+ function openNew(
+ location: SplitLocation,
+ placement: { insertAt: number; besides?: PaneId },
+ navigateOptions: SplitNavigateOptions
+ ): MaybePromise<NavigationResult> {
+ const { insertAt, besides } = placement;
+ const pane = panes.createPaneId();
+ const entry = createEntry(routes, location, undefined, navigateOptions);
+ const decided = panes.ids();
+ const check = {
+ pane,
+ besides,
+ allowDuplicate: navigateOptions.allowDuplicate,
+ mode: 'push' as const,
+ };
+
+ const apply = ([landed]: readonly Entry[]) =>
+ claims.applyUnlessHeld(check, landed!, () => {
+ panes.insert(pane, landed!, insertAt, decided);
+ url.write('push');
+
+ return committed(pane);
+ });
+
+ const opened: Navigation = {
+ cause: 'navigate',
+ targets: [{ pane, to: entry }],
+ apply,
+ };
+
+ opening += 1;
+ const result = runner.start(pane, opened);
+
+ return mapMaybe(result, (outcome) => {
+ opening -= 1;
+
+ return outcome;
+ });
+ }
+
+ const removePane = (pane: PaneId) => {
+ const result = runner.start(pane, {
+ cause: 'navigate',
+ targets: [],
+ removed: [pane],
+ apply: () => {
+ panes.remove(pane);
+ url.write('push');
+
+ return committed(pane);
+ },
+ });
+
+ return mapMaybe(result, isCommitted);
+ };
+
+ function runCloseAction(
+ pane: PaneId,
+ from: Entry,
+ closeAction: SplitCloseAction
+ ): MaybePromise<boolean> {
+ return match(closeAction)
+ .with({ type: 'keep' }, () => false)
+ .with({ type: 'remove' }, () => removePane(pane))
+ .with({ type: 'navigate' }, ({ destination, replace }) => {
+ const location = canonicalLocation(routes, destination);
+ if (!location) return false;
+
+ const result = navigation.visitLocation(pane, from, location, {
+ replace,
+ });
+
+ return mapMaybe(result, isCommitted);
+ })
+ .with({ type: 'back-to' }, ({ to, otherwise = KEEP }) => {
+ const step = navigation.backStep(pane, to);
+ // A refused jump keeps the pane; only a missing entry falls back.
+ if (!step) return runCloseAction(pane, from, otherwise);
+
+ return navigation.jumpBack(pane, from, step);
+ })
+ .exhaustive();
+ }
+
+ return {
+ /**
+ * Open a destination in a pane, or where the policy places a new pane.
+ * Relative targets resolve against that pane or the new pane's source.
+ */
+ open(
+ to: SplitNavigationTarget,
+ target: OpenTarget,
+ navigateOptions: SplitNavigateOptions = {}
+ ): MaybePromise<NavigationResult> {
+ return runner.act(CANCELLED_RESULT, () => {
+ const base = openBase(target);
+ const location = navigation.resolve(base, to, navigateOptions);
+ if (!location) return CANCELLED_RESULT;
+
+ const { placement, holder } = placementFor(
+ location,
+ target,
+ navigateOptions
+ );
+
+ if ('pane' in placement) {
+ return openIn(placement.pane, location, navigateOptions);
+ }
+
+ const { insertAt } = placement;
+
+ return openNew(
+ location,
+ { insertAt, besides: holder },
+ navigateOptions
+ );
+ });
+ },
+
+ /** Close a pane the way the policy decides; removal waits for leave guards. */
+ close(pane: PaneId): MaybePromise<boolean> {
+ return runner.act(false, () => {
+ const from = panes.current(pane);
+ if (!from) return false;
+
+ return runCloseAction(pane, from, panes.closeAction(pane));
+ });
+ },
+
+ move(pane: PaneId, to: number): void {
+ void runner.act(undefined, () => {
+ runner.commitNow({
+ cause: 'navigate',
+ targets: [],
+ apply: () => {
+ const moved = panes.move(pane, to);
+ if (moved) url.write('push');
+
+ return committed(pane);
+ },
+ });
+ });
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/router/pane-navigation.ts b/apps/web/src/lib/split-router/next/router/pane-navigation.ts
new file mode 100644
index 0000000000..c7ca904f35
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/pane-navigation.ts
@@ -0,0 +1,469 @@
+import { match, P } from 'ts-pattern';
+import {
+ currentEntry,
+ findBack,
+ findStep,
+ removeEntries,
+} from '../panes/history';
+import type { HistoryTarget, PaneChange } from '../panes/types';
+import type { SplitRoutesManifest } from '../routes/manifest';
+import { filterRouteSearch, ownsNamespace } from '../routes/queries';
+import {
+ assertSafeSearchName,
+ locationOf,
+ SearchValueTooLongError,
+ updateSearchState,
+} from '../routes/search';
+import { resolveTarget } from '../routes/targets';
+import type {
+ Entry,
+ PaneArrival,
+ PaneId,
+ SplitLocation,
+ SplitNavigationTarget,
+ SplitSearchUpdate,
+ WriteMode,
+} from '../routes/types';
+import {
+ CANCELLED,
+ type Cancelled,
+ type MaybePromise,
+ mapMaybe,
+} from '../utils';
+import type { Claims } from './claims';
+import {
+ createEntry,
+ mergeDestinationSearch,
+ sameVisit,
+ searchVisitEntry,
+} from './entries';
+import type { Runner } from './runner';
+import {
+ CANCELLED_RESULT,
+ type Navigation,
+ type NavigationCause,
+ type NavigationResult,
+ type PaneTarget,
+ type RouterPanes,
+ type SplitNavigateOptions,
+ type VisitHistory,
+} from './types';
+import type { Url } from './url';
+
+type Visit = { history: VisitHistory; arrival?: PaneArrival };
+
+type VisitOptions = Visit & {
+ target: PaneTarget;
+ cause?: NavigationCause;
+ /** Commit even when another pane or preview already shows the destination. */
+ allowDuplicate?: boolean;
+};
+
+export type PaneNavigation = ReturnType<typeof createPaneNavigation>;
+
+const PUSH: Visit = { history: 'push', arrival: 'fresh' };
+
+const REPLACE: Visit = { history: 'replace', arrival: 'replace' };
+
+const isCommitted = (result: NavigationResult) => result.status === 'committed';
+
+function stepVisit(index: number, arrival: PaneArrival): Visit {
+ return { history: { go: index }, arrival };
+}
+
+/** A push adds a URL entry; replace, go and reset rewrite the current one. */
+function visitWriteMode(history: VisitHistory): WriteMode {
+ if (history === 'push') return 'push';
+
+ return 'replace';
+}
+
+const historyChange = (
+ history: VisitHistory,
+ entry: Entry
+): PaneChange<Entry> =>
+ match(history)
+ .with('push', 'replace', (type) => ({ type, entry }))
+ .with({ go: P.number }, ({ go }) => ({
+ type: 'go' as const,
+ index: go,
+ entry,
+ }))
+ .with({ reset: P.array() }, ({ reset, index }) => ({
+ type: 'reset' as const,
+ entries: reset.with(index, entry),
+ index,
+ }))
+ .exhaustive();
+
+function searchLocation(
+ routes: SplitRoutesManifest,
+ from: Entry,
+ namespace: string,
+ update: SplitSearchUpdate
+): SplitLocation {
+ const updated = updateSearchState(from.location, { [namespace]: update });
+ const search = filterRouteSearch(routes, updated.route, updated.search);
+
+ return locationOf(updated.route, search);
+}
+
+function warnUnownedSearch(
+ routes: SplitRoutesManifest,
+ location: SplitLocation,
+ search: SplitNavigateOptions['search']
+) {
+ if (!import.meta.env.DEV) return;
+ if (!search) return;
+
+ const { route } = location;
+ const leaf = route.matches.at(-1)!;
+ const unowned = Object.keys(search).filter(
+ (namespace) => !ownsNamespace(routes, route, namespace)
+ );
+
+ for (const namespace of unowned) {
+ console.warn(
+ `Split route "${leaf.id}" does not own search namespace "${namespace}"`
+ );
+ }
+}
+
+/** Builds a location from caller input; a search value the URL can't hold refuses it instead of throwing. */
+function withinSearchLimits<T>(build: () => T): T | Cancelled {
+ try {
+ return build();
+ } catch (error) {
+ if (!(error instanceof SearchValueTooLongError)) throw error;
+
+ console.error('Split router refused a navigation', error);
+ return CANCELLED;
+ }
+}
+
+/**
+ * What callers do within one pane: navigate, go back, change search, and
+ * edit its history. Each verb waits until pane actions may run (see
+ * `runner.act`), then navigates or, for changes that need no guards or
+ * middleware, commits at once.
+ */
+export function createPaneNavigation(options: {
+ routes: SplitRoutesManifest;
+ panes: RouterPanes;
+ url: Url;
+ runner: Runner;
+ claims: Claims;
+}) {
+ const { routes, panes, url, runner, claims } = options;
+
+ const applyVisit = (
+ pane: PaneId,
+ { history, arrival }: Visit,
+ entry: Entry
+ ): NavigationResult => {
+ panes.commit(pane, historyChange(history, entry), arrival);
+ url.write(visitWriteMode(history));
+
+ return { status: 'committed', pane };
+ };
+
+ /** A visit to one pane; its claim is checked as it applies. */
+ const visitNavigation = ({
+ target,
+ history,
+ arrival,
+ cause = 'navigate',
+ allowDuplicate,
+ }: VisitOptions): Navigation => {
+ const { pane, from } = target;
+ const check = {
+ pane,
+ from,
+ allowDuplicate,
+ mode: visitWriteMode(history),
+ };
+
+ const apply = ([entry]: readonly Entry[]) =>
+ claims.applyUnlessHeld(check, entry!, () =>
+ applyVisit(pane, { history, arrival }, entry!)
+ );
+
+ return { cause, targets: [target], apply };
+ };
+
+ const visit = (visitOptions: VisitOptions) =>
+ runner.start(visitOptions.target.pane, visitNavigation(visitOptions));
+
+ /** A pane action on the pane's current entry; `missing` when the pane has none. */
+ const withCurrent = <T>(
+ pane: PaneId,
+ missing: T,
+ run: (from: Entry) => MaybePromise<T>
+ ) =>
+ runner.act(missing, () => {
+ const from = panes.current(pane);
+ if (!from) return missing;
+
+ return run(from);
+ });
+
+ const resolve = (
+ base: Entry | undefined,
+ to: SplitNavigationTarget,
+ navigateOptions: SplitNavigateOptions
+ ): SplitLocation | undefined => {
+ const build = () =>
+ resolveTarget(routes, base?.location, to, {
+ depth: navigateOptions.depth,
+ search: navigateOptions.search,
+ });
+ const location = withinSearchLimits(build);
+ if (location === CANCELLED) return;
+
+ if (!location) {
+ console.error('Split router could not resolve navigation target', to);
+ return;
+ }
+
+ warnUnownedSearch(routes, location, navigateOptions.search);
+
+ return location;
+ };
+
+ /** The pane already shows `entry` and nothing is on its way; kept props aren't new. */
+ const isUnchanged = (pane: PaneId, from: Entry, entry: Entry) => {
+ const handsOverProps =
+ entry.props !== undefined && entry.props !== from.props;
+ const sameDestination = !handsOverProps && sameVisit(from, entry);
+
+ return sameDestination && !runner.isRunning(pane);
+ };
+
+ function visitLocation(
+ pane: PaneId,
+ from: Entry,
+ location: SplitLocation,
+ navigateOptions: SplitNavigateOptions
+ ): MaybePromise<NavigationResult> {
+ const entry = createEntry(routes, location, from, navigateOptions);
+ if (isUnchanged(pane, from, entry)) return { status: 'unchanged', pane };
+
+ const history = navigateOptions.replace ? REPLACE : PUSH;
+ const target = { pane, from, to: entry };
+ const { allowDuplicate } = navigateOptions;
+
+ return visit({ ...history, target, allowDuplicate });
+ }
+
+ function navigateToTarget(
+ pane: PaneId,
+ from: Entry,
+ to: SplitNavigationTarget,
+ navigateOptions: SplitNavigateOptions
+ ): MaybePromise<NavigationResult> {
+ const location = resolve(from, to, navigateOptions);
+ if (!location) return CANCELLED_RESULT;
+
+ return visitLocation(pane, from, location, navigateOptions);
+ }
+
+ function traverse(
+ pane: PaneId,
+ from: Entry,
+ delta: number,
+ navigateOptions: SplitNavigateOptions
+ ): MaybePromise<NavigationResult> {
+ const { allowDuplicate } = navigateOptions;
+ const visitable = claims.canVisit(pane, allowDuplicate);
+
+ const snapshot = panes.read(pane);
+ if (!snapshot) return CANCELLED_RESULT;
+
+ const step = findStep(snapshot, delta, visitable);
+ if (!step) return CANCELLED_RESULT;
+
+ const arrival = delta < 0 ? 'back' : 'forward';
+ const target = { pane, from, to: step.entry };
+
+ return visit({
+ ...stepVisit(step.index, arrival),
+ target,
+ cause: 'history',
+ allowDuplicate,
+ });
+ }
+
+ /** The nearest earlier entry matching `predicate` the pane may go back to. */
+ const backStep = (pane: PaneId, predicate: (entry: Entry) => boolean) => {
+ const snapshot = panes.read(pane);
+ if (!snapshot) return;
+
+ return findBack(snapshot, predicate, claims.canVisit(pane));
+ };
+
+ /** False when the jump is turned down. */
+ const jumpBack = (
+ pane: PaneId,
+ from: Entry,
+ step: HistoryTarget<Entry>
+ ): MaybePromise<boolean> => {
+ const target = { pane, from, to: step.entry };
+ const result = visit({
+ ...stepVisit(step.index, 'back'),
+ target,
+ cause: 'history',
+ });
+
+ return mapMaybe(result, isCommitted);
+ };
+
+ function changeSearch(
+ pane: PaneId,
+ from: Entry,
+ namespace: string,
+ update: SplitSearchUpdate,
+ mode: WriteMode
+ ): MaybePromise<NavigationResult> {
+ warnUnownedSearch(routes, from.location, { [namespace]: update });
+
+ const build = () => searchLocation(routes, from, namespace, update);
+ const location = withinSearchLimits(build);
+ if (location === CANCELLED) return CANCELLED_RESULT;
+
+ const to = searchVisitEntry(from, location, mode);
+ if (isUnchanged(pane, from, to)) return { status: 'unchanged', pane };
+
+ return visit({
+ history: mode,
+ target: { pane, from, to },
+ cause: 'search',
+ });
+ }
+
+ /** False when nothing matched or the change was turned down. */
+ function removeFromHistory(
+ pane: PaneId,
+ predicate: (entry: Entry) => boolean
+ ): MaybePromise<boolean> {
+ const snapshot = panes.read(pane);
+ if (!snapshot) return false;
+
+ const next = removeEntries(snapshot, predicate);
+ if (!next) return false;
+
+ const removedAny = next.entries.length < snapshot.entries.length;
+ if (!removedAny) return false;
+
+ // Removing entries shifts history indexes an in-flight traversal relies on.
+ runner.abort(pane);
+
+ const from = currentEntry(snapshot);
+ const to = currentEntry(next);
+ const target = { pane, from, to };
+ const history = { reset: next.entries, index: next.index };
+ const currentStays = to.id === from.id;
+
+ if (currentStays) {
+ const navigation = visitNavigation({ history, target, cause: 'history' });
+
+ return isCommitted(runner.commitNow(navigation));
+ }
+
+ const result = visit({ ...REPLACE, history, target, cause: 'history' });
+
+ return mapMaybe(result, isCommitted);
+ }
+
+ return {
+ navigate(
+ pane: PaneId,
+ to: SplitNavigationTarget | number,
+ navigateOptions: SplitNavigateOptions = {}
+ ): MaybePromise<NavigationResult> {
+ return withCurrent(pane, CANCELLED_RESULT, (from) => {
+ if (typeof to === 'number') {
+ return traverse(pane, from, to, navigateOptions);
+ }
+
+ return navigateToTarget(pane, from, to, navigateOptions);
+ });
+ },
+
+ updateSearch(
+ pane: PaneId,
+ namespace: string,
+ update: SplitSearchUpdate,
+ searchOptions: { history?: WriteMode } = {}
+ ): MaybePromise<NavigationResult> {
+ assertSafeSearchName(namespace, 'namespace');
+ const mode = searchOptions.history ?? 'push';
+
+ return withCurrent(pane, CANCELLED_RESULT, (from) =>
+ changeSearch(pane, from, namespace, update, mode)
+ );
+ },
+
+ /** Jump back to the nearest earlier entry matching `predicate`. False when none qualifies or the jump is turned down. */
+ goBackTo(
+ pane: PaneId,
+ predicate: (entry: Entry) => boolean
+ ): MaybePromise<boolean> {
+ return withCurrent(pane, false, (from) => {
+ const step = backStep(pane, predicate);
+ if (!step) return false;
+
+ return jumpBack(pane, from, step);
+ });
+ },
+
+ /** Drops matching entries from the pane's history. False when none matched or it was turned down. */
+ removeEntries(
+ pane: PaneId,
+ predicate: (entry: Entry) => boolean
+ ): MaybePromise<boolean> {
+ return runner.act(false, () => removeFromHistory(pane, predicate));
+ },
+
+ /** Point the current entry at a new location without a navigation or remount. */
+ rewriteCurrent(
+ pane: PaneId,
+ to: SplitNavigationTarget
+ ): MaybePromise<NavigationResult> {
+ return withCurrent(pane, CANCELLED_RESULT, (from) => {
+ const location = resolve(from, to, {});
+ if (!location) return CANCELLED_RESULT;
+
+ const target = { pane, from, to: { ...from, location } };
+
+ return runner.commitNow(visitNavigation({ ...REPLACE, target }));
+ });
+ },
+
+ canGo(pane: PaneId, delta: number): boolean {
+ const snapshot = panes.read(pane);
+ if (!snapshot) return false;
+
+ return findStep(snapshot, delta, claims.canVisit(pane)) !== undefined;
+ },
+
+ /** Carries the search `destination` asked for to `pane`, which already shows it. */
+ carrySearch(pane: PaneId, destination: Entry, mode: WriteMode): void {
+ void withCurrent(pane, undefined, (from) => {
+ const location = mergeDestinationSearch(routes, from, destination);
+ if (!location) return;
+
+ const to = searchVisitEntry(from, location, mode);
+ void visit({
+ history: mode,
+ target: { pane, from, to },
+ cause: 'search',
+ });
+ });
+ },
+
+ resolve,
+ visitLocation,
+ backStep,
+ jumpBack,
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/router/phases.ts b/apps/web/src/lib/split-router/next/router/phases.ts
new file mode 100644
index 0000000000..1f103ecadc
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/phases.ts
@@ -0,0 +1,214 @@
+import type { Cleanup, MachineScopes } from '@macro-inc/machine';
+import type { SplitRoutesManifest } from '../routes/manifest';
+import { firstChangedDepth } from '../routes/queries';
+import type { Entry, PaneId, PreloadIntent } from '../routes/types';
+import {
+ all,
+ CANCELLED,
+ type Cancelled,
+ isAbortError,
+ isPromise,
+ type MaybePromise,
+ mapMaybe,
+ type Outcome,
+} from '../utils';
+import { withValidState } from './entries';
+import {
+ type Check,
+ checksFor,
+ type LeaveGuards,
+ PANE_LEVEL,
+ runChecks,
+} from './leave-guards';
+import { runMiddleware, type SplitRouterMiddleware } from './middleware';
+import { preloadLocation, withinBudget } from './preload';
+import type { Event as RunEvent, Running, State as RunState } from './run';
+import type { Navigation, PaneTarget } from './types';
+
+type Report = (event: RunEvent) => void;
+
+/** What one phase's work runs with; the signal aborts when the run leaves the phase. */
+type RunContext = { navigation: Navigation; signal: AbortSignal };
+
+/** The work each phase waits on, for any run machine. */
+type PhaseScopes = MachineScopes<RunState, RunEvent>;
+
+const PRELOADED: RunEvent = { t: 'preloaded' };
+
+function intentOf(navigation: Navigation): PreloadIntent {
+ const { cause } = navigation;
+ const fromUrl = cause === 'initial' || cause === 'external';
+ if (fromUrl) return cause;
+
+ return 'navigate';
+}
+
+function toGuardEvent(allowed: boolean): RunEvent {
+ if (allowed) return { t: 'allowed' };
+
+ return { t: 'refused' };
+}
+
+function toMiddlewareEvent(entries: Entry[] | Cancelled): RunEvent {
+ if (entries === CANCELLED) return { t: 'middleware-cancelled' };
+
+ return { t: 'resolved', entries };
+}
+
+/** Does one phase's work and reports its result; leaving the phase aborts it. */
+function perform<T>(
+ state: Running,
+ dispatch: Report,
+ work: (context: RunContext) => MaybePromise<T>,
+ toEvent: (value: T) => RunEvent,
+ waiting: () => void
+): Cleanup {
+ const controller = new AbortController();
+ const context: RunContext = {
+ navigation: state.navigation,
+ signal: controller.signal,
+ };
+
+ const report = (event: RunEvent) => {
+ if (!context.signal.aborted) dispatch(event);
+ };
+
+ const fail = (error: unknown) => {
+ if (isAbortError(error, context.signal)) return;
+
+ console.error('Split router navigation failed', error);
+ report({ t: 'failed' });
+ };
+
+ const reportLater = async (pending: Promise<T>) => {
+ try {
+ report(toEvent(await pending));
+ } catch (error) {
+ fail(error);
+ }
+ };
+
+ try {
+ const result = work(context);
+
+ if (isPromise(result)) {
+ waiting();
+ void reportLater(result);
+ } else {
+ report(toEvent(result));
+ }
+ } catch (error) {
+ fail(error);
+ }
+
+ return () => controller.abort();
+}
+
+/** `waiting` hears when a phase's work goes async, which is when a run counts as pending. */
+export function createPhaseScopes(
+ options: {
+ routes: SplitRoutesManifest;
+ middleware: readonly SplitRouterMiddleware[];
+ guards: LeaveGuards;
+ /** What a pane shows now, which its guards are asked to leave. */
+ current(pane: PaneId): Entry | undefined;
+ preloadBudgetMs: number;
+ },
+ waiting: (state: Running) => void
+): PhaseScopes {
+ const { routes, guards } = options;
+
+ const targetChecks = ({ navigation, signal }: RunContext): Check[] =>
+ navigation.targets.flatMap(({ pane, from, to }) => {
+ if (!from) return [];
+
+ const depth = firstChangedDepth(routes, from, to);
+ if (depth === undefined) return [];
+
+ const context = { pane, from, to, cause: navigation.cause, signal };
+
+ return checksFor(guards.select(pane, depth), context);
+ });
+
+ const removalChecks = ({ navigation, signal }: RunContext): Check[] => {
+ const removed = navigation.removed ?? [];
+
+ return removed.flatMap((pane) => {
+ const from = options.current(pane);
+ if (!from) return [];
+
+ const context = { pane, from, cause: navigation.cause, signal };
+
+ return checksFor(guards.select(pane, PANE_LEVEL), context);
+ });
+ };
+
+ const checkGuards = (context: RunContext) =>
+ runChecks([...targetChecks(context), ...removalChecks(context)]);
+
+ const destination = (
+ { navigation, signal }: RunContext,
+ target: PaneTarget
+ ): Outcome<Entry> => {
+ if (options.middleware.length === 0) return target.to;
+
+ const resolved = runMiddleware(routes, options.middleware, {
+ from: target.from,
+ to: target.to,
+ cause: navigation.cause,
+ externalSearch: navigation.externalSearch,
+ signal,
+ });
+
+ return mapMaybe(resolved, (entry): Entry | Cancelled => {
+ if (entry !== CANCELLED) return withValidState(routes, entry, target.to);
+
+ // An initial load always mounts something, even if middleware cancels it.
+ if (navigation.cause === 'initial') return target.to;
+
+ return CANCELLED;
+ });
+ };
+
+ const resolveDestinations = (context: RunContext) => {
+ const destinations = context.navigation.targets.map((target) =>
+ destination(context, target)
+ );
+
+ return all(destinations);
+ };
+
+ const preloadEntries = (
+ { navigation, signal }: RunContext,
+ entries: readonly Entry[]
+ ): MaybePromise<void> => {
+ const intent = intentOf(navigation);
+ const work = entries.flatMap((entry) => {
+ const context = { location: entry.location, intent, signal };
+
+ return preloadLocation(routes, context) ?? [];
+ });
+ if (work.length === 0) return;
+
+ return withinBudget(Promise.all(work), options.preloadBudgetMs);
+ };
+
+ return {
+ guards: (s, dispatch) =>
+ perform(s, dispatch, checkGuards, toGuardEvent, () => waiting(s)),
+
+ middleware: (s, dispatch) =>
+ perform(s, dispatch, resolveDestinations, toMiddlewareEvent, () =>
+ waiting(s)
+ ),
+
+ preload: (s, dispatch) =>
+ perform(
+ s,
+ dispatch,
+ (context) => preloadEntries(context, s.entries),
+ () => PRELOADED,
+ () => waiting(s)
+ ),
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/router/preload.ts b/apps/web/src/lib/split-router/next/router/preload.ts
new file mode 100644
index 0000000000..95aa8dbbfd
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/preload.ts
@@ -0,0 +1,100 @@
+import {
+ resolveBranch,
+ type SplitRouteNode,
+ type SplitRoutesManifest,
+} from '../routes/manifest';
+import { mergedParams } from '../routes/queries';
+import type { PreloadIntent, SplitLocation } from '../routes/types';
+import { isPromise } from '../utils';
+
+type PreloadContext = {
+ location: SplitLocation;
+ intent: PreloadIntent;
+ signal: AbortSignal;
+};
+
+async function settleQuietly(work: Promise<unknown>): Promise<void> {
+ try {
+ await work;
+ } catch {
+ // The view's own Suspense and error boundaries report chunk failures.
+ }
+}
+
+function hasPreload(component: unknown): component is { preload: unknown } {
+ return typeof component === 'function' && 'preload' in component;
+}
+
+function warmComponent(component: unknown): void {
+ if (!hasPreload(component)) return;
+
+ const preload = component.preload;
+ if (typeof preload !== 'function') return;
+
+ const chunk: unknown = preload.call(component);
+ if (chunk instanceof Promise) void settleQuietly(chunk);
+}
+
+function preloadNode(
+ node: SplitRouteNode,
+ depth: number,
+ context: PreloadContext
+): Promise<unknown> | undefined {
+ const { definition } = node;
+ const { location, intent, signal } = context;
+ warmComponent(definition.component);
+
+ const data = definition.preload?.({
+ params: mergedParams(location.route, depth + 1),
+ search: location.search,
+ intent,
+ signal,
+ });
+
+ return isPromise(data) ? data : undefined;
+}
+
+/**
+ * Starts loading every `lazy()` chunk along the branch without waiting for
+ * them, and returns only the route data preloads that need waiting for.
+ * A preload that fails, synchronously or not, never fails the navigation.
+ */
+export function preloadLocation(
+ routes: SplitRoutesManifest,
+ context: PreloadContext
+): Promise<unknown> | undefined {
+ const work: Promise<unknown>[] = [];
+ const branch = resolveBranch(routes, context.location.route);
+
+ branch.forEach((node, depth) => {
+ try {
+ const data = preloadNode(node, depth, context);
+ if (data) work.push(data);
+ } catch (error) {
+ console.error(
+ `Split route "${node.definition.id}" preload failed`,
+ error
+ );
+ }
+ });
+
+ if (work.length === 0) return;
+
+ return Promise.allSettled(work);
+}
+
+export async function withinBudget(
+ work: Promise<unknown>,
+ ms: number
+): Promise<void> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const deadline = new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, ms);
+ });
+
+ try {
+ await Promise.race([work, deadline]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
diff --git a/apps/web/src/lib/split-router/next/router/run.ts b/apps/web/src/lib/split-router/next/router/run.ts
new file mode 100644
index 0000000000..b92a766efe
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/run.ts
@@ -0,0 +1,133 @@
+import type { MachineDef, Transition } from '@macro-inc/machine';
+import { match } from 'ts-pattern';
+import type { Entry } from '../routes/types';
+import type { CancelReason, Navigation } from './types';
+
+/**
+ * One navigation at a time as a state machine: each pane has one, and so do
+ * URL navigations. Pure: `runner.ts` does each phase's work and
+ * reports it; this module decides what it means.
+ *
+ * Lifecycle: idle → guards → middleware → preload → idle
+ *
+ * A new navigation replaces the one in flight, whatever phase it is in.
+ */
+
+export type State =
+ | { readonly t: 'idle' }
+ | { readonly t: 'guards'; readonly navigation: Navigation }
+ | { readonly t: 'middleware'; readonly navigation: Navigation }
+ | {
+ readonly t: 'preload';
+ readonly navigation: Navigation;
+ readonly entries: readonly Entry[];
+ };
+
+export type Running = Exclude<State, { t: 'idle' }>;
+
+/** A running navigation, named after the work it waits on. */
+export type Phase = Running['t'];
+
+export type Event =
+ | { readonly t: 'navigate'; readonly navigation: Navigation }
+ | {
+ readonly t: 'abort';
+ readonly reason: 'superseded' | 'interrupted' | 'disposed';
+ }
+ | { readonly t: 'allowed' }
+ | { readonly t: 'refused' }
+ /** Middleware settled on these entries, one per target. */
+ | { readonly t: 'resolved'; readonly entries: readonly Entry[] }
+ | { readonly t: 'middleware-cancelled' }
+ | { readonly t: 'preloaded' }
+ /** The phase's work threw or rejected. */
+ | { readonly t: 'failed' };
+
+export type Command =
+ | {
+ readonly t: 'commit';
+ readonly navigation: Navigation;
+ readonly entries: readonly Entry[];
+ }
+ | {
+ readonly t: 'cancel';
+ readonly navigation: Navigation;
+ readonly reason: CancelReason;
+ };
+
+type Result = Transition<State, Command> | undefined;
+
+export const IDLE: State = { t: 'idle' };
+
+const cancel = (navigation: Navigation, reason: CancelReason): Command => ({
+ t: 'cancel',
+ navigation,
+ reason,
+});
+
+const toIdle = (command: Command): Result => ({
+ state: IDLE,
+ commands: [command],
+});
+
+/** Rows every phase shares; any other report comes from a phase already left. */
+function anyPhase(s: Running, e: Event): Result {
+ return match(e)
+ .with(
+ { t: 'navigate' },
+ (e): Result => ({
+ state: { t: 'guards', navigation: e.navigation },
+ commands: [cancel(s.navigation, 'superseded')],
+ })
+ )
+ .with({ t: 'abort' }, (e) => toIdle(cancel(s.navigation, e.reason)))
+ .with({ t: 'failed' }, () => toIdle(cancel(s.navigation, 'failed')))
+ .otherwise(() => undefined);
+}
+
+function guards(s: Extract<State, { t: 'guards' }>, e: Event): Result {
+ if (e.t === 'allowed') {
+ return { state: { t: 'middleware', navigation: s.navigation } };
+ }
+
+ if (e.t === 'refused') return toIdle(cancel(s.navigation, 'refused'));
+
+ return anyPhase(s, e);
+}
+
+function middleware(s: Extract<State, { t: 'middleware' }>, e: Event): Result {
+ if (e.t === 'resolved') {
+ const { entries } = e;
+
+ return { state: { t: 'preload', navigation: s.navigation, entries } };
+ }
+
+ if (e.t === 'middleware-cancelled') {
+ return toIdle(cancel(s.navigation, 'cancelled'));
+ }
+
+ return anyPhase(s, e);
+}
+
+function preload(s: Extract<State, { t: 'preload' }>, e: Event): Result {
+ if (e.t === 'preloaded') {
+ const { navigation, entries } = s;
+
+ return toIdle({ t: 'commit', navigation, entries });
+ }
+
+ return anyPhase(s, e);
+}
+
+function idle(e: Event): Result {
+ if (e.t !== 'navigate') return;
+
+ return { state: { t: 'guards', navigation: e.navigation } };
+}
+
+export const runDef: MachineDef<State, Event, Command> = {
+ idle: { on: (_s, e) => idle(e) },
+ guards: { on: guards },
+ middleware: { on: middleware },
+ preload: { on: preload },
+};
diff --git a/apps/web/src/lib/split-router/next/router/runner.ts b/apps/web/src/lib/split-router/next/router/runner.ts
new file mode 100644
index 0000000000..be02b2bf4b
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/runner.ts
@@ -0,0 +1,461 @@
+import {
+ createMachine,
+ type Machine,
+ type MachineScopes,
+} from '@macro-inc/machine';
+import { untrack } from 'solid-js';
+import { createStore, produce } from 'solid-js/store';
+import { match } from 'ts-pattern';
+import type { Entry, PaneId } from '../routes/types';
+import { isPromise, type MaybePromise, mapMaybe } from '../utils';
+import {
+ IDLE,
+ type Phase,
+ type Command as RunCommand,
+ type Event as RunEvent,
+ type Running,
+ type State as RunState,
+ runDef,
+} from './run';
+import {
+ CANCELLED_RESULT,
+ type Navigation,
+ type NavigationCause,
+ type NavigationResult,
+ type PaneTarget,
+} from './types';
+import {
+ type Command as GateCommand,
+ type Event as GateEvent,
+ type State as GateState,
+ urlGateDef,
+} from './url-gate';
+
+/** An in-flight navigation as it affects one pane. */
+export type PendingNavigation = {
+ phase: Phase;
+ cause: NavigationCause;
+ pane: PaneId;
+ from?: Entry;
+ to: Entry;
+};
+
+type InFlight = {
+ phase: Phase;
+ cause: NavigationCause;
+ targets: readonly PaneTarget[];
+};
+
+type Run = Machine<RunState, RunEvent>;
+
+type PaneRun = { pane: PaneId; machine: Run };
+
+type Settle = (result: NavigationResult) => void;
+
+const URL_KEY = '@url';
+
+/** What each pane, and the URL navigation run, has in flight. */
+function createInFlight() {
+ const [inFlight, setInFlight] = createStore<
+ Record<string, InFlight | undefined>
+ >({});
+
+ const clear = (key: string) => {
+ if (!inFlight[key]) return;
+
+ setInFlight(
+ produce((draft) => {
+ delete draft[key];
+ })
+ );
+ };
+
+ /** Publishes a run once a phase waits on async work; runs that finish at once never show. */
+ const show = (key: string, state: Running) => {
+ const { navigation } = state;
+
+ setInFlight(key, {
+ phase: state.t,
+ cause: navigation.cause,
+ targets: navigation.targets,
+ });
+ };
+
+ /** Keeps a published run up to date as it moves on. */
+ const follow = (key: string, state: RunState) => {
+ const published = untrack(() => inFlight[key]) !== undefined;
+ if (!published) return;
+
+ if (state.t === 'idle') {
+ clear(key);
+ return;
+ }
+
+ show(key, state);
+ };
+
+ const pendingFrom = (
+ key: string,
+ pane: PaneId
+ ): PendingNavigation | undefined => {
+ const record = inFlight[key];
+ if (!record) return;
+
+ const target = record.targets.find((candidate) => candidate.pane === pane);
+ if (!target) return;
+
+ const { phase, cause } = record;
+
+ return { phase, cause, pane, from: target.from, to: target.to };
+ };
+
+ /** The in-flight navigation that affects `pane`, from the pane itself or the URL. */
+ const pending = (pane: PaneId) =>
+ pendingFrom(pane, pane) ?? pendingFrom(URL_KEY, pane);
+
+ return { show, follow, pending };
+}
+
+function runAll(actions: readonly (() => void)[]) {
+ for (const action of actions) {
+ action();
+ }
+}
+
+export type Runner = ReturnType<typeof createRunner>;
+
+/**
+ * Runs navigations: a run machine (`run.ts`) per pane and one for URL
+ * navigations, with the URL gate (`url-gate.ts`) deciding when pane
+ * actions may run. It never looks at what a navigation does; each one
+ * applies itself.
+ */
+export function createRunner(options: {
+ /** Phase work for a run; `waiting` hears when a phase goes async. */
+ phases(waiting: (state: Running) => void): MachineScopes<RunState, RunEvent>;
+ /** Panes still open; runs of the others are dropped once idle. */
+ live(): readonly PaneId[];
+}) {
+ const inFlight = createInFlight();
+ const settlers = new WeakMap<Navigation, Settle>();
+ const outstanding: Promise<unknown>[] = [];
+ const waiters: (() => void)[] = [];
+ const paneRuns: PaneRun[] = [];
+ let committing = 0;
+ let disposed = false;
+
+ const track = async (promise: Promise<unknown>) => {
+ outstanding.push(promise);
+ await promise;
+ outstanding.splice(outstanding.indexOf(promise), 1);
+ };
+
+ /** Starts `navigation`; one that never waits has settled by the time `start` returns. */
+ const run = (
+ navigation: Navigation,
+ begin: () => void
+ ): MaybePromise<NavigationResult> => {
+ const deferred = Promise.withResolvers<NavigationResult>();
+ let result: NavigationResult | undefined;
+
+ settlers.set(navigation, (value) => {
+ result = value;
+ deferred.resolve(value);
+ });
+ void track(deferred.promise);
+ begin();
+
+ return result ?? deferred.promise;
+ };
+
+ const settle = (navigation: Navigation, result: NavigationResult) => {
+ const settler = settlers.get(navigation);
+ settlers.delete(navigation);
+ settler?.(result);
+ };
+
+ const isOpen = () => {
+ const { t } = gate.getState();
+ const gateOpen = t === 'open' || t === 'disposed';
+
+ return gateOpen && committing === 0;
+ };
+
+ /** Lets waiting actions run once no commit or URL navigation holds them back. */
+ const release = () => {
+ if (!isOpen()) return;
+
+ runAll(waiters.splice(0));
+ };
+
+ /**
+ * Applies one navigation. Actions it sets off, such as a view redirecting
+ * as it mounts, wait until it has written the URL. An apply that throws is
+ * turned down so the machines keep running.
+ */
+ const commit = (
+ navigation: Navigation,
+ entries: readonly Entry[]
+ ): NavigationResult => {
+ committing += 1;
+
+ try {
+ return navigation.apply(entries);
+ } catch (error) {
+ console.error('Split router could not commit a navigation', error);
+ return CANCELLED_RESULT;
+ } finally {
+ committing -= 1;
+ release();
+ }
+ };
+
+ /** A run whose waiting phases show under `key` in `pending`. */
+ const createRun = (
+ key: string,
+ execute: (command: RunCommand) => void
+ ): Run => {
+ const scopes = options.phases((state) => inFlight.show(key, state));
+ const machine = createMachine<RunState, RunEvent, RunCommand>({
+ initial: IDLE,
+ def: runDef,
+ scopes,
+ execute,
+ });
+
+ machine.subscribe((state) => inFlight.follow(key, state));
+
+ return machine;
+ };
+
+ const findRun = (pane: PaneId) =>
+ paneRuns.find((item) => item.pane === pane)?.machine;
+
+ const isFinished = (item: PaneRun, live: readonly PaneId[]) => {
+ const stillOpen = live.includes(item.pane);
+ const idle = item.machine.getState().t === 'idle';
+
+ return idle && !stillOpen;
+ };
+
+ /** Drops the runs of panes that were removed and have nothing in flight. */
+ const sweep = () => {
+ const live = options.live();
+ const finished = paneRuns.filter((item) => isFinished(item, live));
+
+ for (const item of finished) {
+ item.machine.dispose();
+ paneRuns.splice(paneRuns.indexOf(item), 1);
+ }
+ };
+
+ const abortPanes = (reason: 'superseded' | 'disposed') => {
+ for (const { machine } of [...paneRuns]) {
+ machine.dispatch({ t: 'abort', reason });
+ }
+ };
+
+ const executePaneRun = (command: RunCommand) => {
+ match(command)
+ .with({ t: 'commit' }, ({ navigation, entries }) =>
+ settle(navigation, commit(navigation, entries))
+ )
+ .with({ t: 'cancel' }, ({ navigation }) =>
+ settle(navigation, CANCELLED_RESULT)
+ )
+ .exhaustive();
+
+ sweep();
+ };
+
+ const paneRun = (pane: PaneId): Run => {
+ const existing = findRun(pane);
+ if (existing) return existing;
+
+ const created = createRun(pane, executePaneRun);
+ paneRuns.push({ pane, machine: created });
+
+ return created;
+ };
+
+ const abort = (pane: PaneId) => {
+ findRun(pane)?.dispatch({ t: 'abort', reason: 'superseded' });
+ };
+
+ const commitUrl = (navigation: Navigation, entries: readonly Entry[]) => {
+ const result = commit(navigation, entries);
+ settle(navigation, result);
+
+ const failed = result.status === 'cancelled';
+ if (failed) return 'failed';
+
+ return 'committed';
+ };
+
+ const executeUrlRun = (command: RunCommand) => {
+ const { navigation } = command;
+
+ const outcome = match(command)
+ .with({ t: 'commit' }, ({ entries }) => commitUrl(navigation, entries))
+ .with({ t: 'cancel' }, ({ reason }) => {
+ settle(navigation, CANCELLED_RESULT);
+
+ return reason;
+ })
+ .exhaustive();
+
+ gate.dispatch({ t: 'settled', navigation, outcome });
+ };
+
+ const urlRun = createRun(URL_KEY, executeUrlRun);
+
+ const abortUrl = (
+ navigation: Navigation,
+ reason: 'interrupted' | 'disposed'
+ ) => {
+ const state = urlRun.getState();
+ const running = state.t !== 'idle' && state.navigation === navigation;
+
+ if (running) {
+ urlRun.dispatch({ t: 'abort', reason });
+ return;
+ }
+
+ // Turned away before it ran.
+ settle(navigation, CANCELLED_RESULT);
+ };
+
+ const revert = (
+ navigation: Navigation,
+ dispatch: (event: GateEvent) => void
+ ) => {
+ const landed = navigation.revert?.();
+
+ void mapMaybe(landed, () => dispatch({ t: 'revert-landed' }));
+ };
+
+ const executeGate = (
+ command: GateCommand,
+ dispatch: (event: GateEvent) => void
+ ) => {
+ match(command)
+ .with({ t: 'run' }, ({ navigation }) =>
+ urlRun.dispatch({ t: 'navigate', navigation })
+ )
+ .with({ t: 'abort' }, ({ navigation, reason }) =>
+ abortUrl(navigation, reason)
+ )
+ .with({ t: 'revert' }, ({ navigation }) => revert(navigation, dispatch))
+ .with({ t: 'cancel-pane-runs' }, () => abortPanes('superseded'))
+ .with({ t: 'opened' }, release)
+ .exhaustive();
+
+ sweep();
+ };
+
+ const gate = createMachine<GateState, GateEvent, GateCommand>({
+ initial: { t: 'open' },
+ def: urlGateDef,
+ execute: executeGate,
+ });
+
+ /**
+ * Settles once pane actions may run: no commit is running and no URL
+ * navigation could replace the panes. Synchronous when nothing is in the
+ * way, including a revert that lands at once.
+ */
+ const whenIdle = (): MaybePromise<void> => {
+ if (isOpen()) return;
+
+ // A running commit ends by itself; only a URL navigation needs to hear that an action waits.
+ if (committing === 0) gate.dispatch({ t: 'action' });
+ if (isOpen()) return;
+
+ const opened = new Promise<void>((resolve) => waiters.push(resolve));
+ void track(opened);
+
+ return opened;
+ };
+
+ /**
+ * Runs `work` once pane actions may run, or returns `disposed` after
+ * `dispose()`. Waking up is no promise: a URL navigation may have started
+ * since, so a woken action asks again.
+ */
+ const act = <T>(
+ disposedValue: T,
+ work: () => MaybePromise<T>
+ ): MaybePromise<T> => {
+ const idle = whenIdle();
+ if (isPromise(idle)) return mapMaybe(idle, () => act(disposedValue, work));
+
+ if (disposed) return disposedValue;
+
+ return untrack(work);
+ };
+
+ return {
+ /** Navigates one pane, replacing whatever that pane had in flight. */
+ start(pane: PaneId, navigation: Navigation) {
+ const begin = () => paneRun(pane).dispatch({ t: 'navigate', navigation });
+
+ return run(navigation, begin);
+ },
+
+ /** Starts a URL navigation; `blocking` makes pane actions wait instead of interrupting it. */
+ startUrl(navigation: Navigation, blocking: boolean) {
+ const begin = () => gate.dispatch({ t: 'start', navigation, blocking });
+
+ return run(navigation, begin);
+ },
+
+ /** Applies without guards or middleware. */
+ commitNow(navigation: Navigation): NavigationResult {
+ const entries = navigation.targets.map((target) => target.to);
+
+ return commit(navigation, entries);
+ },
+
+ whenIdle,
+ act,
+ abort,
+
+ /** The navigation `pane`'s own run has in flight, if any. */
+ inFlight(pane: PaneId): Navigation | undefined {
+ const state = findRun(pane)?.getState();
+ if (!state || state.t === 'idle') return;
+
+ return state.navigation;
+ },
+
+ isRunning(pane: PaneId): boolean {
+ const machine = findRun(pane);
+ if (!machine) return false;
+
+ return machine.getState().t !== 'idle';
+ },
+
+ pending: inFlight.pending,
+
+ /** Resolves once nothing is in flight. */
+ async settled(): Promise<void> {
+ while (outstanding.length > 0) {
+ await Promise.all(outstanding);
+ }
+ },
+
+ /** Cancels everything; waiting actions run and see the runner disposed. */
+ dispose(): void {
+ disposed = true;
+ gate.dispatch({ t: 'dispose' });
+ abortPanes('disposed');
+
+ for (const { machine } of paneRuns) {
+ machine.dispose();
+ }
+
+ paneRuns.length = 0;
+ urlRun.dispose();
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/router/types.ts b/apps/web/src/lib/split-router/next/router/types.ts
new file mode 100644
index 0000000000..7cc5de0799
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/types.ts
@@ -0,0 +1,115 @@
+import type { HistoryAdapter } from '../history/types';
+import type { Panes } from '../panes/panes';
+import type { CloseAction, PanePolicy, PaneStore } from '../panes/types';
+import type {
+ Entry,
+ PaneId,
+ SplitLocation,
+ SplitRouteInfo,
+ SplitRouteParams,
+ SplitRoutes,
+ SplitSearchUpdate,
+} from '../routes/types';
+import type { MaybePromise } from '../utils';
+import type { EntryOptions } from './entries';
+import type { SplitRouterMiddleware } from './middleware';
+
+export type NavigationCause =
+ | 'initial'
+ | 'external'
+ | 'navigate'
+ | 'history'
+ | 'search';
+
+/** Where one pane is going. */
+export type PaneTarget = {
+ pane: PaneId;
+ from?: Entry;
+ to: Entry;
+};
+
+/** How a visit records its entry in the pane's history. */
+export type VisitHistory =
+ | 'push'
+ | 'replace'
+ | { go: number }
+ | { reset: readonly Entry[]; index: number };
+
+/** Who shows a claimed resource: a pane, or a preview or popover registered for it. */
+export type ClaimOwner = PaneId | symbol;
+
+export type NavigationResult =
+ | { status: 'committed'; pane: PaneId }
+ | { status: 'activated'; owner: ClaimOwner }
+ | { status: 'unchanged'; pane: PaneId }
+ | { status: 'cancelled' };
+
+export const CANCELLED_RESULT: NavigationResult = { status: 'cancelled' };
+
+/** A change to what panes show: guards, then middleware, then preload, then `apply`. */
+export type Navigation = {
+ cause: NavigationCause;
+ targets: readonly PaneTarget[];
+ /** Panes being removed; their leave guards must allow it too. */
+ removed?: readonly PaneId[];
+ /** Raw incoming query on initial and external navigation. */
+ externalSearch?: string;
+ /** Undo what started it, such as a browser back. */
+ revert?: () => MaybePromise<void>;
+ /** Changes the panes to show `entries`, one per target, and writes the URL. */
+ apply(entries: readonly Entry[]): NavigationResult;
+};
+
+export type CancelReason =
+ /** A leave guard said no. */
+ | 'refused'
+ /** Middleware cancelled it. */
+ | 'cancelled'
+ /** A newer navigation replaced it. */
+ | 'superseded'
+ /** A pane action took over from a URL navigation. */
+ | 'interrupted'
+ | 'disposed'
+ | 'failed';
+
+/** The pane policy for panes that show routes. */
+export type SplitPanePolicy = PanePolicy<Entry, SplitLocation>;
+export type SplitCloseAction = CloseAction<Entry, SplitLocation>;
+export type RouterPanes = Panes<Entry, SplitLocation>;
+
+export type SplitNavigateOptions = EntryOptions & {
+ replace?: boolean;
+ search?: Readonly<Record<string, SplitSearchUpdate>>;
+ /** Commit even when another pane or preview already shows the destination. */
+ allowDuplicate?: boolean;
+ /** Depth of the calling outlet; relative paths resolve against it. */
+ depth?: number;
+};
+
+export type LeaveGuardContext = {
+ pane: PaneId;
+ from: Entry;
+ /** Undefined when the pane closes or the host leaves the router's routes. */
+ to?: Entry;
+ cause: NavigationCause;
+ signal: AbortSignal;
+};
+
+export type LeaveGuard = (context: LeaveGuardContext) => MaybePromise<boolean>;
+
+export type RouteMatchInfo = {
+ id: string;
+ params: SplitRouteParams;
+ info?: SplitRouteInfo;
+};
+
+export type SplitRouterOptions = {
+ routes: SplitRoutes;
+ history: HistoryAdapter;
+ paneStore: PaneStore<Entry>;
+ policy: SplitPanePolicy;
+ middleware?: readonly SplitRouterMiddleware[];
+ /** How long a navigation waits for route data preloads before committing. */
+ preloadBudgetMs?: number;
+ createPaneId?: () => PaneId;
+};
diff --git a/apps/web/src/lib/split-router/next/router/url-gate.ts b/apps/web/src/lib/split-router/next/router/url-gate.ts
new file mode 100644
index 0000000000..b89521f2ee
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/url-gate.ts
@@ -0,0 +1,213 @@
+import type { MachineDef, Transition } from '@macro-inc/machine';
+import { match } from 'ts-pattern';
+import type { CancelReason, Navigation } from './types';
+
+/**
+ * Whether pane actions may run, as a state machine. A URL navigation
+ * replaces every pane at once, so actions can't run against panes it is
+ * about to replace. Pure: `runner.ts` runs URL navigations and
+ * reverts and reports back.
+ */
+
+/** How a URL navigation's run ended. */
+export type UrlOutcome = CancelReason | 'committed';
+
+export type State =
+ | { readonly t: 'open' }
+ | {
+ readonly t: 'navigating';
+ readonly navigation: Navigation;
+ readonly blocking: boolean;
+ /** URL navigations this one replaced, oldest first; their URLs are still in history. */
+ readonly superseded: readonly Navigation[];
+ }
+ /** URLs being put back one at a time; the first one's revert is in flight. */
+ | { readonly t: 'reverting'; readonly queue: readonly Navigation[] }
+ | { readonly t: 'disposed' };
+
+export type Event =
+ | {
+ readonly t: 'start';
+ readonly navigation: Navigation;
+ readonly blocking: boolean;
+ }
+ /** Every URL navigation's outcome; only the current one's counts. */
+ | {
+ readonly t: 'settled';
+ readonly navigation: Navigation;
+ readonly outcome: UrlOutcome;
+ }
+ | { readonly t: 'action' }
+ | { readonly t: 'revert-landed' }
+ | { readonly t: 'dispose' };
+
+export type Command =
+ | { readonly t: 'run'; readonly navigation: Navigation }
+ | {
+ readonly t: 'abort';
+ readonly navigation: Navigation;
+ readonly reason: 'interrupted' | 'disposed';
+ }
+ /** Put back the URL `navigation` landed on, then report `revert-landed`. */
+ | { readonly t: 'revert'; readonly navigation: Navigation }
+ | { readonly t: 'cancel-pane-runs' }
+ /** Waiting actions may run. */
+ | { readonly t: 'opened' };
+
+type Result = Transition<State, Command> | undefined;
+type Navigating = Extract<State, { t: 'navigating' }>;
+type Reverting = Extract<State, { t: 'reverting' }>;
+type Start = Extract<Event, { t: 'start' }>;
+type Settled = Extract<Event, { t: 'settled' }>;
+
+const OPEN: State = { t: 'open' };
+const DISPOSED: State = { t: 'disposed' };
+const OPENED: Command = { t: 'opened' };
+
+const abort = (
+ navigation: Navigation,
+ reason: 'interrupted' | 'disposed'
+): Command => ({ t: 'abort', navigation, reason });
+
+function run(
+ navigation: Navigation,
+ blocking: boolean,
+ superseded: readonly Navigation[]
+): Result {
+ return {
+ state: { t: 'navigating', navigation, blocking, superseded },
+ commands: [{ t: 'cancel-pane-runs' }, { t: 'run', navigation }],
+ };
+}
+
+/** Put back `s`'s URL, then those of the navigations it replaced, newest first. */
+function putBack(s: Navigating, commands: readonly Command[] = []): Result {
+ const queue = [s.navigation, ...[...s.superseded].reverse()];
+
+ return {
+ state: { t: 'reverting', queue },
+ commands: [...commands, { t: 'revert', navigation: s.navigation }],
+ };
+}
+
+/** A navigation that replaces another inherits its blocking and keeps it to put back later. */
+function supersede(s: Navigating, e: Start): Result {
+ const blocking = s.blocking || e.blocking;
+ const superseded = [...s.superseded, s.navigation];
+
+ return run(e.navigation, blocking, superseded);
+}
+
+/** Committing opens the gate; guards or middleware turning it down put its URLs back; a failure does neither. */
+function settle(s: Navigating, e: Settled): Result {
+ const current = e.navigation === s.navigation;
+ if (!current) return;
+
+ return match<UrlOutcome, Result>(e.outcome)
+ .with('committed', () => ({ state: OPEN, commands: [OPENED] }))
+ .with('refused', 'cancelled', () => putBack(s))
+ .with('failed', () => ({ state: OPEN, commands: [OPENED] }))
+ .with('superseded', 'interrupted', 'disposed', () => undefined)
+ .exhaustive();
+}
+
+/** An action waits for a blocking navigation, and otherwise takes over from it. */
+function interrupt(s: Navigating): Result {
+ if (s.blocking) return;
+
+ return putBack(s, [abort(s.navigation, 'interrupted')]);
+}
+
+/** Disposing opens the gate so waiting actions run and see the router disposed. */
+function disposeNavigating(s: Navigating): Result {
+ return {
+ state: DISPOSED,
+ commands: [abort(s.navigation, 'disposed'), OPENED],
+ };
+}
+
+function navigating(s: Navigating, e: Event): Result {
+ return match(e)
+ .with({ t: 'start' }, (e) => supersede(s, e))
+ .with({ t: 'settled' }, (e) => settle(s, e))
+ .with({ t: 'action' }, () => interrupt(s))
+ .with({ t: 'dispose' }, () => disposeNavigating(s))
+ .with({ t: 'revert-landed' }, () => undefined)
+ .exhaustive();
+}
+
+function revertLanded(s: Reverting): Result {
+ const [, ...rest] = s.queue;
+ const [next] = rest;
+ if (!next) return { state: OPEN, commands: [OPENED] };
+
+ return {
+ state: { t: 'reverting', queue: rest },
+ commands: [{ t: 'revert', navigation: next }],
+ };
+}
+
+/**
+ * A navigation arriving while URLs are put back is turned away and put back
+ * next, before older ones still queued: history is unwound newest first.
+ */
+function queueRevert(s: Reverting, e: Start): Result {
+ const { navigation } = e;
+ const [inFlight, ...older] = s.queue;
+ const queue = [inFlight!, navigation, ...older];
+
+ return {
+ state: { t: 'reverting', queue },
+ commands: [abort(navigation, 'interrupted')],
+ };
+}
+
+function reverting(s: Reverting, e: Event): Result {
+ return match(e)
+ .with({ t: 'start' }, (e) => queueRevert(s, e))
+ .with({ t: 'revert-landed' }, () => revertLanded(s))
+ .with(
+ { t: 'dispose' },
+ (): Result => ({
+ state: DISPOSED,
+ commands: [OPENED],
+ })
+ )
+ .with({ t: 'action' }, { t: 'settled' }, () => undefined)
+ .exhaustive();
+}
+
+function open(e: Event): Result {
+ return match(e)
+ .with({ t: 'start' }, (e) => run(e.navigation, e.blocking, []))
+ .with({ t: 'action' }, (): Result => ({ state: OPEN, commands: [OPENED] }))
+ .with({ t: 'dispose' }, (): Result => ({ state: DISPOSED }))
+ .with({ t: 'settled' }, { t: 'revert-landed' }, () => undefined)
+ .exhaustive();
+}
+
+function disposed(e: Event): Result {
+ return match(e)
+ .with(
+ { t: 'start' },
+ (e): Result => ({
+ state: DISPOSED,
+ commands: [abort(e.navigation, 'disposed')],
+ })
+ )
+ .with(
+ { t: 'action' },
+ (): Result => ({
+ state: DISPOSED,
+ commands: [OPENED],
+ })
+ )
+ .otherwise(() => undefined);
+}
+
+export const urlGateDef: MachineDef<State, Event, Command> = {
+ open: { on: (_s, e) => open(e) },
+ navigating: { on: navigating },
+ reverting: { on: reverting },
+ disposed: { on: (_s, e) => disposed(e) },
+};
diff --git a/apps/web/src/lib/split-router/next/router/url-navigation.ts b/apps/web/src/lib/split-router/next/router/url-navigation.ts
new file mode 100644
index 0000000000..a4bbb9de90
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/url-navigation.ts
@@ -0,0 +1,178 @@
+import { untrack } from 'solid-js';
+import type {
+ ExternalChange,
+ HistoryAdapter,
+ InterceptHandler,
+} from '../history/types';
+import { type ChangedPane, changedPanes } from '../panes/diff';
+import { decodePanes, sameExternalLocation } from '../routes/codec';
+import type { SplitRoutesManifest } from '../routes/manifest';
+import type { Entry, ExternalLocation, WriteMode } from '../routes/types';
+import { type MaybePromise, UNCANCELLABLE } from '../utils';
+import { sameVisit } from './entries';
+import {
+ checksFor,
+ type LeaveGuards,
+ PANE_LEVEL,
+ runChecks,
+} from './leave-guards';
+import type { Runner } from './runner';
+import type {
+ Navigation,
+ NavigationCause,
+ NavigationResult,
+ PaneTarget,
+ RouterPanes,
+} from './types';
+import type { Url } from './url';
+
+type UrlNavigationOptions = {
+ cause: NavigationCause;
+ /** How applying it writes the URL back. */
+ mode: WriteMode;
+ revert?: () => MaybePromise<void>;
+};
+
+// The URL owns the location and history state owns route state; the stored
+// entry keeps its in-memory props and metadata.
+const adopt = (stored: Entry, incoming: Entry): Entry => ({
+ ...stored,
+ location: incoming.location,
+ state: incoming.state,
+});
+
+function toTarget(change: ChangedPane<Entry>): PaneTarget {
+ if (change.kind === 'change') {
+ return { pane: change.pane, from: change.from, to: change.to };
+ }
+
+ return { pane: change.pane, to: change.entry };
+}
+
+/** The panes following the URL: the first load, Back/Forward, and links from outside. */
+export function createUrlNavigation(options: {
+ routes: SplitRoutesManifest;
+ history: HistoryAdapter;
+ panes: RouterPanes;
+ url: Url;
+ runner: Runner;
+ guards: LeaveGuards;
+ markReady(): void;
+}) {
+ const { routes, history, panes, url, runner, guards } = options;
+
+ /** Makes every pane show `location`. */
+ const navigationTo = (
+ location: ExternalLocation,
+ { cause, mode, revert }: UrlNavigationOptions
+ ): Navigation => {
+ const decoded = decodePanes(routes, location);
+ const diff = panes.diff(decoded.panes, { same: sameVisit, adopt });
+
+ const apply = (entries: readonly Entry[]): NavigationResult => {
+ panes.applyDiff(diff, entries);
+ url.write(mode, { landed: location });
+ options.markReady();
+
+ const [first] = diff.panes;
+
+ return { status: 'committed', pane: first!.pane };
+ };
+
+ return {
+ cause,
+ externalSearch: location.search,
+ targets: changedPanes(diff).map(toTarget),
+ removed: diff.removed,
+ revert,
+ apply,
+ };
+ };
+
+ /** The first load; pane actions wait for it. */
+ const load = (location: ExternalLocation) => {
+ const navigation = navigationTo(location, {
+ cause: 'initial',
+ mode: 'replace',
+ });
+
+ return runner.startUrl(navigation, true);
+ };
+
+ /** Back/Forward, or any URL change the router didn't make; it can be put back. */
+ const follow = (change: ExternalChange) => {
+ // Adapters may report our own writes and reverts landing; those match what we show.
+ const alreadyShown = sameExternalLocation(change.location, url.lastKnown());
+ if (alreadyShown) return;
+
+ const previous = url.lastKnown();
+ url.remember(change.location);
+
+ const revert = () => {
+ url.remember(previous);
+
+ return change.revert();
+ };
+
+ const navigation = navigationTo(change.location, {
+ cause: 'external',
+ mode: 'replace',
+ revert,
+ });
+
+ void runner.startUrl(navigation, false);
+ };
+
+ /** A link into the router's routes, handled before it lands; the router writes the URL itself. */
+ const takeOver = (location: ExternalLocation) => {
+ const navigation = navigationTo(location, {
+ cause: 'external',
+ mode: 'push',
+ });
+
+ void runner.startUrl(navigation, false);
+
+ return false;
+ };
+
+ /** Whether every pane's guards let the host leave the router's routes. */
+ const canLeave = () => {
+ const checks = untrack(panes.ids).flatMap((pane) => {
+ const from = untrack(() => panes.current(pane));
+ if (!from) return [];
+
+ const context = {
+ pane,
+ from,
+ cause: 'external' as const,
+ signal: UNCANCELLABLE,
+ };
+
+ return checksFor(guards.select(pane, PANE_LEVEL), context);
+ });
+
+ return runChecks(checks);
+ };
+
+ const intercept: InterceptHandler = (location) => {
+ const leavingRouter = !location;
+ if (leavingRouter) return canLeave();
+
+ return takeOver(location);
+ };
+
+ return {
+ /** Loads the URL and follows the history adapter until the returned stop is called. */
+ connect(): () => void {
+ const unsubscribe = history.subscribe(follow);
+ const stopIntercept = history.intercept?.(intercept);
+
+ void load(url.lastKnown());
+
+ return () => {
+ unsubscribe();
+ stopIntercept?.();
+ };
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/router/url.ts b/apps/web/src/lib/split-router/next/router/url.ts
new file mode 100644
index 0000000000..2f93544b39
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/router/url.ts
@@ -0,0 +1,61 @@
+import { untrack } from 'solid-js';
+import type { HistoryAdapter } from '../history/types';
+import { encodePanes, sameExternalLocation } from '../routes/codec';
+import type { SplitRoutesManifest } from '../routes/manifest';
+import type { ExternalLocation, PaneId, WriteMode } from '../routes/types';
+import type { RouterPanes } from './types';
+
+export type Url = ReturnType<typeof createUrl>;
+
+/** Writes the panes to the URL, and remembers the URL they were last known to show. */
+export function createUrl(options: {
+ routes: SplitRoutesManifest;
+ history: HistoryAdapter;
+ panes: RouterPanes;
+}) {
+ const { routes, history, panes } = options;
+ let lastKnown: ExternalLocation = history.read();
+
+ const shownPanes = () =>
+ untrack(panes.ids).flatMap((pane) => {
+ const entry = untrack(() => panes.current(pane));
+ if (!entry) return [];
+
+ return [{ paneId: pane, entry }];
+ });
+
+ return {
+ lastKnown: () => lastKnown,
+
+ /** The URL shows `location` now, though the router didn't write it. */
+ remember(location: ExternalLocation) {
+ lastKnown = location;
+ },
+
+ /** `landed` is the URL a URL navigation landed on; its hash and global keys carry over. */
+ write(mode: WriteMode, writeOptions: { landed?: ExternalLocation } = {}) {
+ const shown = shownPanes();
+ if (shown.length === 0) return;
+
+ const { landed } = writeOptions;
+ const basis = landed ?? lastKnown;
+ const keepHash = landed !== undefined;
+ const next = encodePanes(routes, shown, basis, { keepHash });
+ if (sameExternalLocation(next, lastKnown)) return;
+
+ // A write that throws never reached the URL, so it isn't known yet.
+ history.write(next, { mode });
+ lastKnown = next;
+ },
+
+ /** An href for one pane's current entry, for copying or a new tab. */
+ href(pane: PaneId): string {
+ const entry = untrack(() => panes.current(pane));
+ if (!entry) return '';
+
+ const single = [{ paneId: pane, entry }];
+
+ return history.href(encodePanes(routes, single, lastKnown));
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/routes/codec.ts b/apps/web/src/lib/split-router/next/routes/codec.ts
new file mode 100644
index 0000000000..9d5f8e6c50
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/routes/codec.ts
@@ -0,0 +1,291 @@
+import deepEqual from 'fast-deep-equal';
+import { createId, isRecord } from '../utils';
+import {
+ decodePane,
+ defaultRoute,
+ formatPane,
+ type SplitRoutesManifest,
+} from './manifest';
+import { decodeSegment, SPLIT_PATH_SEPARATOR, splitSegments } from './path';
+import {
+ externalSearchKeys,
+ filterRouteSearch,
+ parseRouteEntryState,
+} from './queries';
+import {
+ isSplitSearchKey,
+ parsePaneSearch,
+ replacePaneSearchParams,
+} from './search';
+import type {
+ Entry,
+ ExternalLocation,
+ PaneId,
+ SplitHistoryPane,
+ SplitHistoryState,
+ SplitRouteState,
+} from './types';
+
+type DecodedPane = { paneId?: PaneId; entry: Entry };
+type DecodedPanes = { panes: readonly DecodedPane[] };
+type EncodedPane = { paneId: PaneId; entry: Entry };
+
+const LOCATION_BASE = 'http://split-router.invalid';
+
+export function parseLocation(value: string): Omit<ExternalLocation, 'state'> {
+ const url = new URL(value, LOCATION_BASE);
+
+ return { path: url.pathname, search: url.search, hash: url.hash };
+}
+
+function ensurePrefix(value: string, prefix: string): string {
+ if (!value) return value;
+ if (value.startsWith(prefix)) return value;
+
+ return `${prefix}${value}`;
+}
+
+export function formatLocation(
+ location: Pick<ExternalLocation, 'path' | 'search' | 'hash'>
+): string {
+ const path = location.path || '/';
+ const search = ensurePrefix(location.search, '?');
+ const hash = ensurePrefix(location.hash, '#');
+
+ return `${path}${search}${hash}`;
+}
+
+/** Raw, still percent-encoded segments for each pane, split on `~`. */
+export function splitPanePaths(path: string): string[][] {
+ const panes: string[][] = [[]];
+
+ for (const segment of splitSegments(path)) {
+ if (segment === SPLIT_PATH_SEPARATOR) {
+ panes.push([]);
+ continue;
+ }
+
+ panes[panes.length - 1]!.push(segment);
+ }
+
+ return panes.filter((pane) => pane.length > 0);
+}
+
+function encodeSegment(segment: string): string {
+ // `~` is unreserved, so a literal value would read back as a pane separator.
+ return segment === SPLIT_PATH_SEPARATOR ? '%7E' : encodeURIComponent(segment);
+}
+
+function decodePaneSegments(
+ routes: SplitRoutesManifest,
+ raw: readonly string[]
+): SplitRouteState {
+ const segments = raw.map(decodeSegment);
+
+ return decodePane(routes, segments) ?? defaultRoute(routes);
+}
+
+function readHistoryPane(value: unknown): SplitHistoryPane | undefined {
+ if (!isRecord(value)) return;
+ if (typeof value.pane !== 'string') return;
+ if (typeof value.entry !== 'string') return;
+
+ const stored: SplitHistoryPane = {
+ pane: value.pane as PaneId,
+ entry: value.entry,
+ };
+ if (Object.hasOwn(value, 'state')) stored.state = value.state;
+
+ return stored;
+}
+
+/** Validates an untrusted split-router slice of browser history state. */
+export function readHistoryState(
+ value: unknown
+): SplitHistoryState | undefined {
+ if (!isRecord(value)) return;
+ if (!Array.isArray(value.panes)) return;
+
+ const panes: SplitHistoryPane[] = [];
+
+ for (const raw of value.panes) {
+ const pane = readHistoryPane(raw);
+ if (!pane) return;
+
+ panes.push(pane);
+ }
+
+ return { panes };
+}
+
+function storedPanes(
+ state: unknown,
+ count: number
+): readonly SplitHistoryPane[] | undefined {
+ const saved = readHistoryState(state);
+ if (!saved) return;
+ if (saved.panes.length !== count) return;
+
+ return saved.panes;
+}
+
+function storedState(
+ routes: SplitRoutesManifest,
+ route: SplitRouteState,
+ pane: SplitHistoryPane | undefined
+): unknown {
+ if (!pane) return;
+ if (!Object.hasOwn(pane, 'state')) return;
+
+ const parsed = parseRouteEntryState(routes, route, pane.state);
+
+ return parsed.success ? parsed.value : undefined;
+}
+
+function defaultPanes(
+ routes: SplitRoutesManifest,
+ createEntryId: () => string
+): DecodedPanes {
+ const entry: Entry = {
+ id: createEntryId(),
+ location: { route: defaultRoute(routes) },
+ };
+
+ return { panes: [{ entry }] };
+}
+
+/**
+ * Each pane decodes on its own. A pane that matches nothing lands on the
+ * catch-all route (or the default route when there is none); others are unaffected.
+ */
+export function decodePanes(
+ routes: SplitRoutesManifest,
+ location: ExternalLocation,
+ createEntryId: () => string = () => createId('entry')
+): DecodedPanes {
+ const parts = splitPanePaths(location.path);
+ const search = parsePaneSearch(location.search);
+ const stored = storedPanes(location.state, parts.length);
+
+ const panes = parts.map((raw, position): DecodedPane => {
+ const route = decodePaneSegments(routes, raw);
+ const pane = stored?.[position];
+ const entry: Entry = {
+ id: pane?.entry ?? createEntryId(),
+ location: { route },
+ };
+
+ const paneSearch = filterRouteSearch(routes, route, search[position]);
+ if (paneSearch) entry.location.search = paneSearch;
+
+ const state = storedState(routes, route, pane);
+ if (state !== undefined) entry.state = state;
+
+ return pane ? { paneId: pane.pane, entry } : { entry };
+ });
+
+ if (panes.length > 0) return { panes };
+
+ return defaultPanes(routes, createEntryId);
+}
+
+export function formatPanePath(
+ routes: SplitRoutesManifest,
+ route: SplitRouteState
+): string {
+ const segments = formatPane(routes, route).map(encodeSegment);
+
+ return `/${segments.join('/')}`;
+}
+
+function normalizePath(path: string): string {
+ if (path.length > 1) return path.replace(/\/+$/g, '');
+
+ return path || '/';
+}
+
+function panesPath(
+ routes: SplitRoutesManifest,
+ entries: readonly Entry[]
+): string {
+ const panePaths = entries.map((entry) =>
+ formatPanePath(routes, entry.location.route)
+ );
+
+ return panePaths.join(`/${SPLIT_PATH_SEPARATOR}`);
+}
+
+function panesSearch(
+ routes: SplitRoutesManifest,
+ entries: readonly Entry[],
+ previousSearch: string
+): string {
+ const owned = externalSearchKeys(routes, entries);
+ const query = new URLSearchParams();
+
+ for (const [key, value] of new URLSearchParams(previousSearch)) {
+ const keep = !isSplitSearchKey(key) && owned.includes(key);
+ if (keep) query.append(key, value);
+ }
+
+ const paneSearch = entries.map((entry) =>
+ filterRouteSearch(routes, entry.location.route, entry.location.search)
+ );
+ replacePaneSearchParams(query, paneSearch);
+ query.sort();
+
+ const search = query.toString();
+
+ return search ? `?${search}` : '';
+}
+
+function historyPane({ paneId, entry }: EncodedPane): SplitHistoryPane {
+ const stored: SplitHistoryPane = { pane: paneId, entry: entry.id };
+ if (entry.state !== undefined) stored.state = entry.state;
+
+ return stored;
+}
+
+/**
+ * The URL for `panes`. The hash from `previous` survives when the path is
+ * unchanged, or with `keepHash` when rewriting the URL a URL navigation landed on.
+ */
+export function encodePanes(
+ routes: SplitRoutesManifest,
+ panes: readonly EncodedPane[],
+ previous: Pick<ExternalLocation, 'path' | 'search' | 'hash'>,
+ options: { keepHash?: boolean } = {}
+): ExternalLocation {
+ const entries = panes.map(({ entry }) => entry);
+ const path = panesPath(routes, entries);
+ const search = panesSearch(routes, entries, previous.search);
+ const samePath = normalizePath(path) === normalizePath(previous.path);
+ const keepHash = options.keepHash || samePath;
+
+ return {
+ path: path || '/',
+ search,
+ hash: keepHash ? previous.hash : '',
+ state: { panes: panes.map(historyPane) },
+ };
+}
+
+function sortedQuery(search: string): string {
+ const query = new URLSearchParams(search);
+ query.sort();
+
+ return query.toString();
+}
+
+export function sameExternalLocation(
+ left: ExternalLocation,
+ right: ExternalLocation
+): boolean {
+ const samePath = normalizePath(left.path) === normalizePath(right.path);
+ const sameSearch = sortedQuery(left.search) === sortedQuery(right.search);
+ const sameHash = left.hash === right.hash;
+
+ return (
+ samePath && sameSearch && sameHash && deepEqual(left.state, right.state)
+ );
+}
diff --git a/apps/web/src/lib/split-router/next/routes/define.ts b/apps/web/src/lib/split-router/next/routes/define.ts
new file mode 100644
index 0000000000..e1a0fe80c5
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/routes/define.ts
@@ -0,0 +1,240 @@
+import type { StandardSchemaV1 } from '@standard-schema/spec';
+import type {
+ DefinedSplitRoute,
+ DefinedSplitRoutes,
+ Entry,
+ InferSplitRouteParams,
+ InferSplitRoutePathParams,
+ SplitRouteClaim,
+ SplitRouteInfo,
+ SplitRoutePreloadContext,
+ SplitRouteRawParams,
+ SplitRouteRemountContext,
+ SplitRoutes,
+} from './types';
+
+type SplitRouteDefinitionConstraint = {
+ id: string;
+ path: string;
+ aliases?: readonly string[];
+ component?: unknown;
+ children?: readonly SplitRouteDefinitionConstraint[];
+ params?: StandardSchemaV1;
+ state?: StandardSchemaV1;
+ serializeParams?: unknown;
+ claim?: unknown;
+ search?: readonly string[];
+ externalSearch?:
+ | readonly string[]
+ | ((entry: Readonly<Entry>) => readonly string[]);
+ remountKey?: unknown;
+ preload?: unknown;
+ info?: SplitRouteInfo;
+};
+
+type RouteParamCallbacks<TParams> = {
+ serializeParams?: (params: TParams) => SplitRouteRawParams;
+ claim?: (params: TParams) => SplitRouteClaim | undefined;
+ remountKey?: (
+ params: TParams,
+ context: SplitRouteRemountContext
+ ) => string | number | undefined;
+ preload?: (
+ context: SplitRoutePreloadContext<TParams>
+ ) => void | Promise<unknown>;
+};
+
+type KeysOfUnion<T> = T extends unknown ? keyof T : never;
+
+type RequiredKeys<T> = {
+ [K in keyof T]-?: {} extends Pick<T, K> ? never : K;
+}[keyof T];
+
+// Schemas may narrow or coerce raw string values. The declaration boundary
+// therefore compares parameter names and requiredness, not value domains.
+type CompatibleSchemaInputs<TPathParams, TSchemaInput> =
+ TSchemaInput extends unknown
+ ? Exclude<keyof TPathParams, keyof TSchemaInput> extends never
+ ? Exclude<
+ RequiredKeys<TPathParams>,
+ RequiredKeys<TSchemaInput>
+ > extends never
+ ? Exclude<
+ RequiredKeys<TSchemaInput>,
+ RequiredKeys<TPathParams>
+ > extends never
+ ? TSchemaInput
+ : never
+ : never
+ : never
+ : never;
+
+type InvalidSchemaPathParams<TPathParams, TSchemaInput> =
+ TPathParams extends unknown
+ ? [CompatibleSchemaInputs<TPathParams, TSchemaInput>] extends [never]
+ ? TPathParams
+ : never
+ : never;
+
+type RouteParamsSchemaIssue<
+ TPath extends string,
+ TAliases extends readonly string[] | undefined,
+ TSchema extends StandardSchemaV1,
+> =
+ InferSplitRoutePathParams<TPath, TAliases> extends infer TPathParams
+ ? InvalidSchemaPathParams<
+ TPathParams,
+ StandardSchemaV1.InferInput<TSchema>
+ > extends infer TInvalidPathParams
+ ? [TInvalidPathParams] extends [never]
+ ? never
+ : {
+ path: TPath;
+ aliases: TAliases;
+ pathParams: TPathParams;
+ schemaInput: StandardSchemaV1.InferInput<TSchema>;
+ missingSchemaKeys: Exclude<
+ KeysOfUnion<TPathParams>,
+ KeysOfUnion<StandardSchemaV1.InferInput<TSchema>>
+ >;
+ incompatiblePathParams: TInvalidPathParams;
+ }
+ : never
+ : never;
+
+type RouteParamsSchemaConstraint<
+ TPath extends string,
+ TAliases extends readonly string[] | undefined,
+ TSchema extends StandardSchemaV1,
+> = [RouteParamsSchemaIssue<TPath, TAliases, TSchema>] extends [never]
+ ? unknown
+ : {
+ readonly 'ERROR: params schema keys and optionality must match path and aliases': RouteParamsSchemaIssue<
+ TPath,
+ TAliases,
+ TSchema
+ >;
+ };
+
+type DefinitionAliases<TDefinition> = TDefinition extends {
+ aliases: infer TAliases extends readonly string[];
+}
+ ? TAliases
+ : undefined;
+
+type SplitRouteDefinitionRemainder = Omit<
+ SplitRouteDefinitionConstraint,
+ 'path' | 'params'
+>;
+
+type RouteDefinitionParamsSchemaIssues<TDefinition> =
+ | (TDefinition extends {
+ id: infer TId;
+ path: infer TPath extends string;
+ params: infer TSchema extends StandardSchemaV1;
+ }
+ ? RouteParamsSchemaIssue<
+ TPath,
+ DefinitionAliases<TDefinition>,
+ TSchema
+ > extends infer TIssue
+ ? [TIssue] extends [never]
+ ? never
+ : TIssue & { routeId: TId }
+ : never
+ : never)
+ | (TDefinition extends {
+ children: infer TChildren extends readonly unknown[];
+ }
+ ? RouteDefinitionsParamsSchemaIssues<TChildren>
+ : never);
+
+type RouteDefinitionsParamsSchemaIssues<
+ TDefinitions extends readonly unknown[],
+> = TDefinitions[number] extends infer TDefinition
+ ? RouteDefinitionParamsSchemaIssues<TDefinition>
+ : never;
+
+type RouteDefinitionsParamsSchemaConstraint<
+ TDefinitions extends readonly unknown[],
+> = [RouteDefinitionsParamsSchemaIssues<TDefinitions>] extends [never]
+ ? unknown
+ : {
+ readonly 'ERROR: route params schema keys and optionality must match paths and aliases': RouteDefinitionsParamsSchemaIssues<TDefinitions>;
+ };
+
+export function defineRoute<
+ const TPath extends string,
+ const TAliases extends readonly string[] | undefined,
+ const TDefinition extends SplitRouteDefinitionConstraint,
+>(
+ definition: TDefinition & {
+ path: TPath;
+ aliases: TAliases;
+ params?: undefined;
+ } & RouteParamCallbacks<
+ InferSplitRouteParams<{ path: TPath; aliases: TAliases }>
+ >
+): DefinedSplitRoute<
+ TDefinition & {
+ path: TPath;
+ aliases: TAliases;
+ params?: undefined;
+ } & RouteParamCallbacks<
+ InferSplitRouteParams<{ path: TPath; aliases: TAliases }>
+ >
+>;
+export function defineRoute<
+ const TPath extends string,
+ const TDefinition extends SplitRouteDefinitionConstraint,
+>(
+ definition: TDefinition & {
+ path: TPath;
+ aliases?: undefined;
+ params?: undefined;
+ } & RouteParamCallbacks<InferSplitRouteParams<{ path: TPath }>>
+): DefinedSplitRoute<
+ TDefinition & {
+ path: TPath;
+ aliases?: undefined;
+ params?: undefined;
+ } & RouteParamCallbacks<InferSplitRouteParams<{ path: TPath }>>
+>;
+export function defineRoute<
+ const TPath extends string,
+ const TParamsSchema extends StandardSchemaV1,
+ const TDefinition extends SplitRouteDefinitionRemainder,
+>(
+ definition: TDefinition & {
+ path: TPath;
+ params: TParamsSchema;
+ } & RouteParamsSchemaConstraint<
+ NoInfer<TPath>,
+ DefinitionAliases<NoInfer<TDefinition>>,
+ NoInfer<TParamsSchema>
+ > &
+ RouteParamCallbacks<StandardSchemaV1.InferOutput<TParamsSchema>>
+): DefinedSplitRoute<
+ TDefinition & { path: TPath; params: TParamsSchema } & RouteParamCallbacks<
+ StandardSchemaV1.InferOutput<TParamsSchema>
+ >
+>;
+export function defineRoute(
+ definition: SplitRouteDefinitionConstraint
+): unknown {
+ // The overloads add phantom ancestry; runtime declarations remain untouched.
+ return definition;
+}
+
+/** Preserve the declaration tree and infer ancestry without constructing runtime state. */
+export function defineRoutes<
+ const TRoutes extends Omit<SplitRoutes, 'definitions'> & {
+ definitions: readonly SplitRouteDefinitionConstraint[];
+ },
+>(
+ routes: TRoutes &
+ (NoInfer<TRoutes> extends SplitRoutes ? unknown : SplitRoutes) &
+ RouteDefinitionsParamsSchemaConstraint<NoInfer<TRoutes>['definitions']>
+): DefinedSplitRoutes<TRoutes> {
+ return routes as DefinedSplitRoutes<TRoutes>;
+}
diff --git a/apps/web/src/lib/split-router/next/routes/manifest.ts b/apps/web/src/lib/split-router/next/routes/manifest.ts
new file mode 100644
index 0000000000..486f64bc99
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/routes/manifest.ts
@@ -0,0 +1,416 @@
+import type { StandardSchemaV1 } from '@standard-schema/spec';
+import { isRecord, isSafeName } from '../utils';
+import {
+ compileRoutePattern,
+ formatTokens,
+ matchTokens,
+ type PathToken,
+ patternKey,
+ type RoutePattern,
+ specificity,
+} from './path';
+import { assertSafeSearchName } from './search';
+import type {
+ SplitRouteDefinition,
+ SplitRouteMatch,
+ SplitRouteParams,
+ SplitRouteRawParams,
+ SplitRouteState,
+ SplitRoutes,
+} from './types';
+
+type RouteParamsCodec = {
+ parse(params: SplitRouteRawParams): SplitRouteParams | undefined;
+ serialize(params: SplitRouteParams): SplitRouteParams;
+};
+
+export type SplitRouteNode<TComponent = unknown> = {
+ readonly definition: SplitRouteDefinition<TComponent>;
+ readonly parent?: SplitRouteNode<TComponent>;
+ /** Root to this node, inclusive. */
+ readonly branch: readonly SplitRouteNode<TComponent>[];
+ readonly children: readonly SplitRouteNode<TComponent>[];
+ readonly pattern: RoutePattern;
+ readonly params: RouteParamsCodec;
+ /** Search namespaces owned through this node; `'any'` when nothing restricts them. */
+ readonly search: readonly string[] | 'any';
+ readonly state?: StandardSchemaV1;
+ readonly externalSearch: readonly SplitRouteDefinition<TComponent>[];
+};
+
+type RouteBranch<TComponent = unknown> = {
+ readonly nodes: readonly SplitRouteNode<TComponent>[];
+ readonly patterns: readonly (readonly PathToken[])[];
+ readonly score: number;
+ readonly order: number;
+};
+
+/** Runtime route state owned by one router, compiled once from static definitions. */
+export type SplitRoutesManifest<TComponent = unknown> = {
+ readonly byId: ReadonlyMap<string, SplitRouteNode<TComponent>>;
+ /** Every root-to-node path, most specific first. */
+ readonly branches: readonly RouteBranch<TComponent>[];
+ readonly globalSearch: readonly string[];
+ readonly defaultRoute: () => SplitRouteState;
+};
+
+function validateRouteParams(
+ schema: StandardSchemaV1 | undefined,
+ params: SplitRouteParams
+): SplitRouteParams | undefined {
+ if (!schema) return params;
+
+ const result = schema['~standard'].validate(params);
+
+ if (result instanceof Promise) {
+ throw new Error('Split route parameter schemas must be synchronous');
+ }
+
+ if (result.issues) return;
+
+ if (!isRecord(result.value)) {
+ throw new Error('Split route parameter schemas must return an object');
+ }
+
+ return result.value;
+}
+
+function createParamsCodec(definition: SplitRouteDefinition): RouteParamsCodec {
+ const schema = definition.params;
+ const serialize = definition.serializeParams?.bind(definition);
+
+ return {
+ parse: (params) => validateRouteParams(schema, params),
+ // Without a custom serializer, the pattern formats its primitive fields.
+ serialize: (params) => serialize?.(params) ?? params,
+ };
+}
+
+function ownNamespaces(search: readonly string[] | undefined): string[] {
+ const own: string[] = [];
+
+ for (const namespace of search ?? []) {
+ assertSafeSearchName(namespace, 'namespace');
+
+ if (own.includes(namespace)) {
+ throw new Error(`Duplicate split route search namespace "${namespace}"`);
+ }
+
+ own.push(namespace);
+ }
+
+ return own;
+}
+
+function branchSearch(
+ parent: SplitRouteNode | undefined,
+ search: readonly string[] | undefined
+): readonly string[] | 'any' {
+ const own = ownNamespaces(search);
+ if (!parent) return search === undefined ? 'any' : own;
+ if (parent.search === 'any') return 'any';
+
+ const inherited = parent.search;
+ const added = own.filter((name) => !inherited.includes(name));
+
+ return [...inherited, ...added];
+}
+
+function collectBranches<TComponent>(
+ branches: RouteBranch<TComponent>[],
+ node: SplitRouteNode<TComponent>,
+ nodes: readonly SplitRouteNode<TComponent>[],
+ patterns: readonly (readonly PathToken[])[]
+): void {
+ for (const tokens of node.pattern.alternatives) {
+ const branchNodes = [...nodes, node];
+ const branchPatterns = [...patterns, tokens];
+
+ branches.push({
+ nodes: branchNodes,
+ patterns: branchPatterns,
+ score: specificity(branchPatterns.flat()),
+ order: branches.length,
+ });
+
+ for (const child of node.children) {
+ collectBranches(branches, child, branchNodes, branchPatterns);
+ }
+ }
+}
+
+function bySpecificity(left: RouteBranch, right: RouteBranch): number {
+ return right.score - left.score || left.order - right.order;
+}
+
+function compileBranches<TComponent>(
+ roots: readonly SplitRouteNode<TComponent>[]
+): RouteBranch<TComponent>[] {
+ const branches: RouteBranch<TComponent>[] = [];
+
+ for (const root of roots) collectBranches(branches, root, [], []);
+
+ return branches.sort(bySpecificity);
+}
+
+function assertGlobalSearch(keys: readonly string[]): void {
+ for (const key of keys) {
+ if (!isSafeName(key)) {
+ throw new Error(`Invalid global search key "${key}"`);
+ }
+ }
+}
+
+function assertNewRouteId(
+ byId: ReadonlyMap<string, unknown>,
+ id: string
+): void {
+ if (!isSafeName(id)) {
+ throw new Error(`Invalid split route id "${id}"`);
+ }
+
+ if (byId.has(id)) {
+ throw new Error(`Duplicate split route id "${id}"`);
+ }
+}
+
+function claimSiblingPaths(
+ siblingPaths: string[],
+ definition: Pick<SplitRouteDefinition, 'path' | 'aliases'>
+): void {
+ const paths = [definition.path, ...(definition.aliases ?? [])];
+
+ for (const path of paths) {
+ const key = patternKey(path);
+ if (!key) throw new Error(`Invalid split route path "${path}"`);
+
+ if (siblingPaths.includes(key)) {
+ throw new Error(`Duplicate sibling split route path "${key}"`);
+ }
+
+ siblingPaths.push(key);
+ }
+}
+
+function createNode<TComponent>(
+ definition: SplitRouteDefinition<TComponent>,
+ parent: SplitRouteNode<TComponent> | undefined,
+ children: readonly SplitRouteNode<TComponent>[]
+): SplitRouteNode<TComponent> {
+ const branch: SplitRouteNode<TComponent>[] = [...(parent?.branch ?? [])];
+ const ownExternalSearch = definition.externalSearch ? [definition] : [];
+ const node: SplitRouteNode<TComponent> = {
+ definition,
+ parent,
+ branch,
+ children,
+ pattern: compileRoutePattern(definition),
+ params: createParamsCodec(definition as SplitRouteDefinition),
+ search: branchSearch(
+ parent as SplitRouteNode | undefined,
+ definition.search
+ ),
+ state: definition.state ?? parent?.state,
+ externalSearch: [...(parent?.externalSearch ?? []), ...ownExternalSearch],
+ };
+
+ branch.push(node);
+
+ return node;
+}
+
+function compileNodes<TComponent>(
+ byId: Map<string, SplitRouteNode<TComponent>>,
+ definitions: readonly SplitRouteDefinition<TComponent>[],
+ parent?: SplitRouteNode<TComponent>
+): SplitRouteNode<TComponent>[] {
+ const siblingPaths: string[] = [];
+
+ return definitions.map((definition) => {
+ assertNewRouteId(byId, definition.id);
+ claimSiblingPaths(siblingPaths, definition);
+
+ const children: SplitRouteNode<TComponent>[] = [];
+ const node = createNode(definition, parent, children);
+ byId.set(definition.id, node);
+ children.push(...compileNodes(byId, definition.children ?? [], node));
+
+ return node;
+ });
+}
+
+/** Compile static definitions into independent, caller-owned runtime state. */
+export function createRoutesManifest<TComponent>(
+ routes: SplitRoutes<TComponent>
+): SplitRoutesManifest<TComponent> {
+ const globalSearch = routes.globalSearch ?? [];
+ assertGlobalSearch(globalSearch);
+
+ const byId = new Map<string, SplitRouteNode<TComponent>>();
+ const roots = compileNodes(byId, routes.definitions);
+
+ return {
+ byId,
+ branches: compileBranches(roots),
+ globalSearch,
+ defaultRoute: routes.defaultRoute,
+ };
+}
+
+function matchBranch(
+ branch: RouteBranch,
+ segments: readonly string[]
+): SplitRouteState | undefined {
+ const matches: SplitRouteMatch[] = [];
+ let offset = 0;
+
+ for (const [depth, node] of branch.nodes.entries()) {
+ const raw = matchTokens(branch.patterns[depth]!, segments, offset);
+ if (!raw) return;
+
+ const params = node.params.parse(raw.params);
+ if (!params) return;
+
+ matches.push({ id: node.definition.id, params });
+ offset = raw.end;
+ }
+
+ const matchedEverySegment = offset === segments.length;
+ if (!matchedEverySegment) return;
+
+ return { matches: matches as [SplitRouteMatch, ...SplitRouteMatch[]] };
+}
+
+/** The most specific route for one pane's decoded segments. */
+export function decodePane(
+ routes: SplitRoutesManifest,
+ segments: readonly string[]
+): SplitRouteState | undefined {
+ if (segments.length === 0) return;
+
+ for (const branch of routes.branches) {
+ const route = matchBranch(branch, segments);
+ if (route) return route;
+ }
+}
+
+function isNonemptyBranch(value: unknown): value is { matches: unknown[] } {
+ if (!isRecord(value)) return false;
+ if (!Array.isArray(value.matches)) return false;
+
+ return value.matches.length > 0;
+}
+
+function isRouteMatch(value: unknown): value is SplitRouteMatch {
+ if (!isRecord(value)) return false;
+ if (typeof value.id !== 'string') return false;
+
+ return isRecord(value.params);
+}
+
+/** Validate host or persisted state without treating schema outputs as schema inputs. */
+function assertRouteState(
+ routes: SplitRoutesManifest,
+ route: unknown
+): asserts route is SplitRouteState {
+ if (!isNonemptyBranch(route)) {
+ throw new Error('Split route state requires a nonempty match branch');
+ }
+
+ let parent: SplitRouteNode | undefined;
+
+ for (const match of route.matches) {
+ if (!isRouteMatch(match)) {
+ throw new Error('Split route state contains an invalid match');
+ }
+
+ const node = routes.byId.get(match.id);
+ const continuesBranch = node !== undefined && node.parent === parent;
+
+ if (!continuesBranch) {
+ throw new Error('Split route state contains an invalid match branch');
+ }
+
+ parent = node;
+ }
+}
+
+function isBranchOf<TComponent>(
+ nodes: readonly SplitRouteNode<TComponent>[],
+ route: SplitRouteState
+): boolean {
+ if (nodes.length !== route.matches.length) return false;
+
+ return nodes.every(
+ (node, index) => node.definition.id === route.matches[index]!.id
+ );
+}
+
+function sameMatchIds(left: SplitRouteState, right: SplitRouteState): boolean {
+ if (left.matches.length !== right.matches.length) return false;
+
+ return left.matches.every(
+ (match, index) => match.id === right.matches[index]!.id
+ );
+}
+
+export function resolveBranch<TComponent>(
+ routes: SplitRoutesManifest<TComponent>,
+ route: SplitRouteState
+): readonly SplitRouteNode<TComponent>[] {
+ const leaf = route.matches[route.matches.length - 1]!;
+ const branch = routes.byId.get(leaf.id)?.branch ?? [];
+
+ if (!isBranchOf(branch, route)) {
+ throw new Error('Split route state contains an invalid match branch');
+ }
+
+ return branch;
+}
+
+/** The deepest node of a route: the one that owns search, state and external keys. */
+export function leafNode<TComponent>(
+ routes: SplitRoutesManifest<TComponent>,
+ route: SplitRouteState
+): SplitRouteNode<TComponent> {
+ const branch = resolveBranch(routes, route);
+
+ return branch[branch.length - 1]!;
+}
+
+export function defaultRoute(routes: SplitRoutesManifest): SplitRouteState {
+ const route = routes.defaultRoute();
+ assertRouteState(routes, route);
+
+ return route;
+}
+
+/** Decoded path segments of a pane, always using canonical paths. */
+export function formatPane(
+ routes: SplitRoutesManifest,
+ route: SplitRouteState
+): string[] {
+ const branch = resolveBranch(routes, route);
+
+ return branch.flatMap((node, index) => {
+ const params = node.params.serialize(route.matches[index]!.params);
+
+ return formatTokens(node.pattern.canonical, params);
+ });
+}
+
+/**
+ * Round-trip a route through its canonical path so schemas see raw inputs.
+ * Undefined when the path resolves to a different branch.
+ */
+export function canonicalRoute(
+ routes: SplitRoutesManifest,
+ route: SplitRouteState
+): SplitRouteState | undefined {
+ const segments = formatPane(routes, route);
+ const decoded = decodePane(routes, segments);
+ if (!decoded) return;
+ if (!sameMatchIds(decoded, route)) return;
+
+ return decoded;
+}
diff --git a/apps/web/src/lib/split-router/next/routes/path.ts b/apps/web/src/lib/split-router/next/routes/path.ts
new file mode 100644
index 0000000000..6ef48388e4
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/routes/path.ts
@@ -0,0 +1,275 @@
+import { match } from 'ts-pattern';
+import type { SplitRouteParams, SplitRouteRawParams } from './types';
+
+export type PathToken =
+ | { type: 'static'; value: string }
+ | { type: 'param'; name: string; optional: boolean }
+ | { type: 'catchAll'; name: string };
+
+type ParamToken = Extract<PathToken, { type: 'param' }>;
+
+export type RoutePattern = {
+ /** Tokens of the canonical path, used for formatting. */
+ canonical: readonly PathToken[];
+ /** Canonical path first, then aliases, with optional params expanded into concrete variants. */
+ alternatives: readonly (readonly PathToken[])[];
+};
+
+const PARAM_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;
+
+const FORMATTABLE_TYPES: readonly string[] = [
+ 'string',
+ 'number',
+ 'boolean',
+ 'bigint',
+];
+
+export const SPLIT_PATH_SEPARATOR = '~';
+
+export function splitSegments(path: string): string[] {
+ const trimmed = path.replace(/^\/+|\/+$/g, '');
+
+ return trimmed.split('/').filter(Boolean);
+}
+
+/** A malformed escape is kept as written, so it affects only its own pane. */
+export function decodeSegment(segment: string): string {
+ try {
+ return decodeURIComponent(segment);
+ } catch {
+ return segment;
+ }
+}
+
+function paramToken(segment: string): PathToken {
+ const optional = segment.endsWith('?');
+ const name = segment.slice(1, optional ? -1 : undefined);
+
+ if (!PARAM_NAME.test(name)) {
+ throw new Error(`Invalid split route parameter "${segment}"`);
+ }
+
+ return { type: 'param', name, optional };
+}
+
+function catchAllToken(segment: string): PathToken {
+ const name = segment.slice(1);
+
+ if (!PARAM_NAME.test(name)) {
+ throw new Error(`Invalid split route catch-all parameter "${segment}"`);
+ }
+
+ return { type: 'catchAll', name };
+}
+
+function segmentToken(segment: string, pattern: string): PathToken {
+ if (segment.startsWith(':')) return paramToken(segment);
+ if (segment.startsWith('*')) return catchAllToken(segment);
+
+ if (segment === SPLIT_PATH_SEPARATOR) {
+ throw new Error(`Invalid split route path "${pattern}"`);
+ }
+
+ return { type: 'static', value: segment };
+}
+
+function assertCatchAllLast(
+ tokens: readonly PathToken[],
+ pattern: string
+): void {
+ const catchAll = tokens.findIndex((token) => token.type === 'catchAll');
+ const misplaced = catchAll >= 0 && catchAll !== tokens.length - 1;
+
+ if (misplaced) {
+ throw new Error(
+ `Split route catch-all parameter must be the final segment in "${pattern}"`
+ );
+ }
+}
+
+function tokenize(pattern: string): PathToken[] {
+ const segments = splitSegments(pattern);
+ const tokens = segments.map((segment) => segmentToken(segment, pattern));
+
+ if (tokens.length === 0) {
+ throw new Error(`Invalid split route path "${pattern}"`);
+ }
+
+ assertCatchAllLast(tokens, pattern);
+
+ return tokens;
+}
+
+function optionalRun(tokens: readonly PathToken[], start: number): PathToken[] {
+ const run: PathToken[] = [];
+
+ for (const token of tokens.slice(start)) {
+ if (token.type !== 'param') break;
+ if (!token.optional) break;
+
+ run.push({ ...token, optional: false });
+ }
+
+ return run;
+}
+
+function appendPrefixes(
+ variants: readonly PathToken[][],
+ run: readonly PathToken[]
+): PathToken[][] {
+ const prefixes = run.map((_, count) => run.slice(0, count + 1));
+
+ return variants.flatMap((variant) => {
+ const extended = prefixes.map((prefix) => [...variant, ...prefix]);
+
+ return [variant, ...extended];
+ });
+}
+
+/** Adjacent optionals expand to prefixes only: `:a?/:b?` yields ``, `:a` and `:a/:b`. */
+function expandOptionals(tokens: readonly PathToken[]): PathToken[][] {
+ let variants: PathToken[][] = [[]];
+ let index = 0;
+
+ while (index < tokens.length) {
+ const run = optionalRun(tokens, index);
+
+ if (run.length > 0) {
+ variants = appendPrefixes(variants, run);
+ index += run.length;
+ continue;
+ }
+
+ const token = tokens[index]!;
+ variants = variants.map((variant) => [...variant, token]);
+ index += 1;
+ }
+
+ return variants;
+}
+
+export function compileRoutePattern(options: {
+ path: string;
+ aliases?: readonly string[];
+}): RoutePattern {
+ const canonical = tokenize(options.path);
+ const aliases = (options.aliases ?? []).map(tokenize);
+ const alternatives = [canonical, ...aliases].flatMap(expandOptionals);
+
+ return { canonical, alternatives };
+}
+
+/** Normalized pattern text, used to reject duplicate sibling paths. */
+export function patternKey(path: string): string {
+ return splitSegments(path).join('/');
+}
+
+function tokenScore(token: PathToken): number {
+ return match(token.type)
+ .with('static', () => 4)
+ .with('param', () => 3)
+ .with('catchAll', () => -1)
+ .exhaustive();
+}
+
+/** Static segments outrank params; a catch-all ranks below both. */
+export function specificity(tokens: readonly PathToken[]): number {
+ let score = 0;
+
+ for (const token of tokens) score += tokenScore(token);
+
+ return score;
+}
+
+function matchToken(
+ token: PathToken,
+ segments: readonly string[],
+ position: number,
+ params: SplitRouteRawParams
+): number | undefined {
+ if (token.type === 'catchAll') {
+ const rest = segments.slice(position);
+ if (rest.length === 0) return;
+
+ params[token.name] = rest;
+
+ return segments.length;
+ }
+
+ const segment = segments[position];
+ if (segment === undefined) return;
+
+ if (token.type === 'param') {
+ params[token.name] = segment;
+
+ return position + 1;
+ }
+
+ const sameSegment = segment.toLowerCase() === token.value.toLowerCase();
+ if (!sameSegment) return;
+
+ return position + 1;
+}
+
+/** Matches concrete (already expanded) tokens starting at `offset`. */
+export function matchTokens(
+ tokens: readonly PathToken[],
+ segments: readonly string[],
+ offset: number
+): { params: SplitRouteRawParams; end: number } | undefined {
+ const params: SplitRouteRawParams = {};
+ let position = offset;
+
+ for (const token of tokens) {
+ const next = matchToken(token, segments, position, params);
+ if (next === undefined) return;
+
+ position = next;
+ }
+
+ return { params, end: position };
+}
+
+function serializeValue(value: unknown, name: string): string {
+ const formattable = FORMATTABLE_TYPES.includes(typeof value);
+
+ if (!formattable) {
+ throw new Error(`Split route parameter "${name}" requires serializeParams`);
+ }
+
+ return String(value);
+}
+
+function formatCatchAll(name: string, value: unknown): string[] {
+ const items = Array.isArray(value) ? value : [];
+
+ if (items.length === 0) {
+ throw new Error(`Missing split route catch-all parameter "${name}"`);
+ }
+
+ return items.map((item) => serializeValue(item, name));
+}
+
+function formatParam(token: ParamToken, value: unknown): string[] {
+ if (value !== undefined) return [serializeValue(value, token.name)];
+ if (token.optional) return [];
+
+ throw new Error(`Missing split route parameter "${token.name}"`);
+}
+
+function formatToken(token: PathToken, params: SplitRouteParams): string[] {
+ return match(token)
+ .with({ type: 'static' }, ({ value }) => [value])
+ .with({ type: 'catchAll' }, ({ name }) =>
+ formatCatchAll(name, params[name])
+ )
+ .with({ type: 'param' }, (param) => formatParam(param, params[param.name]))
+ .exhaustive();
+}
+
+export function formatTokens(
+ tokens: readonly PathToken[],
+ params: SplitRouteParams
+): string[] {
+ return tokens.flatMap((token) => formatToken(token, params));
+}
diff --git a/apps/web/src/lib/split-router/next/routes/queries.ts b/apps/web/src/lib/split-router/next/routes/queries.ts
new file mode 100644
index 0000000000..de8ac59dfb
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/routes/queries.ts
@@ -0,0 +1,219 @@
+import { isSafeName } from '../utils';
+import { leafNode, resolveBranch, type SplitRoutesManifest } from './manifest';
+import type {
+ Entry,
+ InferSplitRouteState,
+ SplitRouteClaim,
+ SplitRouteDefinition,
+ SplitRouteParams,
+ SplitRouteState,
+ SplitSearchState,
+} from './types';
+
+/** Params of the first `depth` matches, with descendants overriding ancestors. */
+export function mergedParams(
+ route: SplitRouteState,
+ depth = route.matches.length
+): SplitRouteParams {
+ const params = route.matches.slice(0, depth).map((match) => match.params);
+
+ return Object.assign({}, ...params);
+}
+
+function claimKey(claim: SplitRouteClaim): string {
+ return `${claim.namespace}:${claim.id}`;
+}
+
+function assertValidClaim(claim: SplitRouteClaim): void {
+ const valid = isSafeName(claim.namespace) && claim.id.length > 0;
+
+ if (!valid) {
+ throw new Error('Split route returned an invalid claim');
+ }
+}
+
+/** The deepest claim along the branch; an undefined child claim falls back to ancestors. */
+export function claimOf(
+ routes: SplitRoutesManifest,
+ route: SplitRouteState
+): string | undefined {
+ const branch = resolveBranch(routes, route);
+ const params = mergedParams(route);
+
+ for (let index = branch.length - 1; index >= 0; index -= 1) {
+ const claim = branch[index]!.definition.claim?.(params);
+ if (!claim) continue;
+
+ assertValidClaim(claim);
+
+ return claimKey(claim);
+ }
+}
+
+type RouteStateResult = { success: true; value: unknown } | { success: false };
+
+export function parseRouteEntryState(
+ routes: SplitRoutesManifest,
+ route: SplitRouteState,
+ state: unknown
+): RouteStateResult {
+ if (state === undefined) return { success: true, value: undefined };
+
+ const schema = leafNode(routes, route).state;
+ if (!schema) return { success: false };
+
+ const result = schema['~standard'].validate(state);
+
+ if (result instanceof Promise) {
+ throw new Error('Split route state schemas must be synchronous');
+ }
+
+ if (result.issues) return { success: false };
+
+ return { success: true, value: result.value };
+}
+
+/** State of `entry` when `route` is part of its branch and shares its state schema. */
+export function getRouteEntryState<const TRoute extends { id: string }>(
+ routes: SplitRoutesManifest,
+ entry: Entry | undefined,
+ route: TRoute
+): InferSplitRouteState<TRoute> | undefined {
+ if (!entry) return;
+
+ const leaf = leafNode(routes, entry.location.route);
+ const requested = routes.byId.get(route.id);
+ if (!requested) return;
+
+ const sharesState =
+ leaf.branch.includes(requested) && requested.state === leaf.state;
+ if (!sharesState) return;
+
+ return entry.state as InferSplitRouteState<TRoute> | undefined;
+}
+
+export function ownsNamespace(
+ routes: SplitRoutesManifest,
+ route: SplitRouteState,
+ namespace: string
+): boolean {
+ const owned = leafNode(routes, route).search;
+
+ return owned === 'any' || owned.includes(namespace);
+}
+
+function pickNamespaces(
+ search: SplitSearchState,
+ namespaces: readonly string[]
+): SplitSearchState {
+ const kept = Object.entries(search).filter(([namespace]) =>
+ namespaces.includes(namespace)
+ );
+
+ return Object.fromEntries(kept);
+}
+
+export function filterRouteSearch(
+ routes: SplitRoutesManifest,
+ route: SplitRouteState,
+ search: SplitSearchState | undefined
+): SplitSearchState | undefined {
+ if (!search) return;
+
+ const owned = leafNode(routes, route).search;
+ const kept = owned === 'any' ? search : pickNamespaces(search, owned);
+ if (Object.keys(kept).length === 0) return;
+
+ return kept;
+}
+
+function definitionExternalKeys(
+ definition: SplitRouteDefinition,
+ entry: Entry
+): readonly string[] {
+ const externalSearch = definition.externalSearch;
+ if (typeof externalSearch === 'function') return externalSearch(entry);
+
+ return externalSearch ?? [];
+}
+
+function appendMissing(keys: string[], additions: readonly string[]): void {
+ for (const key of additions) {
+ if (!keys.includes(key)) keys.push(key);
+ }
+}
+
+/** Unprefixed query keys to keep: global keys plus those claimed by shown routes. */
+export function externalSearchKeys(
+ routes: SplitRoutesManifest,
+ entries: readonly Entry[]
+): string[] {
+ const keys = [...routes.globalSearch];
+
+ for (const entry of entries) {
+ const definitions = leafNode(routes, entry.location.route).externalSearch;
+
+ for (const definition of definitions) {
+ appendMissing(keys, definitionExternalKeys(definition, entry));
+ }
+ }
+
+ return keys;
+}
+
+/** Identity of the view mounted at each depth; a change remounts that depth and below. */
+function renderKeys(routes: SplitRoutesManifest, entry: Entry): string[] {
+ const route = entry.location.route;
+ const branch = resolveBranch(routes, route);
+
+ return branch.map((node, depth) => {
+ const params = route.matches[depth]!.params;
+ const context = { entryId: entry.id };
+ const remountKey = node.definition.remountKey?.(params, context);
+
+ return JSON.stringify([node.definition.id, remountKey ?? null]);
+ });
+}
+
+/** First depth whose view changes between two entries, or undefined when none does. */
+export function firstChangedDepth(
+ routes: SplitRoutesManifest,
+ from: Entry,
+ to: Entry | undefined
+): number | undefined {
+ if (!to) return 0;
+
+ const before = renderKeys(routes, from);
+ const after = renderKeys(routes, to);
+ const length = Math.max(before.length, after.length);
+
+ for (let depth = 0; depth < length; depth += 1) {
+ if (before[depth] !== after[depth]) return depth;
+ }
+}
+
+export type OutletMatch = {
+ component: unknown;
+ key: string;
+ /** Depth the next nested outlet starts from. */
+ depth: number;
+};
+
+/** The first component at or below `start` in the entry's branch. */
+export function outletAt(
+ routes: SplitRoutesManifest,
+ entry: Entry | undefined,
+ start: number
+): OutletMatch | undefined {
+ if (!entry) return;
+
+ const keys = renderKeys(routes, entry);
+ const branch = resolveBranch(routes, entry.location.route);
+
+ for (let depth = start; depth < branch.length; depth += 1) {
+ const component = branch[depth]!.definition.component;
+ if (typeof component !== 'function') continue;
+
+ return { component, key: keys[depth]!, depth: depth + 1 };
+ }
+}
diff --git a/apps/web/src/lib/split-router/next/routes/search-params.ts b/apps/web/src/lib/split-router/next/routes/search-params.ts
new file mode 100644
index 0000000000..a820ff3dd5
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/routes/search-params.ts
@@ -0,0 +1,169 @@
+import type { StandardSchemaV1 } from '@standard-schema/spec';
+import deepEqual from 'fast-deep-equal';
+import type { SerializedSearchParams } from './types';
+
+export type SearchParamsRecord = Record<string, unknown>;
+type SearchParamsSchema<T> = StandardSchemaV1<unknown, T>;
+type SearchParamsSerializer<T> = (
+ value: T,
+ context: { defaults: T }
+) => SerializedSearchParams | undefined;
+type SearchParamsDeserializer<T> = (
+ params: SerializedSearchParams
+) => Partial<T>;
+
+export type SearchParamsCodecOptions<T extends SearchParamsRecord> = {
+ schema: SearchParamsSchema<T>;
+ defaults: T;
+} & (
+ | { serialize?: never; deserialize?: never }
+ | {
+ serialize: SearchParamsSerializer<T>;
+ deserialize: SearchParamsDeserializer<T>;
+ }
+);
+
+type ValidationResult<T> =
+ | { success: true; data: T }
+ | { success: false; error: unknown };
+
+export type SearchParamsCodec<T> = {
+ parse(params: SerializedSearchParams | undefined): {
+ value: T;
+ valid: boolean;
+ };
+ serialize(value: T): SerializedSearchParams | undefined;
+ validate(value: unknown): ValidationResult<T>;
+};
+
+function deserializeField(
+ values: readonly string[],
+ fallback: unknown
+): unknown {
+ const last = values.at(-1);
+
+ if (Array.isArray(fallback)) {
+ const encodesEmpty = values.length === 1 && values[0] === '';
+
+ return encodesEmpty ? [] : [...values];
+ }
+
+ if (typeof fallback === 'number') return Number(last);
+ if (typeof fallback === 'boolean') return last === 'true';
+
+ return last;
+}
+
+function defaultDeserialize<T extends SearchParamsRecord>(
+ params: SerializedSearchParams | undefined,
+ defaults: T
+): Partial<T> {
+ if (!params) return {};
+
+ const result: SearchParamsRecord = {};
+
+ for (const key of Object.keys(defaults)) {
+ const values = params[key];
+ if (!values?.length) continue;
+
+ result[key] = deserializeField(values, defaults[key]);
+ }
+
+ return result as Partial<T>;
+}
+
+function serializeField(field: unknown): string[] {
+ if (!Array.isArray(field)) return [String(field)];
+ if (field.length === 0) return [''];
+
+ return field.map((item) => String(item));
+}
+
+function defaultSerialize<T extends SearchParamsRecord>(
+ value: T,
+ defaults: T
+): SerializedSearchParams | undefined {
+ const result: SerializedSearchParams = {};
+
+ for (const [key, field] of Object.entries(value)) {
+ const omitted = field === undefined || deepEqual(field, defaults[key]);
+ if (omitted) continue;
+
+ result[key] = serializeField(field);
+ }
+
+ return Object.keys(result).length > 0 ? result : undefined;
+}
+
+function validateSchema<T>(
+ schema: SearchParamsSchema<T>,
+ value: unknown
+): ValidationResult<T> {
+ const result = schema['~standard'].validate(value);
+
+ if (result instanceof Promise) {
+ throw new Error('Search parameter schemas must be synchronous');
+ }
+
+ if (result.issues) return { success: false, error: result.issues };
+
+ return { success: true, data: result.value };
+}
+
+function deserializeParams<T extends SearchParamsRecord>(
+ options: SearchParamsCodecOptions<T>,
+ params: SerializedSearchParams | undefined
+): Partial<T> {
+ if (options.deserialize) return options.deserialize(params ?? {});
+
+ return defaultDeserialize(params, options.defaults);
+}
+
+function copyParams(
+ params: SerializedSearchParams | undefined
+): SerializedSearchParams | undefined {
+ const entries = Object.entries(params ?? {}).map(
+ ([key, values]): [string, string[]] => [key, [...values]]
+ );
+ if (entries.length === 0) return;
+
+ return Object.fromEntries(entries);
+}
+
+export function createSearchParamsCodec<T extends SearchParamsRecord>(
+ options: SearchParamsCodecOptions<T>
+): SearchParamsCodec<T> {
+ function validate(value: unknown): ValidationResult<T> {
+ return validateSchema(options.schema, value);
+ }
+
+ if (!validate(options.defaults).success) {
+ throw new Error('Invalid defaults for search params');
+ }
+
+ return {
+ validate,
+
+ parse(params) {
+ try {
+ const decoded = deserializeParams(options, params);
+ const parsed = validate({ ...options.defaults, ...decoded });
+ if (parsed.success) return { value: parsed.data, valid: true };
+ } catch {
+ // Invalid inbound URL state falls back to defaults and is canonicalized.
+ }
+
+ return { value: options.defaults, valid: false };
+ },
+
+ serialize(value) {
+ if (deepEqual(value, options.defaults)) return;
+ if (!options.serialize) return defaultSerialize(value, options.defaults);
+
+ const params = options.serialize(value, { defaults: options.defaults });
+
+ // Keep the codec's result separate from mutable serializer state.
+ return copyParams(params);
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/routes/search.ts b/apps/web/src/lib/split-router/next/routes/search.ts
new file mode 100644
index 0000000000..4286c7fd81
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/routes/search.ts
@@ -0,0 +1,207 @@
+import { isSafeName } from '../utils';
+import type {
+ SerializedSearchParams,
+ SplitLocation,
+ SplitRouteState,
+ SplitSearchState,
+ SplitSearchUpdate,
+} from './types';
+
+const SPLIT_SEARCH_PREFIX = /^s\d+\./;
+const SPLIT_SEARCH_KEY =
+ /^s(\d+)\.([A-Za-z][A-Za-z0-9_-]*)\.([A-Za-z][A-Za-z0-9_-]*)$/;
+const MAX_SEARCH_VALUE_LENGTH = 16_384;
+
+type PaneSearchKey = { position: number; namespace: string; field: string };
+
+export function isSplitSearchKey(key: string): boolean {
+ return SPLIT_SEARCH_PREFIX.test(key);
+}
+
+export function assertSafeSearchName(
+ value: string,
+ kind: 'namespace' | 'field'
+): void {
+ if (!isSafeName(value)) {
+ throw new Error(`Invalid split search ${kind} "${value}"`);
+ }
+}
+
+function hasKeys(record: object): boolean {
+ return Object.keys(record).length > 0;
+}
+
+function ownValue<T>(record: Record<string, T>, key: string): T | undefined {
+ return Object.hasOwn(record, key) ? record[key] : undefined;
+}
+
+function parsePaneSearchKey(key: string): PaneSearchKey | undefined {
+ const match = SPLIT_SEARCH_KEY.exec(key);
+ if (!match) return;
+
+ const position = Number(match[1]);
+ const namespace = match[2]!;
+ const field = match[3]!;
+ const safe =
+ Number.isSafeInteger(position) &&
+ isSafeName(namespace) &&
+ isSafeName(field);
+ if (!safe) return;
+
+ return { position, namespace, field };
+}
+
+function appendPaneValue(
+ panes: (SplitSearchState | undefined)[],
+ { position, namespace, field }: PaneSearchKey,
+ value: string
+): void {
+ const namespaces = panes[position] ?? {};
+ const fields = ownValue(namespaces, namespace) ?? {};
+ const values = ownValue(fields, field) ?? [];
+
+ fields[field] = [...values, value];
+ namespaces[namespace] = fields;
+ panes[position] = namespaces;
+}
+
+/** Pane search indexed by pane position, from `s{i}.{namespace}.{field}` keys. */
+export function parsePaneSearch(
+ value: string
+): (SplitSearchState | undefined)[] {
+ const panes: (SplitSearchState | undefined)[] = [];
+
+ for (const [key, fieldValue] of new URLSearchParams(value)) {
+ const parsed = parsePaneSearchKey(key);
+ if (!parsed) continue;
+ if (fieldValue.length > MAX_SEARCH_VALUE_LENGTH) continue;
+
+ appendPaneValue(panes, parsed, fieldValue);
+ }
+
+ return panes;
+}
+
+/** A search value too long for the URL; callers refuse the navigation rather than fail. */
+export class SearchValueTooLongError extends Error {
+ constructor(field: string) {
+ super(`Split search value for "${field}" is too long`);
+ this.name = 'SearchValueTooLongError';
+ }
+}
+
+function assertSearchValueLength(field: string, value: string): void {
+ if (value.length > MAX_SEARCH_VALUE_LENGTH) {
+ throw new SearchValueTooLongError(field);
+ }
+}
+
+function appendNamespaceParams(
+ query: URLSearchParams,
+ prefix: string,
+ params: SerializedSearchParams
+): void {
+ for (const field of Object.keys(params).sort()) {
+ assertSafeSearchName(field, 'field');
+
+ for (const value of params[field] ?? []) {
+ query.append(`${prefix}.${field}`, value);
+ }
+ }
+}
+
+function appendPaneSearch(
+ query: URLSearchParams,
+ search: SplitSearchState,
+ position: number
+): void {
+ for (const namespace of Object.keys(search).sort()) {
+ assertSafeSearchName(namespace, 'namespace');
+
+ const params = search[namespace];
+ if (!params) continue;
+
+ appendNamespaceParams(query, `s${position}.${namespace}`, params);
+ }
+}
+
+/** Replaces pane-owned keys in the query and keeps every other key. */
+export function replacePaneSearchParams(
+ query: URLSearchParams,
+ panes: readonly (SplitSearchState | undefined)[]
+): void {
+ for (const key of [...query.keys()]) {
+ if (isSplitSearchKey(key)) query.delete(key);
+ }
+
+ panes.forEach((search, position) => {
+ if (search) appendPaneSearch(query, search, position);
+ });
+}
+
+function normalizeSearchParams(
+ params: SerializedSearchParams | undefined
+): SerializedSearchParams | undefined {
+ if (!params) return;
+
+ const result: SerializedSearchParams = {};
+
+ for (const field of Object.keys(params).sort()) {
+ assertSafeSearchName(field, 'field');
+
+ const values = params[field] ?? [];
+ for (const value of values) {
+ assertSearchValueLength(field, value);
+ }
+
+ if (values.length > 0) result[field] = [...values];
+ }
+
+ return hasKeys(result) ? result : undefined;
+}
+
+function withSearchNamespace(
+ current: SplitLocation,
+ namespace: string,
+ params: SerializedSearchParams | undefined
+): SplitLocation {
+ const search = { ...(current.search ?? {}) };
+ const hasParams = params !== undefined && hasKeys(params);
+
+ if (hasParams) {
+ search[namespace] = params;
+ } else {
+ delete search[namespace];
+ }
+
+ return locationOf(current.route, hasKeys(search) ? search : undefined);
+}
+
+/** A location that carries `search` only when there is some. */
+export function locationOf(
+ route: SplitRouteState,
+ search: SplitSearchState | undefined
+): SplitLocation {
+ if (!search) return { route };
+
+ return { route, search };
+}
+
+export function updateSearchState(
+ location: SplitLocation,
+ updates: Readonly<Record<string, SplitSearchUpdate>> | undefined
+): SplitLocation {
+ let next = location;
+
+ for (const [namespace, update] of Object.entries(updates ?? {})) {
+ assertSafeSearchName(namespace, 'namespace');
+
+ const current = ownValue(next.search ?? {}, namespace);
+ const requested = typeof update === 'function' ? update(current) : update;
+ const params = normalizeSearchParams(requested);
+
+ next = withSearchNamespace(next, namespace, params);
+ }
+
+ return next;
+}
diff --git a/apps/web/src/lib/split-router/next/routes/targets.ts b/apps/web/src/lib/split-router/next/routes/targets.ts
new file mode 100644
index 0000000000..8525bc1ed2
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/routes/targets.ts
@@ -0,0 +1,190 @@
+import { isRecord } from '../utils';
+import {
+ canonicalRoute,
+ decodePane,
+ formatPane,
+ type SplitRoutesManifest,
+} from './manifest';
+import { decodeSegment } from './path';
+import { filterRouteSearch } from './queries';
+import { locationOf, parsePaneSearch, updateSearchState } from './search';
+import type {
+ SplitLocation,
+ SplitNavigationTarget,
+ SplitRouteMatch,
+ SplitRouteParams,
+ SplitRouteState,
+ SplitSearchState,
+ SplitSearchUpdate,
+} from './types';
+
+type ResolveTargetOptions = {
+ /**
+ * Leading matches that belong to the calling route. Relative paths resolve
+ * against their path; defaults to the whole current branch.
+ */
+ depth?: number;
+ search?: Readonly<Record<string, SplitSearchUpdate>>;
+};
+
+type ResolvedRoute = { route: SplitRouteState; search?: SplitSearchState };
+
+function splitTarget(to: string): { path: string; search: string } {
+ const hash = to.indexOf('#');
+ const withoutHash = hash >= 0 ? to.slice(0, hash) : to;
+ const query = withoutHash.indexOf('?');
+ if (query < 0) return { path: withoutHash, search: '' };
+
+ return {
+ path: withoutHash.slice(0, query),
+ search: withoutHash.slice(query),
+ };
+}
+
+function routeState(matches: readonly SplitRouteMatch[]): SplitRouteState {
+ const [first, ...rest] = matches;
+
+ return { matches: [first!, ...rest] };
+}
+
+function formatMatches(
+ routes: SplitRoutesManifest,
+ matches: readonly SplitRouteMatch[]
+): string[] {
+ if (matches.length === 0) return [];
+
+ return formatPane(routes, routeState(matches));
+}
+
+function baseSegments(
+ routes: SplitRoutesManifest,
+ current: SplitLocation | undefined,
+ depth: number | undefined
+): string[] {
+ if (!current) return [];
+
+ const matches = current.route.matches;
+
+ return formatMatches(routes, matches.slice(0, depth ?? matches.length));
+}
+
+function walkPath(base: readonly string[], path: string): string[] {
+ const segments = [...base];
+
+ for (const part of path.split('/')) {
+ const ignored = part === '' || part === '.';
+ if (ignored) continue;
+
+ if (part === '..') {
+ segments.pop();
+ continue;
+ }
+
+ segments.push(decodeSegment(part));
+ }
+
+ return segments;
+}
+
+function resolvePath(
+ routes: SplitRoutesManifest,
+ current: SplitLocation | undefined,
+ to: string,
+ depth: number | undefined
+): ResolvedRoute | undefined {
+ const target = splitTarget(to);
+ const absolute = target.path.startsWith('/');
+ const base = absolute ? [] : baseSegments(routes, current, depth);
+ const segments = walkPath(base, target.path);
+ const route = decodePane(routes, segments);
+ if (!route) return;
+
+ return { route, search: parsePaneSearch(target.search)[0] };
+}
+
+function canonicalTarget(
+ routes: SplitRoutesManifest,
+ matches: readonly SplitRouteMatch[]
+): ResolvedRoute | undefined {
+ const route = canonicalRoute(routes, routeState(matches));
+ if (!route) return;
+
+ return { route };
+}
+
+function inheritedParams(
+ match: SplitRouteMatch | undefined,
+ id: string
+): SplitRouteParams {
+ if (match?.id !== id) return {};
+
+ return match.params;
+}
+
+function resolveRoute(
+ routes: SplitRoutesManifest,
+ current: SplitLocation | undefined,
+ to: { route: { id: string }; params?: unknown }
+): ResolvedRoute | undefined {
+ const node = routes.byId.get(to.route.id);
+ if (!node) return;
+
+ const explicit = isRecord(to.params) ? to.params : {};
+ const currentMatches = current?.route.matches ?? [];
+ const matches = node.branch.map((ancestor, index): SplitRouteMatch => {
+ const id = ancestor.definition.id;
+ const inherited = inheritedParams(currentMatches[index], id);
+
+ // Explicit params override inherited values at every level before each
+ // node serializes the fields it owns.
+ return { id, params: { ...inherited, ...explicit } };
+ });
+
+ return canonicalTarget(routes, matches);
+}
+
+function resolveDestination(
+ routes: SplitRoutesManifest,
+ current: SplitLocation | undefined,
+ to: SplitNavigationTarget,
+ depth: number | undefined
+): ResolvedRoute | undefined {
+ if (typeof to === 'string') return resolvePath(routes, current, to, depth);
+ if (!('route' in to)) return;
+
+ return resolveRoute(routes, current, to);
+}
+
+function carriedSearch(
+ current: SplitLocation | undefined,
+ resolved: ResolvedRoute
+): SplitSearchState | undefined {
+ if (resolved.search !== undefined) return resolved.search;
+ if (!current) return;
+
+ const sameRoot = current.route.matches[0].id === resolved.route.matches[0].id;
+ if (!sameRoot) return;
+
+ return current.search;
+}
+
+/**
+ * Resolves a target within one pane. Search carries over only while the root
+ * route stays the same, and namespaces the destination doesn't own are dropped.
+ */
+export function resolveTarget(
+ routes: SplitRoutesManifest,
+ current: SplitLocation | undefined,
+ to: SplitNavigationTarget,
+ options: ResolveTargetOptions = {}
+): SplitLocation | undefined {
+ const resolved = resolveDestination(routes, current, to, options.depth);
+ if (!resolved) return;
+
+ const search = carriedSearch(current, resolved);
+ const start = locationOf(resolved.route, search);
+ const updated = updateSearchState(start, options.search);
+ const owned = filterRouteSearch(routes, updated.route, updated.search);
+
+ return locationOf(updated.route, owned);
+}
diff --git a/apps/web/src/lib/split-router/next/routes/types.ts b/apps/web/src/lib/split-router/next/routes/types.ts
new file mode 100644
index 0000000000..d222b4ab1b
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/routes/types.ts
@@ -0,0 +1,380 @@
+import type { StandardSchemaV1 } from '@standard-schema/spec';
+import type { PaneArrival, PaneId } from '../panes/types';
+
+export type { PaneArrival, PaneId };
+
+export type SplitRouteParams = Record<string, unknown>;
+export type SplitRouteRawParams = Record<string, string | string[] | undefined>;
+export type SerializedSearchParams = Record<string, string[]>;
+export type SplitSearchState = Record<string, SerializedSearchParams>;
+
+export type SplitSearchUpdate =
+ | SerializedSearchParams
+ | undefined
+ | ((
+ current: SerializedSearchParams | undefined
+ ) => SerializedSearchParams | undefined);
+
+export type SplitRouteMatch = {
+ id: string;
+ params: SplitRouteParams;
+};
+
+export type SplitRouteState = {
+ matches: readonly [SplitRouteMatch, ...SplitRouteMatch[]];
+};
+
+export type SplitLocation = {
+ route: SplitRouteState;
+ search?: SplitSearchState;
+};
+
+export type Entry = {
+ id: string;
+ location: SplitLocation;
+ /** Output of the route's state schema; round-trips through browser history state. */
+ state?: unknown;
+ /** In-memory props for the view this entry opens; never serialized. */
+ props?: unknown;
+ /** Deliver `props` again when returning to this entry, instead of dropping them. */
+ keepProps?: boolean;
+ /** App metadata such as how the entry was reached; memory only. */
+ meta?: Readonly<Record<string, unknown>>;
+};
+
+export type PreloadIntent = 'initial' | 'navigate' | 'external' | 'hover';
+
+export type WriteMode = 'push' | 'replace';
+
+export type SplitRouteClaim = {
+ namespace: string;
+ id: string;
+};
+
+/** Route metadata. Hosts extend this interface through declaration merging. */
+export interface SplitRouteInfo {
+ readonly [key: string]: unknown;
+}
+
+/** The split router's slice of browser history state. */
+export type SplitHistoryState = {
+ panes: readonly SplitHistoryPane[];
+};
+
+export type SplitHistoryPane = {
+ pane: PaneId;
+ entry: string;
+ state?: unknown;
+};
+
+/** Everything below the split router's mount point. */
+export type ExternalLocation = {
+ path: string;
+ search: string;
+ hash: string;
+ state?: SplitHistoryState;
+};
+
+type SplitRouteParamCallback<TParams, TResult> = {
+ bivarianceHack(params: TParams): TResult;
+}['bivarianceHack'];
+
+export type SplitRouteRemountContext = {
+ entryId: string;
+};
+
+export type SplitRoutePreloadContext<TParams = SplitRouteParams> = {
+ params: TParams;
+ search: SplitSearchState | undefined;
+ intent: PreloadIntent;
+ signal: AbortSignal;
+};
+
+export type SplitRouteDefinition<
+ TComponent = unknown,
+ TParamsSchema extends StandardSchemaV1 = StandardSchemaV1<
+ unknown,
+ SplitRouteParams
+ >,
+> = {
+ id: string;
+ path: string;
+ aliases?: readonly string[];
+ component?: TComponent;
+ children?: readonly SplitRouteDefinition<TComponent>[];
+ params?: TParamsSchema;
+ state?: StandardSchemaV1;
+ serializeParams?: SplitRouteParamCallback<
+ StandardSchemaV1.InferOutput<TParamsSchema>,
+ SplitRouteRawParams
+ >;
+ claim?: SplitRouteParamCallback<
+ StandardSchemaV1.InferOutput<TParamsSchema>,
+ SplitRouteClaim | undefined
+ >;
+ /**
+ * Pane search namespaces this route adds. Leaving it undefined adds no
+ * restriction; a root route without `search` owns every namespace.
+ */
+ search?: readonly string[];
+ /** Unprefixed query keys kept in the URL while this route is shown. */
+ externalSearch?:
+ | readonly string[]
+ | ((entry: Readonly<Entry>) => readonly string[]);
+ remountKey?: {
+ bivarianceHack(
+ params: StandardSchemaV1.InferOutput<TParamsSchema>,
+ context: SplitRouteRemountContext
+ ): string | number | undefined;
+ }['bivarianceHack'];
+ preload?: SplitRouteParamCallback<
+ SplitRoutePreloadContext<StandardSchemaV1.InferOutput<TParamsSchema>>,
+ void | Promise<unknown>
+ >;
+ info?: SplitRouteInfo;
+};
+
+/** Static route declarations. Do not mutate them during a router's lifetime. */
+export type SplitRoutes<TComponent = unknown> = {
+ definitions: readonly SplitRouteDefinition<TComponent>[];
+ defaultRoute: () => SplitRouteState;
+ globalSearch?: readonly string[];
+};
+
+type PathSegmentParams<TSegment extends string> =
+ TSegment extends `:${infer TName}?`
+ ? { [K in TName]?: string }
+ : TSegment extends `:${infer TName}`
+ ? { [K in TName]: string }
+ : TSegment extends `*${infer TName}`
+ ? { [K in TName]: string[] }
+ : {};
+
+type PathParams<TPath extends string> = TPath extends unknown
+ ? string extends TPath
+ ? SplitRouteParams
+ : TPath extends `${infer TSegment}/${infer TRest}`
+ ? PathSegmentParams<TSegment> & PathParams<TRest>
+ : PathSegmentParams<TPath>
+ : never;
+
+/** Raw parameters produced by a route's canonical path and aliases. */
+export type InferSplitRoutePathParams<
+ TPath extends string,
+ TAliases extends readonly string[] | undefined = undefined,
+> = PathParams<
+ TPath | (TAliases extends readonly string[] ? TAliases[number] : never)
+>;
+
+type Simplify<T> = { [K in keyof T]: T[K] };
+
+type RequiredParamKeys<T> = {
+ [K in keyof T]-?: {} extends Pick<T, K> ? never : K;
+}[keyof T];
+
+type MergedParam<
+ TParent,
+ TLocal,
+ K extends PropertyKey,
+> = K extends keyof TLocal
+ ? {} extends Pick<TLocal, K>
+ ? K extends keyof TParent
+ ? TParent[K] | TLocal[K]
+ : TLocal[K]
+ : TLocal[K]
+ : K extends keyof TParent
+ ? TParent[K]
+ : never;
+
+// Object.assign retains the parent value when an optional child field is absent.
+type MergeRouteParams<TParent, TLocal> = TParent extends unknown
+ ? TLocal extends unknown
+ ? Simplify<
+ {
+ [K in
+ | RequiredParamKeys<TParent>
+ | RequiredParamKeys<TLocal>]: MergedParam<TParent, TLocal, K>;
+ } & {
+ [K in Exclude<
+ keyof TParent | keyof TLocal,
+ RequiredParamKeys<TParent> | RequiredParamKeys<TLocal>
+ >]?: MergedParam<TParent, TLocal, K>;
+ }
+ >
+ : never
+ : never;
+
+/** The schema output (or raw path params) owned by this node alone. */
+export type InferSplitRouteParams<TRoute> = TRoute extends {
+ params: infer TSchema extends StandardSchemaV1;
+}
+ ? StandardSchemaV1.InferOutput<TSchema>
+ : TRoute extends { path: infer TPath extends string }
+ ? MergeRouteParams<
+ {},
+ InferSplitRoutePathParams<
+ TPath,
+ TRoute extends { aliases: infer TAliases }
+ ? Extract<TAliases, readonly string[]>
+ : undefined
+ >
+ >
+ : SplitRouteParams;
+
+type LocalNavigationParams<TRoute> = TRoute extends { params: StandardSchemaV1 }
+ ? InferSplitRouteParams<TRoute>
+ : TRoute extends { path: infer TPath extends string }
+ ? MergeRouteParams<{}, PathParams<TPath>>
+ : SplitRouteParams;
+
+// Type-only ancestry. Declaration helpers never add properties to supplied objects.
+declare const branchParams: unique symbol;
+
+type LocalRouteStateSchema<TRoute> = TRoute extends {
+ state: infer TSchema extends StandardSchemaV1;
+}
+ ? TSchema
+ : undefined;
+
+type EffectiveRouteStateSchema<TRoute, TParentSchema> =
+ LocalRouteStateSchema<TRoute> extends StandardSchemaV1
+ ? LocalRouteStateSchema<TRoute>
+ : TParentSchema;
+
+type InferSplitRouteStateSchema<TRoute> = TRoute extends {
+ readonly [branchParams]: { state: infer TSchema };
+}
+ ? TSchema
+ : LocalRouteStateSchema<TRoute>;
+
+export type InferSplitRouteState<TRoute> =
+ InferSplitRouteStateSchema<TRoute> extends infer TSchema extends
+ StandardSchemaV1
+ ? StandardSchemaV1.InferOutput<TSchema>
+ : never;
+
+export type InferSplitRouteStateInput<TRoute> =
+ InferSplitRouteStateSchema<TRoute> extends infer TSchema extends
+ StandardSchemaV1
+ ? StandardSchemaV1.InferInput<TSchema>
+ : never;
+
+/** Params accumulated through this node, with child fields overriding ancestors. */
+export type InferSplitRouteBranchParams<TRoute> = TRoute extends {
+ readonly [branchParams]: { read: infer TParams };
+}
+ ? TParams
+ : InferSplitRouteParams<TRoute>;
+
+/** A flat destination bag must satisfy every ancestor's serializer. */
+export type InferSplitRouteNavigationParams<TRoute> = TRoute extends {
+ readonly [branchParams]: { navigate: infer TParams };
+}
+ ? TParams
+ : LocalNavigationParams<TRoute>;
+
+// Empty object schemas can infer an index signature of never. It must not
+// prohibit the fields supplied by other nodes in the same branch.
+type BranchParams<TParams> =
+ TParams extends Record<string, never>
+ ? {
+ [K in keyof TParams as string extends K
+ ? never
+ : number extends K
+ ? never
+ : K]: TParams[K];
+ }
+ : TParams;
+
+type DefinedRoute<TRoute, TParent, TParentNavigation, TParentStateSchema> =
+ TRoute extends unknown
+ ? Omit<TRoute, 'children' | typeof branchParams> & {
+ readonly [branchParams]: {
+ read: MergeRouteParams<
+ TParent,
+ BranchParams<InferSplitRouteParams<TRoute>>
+ >;
+ navigate: MergeRouteParams<
+ {},
+ TParentNavigation & BranchParams<LocalNavigationParams<TRoute>>
+ >;
+ state: EffectiveRouteStateSchema<TRoute, TParentStateSchema>;
+ };
+ } & (TRoute extends {
+ children: infer TChildren extends readonly unknown[];
+ }
+ ? {
+ readonly children: DefinedRouteList<
+ TChildren,
+ MergeRouteParams<
+ TParent,
+ BranchParams<InferSplitRouteParams<TRoute>>
+ >,
+ TParentNavigation & BranchParams<LocalNavigationParams<TRoute>>,
+ EffectiveRouteStateSchema<TRoute, TParentStateSchema>
+ >;
+ }
+ : Pick<TRoute, Extract<keyof TRoute, 'children'>>)
+ : never;
+
+type DefinedRouteList<
+ TDefinitions extends readonly unknown[],
+ TParent,
+ TParentNavigation,
+ TParentStateSchema,
+> = {
+ [K in keyof TDefinitions]: DefinedRoute<
+ TDefinitions[K],
+ TParent,
+ TParentNavigation,
+ TParentStateSchema
+ >;
+};
+
+/** One original definition with descendant ancestry inferred from this root. */
+export type DefinedSplitRoute<TRoute> = DefinedRoute<TRoute, {}, {}, undefined>;
+
+/** The original static tree, with ancestry available on references from that tree. */
+export type DefinedSplitRoutes<
+ TRoutes extends { definitions: readonly unknown[] },
+> = Omit<TRoutes, 'definitions'> & {
+ readonly definitions: DefinedRouteList<
+ TRoutes['definitions'],
+ {},
+ {},
+ undefined
+ >;
+};
+
+type RouteUnion<TRoute> = TRoute extends { children: readonly (infer TChild)[] }
+ ? TRoute | RouteUnion<TChild>
+ : TRoute;
+
+export type SplitRouteUnion<TRoutes extends SplitRoutes> = RouteUnion<
+ TRoutes['definitions'][number]
+>;
+
+export type SplitRouteReference = {
+ id: string;
+ params?: StandardSchemaV1;
+ state?: StandardSchemaV1;
+};
+
+type SplitRouteTargetParams<TRoute extends SplitRouteReference> =
+ {} extends InferSplitRouteNavigationParams<TRoute>
+ ? { params?: InferSplitRouteNavigationParams<TRoute> }
+ : { params: InferSplitRouteNavigationParams<TRoute> };
+
+export type SplitRouteNavigationTarget<
+ TRoute extends SplitRouteReference = SplitRouteReference,
+> = TRoute extends unknown
+ ? { route: TRoute } & SplitRouteTargetParams<NoInfer<TRoute>>
+ : never;
+
+export type SplitNavigationTarget =
+ | string
+ | { route: { id: string }; params?: unknown };
+
+export type SplitRouterStateUpdate<TInput = unknown, TOutput = TInput> =
+ | TInput
+ | ((current: TOutput | undefined) => TInput);
diff --git a/apps/web/src/lib/split-router/next/solid/context.tsx b/apps/web/src/lib/split-router/next/solid/context.tsx
new file mode 100644
index 0000000000..2f3fc34d42
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/solid/context.tsx
@@ -0,0 +1,51 @@
+import {
+ type Accessor,
+ createContext,
+ type ParentProps,
+ useContext,
+} from 'solid-js';
+import type { SplitRouter } from '../router/create-router';
+import type { Entry, PaneId } from '../routes/types';
+
+const SplitRouterContext = createContext<SplitRouter>();
+
+export function SplitRouterProvider(
+ props: ParentProps<{ router: SplitRouter }>
+) {
+ return (
+ <SplitRouterContext.Provider value={props.router}>
+ {props.children}
+ </SplitRouterContext.Provider>
+ );
+}
+
+export function useSplitRouter(): SplitRouter {
+ const router = useContext(SplitRouterContext);
+
+ if (!router) {
+ throw new Error('useSplitRouter must be used inside <SplitRouterProvider>');
+ }
+
+ return router;
+}
+
+export type PaneContextValue = {
+ pane: Accessor<PaneId>;
+ entry: Accessor<Entry | undefined>;
+ /** Leading matches that belong to the route rendering this subtree. */
+ depth: Accessor<number>;
+};
+
+export const PaneContext = createContext<PaneContextValue>();
+
+export function usePaneContext(): PaneContextValue {
+ const scope = useContext(PaneContext);
+
+ if (!scope) {
+ throw new Error(
+ 'Split router hooks must be used inside a <PaneScope> or an <Outlet pane>'
+ );
+ }
+
+ return scope;
+}
diff --git a/apps/web/src/lib/split-router/next/solid/create-search-params.ts b/apps/web/src/lib/split-router/next/solid/create-search-params.ts
new file mode 100644
index 0000000000..a9f4f53a2c
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/solid/create-search-params.ts
@@ -0,0 +1,101 @@
+import deepEqual from 'fast-deep-equal';
+import { createEffect, createMemo, on } from 'solid-js';
+import {
+ createSearchParamsCodec,
+ type SearchParamsCodecOptions,
+ type SearchParamsRecord,
+} from '../routes/search-params';
+import type { SerializedSearchParams, WriteMode } from '../routes/types';
+import { usePaneContext, useSplitRouter } from './context';
+import { createMemoRecord } from './memo-record';
+
+export type CreateSearchParamsOptions<T extends SearchParamsRecord> =
+ SearchParamsCodecOptions<T> & { namespace: string };
+
+type SetSearchParamsOptions = {
+ mode?: 'merge' | 'replace';
+ history?: WriteMode;
+};
+
+type SearchParamsPatch<T extends SearchParamsRecord> = {
+ [Key in keyof T]?: T[Key] | undefined;
+};
+
+export type SetSearchParams<T extends SearchParamsRecord> = (
+ next: SearchParamsPatch<T> | ((current: T) => SearchParamsPatch<T>),
+ options?: SetSearchParamsOptions
+) => void;
+
+/** Typed access to one search namespace of the current pane. */
+export function createSearchParams<T extends SearchParamsRecord>(
+ options: CreateSearchParamsOptions<T>
+): [T, SetSearchParams<T>] {
+ const router = useSplitRouter();
+ const scope = usePaneContext();
+ const codec = createSearchParamsCodec(options);
+
+ const namespaceParams = () => {
+ const search = scope.entry()?.location.search;
+ if (!search) return;
+ if (!Object.hasOwn(search, options.namespace)) return;
+
+ return search[options.namespace];
+ };
+
+ // Other namespaces, params and state change the entry too; only this namespace matters here.
+ const raw = createMemo(namespaceParams, undefined, { equals: deepEqual });
+
+ const parsed = createMemo(() => codec.parse(raw()));
+
+ const writeSearch = (
+ params: SerializedSearchParams | undefined,
+ history: WriteMode | undefined
+ ) =>
+ router.updateSearch(scope.pane(), options.namespace, params, { history });
+
+ const patched = (
+ start: SearchParamsRecord,
+ patch: SearchParamsPatch<T>
+ ): SearchParamsRecord => {
+ const candidate: SearchParamsRecord = { ...start };
+
+ for (const [key, value] of Object.entries(patch)) {
+ candidate[key] = value === undefined ? options.defaults[key] : value;
+ }
+
+ return candidate;
+ };
+
+ // The URL is an external system: invalid or non-canonical values are rewritten in place.
+ createEffect(
+ on([parsed, raw], ([current, rawParams]) => {
+ const canonical = current.valid
+ ? codec.serialize(current.value)
+ : undefined;
+ const alreadyCanonical = deepEqual(rawParams, canonical);
+ if (alreadyCanonical) return;
+
+ void writeSearch(canonical, 'replace');
+ })
+ );
+
+ const setParams: SetSearchParams<T> = (next, setOptions = {}) => {
+ const previous = parsed().value;
+ const patch = typeof next === 'function' ? next(previous) : next;
+ const replacing = setOptions.mode === 'replace';
+ const start = replacing ? options.defaults : previous;
+ const nextValue = codec.validate(patched(start, patch));
+
+ if (!nextValue.success) {
+ console.error(
+ `Invalid search params for namespace "${options.namespace}"`,
+ nextValue.error
+ );
+ return;
+ }
+
+ void writeSearch(codec.serialize(nextValue.data), setOptions.history);
+ };
+
+ return [createMemoRecord(() => parsed().value), setParams];
+}
diff --git a/apps/web/src/lib/split-router/next/solid/hooks.ts b/apps/web/src/lib/split-router/next/solid/hooks.ts
new file mode 100644
index 0000000000..872a91ce72
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/solid/hooks.ts
@@ -0,0 +1,170 @@
+import deepEqual from 'fast-deep-equal';
+import { type Accessor, createMemo, untrack, useContext } from 'solid-js';
+import type { PendingNavigation } from '../router/runner';
+import type {
+ NavigationResult,
+ RouteMatchInfo,
+ SplitNavigateOptions,
+} from '../router/types';
+import { getRouteEntryState, mergedParams } from '../routes/queries';
+import type {
+ InferSplitRouteBranchParams,
+ InferSplitRouteParams,
+ InferSplitRouteState,
+ InferSplitRouteStateInput,
+ PaneArrival,
+ PaneId,
+ SplitNavigationTarget,
+ SplitRouteNavigationTarget,
+ SplitRouteParams,
+ SplitRouteReference,
+ SplitRouterStateUpdate,
+ SplitRouteState,
+} from '../routes/types';
+import type { MaybePromise } from '../utils';
+import { PaneContext, usePaneContext, useSplitRouter } from './context';
+import { createMemoRecord } from './memo-record';
+
+export type SplitRouteNavigateOptions<TRoute> = Omit<
+ SplitNavigateOptions,
+ 'state' | 'depth'
+> &
+ ([InferSplitRouteStateInput<TRoute>] extends [never]
+ ? { state?: never }
+ : {
+ state?: SplitRouterStateUpdate<
+ InferSplitRouteStateInput<TRoute>,
+ InferSplitRouteState<TRoute>
+ >;
+ });
+
+export type SplitNavigate = {
+ <const TTarget extends { route: SplitRouteReference }>(
+ to: TTarget & SplitRouteNavigationTarget<NoInfer<TTarget['route']>>,
+ options?: SplitRouteNavigateOptions<TTarget['route']>
+ ): MaybePromise<NavigationResult>;
+ (
+ to: string | number,
+ options?: Omit<SplitNavigateOptions, 'depth'>
+ ): MaybePromise<NavigationResult>;
+};
+
+function depthThrough(
+ route: SplitRouteState,
+ through: { id: string } | undefined
+): number | undefined {
+ if (!through) return;
+
+ const index = route.matches.findIndex((match) => match.id === through.id);
+
+ return index + 1;
+}
+
+export function usePane(): Accessor<PaneId> {
+ return usePaneContext().pane;
+}
+
+/** Params merged through `route`, or through the whole branch when omitted. */
+export function useParams<const TRoute extends { id: string }>(
+ route: TRoute
+): InferSplitRouteBranchParams<TRoute>;
+export function useParams<T extends SplitRouteParams = SplitRouteParams>(): T;
+export function useParams(through?: { id: string }): SplitRouteParams {
+ const scope = usePaneContext();
+
+ return createMemoRecord(() => {
+ const route = scope.entry()?.location.route;
+ if (!route) return {};
+
+ return mergedParams(route, depthThrough(route, through));
+ });
+}
+
+/** Params owned by `route` alone. */
+export function useRouteParams<const TRoute extends { id: string }>(
+ route: TRoute
+): InferSplitRouteParams<TRoute> {
+ const scope = usePaneContext();
+
+ const params = () => {
+ const matches = scope.entry()?.location.route.matches;
+ const owned = matches?.find((match) => match.id === route.id);
+
+ return owned?.params ?? {};
+ };
+
+ return createMemoRecord(params) as InferSplitRouteParams<TRoute>;
+}
+
+export function useRouteState<const TRoute extends { id: string }>(
+ route: TRoute
+): Accessor<InferSplitRouteState<TRoute> | undefined> {
+ const router = useSplitRouter();
+ const scope = usePaneContext();
+
+ return createMemo(() =>
+ getRouteEntryState(router.routes, scope.entry(), route)
+ );
+}
+
+/** In-memory props handed to this view when it opened; read once at mount. */
+export function useEntryProps<T = unknown>(): T | undefined {
+ const scope = usePaneContext();
+
+ return untrack(() => scope.entry()?.props) as T | undefined;
+}
+
+/** Navigates this pane. Relative paths resolve against the calling route. */
+export function useNavigate(): SplitNavigate {
+ const router = useSplitRouter();
+ const scope = usePaneContext();
+
+ const navigate = (
+ to: SplitNavigationTarget | number,
+ options: SplitNavigateOptions = {}
+ ) => router.navigate(scope.pane(), to, { ...options, depth: scope.depth() });
+
+ return navigate as SplitNavigate;
+}
+
+export function useMatches(
+ pane?: Accessor<PaneId>
+): Accessor<RouteMatchInfo[]> {
+ const router = useSplitRouter();
+ const scope = useContext(PaneContext);
+
+ const matches = () => {
+ const id = pane?.() ?? scope?.pane();
+ if (id === undefined) return [];
+
+ return router.matches(id);
+ };
+
+ // A search change leaves the matches as they were; readers shouldn't hear of it.
+ return createMemo(matches, [], { equals: deepEqual });
+}
+
+/** This pane's in-flight navigation and its phase, such as a leave guard awaiting a reply. */
+export function usePendingNavigation(): Accessor<
+ PendingNavigation | undefined
+> {
+ const router = useSplitRouter();
+ const scope = usePaneContext();
+
+ return () => router.pending(scope.pane());
+}
+
+export function useCanGo(delta: number): Accessor<boolean> {
+ const router = useSplitRouter();
+ const scope = usePaneContext();
+
+ return createMemo(() => router.canGo(scope.pane(), delta));
+}
+
+/** How the pane reached its current entry: fresh, back, forward or replace. */
+export function useArrival(): Accessor<PaneArrival> {
+ const router = useSplitRouter();
+ const scope = usePaneContext();
+
+ return createMemo(() => router.arrival(scope.pane()));
+}
diff --git a/apps/web/src/lib/split-router/next/solid/memo-record.ts b/apps/web/src/lib/split-router/next/solid/memo-record.ts
new file mode 100644
index 0000000000..a4aac788d7
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/solid/memo-record.ts
@@ -0,0 +1,40 @@
+import deepEqual from 'fast-deep-equal';
+import { type Accessor, createMemo, getOwner, runWithOwner } from 'solid-js';
+
+/**
+ * A read-only record with one memo per property, so a reader re-runs only
+ * when the property it read changes.
+ */
+export function createMemoRecord<T extends object>(read: () => T): T {
+ const owner = getOwner();
+ const memos = new Map<PropertyKey, Accessor<unknown>>();
+
+ const createPropertyMemo = (key: PropertyKey) =>
+ runWithOwner(owner, () =>
+ createMemo(() => read()[key as keyof T], undefined, {
+ equals: deepEqual,
+ })
+ )!;
+
+ const value = (key: PropertyKey) => {
+ const existing = memos.get(key);
+ if (existing) return existing();
+
+ const memo = createPropertyMemo(key);
+ memos.set(key, memo);
+
+ return memo();
+ };
+
+ return new Proxy({} as T, {
+ get: (_target, key) => value(key),
+ has: (_target, key) => key in read(),
+ ownKeys: () => Reflect.ownKeys(read()),
+ getOwnPropertyDescriptor: (_target, key) => {
+ const present = key in read();
+ if (!present) return;
+
+ return { enumerable: true, configurable: true, value: value(key) };
+ },
+ });
+}
diff --git a/apps/web/src/lib/split-router/next/solid/outlet.tsx b/apps/web/src/lib/split-router/next/solid/outlet.tsx
new file mode 100644
index 0000000000..3a3d4db1a2
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/solid/outlet.tsx
@@ -0,0 +1,65 @@
+import { type Component, createMemo, type JSX, Show } from 'solid-js';
+import { Dynamic } from 'solid-js/web';
+import { type OutletMatch, outletAt } from '../routes/queries';
+import type { PaneId } from '../routes/types';
+import {
+ PaneContext,
+ type PaneContextValue,
+ usePaneContext,
+ useSplitRouter,
+} from './context';
+import { PaneScope } from './pane-scope';
+
+export type OutletProps = {
+ /** Shorthand for wrapping this outlet in `<PaneScope pane={…}>`. */
+ pane?: PaneId;
+ /** Shown when nothing below this point in the branch has a component. */
+ fallback?: JSX.Element;
+};
+
+function RouteOutlet(props: { fallback?: JSX.Element }) {
+ const router = useSplitRouter();
+ const parent = usePaneContext();
+
+ const match = createMemo<OutletMatch | undefined>(
+ () => outletAt(router.routes, parent.entry(), parent.depth()),
+ undefined,
+ { equals: (left, right) => left?.key === right?.key }
+ );
+
+ const context: PaneContextValue = {
+ pane: parent.pane,
+ entry: parent.entry,
+ depth: () => match()?.depth ?? parent.depth(),
+ };
+
+ return (
+ <Show keyed when={match()} fallback={props.fallback}>
+ {(resolved) => (
+ <PaneContext.Provider value={context}>
+ <Dynamic component={resolved.component as Component} />
+ </PaneContext.Provider>
+ )}
+ </Show>
+ );
+}
+
+/**
+ * Renders the next route component in the enclosing pane's branch. Its view
+ * stays mounted while its route id and `remountKey` are unchanged; params
+ * update in place.
+ */
+export function Outlet(props: OutletProps) {
+ return (
+ <Show
+ when={props.pane}
+ fallback={<RouteOutlet fallback={props.fallback} />}
+ >
+ {(pane) => (
+ <PaneScope pane={pane()}>
+ <RouteOutlet fallback={props.fallback} />
+ </PaneScope>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/lib/split-router/next/solid/pane-scope.tsx b/apps/web/src/lib/split-router/next/solid/pane-scope.tsx
new file mode 100644
index 0000000000..5ad68ca3cd
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/solid/pane-scope.tsx
@@ -0,0 +1,23 @@
+import type { ParentProps } from 'solid-js';
+import type { PaneId } from '../routes/types';
+import { PaneContext, type PaneContextValue, useSplitRouter } from './context';
+
+/**
+ * Makes `pane` the one that nested outlets render and hooks act on. A panel
+ * wraps its chrome and its `<Outlet />` in one so both can use the hooks.
+ */
+export function PaneScope(props: ParentProps<{ pane: PaneId }>) {
+ const router = useSplitRouter();
+
+ const context: PaneContextValue = {
+ pane: () => props.pane,
+ entry: () => router.entry(props.pane),
+ depth: () => 0,
+ };
+
+ return (
+ <PaneContext.Provider value={context}>
+ {props.children}
+ </PaneContext.Provider>
+ );
+}
diff --git a/apps/web/src/lib/split-router/next/solid/use-before-leave.ts b/apps/web/src/lib/split-router/next/solid/use-before-leave.ts
new file mode 100644
index 0000000000..ac2bec1814
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/solid/use-before-leave.ts
@@ -0,0 +1,16 @@
+import { onCleanup } from 'solid-js';
+import type { LeaveGuard } from '../router/types';
+import { usePaneContext, useSplitRouter } from './context';
+
+/**
+ * Runs before a navigation would unmount this view or close its pane.
+ * Return false, or a Promise of false, to keep the pane where it is.
+ */
+export function useBeforeLeave(guard: LeaveGuard): void {
+ const router = useSplitRouter();
+ const scope = usePaneContext();
+ const pane = scope.pane();
+ const viewDepth = scope.depth() - 1;
+
+ onCleanup(router.registerGuard(pane, viewDepth, guard));
+}
diff --git a/apps/web/src/lib/split-router/next/solid/use-claim.ts b/apps/web/src/lib/split-router/next/solid/use-claim.ts
new file mode 100644
index 0000000000..995ba3a834
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/solid/use-claim.ts
@@ -0,0 +1,36 @@
+import { type Accessor, onCleanup } from 'solid-js';
+import type { ClaimHolder } from '../router/claims';
+import { usePaneContext, useSplitRouter } from './context';
+
+/**
+ * Registers a resource this view shows outside a pane route, such as an
+ * inline preview, so opening it elsewhere activates this pane instead.
+ */
+export function useClaim(claim: Accessor<string | undefined>) {
+ const router = useSplitRouter();
+ const scope = usePaneContext();
+ const owner = Symbol('split-router.inline-claim');
+
+ const holders = (): ClaimHolder[] => {
+ const value = claim();
+ if (!value) return [];
+
+ const pane = scope.pane();
+ const holder: ClaimHolder = {
+ owner,
+ pane,
+ claim: value,
+ activate: () => router.activatePane(pane),
+ };
+
+ return [holder];
+ };
+
+ onCleanup(router.claims.register(holders));
+
+ return {
+ /** Who else shows `candidate`, if anyone outside this pane does. */
+ heldElsewhere: (candidate: string): ClaimHolder | undefined =>
+ router.claims.holderOf(candidate, scope.pane()),
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/tests/fake-solid-router.ts b/apps/web/src/lib/split-router/next/tests/fake-solid-router.ts
new file mode 100644
index 0000000000..bd1073b5d2
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/tests/fake-solid-router.ts
@@ -0,0 +1,144 @@
+import { batch, createSignal } from 'solid-js';
+import { vi } from 'vitest';
+import type {
+ SolidBeforeLeaveEvent,
+ SolidRouterLocationLike,
+ SolidRouterNavigate,
+} from '../history/solid-router';
+import { parseLocation } from '../routes/codec';
+
+type HistoryEntry = { path: string; state: unknown };
+
+/**
+ * Stands in for `@solidjs/router` under a `/app` base: history entries,
+ * reactive location, `navigate` and `useBeforeLeave`. Unlike Solid it applies
+ * path navigations synchronously, which is the harder case for echo handling;
+ * `navigate(delta)` lands in a later microtask, like `history.go`.
+ */
+export function createFakeSolidRouter(
+ initial: string,
+ /** Host paths after the current entry, as if the user had gone back. */
+ ahead: readonly string[] = []
+) {
+ const first = parseLocation(initial);
+ const [pathname, setPathname] = createSignal(first.path);
+ const [search, setSearch] = createSignal(first.search);
+ const [hash, setHash] = createSignal(first.hash);
+ const [state, setState] = createSignal<unknown>(undefined);
+ const entries: HistoryEntry[] = [initial, ...ahead].map((path) => ({
+ path,
+ state: undefined,
+ }));
+ let index = 0;
+ const calls: [string | number, unknown?][] = [];
+
+ const show = (value: string, nextState: unknown) => {
+ const next = parseLocation(value);
+
+ batch(() => {
+ setPathname(next.path);
+ setSearch(next.search);
+ setHash(next.hash);
+ setState(() => nextState);
+ });
+ };
+
+ const traverse = (delta: number) => {
+ index += delta;
+ const entry = entries[index]!;
+
+ show(entry.path, entry.state);
+ };
+
+ const record = (entry: HistoryEntry, replace: boolean | undefined) => {
+ if (replace) {
+ entries[index] = entry;
+ return;
+ }
+
+ entries.splice(index + 1);
+ entries.push(entry);
+ index += 1;
+ };
+
+ const navigate = ((
+ to: string | number,
+ options?: { replace?: boolean; state?: unknown }
+ ) => {
+ calls.push([to, options]);
+
+ if (typeof to === 'number') {
+ queueMicrotask(() => traverse(to));
+ return;
+ }
+
+ // Solid resolves absolute paths against the Router `base`.
+ const entry = { path: `/app${to}`, state: options?.state };
+ record(entry, options?.replace);
+ show(entry.path, entry.state);
+ }) as SolidRouterNavigate;
+
+ const leaveListeners: ((event: SolidBeforeLeaveEvent) => void)[] = [];
+
+ const leave = (to: string | number) => {
+ const event = {
+ to,
+ defaultPrevented: false,
+ preventDefault: vi.fn(() => {
+ event.defaultPrevented = true;
+ }),
+ retry: vi.fn(),
+ };
+
+ for (const listener of leaveListeners) listener(event);
+
+ return event;
+ };
+
+ /** A browser Back or Forward: the URL moves, then before-leave listeners may send it back. */
+ const pop = (delta: number) => {
+ index += delta;
+ const event = leave(delta);
+
+ if (event.defaultPrevented) {
+ index -= delta;
+ return event;
+ }
+
+ const entry = entries[index]!;
+ show(entry.path, entry.state);
+
+ return event;
+ };
+
+ const location: SolidRouterLocationLike = {
+ get pathname() {
+ return pathname();
+ },
+ get search() {
+ return search();
+ },
+ get hash() {
+ return hash();
+ },
+ get state() {
+ return state() as SolidRouterLocationLike['state'];
+ },
+ };
+
+ return {
+ location,
+ navigate,
+ calls,
+ show,
+ traverse,
+ leave,
+ pop,
+ landed: () => entries[index]!.path,
+ entries: () => entries,
+
+ beforeLeave: (listener: (event: SolidBeforeLeaveEvent) => void) => {
+ leaveListeners.push(listener);
+ },
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/tests/fixtures.ts b/apps/web/src/lib/split-router/next/tests/fixtures.ts
new file mode 100644
index 0000000000..702d0f99dc
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/tests/fixtures.ts
@@ -0,0 +1,119 @@
+import { z } from 'zod';
+import type { SplitCloseAction, SplitPanePolicy } from '../router/types';
+import { defineRoute, defineRoutes } from '../routes/define';
+import type { PaneId, SplitLocation } from '../routes/types';
+
+export const documentRoute = defineRoute({
+ id: 'drive-document',
+ path: ':documentType/:documentId',
+ params: z.object({
+ documentType: z.enum(['md', 'pdf']),
+ documentId: z.string().min(1),
+ }),
+ claim: ({ documentType, documentId }) => ({
+ namespace: 'block',
+ id: `${documentType}:${documentId}`,
+ }),
+ remountKey: ({ documentId }) => documentId,
+});
+
+export const folderRoute = defineRoute({
+ id: 'drive-folder',
+ path: 'folder/:folderId?',
+ params: z.object({ folderId: z.string().min(1).optional() }),
+});
+
+export const driveRoute = defineRoute({
+ id: 'drive',
+ path: 'drive',
+ search: ['drive'],
+ children: [folderRoute, documentRoute],
+});
+
+export const threadRoute = defineRoute({
+ id: 'mail-thread',
+ path: ':threadId',
+ claim: ({ threadId }) => ({ namespace: 'block', id: `email:${threadId}` }),
+});
+
+export const mailRoute = defineRoute({
+ id: 'mail',
+ path: 'mail',
+ children: [threadRoute],
+});
+
+export const blockRoute = defineRoute({
+ id: 'block',
+ path: ':type/:id',
+ params: z.object({
+ type: z.enum(['md', 'pdf', 'channel']),
+ id: z.string().min(1),
+ }),
+ claim: ({ type, id }) => ({ namespace: 'block', id: `${type}:${id}` }),
+});
+
+export const homeRoute = defineRoute({ id: 'home', path: 'home' });
+
+export const notFoundRoute = defineRoute({
+ id: 'not-found',
+ path: '*segments',
+});
+
+/** Declared out of order on purpose: matching must rank by specificity. */
+export const appRoutes = defineRoutes({
+ definitions: [notFoundRoute, blockRoute, homeRoute, mailRoute, driveRoute],
+ globalSearch: ['referral_code'],
+ defaultRoute: () => ({ matches: [{ id: 'home', params: {} }] }),
+});
+
+export const homeLocation: SplitLocation = {
+ route: { matches: [{ id: 'home', params: {} }] },
+};
+
+/**
+ * Opens new panes after their source, or in the source once `maxPanes` are
+ * open. Closing the last pane goes home instead; pinned panes never close.
+ */
+export function createTestPolicy(
+ options: {
+ maxPanes?: number;
+ pinned?: readonly PaneId[];
+ closeLast?: SplitCloseAction;
+ } = {}
+) {
+ const activated: PaneId[] = [];
+ const placements: Parameters<SplitPanePolicy['placeNewPane']>[0][] = [];
+
+ const policy: SplitPanePolicy = {
+ placeNewPane(request) {
+ placements.push(request);
+
+ const { source, panes, opening } = request;
+ const isFull = panes.length + opening >= (options.maxPanes ?? Infinity);
+ if (isFull) return { pane: source ?? panes.at(-1)! };
+
+ const insertAt = source ? panes.indexOf(source) + 1 : panes.length;
+
+ return { insertAt };
+ },
+
+ closeAction: ({ pane, panes }) => {
+ const isPinned = options.pinned?.includes(pane);
+ if (isPinned) return { type: 'keep' };
+ if (panes.length > 1) return { type: 'remove' };
+
+ const goHome: SplitCloseAction = {
+ type: 'navigate',
+ destination: homeLocation,
+ };
+
+ return options.closeLast ?? goHome;
+ },
+
+ activate: (pane) => {
+ activated.push(pane);
+ },
+ };
+
+ return { policy, activated, placements };
+}
diff --git a/apps/web/src/lib/split-router/next/tests/history.test.ts b/apps/web/src/lib/split-router/next/tests/history.test.ts
new file mode 100644
index 0000000000..05e67c8172
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/tests/history.test.ts
@@ -0,0 +1,305 @@
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createBrowserHistory } from '../history/browser';
+import { createMemoryHistory } from '../history/memory';
+import { readSlice, STATE_KEY, toMountLocation } from '../history/shared';
+import {
+ createSolidRouterHistory,
+ type SolidRouterHistoryOptions,
+} from '../history/solid-router';
+import type { ExternalChange } from '../history/types';
+import { decodePanes, parseLocation } from '../routes/codec';
+import { createRoutesManifest } from '../routes/manifest';
+import type { ExternalLocation, PaneId } from '../routes/types';
+import { createFakeSolidRouter } from './fake-solid-router';
+import { appRoutes } from './fixtures';
+
+const stateFor = (entry: string) => ({
+ panes: [{ pane: 'p1' as PaneId, entry }],
+});
+const at = (path: string, entry = 'e1'): ExternalLocation => ({
+ ...parseLocation(path),
+ state: stateFor(entry),
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe('history helpers', () => {
+ it('matches the base on a segment boundary', () => {
+ expect(toMountLocation('/app', '/app')?.path).toBe('/');
+ expect(toMountLocation('/app/mail', '/app')?.path).toBe('/mail');
+ expect(toMountLocation('/application', '/app')).toBeUndefined();
+ });
+
+ it('reads only non-negative whole history indexes', () => {
+ const slice = (index: unknown) => ({ [STATE_KEY]: { index } });
+ expect(readSlice(slice(2))?.index).toBe(2);
+ expect(readSlice(slice(-1))).toBeUndefined();
+ expect(readSlice(slice(1.5))).toBeUndefined();
+ expect(readSlice(slice(Number.NaN))).toBeUndefined();
+ });
+});
+
+describe('memory history', () => {
+ it('never reports its own writes', () => {
+ const history = createMemoryHistory('/a');
+ const listener = vi.fn();
+ history.subscribe(listener);
+ history.write(at('/b'), { mode: 'push' });
+ history.write(at('/c'), { mode: 'replace' });
+ expect(listener).not.toHaveBeenCalled();
+ expect(history.entries().map((entry) => entry.path)).toEqual(['/a', '/c']);
+ });
+
+ it('reports traversal and reverts it', () => {
+ const history = createMemoryHistory('/a');
+ history.write(at('/b'), { mode: 'push' });
+ const changes: ExternalChange[] = [];
+ history.subscribe((change) => changes.push(change));
+ history.back();
+ expect(changes.map((change) => change.location.path)).toEqual(['/a']);
+ changes[0]!.revert();
+ expect(history.read().path).toBe('/b');
+ });
+
+ it('lets interceptors veto outside navigations', async () => {
+ const history = createMemoryHistory('/a');
+ const listener = vi.fn();
+ history.subscribe(listener);
+ const stop = history.intercept(() => false);
+ await expect(history.navigate('/x')).resolves.toBe(false);
+ expect(history.read().path).toBe('/a');
+ stop();
+ history.intercept(async () => true);
+ await expect(history.navigate('/y')).resolves.toBe(true);
+ expect(listener).toHaveBeenCalledOnce();
+ expect(history.read().path).toBe('/y');
+ });
+});
+
+describe('browser history', () => {
+ beforeEach(() => window.history.replaceState(null, '', '/app/home'));
+
+ it('reads mount-relative locations and records positions on write', () => {
+ const history = createBrowserHistory({ base: '/app' });
+ expect(history.read()).toMatchObject({ path: '/home' });
+ history.write(at('/mail?x=1'), { mode: 'push' });
+ expect(window.location.pathname).toBe('/app/mail');
+ expect(window.history.state.__splitRouter).toEqual({
+ index: 1,
+ value: stateFor('e1'),
+ });
+ expect(history.read()).toEqual({
+ path: '/mail',
+ search: '?x=1',
+ hash: '',
+ state: stateFor('e1'),
+ });
+ expect(history.href({ path: '/mail', search: '?q=1', hash: '' })).toBe(
+ '/app/mail?q=1'
+ );
+ });
+
+ it('reports back/forward, and a revert returns to the previous entry', async () => {
+ const history = createBrowserHistory({ base: '/app' });
+ history.write(at('/home', 'e1'), { mode: 'replace' });
+ history.write(at('/mail', 'e2'), { mode: 'push' });
+ const changes: ExternalChange[] = [];
+ history.subscribe((change) => changes.push(change));
+
+ const popped = () =>
+ new Promise((resolve) =>
+ window.addEventListener('popstate', resolve, { once: true })
+ );
+ const back = popped();
+ window.history.back();
+ await back;
+ expect(changes.map((change) => change.location.path)).toEqual(['/home']);
+
+ await changes[0]!.revert();
+ expect(window.location.pathname).toBe('/app/mail');
+ expect(changes.map((change) => change.location.path)).toEqual([
+ '/home',
+ '/mail',
+ ]);
+ });
+
+ it('rewrites legacy multi-pane paths through transformPath', () => {
+ // Pre-`~` URLs listed each pane as a `type/id` pair in one path.
+ const upgradeLegacy = (path: string) => {
+ const segments = path.split('/').filter(Boolean);
+ const pairs = segments.length >= 4 && segments.length % 2 === 0;
+ if (!pairs) return path;
+ const panes = [];
+ for (let index = 0; index < segments.length; index += 2) {
+ if (!['md', 'pdf', 'channel'].includes(segments[index]!)) return path;
+ panes.push(`${segments[index]}/${segments[index + 1]}`);
+ }
+ return `/${panes.join('/~/')}`;
+ };
+ window.history.replaceState(null, '', '/app/md/a/pdf/b');
+ const history = createBrowserHistory({
+ base: '/app',
+ transformPath: upgradeLegacy,
+ });
+ const decoded = decodePanes(
+ createRoutesManifest(appRoutes),
+ history.read()
+ );
+ expect(
+ decoded.panes.map((pane) => pane.entry.location.route.matches[0].params)
+ ).toEqual([
+ { type: 'md', id: 'a' },
+ { type: 'pdf', id: 'b' },
+ ]);
+
+ window.history.replaceState(null, '', '/app/drive/md/a');
+ expect(history.read().path).toBe('/drive/md/a');
+ });
+});
+
+describe('Solid Router history', () => {
+ const adapterFor = (
+ router: ReturnType<typeof createFakeSolidRouter>,
+ options: Partial<SolidRouterHistoryOptions> = {}
+ ) =>
+ createSolidRouterHistory({
+ location: router.location,
+ navigate: router.navigate,
+ beforeLeave: router.beforeLeave,
+ base: '/app',
+ owns: () => true,
+ ...options,
+ });
+
+ it('writes in a later task, merges writes, and skips its own write landing', () => {
+ vi.useFakeTimers();
+ const router = createFakeSolidRouter('/app/home');
+ const listener = vi.fn();
+ const { history, dispose } = createRoot((dispose) => {
+ const history = adapterFor(router);
+ history.subscribe(listener);
+ return { history, dispose };
+ });
+
+ history.write(at('/mail'), { mode: 'push' });
+ history.write(at('/mail/t1'), { mode: 'replace' });
+ expect(router.calls).toEqual([]);
+ vi.runAllTimers();
+
+ expect(router.calls).toEqual([
+ [
+ '/mail/t1',
+ {
+ replace: false,
+ scroll: false,
+ state: { __splitRouter: { index: 1, value: stateFor('e1') } },
+ },
+ ],
+ ]);
+ expect(listener).not.toHaveBeenCalled();
+ expect(history.read()).toEqual({
+ path: '/mail/t1',
+ search: '',
+ hash: '',
+ state: stateFor('e1'),
+ });
+ dispose();
+ });
+
+ it('strips the base and applies the path transform', () => {
+ const router = createFakeSolidRouter('/app/s_abc');
+ createRoot((dispose) => {
+ const history = adapterFor(router, {
+ transformPath: (path) => path.replace('s_abc', 'md/abc'),
+ });
+ expect(history.read().path).toBe('/md/abc');
+ dispose();
+ });
+ });
+
+ it('reports back/forward, and a revert settles once it has landed', async () => {
+ vi.useFakeTimers();
+ const router = createFakeSolidRouter('/app/home');
+ const changes: ExternalChange[] = [];
+ const { history, dispose } = createRoot((dispose) => {
+ const history = adapterFor(router);
+ history.subscribe((change) => changes.push(change));
+ return { history, dispose };
+ });
+ history.write(at('/home', 'e1'), { mode: 'replace' });
+ vi.runAllTimers();
+ history.write(at('/mail', 'e2'), { mode: 'push' });
+ vi.runAllTimers();
+
+ router.traverse(-1);
+ expect(changes.map((change) => change.location.path)).toEqual(['/home']);
+ const reverted = changes[0]!.revert();
+ expect(history.read().path).toBe('/home');
+ await reverted;
+ expect(router.calls.at(-1)).toEqual([1, undefined]);
+ expect(history.read().path).toBe('/mail');
+ expect(changes.map((change) => change.location.path)).toEqual([
+ '/home',
+ '/mail',
+ ]);
+ dispose();
+ });
+
+ it('ignores locations outside the split panes', () => {
+ const router = createFakeSolidRouter('/app/home');
+ const listener = vi.fn();
+ const dispose = createRoot((dispose) => {
+ adapterFor(router, { owns: (path) => path !== '/login' }).subscribe(
+ listener
+ );
+ return dispose;
+ });
+ router.show('/app/login', undefined);
+ expect(listener).not.toHaveBeenCalled();
+ router.show('/app/mail', undefined);
+ expect(listener).toHaveBeenCalledOnce();
+ dispose();
+ });
+
+ it('intercepts outside navigations through beforeLeave', async () => {
+ const router = createFakeSolidRouter('/app/home');
+ const verdicts: (boolean | Promise<boolean>)[] = [
+ false,
+ Promise.resolve(true),
+ true,
+ ];
+ const seen: (ExternalLocation | undefined)[] = [];
+ const dispose = createRoot((dispose) => {
+ adapterFor(router, { owns: (path) => path !== '/login' }).intercept?.(
+ (location) => {
+ seen.push(location);
+ return verdicts.shift()!;
+ }
+ );
+ return dispose;
+ });
+
+ const blocked = router.leave('/app/mail/t1');
+ expect(blocked.preventDefault).toHaveBeenCalled();
+ expect(seen[0]).toEqual({ path: '/mail/t1', search: '', hash: '' });
+
+ const deferred = router.leave('/app/login');
+ expect(seen[1]).toBeUndefined();
+ expect(deferred.preventDefault).toHaveBeenCalled();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(deferred.retry).toHaveBeenCalledWith(true);
+
+ const allowed = router.leave('/app/mail');
+ expect(allowed.preventDefault).not.toHaveBeenCalled();
+
+ const traversal = router.leave(-1);
+ expect(traversal.preventDefault).not.toHaveBeenCalled();
+ expect(seen).toHaveLength(3);
+ dispose();
+ });
+});
diff --git a/apps/web/src/lib/split-router/next/tests/navigation.test.ts b/apps/web/src/lib/split-router/next/tests/navigation.test.ts
new file mode 100644
index 0000000000..bb951441bd
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/tests/navigation.test.ts
@@ -0,0 +1,349 @@
+import { simulate, step } from '@macro-inc/machine';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ runMiddleware,
+ type SplitRouterMiddleware,
+} from '../router/middleware';
+import { IDLE, type State as RunState, runDef } from '../router/run';
+import type { Navigation } from '../router/types';
+import {
+ type Event as GateEvent,
+ type State as GateState,
+ type UrlOutcome,
+ urlGateDef,
+} from '../router/url-gate';
+import { createRoutesManifest, decodePane } from '../routes/manifest';
+import type { Entry, PaneId } from '../routes/types';
+import { CANCELLED } from '../utils';
+import { appRoutes } from './fixtures';
+
+const routes = createRoutesManifest(appRoutes);
+const entry = (
+ id: string,
+ path: string,
+ extra: Partial<Entry> = {}
+): Entry => ({
+ id,
+ location: { route: decodePane(routes, path.split('/').filter(Boolean))! },
+ ...extra,
+});
+const signal = () => new AbortController().signal;
+
+const pane = 'p1' as PaneId;
+const navigation = (id: string): Navigation => ({
+ cause: 'navigate',
+ targets: [{ pane, to: entry(id, '/home') }],
+ apply: () => ({ status: 'committed', pane }),
+});
+const first = navigation('e1');
+const second = navigation('e2');
+const third = navigation('e4');
+const entries = [entry('e3', '/mail')];
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('run', () => {
+ const guards: RunState = { t: 'guards', navigation: first };
+ const middleware: RunState = { t: 'middleware', navigation: first };
+ const preload: RunState = { t: 'preload', navigation: first, entries };
+
+ it('moves from guards to middleware to preload, then commits', () => {
+ const run = simulate(runDef, IDLE, [
+ { t: 'navigate', navigation: first },
+ { t: 'allowed' },
+ { t: 'resolved', entries },
+ { t: 'preloaded' },
+ ]);
+ expect(run.state).toEqual(IDLE);
+ expect(run.commands).toEqual([{ t: 'commit', navigation: first, entries }]);
+ });
+
+ it('is turned down by guards or middleware, and fails from any phase', () => {
+ expect(step(runDef, guards, { t: 'refused' })?.commands).toEqual([
+ { t: 'cancel', navigation: first, reason: 'refused' },
+ ]);
+ expect(
+ step(runDef, middleware, { t: 'middleware-cancelled' })?.commands
+ ).toEqual([{ t: 'cancel', navigation: first, reason: 'cancelled' }]);
+ expect(step(runDef, preload, { t: 'failed' })).toEqual({
+ state: IDLE,
+ commands: [{ t: 'cancel', navigation: first, reason: 'failed' }],
+ });
+ });
+
+ it('ignores a report from a phase it has left', () => {
+ expect(step(runDef, middleware, { t: 'allowed' })).toBeUndefined();
+ expect(step(runDef, preload, { t: 'resolved', entries })).toBeUndefined();
+ });
+
+ it('lets a newer navigation replace the one in flight', () => {
+ const run = simulate(runDef, IDLE, [
+ { t: 'navigate', navigation: first },
+ { t: 'allowed' },
+ { t: 'navigate', navigation: second },
+ ]);
+ expect(run.state).toEqual({ t: 'guards', navigation: second });
+ expect(run.commands).toEqual([
+ { t: 'cancel', navigation: first, reason: 'superseded' },
+ ]);
+ });
+
+ it('cancels with the reason it is aborted for', () => {
+ expect(
+ step(runDef, preload, { t: 'abort', reason: 'interrupted' })
+ ).toEqual({
+ state: IDLE,
+ commands: [{ t: 'cancel', navigation: first, reason: 'interrupted' }],
+ });
+ });
+
+ it('ignores reports and aborts while idle', () => {
+ expect(
+ step(runDef, IDLE, { t: 'abort', reason: 'superseded' })
+ ).toBeUndefined();
+ expect(step(runDef, IDLE, { t: 'preloaded' })).toBeUndefined();
+ });
+});
+
+describe('URL gate', () => {
+ const open: GateState = { t: 'open' };
+ const start = (navigating: Navigation, blocking = false): GateEvent => ({
+ t: 'start',
+ navigation: navigating,
+ blocking,
+ });
+ const settled = (navigating: Navigation, outcome: UrlOutcome): GateEvent => ({
+ t: 'settled',
+ navigation: navigating,
+ outcome,
+ });
+ const ACTION: GateEvent = { t: 'action' };
+ const LANDED: GateEvent = { t: 'revert-landed' };
+ const OPENED = { t: 'opened' };
+ const runs = (navigating: Navigation) => [
+ { t: 'cancel-pane-runs' },
+ { t: 'run', navigation: navigating },
+ ];
+ const revert = (navigating: Navigation) => ({
+ t: 'revert',
+ navigation: navigating,
+ });
+ const abort = (navigating: Navigation, reason: string) => ({
+ t: 'abort',
+ navigation: navigating,
+ reason,
+ });
+
+ it('lets actions straight through while no URL navigation runs', () => {
+ expect(step(urlGateDef, open, ACTION)).toEqual({
+ state: open,
+ commands: [OPENED],
+ });
+ expect(step(urlGateDef, open, start(first))?.commands).toEqual(runs(first));
+ });
+
+ it('keeps a replaced URL navigation to put back later, and its blocking', () => {
+ const run = simulate(urlGateDef, open, [start(first, true), start(second)]);
+ expect(run.state).toEqual({
+ t: 'navigating',
+ navigation: second,
+ blocking: true,
+ superseded: [first],
+ });
+ expect(run.commands).toEqual([...runs(first), ...runs(second)]);
+ });
+
+ it('opens once the current URL navigation commits, forgetting the ones it replaced', () => {
+ const run = simulate(urlGateDef, open, [
+ start(first),
+ start(second),
+ settled(second, 'committed'),
+ ]);
+ expect(run.state).toEqual(open);
+ expect(run.commands).toEqual([...runs(first), ...runs(second), OPENED]);
+ });
+
+ it.each(['refused', 'cancelled'] as const)(
+ 'puts back a %s URL navigation, then the ones it replaced, newest first',
+ (outcome) => {
+ const run = simulate(urlGateDef, open, [
+ start(first),
+ start(second),
+ start(third),
+ settled(third, outcome),
+ LANDED,
+ LANDED,
+ LANDED,
+ ]);
+ expect(run.state).toEqual(open);
+ expect(run.commands.slice(6)).toEqual([
+ revert(third),
+ revert(second),
+ revert(first),
+ OPENED,
+ ]);
+ }
+ );
+
+ it('opens after a failed URL navigation without putting its URL back', () => {
+ const run = simulate(urlGateDef, open, [
+ start(first),
+ settled(first, 'failed'),
+ ]);
+ expect(run.state).toEqual(open);
+ expect(run.commands).toEqual([...runs(first), OPENED]);
+ });
+
+ it('ignores the outcome of a URL navigation that is no longer current', () => {
+ const navigating: GateState = {
+ t: 'navigating',
+ navigation: second,
+ blocking: false,
+ superseded: [first],
+ };
+ expect(
+ step(urlGateDef, navigating, settled(first, 'committed'))
+ ).toBeUndefined();
+ });
+
+ it('holds an action while a blocking URL navigation runs', () => {
+ const blocking: GateState = {
+ t: 'navigating',
+ navigation: first,
+ blocking: true,
+ superseded: [],
+ };
+ expect(step(urlGateDef, blocking, ACTION)).toBeUndefined();
+ });
+
+ it('lets an action take over from any other URL navigation once its URLs are back', () => {
+ const run = simulate(urlGateDef, open, [
+ start(first),
+ start(second),
+ ACTION,
+ LANDED,
+ LANDED,
+ ]);
+ expect(run.state).toEqual(open);
+ expect(run.commands.slice(4)).toEqual([
+ abort(second, 'interrupted'),
+ revert(second),
+ revert(first),
+ OPENED,
+ ]);
+ });
+
+ it('turns away a URL navigation that arrives while reverting and puts it back too', () => {
+ const run = simulate(urlGateDef, open, [
+ start(first),
+ ACTION,
+ start(second),
+ LANDED,
+ LANDED,
+ ]);
+ expect(run.state).toEqual(open);
+ expect(run.commands.slice(2)).toEqual([
+ abort(first, 'interrupted'),
+ revert(first),
+ abort(second, 'interrupted'),
+ revert(second),
+ OPENED,
+ ]);
+ });
+
+ it('puts back a URL navigation arriving mid-revert before the older ones still queued', () => {
+ const run = simulate(urlGateDef, open, [
+ start(first),
+ start(second),
+ settled(second, 'refused'),
+ start(third),
+ LANDED,
+ LANDED,
+ LANDED,
+ ]);
+ const reverts = run.commands.filter((command) => command.t === 'revert');
+
+ expect(run.state).toEqual(open);
+ expect(reverts).toEqual([revert(second), revert(third), revert(first)]);
+ });
+
+ it('aborts the URL navigation and opens on dispose, then turns everything away', () => {
+ const run = simulate(urlGateDef, open, [
+ start(first, true),
+ { t: 'dispose' },
+ ACTION,
+ start(second),
+ ]);
+ expect(run.state).toEqual({ t: 'disposed' });
+ expect(run.commands.slice(2)).toEqual([
+ abort(first, 'disposed'),
+ OPENED,
+ OPENED,
+ abort(second, 'disposed'),
+ ]);
+ });
+});
+
+describe('middleware', () => {
+ const navigatingTo = (to: Entry) => ({
+ to,
+ cause: 'navigate' as const,
+ signal: signal(),
+ });
+
+ it('follows redirects and keeps the entry identity', () => {
+ const middleware: SplitRouterMiddleware = ({ to, redirect }) =>
+ to.location.route.matches[0].id === 'block'
+ ? redirect('/mail/t1')
+ : undefined;
+ const result = runMiddleware(
+ routes,
+ [middleware],
+ navigatingTo(entry('e1', '/md/d1'))
+ );
+ expect(result).toMatchObject({
+ id: 'e1',
+ location: { route: { matches: [{ id: 'mail' }, { id: 'mail-thread' }] } },
+ });
+ });
+
+ it('cancels when a handler asks to', () => {
+ const result = runMiddleware(
+ routes,
+ [({ cancel }) => cancel()],
+ navigatingTo(entry('e1', '/home'))
+ );
+ expect(result).toBe(CANCELLED);
+ });
+
+ it('awaits async handlers', async () => {
+ const result = runMiddleware(
+ routes,
+ [
+ async ({ path, redirect }) =>
+ path === '/drive' ? undefined : redirect('/drive'),
+ ],
+ navigatingTo(entry('e1', '/home'))
+ );
+ await expect(result).resolves.toMatchObject({
+ location: { route: { matches: [{ id: 'drive' }] } },
+ });
+ });
+
+ it('falls back to the proposed entry on a redirect loop', () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const original = entry('e1', '/home');
+ const result = runMiddleware(
+ routes,
+ [
+ ({ to, redirect }) =>
+ redirect(
+ to.location.route.matches[0].id === 'home' ? '/drive' : '/home'
+ ),
+ ],
+ navigatingTo(original)
+ );
+ expect(result).toBe(original);
+ expect(error).toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/lib/split-router/next/tests/panes.test.ts b/apps/web/src/lib/split-router/next/tests/panes.test.ts
new file mode 100644
index 0000000000..517d827323
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/tests/panes.test.ts
@@ -0,0 +1,261 @@
+import { describe, expect, it } from 'vitest';
+import { changedPanes, diffPanes } from '../panes/diff';
+import {
+ applyHistoryChange,
+ findBack,
+ findStep,
+ removeEntries,
+} from '../panes/history';
+import { createMemoryPaneStore } from '../panes/memory-store';
+import { createPanes, insertionIndex } from '../panes/panes';
+import type {
+ PaneId,
+ PanePolicy,
+ PaneSnapshot,
+ Placement,
+} from '../panes/types';
+
+/** Panes know nothing about routes; these entries are just titled cards. */
+type Card = {
+ id: string;
+ title: string;
+ props?: unknown;
+ keepProps?: boolean;
+};
+
+const card = (id: string, title = id, extra: Partial<Card> = {}): Card => ({
+ id,
+ title,
+ ...extra,
+});
+const pane = (id: string) => id as PaneId;
+const sameTitle = (left: Card, right: Card) => left.title === right.title;
+
+describe('pane history', () => {
+ const snapshot: PaneSnapshot<Card> = {
+ entries: [
+ card('a'),
+ card('b', 'b', { props: { once: true } }),
+ card('c', 'c', { props: { kept: true }, keepProps: true }),
+ ],
+ index: 1,
+ };
+
+ it('drops one-shot props from the entry being left', () => {
+ const pushed = applyHistoryChange(snapshot, {
+ type: 'push',
+ entry: card('d'),
+ });
+ expect(pushed.entries.map((item) => item.id)).toEqual(['a', 'b', 'd']);
+ expect(pushed.entries[1]!.props).toBeUndefined();
+ expect(pushed.index).toBe(2);
+
+ const moved = applyHistoryChange(
+ { ...snapshot, index: 2 },
+ { type: 'go', index: 0, entry: snapshot.entries[0]! }
+ );
+ expect(moved.entries[2]!.props).toEqual({ kept: true });
+ });
+
+ it('steps over entries that cannot be visited', () => {
+ const skipB = (item: Card) => item.id !== 'b';
+ expect(findStep({ ...snapshot, index: 2 }, -1, skipB)?.entry.id).toBe('a');
+ expect(findStep(snapshot, 1)?.entry.id).toBe('c');
+ expect(findStep(snapshot, 5)).toBeUndefined();
+ expect(
+ findBack({ ...snapshot, index: 2 }, (item) => item.id === 'a')?.index
+ ).toBe(0);
+ });
+
+ it('removes entries and keeps the cursor on the nearest survivor', () => {
+ const next = removeEntries(
+ { ...snapshot, index: 2 },
+ (item) => item.id !== 'c'
+ );
+ expect(next).toEqual({ entries: [snapshot.entries[2]], index: 0 });
+ expect(removeEntries(snapshot, () => true)).toBeUndefined();
+ });
+});
+
+describe('panes diff', () => {
+ const histories = new Map<PaneId, PaneSnapshot<Card>>([
+ [pane('p1'), { entries: [card('a', 'home'), card('b', 'mail')], index: 1 }],
+ [pane('p2'), { entries: [card('c', 'drive')], index: 0 }],
+ ]);
+ const live = {
+ panes: [pane('p1'), pane('p2')],
+ read: (id: PaneId) => histories.get(id),
+ };
+ const options = { createPaneId: () => pane('new'), same: sameTitle };
+
+ it('keeps untouched panes and moves within history for known entries', () => {
+ const diff = diffPanes(
+ live,
+ [
+ { paneId: pane('p1'), entry: card('a', 'home') },
+ { paneId: pane('p2'), entry: card('c', 'drive') },
+ ],
+ options
+ );
+ expect(diff.panes).toMatchObject([
+ { kind: 'change', pane: 'p1', index: 0, to: { id: 'a' } },
+ { kind: 'keep', pane: 'p2' },
+ ]);
+ expect(diff.removed).toEqual([]);
+ });
+
+ it('lets the caller merge a stored entry with the incoming one', () => {
+ const diff = diffPanes(
+ live,
+ [{ paneId: pane('p1'), entry: card('a', 'home again') }],
+ {
+ ...options,
+ adopt: (stored, incoming) => ({ ...stored, title: incoming.title }),
+ }
+ );
+ expect(diff.panes[0]).toMatchObject({
+ kind: 'change',
+ index: 0,
+ to: { id: 'a', title: 'home again' },
+ });
+ });
+
+ it('creates, changes by position and removes panes as needed', () => {
+ const created = diffPanes(
+ live,
+ [{ paneId: pane('p9'), entry: card('z', 'doc') }],
+ options
+ );
+ expect(created.panes).toMatchObject([{ kind: 'create', pane: 'p9' }]);
+ expect(created.removed).toEqual(['p1', 'p2']);
+
+ const positional = diffPanes(
+ live,
+ [{ entry: card('x', 'doc') }, { entry: card('y', 'drive') }],
+ options
+ );
+ expect(positional.panes).toMatchObject([
+ { kind: 'change', pane: 'p1', to: { id: 'x' } },
+ { kind: 'keep', pane: 'p2' },
+ ]);
+ expect(positional.panes[0]).not.toHaveProperty('index');
+ });
+});
+
+describe('panes', () => {
+ function setup(policy: Partial<PanePolicy<Card, string>> = {}) {
+ const removed: PaneId[] = [];
+ let created = 0;
+ const panes = createPanes<Card, string>({
+ store: createMemoryPaneStore<Card>(),
+ policy: {
+ placeNewPane: ({ panes }) => ({ insertAt: panes.length }),
+ closeAction: () => ({ type: 'remove' }),
+ activate: () => {},
+ ...policy,
+ },
+ createPaneId: () => pane(`p${++created}`),
+ onRemove: (id) => removed.push(id),
+ });
+ return { panes, removed };
+ }
+
+ it('inserts, moves and removes panes in order', () => {
+ const { panes, removed } = setup();
+ panes.insert(pane('a'), card('1'), 0);
+ panes.insert(pane('b'), card('2'), 1);
+ expect(panes.ids()).toEqual(['a', 'b']);
+
+ expect(panes.move(pane('b'), 0)).toBe(true);
+ expect(panes.ids()).toEqual(['b', 'a']);
+ expect(panes.move(pane('b'), 0)).toBe(false);
+
+ panes.remove(pane('a'));
+ expect(panes.ids()).toEqual(['b']);
+ expect(panes.read(pane('a'))).toBeUndefined();
+ expect(removed).toEqual(['a']);
+ });
+
+ it('places a new pane after the same neighbour when panes changed meanwhile', () => {
+ const [a, b, c] = ['a', 'b', 'c'] as PaneId[];
+ expect(insertionIndex([a, b], 1, [a, b])).toBe(1);
+ expect(insertionIndex([a, b], 1, [a, c, b])).toBe(2);
+ expect(insertionIndex([a, b], 0, [c, a, b])).toBe(1);
+ expect(insertionIndex([a, b], 2, [c, a, b])).toBe(3);
+ expect(insertionIndex([a, b], 1, [b])).toBe(1);
+
+ const { panes } = setup();
+ panes.insert(a, card('1'), 0);
+ panes.insert(b, card('2'), 1, [a]);
+ panes.insert(c, card('3'), 1, [a]);
+ expect(panes.ids()).toEqual(['a', 'b', 'c']);
+ });
+
+ it('records each change and how the pane arrived', () => {
+ const { panes } = setup();
+ panes.insert(pane('a'), card('1'), 0);
+ expect(panes.arrival(pane('a'))).toBe('fresh');
+ panes.commit(pane('a'), { type: 'push', entry: card('2') }, 'fresh');
+ panes.commit(pane('a'), { type: 'go', index: 0, entry: card('1') }, 'back');
+ expect(panes.current(pane('a'))?.id).toBe('1');
+ expect(panes.arrival(pane('a'))).toBe('back');
+ });
+
+ it('applies a diff: moving through history, changing and removing panes', () => {
+ const { panes, removed } = setup();
+ panes.insert(pane('a'), card('1', 'home'), 0);
+ panes.commit(pane('a'), { type: 'push', entry: card('2', 'mail') });
+ panes.insert(pane('b'), card('3', 'drive'), 1);
+ panes.insert(pane('c'), card('4', 'tasks'), 2);
+
+ const diff = panes.diff(
+ [
+ { paneId: pane('a'), entry: card('1', 'home') },
+ { entry: card('5', 'calendar') },
+ ],
+ { same: sameTitle }
+ );
+ panes.applyDiff(
+ diff,
+ changedPanes(diff).map((change) =>
+ change.kind === 'change' ? change.to : change.entry
+ )
+ );
+
+ expect(panes.ids()).toEqual(['a', 'b']);
+ expect(panes.current(pane('a'))?.id).toBe('1');
+ expect(panes.arrival(pane('a'))).toBe('back');
+ expect(panes.current(pane('b'))?.id).toBe('5');
+ expect(panes.arrival(pane('b'))).toBe('fresh');
+ expect(removed).toEqual(['c']);
+ });
+
+ it('asks the policy with the panes as they are now', () => {
+ const requests: unknown[] = [];
+ const { panes } = setup({
+ placeNewPane: (request): Placement => {
+ requests.push(request);
+ return { pane: pane('a') };
+ },
+ closeAction: (request) => {
+ requests.push(request);
+ return { type: 'keep' };
+ },
+ });
+ panes.insert(pane('a'), card('1'), 0);
+ expect(panes.placeNewPane({ destination: 'doc' })).toEqual({
+ pane: 'a',
+ });
+ expect(panes.closeAction(pane('a'))).toEqual({ type: 'keep' });
+ expect(requests).toEqual([
+ {
+ destination: 'doc',
+ intent: {},
+ allowDuplicate: false,
+ opening: 0,
+ panes: ['a'],
+ },
+ { pane: 'a', panes: ['a'] },
+ ]);
+ });
+});
diff --git a/apps/web/src/lib/split-router/next/tests/router.test.ts b/apps/web/src/lib/split-router/next/tests/router.test.ts
new file mode 100644
index 0000000000..72be178686
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/tests/router.test.ts
@@ -0,0 +1,1313 @@
+import { createEffect, createRoot, untrack } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createMemoryHistory } from '../history/memory';
+import { createSolidRouterHistory } from '../history/solid-router';
+import type { HistoryAdapter } from '../history/types';
+import { createMemoryPaneStore } from '../panes/memory-store';
+import { createSplitRouter } from '../router/create-router';
+import { PANE_LEVEL } from '../router/leave-guards';
+import type { SplitCloseAction, SplitRouterOptions } from '../router/types';
+import { defineRoute } from '../routes/define';
+import type {
+ Entry,
+ PaneId,
+ SplitLocation,
+ SplitRoutes,
+} from '../routes/types';
+import { isPromise } from '../utils';
+import { createFakeSolidRouter } from './fake-solid-router';
+import { appRoutes, createTestPolicy, homeLocation } from './fixtures';
+
+function setup(
+ url: string,
+ overrides: Partial<SplitRouterOptions> = {},
+ testPolicy = createTestPolicy()
+) {
+ const history = createMemoryHistory(url);
+ const paneStore = createMemoryPaneStore<Entry>();
+ const { policy, activated, placements } = testPolicy;
+ let created = 0;
+ const { router, dispose } = createRoot((dispose) => ({
+ router: createSplitRouter({
+ routes: appRoutes,
+ history,
+ paneStore,
+ policy,
+ createPaneId: () => `pane-${++created}` as PaneId,
+ ...overrides,
+ }),
+ dispose,
+ }));
+ return {
+ router,
+ history,
+ paneStore,
+ activated,
+ placements,
+ pane: (index: number) => router.panes()[index]!,
+ dispose: () => {
+ router.dispose();
+ dispose();
+ },
+ };
+}
+
+/** A router over the Solid Router fake mounted at `/app`. */
+function setupSolid(url: string, ahead: readonly string[] = []) {
+ const solid = createFakeSolidRouter(url, ahead);
+ return createRoot((dispose) => {
+ const router = createSplitRouter({
+ routes: appRoutes,
+ history: createSolidRouterHistory({
+ location: solid.location,
+ navigate: solid.navigate,
+ base: '/app',
+ owns: () => true,
+ beforeLeave: solid.beforeLeave,
+ landedPath: solid.landed,
+ }),
+ paneStore: createMemoryPaneStore(),
+ policy: createTestPolicy().policy,
+ });
+ return {
+ router,
+ solid,
+ dispose: () => {
+ router.dispose();
+ dispose();
+ },
+ };
+ });
+}
+
+/** Memory history whose reverts land only when the test says so. */
+function slowRevertHistory(url: string) {
+ const history = createMemoryHistory(url);
+ const landings: (() => void)[] = [];
+ const adapter: HistoryAdapter = {
+ ...history,
+ subscribe: (listener) =>
+ history.subscribe((change) =>
+ listener({
+ ...change,
+ revert: () =>
+ new Promise<void>((resolve) => {
+ landings.push(() => {
+ void change.revert();
+ resolve();
+ });
+ }),
+ })
+ ),
+ };
+
+ const landAll = async () => {
+ for (let attempt = 0; attempt < 8; attempt += 1) {
+ landings.shift()?.();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ }
+ };
+
+ return { history, adapter, landAll };
+}
+
+const routeIds = (entry: Entry | undefined) =>
+ entry?.location.route.matches.map((match) => match.id);
+const location = (id: string, params = {}): SplitLocation => ({
+ route: { matches: [{ id, params }] },
+});
+const never = () => new Promise<boolean>(() => {});
+
+let cleanup: (() => void) | undefined;
+const track = <T extends { dispose: () => void }>(context: T) => {
+ cleanup = context.dispose;
+ return context;
+};
+
+afterEach(() => {
+ cleanup?.();
+ cleanup = undefined;
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe('split router', () => {
+ it('starts ready with one pane per URL segment and records pane state in place', () => {
+ const { router, history } = track(setup('/mail/t1/~/drive'));
+ expect(router.ready()).toBe(true);
+ expect(router.panes()).toEqual(['pane-1', 'pane-2']);
+ expect(history.entries()).toHaveLength(1);
+ expect(history.read().state?.panes.map((pane) => pane.pane)).toEqual([
+ 'pane-1',
+ 'pane-2',
+ ]);
+ });
+
+ it('navigates one pane without touching the others', () => {
+ const { router, history, pane } = track(setup('/home/~/drive'));
+ const drive = router.entry(pane(1));
+
+ const result = router.navigate(pane(0), '/mail/t1');
+ expect(result).toEqual({ status: 'committed', pane: pane(0) });
+ expect(router.entry(pane(1))).toBe(drive);
+ expect(router.arrival(pane(1))).toBe('fresh');
+ expect(history.entries().map((entry) => entry.path)).toEqual([
+ '/home/~/drive',
+ '/mail/t1/~/drive',
+ ]);
+ });
+
+ it('pane back replaces the browser entry and records how the pane arrived', () => {
+ const { router, history, pane } = track(setup('/home'));
+ router.navigate(pane(0), '/mail');
+ router.navigate(pane(0), -1);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);
+ expect(router.arrival(pane(0))).toBe('back');
+ expect(router.canGo(pane(0), 1)).toBe(true);
+ expect(history.entries().map((entry) => entry.path)).toEqual([
+ '/home',
+ '/home',
+ ]);
+ });
+
+ it('browser back brings a pane back through its own history', () => {
+ const { router, history, paneStore, pane } = track(setup('/home/~/drive'));
+ router.navigate(pane(0), '/mail');
+ const drive = router.entry(pane(1));
+ history.back();
+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);
+ expect(router.arrival(pane(0))).toBe('back');
+ expect(paneStore.read(pane(0))).toMatchObject({ index: 0 });
+ expect(paneStore.read(pane(0))?.entries).toHaveLength(2);
+ expect(router.entry(pane(1))).toBe(drive);
+ });
+
+ it('a leave guard can refuse browser back, and the URL is put back', () => {
+ const { router, history, pane } = track(setup('/home'));
+ router.navigate(pane(0), '/mail');
+ router.registerGuard(pane(0), 0, () => false);
+ history.back();
+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);
+ expect(history.index()).toBe(1);
+ expect(history.read().path).toBe('/mail');
+ });
+
+ it('ignores the report of its own revert landing', async () => {
+ vi.useFakeTimers();
+ const { router, solid } = track(setupSolid('/app/home'));
+ vi.runAllTimers();
+ const pane = router.panes()[0]!;
+ router.navigate(pane, '/mail');
+ vi.runAllTimers();
+ const mail = router.entry(pane);
+ router.registerGuard(pane, 0, () => false);
+
+ solid.traverse(-1);
+ await new Promise<void>((resolve) => queueMicrotask(resolve));
+ vi.runAllTimers();
+ expect(router.entry(pane)).toBe(mail);
+ expect(solid.calls.map(([to]) => to)).toEqual(['/home', '/mail', 1]);
+ expect(solid.location.pathname).toBe('/app/mail');
+ });
+
+ it('keeps an async-guarded navigation pending until the guard settles', async () => {
+ const { router, pane } = track(setup('/home'));
+ let allow: (value: boolean) => void = () => {};
+ router.registerGuard(
+ pane(0),
+ 0,
+ () =>
+ new Promise<boolean>((resolve) => {
+ allow = resolve;
+ })
+ );
+ const result = router.navigate(pane(0), '/mail');
+ expect(isPromise(result)).toBe(true);
+ expect(routeIds(router.pending(pane(0))?.to)).toEqual(['mail']);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);
+ allow(true);
+ await expect(result).resolves.toMatchObject({ status: 'committed' });
+ expect(router.pending(pane(0))).toBeUndefined();
+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);
+ });
+
+ it('a newer navigation in the same pane supersedes a pending one', async () => {
+ const { router, pane } = track(
+ setup('/home', {
+ middleware: [
+ async ({ path }) => {
+ if (path === '/mail')
+ await new Promise((done) => setTimeout(done, 10));
+ },
+ ],
+ })
+ );
+ expect(router.ready()).toBe(false);
+ await router.settled();
+ expect(router.ready()).toBe(true);
+ const first = router.navigate(pane(0), '/mail');
+ const second = router.navigate(pane(0), '/drive');
+ await expect(first).resolves.toEqual({ status: 'cancelled' });
+ await expect(second).resolves.toMatchObject({ status: 'committed' });
+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);
+ });
+
+ it('a superseded navigation settles even when its guard never does', async () => {
+ const { router, pane } = track(setup('/home'));
+ const unregister = router.registerGuard(pane(0), 0, never);
+ const first = router.navigate(pane(0), '/mail');
+ unregister();
+ const second = router.navigate(pane(0), '/drive');
+ await expect(first).resolves.toEqual({ status: 'cancelled' });
+ expect(second).toMatchObject({ status: 'committed' });
+ });
+
+ it('ignores a superseded navigation whose guard answers late', async () => {
+ const { router, pane } = track(setup('/home'));
+ const answers: ((allowed: boolean) => void)[] = [];
+ router.registerGuard(
+ pane(0),
+ 0,
+ () => new Promise<boolean>((resolve) => answers.push(resolve))
+ );
+ const first = router.navigate(pane(0), '/mail');
+ const second = router.navigate(pane(0), '/drive');
+ answers[0]!(true);
+ answers[1]!(false);
+ await expect(first).resolves.toEqual({ status: 'cancelled' });
+ await expect(second).resolves.toEqual({ status: 'cancelled' });
+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);
+ });
+
+ it('browser back cancels a pane navigation still in flight', async () => {
+ const { router, history, pane } = track(setup('/home'));
+ router.navigate(pane(0), '/mail');
+ let allow: (allowed: boolean) => void = () => {};
+ router.registerGuard(pane(0), 0, ({ cause }) =>
+ cause === 'external'
+ ? true
+ : new Promise<boolean>((resolve) => {
+ allow = resolve;
+ })
+ );
+ const drive = router.navigate(pane(0), '/drive');
+ history.back();
+ allow(true);
+ await expect(drive).resolves.toEqual({ status: 'cancelled' });
+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);
+ });
+
+ it('mounts the URL even when middleware cancels the initial load', () => {
+ const { router, pane } = track(
+ setup('/mail', { middleware: [({ cancel }) => cancel()] })
+ );
+ expect(router.ready()).toBe(true);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);
+ });
+
+ it('settles commands waiting on the initial load when disposed', async () => {
+ const { router, dispose } = setup('/home', {
+ middleware: [() => new Promise<void>(() => {})],
+ });
+ const opened = router.open('/mail', { newPane: true });
+ dispose();
+ await expect(opened).resolves.toEqual({ status: 'cancelled' });
+ });
+
+ it('waits for an async initial load before opening a pane', async () => {
+ const { router } = track(
+ setup('/home/~/drive', { middleware: [async () => {}] })
+ );
+ expect(router.ready()).toBe(false);
+ const opened = router.open('/mail', { newPane: true });
+ await expect(opened).resolves.toEqual({
+ status: 'committed',
+ pane: 'pane-3',
+ });
+ expect(router.ready()).toBe(true);
+ expect(router.panes()).toEqual(['pane-1', 'pane-2', 'pane-3']);
+ });
+
+ it('drops commands still waiting on a revert once disposed', async () => {
+ vi.useFakeTimers();
+ const { router, solid } = track(setupSolid('/app/home'));
+ vi.runAllTimers();
+ const pane = router.panes()[0]!;
+ router.navigate(pane, '/mail');
+ vi.runAllTimers();
+ router.registerGuard(pane, 0, never);
+ solid.traverse(-1);
+
+ const rewrite = router.rewriteCurrent(pane, '/drive');
+ router.move(pane, 0);
+ router.dispose();
+ await expect(rewrite).resolves.toEqual({ status: 'cancelled' });
+ vi.runAllTimers();
+ expect(solid.calls.map(([to]) => to)).toEqual(['/home', '/mail', 1]);
+ });
+
+ it('a pane command cancels a pending browser back and reverts it first', () => {
+ const { router, history, pane } = track(setup('/home/~/drive'));
+ router.navigate(pane(0), '/mail');
+ let guardSignal: AbortSignal | undefined;
+ router.registerGuard(pane(0), 0, ({ signal }) => {
+ guardSignal = signal;
+ return never();
+ });
+ history.back();
+ expect(routeIds(router.pending(pane(0))?.to)).toEqual(['home']);
+
+ expect(router.navigate(pane(1), '/drive/folder/f1')).toMatchObject({
+ status: 'committed',
+ });
+ expect(guardSignal?.aborted).toBe(true);
+ expect(router.pending(pane(0))).toBeUndefined();
+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);
+ expect(history.entries().map((entry) => entry.path)).toEqual([
+ '/home/~/drive',
+ '/mail/~/drive',
+ '/mail/~/drive/folder/f1',
+ ]);
+ expect(history.index()).toBe(2);
+ });
+
+ it('writes after the reverted back has landed', async () => {
+ vi.useFakeTimers();
+ const { router, solid } = track(setupSolid('/app/home'));
+ vi.runAllTimers();
+ const pane = router.panes()[0]!;
+ router.navigate(pane, '/mail');
+ vi.runAllTimers();
+ router.registerGuard(pane, 0, ({ cause }) =>
+ cause === 'external' ? never() : true
+ );
+ solid.traverse(-1);
+ expect(routeIds(router.pending(pane)?.to)).toEqual(['home']);
+
+ const result = router.navigate(pane, '/drive');
+ expect(isPromise(result)).toBe(true);
+ await expect(result).resolves.toMatchObject({ status: 'committed' });
+ vi.runAllTimers();
+ expect(solid.calls.map(([to]) => to)).toEqual([
+ '/home',
+ '/mail',
+ 1,
+ '/drive',
+ ]);
+ expect(solid.entries().map((entry) => entry.path)).toEqual([
+ '/app/home',
+ '/app/mail',
+ '/app/drive',
+ ]);
+ });
+
+ it('reports a pending URL navigation only for the panes it changes', async () => {
+ let slow = false;
+ const { router, history, pane } = track(
+ setup('/home/~/drive', {
+ middleware: [
+ ({ path }) =>
+ slow && path === '/home'
+ ? new Promise<void>((done) => setTimeout(done, 5))
+ : undefined,
+ ],
+ })
+ );
+ router.navigate(pane(0), '/mail');
+ slow = true;
+ history.back();
+ expect(routeIds(router.pending(pane(0))?.to)).toEqual(['home']);
+ expect(router.pending(pane(1))).toBeUndefined();
+ await router.settled();
+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);
+ });
+
+ it('opening something another pane shows activates that pane instead', () => {
+ const { router, activated, pane } = track(setup('/drive/md/d1/~/home'));
+ const result = router.navigate(pane(1), '/md/d1');
+ expect(result).toEqual({ status: 'activated', owner: pane(0) });
+ expect(activated).toEqual([pane(0)]);
+ expect(routeIds(router.entry(pane(1)))).toEqual(['home']);
+ expect(
+ router.navigate(pane(1), '/md/d1', { allowDuplicate: true })
+ ).toMatchObject({ status: 'committed' });
+ });
+
+ it('tells the policy who shows a new pane’s destination and whether a duplicate is allowed', () => {
+ const testPolicy = createTestPolicy();
+ const { router, pane } = track(setup('/md/d1/~/home', {}, testPolicy));
+ const target = { newPane: true as const, source: pane(1) };
+
+ router.open('/md/d1', target, { allowDuplicate: true });
+
+ expect(testPolicy.placements).toMatchObject([
+ { holder: pane(0), allowDuplicate: true },
+ ]);
+ });
+
+ it('opens a new pane beside the one showing the destination when the policy places it there', () => {
+ const { router, activated, pane } = track(setup('/md/d1/~/home'));
+
+ const result = router.open('/md/d1', { newPane: true, source: pane(1) });
+
+ expect(result).toMatchObject({ status: 'committed' });
+ expect(router.panes()).toHaveLength(3);
+ expect(activated).toEqual([]);
+ });
+
+ it('brings up a pane that started showing a new pane’s destination after it was placed', async () => {
+ let release: () => void = () => {};
+ let held = false;
+ const holdFirstVisit = ({ path }: { path: string }) => {
+ if (path !== '/md/d1' || held) return;
+
+ held = true;
+
+ return new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ };
+ const { router, pane } = track(
+ setup('/home/~/drive', { middleware: [holdFirstVisit] })
+ );
+
+ const opened = router.open('/md/d1', { newPane: true, source: pane(1) });
+ router.navigate(pane(0), '/md/d1');
+ release();
+
+ await expect(opened).resolves.toEqual({
+ status: 'activated',
+ owner: pane(0),
+ });
+ expect(router.panes()).toHaveLength(2);
+ });
+
+ it('skips entries another pane shows on Back and Forward, unless duplicates are allowed', () => {
+ const { router, pane } = track(setup('/home/~/home'));
+ router.navigate(pane(0), '/md/d1');
+ router.navigate(pane(0), '/drive');
+ router.navigate(pane(1), '/md/d1');
+
+ router.navigate(pane(0), -1);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);
+ expect(router.canGo(pane(0), 1)).toBe(true);
+
+ router.navigate(pane(0), 1, { allowDuplicate: true });
+ expect(routeIds(router.entry(pane(0)))).toEqual(['block']);
+ });
+
+ it('keeps duplicates loaded from a URL', () => {
+ const { router } = track(setup('/md/d1/~/md/d1'));
+ expect(router.panes()).toHaveLength(2);
+ });
+
+ it('changing search in a duplicate keeps it in place', () => {
+ const { router, activated, pane } = track(
+ setup('/drive/md/d1/~/drive/md/d1')
+ );
+ expect(
+ router.updateSearch(pane(1), 'drive', { sort: ['name'] })
+ ).toMatchObject({ status: 'committed', pane: pane(1) });
+ expect(activated).toEqual([]);
+ });
+
+ it('browser back brings back a duplicate', () => {
+ const { router, history, activated, pane } = track(setup('/home/~/md/d1'));
+ router.navigate(pane(0), '/md/d1', { allowDuplicate: true });
+ router.navigate(pane(0), '/drive');
+ history.back();
+ expect(routeIds(router.entry(pane(0)))).toEqual(['block']);
+ expect(activated).toEqual([]);
+ });
+
+ it('opens and closes panes where the policy places them', () => {
+ const { router, history } = track(setup('/home/~/drive'));
+ expect(
+ router.open('/mail', {
+ newPane: true,
+ source: 'pane-1' as PaneId,
+ })
+ ).toEqual({ status: 'committed', pane: 'pane-3' });
+ expect(router.panes()).toEqual(['pane-1', 'pane-3', 'pane-2']);
+ expect(history.read().path).toBe('/home/~/mail/~/drive');
+
+ expect(router.open('/home', { pane: 'pane-3' as PaneId })).toEqual({
+ status: 'committed',
+ pane: 'pane-3',
+ });
+ expect(router.close('pane-3' as PaneId)).toBe(true);
+ expect(router.close('pane-2' as PaneId)).toBe(true);
+ expect(router.panes()).toEqual(['pane-1']);
+ expect(history.read().path).toBe('/home');
+
+ expect(router.close('pane-1' as PaneId)).toBe(false);
+ router.navigate('pane-1' as PaneId, '/mail');
+ expect(router.close('pane-1' as PaneId)).toBe(true);
+ expect(router.panes()).toEqual(['pane-1']);
+ expect(history.read().path).toBe('/home');
+ });
+
+ it('opens several panes at once without one cancelling another', async () => {
+ const { router } = track(
+ setup('/home', {
+ middleware: [
+ ({ path }) => (path === '/home' ? undefined : Promise.resolve()),
+ ],
+ })
+ );
+ const source = 'pane-1' as PaneId;
+ const first = router.open('/mail', { newPane: true, source });
+ const second = router.open('/drive', { newPane: true, source });
+ await expect(first).resolves.toEqual({
+ status: 'committed',
+ pane: 'pane-2',
+ });
+ await expect(second).resolves.toEqual({
+ status: 'committed',
+ pane: 'pane-3',
+ });
+ expect(router.panes()).toEqual(['pane-1', 'pane-2', 'pane-3']);
+ });
+
+ it('lets the policy open in an existing pane when enough are open', () => {
+ const testPolicy = createTestPolicy({ maxPanes: 2 });
+ const { router } = track(setup('/home/~/drive', {}, testPolicy));
+ const intent = { replaceWhenFull: true };
+ expect(
+ router.open('/mail', {
+ newPane: true,
+ source: 'pane-2' as PaneId,
+ intent,
+ })
+ ).toEqual({ status: 'committed', pane: 'pane-2' });
+ expect(router.panes()).toEqual(['pane-1', 'pane-2']);
+ expect(routeIds(router.entry('pane-2' as PaneId))).toEqual(['mail']);
+ expect(testPolicy.placements).toEqual([
+ {
+ destination: location('mail'),
+ source: 'pane-2',
+ intent,
+ allowDuplicate: false,
+ opening: 0,
+ panes: ['pane-1', 'pane-2'],
+ },
+ ]);
+ });
+
+ it('keeps a pane the policy pins, without asking its guards', () => {
+ const { router } = track(
+ setup(
+ '/home/~/mail',
+ {},
+ createTestPolicy({ pinned: ['pane-1' as PaneId] })
+ )
+ );
+ const guard = vi.fn(() => true);
+ router.registerGuard('pane-1' as PaneId, 0, guard);
+ expect(router.close('pane-1' as PaneId)).toBe(false);
+ expect(router.panes()).toEqual(['pane-1', 'pane-2']);
+ expect(guard).not.toHaveBeenCalled();
+ });
+
+ it('closing the last pane can go back to an earlier entry', () => {
+ const closeLast: SplitCloseAction = {
+ type: 'back-to',
+ to: (entry) => routeIds(entry)?.[0] === 'mail',
+ otherwise: { type: 'navigate', destination: homeLocation, replace: true },
+ };
+ const { router, pane } = track(
+ setup('/mail', {}, createTestPolicy({ closeLast }))
+ );
+ router.navigate(pane(0), '/drive');
+ expect(router.close(pane(0))).toBe(true);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);
+ expect(router.canGo(pane(0), 1)).toBe(true);
+ });
+
+ it('closing the last pane can replace it without a back entry', () => {
+ const closeLast: SplitCloseAction = {
+ type: 'back-to',
+ to: (entry) => routeIds(entry)?.[0] === 'mail',
+ otherwise: { type: 'navigate', destination: homeLocation, replace: true },
+ };
+ const { router, history, pane } = track(
+ setup('/drive', {}, createTestPolicy({ closeLast }))
+ );
+ expect(router.close(pane(0))).toBe(true);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);
+ expect(router.canGo(pane(0), -1)).toBe(false);
+ expect(history.entries()).toHaveLength(1);
+ });
+
+ it('keeps the hash of the URL it follows through a redirect', () => {
+ const { history } = track(
+ setup('/home#focus', {
+ middleware: [
+ ({ path, redirect }) =>
+ path === '/home' ? redirect('/mail') : undefined,
+ ],
+ })
+ );
+ expect(history.read()).toMatchObject({ path: '/mail', hash: '#focus' });
+ });
+
+ it('writes an outside navigation with its own hash and global search', async () => {
+ const { history } = track(setup('/home?referral_code=old#top'));
+ await history.navigate('/mail/t2?referral_code=new#frag');
+ expect(history.read()).toMatchObject({
+ path: '/mail/t2',
+ search: '?referral_code=new',
+ hash: '#frag',
+ });
+ });
+
+ it('a leave guard can keep a pane open', () => {
+ const { router } = track(setup('/home/~/mail'));
+ router.registerGuard('pane-2' as PaneId, 0, () => false);
+ expect(router.close('pane-2' as PaneId)).toBe(false);
+ expect(router.panes()).toHaveLength(2);
+ });
+
+ it('shows the catch-all route in an unmatched pane and loads the others', () => {
+ const { router, pane } = track(setup('/mail/t1/~/no/such'));
+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail', 'mail-thread']);
+ expect(routeIds(router.entry(pane(1)))).toEqual(['not-found']);
+ });
+
+ it('takes over outside navigations into the panes', async () => {
+ const { router, history, pane } = track(setup('/home'));
+ await expect(history.navigate('/mail/t2')).resolves.toBe(false);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail', 'mail-thread']);
+ expect(history.entries().map((entry) => entry.path)).toEqual([
+ '/home',
+ '/mail/t2',
+ ]);
+ });
+
+ it('commits in the same tick without data preloads and waits for them within a budget', async () => {
+ const preload = vi.fn(() => new Promise(() => {}));
+ const routes: SplitRoutes = {
+ ...appRoutes,
+ definitions: [
+ ...appRoutes.definitions,
+ defineRoute({ id: 'slow', path: 'slow', preload }),
+ ],
+ };
+ const { router, pane } = track(
+ setup('/home', { routes, preloadBudgetMs: 5 })
+ );
+ expect(isPromise(router.navigate(pane(0), '/mail'))).toBe(false);
+
+ const result = router.navigate(pane(0), '/slow');
+ expect(isPromise(result)).toBe(true);
+ expect(preload).toHaveBeenCalledWith(
+ expect.objectContaining({ intent: 'navigate', params: {} })
+ );
+ await expect(result).resolves.toMatchObject({ status: 'committed' });
+ expect(routeIds(router.entry(pane(0)))).toEqual(['slow']);
+ });
+
+ it('logs a preload that throws and still navigates', () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const routes: SplitRoutes = {
+ ...appRoutes,
+ definitions: [
+ ...appRoutes.definitions,
+ defineRoute({
+ id: 'broken',
+ path: 'broken',
+ preload: () => {
+ throw new Error('boom');
+ },
+ }),
+ ],
+ };
+ const { router, pane } = track(setup('/home', { routes }));
+ expect(router.navigate(pane(0), '/broken')).toEqual({
+ status: 'committed',
+ pane: pane(0),
+ });
+ expect(error).toHaveBeenCalledWith(
+ 'Split route "broken" preload failed',
+ expect.any(Error)
+ );
+ });
+
+ it('writes search as a new entry or in place', () => {
+ const { router, history, pane } = track(setup('/drive'));
+ const first = router.entry(pane(0))!.id;
+ router.updateSearch(
+ pane(0),
+ 'drive',
+ { sort: ['name'] },
+ { history: 'replace' }
+ );
+ expect(router.entry(pane(0))!.id).toBe(first);
+ expect(history.read().search).toBe('?s0.drive.sort=name');
+ expect(history.entries()).toHaveLength(1);
+
+ router.updateSearch(pane(0), 'drive', { sort: ['date'] });
+ expect(router.entry(pane(0))!.id).not.toBe(first);
+ expect(history.entries()).toHaveLength(2);
+ });
+
+ it('jumps back to the nearest matching entry', () => {
+ const { router, pane } = track(setup('/home'));
+ router.navigate(pane(0), '/mail');
+ router.navigate(pane(0), '/drive');
+ expect(
+ router.goBackTo(pane(0), (entry) => routeIds(entry)?.[0] === 'home')
+ ).toBe(true);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);
+ expect(router.goBackTo(pane(0), () => true)).toBe(false);
+ });
+
+ it('removing entries cancels a pending traversal in that pane', async () => {
+ const { router, pane } = track(setup('/home'));
+ router.navigate(pane(0), '/mail');
+ router.navigate(pane(0), '/drive');
+ router.registerGuard(pane(0), 0, never);
+ const back = router.navigate(pane(0), -1);
+ expect(routeIds(router.pending(pane(0))?.to)).toEqual(['mail']);
+
+ const isMail = (entry: Entry) => routeIds(entry)?.[0] === 'mail';
+ expect(router.removeEntries(pane(0), isMail)).toBe(true);
+ await expect(back).resolves.toEqual({ status: 'cancelled' });
+ expect(router.pending(pane(0))).toBeUndefined();
+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);
+ expect(router.canGo(pane(0), -1)).toBe(true);
+ expect(router.removeEntries(pane(0), isMail)).toBe(false);
+ });
+
+ it('rewrites the current entry in place', () => {
+ const { router, history, pane } = track(setup('/md/draft'));
+ const id = router.entry(pane(0))!.id;
+ router.rewriteCurrent(pane(0), '/md/real');
+ expect(router.entry(pane(0))!.id).toBe(id);
+ expect(history.read().path).toBe('/md/real');
+ expect(history.entries()).toHaveLength(1);
+ });
+
+ it('builds a single-pane href', () => {
+ const { router, pane } = track(setup('/home/~/mail/t1'));
+ expect(router.href(pane(1))).toBe('/mail/t1');
+ });
+});
+
+describe('split router while other work is in flight', () => {
+ it('keeps the entry an outside navigation came from when the new view redirects in place', async () => {
+ const { router, history, pane } = track(setup('/home'));
+ const stopRedirecting = createRoot((dispose) => {
+ createEffect(() => {
+ const showsDrive = routeIds(router.entry(pane(0)))?.[0] === 'drive';
+ if (!showsDrive) return;
+
+ untrack(() => router.navigate(pane(0), '/mail', { replace: true }));
+ });
+
+ return dispose;
+ });
+
+ await history.navigate('/drive');
+ await router.settled();
+ stopRedirecting();
+
+ expect(history.entries().map((entry) => entry.path)).toEqual([
+ '/home',
+ '/mail',
+ ]);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);
+ });
+
+ it('lets an outside navigation replace an async initial load, then runs the open waiting on it', async () => {
+ const { router, history, pane } = track(
+ setup('/home', { middleware: [async () => {}] })
+ );
+ const opened = router.open('/mail', { newPane: true });
+ void history.navigate('/drive');
+
+ await expect(opened).resolves.toMatchObject({ status: 'committed' });
+ await router.settled();
+ expect(router.ready()).toBe(true);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);
+ expect(routeIds(router.entry(pane(1)))).toEqual(['mail']);
+ });
+
+ it('holds an open that follows an outside navigation during the initial load', async () => {
+ const { router, history } = track(
+ setup('/home', { middleware: [async () => {}] })
+ );
+ void history.navigate('/drive');
+ const opened = router.open('/mail', { newPane: true });
+
+ await expect(opened).resolves.toMatchObject({ status: 'committed' });
+ await router.settled();
+ expect(router.ready()).toBe(true);
+ expect(router.panes().map((id) => routeIds(router.entry(id))?.[0])).toEqual(
+ ['drive', 'mail']
+ );
+ });
+
+ it('asks guards registered above the first route before closing the pane', () => {
+ const { router, pane } = track(setup('/home/~/mail'));
+ router.registerGuard(pane(1), PANE_LEVEL, () => false);
+
+ expect(router.close(pane(1))).toBe(false);
+ expect(router.panes()).toHaveLength(2);
+ });
+
+ it('puts the URL back past every Back that a refused Back replaced', async () => {
+ const { router, history, pane } = track(setup('/home'));
+ router.navigate(pane(0), '/mail');
+ router.navigate(pane(0), '/drive');
+ const answers: ((allowed: boolean) => void)[] = [];
+ router.registerGuard(pane(0), 0, ({ cause }) => {
+ if (cause !== 'external') return true;
+
+ return new Promise<boolean>((resolve) => answers.push(resolve));
+ });
+
+ history.back();
+ history.back();
+ answers[1]!(false);
+ await router.settled();
+
+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);
+ expect(history.index()).toBe(2);
+ expect(history.read().path).toBe('/drive');
+ });
+
+ it('cancels the pending departure of a pane it activates for a claim', async () => {
+ const { router, activated, pane } = track(setup('/md/d1/~/home'));
+ let leave: (allowed: boolean) => void = () => {};
+ router.registerGuard(
+ pane(0),
+ 0,
+ () =>
+ new Promise<boolean>((resolve) => {
+ leave = resolve;
+ })
+ );
+
+ const departure = router.navigate(pane(0), '/drive');
+ expect(router.navigate(pane(1), '/md/d1')).toEqual({
+ status: 'activated',
+ owner: pane(0),
+ });
+ leave(true);
+
+ await expect(departure).resolves.toEqual({ status: 'cancelled' });
+ expect(routeIds(router.entry(pane(0)))).toEqual(['block']);
+ expect(activated).toEqual([pane(0)]);
+ });
+
+ it('carries the search a navigation asked for to the pane already showing its resource', async () => {
+ const { router, activated, pane } = track(setup('/drive/md/d1/~/home'));
+
+ expect(
+ router.navigate(pane(1), '/drive/md/d1', {
+ search: { drive: { sort: ['name'] } },
+ })
+ ).toEqual({ status: 'activated', owner: pane(0) });
+ await router.settled();
+
+ expect(activated).toEqual([pane(0)]);
+ expect(router.entry(pane(0))?.location.search).toEqual({
+ drive: { sort: ['name'] },
+ });
+ expect(routeIds(router.entry(pane(1)))).toEqual(['home']);
+ });
+
+ it('keeps an owner’s pending navigation that stays on the claimed resource', async () => {
+ let release: () => void = () => {};
+ const { router, pane } = track(
+ setup('/drive/md/d1/~/home', {
+ middleware: [
+ ({ cause }) => {
+ if (cause !== 'search') return;
+
+ return new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ },
+ ],
+ })
+ );
+ await router.settled();
+
+ const sorting = router.updateSearch(pane(0), 'drive', { sort: ['date'] });
+ router.navigate(pane(1), '/drive/md/d1');
+ release();
+
+ await expect(sorting).resolves.toMatchObject({ status: 'committed' });
+ expect(router.entry(pane(0))?.location.search).toEqual({
+ drive: { sort: ['date'] },
+ });
+ });
+
+ it('counts opens still in flight against the policy’s limit', async () => {
+ const { router } = track(
+ setup(
+ '/home',
+ {
+ middleware: [
+ ({ path }) => (path === '/home' ? undefined : Promise.resolve()),
+ ],
+ },
+ createTestPolicy({ maxPanes: 2 })
+ )
+ );
+ const source = 'pane-1' as PaneId;
+
+ const first = router.open('/mail', { newPane: true, source });
+ const second = router.open('/drive', { newPane: true, source });
+ await Promise.all([first, second]);
+
+ expect(router.panes()).toHaveLength(2);
+ });
+
+ it('turns down a location it cannot write, leaving the pane and later writes intact', () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const { router, history, pane } = track(setup('/drive'));
+ const tooLong = 'x'.repeat(17_000);
+
+ expect(router.updateSearch(pane(0), 'drive', { sort: [tooLong] })).toEqual({
+ status: 'cancelled',
+ });
+ expect(
+ router.rewriteCurrent(pane(0), { route: { id: 'missing' } })
+ ).toEqual({
+ status: 'cancelled',
+ });
+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);
+ expect(router.entry(pane(0))?.location.search).toBeUndefined();
+
+ expect(router.navigate(pane(0), '/mail')).toMatchObject({
+ status: 'committed',
+ });
+ expect(history.read().path).toBe('/mail');
+ expect(error).toHaveBeenCalled();
+ expect(error).not.toHaveBeenCalledWith(
+ 'Split router could not commit a navigation',
+ expect.anything()
+ );
+ });
+
+ it('drops a search value from the URL that is too long to write back', () => {
+ const tooLong = 'x'.repeat(17_000);
+ const { router, pane } = track(setup(`/drive?s0.drive.sort=${tooLong}`));
+
+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);
+ expect(router.entry(pane(0))?.location.search).toBeUndefined();
+ });
+
+ it('reports a refused jump back as false, and a back-to close then keeps the pane', async () => {
+ const closeLast: SplitCloseAction = {
+ type: 'back-to',
+ to: (entry) => routeIds(entry)?.[0] === 'home',
+ otherwise: {
+ type: 'navigate',
+ destination: location('mail'),
+ replace: true,
+ },
+ };
+ const { router, pane } = track(
+ setup('/home', {}, createTestPolicy({ closeLast }))
+ );
+ router.navigate(pane(0), '/drive');
+ router.registerGuard(pane(0), 0, ({ to }) => routeIds(to)?.[0] !== 'home');
+
+ const isHome = (entry: Entry) => routeIds(entry)?.[0] === 'home';
+ expect(await router.goBackTo(pane(0), isHome)).toBe(false);
+ expect(await router.close(pane(0))).toBe(false);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);
+ });
+
+ it('turns down a close action that leads to no route', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const closeLast: SplitCloseAction = {
+ type: 'navigate',
+ destination: location('missing'),
+ };
+ const { router, history, pane } = track(
+ setup('/drive', {}, createTestPolicy({ closeLast }))
+ );
+
+ expect(await router.close(pane(0))).toBe(false);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive']);
+ expect(history.read().path).toBe('/drive');
+ expect(error).toHaveBeenCalledWith(
+ 'Split router close action leads to no route',
+ closeLast.destination
+ );
+ });
+
+ it('writes a replace another pane makes while one commits after that commit’s push', async () => {
+ const { router, history, pane } = track(setup('/home/~/home'));
+ const stopRedirecting = createRoot((dispose) => {
+ createEffect(() => {
+ const showsDrive = routeIds(router.entry(pane(0)))?.[0] === 'drive';
+ if (!showsDrive) return;
+
+ untrack(() => router.navigate(pane(1), '/mail', { replace: true }));
+ });
+
+ return dispose;
+ });
+
+ router.navigate(pane(0), '/drive');
+ await router.settled();
+ stopRedirecting();
+
+ expect(history.entries().map((entry) => entry.path)).toEqual([
+ '/home/~/home',
+ '/drive/~/mail',
+ ]);
+ });
+
+ it('keeps a Back whose view redirects in place as it mounts', async () => {
+ const { router, history, pane } = track(setup('/drive'));
+ router.navigate(pane(0), '/mail');
+ let armed = false;
+ const stopRedirecting = createRoot((dispose) => {
+ createEffect(() => {
+ const showsDrive = routeIds(router.entry(pane(0)))?.[0] === 'drive';
+ const redirects = armed && showsDrive;
+ if (!redirects) return;
+
+ untrack(() => router.navigate(pane(0), '/home', { replace: true }));
+ });
+
+ return dispose;
+ });
+ armed = true;
+
+ history.back();
+ await router.settled();
+ stopRedirecting();
+
+ expect(history.index()).toBe(0);
+ expect(history.entries().map((entry) => entry.path)).toEqual([
+ '/home',
+ '/mail',
+ ]);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);
+ });
+
+ it('keeps navigating after the history adapter fails a write', () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const history = createMemoryHistory('/home');
+ let failNext = false;
+ const flaky: HistoryAdapter = {
+ ...history,
+ write(location, writeOptions) {
+ if (failNext) {
+ failNext = false;
+ throw new Error('write failed');
+ }
+
+ history.write(location, writeOptions);
+ },
+ };
+ const { router, pane } = track(setup('/home', { history: flaky }));
+
+ failNext = true;
+ expect(router.navigate(pane(0), '/mail')).toEqual({ status: 'cancelled' });
+ expect(router.navigate(pane(0), '/drive')).toMatchObject({
+ status: 'committed',
+ });
+ expect(history.read().path).toBe('/drive');
+ expect(error).toHaveBeenCalledWith(
+ 'Split router could not commit a navigation',
+ expect.any(Error)
+ );
+ });
+
+ it('settles a URL navigation that arrives while an earlier one is being put back', async () => {
+ const { history, adapter, landAll } = slowRevertHistory('/home');
+ const { router, pane } = track(setup('/home', { history: adapter }));
+ router.navigate(pane(0), '/mail');
+ router.navigate(pane(0), '/drive');
+ router.registerGuard(pane(0), 0, ({ cause }) =>
+ cause === 'external' ? never() : true
+ );
+
+ history.back();
+ const navigated = router.navigate(pane(0), '/drive/folder/f1');
+ history.back();
+ await landAll();
+
+ await expect(navigated).resolves.toMatchObject({ status: 'committed' });
+ await expect(router.settled()).resolves.toBeUndefined();
+ expect(history.read().path).toBe('/drive/folder/f1');
+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive', 'drive-folder']);
+ });
+
+ it('puts back a Back that arrives while others are put back before them', async () => {
+ const { history, adapter, landAll } = slowRevertHistory('/home');
+ const { router, pane } = track(setup('/home', { history: adapter }));
+ router.navigate(pane(0), '/mail');
+ router.navigate(pane(0), '/drive');
+ router.navigate(pane(0), '/md/d1');
+ let refuse: () => void = () => {};
+ router.registerGuard(pane(0), 0, ({ cause }) => {
+ if (cause !== 'external') return true;
+
+ return new Promise<boolean>((resolve) => {
+ refuse = () => resolve(false);
+ });
+ });
+
+ history.back();
+ history.back();
+ refuse();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ history.back();
+ await landAll();
+ await router.settled();
+
+ expect(history.index()).toBe(3);
+ expect(history.read().path).toBe('/md/d1');
+ expect(routeIds(router.entry(pane(0)))).toEqual(['block']);
+ });
+
+ it('opens a pane that already shows the destination by activating it', () => {
+ const { router, activated, pane } = track(setup('/mail/t1/~/home'));
+
+ expect(router.open('/mail/t1', { pane: pane(0) })).toEqual({
+ status: 'activated',
+ owner: pane(0),
+ });
+ expect(activated).toEqual([pane(0)]);
+ });
+
+ it('checks again before running a waiting action that a new Back overtook', async () => {
+ const { router, history, pane, paneStore } = track(setup('/home'));
+ router.navigate(pane(0), '/mail');
+ let allow: (allowed: boolean) => void = () => {};
+ router.registerGuard(pane(0), 0, ({ cause }) => {
+ if (cause !== 'external') return true;
+
+ return new Promise<boolean>((resolve) => {
+ allow = resolve;
+ });
+ });
+ let redirected = false;
+ const stopRedirecting = createRoot((dispose) => {
+ createEffect(() => {
+ const showsDrive = routeIds(router.entry(pane(0)))?.[0] === 'drive';
+ const redirects = showsDrive && !redirected;
+ if (!redirects) return;
+
+ redirected = true;
+ untrack(() =>
+ router.navigate(pane(0), '/drive/folder/f1', { replace: true })
+ );
+ });
+
+ return dispose;
+ });
+
+ router.navigate(pane(0), '/drive');
+ history.back();
+ await Promise.resolve();
+ await Promise.resolve();
+ allow(true);
+ await router.settled();
+ stopRedirecting();
+
+ expect(routeIds(router.entry(pane(0)))).toEqual(['drive', 'drive-folder']);
+ expect(history.index()).toBe(2);
+ expect(history.read().path).toBe('/drive/folder/f1');
+ expect(paneStore.read(pane(0))?.index).toBe(2);
+ });
+
+ it('writes the URL again after the history adapter failed to write it', () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const history = createMemoryHistory('/home');
+ let failNext = false;
+ const flaky: HistoryAdapter = {
+ ...history,
+ write(location, writeOptions) {
+ if (failNext) {
+ failNext = false;
+ throw new Error('write failed');
+ }
+
+ history.write(location, writeOptions);
+ },
+ };
+ const { router, pane } = track(setup('/home', { history: flaky }));
+
+ failNext = true;
+ router.navigate(pane(0), '/mail');
+ router.rewriteCurrent(pane(0), '/mail');
+
+ expect(history.read().path).toBe('/mail');
+ });
+
+ it('ignores a host location outside the router’s base', () => {
+ vi.useFakeTimers();
+ const { router, solid } = track(setupSolid('/app/mail'));
+ vi.runAllTimers();
+
+ solid.show('/elsewhere', undefined);
+ vi.runAllTimers();
+
+ expect(routeIds(router.entry(router.panes()[0]!))).toEqual(['mail']);
+ });
+
+ it('drops a URL write still queued when the router is disposed', () => {
+ vi.useFakeTimers();
+ const { router, solid, dispose } = setupSolid('/app/home');
+ vi.runAllTimers();
+
+ router.navigate(router.panes()[0]!, '/mail');
+ dispose();
+ vi.runAllTimers();
+
+ expect(solid.calls.map(([to]) => to)).toEqual(['/home']);
+ });
+
+ it('asks leave guards when Back or Forward leaves the router’s routes', () => {
+ vi.useFakeTimers();
+ const { router, solid } = track(setupSolid('/app/home', ['/settings']));
+ vi.runAllTimers();
+ const guard = vi.fn(() => false);
+ router.registerGuard(router.panes()[0]!, 0, guard);
+
+ expect(solid.pop(1).defaultPrevented).toBe(true);
+ expect(guard).toHaveBeenCalledTimes(1);
+ expect(solid.landed()).toBe('/app/home');
+
+ guard.mockReturnValue(true);
+ expect(solid.pop(1).defaultPrevented).toBe(false);
+ expect(solid.landed()).toBe('/settings');
+ });
+
+ it('drops a queued write when a navigation leaves the router’s routes', () => {
+ vi.useFakeTimers();
+ const { router, solid } = track(setupSolid('/app/home'));
+ vi.runAllTimers();
+
+ router.navigate(router.panes()[0]!, '/mail');
+ expect(solid.leave('/settings').defaultPrevented).toBe(false);
+ vi.runAllTimers();
+
+ expect(solid.calls.map(([to]) => to)).toEqual(['/home']);
+ });
+
+ it('moves the cursor on Back to an entry that looks like the current one', () => {
+ const { router, history, paneStore, pane } = track(setup('/home'));
+ router.navigate(pane(0), '/home', { props: { note: 1 } });
+ expect(paneStore.read(pane(0))?.entries).toHaveLength(2);
+
+ history.back();
+ expect(paneStore.read(pane(0))?.index).toBe(0);
+ expect(router.canGo(pane(0), -1)).toBe(false);
+
+ history.forward();
+ expect(paneStore.read(pane(0))?.index).toBe(1);
+ expect(router.arrival(pane(0))).toBe('forward');
+ });
+});
diff --git a/apps/web/src/lib/split-router/next/tests/routes.test.ts b/apps/web/src/lib/split-router/next/tests/routes.test.ts
new file mode 100644
index 0000000000..33024b7994
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/tests/routes.test.ts
@@ -0,0 +1,304 @@
+import { describe, expect, it } from 'vitest';
+import {
+ decodePanes,
+ encodePanes,
+ formatPanePath,
+ splitPanePaths,
+} from '../routes/codec';
+import { defineRoute } from '../routes/define';
+import {
+ canonicalRoute,
+ createRoutesManifest,
+ decodePane,
+ formatPane,
+} from '../routes/manifest';
+import { compileRoutePattern } from '../routes/path';
+import { claimOf, externalSearchKeys, ownsNamespace } from '../routes/queries';
+import { resolveTarget } from '../routes/targets';
+import type { PaneId, SplitLocation, SplitRouteState } from '../routes/types';
+import {
+ appRoutes,
+ documentRoute,
+ driveRoute,
+ folderRoute,
+ mailRoute,
+ notFoundRoute,
+} from './fixtures';
+
+const routes = createRoutesManifest(appRoutes);
+const ids = (route: SplitRouteState | undefined) =>
+ route?.matches.map((match) => match.id);
+const at = (path: string): SplitLocation => ({
+ route: decodePane(routes, path.split('/').filter(Boolean))!,
+});
+
+describe('route matching', () => {
+ it('prefers specific routes regardless of declaration order', () => {
+ expect(ids(decodePane(routes, ['mail', 't1']))).toEqual([
+ 'mail',
+ 'mail-thread',
+ ]);
+ expect(ids(decodePane(routes, ['md', 'doc']))).toEqual(['block']);
+ expect(ids(decodePane(routes, ['drive', 'md', 'doc']))).toEqual([
+ 'drive',
+ 'drive-document',
+ ]);
+ expect(ids(decodePane(routes, ['drive', 'folder']))).toEqual([
+ 'drive',
+ 'drive-folder',
+ ]);
+ expect(decodePane(routes, ['drive', 'folder', 'f1'])?.matches[1]).toEqual({
+ id: 'drive-folder',
+ params: { folderId: 'f1' },
+ });
+ });
+
+ it('moves to the next branch when a params schema rejects the match', () => {
+ expect(ids(decodePane(routes, ['drive', 'garbage']))).toEqual([
+ 'not-found',
+ ]);
+ expect(ids(decodePane(routes, ['video', 'x']))).toEqual(['not-found']);
+ });
+
+ it('matches static segments case-insensitively and formats the declared casing', () => {
+ const route = decodePane(routes, ['DRIVE', 'Folder']);
+ expect(ids(route)).toEqual(['drive', 'drive-folder']);
+ expect(formatPane(routes, route!)).toEqual(['drive', 'folder']);
+ });
+
+ it('ranks a nested catch-all above the root catch-all', () => {
+ const driveMissing = defineRoute({ id: 'drive-missing', path: '*rest' });
+ const nested = createRoutesManifest({
+ ...appRoutes,
+ definitions: [
+ notFoundRoute,
+ { ...driveRoute, children: [folderRoute, documentRoute, driveMissing] },
+ ],
+ });
+ expect(ids(decodePane(nested, ['drive', 'garbage']))).toEqual([
+ 'drive',
+ 'drive-missing',
+ ]);
+ expect(ids(decodePane(nested, ['elsewhere']))).toEqual(['not-found']);
+ });
+
+ it('expands adjacent optional params into prefixes only', () => {
+ const pattern = compileRoutePattern({ path: 'a/:b?/:c?' });
+ expect(pattern.alternatives.map((tokens) => tokens.length)).toEqual([
+ 1, 2, 3,
+ ]);
+ });
+
+ it('rejects invalid declarations', () => {
+ const home = defineRoute({ id: 'home', path: 'home' });
+ expect(() =>
+ createRoutesManifest({ ...appRoutes, definitions: [home, home] })
+ ).toThrow(/Duplicate split route id/);
+ expect(() =>
+ createRoutesManifest({
+ ...appRoutes,
+ definitions: [home, defineRoute({ id: 'other', path: '/home/' })],
+ })
+ ).toThrow(/Duplicate sibling split route path/);
+ expect(() =>
+ createRoutesManifest({
+ ...appRoutes,
+ definitions: [defineRoute({ id: 'bad', path: '*rest/after' })],
+ })
+ ).toThrow(/catch-all/);
+ });
+});
+
+describe('route queries', () => {
+ it('uses the deepest claim and falls back to ancestors', () => {
+ expect(claimOf(routes, at('/drive/md/d1').route)).toBe('block:md:d1');
+ expect(claimOf(routes, at('/mail/t1').route)).toBe('block:email:t1');
+ expect(claimOf(routes, at('/mail').route)).toBeUndefined();
+ });
+
+ it('restricts search only where a route lists namespaces', () => {
+ const drive = at('/drive/folder/f1').route;
+ expect(ownsNamespace(routes, drive, 'drive')).toBe(true);
+ expect(ownsNamespace(routes, drive, 'mail')).toBe(false);
+ expect(ownsNamespace(routes, at('/mail/t1').route, 'anything')).toBe(true);
+ });
+
+ it('keeps global and route-owned unprefixed search keys', () => {
+ const withExternal = createRoutesManifest({
+ ...appRoutes,
+ definitions: [
+ ...appRoutes.definitions,
+ defineRoute({ id: 'pdf', path: 'viewer', externalSearch: ['page'] }),
+ ],
+ });
+ const keys = externalSearchKeys(withExternal, [
+ { id: 'e', location: { route: decodePane(withExternal, ['viewer'])! } },
+ ]);
+ expect([...keys].sort()).toEqual(['page', 'referral_code']);
+ });
+});
+
+describe('panes codec', () => {
+ it('decodes each pane on its own, so one unmatched pane is not found', () => {
+ const decoded = decodePanes(routes, {
+ path: '/mail/t1/~/no/such/place/~/drive',
+ search: '',
+ hash: '',
+ });
+ expect(decoded.panes.map((pane) => ids(pane.entry.location.route))).toEqual(
+ [['mail', 'mail-thread'], ['not-found'], ['drive']]
+ );
+ expect(decoded.panes[1]!.entry.location.route.matches[0].params).toEqual({
+ segments: ['no', 'such', 'place'],
+ });
+ });
+
+ it('falls back to the default route for a pane only when nothing matches', () => {
+ const strict = createRoutesManifest({
+ ...appRoutes,
+ definitions: [mailRoute, defineRoute({ id: 'home', path: 'home' })],
+ });
+ const decoded = decodePanes(strict, {
+ path: '/mail/t1/~/unknown',
+ search: '',
+ hash: '',
+ });
+ expect(decoded.panes.map((pane) => ids(pane.entry.location.route))).toEqual(
+ [['mail', 'mail-thread'], ['home']]
+ );
+ expect(
+ ids(
+ decodePanes(strict, { path: '/', search: '', hash: '' }).panes[0]!.entry
+ .location.route
+ )
+ ).toEqual(['home']);
+ });
+
+ it('reads pane and entry ids back only when the pane count matches', () => {
+ const state = {
+ panes: [
+ { pane: 'p1' as PaneId, entry: 'e1' },
+ { pane: 'p2' as PaneId, entry: 'e2' },
+ ],
+ };
+ const matching = decodePanes(routes, {
+ path: '/home/~/mail',
+ search: '',
+ hash: '',
+ state,
+ });
+ expect(matching.panes.map((pane) => [pane.paneId, pane.entry.id])).toEqual([
+ ['p1', 'e1'],
+ ['p2', 'e2'],
+ ]);
+ const mismatched = decodePanes(routes, {
+ path: '/home',
+ search: '',
+ hash: '',
+ state,
+ });
+ expect(mismatched.panes[0]!.paneId).toBeUndefined();
+ });
+
+ it('frames search by pane and drops namespaces a route does not own', () => {
+ const decoded = decodePanes(routes, {
+ path: '/drive/~/mail',
+ search: '?s0.drive.sort=name&s0.other.x=1&s1.mail.tab=inbox',
+ hash: '',
+ });
+ expect(decoded.panes.map((pane) => pane.entry.location.search)).toEqual([
+ { drive: { sort: ['name'] } },
+ { mail: { tab: ['inbox'] } },
+ ]);
+ });
+
+ it('encodes panes, keeps owned unprefixed keys, and keeps the hash while the path is unchanged', () => {
+ const entry = {
+ id: 'e1',
+ location: {
+ ...at('/drive/folder/f1'),
+ search: { drive: { sort: ['name'] } },
+ },
+ };
+ const mail = { id: 'e2', location: at('/mail/t1') };
+ const encoded = encodePanes(
+ routes,
+ [
+ { paneId: 'p1' as PaneId, entry },
+ { paneId: 'p2' as PaneId, entry: mail },
+ ],
+ {
+ path: '/drive/folder/f1/~/mail/t1',
+ search: '?referral_code=r&junk=1',
+ hash: '#h',
+ }
+ );
+ expect(encoded).toEqual({
+ path: '/drive/folder/f1/~/mail/t1',
+ search: '?referral_code=r&s0.drive.sort=name',
+ hash: '#h',
+ state: {
+ panes: [
+ { pane: 'p1', entry: 'e1' },
+ { pane: 'p2', entry: 'e2' },
+ ],
+ },
+ });
+ expect(
+ encodePanes(routes, [{ paneId: 'p2' as PaneId, entry: mail }], encoded)
+ .hash
+ ).toBe('');
+ });
+
+ it('escapes a literal separator value so it round-trips', () => {
+ const route = canonicalRoute(routes, {
+ matches: [{ id: 'block', params: { type: 'md', id: '~' } }],
+ })!;
+ const path = formatPanePath(routes, route);
+ expect(path).toBe('/md/%7E');
+ expect(splitPanePaths(path)).toEqual([['md', '%7E']]);
+ expect(
+ decodePanes(routes, { path, search: '', hash: '' }).panes[0]!.entry
+ .location.route.matches[0].params
+ ).toEqual({ type: 'md', id: '~' });
+ });
+});
+
+describe('target resolution', () => {
+ const folder: SplitLocation = {
+ ...at('/drive/folder/f1'),
+ search: { drive: { sort: ['name'] } },
+ };
+
+ it('resolves relative paths against the calling route', () => {
+ expect(
+ ids(resolveTarget(routes, folder, 'md/d1', { depth: 1 })?.route)
+ ).toEqual(['drive', 'drive-document']);
+ expect(
+ resolveTarget(routes, folder, '../f2', { depth: 2 })?.route.matches[1]
+ ).toEqual({ id: 'drive-folder', params: { folderId: 'f2' } });
+ expect(ids(resolveTarget(routes, folder, '/mail/t2')?.route)).toEqual([
+ 'mail',
+ 'mail-thread',
+ ]);
+ });
+
+ it('inherits ancestor params and carries search only within the same root', () => {
+ const document = resolveTarget(routes, folder, {
+ route: documentRoute,
+ params: { documentType: 'md', documentId: 'd1' },
+ });
+ expect(ids(document?.route)).toEqual(['drive', 'drive-document']);
+ expect(document?.search).toEqual({ drive: { sort: ['name'] } });
+ expect(
+ resolveTarget(routes, folder, { route: mailRoute })?.search
+ ).toBeUndefined();
+ });
+
+ it('applies search updates and drops namespaces the destination does not own', () => {
+ const location = resolveTarget(routes, folder, '/drive', {
+ search: { drive: { view: ['grid'] }, mail: { tab: ['x'] } },
+ });
+ expect(location?.search).toEqual({ drive: { view: ['grid'] } });
+ });
+});
diff --git a/apps/web/src/lib/split-router/next/tests/solid.test.tsx b/apps/web/src/lib/split-router/next/tests/solid.test.tsx
new file mode 100644
index 0000000000..4d08f75ff3
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/tests/solid.test.tsx
@@ -0,0 +1,319 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { createEffect, For, type JSX, onCleanup, onMount } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { z } from 'zod';
+import { createMemoryHistory, type MemoryHistory } from '../history/memory';
+import { createMemoryPaneStore } from '../panes/memory-store';
+import { createSplitRouter, type SplitRouter } from '../router/create-router';
+import { defineRoute } from '../routes/define';
+import type { PaneId, SplitRoutes } from '../routes/types';
+import { SplitRouterProvider } from '../solid/context';
+import { createSearchParams } from '../solid/create-search-params';
+import {
+ useCanGo,
+ useMatches,
+ useNavigate,
+ usePane,
+ usePendingNavigation,
+ useRouteParams,
+} from '../solid/hooks';
+import { Outlet } from '../solid/outlet';
+import { PaneScope } from '../solid/pane-scope';
+import { useBeforeLeave } from '../solid/use-before-leave';
+import { createTestPolicy } from './fixtures';
+
+const counts = { drive: 0, document: 0 };
+const documentTypeReads = vi.fn();
+let allowLeave = true;
+
+const documentRoute = defineRoute({
+ id: 'document',
+ path: ':documentType/:documentId',
+ params: z.object({
+ documentType: z.enum(['md', 'pdf']),
+ documentId: z.string().min(1),
+ }),
+ remountKey: ({ documentType }) => documentType,
+ component: DocumentView,
+});
+
+function DocumentView() {
+ const params = useRouteParams(documentRoute);
+ onMount(() => {
+ counts.document += 1;
+ });
+ createEffect(() => documentTypeReads(params.documentType));
+ return (
+ <p data-testid="document">{`${params.documentType}:${params.documentId}`}</p>
+ );
+}
+
+function DriveView() {
+ const navigate = useNavigate();
+ onMount(() => {
+ counts.drive += 1;
+ });
+ return (
+ <div>
+ <button type="button" onClick={() => navigate('md/d3')}>
+ relative
+ </button>
+ <Outlet />
+ </div>
+ );
+}
+
+function GuardedView() {
+ useBeforeLeave(() => allowLeave);
+ return <p data-testid="guarded">guarded</p>;
+}
+
+function ListView() {
+ const [search, setSearch] = createSearchParams({
+ namespace: 'list',
+ schema: z.object({ sort: z.enum(['name', 'date']) }),
+ defaults: { sort: 'name' as 'name' | 'date' },
+ });
+ return (
+ <button type="button" onClick={() => setSearch({ sort: 'date' })}>
+ {`sort:${search.sort}`}
+ </button>
+ );
+}
+
+const runs: Record<string, number> = {};
+const bump = (key: string) => {
+ runs[key] = (runs[key] ?? 0) + 1;
+};
+
+/** Counts every reader a search change could wake, per pane. */
+function ProbeView() {
+ const pane = usePane();
+ const [probe, setProbe] = createSearchParams({
+ namespace: 'probe',
+ schema: z.object({
+ sort: z.enum(['name', 'date']),
+ tags: z.array(z.string()),
+ }),
+ defaults: { sort: 'name' as 'name' | 'date', tags: ['all'] },
+ });
+ const [other] = createSearchParams({
+ namespace: 'other',
+ schema: z.object({ tab: z.enum(['a', 'b']) }),
+ defaults: { tab: 'a' as 'a' | 'b' },
+ });
+ const matches = useMatches();
+ const pending = usePendingNavigation();
+ const canGoForward = useCanGo(1);
+ const count = (reader: string) => bump(`${pane()}:${reader}`);
+
+ onMount(() => count('mount'));
+ createEffect(() => count(`sort=${probe.sort}`));
+ createEffect(() => count(`tags=${probe.tags.join()}`));
+ createEffect(() => count(`tab=${other.tab}`));
+ createEffect(() => count(`matches=${matches().length}`));
+ createEffect(() => count(`pending=${pending()?.phase ?? 'none'}`));
+ createEffect(() => count(`canGo=${canGoForward()}`));
+
+ const toggle = () => {
+ const sort = probe.sort === 'name' ? 'date' : 'name';
+
+ setProbe({ sort }, { history: 'replace' });
+ };
+
+ return (
+ <button type="button" onClick={toggle}>
+ {`probe:${pane()}`}
+ </button>
+ );
+}
+
+const routes: SplitRoutes = {
+ definitions: [
+ defineRoute({
+ id: 'drive',
+ path: 'drive',
+ component: DriveView,
+ children: [documentRoute],
+ }),
+ defineRoute({
+ id: 'probe',
+ path: 'probe',
+ search: ['probe', 'other'],
+ component: ProbeView,
+ }),
+ defineRoute({ id: 'home', path: 'home', component: () => <p>home</p> }),
+ defineRoute({ id: 'guarded', path: 'guarded', component: GuardedView }),
+ defineRoute({
+ id: 'list',
+ path: 'list',
+ search: ['list'],
+ component: ListView,
+ }),
+ ],
+ defaultRoute: () => ({ matches: [{ id: 'home', params: {} }] }),
+};
+
+function PanelHeader() {
+ const matches = useMatches();
+ const canGoBack = useCanGo(-1);
+ const trail = () => matches().map((match) => match.id);
+
+ return (
+ <header data-testid="header">
+ {`${trail().join('/')} back:${canGoBack()}`}
+ </header>
+ );
+}
+
+function GuardedChrome() {
+ useBeforeLeave(() => allowLeave);
+
+ return null;
+}
+
+function Panel(props: { pane: PaneId }) {
+ return (
+ <PaneScope pane={props.pane}>
+ <PanelHeader />
+ <Outlet />
+ </PaneScope>
+ );
+}
+
+function renderPanes(
+ url: string,
+ renderPane: (pane: PaneId) => JSX.Element = (pane) => <Outlet pane={pane} />
+) {
+ const history: MemoryHistory = createMemoryHistory(url);
+ let router: SplitRouter | undefined;
+ render(() => {
+ const created = createSplitRouter({
+ routes,
+ history,
+ paneStore: createMemoryPaneStore(),
+ policy: createTestPolicy().policy,
+ });
+ router = created;
+ onCleanup(() => created.dispose());
+ return (
+ <SplitRouterProvider router={created}>
+ <For each={created.panes()}>{renderPane}</For>
+ </SplitRouterProvider>
+ );
+ });
+ return { history, router: router! };
+}
+
+beforeEach(() => {
+ counts.drive = 0;
+ counts.document = 0;
+ documentTypeReads.mockClear();
+ allowLeave = true;
+
+ for (const key of Object.keys(runs)) {
+ delete runs[key];
+ }
+});
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('split router Solid bindings', () => {
+ it('keeps a view mounted while its remount key holds and updates params in place', () => {
+ const { router } = renderPanes('/drive/md/d1');
+ const pane = router.panes()[0]!;
+ expect(screen.getByTestId('document').textContent).toBe('md:d1');
+
+ router.navigate(pane, '/drive/md/d2');
+ expect(screen.getByTestId('document').textContent).toBe('md:d2');
+ expect(counts).toEqual({ drive: 1, document: 1 });
+ expect(documentTypeReads).toHaveBeenCalledTimes(1);
+
+ router.navigate(pane, '/drive/pdf/d2');
+ expect(counts).toEqual({ drive: 1, document: 2 });
+ });
+
+ it('lets panel chrome around a prop-less outlet use the hooks', () => {
+ const { router } = renderPanes('/drive/md/d1', (pane) => (
+ <Panel pane={pane} />
+ ));
+ const pane = router.panes()[0]!;
+ expect(screen.getByTestId('header').textContent).toBe(
+ 'drive/document back:false'
+ );
+ expect(screen.getByTestId('document').textContent).toBe('md:d1');
+
+ router.navigate(pane, '/home');
+ expect(screen.getByTestId('header').textContent).toBe('home back:true');
+ expect(screen.getByText('home')).toBeTruthy();
+ });
+
+ it('asks a guard in pane chrome before the pane closes, not on navigations inside it', async () => {
+ const { router } = renderPanes('/home/~/drive/md/d1', (pane) => (
+ <PaneScope pane={pane}>
+ <GuardedChrome />
+ <Outlet />
+ </PaneScope>
+ ));
+ const second = router.panes()[1]!;
+ allowLeave = false;
+
+ expect(router.navigate(second, '/home')).toMatchObject({
+ status: 'committed',
+ });
+ expect(await router.close(second)).toBe(false);
+
+ allowLeave = true;
+ expect(await router.close(second)).toBe(true);
+ expect(router.panes()).toHaveLength(1);
+ });
+
+ it('re-runs only the readers of the search field that changed', () => {
+ let paneRenders = 0;
+ const { router } = renderPanes('/probe/~/probe', (pane) => {
+ paneRenders += 1;
+
+ return <Outlet pane={pane} />;
+ });
+ const [first, second] = router.panes();
+ const before = { ...runs };
+
+ fireEvent.click(screen.getByText(`probe:${first}`));
+
+ const woken = Object.keys(runs).filter((key) => runs[key] !== before[key]);
+ expect(woken).toEqual([`${first}:sort=date`]);
+ expect(paneRenders).toBe(2);
+ expect(runs[`${second}:mount`]).toBe(1);
+ });
+
+ it('resolves relative paths against the calling route', () => {
+ renderPanes('/drive/md/d1');
+ fireEvent.click(screen.getByText('relative'));
+ expect(screen.getByTestId('document').textContent).toBe('md:d3');
+ });
+
+ it('runs leave guards before unmounting a view but not for search changes', () => {
+ const { router, history } = renderPanes('/guarded');
+ const pane = router.panes()[0]!;
+ allowLeave = false;
+ router.navigate(pane, '/home');
+ expect(screen.getByTestId('guarded')).toBeTruthy();
+ router.updateSearch(pane, 'anything', { x: ['1'] });
+ expect(history.read().search).toBe('?s0.anything.x=1');
+ allowLeave = true;
+ router.navigate(pane, '/home');
+ expect(screen.queryByTestId('guarded')).toBeNull();
+ });
+
+ it('reads and writes one search namespace and rewrites invalid values', () => {
+ const { history } = renderPanes('/list?s0.list.sort=bogus');
+ expect(screen.getByRole('button').textContent).toBe('sort:name');
+ expect(history.read().search).toBe('');
+ fireEvent.click(screen.getByRole('button'));
+ expect(screen.getByRole('button').textContent).toBe('sort:date');
+ expect(history.read().search).toBe('?s0.list.sort=date');
+ });
+});
diff --git a/apps/web/src/lib/split-router/next/utils.ts b/apps/web/src/lib/split-router/next/utils.ts
new file mode 100644
index 0000000000..137aa6059a
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/utils.ts
@@ -0,0 +1,110 @@
+const SAFE_NAME = /^[A-Za-z][A-Za-z0-9_-]*$/;
+const MAX_NAME_LENGTH = 64;
+
+/** Bounded identifier that is safe to use as an ordinary object key. */
+export function isSafeName(value: string): boolean {
+ const reserved = value === 'constructor' || value === 'prototype';
+ const bounded = value.length <= MAX_NAME_LENGTH;
+
+ return bounded && !reserved && SAFE_NAME.test(value);
+}
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ const isObject = value !== null && typeof value === 'object';
+
+ return isObject && !Array.isArray(value);
+}
+
+/** For work nothing can call off, such as hover preloads; it never aborts. */
+export const UNCANCELLABLE: AbortSignal = new AbortController().signal;
+
+export function isAbortError(error: unknown, signal?: AbortSignal): boolean {
+ if (signal?.aborted) return true;
+
+ return error instanceof DOMException && error.name === 'AbortError';
+}
+
+let fallbackSequence = 0;
+
+export function createId(prefix: string): string {
+ const random = globalThis.crypto?.randomUUID?.();
+ if (random) return `${prefix}_${random}`;
+
+ fallbackSequence += 1;
+ const time = Date.now().toString(36);
+ const sequence = fallbackSequence.toString(36);
+
+ return `${prefix}_${time}${sequence}`;
+}
+
+/** A value now, or later; only real promises leave the current tick. */
+export type MaybePromise<T> = T | Promise<T>;
+
+export function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
+ return value instanceof Promise;
+}
+
+/** Applies `fn` now, or once `value` settles. */
+export function mapMaybe<T, R>(
+ value: MaybePromise<T>,
+ fn: (value: T) => MaybePromise<R>
+): MaybePromise<R> {
+ if (!isPromise(value)) return fn(value);
+
+ return value.then(fn);
+}
+
+/** Runs `run`, turning a synchronous throw or a rejection into `onError`'s result. */
+export function settleMaybe<T>(
+ run: () => MaybePromise<T>,
+ onError: (error: unknown) => T
+): MaybePromise<T> {
+ let value: MaybePromise<T>;
+
+ try {
+ value = run();
+ } catch (error) {
+ return onError(error);
+ }
+
+ if (!isPromise(value)) return value;
+
+ return value.catch(onError);
+}
+
+export const CANCELLED: unique symbol = Symbol('split-router.cancelled');
+
+export type Cancelled = typeof CANCELLED;
+
+/** A value, possibly async, or `CANCELLED` when the work was called off. */
+export type Outcome<T> = MaybePromise<T | Cancelled>;
+
+/**
+ * The next step, skipped once cancelled. Not named `then`: a module
+ * exporting `then` is a thenable, which breaks `await import()`.
+ */
+export function andThen<T, R>(
+ value: Outcome<T>,
+ step: (value: T) => Outcome<R>
+): Outcome<R> {
+ return mapMaybe(value, (resolved): Outcome<R> => {
+ if (resolved === CANCELLED) return CANCELLED;
+
+ return step(resolved);
+ });
+}
+
+function unlessCancelled<T>(
+ resolved: readonly (T | Cancelled)[]
+): T[] | Cancelled {
+ if (resolved.includes(CANCELLED)) return CANCELLED;
+
+ return resolved as T[];
+}
+
+export function all<T>(values: readonly Outcome<T>[]): Outcome<T[]> {
+ const waiting = values.some(isPromise);
+ if (!waiting) return unlessCancelled(values as (T | Cancelled)[]);
+
+ return mapMaybe(Promise.all(values), unlessCancelled);
+}