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.

fix(tabs): keep background desktop tabs mounted so switching is instant (#9441)

Eric Hayes3469707ecc8c
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 0ff96cdcd5..524b8e0201 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -468,7 +468,7 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to
- Keep split chrome portal targets reactive so cached views can mount before their header, and clear a retiring header's targets only while it still owns them.
- Opt views into session restoration with `split-layout/view-restoration` and set `resume: true` on ordinary layout navigation; publish captured state only through the leave guard's `onCommit`, keep explicit links and new splits fresh, and reuse entry-state captors rather than hidden mounted views.
- Let `ViewShell.TopBar` own split close and navigation controls; do not add a second split close button inside Agents headers or their preview `headerLeading`.
-- Desktop tabs (`components/app/tab-layout`, macOS + `enable-desktop-tabs`) hold one split layout per tab over the router's `layoutSnapshot`/`restoreLayout`; only the active tab is live, and the strip renders in the title bar's center slot. Cmd+click becomes a background tab through `openInNewTabMiddleware`, so tab operations must disarm the intent tracker before navigating. Tabs are not draggable. See the tabs section of `docs/agent-guide/navigation.md` at the repository root.
+- Desktop tabs (`components/app/tab-layout`, macOS + `enable-desktop-tabs`) hold one split layout per tab. Switching parks the active tab's panes (`router.openLayout`/`showLayout`) instead of removing them; the split manager keeps parked splits and `SplitLayout` renders one layer per tab, hiding background layers with `content-visibility` and `inert` without unmounting them. Up to `MAX_PARKED_TABS` stay mounted. The strip renders in the title bar's center slot. Cmd+click becomes a background tab through `openInNewTabMiddleware`, so tab operations must disarm the intent tracker before navigating. Tabs are not draggable. See the tabs section of `docs/agent-guide/navigation.md` at the repository root.
- Show only the Recent conversation feed in mobile Channels, without view tabs or a persisted mobile tab selection; render its rows with Home's touch row (`ChannelCardLayout` and `InboxDivider`) and pin at most six channel favorites above it.
- Mount the mobile search input before focusing it inside the dock tap; keep navigation in that handler so focus does not trigger a second navigation or lose iOS keyboard activation.
- Preserve focused chrome editors during deferred split insertion/removal/content-change autofocus; explicit return-focus commands may still focus the pane. On desktop, content changes claim focus only for Cmd+K navigation or create-menu arrivals, and only if the destination has not already focused a child. Back/forward and ordinary clicks do not autofocus content.
diff --git a/apps/web/src/components/app/split-layout/SplitLayout.tsx b/apps/web/src/components/app/split-layout/SplitLayout.tsx
index 4f6da83c90..12231e7de6 100644
--- a/apps/web/src/components/app/split-layout/SplitLayout.tsx
+++ b/apps/web/src/components/app/split-layout/SplitLayout.tsx
@@ -1,9 +1,11 @@
import { CreateContextProvider } from '@app/features/command/context/create-context';
import { useSplitRouter } from '@app/lib/split-router';
import { setGlobalSplitManager } from '@app/signal/splitLayout';
+import { globalTabManager } from '@app/signal/tabLayout';
import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
import { DesktopTabsController } from '@components/app/tab-layout/DesktopTabsController';
import { Resize } from '@core/component/Resize';
+import type { ResizeZoneCtx } from '@core/component/Resize/types';
import { useIsAuthenticated, useUserId } from '@core/context/user';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
@@ -12,6 +14,7 @@ import {
createEffect,
createMemo,
createSelector,
+ createSignal,
For,
onCleanup,
type ParentProps,
@@ -22,6 +25,7 @@ import {
import { PopoverSplitRenderer } from './components/PopoverSplitRenderer';
import { SplitPanel } from './components/SplitPanel';
import { SplitLayoutContext } from './context';
+import { INITIAL_LAYER_ID, type SplitLayers, sameIds } from './layers';
import { createSplitLayout, type SplitId } from './layoutManager';
import { createMobilePaneStack } from './mobile/createMobilePaneStack';
import { MobileSplitContainer } from './mobile/MobileSplitContainer';
@@ -75,13 +79,32 @@ export function SplitLayout() {
const splits = createMemo(splitManager.splits);
const useBentoLayout = () => !isTouchDevice();
+ // <For> on plain ids for stable referential equality
+ const ids = createMemo(() => splits().map(({ id }) => id));
+
+ // Desktop tabs render one layer per tab; without them, one live layer.
+ const layers = (): SplitLayers => {
+ const tabLayers = globalTabManager();
+ if (tabLayers) return tabLayers;
+
+ return {
+ layerIds: () => [INITIAL_LAYER_ID],
+ layerSplits: ids,
+ isLive: () => true,
+ };
+ };
+ const layerIds = createMemo(() => layers().layerIds(), undefined, {
+ equals: sameIds,
+ });
+
// Drop refs for departed splits by reconciling against the live list:
// batched mutations can remove several splits in one flush (e.g. closing
// a Preview Pair), and the events signal only surfaces the last event.
+ // Parked splits stay mounted, so they keep their refs.
createEffect(() => {
- const alive = new Set(splits().map(({ id }) => id));
+ splits();
for (const id of panelRefs.keys()) {
- if (!alive.has(id)) panelRefs.delete(id);
+ if (!splitManager.splitState(id)) panelRefs.delete(id);
}
});
@@ -91,30 +114,40 @@ export function SplitLayout() {
setTabTitle(splitManager.tabTitle());
});
- // <For> on plain ids for stable referential equality
- const ids = createMemo(() => splits().map(({ id }) => id));
-
createSplitFocusTracker({ splitManager, panelRefs, splits });
- return (
- <>
- <Show
- when={paneStack}
- fallback={
- <div
- class="size-full"
- classList={{ 'py-1.5 pr-1.5': useBentoLayout() }}
- >
- <Resize.Zone
- direction="horizontal"
- gutter={useBentoLayout() ? 6 : 1}
- showDividers={!useBentoLayout()}
- captureResizeCtx={splitManager.setResizeContext}
- >
- <For each={ids()}>
- {(id, index) => (
- <Show when={splitManager.getSplit(id)}>
- {(handle) => (
+ function SplitLayer(props: { layer: string }) {
+ const live = () => layers().isLive(props.layer);
+ const layerIds = createMemo(() => layers().layerSplits(props.layer), [], {
+ equals: sameIds,
+ });
+ const [resizeContext, setResizeContext] = createSignal<ResizeZoneCtx>();
+ createEffect(() => {
+ const context = resizeContext();
+ if (live() && context) splitManager.setResizeContext(context);
+ });
+
+ return (
+ // A parked layer keeps its views mounted but skips their rendering,
+ // and inert keeps focus, hotkeys, and assistive tech out of it.
+ <div
+ class="absolute inset-0"
+ classList={{ 'invisible [content-visibility:hidden]': !live() }}
+ inert={!live()}
+ data-split-layer={props.layer}
+ >
+ <Resize.Zone
+ direction="horizontal"
+ gutter={useBentoLayout() ? 6 : 1}
+ showDividers={!useBentoLayout()}
+ captureResizeCtx={setResizeContext}
+ >
+ <For each={layerIds()}>
+ {(id, index) => (
+ <Show when={splitManager.getSplit(id)}>
+ {(handle) => (
+ <Show when={splitManager.splitState(id)}>
+ {(split) => (
<Suspense>
<Resize.Panel
id={id}
@@ -122,7 +155,7 @@ export function SplitLayout() {
index={index()}
>
<SplitPanel
- split={splits()[index()]!}
+ split={split()}
handle={handle()}
active={activeSplitSelector(id)}
setPanelRef={(panelRef) =>
@@ -135,8 +168,28 @@ export function SplitLayout() {
)}
</Show>
)}
+ </Show>
+ )}
+ </For>
+ </Resize.Zone>
+ </div>
+ );
+ }
+
+ return (
+ <>
+ <Show
+ when={paneStack}
+ fallback={
+ <div
+ class="size-full"
+ classList={{ 'py-1.5 pr-1.5': useBentoLayout() }}
+ >
+ <div class="relative size-full">
+ <For each={layerIds()}>
+ {(layer) => <SplitLayer layer={layer} />}
</For>
- </Resize.Zone>
+ </div>
</div>
}
>
diff --git a/apps/web/src/components/app/split-layout/layers.ts b/apps/web/src/components/app/split-layout/layers.ts
new file mode 100644
index 0000000000..63a2e88e7e
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/layers.ts
@@ -0,0 +1,27 @@
+import type { SplitId } from './layoutManager';
+
+/**
+ * The layer the split layout renders before (or without) desktop tabs. The
+ * tab manager gives its first live tab this id, so enabling tabs keeps the
+ * panes that are already mounted.
+ */
+export const INITIAL_LAYER_ID = 'initial';
+
+/**
+ * Groups of panes rendered side by side in the split layout, one per desktop
+ * tab. Only the live layer shows the router's open panes; the others hold
+ * parked panes, kept mounted but hidden and inert.
+ */
+export type SplitLayers = {
+ layerIds(): readonly string[];
+ layerSplits(layer: string): readonly SplitId[];
+ isLive(layer: string): boolean;
+};
+
+/** Equality for id lists, so layer memos keep their identity. */
+export function sameIds(
+ left: readonly string[],
+ right: readonly string[]
+): boolean {
+ return left.length === right.length && left.every((id, i) => id === right[i]);
+}
diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.ts
index cf49308ce3..3da2104921 100644
--- a/apps/web/src/components/app/split-layout/layoutManager.ts
+++ b/apps/web/src/components/app/split-layout/layoutManager.ts
@@ -334,6 +334,8 @@ export type SplitManager = {
/** Register live inline views; call the returned function when the host is disposed. */
registerOpenViews: (source: () => readonly ContentInstance[]) => () => void;
readonly splits: Accessor<ReadonlyArray<SplitState>>;
+ /** A split's state, including splits of parked panes, which `splits` omits. */
+ splitState: (id: SplitId) => SplitState | undefined;
readonly activeSplitId: Accessor<SplitId | undefined>;
readonly activeSplit: Accessor<SplitHandle | undefined>;
readonly lastActiveSplitId: Accessor<SplitId | undefined>;
@@ -595,6 +597,8 @@ export function createSplitLayout(
const stacked = () => options.stacked?.() ?? false;
const [state, setState] = createStore<{
splits: SplitState[];
+ /** Splits whose panes the router parked: mounted elsewhere, off screen. */
+ parked: SplitState[];
activeSplitId: SplitId | undefined;
lastActiveSplitId: SplitId | undefined;
spotlightId: SplitId | undefined;
@@ -611,6 +615,7 @@ export function createSplitLayout(
>;
}>({
splits: [],
+ parked: [],
activeSplitId: undefined,
lastActiveSplitId: undefined,
spotlightId: undefined,
@@ -722,11 +727,10 @@ export function createSplitLayout(
if (!state) return;
// Mirror onto SplitState.content so live reads see the captured state.
- setState('splits', (s) => {
- const i = s.findIndex((x) => x.id === split.id);
- if (i < 0) return s;
- return s.with(i, { ...s[i], content: { ...s[i].content, state } });
- });
+ updateSplit(split.id, (current) => ({
+ ...current,
+ content: { ...current.content, state },
+ }));
}
const DEFAULT_SPLIT_CONTENT = defaultSplitContent ?? {
@@ -743,7 +747,21 @@ export function createSplitLayout(
setLastEvent({ type, ...payload } as SplitEventWithType);
}
- const findSplitById = (id: SplitId) => state.splits.find((s) => s.id === id);
+ const findSplitById = (id: SplitId) =>
+ state.splits.find((s) => s.id === id) ??
+ state.parked.find((s) => s.id === id);
+
+ /** Updates a split, open or parked. */
+ function updateSplit(id: SplitId, update: (split: SplitState) => SplitState) {
+ const inList = (list: SplitState[]) => {
+ const i = list.findIndex((x) => x.id === id);
+ return i < 0 ? list : list.with(i, update(list[i]!));
+ };
+ batch(() => {
+ setState('splits', inList);
+ setState('parked', inList);
+ });
+ }
const splitIndexById = (id: SplitId) =>
state.splits.findIndex((s) => s.id === id);
@@ -836,47 +854,32 @@ export function createSplitLayout(
if (keyOfSplitContent(split.content) === keyOfSplitContent(content)) {
// Update referredFrom if provided, even if content is the same
if (referredFrom !== undefined) {
- return setState('splits', (s) => {
- const i = s.findIndex((x) => x.id === split.id);
- if (i < 0) return s;
- const target = {
- ...s[i],
- content: content,
- referredFrom,
- lastNavigationSource: referredFrom,
- lastNavigationCause: cause,
- };
- return s.with(i, target);
- });
- }
- return setState('splits', (s) => {
- const i = s.findIndex((x) => x.id === split.id);
- if (i < 0) return s;
- const target = {
- ...s[i],
+ return updateSplit(split.id, (current) => ({
+ ...current,
content: content,
- lastNavigationSource: null,
+ referredFrom,
+ lastNavigationSource: referredFrom,
lastNavigationCause: cause,
- };
- return s.with(i, target);
- });
+ }));
+ }
+ return updateSplit(split.id, (current) => ({
+ ...current,
+ content: content,
+ lastNavigationSource: null,
+ lastNavigationCause: cause,
+ }));
}
const newMount = createPinnedMount(orchestrator, content);
- setState('splits', (s) => {
- const i = s.findIndex((x) => x.id === split.id);
- if (i < 0) return s;
- const target = {
- ...s[i],
- content,
- mount: newMount,
- lastNavigationSource: referredFrom ?? null,
- lastNavigationCause: cause,
- ...(referredFrom !== undefined && { referredFrom }),
- };
- return s.with(i, target);
- });
+ updateSplit(split.id, (current) => ({
+ ...current,
+ content,
+ mount: newMount,
+ lastNavigationSource: referredFrom ?? null,
+ lastNavigationCause: cause,
+ ...(referredFrom !== undefined && { referredFrom }),
+ }));
}
/** How the manager reached an entry; kept on the router entry, in memory only. */
@@ -1020,20 +1023,15 @@ export function createSplitLayout(
const current = split.content;
batch(() => {
- setState('splits', (splits) => {
- const index = splits.findIndex((s) => s.id === split.id);
- if (index < 0) return splits;
- const previous = splits[index];
- return splits.with(index, {
- ...previous,
- content: next,
- mount:
- previous.mount.kind === 'block'
- ? { ...previous.mount, id: next.id }
- : previous.mount,
- lastNavigationCause: 'replace',
- });
- });
+ updateSplit(split.id, (previous) => ({
+ ...previous,
+ content: next,
+ mount:
+ previous.mount.kind === 'block'
+ ? { ...previous.mount, id: next.id }
+ : previous.mount,
+ lastNavigationCause: 'replace',
+ }));
if (current.type !== 'component') {
orchestrator.rekeyBlockInstance(
resolveBlockAlias(current.type),
@@ -1133,6 +1131,7 @@ export function createSplitLayout(
})
);
setState('splits', (splits) => splits.filter((s) => s.id !== id));
+ setState('parked', (splits) => splits.filter((s) => s.id !== id));
const front = state.splits.at(-1);
if (stacked() && state.activeSplitId === id && front) {
setState('activeSplitId', front.id);
@@ -1142,16 +1141,27 @@ export function createSplitLayout(
});
}
- /** Puts splits in the router's pane order. */
+ /**
+ * Puts the open splits in the router's pane order; splits of retained panes
+ * the router no longer shows move to `parked`, keeping their state.
+ */
function orderSplits(ids: readonly SplitId[]) {
- const byId = new Map(state.splits.map((split) => [split.id, split]));
+ const all = [...state.splits, ...state.parked];
+ const byId = new Map(all.map((split) => [split.id, split]));
const ordered = ids.flatMap((id) => byId.get(id) ?? []);
const inOrder =
ordered.length === state.splits.length &&
ordered.every((split, index) => split === state.splits[index]);
if (inOrder) return;
- setState('splits', ordered);
+ const open = new Set(ids);
+ batch(() => {
+ setState('splits', ordered);
+ setState(
+ 'parked',
+ all.filter((split) => !open.has(split.id))
+ );
+ });
}
function activateSplit(id: SplitId) {
@@ -1436,7 +1446,8 @@ export function createSplitLayout(
}
// The router owns each pane's history; splits mirror what its panes show.
- const paneSplits = mapArray(router.panes, (pane) => {
+ // Parked panes keep their splits, so their views can stay mounted.
+ const paneSplits = mapArray(router.retainedPanes, (pane) => {
const id = splitOf(pane);
let entryIds = new Set<string>();
@@ -1483,8 +1494,9 @@ export function createSplitLayout(
});
createComputed(() => {
- const ids = paneSplits();
- untrack(() => orderSplits(ids));
+ paneSplits();
+ const open = router.panes().map(splitOf);
+ untrack(() => orderSplits(open));
});
trackNavigationLifecycle(router, () => entryStates.size);
@@ -1842,6 +1854,8 @@ export function createSplitLayout(
return {
viewState,
splits: () => state.splits,
+ /** A split's state, whether open or parked. */
+ splitState: findSplitById,
findOpenView,
registerOpenViews: contentInstances.register,
activeSplitId: () => state.activeSplitId,
diff --git a/apps/web/src/components/app/tab-layout/tab-manager.ts b/apps/web/src/components/app/tab-layout/tab-manager.ts
index f0ab6cfe28..7ef775978f 100644
--- a/apps/web/src/components/app/tab-layout/tab-manager.ts
+++ b/apps/web/src/components/app/tab-layout/tab-manager.ts
@@ -1,19 +1,46 @@
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
-import type { Entry, LayoutSnapshot, SplitRouter } from '@app/lib/split-router';
+import type {
+ Entry,
+ LayoutSnapshot,
+ PaneId,
+ ShowLayoutOptions,
+ SplitRouter,
+} from '@app/lib/split-router';
+import {
+ INITIAL_LAYER_ID,
+ type SplitLayers,
+ sameIds,
+} from '@components/app/split-layout/layers';
import type {
SplitId,
SplitManager,
} from '@components/app/split-layout/layoutManager';
import { fireAndForget } from '@core/util/fireAndForget';
import { Telemetry } from '@macro-inc/observability';
-import { batch, createEffect, createSignal, untrack } from 'solid-js';
+import {
+ batch,
+ createEffect,
+ createMemo,
+ createSignal,
+ onCleanup,
+ untrack,
+} from 'solid-js';
+import { match } from 'ts-pattern';
import { disarmOpenInNewTabIntent } from './open-in-tab-intent';
import { readPersistedTabs, writePersistedTabs } from './tab-persistence';
export type DesktopTabId = string & { readonly DesktopTabId: unique symbol };
-/** How an inactive tab comes back: a kept capture, or a saved URL. */
+/**
+ * How an inactive tab comes back: its panes still mounted (parked), a kept
+ * capture of a layout that is not mounted, or a saved URL.
+ */
type StoredLayout =
+ | {
+ kind: 'parked';
+ panes: readonly PaneId[];
+ activeSplit: SplitId | undefined;
+ }
| {
kind: 'snapshot';
layout: LayoutSnapshot;
@@ -30,13 +57,19 @@ export type DesktopTab = {
readonly stored: StoredLayout;
};
+/**
+ * Background tabs kept mounted (parked) for instant switching. Past this, the
+ * least recently used ones unmount and come back from a capture.
+ */
+export const MAX_PARKED_TABS = 5;
+
const newTabId = () => crypto.randomUUID() as DesktopTabId;
const SURFACE = 'desktop-tabs';
-function newUrlTab(url: string): DesktopTab {
+function newUrlTab(url: string, id: DesktopTabId = newTabId()): DesktopTab {
return {
- id: newTabId(),
+ id,
title: undefined,
paneCount: 1,
stored: { kind: 'url', url },
@@ -58,70 +91,157 @@ export type TabManagerOptions = {
export type TabManager = ReturnType<typeof createTabManager>;
/**
- * Browser-style tabs over the split layout. Only the active tab is live; the
- * others hold a layout capture (or a saved URL) and restore through the
- * router, so switching runs leave guards and keeps pane histories.
+ * Browser-style tabs over the split layout. The active tab's panes are the
+ * router's open panes. Switching away parks them: the router keeps them out of
+ * the URL, and the split layout keeps their views mounted but hidden and not
+ * rendered, so switching back is instant. Tabs not yet opened, or evicted past
+ * `MAX_PARKED_TABS`, hold a capture (or a saved URL) and mount on activation.
*/
export function createTabManager(options: TabManagerOptions) {
const { router, manager, userId } = options;
const persisted = readPersistedTabs(userId);
+ const initialActiveIndex = persisted
+ ? Math.min(persisted.active, persisted.tabs.length - 1)
+ : 0;
+ // The live tab takes the split layout's initial layer, so the panes that
+ // are already mounted stay mounted when tabs turn on.
const initialTabs: readonly DesktopTab[] = persisted
- ? persisted.tabs.map((tab) => ({
- id: newTabId(),
+ ? persisted.tabs.map((tab, index) => ({
+ id:
+ index === initialActiveIndex
+ ? (INITIAL_LAYER_ID as DesktopTabId)
+ : newTabId(),
title: tab.title,
paneCount: tab.paneCount,
stored: { kind: 'url', url: tab.url },
}))
- : [newUrlTab(DEFAULT_ROUTE)];
- const initialActive =
- initialTabs[Math.min(persisted?.active ?? 0, initialTabs.length - 1)]!;
+ : [newUrlTab(DEFAULT_ROUTE, INITIAL_LAYER_ID as DesktopTabId)];
+ const initialActive = initialTabs[initialActiveIndex]!;
const [tabs, setTabs] = createSignal<readonly DesktopTab[]>(initialTabs);
const [activeTabId, setActiveTabId] = createSignal(initialActive.id);
+ // Which tab each pane belongs to, recorded when a tab parks or opens.
+ // Panes opened inside the live tab are unrecorded until it parks.
+ const [owners, setOwners] = createSignal<ReadonlyMap<PaneId, DesktopTabId>>(
+ new Map()
+ );
+ const lastUsed = new Map<DesktopTabId, number>();
+ let useCount = 0;
+ const touch = (id: DesktopTabId) => lastUsed.set(id, ++useCount);
+ touch(initialActive.id);
// Tab operations swap the whole layout; one at a time keeps them coherent.
let switching = false;
const findTab = (id: DesktopTabId) => tabs().find((tab) => tab.id === id);
const activeIndex = () => tabs().findIndex((tab) => tab.id === activeTabId());
- /** The active tab with the live layout frozen in, ready to be stored. */
- const captureActiveTab = (): DesktopTab | undefined => {
+ /**
+ * The tab the router's open panes belong to. It moves with the router's
+ * commit, before the strip highlights the tab, so a layer never shows
+ * another tab's panes.
+ */
+ const liveTabId = createMemo(() => {
+ const owned = owners();
+ for (const pane of router.panes()) {
+ const owner = owned.get(pane);
+ if (owner) return owner;
+ }
+
+ return activeTabId();
+ });
+
+ const assignOwners = (panes: readonly PaneId[], id: DesktopTabId) => {
+ setOwners((current) => {
+ const next = new Map(current);
+ for (const pane of panes) next.set(pane, id);
+ return next;
+ });
+ };
+
+ const dropOwners = (panes: readonly PaneId[]) => {
+ setOwners((current) => {
+ const next = new Map(current);
+ for (const pane of panes) next.delete(pane);
+ return next;
+ });
+ };
+
+ const setTab = (next: DesktopTab) =>
+ setTabs((list) => list.map((tab) => (tab.id === next.id ? next : tab)));
+
+ /** Records the active tab's open panes as parked, before they are swapped out. */
+ const parkActiveTab = () => {
const current = findTab(activeTabId());
- if (!current) return;
-
- const layout = router.layoutSnapshot();
- if (layout.panes.length === 0) return current;
-
- return {
- ...current,
- title: manager.tabTitle() ?? current.title,
- paneCount: layout.panes.length,
- stored: {
- kind: 'snapshot',
- layout,
- activeSplit: manager.activeSplitId(),
- href: router.layoutHref(layout),
- },
- };
+ const panes = router.panes();
+ if (!current || panes.length === 0) return;
+
+ batch(() => {
+ assignOwners(panes, current.id);
+ setTab({
+ ...current,
+ title: manager.tabTitle() ?? current.title,
+ paneCount: panes.length,
+ stored: {
+ kind: 'parked',
+ panes,
+ activeSplit: manager.activeSplitId(),
+ },
+ });
+ });
};
+ const parkedPanes = (tab: DesktopTab): readonly PaneId[] =>
+ tab.stored.kind === 'parked' ? tab.stored.panes : [];
+
const storedHref = (tab: DesktopTab): string =>
- tab.stored.kind === 'url' ? tab.stored.url : tab.stored.href;
+ match(tab.stored)
+ .with({ kind: 'url' }, (stored) => stored.url)
+ .with({ kind: 'snapshot' }, (stored) => stored.href)
+ .with({ kind: 'parked' }, (stored) =>
+ router.layoutHref(router.layoutSnapshot(stored.panes))
+ )
+ .exhaustive();
+
+ /** Mounts a captured layout as `tab`'s panes. */
+ const openLayout = (
+ tab: DesktopTab,
+ layout: LayoutSnapshot,
+ showOptions: ShowLayoutOptions
+ ) => {
+ assignOwners(
+ layout.panes.map((pane) => pane.pane),
+ tab.id
+ );
+ return router.openLayout(layout, showOptions);
+ };
- /** Brings a stored tab's layout up; false when a leave guard refused. */
- const show = async (tab: DesktopTab): Promise<boolean> => {
+ /**
+ * Brings a stored tab's layout up: parked panes come back as they were;
+ * anything else mounts. False when a leave guard or middleware refused.
+ */
+ const show = async (
+ tab: DesktopTab,
+ showOptions: ShowLayoutOptions = {}
+ ): Promise<boolean> => {
disarmOpenInNewTabIntent();
- const result =
- tab.stored.kind === 'snapshot'
- ? await router.restoreLayout(tab.stored.layout)
- : await router.navigate(tab.stored.url);
+ const result = await match(tab.stored)
+ .with({ kind: 'parked' }, (stored) =>
+ router.showLayout(stored.panes, showOptions)
+ )
+ .with({ kind: 'snapshot' }, (stored) =>
+ openLayout(tab, stored.layout, showOptions)
+ )
+ .with({ kind: 'url' }, (stored) =>
+ openLayout(tab, router.layoutFromHref(stored.url), showOptions)
+ )
+ .exhaustive();
return result.status !== 'cancelled';
};
const focusStoredSplit = (tab: DesktopTab) => {
- const stored = tab.stored.kind === 'snapshot' ? tab.stored : undefined;
+ const stored = tab.stored.kind === 'url' ? undefined : tab.stored;
const target =
stored?.activeSplit !== undefined && manager.getSplit(stored.activeSplit)
? stored.activeSplit
@@ -129,6 +249,37 @@ export function createTabManager(options: TabManagerOptions) {
if (target) manager.activateSplit(target);
};
+ /** Unmounts the least recently used parked tabs past `MAX_PARKED_TABS`. */
+ const evictParkedTabs = () => {
+ const parked = untrack(tabs).filter(
+ (tab) => tab.stored.kind === 'parked' && tab.id !== untrack(liveTabId)
+ );
+ const excess = parked.length - MAX_PARKED_TABS;
+ if (excess <= 0) return;
+
+ const oldest = [...parked]
+ .sort((a, b) => (lastUsed.get(a.id) ?? 0) - (lastUsed.get(b.id) ?? 0))
+ .slice(0, excess);
+ batch(() => {
+ for (const tab of oldest) {
+ const panes = parkedPanes(tab);
+ const layout = router.layoutSnapshot(panes);
+ setTab({
+ ...tab,
+ stored: {
+ kind: 'snapshot',
+ layout,
+ activeSplit:
+ tab.stored.kind === 'parked' ? tab.stored.activeSplit : undefined,
+ href: router.layoutHref(layout),
+ },
+ });
+ router.discardPanes(panes);
+ dropOwners(panes);
+ }
+ });
+ };
+
async function activateTab(id: DesktopTabId): Promise<void> {
if (switching || id === untrack(activeTabId)) return;
const target = untrack(() => findTab(id));
@@ -139,20 +290,16 @@ export function createTabManager(options: TabManagerOptions) {
try {
span.setAttr('tabs.count', untrack(tabs).length);
span.setAttr('tabs.target_pane_count', target.paneCount);
- const previous = untrack(captureActiveTab);
+ span.setAttr('tabs.target_kept', target.stored.kind === 'parked');
+ untrack(parkActiveTab);
const shown = await show(target);
span.setAttr('tabs.outcome', shown ? 'committed' : 'cancelled');
if (!shown) return;
- batch(() => {
- if (previous) {
- setTabs((list) =>
- list.map((tab) => (tab.id === previous.id ? previous : tab))
- );
- }
- setActiveTabId(id);
- });
+ setActiveTabId(id);
+ touch(id);
focusStoredSplit(target);
+ evictParkedTabs();
} finally {
switching = false;
span.end();
@@ -169,15 +316,19 @@ export function createTabManager(options: TabManagerOptions) {
switching = true;
try {
- // Restoring the neighbor removes this tab's panes, so its leave
- // guards (unsaved changes) decide whether the close happens.
- const shown = await show(target);
+ // Showing the neighbor removes this tab's panes, so its leave guards
+ // (unsaved changes) decide whether the close happens.
+ const closing = untrack(router.panes);
+ const shown = await show(target, { closeOpen: true });
if (!shown) return;
batch(() => {
setTabs((list) => list.filter((tab) => tab.id !== id));
setActiveTabId(neighbor);
+ dropOwners(closing);
});
+ lastUsed.delete(id);
+ touch(neighbor);
focusStoredSplit(target);
} finally {
switching = false;
@@ -192,6 +343,47 @@ export function createTabManager(options: TabManagerOptions) {
});
};
+ // Layers keep the order tabs first got one, so opening or closing a tab
+ // never moves another tab's mounted panes in the document.
+ let layerOrder: readonly DesktopTabId[] = [];
+ const layerIds = createMemo(
+ () => {
+ const live = liveTabId();
+ const mounted = new Set(
+ tabs()
+ .filter((tab) => tab.id === live || tab.stored.kind === 'parked')
+ .map((tab) => tab.id)
+ );
+ mounted.add(live);
+ const kept = layerOrder.filter((id) => mounted.has(id));
+ const added = [...mounted].filter((id) => !kept.includes(id));
+ layerOrder = [...kept, ...added];
+ return layerOrder;
+ },
+ [],
+ { equals: sameIds }
+ );
+
+ const layers: SplitLayers = {
+ layerIds,
+ layerSplits(layer) {
+ const tab = findTab(layer as DesktopTabId);
+ const panes =
+ layer === liveTabId() ? router.panes() : tab ? parkedPanes(tab) : [];
+ return panes as readonly string[] as readonly SplitId[];
+ },
+ isLive: (layer) => layer === liveTabId(),
+ };
+
+ // Parked panes outlive nothing: when tabs turn off or the account changes,
+ // forget them so only the open layout remains.
+ onCleanup(() => {
+ const open = untrack(router.panes);
+ router.discardPanes(
+ untrack(router.retainedPanes).filter((pane) => !open.includes(pane))
+ );
+ });
+
// Keep the saved tabs current: the active tab persists its live layout URL.
createEffect(() => {
const list = tabs();
@@ -223,6 +415,7 @@ export function createTabManager(options: TabManagerOptions) {
return {
tabs,
activeTabId,
+ ...layers,
/** Live title for the strip: the active tab reads the layout manager.
* Undefined when the tab has no title yet; the strip renders the
@@ -250,7 +443,13 @@ export function createTabManager(options: TabManagerOptions) {
if (index < 0) return;
if (id !== untrack(activeTabId)) {
- setTabs((current) => current.filter((tab) => tab.id !== id));
+ const panes = parkedPanes(list[index]!);
+ batch(() => {
+ setTabs((current) => current.filter((tab) => tab.id !== id));
+ router.discardPanes(panes);
+ dropOwners(panes);
+ });
+ lastUsed.delete(id);
return;
}
diff --git a/apps/web/src/components/app/tab-layout/tests/tab-layers.test.tsx b/apps/web/src/components/app/tab-layout/tests/tab-layers.test.tsx
new file mode 100644
index 0000000000..409bc44bf7
--- /dev/null
+++ b/apps/web/src/components/app/tab-layout/tests/tab-layers.test.tsx
@@ -0,0 +1,172 @@
+import {
+ createMemoryHistory,
+ createMemoryPaneStore,
+ createSplitRouter,
+ type Entry,
+ type SplitRouter,
+ type SplitRoutes,
+} from '@app/lib/split-router';
+import { paneRoute } from '@app/routes/app-route';
+import {
+ appRoute,
+ channelDetailRoute,
+ channelsSplitRoute,
+ homeSplitRoute,
+ legacyContentRoute,
+ notFoundRoute,
+} from '@app/routes/routes';
+import { setGlobalTabManager } from '@app/signal/tabLayout';
+import { SplitLayoutContext } from '@components/app/split-layout/context';
+import {
+ createSplitLayout,
+ type SplitManager,
+} from '@components/app/split-layout/layoutManager';
+import { SplitLayout } from '@components/app/split-layout/SplitLayout';
+import { createAppPanePolicy } from '@components/app/split-layout/split-router/app-pane-policy';
+import {
+ resolveContentLocation,
+ splitContentFromLocation,
+} from '@components/app/split-layout/split-router/legacy-route';
+import type { BlockOrchestrator } from '@core/orchestrator';
+import { cleanup, render } from '@solidjs/testing-library';
+import { onCleanup, type ParentProps } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createTabManager, type TabManager } from '../tab-manager';
+
+const panels = vi.hoisted(() => ({ mounted: 0, unmounted: 0 }));
+
+// Stand-ins that count mounts: the layers decide what stays mounted, not the
+// panel or the resize zone.
+vi.mock('@components/app/split-layout/components/SplitPanel', () => ({
+ SplitPanel: (props: { split: { id: string } }) => {
+ panels.mounted += 1;
+ onCleanup(() => {
+ panels.unmounted += 1;
+ });
+ return <div data-panel={props.split.id} />;
+ },
+}));
+vi.mock('@core/component/Resize', () => ({
+ Resize: {
+ Zone: (props: ParentProps) => <div>{props.children}</div>,
+ Panel: (props: ParentProps) => <div>{props.children}</div>,
+ },
+}));
+
+const routes: SplitRoutes = {
+ definitions: [
+ {
+ ...appRoute,
+ children: [
+ homeSplitRoute,
+ { ...channelsSplitRoute, children: [channelDetailRoute] },
+ legacyContentRoute,
+ notFoundRoute,
+ ],
+ },
+ ],
+ defaultRoute: () => paneRoute({ id: 'view-home', params: {} }),
+};
+
+function setup(url: string) {
+ let router!: SplitRouter;
+ let manager!: SplitManager;
+ let tabManager!: TabManager;
+ render(() => {
+ router = createSplitRouter({
+ routes,
+ history: createMemoryHistory(url),
+ paneStore: createMemoryPaneStore<Entry>(),
+ policy: createAppPanePolicy({
+ manager: () => manager,
+ toContent: splitContentFromLocation,
+ defaultLocation: () => ({ route: routes.defaultRoute() }),
+ stacked: () => false,
+ }),
+ });
+ const orchestrator = {
+ isBlockMounted: () => false,
+ createBlockInstance: vi.fn(),
+ } as unknown as BlockOrchestrator;
+ manager = createSplitLayout(orchestrator, {
+ router,
+ toLocation: (content) => resolveContentLocation(router.routes, content),
+ toContent: splitContentFromLocation,
+ stacked: () => false,
+ });
+ tabManager = createTabManager({
+ router,
+ manager,
+ userId: `user-${Math.random()}`,
+ });
+ setGlobalTabManager(tabManager);
+ return (
+ <SplitLayoutContext.Provider value={{ manager }}>
+ <SplitLayout />
+ </SplitLayoutContext.Provider>
+ );
+ });
+ return { router, tabManager };
+}
+
+async function flush(router: SplitRouter) {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await router.settled();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+const layer = (id: string) =>
+ document.querySelector<HTMLElement>(`[data-split-layer="${id}"]`);
+
+afterEach(() => {
+ setGlobalTabManager(undefined);
+ cleanup();
+ panels.mounted = 0;
+ panels.unmounted = 0;
+});
+
+describe('desktop tab layers', () => {
+ it('switching tabs hides the left tab and shows it again without remounting', async () => {
+ const { router, tabManager } = setup('/channels/channel-one');
+ await flush(router);
+ const first = tabManager.activeTabId();
+ const firstPanel = document.querySelector('[data-panel]');
+ expect(firstPanel).not.toBeNull();
+ expect(panels.mounted).toBe(1);
+
+ tabManager.newTab();
+ await flush(router);
+ const second = tabManager.activeTabId();
+ expect(panels.mounted).toBe(2);
+ expect(panels.unmounted).toBe(0);
+ expect(layer(first)?.inert).toBe(true);
+ expect(layer(first)?.classList.contains('invisible')).toBe(true);
+ expect(layer(second)?.inert).toBe(false);
+
+ tabManager.activateTab(first);
+ await flush(router);
+ tabManager.activateTab(second);
+ await flush(router);
+ tabManager.activateTab(first);
+ await flush(router);
+
+ expect(panels.mounted).toBe(2);
+ expect(panels.unmounted).toBe(0);
+ expect(document.querySelector('[data-panel]')).toBe(firstPanel);
+ expect(layer(first)?.inert).toBe(false);
+ expect(layer(second)?.inert).toBe(true);
+ });
+
+ it('closing a tab unmounts only its panes', async () => {
+ const { router, tabManager } = setup('/channels/channel-one');
+ await flush(router);
+ tabManager.newTab();
+ await flush(router);
+
+ tabManager.closeTab(tabManager.activeTabId());
+ await flush(router);
+ expect(panels.mounted).toBe(2);
+ expect(panels.unmounted).toBe(1);
+ expect(document.querySelectorAll('[data-split-layer]')).toHaveLength(1);
+ });
+});
diff --git a/apps/web/src/components/app/tab-layout/tests/tab-manager.test.ts b/apps/web/src/components/app/tab-layout/tests/tab-manager.test.ts
index 98a9ee0709..0662dfeaf5 100644
--- a/apps/web/src/components/app/tab-layout/tests/tab-manager.test.ts
+++ b/apps/web/src/components/app/tab-layout/tests/tab-manager.test.ts
@@ -3,6 +3,7 @@ import {
createMemoryPaneStore,
createSplitRouter,
type Entry,
+ PANE_LEVEL,
type PaneId,
type SplitRouter,
} from '@app/lib/split-router';
@@ -12,7 +13,11 @@ import {
} from '@app/lib/split-router/tests/fixtures';
import { createRoot } from 'solid-js';
import { afterEach, describe, expect, it } from 'vitest';
-import { createTabManager, type TabLayoutHost } from '../tab-manager';
+import {
+ createTabManager,
+ MAX_PARKED_TABS,
+ type TabLayoutHost,
+} from '../tab-manager';
const fakeHost = (): TabLayoutHost => ({
tabTitle: () => undefined,
@@ -172,4 +177,84 @@ describe('desktop tab manager', () => {
url: '/mail/t1',
});
});
+
+ it('parks the tab it leaves, so switching back shows the same panes without remounting', async () => {
+ const { router, tabManager } = track(setup('/mail/t1'));
+ const [first] = tabManager.tabs();
+ const firstPanes = router.panes();
+ const firstEntry = router.entry(firstPanes[0]!);
+
+ tabManager.newTab();
+ await flush(router);
+ const second = tabManager.activeTabId();
+ expect(tabManager.layerIds()).toEqual([first!.id, second]);
+ expect(tabManager.isLive(second)).toBe(true);
+ expect(tabManager.isLive(first!.id)).toBe(false);
+ // The left tab's panes stay retained, with their entries, in its layer.
+ expect(tabManager.layerSplits(first!.id)).toEqual(firstPanes);
+ expect(router.entry(firstPanes[0]!)).toBe(firstEntry);
+
+ tabManager.activateTab(first!.id);
+ await flush(router);
+ expect(router.panes()).toEqual(firstPanes);
+ expect(router.entry(firstPanes[0]!)).toBe(firstEntry);
+ expect(tabManager.isLive(first!.id)).toBe(true);
+ expect(tabManager.layerSplits(second)).toHaveLength(1);
+ });
+
+ it('the first live tab takes the initial layer, so enabling tabs remounts nothing', () => {
+ const { tabManager } = track(setup('/mail/t1'));
+ expect(tabManager.layerIds()).toEqual(['initial']);
+ });
+
+ it(`unmounts the least recently used tabs past ${MAX_PARKED_TABS} parked`, async () => {
+ const { router, tabManager } = track(setup('/mail/t1'));
+ const [first] = tabManager.tabs();
+ const firstPanes = router.panes();
+
+ for (let i = 0; i <= MAX_PARKED_TABS; i += 1) {
+ tabManager.newTab();
+ await flush(router);
+ }
+
+ const evicted = tabManager.tabs().find((tab) => tab.id === first!.id)!;
+ expect(evicted.stored.kind).toBe('snapshot');
+ expect(router.retainedPanes()).not.toContain(firstPanes[0]);
+ expect(tabManager.layerIds()).toHaveLength(MAX_PARKED_TABS + 1);
+
+ tabManager.activateTab(first!.id);
+ await flush(router);
+ expect(routeIds(router)).toEqual([['mail', 'mail-thread']]);
+ });
+
+ it('closing a background tab forgets its parked panes', async () => {
+ const { router, tabManager } = track(setup('/mail/t1'));
+ const [first] = tabManager.tabs();
+ const firstPanes = router.panes();
+ tabManager.newTab();
+ await flush(router);
+
+ tabManager.closeTab(first!.id);
+ expect(tabManager.tabs()).toHaveLength(1);
+ expect(router.retainedPanes()).toEqual(router.panes());
+ expect(router.entry(firstPanes[0]!)).toBeUndefined();
+ });
+
+ it('a leave guard in the active tab can refuse closing it', async () => {
+ const { router, tabManager } = track(setup('/mail/t1'));
+ tabManager.newTab();
+ await flush(router);
+ const closing = tabManager.activeTabId();
+ const stop = router.registerGuard(
+ router.panes()[0]!,
+ PANE_LEVEL,
+ () => false
+ );
+
+ tabManager.closeTab(closing);
+ await flush(router);
+ expect(tabManager.tabs()).toHaveLength(2);
+ expect(tabManager.activeTabId()).toBe(closing);
+ stop();
+ });
});
diff --git a/apps/web/src/lib/split-router/README.md b/apps/web/src/lib/split-router/README.md
index ec31c575f3..31677c5382 100644
--- a/apps/web/src/lib/split-router/README.md
+++ b/apps/web/src/lib/split-router/README.md
@@ -24,6 +24,16 @@ Preload and middleware errors that the router recovers from still allow commit
callbacks when navigation commits. Host-leave permission checks cannot confirm
that the host actually navigates, so their `onCommit` registration is a no-op.
+## Parked layouts
+
+`layoutSnapshot` and `restoreLayout` capture and bring back whole layouts.
+To keep a layout's views mounted while another shows, park it instead:
+`openLayout` shows a captured layout (or `layoutFromHref`) in new panes, and
+`showLayout` shows retained panes again; both park the open panes, which leave
+the URL but keep their histories in `retainedPanes`. Nothing leaves, so no
+leave guard runs, unless `closeOpen` removes the open panes. `discardPanes`
+forgets parked panes. URL navigation never reuses a parked pane id.
+
## Outlets
An outlet outside a pane renders the first available pane. While no pane exists,
diff --git a/apps/web/src/lib/split-router/index.ts b/apps/web/src/lib/split-router/index.ts
index 7885eb8289..3ad56e98c2 100644
--- a/apps/web/src/lib/split-router/index.ts
+++ b/apps/web/src/lib/split-router/index.ts
@@ -26,6 +26,7 @@ export type {
LayoutPane,
LayoutSnapshot,
RestoreLayoutOptions,
+ ShowLayoutOptions,
} from './router/layout';
export { PANE_LEVEL } from './router/leave-guards';
export type {
diff --git a/apps/web/src/lib/split-router/panes/diff.ts b/apps/web/src/lib/split-router/panes/diff.ts
index 405513d037..c00959a627 100644
--- a/apps/web/src/lib/split-router/panes/diff.ts
+++ b/apps/web/src/lib/split-router/panes/diff.ts
@@ -26,6 +26,8 @@ export type PanesDiff<E extends PaneEntry = PaneEntry> = {
export type LivePanes<E extends PaneEntry = PaneEntry> = {
panes: readonly PaneId[];
+ /** Parked panes; their ids are never reused for a new pane. */
+ parked?: readonly PaneId[];
read(pane: PaneId): PaneSnapshot<E> | undefined;
};
@@ -91,7 +93,8 @@ export function diffPanes<E extends PaneEntry>(
};
const idForNewPane = (paneId: PaneId | undefined): PaneId => {
- const reusable = paneId && !isLive(paneId) && !isUsed(paneId);
+ const parked = paneId !== undefined && live.parked?.includes(paneId);
+ const reusable = paneId && !isLive(paneId) && !isUsed(paneId) && !parked;
return reusable ? paneId : options.createPaneId();
};
diff --git a/apps/web/src/lib/split-router/panes/panes.ts b/apps/web/src/lib/split-router/panes/panes.ts
index 49c6b54d7e..2610083476 100644
--- a/apps/web/src/lib/split-router/panes/panes.ts
+++ b/apps/web/src/lib/split-router/panes/panes.ts
@@ -99,6 +99,11 @@ export function createPanes<E extends PaneEntry, D>(
const [ids, setIds] = createSignal<readonly PaneId[]>([], {
equals: sameIds,
});
+ // Every pane with a history: the open ones plus any a host parked (took
+ // out of `ids` without removing) to show again later.
+ const [retained, setRetained] = createSignal<readonly PaneId[]>([], {
+ equals: sameIds,
+ });
const [arrivals, setArrivals] = createStore<
Record<string, PaneArrival | undefined>
>({});
@@ -121,11 +126,13 @@ export function createPanes<E extends PaneEntry, D>(
const addPane = (pane: PaneId, entry: E) => {
store.create(pane, entry);
setArrivals(pane, 'fresh');
+ setRetained((list) => (list.includes(pane) ? list : [...list, pane]));
};
const forget = (pane: PaneId) => {
store.remove(pane);
setArrivals(pane, undefined);
+ setRetained((list) => list.filter((id) => id !== pane));
options.onRemove?.(pane);
};
@@ -152,6 +159,7 @@ export function createPanes<E extends PaneEntry, D>(
return {
ids,
+ retained,
read: (pane: PaneId) => store.read(pane),
current,
arrival: (pane: PaneId): PaneArrival => arrivals[pane] ?? 'fresh',
@@ -183,6 +191,26 @@ export function createPanes<E extends PaneEntry, D>(
arrange(next, () => forget(pane));
},
+ /**
+ * Makes `next`, retained panes, the open ones. Open panes not in `next`
+ * stay retained (parked) with their histories until `discard`.
+ */
+ show(next: readonly PaneId[]) {
+ const known = untrack(retained);
+ const missing = next.some((pane) => !known.includes(pane));
+ if (missing) throw new Error('Only retained panes can be shown');
+
+ setIds(next);
+ },
+
+ /** Forgets a parked pane; open panes are removed through `remove`. */
+ discard(pane: PaneId) {
+ if (untrack(ids).includes(pane)) return;
+ if (!untrack(retained).includes(pane)) return;
+
+ forget(pane);
+ },
+
/** False when `pane` isn't open or already sits at `to`. */
move(pane: PaneId, to: number): boolean {
const before = untrack(ids);
@@ -203,8 +231,10 @@ export function createPanes<E extends PaneEntry, D>(
incoming: readonly IncomingPane<E>[],
diffOptions: Omit<DiffOptions<E>, 'createPaneId'>
): PanesDiff<E> {
+ const open = untrack(ids);
const live: LivePanes<E> = {
- panes: untrack(ids),
+ panes: open,
+ parked: untrack(retained).filter((pane) => !open.includes(pane)),
read: (pane) => untrack(() => store.read(pane)),
};
diff --git a/apps/web/src/lib/split-router/router/create-router.ts b/apps/web/src/lib/split-router/router/create-router.ts
index 10976df80d..346204b79e 100644
--- a/apps/web/src/lib/split-router/router/create-router.ts
+++ b/apps/web/src/lib/split-router/router/create-router.ts
@@ -133,6 +133,8 @@ export function createSplitRouter(options: SplitRouterOptions) {
claims: claims.registry,
ready,
panes: panes.ids,
+ /** Open and parked panes; see `openLayout` and `showLayout`. */
+ retainedPanes: panes.retained,
navigate: urlNavigation.navigate,
navigatePane: paneNavigation.navigate,
/** Cancels pending navigation and new panes requested from this pane. */
@@ -159,6 +161,10 @@ export function createSplitRouter(options: SplitRouterOptions) {
href: url.href,
layoutSnapshot: layout.snapshot,
restoreLayout: layout.restore,
+ openLayout: layout.open,
+ showLayout: layout.show,
+ discardPanes: layout.discard,
+ layoutFromHref: layout.fromHref,
layoutHref: layout.href,
createPaneId: panes.createPaneId,
activatePane: panes.activate,
diff --git a/apps/web/src/lib/split-router/router/layout.ts b/apps/web/src/lib/split-router/router/layout.ts
index b195fbfcf1..95a0509ba7 100644
--- a/apps/web/src/lib/split-router/router/layout.ts
+++ b/apps/web/src/lib/split-router/router/layout.ts
@@ -1,7 +1,12 @@
import { batch, untrack } from 'solid-js';
-import { type ChangedPane, changedPanes } from '../panes/diff';
+import { type ChangedPane, changedPanes, type PanesDiff } from '../panes/diff';
import type { PaneId } from '../panes/types';
-import { encodePanes, formatLocation } from '../routes/codec';
+import {
+ decodePanes,
+ encodePanes,
+ formatLocation,
+ parseLocation,
+} from '../routes/codec';
import type { SplitRoutesManifest } from '../routes/manifest';
import type { Entry } from '../routes/types';
import type { MaybePromise } from '../utils';
@@ -32,6 +37,11 @@ export type RestoreLayoutOptions = {
replace?: boolean;
};
+export type ShowLayoutOptions = {
+ /** Remove the open panes, through their leave guards, instead of parking them. */
+ closeOpen?: boolean;
+};
+
const shownEntry = (pane: LayoutPane): Entry => pane.entries[pane.index]!;
function toTarget(change: ChangedPane<Entry>): PaneTarget {
@@ -46,6 +56,10 @@ function toTarget(change: ChangedPane<Entry>): PaneTarget {
* Capturing the open panes as plain data and bringing a capture back, so a
* host can keep several layouts (such as window tabs) and swap between them
* without losing any pane's back/forward history.
+ *
+ * A host can also park layouts: `openLayout` and `showLayout` take the open
+ * panes out of the URL without removing them, so their views can stay mounted
+ * (hidden) and come back with `showLayout` without remounting.
*/
export function createLayout(options: {
routes: SplitRoutesManifest;
@@ -55,9 +69,9 @@ export function createLayout(options: {
}) {
const { routes, panes, url, runner } = options;
- /** The open panes with their histories; entries are shared, not copied. */
- const snapshot = (): LayoutSnapshot => ({
- panes: untrack(panes.ids).flatMap((pane) => {
+ /** The open (or the given retained) panes with their histories; entries are shared, not copied. */
+ const snapshot = (only?: readonly PaneId[]): LayoutSnapshot => ({
+ panes: (only ?? untrack(panes.ids)).flatMap((pane) => {
const stored = untrack(() => panes.read(pane));
if (!stored) return [];
@@ -82,6 +96,18 @@ export function createLayout(options: {
}));
const diff = panes.diff(incoming, { same: sameVisit });
+ return runner.startUrl(
+ applyLayout(layout, diff, restoreOptions.replace ? 'replace' : 'push'),
+ false
+ );
+ };
+
+ /** A navigation applying `diff` and putting each captured history back. */
+ const applyLayout = (
+ layout: LayoutSnapshot,
+ diff: PanesDiff<Entry>,
+ mode: 'push' | 'replace'
+ ): Navigation => {
const apply = (entries: readonly Entry[]): NavigationResult => {
batch(() => {
panes.applyDiff(diff, entries);
@@ -102,23 +128,103 @@ export function createLayout(options: {
});
});
});
- url.write(restoreOptions.replace ? 'replace' : 'push');
+ url.write(mode);
const [first] = diff.panes;
return { status: 'committed', pane: first!.pane };
};
- const navigation: Navigation = {
+ return {
cause: 'navigate',
targets: changedPanes(diff).map(toTarget),
removed: diff.removed,
apply,
};
+ };
+
+ /**
+ * Shows a captured layout in new panes, with the ids it names, and parks
+ * the open panes instead of removing them: nothing leaves, so no leave
+ * guard runs (with `closeOpen`, they are removed through their guards).
+ * The layout's pane ids must not be retained already.
+ */
+ const open = (
+ layout: LayoutSnapshot,
+ openOptions: ShowLayoutOptions = {}
+ ): MaybePromise<NavigationResult> => {
+ const retained = untrack(panes.retained);
+ const reused = layout.panes.some((pane) => retained.includes(pane.pane));
+ if (layout.panes.length === 0 || reused) return CANCELLED_RESULT;
+
+ const diff: PanesDiff<Entry> = {
+ panes: layout.panes.map((pane) => ({
+ kind: 'create',
+ pane: pane.pane,
+ entry: shownEntry(pane),
+ })),
+ removed: openOptions.closeOpen ? untrack(panes.ids) : [],
+ };
+
+ return runner.startUrl(applyLayout(layout, diff, 'replace'), false);
+ };
+
+ /**
+ * Makes retained (parked) panes the open ones, as they were: nothing
+ * remounts. The open panes are parked, or removed through their leave
+ * guards with `closeOpen`.
+ */
+ const show = (
+ next: readonly PaneId[],
+ showOptions: ShowLayoutOptions = {}
+ ): MaybePromise<NavigationResult> => {
+ const retained = untrack(panes.retained);
+ const missing = next.some((pane) => !retained.includes(pane));
+ if (next.length === 0 || missing) return CANCELLED_RESULT;
+
+ const open = untrack(panes.ids);
+ const removed = showOptions.closeOpen
+ ? open.filter((pane) => !next.includes(pane))
+ : [];
+
+ const navigation: Navigation = {
+ cause: 'navigate',
+ targets: [],
+ removed,
+ apply: () => {
+ batch(() => {
+ panes.show(next);
+ for (const pane of removed) panes.discard(pane);
+ });
+ url.write('replace');
+
+ return { status: 'committed', pane: next[0]! };
+ },
+ };
return runner.startUrl(navigation, false);
};
+ /** Forgets parked panes and their histories; open panes are left alone. */
+ const discard = (parked: readonly PaneId[]): void => {
+ batch(() => {
+ for (const pane of parked) panes.discard(pane);
+ });
+ };
+
+ /** The layout a mount-relative URL shows, in new panes, for `open`. */
+ const fromHref = (href: string): LayoutSnapshot => {
+ const decoded = decodePanes(routes, parseLocation(href));
+
+ return {
+ panes: decoded.panes.map(({ entry }) => ({
+ pane: panes.createPaneId(),
+ entries: [entry],
+ index: 0,
+ })),
+ };
+ };
+
/** The mount-relative URL a captured layout shows, for saving or sharing. */
const href = (layout: LayoutSnapshot): string => {
const shown = layout.panes.map((pane) => ({
@@ -129,5 +235,5 @@ export function createLayout(options: {
return formatLocation(encodePanes(routes, shown, untrack(url.lastKnown)));
};
- return { snapshot, restore, href };
+ return { snapshot, restore, open, show, discard, fromHref, href };
}
diff --git a/apps/web/src/lib/split-router/tests/layout.test.ts b/apps/web/src/lib/split-router/tests/layout.test.ts
index 15131d2e4a..d3e8ab3e6b 100644
--- a/apps/web/src/lib/split-router/tests/layout.test.ts
+++ b/apps/web/src/lib/split-router/tests/layout.test.ts
@@ -122,3 +122,94 @@ describe('layout snapshot and restore', () => {
expect(router.layoutHref(router.layoutSnapshot())).toBe('/mail/t1');
});
});
+
+describe('parked layouts', () => {
+ it('opens a layout in new panes and parks the open ones with their entries', async () => {
+ const { router, history } = track(setup('/home/~/drive'));
+ const home = router.entry('pane-1' as PaneId);
+
+ const result = await router.openLayout(router.layoutFromHref('/mail/t1'));
+ expect(result.status).toBe('committed');
+ expect(router.panes()).toEqual(['pane-3']);
+ expect(router.retainedPanes()).toEqual(['pane-1', 'pane-2', 'pane-3']);
+ expect(routeIds(router.entry('pane-3' as PaneId))).toEqual([
+ 'mail',
+ 'mail-thread',
+ ]);
+ // Parked panes keep their entries, so their views can stay mounted.
+ expect(router.entry('pane-1' as PaneId)).toBe(home);
+ expect(history.entries().at(-1)?.path).toBe('/mail/t1');
+ });
+
+ it('shows parked panes again as they were, without leave guards', async () => {
+ const { router, history } = track(setup('/home/~/drive'));
+ const home = router.entry('pane-1' as PaneId);
+ await router.openLayout(router.layoutFromHref('/mail'));
+ const stop = router.registerGuard(
+ 'pane-3' as PaneId,
+ PANE_LEVEL,
+ () => false
+ );
+
+ const result = await router.showLayout(['pane-1', 'pane-2'] as PaneId[]);
+ expect(result.status).toBe('committed');
+ expect(router.panes()).toEqual(['pane-1', 'pane-2']);
+ expect(router.entry('pane-1' as PaneId)).toBe(home);
+ expect(router.retainedPanes()).toContain('pane-3');
+ expect(history.entries().at(-1)?.path).toBe('/home/~/drive');
+ stop();
+ });
+
+ it('closing the open panes while showing parked ones asks their guards', async () => {
+ const { router } = track(setup('/home'));
+ await router.openLayout(router.layoutFromHref('/mail'));
+ const stop = router.registerGuard(
+ 'pane-2' as PaneId,
+ PANE_LEVEL,
+ () => false
+ );
+
+ const refused = await router.showLayout(['pane-1'] as PaneId[], {
+ closeOpen: true,
+ });
+ expect(refused.status).toBe('cancelled');
+ expect(router.panes()).toEqual(['pane-2']);
+ stop();
+
+ const closed = await router.showLayout(['pane-1'] as PaneId[], {
+ closeOpen: true,
+ });
+ expect(closed.status).toBe('committed');
+ expect(router.panes()).toEqual(['pane-1']);
+ expect(router.retainedPanes()).toEqual(['pane-1']);
+ });
+
+ it('discards parked panes but never open ones', async () => {
+ const { router } = track(setup('/home'));
+ await router.openLayout(router.layoutFromHref('/mail'));
+
+ router.discardPanes(['pane-1', 'pane-2'] as PaneId[]);
+ expect(router.panes()).toEqual(['pane-2']);
+ expect(router.retainedPanes()).toEqual(['pane-2']);
+ expect(router.entry('pane-1' as PaneId)).toBeUndefined();
+ });
+
+ it('refuses to show panes that are not retained or to reopen retained ids', async () => {
+ const { router } = track(setup('/home'));
+ const shown = await router.showLayout(['missing' as PaneId]);
+ expect(shown.status).toBe('cancelled');
+
+ const reopened = await router.openLayout(router.layoutSnapshot());
+ expect(reopened.status).toBe('cancelled');
+ });
+
+ it('a URL navigation never reuses a parked pane id', async () => {
+ const { router } = track(setup('/home'));
+ await router.openLayout(router.layoutFromHref('/mail'));
+ const home = router.entry('pane-1' as PaneId);
+
+ await router.navigate('/drive/~/calls');
+ expect(router.panes()).not.toContain('pane-1');
+ expect(router.entry('pane-1' as PaneId)).toBe(home);
+ });
+});
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index 5e4fe23a15..ff56d069ce 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -15,9 +15,11 @@ Its tooltip is “New Split” and displays the registered new-split shortcut (`
## Desktop tabs (macOS, `enable-desktop-tabs` flag)
The title bar's center holds browser-style tabs; each tab is a whole split
-layout. Only the active tab's layout is mounted — switching tabs swaps every
-split through the router, preserving each split's back/forward history and
-running unsaved-changes guards. A tab holding more than one split shows a
+layout. Tabs you have visited stay mounted in the background: switching back
+is instant and keeps scroll, selection, and editor state, and each split keeps
+its back/forward history. Background tabs are hidden, inert, and skip
+rendering; past five, the least recently used unmount and reload when next
+opened. Closing the active tab runs its unsaved-changes guards. A tab holding more than one split shows a
split icon with the count. The strip's `+` button (and `Cmd+T`) opens a tab on
Home; the `X` or a middle click closes one (the last tab cannot close;
`Shift+Cmd+W` closes the active tab); `Ctrl+Tab` / `Ctrl+Shift+Tab` cycle.