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(split-router): add route-owned history state (#6920)

dev-rb7ba96f947057
diff --git a/apps/web/src/components/app/split-layout/SplitLayout.tsx b/apps/web/src/components/app/split-layout/SplitLayout.tsx
index a3c3a56d98..5564101100 100644
--- a/apps/web/src/components/app/split-layout/SplitLayout.tsx
+++ b/apps/web/src/components/app/split-layout/SplitLayout.tsx
@@ -62,6 +62,7 @@ export function SplitLayoutContainer(props: SplitLayoutContainerProps) {
pathname: () => `/${props.pairs.join('/')}`,
search: () => location.search,
hash: () => location.hash,
+ state: () => location.state,
navigate,
});
const [, setTabTitle] = tabTitleSignal;
diff --git a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts
index 02a0022fe4..4dfbe42db9 100644
--- a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts
+++ b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts
@@ -268,9 +268,11 @@ export function resolveContentLocation(
routes: SplitRoutesManifest,
content: SplitContent
): SplitLocation {
- const metadata = isRecord(content.entryMetadata)
- ? content.entryMetadata
- : undefined;
+ let metadata: Record<string, unknown> | undefined;
+ if (isRecord(content.entryMetadata)) metadata = content.entryMetadata;
+
+ let metadataLocation = metadata;
+ if (isRecord(metadata?.location)) metadataLocation = metadata.location;
const resolve = (route: unknown) => {
assertRouteState(routes, route);
// Go through the URL representation, not schema validation of schema outputs.
@@ -290,9 +292,9 @@ export function resolveContentLocation(
return decoded.location.route;
};
let route: SplitLocation['route'] | undefined;
- if (metadata?.route !== undefined) {
+ if (metadataLocation?.route !== undefined) {
try {
- route = resolve(metadata.route);
+ route = resolve(metadataLocation.route);
} catch {
// Old or malformed metadata falls back to the content's compatibility route.
}
@@ -301,9 +303,11 @@ export function resolveContentLocation(
const search = filterRouteSearch(
routes,
route,
- parseSearchState(metadata?.search)
+ parseSearchState(metadataLocation?.search)
);
- return search ? { route, search } : { route };
+ const location: SplitLocation = { route };
+ if (search) location.search = search;
+ return location;
}
export function splitContentFromLocation(
diff --git a/apps/web/src/components/app/split-layout/splitRouterLayout.ts b/apps/web/src/components/app/split-layout/splitRouterLayout.ts
index b8f4ebecf4..ba4f5afc4a 100644
--- a/apps/web/src/components/app/split-layout/splitRouterLayout.ts
+++ b/apps/web/src/components/app/split-layout/splitRouterLayout.ts
@@ -1,6 +1,5 @@
import type {
BrowserHistoryIntent,
- SplitLocation,
SplitRouterEntry,
SplitRouterLayout,
SplitRouterLayoutSnapshot,
@@ -17,32 +16,18 @@ import {
export type AppSplitRouterLayout = SplitRouterLayout<SplitId>;
type AppSplitRouterSnapshot = SplitRouterLayoutSnapshot<SplitId>;
-const withoutLocation = (content: SplitContent): SplitContent => {
- const result = { ...content };
-
- delete result.entryMetadata;
-
- return result;
-};
-
-const withLocation = (
- content: SplitContent,
- location: SplitLocation
-): SplitContent => ({
- ...content,
- entryMetadata: location,
-});
-
-const sameContent = (left: SplitContent, right: SplitContent) =>
- left.type === right.type && left.id === right.id;
-
function contentForLocation(
- location: SplitLocation,
+ location: SplitRouterEntry['location'],
current?: SplitContent
): SplitContent {
const routed = splitContentFromLocation(location);
- const content = current && sameContent(current, routed) ? current : routed;
- return withLocation(withoutLocation(content), location);
+ let source = routed;
+ if (current?.type === routed.type && current.id === routed.id) {
+ source = current;
+ }
+ const { entryMetadata: _entryMetadata, ...content } = source;
+
+ return { ...content, entryMetadata: location };
}
const sameRouterEntries = (
@@ -53,11 +38,9 @@ const sameRouterEntries = (
previous.every((entry, index) => {
const next = current[index];
- return (
- next !== undefined &&
- Object.is(entry.splitId, next.splitId) &&
- deepEqual(entry.location, next.location)
- );
+ if (!next) return false;
+ if (!Object.is(entry.splitId, next.splitId)) return false;
+ return deepEqual(entry.location, next.location);
});
function changeHistory(
@@ -81,54 +64,67 @@ export function createAppSplitRouterLayout(
manager: SplitManager,
routes: SplitRoutesManifest
): AppSplitRouterLayout {
- const locationOf = (content: SplitContent) =>
- resolveContentLocation(routes, content);
const snapshot = (): AppSplitRouterSnapshot => ({
entries: manager.getVisibleSplits().map((split) => ({
splitId: split.id,
- location: locationOf(split.content),
+ location: resolveContentLocation(routes, split.content),
})),
});
return {
snapshot,
- updateCurrentEntry(splitId, update) {
+ updateCurrentLocation(splitId, update) {
const handle = manager.getSplit(splitId);
if (!handle) return;
- const current = locationOf(handle.content());
+ const current = resolveContentLocation(routes, handle.content());
const next = update({ splitId, location: current });
// Child routes keep the workspace mounted but can dispose its list.
// Capture list focus/scroll before committing that accepted transition.
- if (!deepEqual(current.route, next.location.route)) {
+ if (!deepEqual(current.route, next.route)) {
handle.captureEntryState();
}
- handle.updateCurrentEntry((content) =>
- contentForLocation(next.location, content)
- );
+ handle.updateCurrentEntry((content) => contentForLocation(next, content));
},
open({ location, target, replace }) {
- const handle =
- target && target !== 'new-split' ? manager.getSplit(target) : undefined;
+ let handle: ReturnType<SplitManager['getSplit']>;
+ if (target && target !== 'new-split') {
+ handle = manager.getSplit(target);
+ }
- manager.openWithSplit(contentForLocation(location), {
+ const result = manager.openWithSplit(contentForLocation(location), {
handle,
preferNewSplit: target === 'new-split',
allowDuplicate: target === 'new-split',
mergeHistory: replace,
referredFrom: null,
});
+ if (!result.split) return { status: 'unavailable' };
+
+ const appliedLocation = resolveContentLocation(
+ routes,
+ result.split.content()
+ );
+ if (!deepEqual(appliedLocation, location)) {
+ if (!deepEqual(appliedLocation.route, location.route)) {
+ result.split.captureEntryState();
+ }
+ result.split.updateCurrentEntry((content) =>
+ contentForLocation(location, content)
+ );
+ }
+ return { status: 'applied', splitId: result.split.id };
},
- reconcile(entries) {
+ reconcile(locations) {
for (const [index, split] of manager.getVisibleSplits().entries()) {
if (
!deepEqual(
- locationOf(split.content).route,
- entries[index]?.location.route
+ resolveContentLocation(routes, split.content).route,
+ locations[index]?.route
)
) {
manager.getSplit(split.id)?.captureEntryState();
@@ -136,8 +132,8 @@ export function createAppSplitRouterLayout(
}
const visible = manager.getVisibleSplits();
manager.reconcile(
- entries.map((entry, index) =>
- contentForLocation(entry.location, visible[index]?.content)
+ locations.map((location, index) =>
+ contentForLocation(location, visible[index]?.content)
)
);
},
diff --git a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts b/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts
index 81042dd4f1..befec5e384 100644
--- a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts
+++ b/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts
@@ -1016,6 +1016,32 @@ describe('layoutManager', () => {
dispose();
});
+ it('applies a new-split location when an entity pane is reused', async () => {
+ const { manager, router, dispose } = ingressRouter('/channel/one', {
+ enabled: false,
+ });
+ await router.settled();
+ const split = manager.splits()[0];
+
+ router.navigate(split.id, '/channel/one', {
+ target: 'new-split',
+ allowDuplicate: true,
+ search: {
+ 'channel-detail': { messageId: ['second'] },
+ },
+ });
+ await router.settled();
+
+ expect(manager.splits()).toHaveLength(1);
+ expect(manager.splits()[0].content.entryMetadata).toMatchObject({
+ search: {
+ 'channel-detail': { messageId: ['second'] },
+ },
+ });
+ router.dispose();
+ dispose();
+ });
+
it('normalizes every external URL and restores targets through browser history', async () => {
const { manager, location, router, dispose } = ingressRouter(
'/mail/one?email_message_id=first'
diff --git a/apps/web/src/features/channels-view/channels-view-context.test.tsx b/apps/web/src/features/channels-view/channels-view-context.test.tsx
index 890b15c6d2..e92ec4371b 100644
--- a/apps/web/src/features/channels-view/channels-view-context.test.tsx
+++ b/apps/web/src/features/channels-view/channels-view-context.test.tsx
@@ -1,7 +1,7 @@
import {
SplitRouter,
- type SplitRouterEntry,
type SplitRouterLayout,
+ type SplitRouterLayoutEntry,
type SplitRouterSettledChange,
useSplitRouter,
} from '@app/lib/split-router';
@@ -71,22 +71,22 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({
}));
function createLayout(): SplitRouterLayout<string> {
- let current: (SplitRouterEntry & { splitId: string }) | undefined;
+ let current: SplitRouterLayoutEntry<string> | undefined;
const listeners = new Set<(change: SplitRouterSettledChange) => void>();
const notify = () => {
for (const listener of listeners) listener({ history: 'push' });
};
return {
snapshot: () => ({ entries: current ? [current] : [] }),
- updateCurrentEntry(_splitId, update) {
+ updateCurrentLocation(_splitId, update) {
if (!current) return;
- current = { splitId: current.splitId, ...update(current) };
+ current = { splitId: current.splitId, location: update(current) };
notify();
},
- open: () => {},
- reconcile(entries) {
- const next = entries[0];
- current = next ? { splitId: 'split', ...next } : undefined;
+ open: () => ({ status: 'unavailable' }),
+ reconcile(locations) {
+ const location = locations[0];
+ current = location ? { splitId: 'split', location } : undefined;
notify();
},
activate: () => {},
diff --git a/apps/web/src/features/drive-view/drive-detail-navigation.tsx b/apps/web/src/features/drive-view/drive-detail-navigation.tsx
index 8600a83154..538fe62303 100644
--- a/apps/web/src/features/drive-view/drive-detail-navigation.tsx
+++ b/apps/web/src/features/drive-view/drive-detail-navigation.tsx
@@ -124,7 +124,7 @@ export function DriveDetailNavigationProvider(
const result: DriveDetailHistoryEntry[] = [];
for (let index = 0; index <= snapshot.index; index += 1) {
const target = targetFromParams(
- routeParams(snapshot.entries[index]?.route) as DriveRouteParams
+ routeParams(snapshot.entries[index]?.location.route) as DriveRouteParams
);
if (!target) {
diff --git a/apps/web/src/features/inbox-view/inbox-view-context.test.tsx b/apps/web/src/features/inbox-view/inbox-view-context.test.tsx
index f003a81898..4b23f237b1 100644
--- a/apps/web/src/features/inbox-view/inbox-view-context.test.tsx
+++ b/apps/web/src/features/inbox-view/inbox-view-context.test.tsx
@@ -1,7 +1,7 @@
import {
SplitRouter,
- type SplitRouterEntry,
type SplitRouterLayout,
+ type SplitRouterLayoutEntry,
type SplitRouterSettledChange,
useSplitRouter,
} from '@app/lib/split-router';
@@ -132,22 +132,22 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({
}));
function createLayout(): SplitRouterLayout<string> {
- let current: (SplitRouterEntry & { splitId: string }) | undefined;
+ let current: SplitRouterLayoutEntry<string> | undefined;
const listeners = new Set<(change: SplitRouterSettledChange) => void>();
const notify = () => {
for (const listener of listeners) listener({ history: 'push' });
};
return {
snapshot: () => ({ entries: current ? [current] : [] }),
- updateCurrentEntry(_splitId, update) {
+ updateCurrentLocation(_splitId, update) {
if (!current) return;
- current = { splitId: current.splitId, ...update(current) };
+ current = { splitId: current.splitId, location: update(current) };
notify();
},
- open: () => {},
- reconcile(entries) {
- const next = entries[0];
- current = next ? { splitId: 'split', ...next } : undefined;
+ open: () => ({ status: 'unavailable' }),
+ reconcile(locations) {
+ const location = locations[0];
+ current = location ? { splitId: 'split', location } : undefined;
notify();
},
activate: () => {},
diff --git a/apps/web/src/lib/core/constant/SettingsState.test.tsx b/apps/web/src/lib/core/constant/SettingsState.test.tsx
index 38eab0e795..d0cf089598 100644
--- a/apps/web/src/lib/core/constant/SettingsState.test.tsx
+++ b/apps/web/src/lib/core/constant/SettingsState.test.tsx
@@ -103,18 +103,20 @@ describe('settings entry points', () => {
layout: {
snapshot: () => ({ entries }),
reconcile: (next) => {
- entries = next.map((entry) => ({
- ...entry,
+ entries = next.map((location) => ({
+ location,
splitId: 'settings-split',
}));
},
open: ({ location }) => {
entries = [{ splitId: 'settings-split', location }];
+ return { status: 'applied', splitId: 'settings-split' };
},
- updateCurrentEntry: (id, update) => {
- entries = entries.map((entry) =>
- entry.splitId === id ? { ...update(entry), splitId: id } : entry
- );
+ updateCurrentLocation: (id, update) => {
+ entries = entries.map((entry) => {
+ if (entry.splitId !== id) return entry;
+ return { location: update(entry), splitId: id };
+ });
},
activate: () => {},
subscribe: () => () => {},
diff --git a/apps/web/src/lib/split-router/README.md b/apps/web/src/lib/split-router/README.md
index de5e0a7e8a..2878474099 100644
--- a/apps/web/src/lib/split-router/README.md
+++ b/apps/web/src/lib/split-router/README.md
@@ -90,6 +90,41 @@ those fields back to canonical names. Widened `string` paths retain untyped para
- Clearing search retains the route. Ordinary unprefixed external/global search
keys remain distinct from namespaced split search.
+### Route-owned entry state
+
+A route may declare a synchronous Standard Schema as `state`. Descendants inherit
+that schema unless they declare their own, so a view root can own history state for
+its complete route branch. Typed route navigation infers the schema input and output,
+and `useRouteState(route)` returns its parsed output. Since browser history stores a
+structured clone of that output, schemas with different input/output shapes must also
+accept their cloned output when restoring an entry.
+
+Every accepted history entry has a stable router-generated `key`. State supplied to
+navigation is parsed by the destination route and structured-cloned before the entry
+is accepted. If cloning fails, navigation continues without state. Invalid local
+navigation state throws. Invalid browser, persisted, or
+host-layout state is discarded without rejecting the route. Middleware redirects
+retain state only when it is accepted by the final route. A route without a state
+schema cannot retain state.
+
+A route navigation without state starts with no state. Every route navigation receives
+a new key, whether it pushes or replaces the browser slot. Search-only writes preserve
+already parsed state; a search push receives a new key while a search replacement
+retains its key. Values read from entries are immutable snapshots and must not be
+mutated.
+
+`router.entry(splitId)` and history snapshots expose complete entries. Numeric
+history traversal restores the exact stored entry. The external
+location adapters round-trip visible entry keys and parsed state through a namespaced
+field in browser `history.state`; the URL remains route-and-search only. Copied or
+direct URLs therefore have no entry state, and views must provide a route-derived
+fallback. Malformed or positionally mismatched browser metadata is ignored.
+
+Host layout adapters own pane identity and the current location only. Entry keys,
+route state, and per-pane history remain router-owned. Key/state-only navigation does
+not write layout metadata or remount the view. Opening reports the pane that accepted
+the requested location, or reports that no pane was available.
+
## Claims
A route may return `{ namespace, id }` from `claim(params)`. Providers are checked
@@ -152,6 +187,7 @@ failures are logged and release their reservations.
- `routes.ts`, `path.ts`: manifest, matching, params, ownership, and claim derivation.
- `router.ts`, `transitions.ts`, `claims.ts`: orchestration, cancellation, pending claims.
- `history.ts`, `layout.ts`, `location-sync.ts`: pane history and host boundaries.
+- `entry-state.ts`: entry identity and browser-history state envelopes.
- `url.ts`, `search.ts`: URL framing and raw search state.
- `search-params-codec.ts`, `create-search-params.ts`: typed search conversion/binding.
- `solid.tsx`: providers, hooks, and nested outlets.
diff --git a/apps/web/src/lib/split-router/entry-state.ts b/apps/web/src/lib/split-router/entry-state.ts
new file mode 100644
index 0000000000..135d2ebdb2
--- /dev/null
+++ b/apps/web/src/lib/split-router/entry-state.ts
@@ -0,0 +1,75 @@
+import type { SplitRouterEntry, SplitRouterEntryState } from './types';
+import { isRecord } from './utils';
+
+const SPLIT_ROUTER_BROWSER_STATE_KEY = '__macroSplitRouter';
+
+type BrowserEntryState = {
+ key: string;
+ state?: SplitRouterEntryState;
+};
+
+type BrowserRouterState = {
+ entries: BrowserEntryState[];
+};
+
+let fallbackKeySequence = 0;
+
+export function createEntryKey(): string {
+ const randomId = globalThis.crypto?.randomUUID?.();
+ if (randomId) return `split-router:${randomId}`;
+
+ fallbackKeySequence += 1;
+ return `split-router:${Date.now().toString(36)}:${fallbackKeySequence.toString(36)}`;
+}
+
+export function parseBrowserEntries(
+ state: unknown
+): BrowserEntryState[] | undefined {
+ if (!isRecord(state)) return;
+
+ const value = state[SPLIT_ROUTER_BROWSER_STATE_KEY];
+ if (!isRecord(value) || !Array.isArray(value.entries)) return;
+
+ const entries: BrowserEntryState[] = [];
+ for (const candidate of value.entries) {
+ if (!isRecord(candidate) || typeof candidate.key !== 'string') return;
+
+ const entry: BrowserEntryState = { key: candidate.key };
+ if (Object.hasOwn(candidate, 'state')) {
+ entry.state = candidate.state as SplitRouterEntryState;
+ }
+ entries.push(entry);
+ }
+ return entries;
+}
+
+export function mergeBrowserEntries(
+ previous: unknown,
+ entries: readonly SplitRouterEntry[]
+): unknown {
+ const result = isRecord(previous) ? { ...previous } : {};
+ const browserEntries: BrowserEntryState[] = [];
+
+ for (const entry of entries) {
+ if (!entry.key) {
+ delete result[SPLIT_ROUTER_BROWSER_STATE_KEY];
+ if (Object.keys(result).length === 0) return;
+ return result;
+ }
+
+ const browserEntry: BrowserEntryState = { key: entry.key };
+ if (Object.hasOwn(entry, 'state')) browserEntry.state = entry.state;
+ browserEntries.push(browserEntry);
+ }
+
+ const routerState: BrowserRouterState = { entries: browserEntries };
+ result[SPLIT_ROUTER_BROWSER_STATE_KEY] = routerState;
+ return result;
+}
+
+export function browserEntryKeySignature(state: unknown): string {
+ const entries = parseBrowserEntries(state);
+ if (!entries) return '';
+
+ return JSON.stringify(entries.map(({ key }) => key));
+}
diff --git a/apps/web/src/lib/split-router/history.ts b/apps/web/src/lib/split-router/history.ts
index 0772bb6b24..72c5a37f00 100644
--- a/apps/web/src/lib/split-router/history.ts
+++ b/apps/web/src/lib/split-router/history.ts
@@ -12,7 +12,8 @@ export type SplitRouterHistory<TEntry> = {
export function createSplitRouterHistory<TEntry>(
initial: TEntry,
- equals: (left: TEntry, right: TEntry) => boolean
+ equals: (left: TEntry, right: TEntry) => boolean,
+ sameIdentity: (left: TEntry, right: TEntry) => boolean = equals
): SplitRouterHistory<TEntry> {
let items = [initial];
let currentIndex = 0;
@@ -65,9 +66,10 @@ export function createSplitRouterHistory<TEntry>(
if (equals(items[currentIndex]!, entry)) return false;
const existingIndex = items.findIndex((candidate) =>
- equals(candidate, entry)
+ sameIdentity(candidate, entry)
);
if (existingIndex >= 0) {
+ items = items.with(existingIndex, entry);
currentIndex = existingIndex;
return true;
}
@@ -84,7 +86,8 @@ export function createSplitRouterHistory<TEntry>(
}
export function createSplitRouterHistories<TId, TEntry>(
- equals: (left: TEntry, right: TEntry) => boolean
+ equals: (left: TEntry, right: TEntry) => boolean,
+ sameIdentity: (left: TEntry, right: TEntry) => boolean = equals
) {
const histories = new Map<TId, SplitRouterHistory<TEntry>>();
let order: TId[] = [];
@@ -117,7 +120,10 @@ export function createSplitRouterHistories<TId, TEntry>(
else if (intent === 'replace') history.replace(entry);
else history.push(entry);
} else {
- histories.set(id, createSplitRouterHistory(entry, equals));
+ histories.set(
+ id,
+ createSplitRouterHistory(entry, equals, sameIdentity)
+ );
}
});
diff --git a/apps/web/src/lib/split-router/index.ts b/apps/web/src/lib/split-router/index.ts
index 5970b55703..68e5231f67 100644
--- a/apps/web/src/lib/split-router/index.ts
+++ b/apps/web/src/lib/split-router/index.ts
@@ -31,8 +31,10 @@ export {
filterRouteSearch,
getExternalSearchKeys,
getRouteClaim,
+ getRouteEntryState,
getRouteId,
getRouteSearchNamespaces,
+ parseRouteEntryState,
type RouteParamsCodec,
resolveRouteBranch,
rootRouteMatch,
@@ -60,6 +62,7 @@ export {
useNavigate,
useParams,
useRouteParams,
+ useRouteState,
useSplitHistory,
useSplitRouter,
} from './solid';
@@ -70,6 +73,8 @@ export type {
InferSplitRouteBranchParams,
InferSplitRouteNavigationParams,
InferSplitRouteParams,
+ InferSplitRouteState,
+ InferSplitRouteStateInput,
SerializedSearchParams,
SplitLocation,
SplitNavigate,
@@ -80,15 +85,18 @@ export type {
SplitRouteClaim,
SplitRouteDefinition,
SplitRouteMatch,
+ SplitRouteNavigateOptions,
SplitRouteNavigationTarget,
SplitRouteParams,
SplitRouteRawParams,
SplitRouterEntry,
+ SplitRouterEntryState,
SplitRouterExternalLocation,
SplitRouterExternalLocationValue,
SplitRouterHistorySnapshot,
SplitRouterLayout,
SplitRouterLayoutEntry,
+ SplitRouterLayoutOpenResult,
SplitRouterLayoutSnapshot,
SplitRouterMiddleware,
SplitRouterMiddlewareConfig,
@@ -100,6 +108,7 @@ export type {
SplitRouterNavigationCause,
SplitRouterOptions,
SplitRouterSettledChange,
+ SplitRouterStateUpdate,
SplitRouteState,
SplitRoutes,
SplitRouteUnion,
diff --git a/apps/web/src/lib/split-router/integrations/solid-router.ts b/apps/web/src/lib/split-router/integrations/solid-router.ts
index 90d10df223..e754954bcb 100644
--- a/apps/web/src/lib/split-router/integrations/solid-router.ts
+++ b/apps/web/src/lib/split-router/integrations/solid-router.ts
@@ -1,4 +1,5 @@
import { type Accessor, createEffect, createRoot, on } from 'solid-js';
+import { browserEntryKeySignature } from '../entry-state';
import type {
SplitRouterExternalLocation,
SplitRouterExternalLocationValue,
@@ -9,7 +10,11 @@ export type SolidRouterLocationOptions = {
pathname: Accessor<string>;
search?: Accessor<string>;
hash?: Accessor<string>;
- navigate: (to: string, options: { replace: boolean }) => unknown;
+ state?: Accessor<unknown>;
+ navigate: (
+ to: string,
+ options: { replace: boolean; state?: unknown }
+ ) => unknown;
};
/**
@@ -19,11 +24,15 @@ export type SolidRouterLocationOptions = {
export function createSolidRouterLocation(
options: SolidRouterLocationOptions
): SplitRouterExternalLocation {
- const read = (): SplitRouterExternalLocationValue => ({
- pathname: options.pathname(),
- search: options.search?.() ?? '',
- hash: options.hash?.() ?? '',
- });
+ const read = (): SplitRouterExternalLocationValue => {
+ const location: SplitRouterExternalLocationValue = {
+ pathname: options.pathname(),
+ search: options.search?.() ?? '',
+ hash: options.hash?.() ?? '',
+ };
+ if (options.state) location.state = options.state();
+ return location;
+ };
return {
read,
@@ -39,6 +48,7 @@ export function createSolidRouterLocation(
location.pathname,
location.search,
location.hash,
+ browserEntryKeySignature(location.state),
]);
},
() => listener(read()),
@@ -53,6 +63,7 @@ export function createSolidRouterLocation(
commit(location, commitOptions) {
options.navigate(externalLocationToString(location), {
replace: commitOptions.history === 'replace',
+ state: location.state,
});
},
};
diff --git a/apps/web/src/lib/split-router/layout.ts b/apps/web/src/lib/split-router/layout.ts
index 61ddd02e4d..54e718e69d 100644
--- a/apps/web/src/lib/split-router/layout.ts
+++ b/apps/web/src/lib/split-router/layout.ts
@@ -16,9 +16,7 @@ export function createLayoutAdapter<TSplitId>(
return value;
};
const entries = (): SplitRouterEntry[] =>
- snapshot().entries.map((entry) => ({
- location: entry.location,
- }));
+ snapshot().entries.map(({ splitId: _splitId, ...entry }) => entry);
const find = (
splitId: TSplitId
@@ -28,18 +26,46 @@ export function createLayoutAdapter<TSplitId>(
const entryEquals = (
left: SplitRouterEntry | undefined,
right: SplitRouterEntry | undefined
- ): boolean =>
- left === right ||
- (left !== undefined &&
- right !== undefined &&
- deepEqual(left.location, right.location));
+ ): boolean => {
+ if (left === right) return true;
+ if (!left || !right) return false;
+ if (left.key !== right.key) return false;
+ if (!deepEqual(left.location, right.location)) return false;
+ return Object.is(left.state, right.state);
+ };
+
+ const entryIdentityEquals = (
+ left: SplitRouterEntry,
+ right: SplitRouterEntry
+ ): boolean => {
+ if (left.key !== undefined && right.key !== undefined) {
+ return left.key === right.key;
+ }
+ return deepEqual(left.location, right.location);
+ };
const layoutsEqual = (
left: SplitRouterEntry[],
right: SplitRouterEntry[]
): boolean =>
left.length === right.length &&
- left.every((entry, index) => entryEquals(entry, right[index]));
+ left.every((entry, index) =>
+ deepEqual(entry.location, right[index]?.location)
+ );
+
+ const snapshotsEqual = (
+ left: SplitRouterLayoutEntry<TSplitId>[],
+ right: SplitRouterLayoutEntry<TSplitId>[]
+ ) =>
+ left.length === right.length &&
+ left.every((entry, index) => {
+ const candidate = right[index];
+ return (
+ candidate !== undefined &&
+ Object.is(entry.splitId, candidate.splitId) &&
+ deepEqual(entry.location, candidate.location)
+ );
+ });
const changedIds = (
before: SplitRouterEntry[],
@@ -49,7 +75,7 @@ export function createLayoutAdapter<TSplitId>(
const changed = new Set<TSplitId>();
after.forEach((entry, index) => {
- if (entryEquals(before[index], entry)) return;
+ if (deepEqual(before[index]?.location, entry.location)) return;
const splitId = visible[index]?.splitId;
if (splitId !== undefined) changed.add(splitId);
@@ -65,7 +91,7 @@ export function createLayoutAdapter<TSplitId>(
for (const entry of requested) assertRouteEntry(routes, entry);
if (layoutsEqual(current, requested)) return false;
- layout.reconcile(requested);
+ layout.reconcile(requested.map((entry) => entry.location));
return true;
};
@@ -74,27 +100,54 @@ export function createLayoutAdapter<TSplitId>(
target: TSplitId | 'new-split';
replace: boolean;
requireExistingTarget?: boolean;
- }): boolean => {
+ }): { changed: boolean; layoutChanged: boolean; splitId?: TSplitId } => {
assertRouteEntry(routes, options.entry);
- const targetId =
- options.target === 'new-split' ? undefined : options.target;
- const current = targetId === undefined ? undefined : find(targetId);
+ let targetId: TSplitId | undefined;
+ let current: SplitRouterLayoutEntry<TSplitId> | undefined;
+ if (options.target !== 'new-split') {
+ targetId = options.target;
+ current = find(targetId);
+ }
- if (options.requireExistingTarget && !current) return false;
+ if (options.requireExistingTarget && !current) {
+ return { changed: false, layoutChanged: false };
+ }
if (targetId !== undefined && current) {
- if (deepEqual(current.location, options.entry.location)) return false;
-
- layout.updateCurrentEntry(targetId, () => options.entry);
- return true;
+ if (deepEqual(current.location, options.entry.location)) {
+ return { changed: true, layoutChanged: false, splitId: targetId };
+ }
+
+ layout.updateCurrentLocation(targetId, () => options.entry.location);
+ const applied = find(targetId);
+ if (!deepEqual(applied?.location, options.entry.location)) {
+ throw new Error('Split layout did not apply the requested location');
+ }
+ return { changed: true, layoutChanged: true, splitId: targetId };
}
- layout.open({
+ const before = snapshot().entries;
+ const result = layout.open({
location: options.entry.location,
target: options.target,
replace: options.replace,
});
- return true;
+ if (result.status === 'unavailable') {
+ return { changed: false, layoutChanged: false };
+ }
+
+ const after = snapshot().entries;
+ const applied = after.find((entry) =>
+ Object.is(entry.splitId, result.splitId)
+ );
+ if (!deepEqual(applied?.location, options.entry.location)) {
+ throw new Error('Split layout did not apply the requested location');
+ }
+ return {
+ changed: true,
+ layoutChanged: !snapshotsEqual(before, after),
+ splitId: result.splitId,
+ };
};
return {
@@ -103,9 +156,11 @@ export function createLayoutAdapter<TSplitId>(
changedIds,
entries,
entryEquals,
+ entryIdentityEquals,
find,
layoutsEqual,
reconcile,
snapshot,
+ snapshotsEqual,
};
}
diff --git a/apps/web/src/lib/split-router/location-sync.ts b/apps/web/src/lib/split-router/location-sync.ts
index f1b19bedb8..fef20f593e 100644
--- a/apps/web/src/lib/split-router/location-sync.ts
+++ b/apps/web/src/lib/split-router/location-sync.ts
@@ -1,3 +1,4 @@
+import { browserEntryKeySignature } from './entry-state';
import type { SplitRoutesManifest } from './routes';
import type {
BrowserHistoryIntent,
@@ -11,17 +12,22 @@ function externalLocationSignature(
location: SplitRouterExternalLocationValue
): string {
const query = [...new URLSearchParams(location.search)].sort(
- ([leftKey, leftValue], [rightKey, rightValue]) =>
- leftKey === rightKey
- ? leftValue.localeCompare(rightValue)
- : leftKey.localeCompare(rightKey)
+ ([leftKey, leftValue], [rightKey, rightValue]) => {
+ if (leftKey === rightKey) return leftValue.localeCompare(rightValue);
+ return leftKey.localeCompare(rightKey);
+ }
);
- const pathname =
- location.pathname.length > 1
- ? location.pathname.replace(/\/+$/g, '')
- : location.pathname || '/';
+ let pathname = location.pathname || '/';
+ if (location.pathname.length > 1) {
+ pathname = location.pathname.replace(/\/+$/g, '');
+ }
- return JSON.stringify([pathname, query, location.hash]);
+ return JSON.stringify([
+ pathname,
+ query,
+ location.hash,
+ browserEntryKeySignature(location.state),
+ ]);
}
export type LocationSync = {
diff --git a/apps/web/src/lib/split-router/middleware.ts b/apps/web/src/lib/split-router/middleware.ts
index a1a2793d25..0d03fe5897 100644
--- a/apps/web/src/lib/split-router/middleware.ts
+++ b/apps/web/src/lib/split-router/middleware.ts
@@ -32,6 +32,7 @@ function withSearch(
if (!search || entry.location.search) return entry;
return {
+ ...entry,
location: {
...entry.location,
search,
@@ -87,7 +88,14 @@ export function runSplitRouterMiddleware(
);
}
- return runEntry(withSearch(next, current.location.search));
+ const redirected: SplitRouterEntry = {
+ ...next,
+ key: current.key,
+ };
+ if (Object.hasOwn(current, 'state')) {
+ redirected.state = current.state;
+ }
+ return runEntry(withSearch(redirected, current.location.search));
};
const runAt = (index: number): SplitRouterMiddlewareRun => {
@@ -109,9 +117,10 @@ export function runSplitRouterMiddleware(
redirect: (to) => ({ type: 'redirect', to }),
});
- return isPromise(result)
- ? result.then((settled) => handleResult(settled, index + 1))
- : handleResult(result, index + 1);
+ if (isPromise(result)) {
+ return result.then((settled) => handleResult(settled, index + 1));
+ }
+ return handleResult(result, index + 1);
};
return runAt(0);
@@ -141,9 +150,10 @@ export function prepareEntry(
try {
const prepared = runSplitRouterMiddleware(config, request);
- return isPromise(prepared)
- ? prepared.catch((error) => recoverFailure(error, config, request))
- : prepared;
+ if (isPromise(prepared)) {
+ return prepared.catch((error) => recoverFailure(error, config, request));
+ }
+ return prepared;
} catch (error) {
return recoverFailure(error, config, request);
}
@@ -163,7 +173,6 @@ export function prepareEntries(
})
);
- return prepared.some(isPromise)
- ? Promise.all(prepared)
- : (prepared as SplitRouterEntry[]);
+ if (prepared.some(isPromise)) return Promise.all(prepared);
+ return prepared as SplitRouterEntry[];
}
diff --git a/apps/web/src/lib/split-router/navigation.ts b/apps/web/src/lib/split-router/navigation.ts
index ea07b7ad29..125c14d789 100644
--- a/apps/web/src/lib/split-router/navigation.ts
+++ b/apps/web/src/lib/split-router/navigation.ts
@@ -15,33 +15,28 @@ import type {
} from './types';
import { parseExternalLocation, parseRoutePathname } from './url';
-function decodeRouteState(
- routes: SplitRoutesManifest,
- route: SplitRouteState
-): SplitRouterEntry | undefined {
- return decodeRoute(routes, encodeRoute(routes, { location: { route } }));
-}
-
function resolveRouteTarget(
routes: SplitRoutesManifest,
current: SplitRouterEntry,
target: { route: { id: string }; params?: unknown }
): SplitRouterEntry | undefined {
const routeId = target.route.id;
- const targetParams =
+ let targetParams: SplitRouteParams = {};
+ if (
target.params &&
typeof target.params === 'object' &&
!Array.isArray(target.params)
- ? (target.params as SplitRouteParams)
- : {};
+ ) {
+ targetParams = target.params as SplitRouteParams;
+ }
const branch = findRouteBranch(routes, routeId);
if (!branch) return;
const currentMatches = current.location.route.matches;
const matches = branch.map(({ definition }, index) => {
const currentMatch = currentMatches[index];
- const params =
- currentMatch?.id === definition.id ? currentMatch.params : {};
+ let params: SplitRouteParams = {};
+ if (currentMatch?.id === definition.id) params = currentMatch.params;
return {
id: definition.id,
@@ -54,7 +49,8 @@ function resolveRouteTarget(
const [first, ...rest] = matches;
if (!first) return;
- return decodeRouteState(routes, { matches: [first, ...rest] });
+ const route: SplitRouteState = { matches: [first, ...rest] };
+ return decodeRoute(routes, encodeRoute(routes, { location: { route } }));
}
function resolveParentTarget(
@@ -72,7 +68,11 @@ function resolveParentTarget(
const [first, ...rest] = route.matches.slice(0, length);
if (!first) return;
- return decodeRouteState(routes, { matches: [first, ...rest] });
+ const parentRoute: SplitRouteState = { matches: [first, ...rest] };
+ return decodeRoute(
+ routes,
+ encodeRoute(routes, { location: { route: parentRoute } })
+ );
}
function resolvePathTarget(
@@ -86,10 +86,12 @@ function resolvePathTarget(
}
| undefined {
const childRelative = to.startsWith('./');
- const value = childRelative ? to.slice(2) : to;
- const targetUrl = parseExternalLocation(
- value.startsWith('/') ? value : `/${value}`
- );
+ let value = to;
+ if (childRelative) value = to.slice(2);
+
+ let pathname = value;
+ if (!value.startsWith('/')) pathname = `/${value}`;
+ const targetUrl = parseExternalLocation(pathname);
const requested = parseRoutePathname(routes, targetUrl.pathname);
if (!requested) return;
@@ -120,30 +122,35 @@ export function resolveNavigation(
target: SplitRouterEntry | undefined,
to: Exclude<SplitNavigateTo, number>
): SplitRouterEntry | undefined {
- const resolved =
- typeof to === 'string'
- ? resolvePathTarget(routes, current, to)
- : 'route' in to
- ? {
- entry: resolveRouteTarget(routes, current, to),
- explicitSearch: undefined,
- }
- : {
- entry: resolveParentTarget(routes, current, to.levels),
- explicitSearch: undefined,
- };
- const decoded = resolved?.entry;
+ let resolved:
+ | {
+ entry: SplitRouterEntry | undefined;
+ explicitSearch: SplitLocation['search'];
+ }
+ | undefined;
+ if (typeof to === 'string') {
+ resolved = resolvePathTarget(routes, current, to);
+ } else if ('route' in to) {
+ resolved = {
+ entry: resolveRouteTarget(routes, current, to),
+ explicitSearch: undefined,
+ };
+ } else {
+ resolved = {
+ entry: resolveParentTarget(routes, current, to.levels),
+ explicitSearch: undefined,
+ };
+ }
+ if (!resolved) return;
+ const decoded = resolved.entry;
if (!decoded) return;
- const matchingRoute = target && getRouteId(target) === getRouteId(decoded);
let search = resolved.explicitSearch;
+ if (!search && target && getRouteId(target) === getRouteId(decoded)) {
+ search = target.location.search;
+ }
- if (!search && matchingRoute) search = target.location.search;
-
- return {
- location: {
- ...decoded.location,
- ...(search ? { search } : {}),
- },
- };
+ const location: SplitLocation = { ...decoded.location };
+ if (search) location.search = search;
+ return { location };
}
diff --git a/apps/web/src/lib/split-router/router.ts b/apps/web/src/lib/split-router/router.ts
index 5352eb95c0..558a557631 100644
--- a/apps/web/src/lib/split-router/router.ts
+++ b/apps/web/src/lib/split-router/router.ts
@@ -1,5 +1,6 @@
import deepEqual from 'fast-deep-equal';
import { createClaimReservations } from './claims';
+import { createEntryKey } from './entry-state';
import { createSplitRouterHistories } from './history';
import { createLayoutAdapter } from './layout';
import { createLocationSync } from './location-sync';
@@ -10,9 +11,12 @@ import {
assertSearchNamespacesAllowed,
createRoutesManifest,
getRouteClaim,
+ parseRouteEntryState,
+ type SplitRouteNode,
+ type SplitRoutesManifest,
} from './routes';
import { assertSafeSearchName, updateSearchState } from './search';
-import { createTransitionManager } from './transitions';
+import { createTransitionManager, type Transition } from './transitions';
import type {
BrowserHistoryIntent,
SplitNavigateOptions,
@@ -20,8 +24,11 @@ import type {
SplitRouteClaim,
SplitRouter,
SplitRouterEntry,
+ SplitRouterEntryState,
SplitRouterExternalLocationValue,
+ SplitRouterLayoutSnapshot,
SplitRouterOptions,
+ SplitRouterStateUpdate,
} from './types';
import { decodeSplitRouterLocation, serializeSplitRouterLocation } from './url';
import { isPromise, throwIfAborted } from './utils';
@@ -61,20 +68,62 @@ type EntryTransition<TSplitId> = {
const GLOBAL_TRANSITION = Symbol('split-router-global-transition');
+function resolveNavigationEntryState(
+ routes: SplitRoutesManifest,
+ route: SplitRouterEntry['location']['route'],
+ current: SplitRouterEntry | undefined,
+ update: SplitRouterStateUpdate
+): SplitRouterEntryState | undefined {
+ const destinationRouteId = route.matches.at(-1)!.id;
+ const destinationSchema = routes.byId.get(destinationRouteId)?.state;
+ let currentSchema: SplitRouteNode['state'];
+ if (current) {
+ const currentRouteId = current.location.route.matches.at(-1)!.id;
+ currentSchema = routes.byId.get(currentRouteId)?.state;
+ }
+
+ let currentState: SplitRouterEntryState;
+ if (current && currentSchema === destinationSchema) {
+ currentState = current.state;
+ }
+
+ let value = update;
+ if (typeof update === 'function') value = update(currentState);
+ const parsed = parseRouteEntryState(routes, route, value);
+ if (!parsed.success) {
+ const routeId = route.matches.at(-1)?.id ?? 'unknown';
+ throw new Error(`Split route "${routeId}" rejected navigation state`);
+ }
+ if (parsed.value === undefined) return;
+
+ try {
+ return structuredClone(parsed.value);
+ } catch (error) {
+ console.warn(
+ 'Split route state could not be cloned; continuing without state',
+ error
+ );
+ return;
+ }
+}
+
export function createSplitRouter<TSplitId>(
options: SplitRouterOptions<TSplitId>
): SplitRouter<TSplitId> {
- const routes =
- 'definitions' in options.routes
- ? createRoutesManifest(options.routes)
- : options.routes;
+ let routes: SplitRoutesManifest;
+ if ('definitions' in options.routes) {
+ routes = createRoutesManifest(options.routes);
+ } else {
+ routes = options.routes;
+ }
const middleware = options.middleware ?? [];
const claims = createClaimReservations();
const entryControllers = new Map<unknown, AbortController>();
const subscribers = new Set<(splitId: TSplitId | undefined) => void>();
let accepted: SplitRouterEntry[] = [];
- let expectedLayout: SplitRouterEntry[] | undefined;
+ let acceptedIds: TSplitId[] = [];
+ let expectedLayout: SplitRouterLayoutSnapshot<TSplitId> | undefined;
let layoutChangeQueued = false;
let queuedHistory: BrowserHistoryIntent = 'push';
let ready = false;
@@ -87,7 +136,8 @@ export function createSplitRouter<TSplitId>(
const middlewareConfig = { routes, handlers: middleware };
const layout = createLayoutAdapter(options.layout, routes);
const histories = createSplitRouterHistories<TSplitId, SplitRouterEntry>(
- layout.entryEquals
+ layout.entryEquals,
+ layout.entryIdentityEquals
);
const reconcileHistories = (
@@ -95,10 +145,7 @@ export function createSplitRouter<TSplitId>(
mode: 'move' | 'write'
) => {
histories.reconcile(
- layout.snapshot().entries.map(({ splitId, location }) => ({
- id: splitId,
- entry: { location },
- })),
+ accepted.map((entry, index) => ({ id: acceptedIds[index]!, entry })),
intent,
mode
);
@@ -108,6 +155,84 @@ export function createSplitRouter<TSplitId>(
for (const listener of subscribers) listener(splitId);
};
+ const normalizeEntry = (
+ entry: SplitRouterEntry,
+ previous?: SplitRouterEntry
+ ): SplitRouterEntry => {
+ const preservePrevious =
+ !entry.key &&
+ previous !== undefined &&
+ deepEqual(previous.location, entry.location);
+ const hasEntryState = Object.hasOwn(entry, 'state');
+ let parsedState: SplitRouterEntry['state'];
+ if (!hasEntryState && preservePrevious && previous) {
+ parsedState = previous.state;
+ } else {
+ const state = hasEntryState ? entry.state : undefined;
+ const parsed = parseRouteEntryState(routes, entry.location.route, state);
+ if (parsed.success && parsed.value !== undefined) {
+ try {
+ parsedState = structuredClone(parsed.value);
+ } catch {
+ parsedState = undefined;
+ }
+ }
+ }
+ let key = entry.key;
+ if (!key && preservePrevious && previous) key = previous.key;
+ if (!key) key = createEntryKey();
+
+ const { state: _state, ...rest } = entry;
+ const normalized: SplitRouterEntry = { ...rest, key };
+ if (parsedState !== undefined) normalized.state = parsedState;
+ return normalized;
+ };
+
+ const normalizeEntries = (
+ entries: SplitRouterEntry[],
+ previous: readonly (SplitRouterEntry | undefined)[] = []
+ ) => entries.map((entry, index) => normalizeEntry(entry, previous[index]));
+
+ const acceptedById = () => {
+ const entries = new Map<TSplitId, SplitRouterEntry>();
+ accepted.forEach((entry, index) => {
+ entries.set(acceptedIds[index] as TSplitId, entry);
+ });
+ return entries;
+ };
+
+ const acceptedInLayoutOrder = () => {
+ const byId = acceptedById();
+ return layout.snapshot().entries.map(({ splitId, location }) => {
+ const entry = byId.get(splitId);
+ if (!entry || !deepEqual(entry.location, location)) return;
+ return entry;
+ });
+ };
+
+ const bindAccepted = (entries: SplitRouterEntry[]) => {
+ const snapshot = layout.snapshot().entries;
+ accepted = snapshot.map(({ location }, index) => {
+ const entry = entries[index];
+ if (entry && deepEqual(entry.location, location)) return entry;
+ return normalizeEntry({ location });
+ });
+ acceptedIds = snapshot.map(({ splitId }) => splitId);
+ };
+
+ const validateRedirectedState = (
+ entry: SplitRouterEntry,
+ proposed: SplitRouterEntry
+ ) => {
+ const entryRouteId = entry.location.route.matches.at(-1)!.id;
+ const proposedRouteId = proposed.location.route.matches.at(-1)!.id;
+ const entrySchema = routes.byId.get(entryRouteId)?.state;
+ const proposedSchema = routes.byId.get(proposedRouteId)?.state;
+
+ if (entrySchema === proposedSchema) return entry;
+ return normalizeEntry(entry);
+ };
+
const transitions = createTransitionManager<TSplitId, SplitRouterEntry>({
onError(error) {
console.error('Split router transition failed', error);
@@ -115,12 +240,21 @@ export function createSplitRouter<TSplitId>(
onSettled(splitId, publicStateChanged) {
const becameReady = !ready;
ready = true;
- if (becameReady) notify();
- else if (publicStateChanged) notify(splitId);
+ if (becameReady) {
+ notify();
+ } else if (publicStateChanged) {
+ notify(splitId);
+ }
},
});
- const findEntry = (splitId: TSplitId) =>
- transitions.pending(splitId) ?? layout.find(splitId);
+ const findEntry = (splitId: TSplitId) => {
+ const pending = transitions.pending(splitId);
+ if (pending) return pending;
+
+ const index = acceptedIds.findIndex((id) => Object.is(id, splitId));
+ if (index < 0) return;
+ return accepted[index];
+ };
const findClaimedSplit = (
claim: SplitRouteClaim,
@@ -140,8 +274,8 @@ export function createSplitRouter<TSplitId>(
) => {
if (config.allowDuplicate) return;
const claim = getRouteClaim(routes, entry.location.route);
- const current =
- config.splitId === undefined ? undefined : layout.find(config.splitId);
+ let current: SplitRouterEntry | undefined;
+ if (config.splitId !== undefined) current = layout.find(config.splitId);
// Updating an existing owner is not a new acquisition. In particular,
// search/parameter updates must not collapse restored duplicate panes.
if (
@@ -162,7 +296,7 @@ export function createSplitRouter<TSplitId>(
};
const expectLayoutEcho = () => {
- expectedLayout = layout.entries();
+ expectedLayout = layout.snapshot();
};
const reconcileEntries = (
@@ -178,7 +312,7 @@ export function createSplitRouter<TSplitId>(
};
const commitLayout = (commit: CommitOptions) => {
- locationSync.commit(layout.entries(), commit);
+ locationSync.commit(accepted, commit);
};
const abortAllTransitions = (publish = true) => {
@@ -195,7 +329,7 @@ export function createSplitRouter<TSplitId>(
const applyDecoded = (entries: SplitRouterEntry[]) => {
const layoutChanged = reconcileEntries(layout.entries(), entries);
- accepted = layout.entries();
+ bindAccepted(entries);
reconcileHistories('replace', 'move');
commitLayout({ history: 'replace', preserveHash: true });
const becameReady = !ready;
@@ -205,22 +339,39 @@ export function createSplitRouter<TSplitId>(
const transitionLayout = (transition: LayoutTransition) => {
abortAllTransitions();
+ let previous: Array<SplitRouterEntry | undefined> = [];
+ if (transition.cause === 'layout') {
+ previous = acceptedInLayoutOrder();
+ } else if (transition.cause === 'external') {
+ previous = accepted.map((entry) => {
+ if (Object.hasOwn(entry, 'state')) return;
+ return entry;
+ });
+ }
+ const entries = normalizeEntries(transition.entries, previous);
if (middleware.length === 0) {
- transition.apply(transition.entries);
+ transition.apply(entries);
return;
}
const controller = new AbortController();
+ const validatePrepared = (prepared: SplitRouterEntry[]) =>
+ prepared.map((entry, index) =>
+ validateRedirectedState(entry, entries[index]!)
+ );
+ let from: SplitRouterEntry[] | undefined = accepted;
+ if (transition.cause === 'initial') from = undefined;
+
const prepared = prepareEntries(middlewareConfig, {
- from: transition.cause === 'initial' ? undefined : accepted,
- to: transition.entries,
+ from,
+ to: entries,
cause: transition.cause,
externalSearch: transition.externalSearch,
signal: controller.signal,
});
if (!isPromise(prepared)) {
- transition.apply(prepared);
+ transition.apply(validatePrepared(prepared));
return;
}
@@ -229,7 +380,7 @@ export function createSplitRouter<TSplitId>(
async run() {
const result = await prepared;
throwIfAborted(controller.signal);
- transition.apply(result);
+ transition.apply(validatePrepared(result));
},
});
};
@@ -253,7 +404,7 @@ export function createSplitRouter<TSplitId>(
});
};
- accepted = layout.entries();
+ bindAccepted(normalizeEntries(layout.entries()));
const applyPrepared = (
original: SplitRouterEntry[],
@@ -263,7 +414,7 @@ export function createSplitRouter<TSplitId>(
const before = accepted;
reconcileEntries(original, prepared);
- accepted = layout.entries();
+ bindAccepted(prepared);
reconcileHistories(history, 'move');
commitLayout({
history,
@@ -279,10 +430,15 @@ export function createSplitRouter<TSplitId>(
const onLayoutChange = (history: BrowserHistoryIntent) => {
if (disposed) return;
- const entries = layout.entries();
- if (expectedLayout && layout.layoutsEqual(expectedLayout, entries)) {
+ const snapshot = layout.snapshot();
+ const entries = snapshot.entries.map(
+ ({ splitId: _splitId, ...entry }) => entry
+ );
+ if (
+ expectedLayout &&
+ layout.snapshotsEqual(expectedLayout.entries, snapshot.entries)
+ ) {
expectedLayout = undefined;
- accepted = entries;
return;
}
expectedLayout = undefined;
@@ -295,16 +451,26 @@ export function createSplitRouter<TSplitId>(
};
const applyEntry = (config: ApplyOptions<TSplitId>): boolean => {
- const changed = layout.apply({
+ const previousById = acceptedById();
+ const result = layout.apply({
entry: config.entry,
target: config.target,
replace: config.replace,
requireExistingTarget: config.requireTarget,
});
- if (!changed) return false;
+ if (!result.changed) return false;
- expectLayoutEcho();
- accepted = layout.entries();
+ if (result.layoutChanged) expectLayoutEcho();
+
+ const snapshot = layout.snapshot().entries;
+ accepted = snapshot.map(({ splitId, location }) => {
+ if (Object.is(result.splitId, splitId)) return config.entry;
+
+ const previous = previousById.get(splitId);
+ if (previous && deepEqual(previous.location, location)) return previous;
+ return normalizeEntry({ location });
+ });
+ acceptedIds = snapshot.map(({ splitId }) => splitId);
if (config.recordHistory !== false) {
reconcileHistories(config.history, 'write');
}
@@ -333,11 +499,20 @@ export function createSplitRouter<TSplitId>(
checkClaim: (entry: SplitRouterEntry) => SplitRouterEntry | undefined
) => {
const { splitId } = config;
+ let pending: SplitRouterEntry | undefined;
+ let onSettled:
+ | ((transition: Transition<SplitRouterEntry>) => boolean)
+ | undefined;
+ if (splitId !== undefined) {
+ pending = config.entry;
+ onSettled = (transition) =>
+ !layout.entryEquals(transition.pending, layout.find(splitId));
+ }
void transitions.start(config.key, {
controller,
target: splitId,
- pending: splitId === undefined ? undefined : config.entry,
+ pending,
async run(transition) {
try {
const entry = await prepared;
@@ -364,11 +539,7 @@ export function createSplitRouter<TSplitId>(
finish();
}
},
- onSettled:
- splitId === undefined
- ? undefined
- : (transition) =>
- !layout.entryEquals(transition.pending, layout.find(splitId)),
+ onSettled,
});
if (splitId !== undefined) notify(splitId);
@@ -415,32 +586,37 @@ export function createSplitRouter<TSplitId>(
const accept = (entry: SplitRouterEntry) => {
throwIfAborted(controller.signal);
assertRouteEntry(routes, entry);
- const claim = claimToAcquire(entry, config);
+ const normalized = validateRedirectedState(entry, config.entry);
+ const claim = claimToAcquire(normalized, config);
reservation.move(claim);
if (claim && findClaimedSplit(claim, config.splitId)) {
- return reuseOrAccept(entry, claim);
+ return reuseOrAccept(normalized, claim);
}
const turn = reservation.wait(controller.signal);
- if (!isPromise(turn)) return reuseOrAccept(entry, claim);
- return waitForClaim(turn, entry, claim);
+ if (!isPromise(turn)) return reuseOrAccept(normalized, claim);
+ return waitForClaim(turn, normalized, claim);
};
- const acceptPrepared = async (prepared: Promise<SplitRouterEntry>) =>
- accept(await prepared);
-
try {
reservation.move(claimToAcquire(config.entry, config));
- const prepared =
- middleware.length === 0
- ? config.entry
- : prepareEntry(middlewareConfig, {
- from: config.from,
- to: config.entry,
- cause: config.cause,
- signal: controller.signal,
- });
- const resolved = isPromise(prepared)
- ? acceptPrepared(prepared)
- : accept(prepared);
+ let prepared: SplitRouterEntry | Promise<SplitRouterEntry> = config.entry;
+ if (middleware.length > 0) {
+ prepared = prepareEntry(middlewareConfig, {
+ from: config.from,
+ to: config.entry,
+ cause: config.cause,
+ signal: controller.signal,
+ });
+ }
+
+ let resolved:
+ | SplitRouterEntry
+ | Promise<SplitRouterEntry | undefined>
+ | undefined;
+ if (isPromise(prepared)) {
+ resolved = (async () => accept(await prepared))();
+ } else {
+ resolved = accept(prepared);
+ }
if (isPromise(resolved)) {
assertRouteEntry(routes, config.entry);
startAsyncEntry(config, controller, resolved, finish, (entry) =>
@@ -448,7 +624,8 @@ export function createSplitRouter<TSplitId>(
);
} else {
try {
- const changed = resolved ? publishEntry(config, resolved) : false;
+ let changed = false;
+ if (resolved) changed = publishEntry(config, resolved);
if (!changed && hadPending) notify(config.splitId);
} finally {
finish();
@@ -468,16 +645,17 @@ export function createSplitRouter<TSplitId>(
navigateOptions: SplitNavigateOptions<TSplitId>
) => {
if (
- (navigateOptions.target !== undefined &&
- navigateOptions.target !== 'current') ||
- navigateOptions.search !== undefined
+ navigateOptions.target !== undefined &&
+ navigateOptions.target !== 'current'
) {
return;
}
+ if (navigateOptions.search !== undefined) return;
const history = histories.get(splitId);
- const historical = history?.peek(delta);
- if (!history || !historical) return;
+ if (!history) return;
+ const historical = history.peek(delta);
+ if (!historical) return;
transitionEntry({
key: splitId,
@@ -525,6 +703,8 @@ export function createSplitRouter<TSplitId>(
const router: SplitRouter<TSplitId> = {
routes,
+ entry: (splitId) => findEntry(splitId),
+
route(splitId) {
const entry = findEntry(splitId);
return entry?.location.route;
@@ -535,10 +715,9 @@ export function createSplitRouter<TSplitId>(
search(splitId, namespace) {
assertSafeSearchName(namespace, 'namespace');
- const search = findEntry(splitId)?.location?.search;
- return search && Object.hasOwn(search, namespace)
- ? search[namespace]
- : undefined;
+ const search = findEntry(splitId)?.location.search;
+ if (!search || !Object.hasOwn(search, namespace)) return;
+ return search[namespace];
},
canGo(splitId, delta) {
@@ -550,7 +729,7 @@ export function createSplitRouter<TSplitId>(
if (!history) return;
return {
- entries: history.entries().map((entry) => entry.location),
+ entries: history.entries(),
index: history.index(),
};
},
@@ -570,13 +749,16 @@ export function createSplitRouter<TSplitId>(
return;
}
- const target =
- navigateOptions.target === undefined ||
- navigateOptions.target === 'current'
- ? splitId
- : navigateOptions.target;
- const targetEntry =
- target === 'new-split' ? undefined : findEntry(target);
+ let target: TSplitId | 'new-split' = splitId;
+ if (
+ navigateOptions.target !== undefined &&
+ navigateOptions.target !== 'current'
+ ) {
+ target = navigateOptions.target;
+ }
+
+ let targetEntry: SplitRouterEntry | undefined;
+ if (target !== 'new-split') targetEntry = findEntry(target);
const decoded = resolveNavigation(routes, current, targetEntry, to);
if (!decoded) return;
@@ -587,12 +769,27 @@ export function createSplitRouter<TSplitId>(
Object.keys(navigateOptions.search ?? {})
);
+ let history: BrowserHistoryIntent = 'push';
+ if (navigateOptions.replace) history = 'replace';
+
+ let state: SplitRouterEntryState;
+ if (Object.hasOwn(navigateOptions, 'state')) {
+ state = resolveNavigationEntryState(
+ routes,
+ decoded.location.route,
+ targetEntry,
+ navigateOptions.state
+ );
+ }
+
const next: SplitRouterEntry = {
+ key: createEntryKey(),
location: updateSearchState(decoded.location, navigateOptions.search),
};
- const history = navigateOptions.replace ? 'replace' : 'push';
- const targetId =
- target === 'new-split' ? undefined : (target as TSplitId);
+ if (state !== undefined) next.state = state;
+
+ let targetId: TSplitId | undefined;
+ if (target !== 'new-split') targetId = target;
transitionEntry({
key: targetId ?? Symbol('new-split-transition'),
splitId: targetId,
@@ -618,12 +815,17 @@ export function createSplitRouter<TSplitId>(
if (!entry) return;
assertSearchNamespacesAllowed(routes, entry.location.route, [namespace]);
+ const history = updateOptions.history ?? 'push';
+ let key = entry.key;
+ if (history !== 'replace' || !key) key = createEntryKey();
+
const next: SplitRouterEntry = {
+ ...entry,
+ key,
location: updateSearchState(entry.location, {
[namespace]: update,
}),
};
- const history = updateOptions.history ?? 'push';
transitionEntry({
key: splitId,
diff --git a/apps/web/src/lib/split-router/routes.ts b/apps/web/src/lib/split-router/routes.ts
index 630a7a2226..55d1d46bac 100644
--- a/apps/web/src/lib/split-router/routes.ts
+++ b/apps/web/src/lib/split-router/routes.ts
@@ -6,12 +6,14 @@ import type {
DefinedSplitRoutes,
InferSplitRouteParams,
InferSplitRoutePathParams,
+ InferSplitRouteState,
SplitRouteClaim,
SplitRouteDefinition,
SplitRouteMatch,
SplitRouteParams,
SplitRouteRawParams,
SplitRouterEntry,
+ SplitRouterEntryState,
SplitRouteState,
SplitRoutes,
SplitSearchState,
@@ -26,6 +28,7 @@ type SplitRouteDefinitionConstraint = {
component?: unknown;
children?: readonly SplitRouteDefinitionConstraint[];
params?: StandardSchemaV1;
+ state?: StandardSchemaV1;
serializeParams?: unknown;
claim?: unknown;
search?: readonly string[] | '*';
@@ -260,6 +263,7 @@ export type SplitRouteNode<TComponent = unknown> = {
readonly search: ReadonlySet<string>;
readonly claims: readonly SplitRouteDefinition<TComponent>[];
readonly externalSearch: readonly SplitRouteDefinition<TComponent>[];
+ readonly state?: StandardSchemaV1;
};
/** Runtime route state owned by a router, or explicitly supplied by its host. */
@@ -340,6 +344,7 @@ export function createRoutesManifest<TComponent>(
...(parent?.externalSearch ?? []),
...(definition.externalSearch ? [definition] : []),
],
+ state: definition.state ?? parent?.state,
};
branch.push(node);
byId.set(definition.id, node);
@@ -477,6 +482,44 @@ export function resolveRouteBranch<TComponent>(
return resolveRouteNode(routes, route).branch;
}
+export type SplitRouteEntryStateResult =
+ | { success: true; value: SplitRouterEntryState }
+ | { success: false };
+
+export function parseRouteEntryState(
+ routes: SplitRoutesManifest,
+ route: SplitRouteState,
+ state: unknown
+): SplitRouteEntryStateResult {
+ if (state === undefined) return { success: true, value: undefined };
+ const schema = resolveRouteNode(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 as SplitRouterEntryState,
+ };
+}
+
+export function getRouteEntryState<const TRoute extends { id: string }>(
+ routes: SplitRoutesManifest,
+ entry: SplitRouterEntry | undefined,
+ route: TRoute
+): InferSplitRouteState<TRoute> | undefined {
+ if (!entry) return;
+ const active = resolveRouteNode(routes, entry.location.route);
+ const requested = routes.byId.get(route.id);
+ if (!requested) return;
+ if (!active.branch.includes(requested)) return;
+ if (requested.state !== active.state) return;
+ return entry.state as InferSplitRouteState<TRoute> | undefined;
+}
+
export function getRouteClaim(
routes: SplitRoutesManifest,
route: SplitRouteState
diff --git a/apps/web/src/lib/split-router/solid.tsx b/apps/web/src/lib/split-router/solid.tsx
index 06c8712642..a572247653 100644
--- a/apps/web/src/lib/split-router/solid.tsx
+++ b/apps/web/src/lib/split-router/solid.tsx
@@ -13,6 +13,7 @@ import {
import { Dynamic } from 'solid-js/web';
import { createSplitRouter } from './router';
import {
+ getRouteEntryState,
resolveRouteBranch,
routeParams,
type SplitRoutesManifest,
@@ -20,6 +21,7 @@ import {
import type {
InferSplitRouteBranchParams,
InferSplitRouteParams,
+ InferSplitRouteState,
SplitNavigate,
SplitNavigateOptions,
SplitNavigateTo,
@@ -78,6 +80,11 @@ export function useSplitRouterState<TSplitId>() {
return router.canGo(splitId, delta);
},
+ entry(splitId: TSplitId) {
+ context.track(splitId);
+
+ return router.entry(splitId);
+ },
history(splitId: TSplitId) {
context.track(splitId);
@@ -134,6 +141,16 @@ export function useCanGo(delta: number): Accessor<boolean> {
return () => router.canGo(splitId(), delta);
}
+export function useRouteState<const TRoute extends { id: string }>(
+ route: TRoute
+): Accessor<InferSplitRouteState<TRoute> | undefined> {
+ const state = useSplitRouterState<unknown>();
+ const splitId = useSplitRouterScope<unknown>();
+
+ return () =>
+ getRouteEntryState(state.router.routes, state.entry(splitId()), route);
+}
+
export function useSplitHistory() {
const router = useSplitRouterState<unknown>();
const splitId = useSplitRouterScope<unknown>();
diff --git a/apps/web/src/lib/split-router/tests/location-sync.test.ts b/apps/web/src/lib/split-router/tests/location-sync.test.ts
index bdb11bd06c..5829fd8d94 100644
--- a/apps/web/src/lib/split-router/tests/location-sync.test.ts
+++ b/apps/web/src/lib/split-router/tests/location-sync.test.ts
@@ -80,4 +80,34 @@ describe('external location synchronization', () => {
expect(acknowledge(parseExternalLocation('/item/first'))).toBe(true);
expect(acknowledge(parseExternalLocation('/item/second'))).toBe(false);
});
+
+ it('distinguishes commits with the same URL by entry identity', () => {
+ const current = parseExternalLocation('/item/initial');
+ const commit = vi.fn();
+ const sync = createLocationSync({
+ routes,
+ location: {
+ read: () => current,
+ commit,
+ subscribe: () => () => {},
+ },
+ });
+ const entry = decodeRoute(routes, ['item', 'same'])!;
+
+ sync.commit([{ ...entry, key: 'entry-1', state: { feature: 'first' } }], {
+ history: 'push',
+ preserveHash: false,
+ });
+ sync.commit([{ ...entry, key: 'entry-2', state: { feature: 'second' } }], {
+ history: 'push',
+ preserveHash: false,
+ });
+
+ expect(commit).toHaveBeenCalledTimes(2);
+ expect(commit.mock.calls[0]?.[0].pathname).toBe('/item/same');
+ expect(commit.mock.calls[1]?.[0].pathname).toBe('/item/same');
+ expect(commit.mock.calls[0]?.[0].state).not.toEqual(
+ commit.mock.calls[1]?.[0].state
+ );
+ });
});
diff --git a/apps/web/src/lib/split-router/tests/middleware.test.ts b/apps/web/src/lib/split-router/tests/middleware.test.ts
index 8d36c8c3c1..ce770ed762 100644
--- a/apps/web/src/lib/split-router/tests/middleware.test.ts
+++ b/apps/web/src/lib/split-router/tests/middleware.test.ts
@@ -52,7 +52,11 @@ describe('split router middleware', () => {
],
},
{
- to: legacyEntry,
+ to: {
+ ...legacyEntry,
+ key: 'entry-1',
+ state: { feature: 'state' },
+ },
cause: 'navigate',
signal: new AbortController().signal,
}
@@ -60,6 +64,8 @@ describe('split router middleware', () => {
expect(result).not.toBeInstanceOf(Promise);
expect(result).toMatchObject({
+ key: 'entry-1',
+ state: { feature: 'state' },
location: {
route: {
matches: [
diff --git a/apps/web/src/lib/split-router/tests/navigation.test.ts b/apps/web/src/lib/split-router/tests/navigation.test.ts
index a46022a6ef..616684cea0 100644
--- a/apps/web/src/lib/split-router/tests/navigation.test.ts
+++ b/apps/web/src/lib/split-router/tests/navigation.test.ts
@@ -41,6 +41,16 @@ const workspaceRoute = defineRoute({
children: [workspaceFolderRoute, workspacePageRoute],
});
+const stateRoute = defineRoute({
+ id: 'state-root',
+ path: 'state',
+ state: z
+ .object({ trail: z.array(z.string()) })
+ .transform((state) => ({ ...state, length: state.trail.length })),
+ children: [{ id: 'state-child', path: 'child' }],
+});
+const stateChildRoute = stateRoute.children[0];
+
const tree = defineRoutes({ definitions: [workspaceRoute] });
const routes = createRoutesManifest(tree);
const boundDetail = tree.definitions[0].children[0].children[0];
@@ -56,6 +66,19 @@ function assertTypedRouteTargets(navigate: SplitNavigate<string>) {
params: { documentId: 'document-1' },
});
navigate({ route: workspaceRoute });
+ navigate({ route: stateChildRoute }, { state: { trail: ['first'] } });
+ navigate(
+ { route: stateChildRoute },
+ {
+ state: (current) => ({
+ trail: [...(current?.trail ?? []), String(current?.length ?? 0)],
+ }),
+ }
+ );
+ // @ts-expect-error Routes without a state schema reject navigation state.
+ navigate({ route: workspaceRoute }, { state: { trail: [] } });
+ // @ts-expect-error Navigation uses the route state schema's input type.
+ navigate({ route: stateChildRoute }, { state: { length: 1 } });
navigate({ route: workspacePageRoute, params: { page: 2 } });
navigate({
route: boundDetail,
diff --git a/apps/web/src/lib/split-router/tests/router.test.ts b/apps/web/src/lib/split-router/tests/router.test.ts
index 052ca09667..345c63948e 100644
--- a/apps/web/src/lib/split-router/tests/router.test.ts
+++ b/apps/web/src/lib/split-router/tests/router.test.ts
@@ -5,7 +5,7 @@ import * as path from '../path';
import { createSplitRouter } from '../router';
import { defineRoute, rootRouteMatch, routeParams } from '../routes';
import type {
- SplitRouterEntry,
+ SplitLocation,
SplitRouterExternalLocation,
SplitRouterExternalLocationValue,
SplitRouterLayout,
@@ -17,7 +17,9 @@ import type {
type Layout = SplitRouterLayout<string> & {
reconcileCount(): number;
+ updateCount(): number;
activatedSplitId(): string | undefined;
+ swapEntries(): void;
};
const driveFolderRoute = defineRoute({
@@ -33,6 +35,7 @@ const routes: SplitRoutes = {
id: 'drive',
path: 'drive',
search: ['drive'],
+ state: z.record(z.string(), z.unknown()),
children: [driveFolderRoute],
}),
{
@@ -47,6 +50,7 @@ const routes: SplitRoutes = {
function createLayout(): Layout {
let nextId = 0;
let reconciliations = 0;
+ let updates = 0;
let activatedSplitId: string | undefined;
let entries: SplitRouterLayoutSnapshot<string>['entries'] = [];
const listeners = new Set<(change: SplitRouterSettledChange) => void>();
@@ -60,18 +64,21 @@ function createLayout(): Layout {
return {
snapshot: () => ({ entries }),
- updateCurrentEntry(splitId, update) {
- entries = entries.map((entry) =>
- entry.splitId === splitId ? { splitId, ...update(entry) } : entry
- );
+ updateCurrentLocation(splitId, update) {
+ updates += 1;
+ entries = entries.map((entry) => {
+ if (entry.splitId !== splitId) return entry;
+ return { splitId, location: update(entry) };
+ });
notify();
},
- open({ location, target, replace }) {
+ open({ target, replace, ...entry }) {
const next = {
splitId: `split-${++nextId}`,
- location,
+ ...entry,
};
+ let openedId = next.splitId;
if (target === 'new-split' || !target) {
entries = [...entries, next];
} else {
@@ -80,23 +87,25 @@ function createLayout(): Layout {
if (index < 0) {
entries = [...entries, next];
} else {
+ openedId = entries[index]!.splitId;
entries = entries.with(index, {
...next,
- splitId: entries[index]!.splitId,
+ splitId: openedId,
});
}
}
notify(replace ? 'replace' : 'push');
+ return { status: 'applied', splitId: openedId };
},
- reconcile(nextEntries) {
+ reconcile(nextLocations) {
reconciliations++;
- entries = nextEntries.map((entry, index) => {
+ entries = nextLocations.map((location, index) => {
const current = entries[index];
return {
splitId: current?.splitId ?? `split-${++nextId}`,
- ...entry,
+ location,
};
});
notify('replace');
@@ -112,7 +121,12 @@ function createLayout(): Layout {
},
reconcileCount: () => reconciliations,
+ updateCount: () => updates,
activatedSplitId: () => activatedSplitId,
+ swapEntries() {
+ entries = entries.toReversed();
+ notify();
+ },
};
}
@@ -251,7 +265,7 @@ describe('split router', () => {
});
it('rejects unresolved host snapshots before accepting state or committing a URL', () => {
const layout = createLayout();
- layout.reconcile([{ location: {} } as SplitRouterEntry]);
+ layout.reconcile([{} as SplitLocation]);
const location = createMemorySplitRouterLocation('/drive');
expect(() => createSplitRouter({ layout, routes, location })).toThrow(
'nonempty match branch'
@@ -295,7 +309,7 @@ describe('split router', () => {
router.navigate(splitId, 'folder/two');
await settle();
- expect(location.read()).toEqual({
+ expect(location.read()).toMatchObject({
pathname: '/drive/folder/two',
search: '?s0.drive.sort=created_at',
hash: '',
@@ -891,6 +905,296 @@ describe('split router', () => {
expect(routeParams(router.route(splitId)).folderId).toBe('two');
});
+ it('restores distinct state for duplicate URLs across browser Back and Forward', async () => {
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, '/drive/folder/one', {
+ state: { breadcrumb: 'first' },
+ });
+ await router.settled();
+ router.navigate(splitId, '/drive/folder/one', {
+ state: { breadcrumb: 'second' },
+ });
+ await router.settled();
+
+ expect(layout.updateCount()).toBe(0);
+ const entries = router.history(splitId)!.entries;
+ expect(entries).toHaveLength(3);
+ expect(entries[1]?.key).not.toBe(entries[2]?.key);
+ expect(router.entry(splitId)?.state).toEqual({ breadcrumb: 'second' });
+
+ expect(location.back()).toBe(true);
+ await router.settled();
+ expect(router.entry(splitId)?.state).toEqual({ breadcrumb: 'first' });
+
+ expect(location.forward()).toBe(true);
+ await router.settled();
+ expect(router.entry(splitId)?.state).toEqual({ breadcrumb: 'second' });
+
+ router.navigate(splitId, '/drive/folder/one', {
+ replace: true,
+ state: { breadcrumb: 'replacement' },
+ });
+ await router.settled();
+ expect(location.history()).toHaveLength(3);
+ expect(router.entry(splitId)?.state).toEqual({
+ breadcrumb: 'replacement',
+ });
+ expect(location.back()).toBe(true);
+ await router.settled();
+ expect(location.forward()).toBe(true);
+ await router.settled();
+ expect(router.entry(splitId)?.state).toEqual({
+ breadcrumb: 'replacement',
+ });
+ });
+
+ it('preserves router metadata when duplicate-URL panes swap', async () => {
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/one'
+ );
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const [first, second] = layout.snapshot().entries;
+
+ router.navigate(first!.splitId, '/drive/folder/one', {
+ state: { breadcrumb: 'first' },
+ });
+ router.navigate(second!.splitId, '/drive/folder/one', {
+ state: { breadcrumb: 'second' },
+ });
+ await router.settled();
+ const browserStateBeforeSwap = location.read().state;
+
+ layout.swapEntries();
+ await router.settled();
+
+ expect(layout.snapshot().entries.map((entry) => entry.splitId)).toEqual([
+ second!.splitId,
+ first!.splitId,
+ ]);
+ expect(router.entry(first!.splitId)?.state).toEqual({
+ breadcrumb: 'first',
+ });
+ expect(router.entry(second!.splitId)?.state).toEqual({
+ breadcrumb: 'second',
+ });
+ expect(location.read().state).not.toEqual(browserStateBeforeSwap);
+ });
+
+ it('observes a duplicate-pane swap during a queued layout echo', async () => {
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const first = layout.snapshot().entries[0]!;
+
+ router.navigate(first.splitId, '/drive/folder/one', {
+ state: { breadcrumb: 'first' },
+ });
+ await router.settled();
+ router.navigate(first.splitId, '/drive/folder/one', {
+ target: 'new-split',
+ allowDuplicate: true,
+ state: { breadcrumb: 'second' },
+ });
+ const browserStateBeforeSwap = location.read().state;
+
+ layout.swapEntries();
+ await router.settled();
+
+ expect(location.read().state).not.toEqual(browserStateBeforeSwap);
+ const second = layout
+ .snapshot()
+ .entries.find((entry) => entry.splitId !== first.splitId)!;
+ expect(layout.snapshot().entries[0]?.splitId).toBe(second.splitId);
+ expect(router.entry(first.splitId)?.state).toEqual({
+ breadcrumb: 'first',
+ });
+ expect(router.entry(second.splitId)?.state).toEqual({
+ breadcrumb: 'second',
+ });
+ });
+
+ it('snapshots cloneable state and drops state that cannot be cloned', async () => {
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+ const state = { breadcrumbs: ['one'] };
+
+ router.navigate(splitId, '/drive/folder/two', { state });
+ state.breadcrumbs.push('mutated');
+ await router.settled();
+
+ expect(router.entry(splitId)?.state).toEqual({ breadcrumbs: ['one'] });
+
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ router.navigate(splitId, '/drive/folder/three', {
+ state: { callback: () => undefined },
+ });
+ await router.settled();
+
+ expect(routeParams(router.route(splitId)).folderId).toBe('three');
+ expect(router.entry(splitId)?.state).toBeUndefined();
+ expect(warn).toHaveBeenCalledOnce();
+ });
+
+ it('passes parsed output to state updaters without reparsing it', async () => {
+ let parses = 0;
+ const stateRoute = defineRoute({
+ id: 'state',
+ path: 'state',
+ state: z.object({ value: z.string() }).transform(({ value }) => ({
+ value,
+ parseNumber: ++parses,
+ })),
+ });
+ const location = createMemorySplitRouterLocation('/state');
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes: { definitions: [stateRoute] },
+ location,
+ });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, '/state', { state: { value: 'first' } });
+ await router.settled();
+ expect(router.entry(splitId)?.state).toEqual({
+ value: 'first',
+ parseNumber: 1,
+ });
+
+ router.navigate(splitId, '/state', {
+ state: (current) => ({
+ value: `${(current as { value: string }).value}-second`,
+ }),
+ });
+ await router.settled();
+ expect(router.entry(splitId)?.state).toEqual({
+ value: 'first-second',
+ parseNumber: 2,
+ });
+ });
+
+ it('rejects local state that the destination route does not accept', async () => {
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ expect(() =>
+ router.navigate(splitId, '/drive/folder/two', { state: 'invalid' })
+ ).toThrow('rejected navigation state');
+ expect(() =>
+ router.navigate(splitId, '/legacy/one', {
+ state: { unsupported: true },
+ })
+ ).toThrow('rejected navigation state');
+ expect(routeParams(router.route(splitId)).folderId).toBe('one');
+ });
+
+ it('validates navigation state against a middleware redirect destination', async () => {
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ path, redirect }) =>
+ path === '/drive/folder/two' ? redirect('/legacy/two') : undefined,
+ ],
+ });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, '/drive/folder/two', {
+ state: { breadcrumb: 'two' },
+ });
+ await router.settled();
+
+ expect(rootRouteMatch(router.route(splitId))?.id).toBe('legacy');
+ expect(router.entry(splitId)?.state).toBeUndefined();
+ });
+
+ it('drops restored state that the destination route does not accept', async () => {
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ location.set(
+ {
+ pathname: '/drive/folder/two',
+ search: '',
+ hash: '',
+ state: {
+ __macroSplitRouter: {
+ entries: [{ key: 'restored-entry', state: 'invalid' }],
+ },
+ },
+ },
+ { replace: true }
+ );
+ await router.settled();
+
+ expect(routeParams(router.route(splitId)).folderId).toBe('two');
+ expect(router.entry(splitId)?.state).toBeUndefined();
+ });
+
+ it('treats an external URL without state as a fresh entry', async () => {
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, '/drive/folder/one', {
+ replace: true,
+ state: { breadcrumb: 'stored' },
+ });
+ await router.settled();
+ const storedKey = router.entry(splitId)?.key;
+
+ location.set('/drive/folder/one', { replace: true });
+ await router.settled();
+
+ expect(router.entry(splitId)?.key).not.toBe(storedKey);
+ expect(router.entry(splitId)?.state).toBeUndefined();
+ });
+
+ it('preserves entry state through search pushes and replacements', async () => {
+ const location = createMemorySplitRouterLocation('/drive/folder/one');
+ const layout = createLayout();
+ const router = createSplitRouter({ layout, routes, location });
+ const splitId = layout.snapshot().entries[0]!.splitId;
+
+ router.navigate(splitId, '/drive/folder/two', {
+ state: (current) => ({ previous: current, breadcrumb: 'two' }),
+ });
+ await router.settled();
+ const routeKey = router.entry(splitId)?.key;
+ const state = router.entry(splitId)?.state;
+
+ router.updateSearch(splitId, 'drive', { sort: ['name'] });
+ await router.settled();
+ const pushedKey = router.entry(splitId)?.key;
+ expect(pushedKey).not.toBe(routeKey);
+ expect(router.entry(splitId)?.state).toBe(state);
+
+ router.updateSearch(
+ splitId,
+ 'drive',
+ { sort: ['created_at'] },
+ { history: 'replace' }
+ );
+ await router.settled();
+ expect(router.entry(splitId)?.key).toBe(pushedKey);
+ expect(router.entry(splitId)?.state).toBe(state);
+ });
+
it('restores search state during history traversal', async () => {
const location = createMemorySplitRouterLocation('/drive/folder/one');
const layout = createLayout();
@@ -1014,7 +1318,7 @@ describe('split router', () => {
await settle();
expect(location.history()).toHaveLength(2);
- expect(location.read()).toEqual({
+ expect(location.read()).toMatchObject({
pathname: '/drive/folder/two',
search: '?s0.drive.sort=created_at',
hash: '',
@@ -1353,6 +1657,8 @@ describe('split router', () => {
const layout = createLayout();
const router = createSplitRouter({ layout, routes, location });
const splitId = layout.snapshot().entries[0]!.splitId;
+ // Initialization adds the router's opaque entry metadata with replacement.
+ flush();
router.updateSearch(splitId, 'drive', { sort: ['name'] });
router.updateSearch(splitId, 'drive', { sort: ['created_at'] });
diff --git a/apps/web/src/lib/split-router/tests/routes.test.ts b/apps/web/src/lib/split-router/tests/routes.test.ts
index 5c015a58dd..2cc6f970e8 100644
--- a/apps/web/src/lib/split-router/tests/routes.test.ts
+++ b/apps/web/src/lib/split-router/tests/routes.test.ts
@@ -9,6 +9,8 @@ import {
findRouteBranch,
getExternalSearchKeys,
getRouteClaim,
+ getRouteEntryState,
+ parseRouteEntryState,
routeParams,
validateRouteParams,
validateSplitRoutes,
@@ -17,6 +19,8 @@ import type {
InferSplitRouteBranchParams,
InferSplitRouteNavigationParams,
InferSplitRouteParams,
+ InferSplitRouteState,
+ InferSplitRouteStateInput,
SplitRoutes,
} from '../types';
@@ -31,6 +35,7 @@ const driveRoute = defineRoute({
aliases: ['files'],
params: z.object({}),
search: ['drive'],
+ state: z.object({ trail: z.array(z.string()) }),
externalSearch: ['action'],
children: [
{
@@ -157,6 +162,68 @@ function assertInvalidRouteDeclarations() {
});
}
+describe('route entry state schemas', () => {
+ it('parses inherited state and exposes it through the owning branch', () => {
+ const entry = decodeRoute(routes, [
+ 'drive',
+ 'folder',
+ 'folder-id',
+ 'pdf',
+ 'document-id',
+ ])!;
+ const state = { trail: ['first', 'second'] };
+ const parsed = parseRouteEntryState(routes, entry.location.route, state);
+
+ expect(parsed).toEqual({ success: true, value: state });
+ expect(
+ getRouteEntryState(
+ routes,
+ { ...entry, state: parsed.success ? parsed.value : undefined },
+ driveRoute.children[0].children[0]
+ )
+ ).toEqual(state);
+ });
+
+ it('uses the deepest state schema and does not expose it through an overridden owner', () => {
+ const root = defineRoute({
+ id: 'root-state',
+ path: 'root',
+ state: z.object({ root: z.string() }),
+ children: [
+ {
+ id: 'child-state',
+ path: 'child',
+ state: z.object({ child: z.number() }),
+ },
+ ],
+ });
+ const child = root.children[0];
+ const manifest = createRoutesManifest({ definitions: [root] });
+ const entry = {
+ ...decodeRoute(manifest, ['root', 'child'])!,
+ state: { child: 1 },
+ };
+
+ expect(getRouteEntryState(manifest, entry, root)).toBeUndefined();
+ expect(getRouteEntryState(manifest, entry, child)).toEqual({ child: 1 });
+ expectTypeOf<InferSplitRouteState<typeof child>>().toEqualTypeOf<{
+ child: number;
+ }>();
+ });
+
+ it('rejects state outside an owning branch or outside its schema', () => {
+ const drive = decodeRoute(routes, ['drive'])!;
+ const legacy = decodeRoute(routes, ['legacy', 'one'])!;
+
+ expect(
+ parseRouteEntryState(routes, drive.location.route, { trail: 42 })
+ ).toEqual({ success: false });
+ expect(
+ parseRouteEntryState(routes, legacy.location.route, { trail: [] })
+ ).toEqual({ success: false });
+ });
+});
+
describe('typed route trees', () => {
it('checks declaration contracts without widening node inference', () => {
expectTypeOf(assertInvalidRouteDeclarations).toBeFunction();
@@ -187,6 +254,12 @@ describe('typed route trees', () => {
folderId: string;
documentId: string;
}>();
+ expectTypeOf<InferSplitRouteState<typeof detail>>().toEqualTypeOf<{
+ trail: string[];
+ }>();
+ expectTypeOf<InferSplitRouteStateInput<typeof detail>>().toEqualTypeOf<{
+ trail: string[];
+ }>();
});
it('types descendants directly from a named definition before assembly', () => {
diff --git a/apps/web/src/lib/split-router/tests/solid.test.tsx b/apps/web/src/lib/split-router/tests/solid.test.tsx
index aa99e207ac..06497bfa32 100644
--- a/apps/web/src/lib/split-router/tests/solid.test.tsx
+++ b/apps/web/src/lib/split-router/tests/solid.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, render } from '@solidjs/testing-library';
+import { cleanup, fireEvent, render } from '@solidjs/testing-library';
import { type Accessor, onCleanup } from 'solid-js';
import { afterEach, describe, expect, expectTypeOf, it, vi } from 'vitest';
import { z } from 'zod';
@@ -14,13 +14,14 @@ import {
useNavigate,
useParams,
useRouteParams,
+ useRouteState,
useSplitHistory,
useSplitRouter,
} from '../solid';
import type {
- SplitRouterEntry,
SplitRouterHistorySnapshot,
SplitRouterLayout,
+ SplitRouterLayoutEntry,
SplitRouterSettledChange,
SplitRoutes,
} from '../types';
@@ -38,7 +39,7 @@ function CoercedParamsView() {
}
function createLayout(): SplitRouterLayout<string> {
- let entry: (SplitRouterEntry & { splitId: string }) | undefined;
+ let entry: SplitRouterLayoutEntry<string> | undefined;
const listeners = new Set<(change: SplitRouterSettledChange) => void>();
const notify = () => {
for (const listener of listeners) {
@@ -50,15 +51,15 @@ function createLayout(): SplitRouterLayout<string> {
snapshot: () => ({
entries: entry ? [entry] : [],
}),
- updateCurrentEntry(_splitId, update) {
+ updateCurrentLocation(_splitId, update) {
if (!entry) return;
- entry = { splitId: entry.splitId, ...update(entry) };
+ entry = { splitId: entry.splitId, location: update(entry) };
notify();
},
- open: () => {},
- reconcile(entries) {
- const next = entries[0];
- entry = next ? { splitId: 'split', ...next } : undefined;
+ open: () => ({ status: 'unavailable' }),
+ reconcile(locations) {
+ const location = locations[0];
+ entry = location ? { splitId: 'split', location } : undefined;
notify();
},
activate: () => {},
@@ -104,6 +105,61 @@ afterEach(() => {
});
describe('Solid split router hooks', () => {
+ it('reads inherited route state and types navigation state', () => {
+ const root = defineRoute({
+ id: 'state-root',
+ path: 'state',
+ state: z
+ .object({ trail: z.array(z.string()) })
+ .transform((state) => ({ ...state, length: state.trail.length })),
+ children: [{ id: 'state-child', path: 'item/:id' }],
+ });
+ const child = root.children[0];
+
+ function StateView() {
+ const state = useRouteState(root);
+ const navigate = useNavigate();
+ expectTypeOf(state()).toEqualTypeOf<
+ { trail: string[]; length: number } | undefined
+ >();
+ return (
+ <button
+ type="button"
+ onClick={() =>
+ navigate(
+ { route: child, params: { id: 'one' } },
+ {
+ state: (current) => ({
+ trail: [
+ ...(current?.trail ?? []),
+ `one-${current?.length ?? 0}`,
+ ],
+ }),
+ }
+ )
+ }
+ >
+ {state()?.trail.join('/') ?? 'empty'}
+ </button>
+ );
+ }
+
+ const result = render(() => (
+ <SplitRouter.Root
+ layout={createLayout()}
+ routes={{ definitions: [root] }}
+ location={createMemorySplitRouterLocation('/state')}
+ >
+ <SplitRouter.Scope splitId="split">
+ <StateView />
+ </SplitRouter.Scope>
+ </SplitRouter.Root>
+ ));
+
+ fireEvent.click(result.getByRole('button'));
+ expect(result.getByRole('button').textContent).toBe('one-0');
+ });
+
it('reads typed branch params only through the referenced node and stays reactive', () => {
const tree = defineRoutes({
definitions: [
@@ -269,16 +325,13 @@ describe('Solid split router hooks', () => {
));
const setChild = (itemId: string) => {
- layout.updateCurrentEntry('split', (entry) => ({
- ...entry,
- location: {
- ...entry.location,
- route: {
- matches: [
- { id: 'parent', params: {} },
- { id: 'child', params: { itemId } },
- ],
- },
+ layout.updateCurrentLocation('split', (entry) => ({
+ ...entry.location,
+ route: {
+ matches: [
+ { id: 'parent', params: {} },
+ { id: 'child', params: { itemId } },
+ ],
},
}));
};
diff --git a/apps/web/src/lib/split-router/tests/url.test.ts b/apps/web/src/lib/split-router/tests/url.test.ts
index 24dbe4ac2d..910eca1f83 100644
--- a/apps/web/src/lib/split-router/tests/url.test.ts
+++ b/apps/web/src/lib/split-router/tests/url.test.ts
@@ -6,6 +6,7 @@ import {
decodeRouteLayout,
decodeSplitRouterLocation,
encodeRouteLayout,
+ encodeSplitRouterLocation,
formatRoutePathname,
parseRoutePathname,
serializeSplitRouterLocation,
@@ -17,6 +18,7 @@ const routeDefinitions: SplitRoutes = {
id: 'drive',
path: 'drive',
search: ['drive'],
+ state: z.record(z.string(), z.unknown()),
children: [{ id: 'folder', path: 'folder/:folderId' }],
},
{ id: 'legacy', path: 'legacy/:id' },
@@ -147,6 +149,64 @@ describe('split layout URLs', () => {
).toBeUndefined();
});
+ it('round trips route entry state outside the serialized URL', () => {
+ const entry = {
+ ...decodeRoute(routes, ['drive', 'folder', 'one'])!,
+ key: 'entry-1',
+ state: { feature: { root: 'document-1' } },
+ };
+ const external = encodeSplitRouterLocation({
+ routes,
+ entries: [entry],
+ previous: {
+ pathname: '/drive',
+ search: '',
+ hash: '',
+ state: { unrelated: 'preserved' },
+ },
+ });
+
+ expect(external.state).toMatchObject({
+ unrelated: 'preserved',
+ __macroSplitRouter: {
+ entries: [
+ {
+ key: 'entry-1',
+ state: { feature: { root: 'document-1' } },
+ },
+ ],
+ },
+ });
+ expect(
+ serializeSplitRouterLocation({
+ routes,
+ entries: [entry],
+ previous: external,
+ })
+ ).toBe('/drive/folder/one');
+ expect(
+ decodeSplitRouterLocation({ routes, location: external }).entries[0]
+ ).toEqual(entry);
+ });
+
+ it('ignores malformed browser entry state', () => {
+ const decoded = decodeSplitRouterLocation({
+ routes,
+ location: {
+ pathname: '/drive',
+ search: '',
+ hash: '',
+ state: {
+ __macroSplitRouter: {
+ entries: [{ key: 42, state: { ignored: true } }],
+ },
+ },
+ },
+ });
+
+ expect(decoded.entries).toEqual([decodeRoute(routes, ['drive'])!]);
+ });
+
it('preserves owned query values and hashes without keeping unrelated search', () => {
const previous =
'/drive/folder/one?s0.drive.tags=b&s0.drive.tags=a&s0.other.x=1&referral_code=ref&unowned=1#heading';
diff --git a/apps/web/src/lib/split-router/types.ts b/apps/web/src/lib/split-router/types.ts
index e60945084b..b8c992d8c5 100644
--- a/apps/web/src/lib/split-router/types.ts
+++ b/apps/web/src/lib/split-router/types.ts
@@ -73,6 +73,7 @@ export type SplitRouterMiddlewareRun =
type SplitRouteReference = {
id: string;
params?: StandardSchemaV1;
+ state?: StandardSchemaV1;
};
type SplitRouteTargetParams<TRoute extends SplitRouteReference> =
@@ -103,10 +104,30 @@ export type SplitNavigateTo =
params?: unknown;
};
-export type SplitNavigateOptions<TSplitId> = {
+export type SplitRouterEntryState =
+ | object
+ | string
+ | number
+ | bigint
+ | boolean
+ | null
+ | undefined;
+
+export type SplitRouterStateUpdate<
+ TInput = SplitRouterEntryState,
+ TOutput = TInput,
+> = TInput | ((current: TOutput | undefined) => TInput);
+
+export type SplitNavigateOptions<
+ TSplitId,
+ TStateInput = SplitRouterEntryState,
+ TStateOutput = TStateInput,
+> = {
replace?: boolean;
target?: 'current' | 'new-split' | TSplitId;
search?: Record<string, SplitSearchUpdate>;
+ /** State parsed by the destination route's synchronous state schema. */
+ state?: SplitRouterStateUpdate<TStateInput, TStateOutput>;
/** Bypasses final-destination claims and pending reservations, including history
* traversal. The host layout may still enforce stricter duplicate policy. */
allowDuplicate?: boolean;
@@ -134,7 +155,11 @@ export type SplitLocation = {
};
export type SplitRouterEntry = {
+ /** Stable identity for this history entry. Generated by the router when omitted. */
+ key?: string;
location: SplitLocation;
+ /** Immutable output of the active route's state schema. */
+ state?: SplitRouterEntryState;
};
type SplitRouteParamCallback<TParams, TResult> = {
@@ -154,6 +179,7 @@ export type SplitRouteDefinition<
component?: TComponent;
children?: readonly SplitRouteDefinition<TComponent>[];
params?: TParamsSchema;
+ state?: StandardSchemaV1;
serializeParams?: SplitRouteParamCallback<
StandardSchemaV1.InferOutput<TParamsSchema>,
SplitRouteRawParams
@@ -259,6 +285,35 @@ type LocalNavigationParams<TRoute> = TRoute extends { params: StandardSchemaV1 }
// 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 };
@@ -286,52 +341,64 @@ type BranchParams<TParams> =
}
: TParams;
-type DefinedRoute<TRoute, TParent, TParentNavigation> = TRoute extends unknown
- ? Omit<TRoute, 'children' | typeof branchParams> & {
- readonly [branchParams]: {
- read: MergeRouteParams<
- TParent,
- BranchParams<InferSplitRouteParams<TRoute>>
- >;
- navigate: MergeRouteParams<
- {},
- TParentNavigation & BranchParams<LocalNavigationParams<TRoute>>
- >;
- };
- } & (TRoute extends { children: infer TChildren extends readonly unknown[] }
- ? {
- readonly children: DefinedRouteList<
- TChildren,
- MergeRouteParams<
- TParent,
- BranchParams<InferSplitRouteParams<TRoute>>
- >,
- TParentNavigation & BranchParams<LocalNavigationParams<TRoute>>
- >;
- }
- : Pick<TRoute, Extract<keyof TRoute, 'children'>>)
- : never;
+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
+ TParentNavigation,
+ TParentStateSchema
>;
};
/** One original definition with descendant ancestry inferred from this root. */
-export type DefinedSplitRoute<TRoute> = DefinedRoute<TRoute, {}, {}>;
+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'], {}, {}>;
+ readonly definitions: DefinedRouteList<
+ TRoutes['definitions'],
+ {},
+ {},
+ undefined
+ >;
};
type RouteUnion<TRoute> = TRoute extends { children: readonly (infer TChild)[] }
@@ -360,8 +427,9 @@ export type SplitRoutes<TComponent = unknown> = {
basePath?: string | readonly string[];
};
-export type SplitRouterLayoutEntry<TSplitId> = SplitRouterEntry & {
+export type SplitRouterLayoutEntry<TSplitId> = {
splitId: TSplitId;
+ location: SplitLocation;
};
export type SplitRouterLayoutSnapshot<TSplitId> = {
@@ -373,23 +441,26 @@ export type SplitRouterSettledChange = {
};
export type SplitRouterHistorySnapshot = {
- entries: readonly SplitLocation[];
+ entries: readonly SplitRouterEntry[];
index: number;
};
+export type SplitRouterLayoutOpenResult<TSplitId> =
+ | { status: 'applied'; splitId: TSplitId }
+ | { status: 'unavailable' };
+
export interface SplitRouterLayout<TSplitId> {
snapshot(): SplitRouterLayoutSnapshot<TSplitId>;
- updateCurrentEntry(
+ updateCurrentLocation(
splitId: TSplitId,
- update: (current: SplitRouterLayoutEntry<TSplitId>) => SplitRouterEntry
- ): void;
- open(
- request: SplitRouterEntry & {
- target?: TSplitId | 'new-split';
- replace?: boolean;
- }
+ update: (current: SplitRouterLayoutEntry<TSplitId>) => SplitLocation
): void;
- reconcile(entries: SplitRouterEntry[]): void;
+ open(request: {
+ location: SplitLocation;
+ target?: TSplitId | 'new-split';
+ replace?: boolean;
+ }): SplitRouterLayoutOpenResult<TSplitId>;
+ reconcile(locations: SplitLocation[]): void;
activate(splitId: TSplitId): void;
subscribe(listener: (change: SplitRouterSettledChange) => void): () => void;
}
@@ -398,6 +469,8 @@ export type SplitRouterExternalLocationValue = {
pathname: string;
search: string;
hash: string;
+ /** Opaque browser history state. It is never encoded into the URL. */
+ state?: unknown;
};
export interface SplitRouterExternalLocation {
@@ -418,16 +491,30 @@ export type SplitRouterOptions<TSplitId> = {
middleware?: readonly SplitRouterMiddleware[];
};
+export type SplitRouteNavigateOptions<TSplitId, TRoute> = Omit<
+ SplitNavigateOptions<TSplitId>,
+ 'state'
+> &
+ ([InferSplitRouteStateInput<TRoute>] extends [never]
+ ? { state?: never }
+ : {
+ state?: SplitRouterStateUpdate<
+ InferSplitRouteStateInput<TRoute>,
+ InferSplitRouteState<TRoute>
+ >;
+ });
+
export type SplitNavigate<TSplitId> = {
<const TTarget extends { route: SplitRouteReference }>(
to: TTarget & SplitRouteNavigationTarget<NoInfer<TTarget['route']>>,
- options?: SplitNavigateOptions<TSplitId>
+ options?: SplitRouteNavigateOptions<TSplitId, TTarget['route']>
): void;
(to: SplitNonRouteNavigateTo, options?: SplitNavigateOptions<TSplitId>): void;
};
export interface SplitRouter<TSplitId> {
readonly routes: SplitRoutesManifest;
+ entry(splitId: TSplitId): SplitRouterEntry | undefined;
route(splitId: TSplitId): SplitRouteState | undefined;
location(splitId: TSplitId): SplitLocation | undefined;
search(
@@ -437,7 +524,7 @@ export interface SplitRouter<TSplitId> {
navigate<const TTarget extends { route: SplitRouteReference }>(
splitId: TSplitId,
to: TTarget & SplitRouteNavigationTarget<NoInfer<TTarget['route']>>,
- options?: SplitNavigateOptions<TSplitId>
+ options?: SplitRouteNavigateOptions<TSplitId, TTarget['route']>
): void;
navigate(
splitId: TSplitId,
diff --git a/apps/web/src/lib/split-router/url.ts b/apps/web/src/lib/split-router/url.ts
index 5cdd969b55..99a558870c 100644
--- a/apps/web/src/lib/split-router/url.ts
+++ b/apps/web/src/lib/split-router/url.ts
@@ -1,3 +1,4 @@
+import { mergeBrowserEntries, parseBrowserEntries } from './entry-state';
import {
assertRouteEntry,
decodeRoute,
@@ -38,11 +39,13 @@ export function parseExternalLocation(
value: string | SplitRouterExternalLocationValue
): SplitRouterExternalLocationValue {
if (typeof value !== 'string') {
- return {
+ const location: SplitRouterExternalLocationValue = {
pathname: value.pathname || '/',
search: addPrefix(value.search, '?'),
hash: addPrefix(value.hash, '#'),
};
+ if (Object.hasOwn(value, 'state')) location.state = value.state;
+ return location;
}
const parsed = new URL(value, 'https://split-router.invalid');
@@ -63,10 +66,9 @@ export function parseRoutePathname(
.split('/')
.filter(Boolean);
const base = routes.basePath;
- const segments =
- base.length > 0 && base.every((part, index) => raw[index] === part)
- ? raw.slice(base.length)
- : raw;
+ let segments = raw;
+ const startsWithBase = base.every((part, index) => raw[index] === part);
+ if (base.length > 0 && startsWithBase) segments = raw.slice(base.length);
try {
return segments.map(decodeURIComponent);
@@ -102,9 +104,10 @@ export function decodeRouteLayout(
routes: SplitRoutesManifest,
segments: string[]
): SplitRouterEntry[] {
- const parts = segments.includes(SPLIT_PATH_SEPARATOR)
- ? framedParts(segments)
- : [segments];
+ let parts = [segments];
+ if (segments.includes(SPLIT_PATH_SEPARATOR)) {
+ parts = framedParts(segments);
+ }
const decoded = parts.map((part) => decodeRoute(routes, part));
if (decoded.length > 0 && decoded.every(Boolean)) {
@@ -136,7 +139,8 @@ export function encodeRouteLayout(
return entries.flatMap((entry, index) => {
const segments = encodeRoute(routes, entry);
- return index === 0 ? segments : [SPLIT_PATH_SEPARATOR, ...segments];
+ if (index === 0) return segments;
+ return [SPLIT_PATH_SEPARATOR, ...segments];
});
}
@@ -155,23 +159,30 @@ export function decodeSplitRouterLocation(options: {
externalLocation.pathname
);
const search = parseSplitSearch(externalLocation.search);
- const entries = decodeRouteLayout(options.routes, segments ?? []).map(
- (entry, index) => {
- const route = entry.location.route;
- const splitSearch = filterRouteSearch(
- options.routes,
- route,
- search.get(index)
- );
-
- return {
- location: {
- ...entry.location,
- ...(splitSearch ? { search: splitSearch } : {}),
- },
- };
+ const browserEntries = parseBrowserEntries(externalLocation.state);
+ const decodedEntries = decodeRouteLayout(options.routes, segments ?? []);
+ let entryState: typeof browserEntries;
+ if (browserEntries?.length === decodedEntries.length) {
+ entryState = browserEntries;
+ }
+ const entries = decodedEntries.map((entry, index) => {
+ const route = entry.location.route;
+ const splitSearch = filterRouteSearch(
+ options.routes,
+ route,
+ search.get(index)
+ );
+ const browserEntry = entryState?.[index];
+ const decoded: SplitRouterEntry = {
+ location: { ...entry.location },
+ };
+ if (splitSearch) decoded.location.search = splitSearch;
+ if (browserEntry?.key) decoded.key = browserEntry.key;
+ if (browserEntry && Object.hasOwn(browserEntry, 'state')) {
+ decoded.state = browserEntry.state;
}
- );
+ return decoded;
+ });
return { entries, externalLocation };
}
@@ -187,10 +198,12 @@ export function encodeSplitRouterLocation(options: {
options.routes,
encodeRouteLayout(options.routes, options.entries)
);
- const ownedSearch =
- options.preserveExternalSearch === false
- ? new Set(options.routes.globalSearch ?? [])
- : getExternalSearchKeys(options.routes, options.entries);
+ let ownedSearch: ReadonlySet<string>;
+ if (options.preserveExternalSearch === false) {
+ ownedSearch = new Set(options.routes.globalSearch ?? []);
+ } else {
+ ownedSearch = getExternalSearchKeys(options.routes, options.entries);
+ }
const query = new URLSearchParams();
for (const [key, value] of new URLSearchParams(options.previous.search)) {
@@ -218,11 +231,17 @@ export function encodeSplitRouterLocation(options: {
pathname.replace(/\/+$/g, '') !==
options.previous.pathname.replace(/\/+$/g, '');
- return {
+ const encoded: SplitRouterExternalLocationValue = {
pathname,
- search: search ? `?${search}` : '',
- hash: !pathChanged || options.preserveHash ? options.previous.hash : '',
+ search: '',
+ hash: '',
+ state: mergeBrowserEntries(options.previous.state, options.entries),
};
+ if (search) encoded.search = `?${search}`;
+ if (!pathChanged || options.preserveHash) {
+ encoded.hash = options.previous.hash;
+ }
+ return encoded;
}
export function serializeSplitRouterLocation(options: {