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-layout): stack splits above and below each other (#9408)

Peter Chinmanca4e7437cb5a
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 2569ea807e..5899bc0ff7 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -42,6 +42,13 @@ Split dragging and composer reflow have a backend-free browser regression:
`bunx playwright test --config src/lib/core/component/Resize/browser-test/playwright.config.ts`.
It exercises the real resize solver, scroll container, and Lexical layout primitive.
+Stacked splits have a backend-free browser regression over the real split
+router and tiled layout: splitting keeps the pane mounted, stacked gutters drag
+and nudge to the minimum height, and closing hands the column back:
+`bunx playwright test --config src/components/app/split-layout/browser-test/playwright.config.ts`.
+Keep panes in one keyed list positioned by the layout tree; nesting a
+`Resize.Zone` per split remounts a pane whenever its split changes.
+
Desktop app switches open the requested list in the target split when the
retained detail is claimed by another pane or preview. Keep this check in view
restoration and preserve entity deduplication and native dock stack restoration;
diff --git a/apps/web/src/components/app/DesktopTitleBar.test.tsx b/apps/web/src/components/app/DesktopTitleBar.test.tsx
index c9239506c2..830fbe7e9b 100644
--- a/apps/web/src/components/app/DesktopTitleBar.test.tsx
+++ b/apps/web/src/components/app/DesktopTitleBar.test.tsx
@@ -43,6 +43,7 @@ it('navigates the active split and disables unavailable directions', () => {
const [activeSplit, setActiveSplit] = createSignal(first);
setGlobalSplitManager({
activeSplit,
+ activeSplitId: () => undefined,
canAppendSplit: () => false,
} as unknown as SplitManager);
diff --git a/apps/web/src/components/app/DesktopTitleBar.tsx b/apps/web/src/components/app/DesktopTitleBar.tsx
index ca6c75a787..f84fa27709 100644
--- a/apps/web/src/components/app/DesktopTitleBar.tsx
+++ b/apps/web/src/components/app/DesktopTitleBar.tsx
@@ -1,4 +1,5 @@
import { LIST_VIEW_ID } from '@app/constants/list-views';
+import { t } from '@app/lib/i18n';
import { globalSplitManager } from '@app/signal/splitLayout';
import { splitBackInterceptor } from '@components/app/split-layout/back-interceptor';
import { DesktopTabStrip } from '@components/app/tab-layout/DesktopTabStrip';
@@ -6,6 +7,7 @@ import { TOKENS } from '@core/hotkey/tokens';
import CaretLeftIcon from '@icon/system/regular/caret-left.svg';
import CaretRightIcon from '@icon/system/regular/caret-right.svg';
import ColumnsPlusIcon from '@icon/system/regular/columns-plus-right.svg';
+import RowsPlusIcon from '@icon/system/regular/rows-plus-bottom.svg';
import { Button } from '@ui';
import { Show } from 'solid-js';
@@ -19,8 +21,11 @@ export function DesktopTitleBar() {
>
<div class="flex items-center gap-1">
<Button
- aria-label="Go Back"
- tooltip={{ content: 'Go Back', hotkey: TOKENS.split.go.back }}
+ aria-label={t('splitMenu.goBack')}
+ tooltip={{
+ content: t('splitMenu.goBack'),
+ hotkey: TOKENS.split.go.back,
+ }}
variant="ghost"
size="icon-sm"
disabled={!activeSplit()?.canGoBack()}
@@ -32,8 +37,11 @@ export function DesktopTitleBar() {
<CaretLeftIcon class="size-4" />
</Button>
<Button
- aria-label="Go Forward"
- tooltip={{ content: 'Go Forward', hotkey: TOKENS.split.go.forward }}
+ aria-label={t('splitMenu.goForward')}
+ tooltip={{
+ content: t('splitMenu.goForward'),
+ hotkey: TOKENS.split.go.forward,
+ }}
variant="ghost"
size="icon-sm"
disabled={!activeSplit()?.canGoForward()}
@@ -49,31 +57,61 @@ export function DesktopTitleBar() {
<DesktopTabStrip />
</div>
<Show when={globalSplitManager()}>
- {(manager) => (
- <Button
- aria-label="New Split"
- tooltip={{
- content: 'New Split',
- hotkey: TOKENS.global.createNewSplit,
- }}
- variant="ghost"
- size="icon-sm"
- disabled={!manager().canAppendSplit()}
- onClick={() =>
- manager().openWithSplit(
- { type: 'component', id: LIST_VIEW_ID.home },
- {
- preferNewSplit: true,
- allowDuplicate: true,
- replaceWhenFull: false,
- activate: true,
- }
- )
- }
- >
- <ColumnsPlusIcon class="size-4" />
- </Button>
- )}
+ {(manager) => {
+ const activeId = () => manager().activeSplitId();
+ /** Room to split the active split toward `side`; with none active, room at the end. */
+ const canSplit = (side: 'right' | 'below') => {
+ const active = activeId();
+ if (!active) return manager().canAppendSplit();
+
+ return manager().canSplit(active, side);
+ };
+ /** Opens Home splitting the active split toward `side`. */
+ const openHome = (side: 'right' | 'below') => {
+ const active = activeId();
+ manager().openWithSplit(
+ { type: 'component', id: LIST_VIEW_ID.home },
+ {
+ preferNewSplit: true,
+ allowDuplicate: true,
+ replaceWhenFull: false,
+ activate: true,
+ beside: active && { split: active, side },
+ }
+ );
+ };
+
+ return (
+ <div class="flex items-center gap-1">
+ <Button
+ aria-label={t('splitMenu.newSplitBelow')}
+ tooltip={{
+ content: t('splitMenu.newSplitBelow'),
+ hotkey: TOKENS.global.createNewSplitBelow,
+ }}
+ variant="ghost"
+ size="icon-sm"
+ disabled={!canSplit('below')}
+ onClick={() => openHome('below')}
+ >
+ <RowsPlusIcon class="size-4" />
+ </Button>
+ <Button
+ aria-label={t('splitMenu.newSplit')}
+ tooltip={{
+ content: t('splitMenu.newSplit'),
+ hotkey: TOKENS.global.createNewSplit,
+ }}
+ variant="ghost"
+ size="icon-sm"
+ disabled={!canSplit('right')}
+ onClick={() => openHome('right')}
+ >
+ <ColumnsPlusIcon class="size-4" />
+ </Button>
+ </div>
+ );
+ }}
</Show>
</div>
);
diff --git a/apps/web/src/components/app/GlobalHotkeys.tsx b/apps/web/src/components/app/GlobalHotkeys.tsx
index b359529126..617629a107 100644
--- a/apps/web/src/components/app/GlobalHotkeys.tsx
+++ b/apps/web/src/components/app/GlobalHotkeys.tsx
@@ -208,6 +208,14 @@ async function toggleKeyboardShortcuts(sheet: ShortcutSheet) {
export default function GlobalShortcuts() {
const canFit = () => globalSplitManager()?.canAppendSplit() ?? true;
+ /** Room to split the active split toward `side`; with none active, room at the end. */
+ const canSplitActive = (side: 'right' | 'below') => {
+ const manager = globalSplitManager();
+ const active = manager?.activeSplitId();
+ if (!manager || !active) return canFit();
+
+ return manager.canSplit(active, side);
+ };
const analytics = useAnalytics();
const undoCtx = useMutationUndoContext();
@@ -364,24 +372,29 @@ export default function GlobalShortcuts() {
const { openWithSplit } = useSplitLayout();
- const createNewSplit = () => {
- analytics.track('split_created', { from: 'global_hotkey' });
+ /** Opens Home splitting the active split toward `side`. */
+ const splitActive = (side: 'right' | 'below') => {
+ const active = globalSplitManager()?.activeSplitId();
+ analytics.track('split_created', { from: 'global_hotkey', side });
openWithSplit(
{ type: 'component', id: 'home' },
{
referredFrom: 'hotkey',
allowDuplicate: true,
preferNewSplit: true,
+ beside: active && { split: active, side },
}
);
return true;
};
+ const createNewSplit = () => splitActive('right');
+ const createNewSplitBelow = () => splitActive('below');
registerHotkey({
hotkey: 'cmd+\\',
scopeId: 'global',
description: () => t('commands.createNewSplit'),
- condition: canFit,
+ condition: () => canSplitActive('right'),
keyDownHandler: createNewSplit,
runWithInputFocused: true,
});
@@ -391,10 +404,28 @@ export default function GlobalShortcuts() {
hotkey: '\\',
scopeId: 'global',
description: () => t('commands.createNewSplit'),
- condition: canFit,
+ condition: () => canSplitActive('right'),
keyDownHandler: createNewSplit,
});
+ registerHotkey({
+ hotkey: 'shift+cmd+\\',
+ scopeId: 'global',
+ description: () => t('commands.createNewSplitBelow'),
+ condition: () => canSplitActive('below'),
+ keyDownHandler: createNewSplitBelow,
+ runWithInputFocused: true,
+ });
+
+ registerHotkey({
+ hotkeyToken: TOKENS.global.createNewSplitBelow,
+ hotkey: 'shift+\\',
+ scopeId: 'global',
+ description: () => t('commands.createNewSplitBelow'),
+ condition: () => canSplitActive('below'),
+ keyDownHandler: createNewSplitBelow,
+ });
+
// Open settings to a specific tab, switching the page in place if settings
// are already open.
const openSettingsAt = (tab?: SettingsTab) => {
diff --git a/apps/web/src/components/app/split-layout/README.md b/apps/web/src/components/app/split-layout/README.md
index 62fb36aef5..183c30d7f5 100644
--- a/apps/web/src/components/app/split-layout/README.md
+++ b/apps/web/src/components/app/split-layout/README.md
@@ -1,4 +1,35 @@
-Split layout should support an arbitrary number of vertical splits.
+Splits tile like a window manager: any split can be split again beside
+(left/right) or stacked (above/below), nested to any depth.
+
+## Tiling
+
+The split router owns the tiling as a tree (`lib/split-router/panes/layout-tree.ts`):
+row and column splits whose leaves, depth-first, are the open panes in order.
+`TiledSplits` renders desktop panes from it. Every pane stays in one keyed
+list and is positioned absolutely at the rectangle `split-geometry.ts` solves,
+so splitting or closing a neighbour never moves a pane's content to another
+parent and remounts it. Keep it that way: don't nest a `Resize.Zone` per
+split. Gutters reuse `Resize`'s `Gutter` and `moveHandleShares`; sizes live in
+the tree but not in the URL. A split is at least `DEFAULT_SPLIT_MIN_WIDTH` wide
+and, stacked, `DEFAULT_SPLIT_MIN_HEIGHT` tall (`splitContentSizing.ts`).
+With desktop tabs, `SplitLayout` renders one `TiledSplits` per tab layer: the
+live layer tiles as `router.layout()`, and a parked one keeps the tiles its
+panes were parked in (`router.layoutOf`), so a background tab comes back
+stacked as it was. Only the live layer reports its area or resizes.
+
+Open beside a split with `beside: { split, side }` on `openWithSplit` or
+`createNewSplit`; without it a new split is a full-height column at the end.
+The new-split keys (`\`, `|`) and title-bar buttons open beside the active split.
+`canAppendSplit()` checks room for that column and `canSplit(id, side)` for a
+split along `side`'s axis, both against the area `TiledSplits` measured.
+A Shift-click that also holds Option (Alt) opens below the split it came from:
+`split-below-intent.ts` remembers the click, as `tab-layout/open-in-tab-intent.ts`
+does for Cmd-click. Moving panes (swap left/right, mobile bring-to-front)
+keeps the tiles and their sizes and changes which split shows where.
+
+`browser-test/` is a backend-free Playwright regression over the real router
+and `TiledSplits`:
+`bunx playwright test --config src/components/app/split-layout/browser-test/playwright.config.ts`.
## Opt-in view restoration
diff --git a/apps/web/src/components/app/split-layout/SplitLayout.tsx b/apps/web/src/components/app/split-layout/SplitLayout.tsx
index 12231e7de6..21819d8239 100644
--- a/apps/web/src/components/app/split-layout/SplitLayout.tsx
+++ b/apps/web/src/components/app/split-layout/SplitLayout.tsx
@@ -4,8 +4,6 @@ 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';
@@ -26,15 +24,25 @@ 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 {
+ createSplitLayout,
+ paneOf,
+ type SplitId,
+ splitOf,
+} from './layoutManager';
import { createMobilePaneStack } from './mobile/createMobilePaneStack';
import { MobileSplitContainer } from './mobile/MobileSplitContainer';
+import {
+ consumeSplitBelowIntent,
+ installSplitBelowIntentTracker,
+} from './split-below-intent';
+import type { TileArea } from './split-geometry';
import {
resolveContentLocation,
splitContentFromLocation,
} from './split-router/legacy-route';
-import { DEFAULT_SPLIT_MIN_WIDTH } from './splitContentSizing';
import { createSplitFocusTracker } from './splitFocusTracker';
+import { TiledSplits } from './TiledSplits';
/** Own the layout and creation context above both app chrome and pane content. */
export function SplitLayoutProvider(props: ParentProps) {
@@ -49,7 +57,9 @@ export function SplitLayoutProvider(props: ParentProps) {
toContent: splitContentFromLocation,
stacked: isNativeMobilePlatform,
sessionKey: () => (authenticated() === false ? undefined : userId()),
+ consumeSplitBelowIntent,
});
+ if (!isTouchDevice()) onCleanup(installSplitBelowIntentTracker());
createEffect(() => setGlobalSplitManager(splitManager));
onCleanup(() => setGlobalSplitManager(undefined));
@@ -65,6 +75,7 @@ export function SplitLayoutProvider(props: ParentProps) {
/** The app route's view: one panel per pane in the owning layout. */
export function SplitLayout() {
+ const router = useSplitRouter();
const layout = useContext(SplitLayoutContext);
if (!layout) throw new Error('SplitLayout requires SplitLayoutProvider');
const splitManager = layout.manager;
@@ -118,13 +129,22 @@ export function SplitLayout() {
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>();
+ const layerPanes = createMemo(
+ () => layers().layerSplits(props.layer).map(paneOf),
+ [],
+ { equals: sameIds }
+ );
+ // The live layer tiles as the open panes do; a parked one as its panes
+ // did when they were parked.
+ const tiles = () => {
+ const [first] = layerPanes();
+
+ return first && router.layoutOf(first);
+ };
+ const [area, setArea] = createSignal<TileArea>();
createEffect(() => {
- const context = resizeContext();
- if (live() && context) splitManager.setResizeContext(context);
+ const measured = area();
+ if (live() && measured) splitManager.setTileArea(measured);
});
return (
@@ -136,42 +156,42 @@ export function SplitLayout() {
inert={!live()}
data-split-layer={props.layer}
>
- <Resize.Zone
- direction="horizontal"
+ <TiledSplits
+ layout={tiles}
+ panes={layerPanes}
gutter={useBentoLayout() ? 6 : 1}
showDividers={!useBentoLayout()}
- captureResizeCtx={setResizeContext}
+ onResize={(path, shares) => {
+ if (live()) router.resizeLayout(path, shares);
+ }}
+ onArea={setArea}
>
- <For each={layerIds()}>
- {(id, index) => (
+ {(pane, index) => {
+ const id = splitOf(pane);
+
+ return (
<Show when={splitManager.getSplit(id)}>
{(handle) => (
<Show when={splitManager.splitState(id)}>
{(split) => (
<Suspense>
- <Resize.Panel
- id={id}
- minSize={DEFAULT_SPLIT_MIN_WIDTH}
+ <SplitPanel
+ split={split()}
+ handle={handle()}
+ active={activeSplitSelector(id)}
+ setPanelRef={(panelRef) =>
+ panelRefs.set(id, panelRef)
+ }
index={index()}
- >
- <SplitPanel
- split={split()}
- handle={handle()}
- active={activeSplitSelector(id)}
- setPanelRef={(panelRef) =>
- panelRefs.set(id, panelRef)
- }
- index={index()}
- />
- </Resize.Panel>
+ />
</Suspense>
)}
</Show>
)}
</Show>
- )}
- </For>
- </Resize.Zone>
+ );
+ }}
+ </TiledSplits>
</div>
);
}
diff --git a/apps/web/src/components/app/split-layout/TiledSplits.tsx b/apps/web/src/components/app/split-layout/TiledSplits.tsx
new file mode 100644
index 0000000000..c6db3c89ec
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/TiledSplits.tsx
@@ -0,0 +1,152 @@
+import type { PaneId, PaneLayout, SplitPath } from '@app/lib/split-router';
+import { Gutter } from '@core/component/Resize';
+import { moveHandleShares } from '@core/component/Resize/solver';
+import { createElementSize } from '@solid-primitives/resize-observer';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ For,
+ Index,
+ type JSX,
+} from 'solid-js';
+import {
+ type Rect,
+ type SolvedSplit,
+ solveTiles,
+ type TileArea,
+ type TileGeometry,
+} from './split-geometry';
+
+type TiledSplitsProps = {
+ layout: Accessor<PaneLayout | undefined>;
+ /** The panes to render, in order; the layout's panes once it catches up. */
+ panes: Accessor<readonly PaneId[]>;
+ gutter: number;
+ showDividers: boolean;
+ onResize: (path: SplitPath, shares: readonly number[]) => void;
+ /** Reports the measured area, for deciding whether another split fits. */
+ onArea: (area: TileArea) => void;
+ children: (pane: PaneId, index: Accessor<number>) => JSX.Element;
+};
+
+const rectStyle = (rect: Rect): JSX.CSSProperties => ({
+ position: 'absolute',
+ left: `${rect.left}px`,
+ top: `${rect.top}px`,
+ width: `${rect.width}px`,
+ height: `${rect.height}px`,
+});
+
+const sameArea = (left: TileArea, right: TileArea) =>
+ left.width === right.width &&
+ left.height === right.height &&
+ left.gutter === right.gutter;
+
+/**
+ * Lays the panes out as the layout tree tiles them. Every pane stays in one
+ * keyed list and is positioned absolutely, so splitting or closing a
+ * neighbour never moves a pane's content to another parent and remounts it.
+ */
+export function TiledSplits(props: TiledSplitsProps) {
+ const [root, setRoot] = createSignal<HTMLDivElement>();
+ const size = createElementSize(root);
+ const area = createMemo(
+ (): TileArea => ({
+ width: size.width ?? 0,
+ height: size.height ?? 0,
+ gutter: props.gutter,
+ }),
+ undefined,
+ { equals: sameArea }
+ );
+
+ createEffect(() => props.onArea(area()));
+
+ const geometry = createMemo<TileGeometry | undefined>((previous) => {
+ const current = area();
+ // Unmeasured or hidden: keep the last real layout instead of collapsing every split.
+ const unmeasured = current.width <= 0 || current.height <= 0;
+ if (previous && unmeasured) return previous;
+
+ return solveTiles(props.layout(), current);
+ });
+
+ const gutters = createMemo(() =>
+ (geometry()?.splits ?? []).flatMap((split) =>
+ split.gutters.map((offset, index) => ({ split, index, offset }))
+ )
+ );
+
+ const nudge = (split: SolvedSplit, index: number, deltaPx: number) => {
+ const length = split.axis === 'row' ? split.rect.width : split.rect.height;
+ const shares = moveHandleShares({
+ panels: split.minimums.map((minSize) => ({
+ minSize,
+ maxSize: Infinity,
+ })),
+ shares: split.shares,
+ index,
+ deltaPx,
+ usable: length - props.gutter * (split.shares.length - 1),
+ });
+ if (shares) props.onResize(split.path, shares);
+ };
+
+ return (
+ <div
+ ref={setRoot}
+ style={{ position: 'relative', width: '100%', height: '100%' }}
+ data-resize-zone
+ >
+ <For each={props.panes()}>
+ {(pane, index) => {
+ const style = (): JSX.CSSProperties => {
+ const rect = geometry()?.panes.get(pane);
+
+ return rect ? rectStyle(rect) : { display: 'none' };
+ };
+
+ return (
+ <div style={style()} data-resize-panel>
+ {props.children(pane, index)}
+ </div>
+ );
+ }}
+ </For>
+ {/* Index keeps each gutter mounted while a drag re-solves the layout every frame. */}
+ <Index each={gutters()}>
+ {(gutter) => {
+ const [box, setBox] = createSignal<HTMLDivElement>();
+ const horizontal = () => gutter().split.axis === 'row';
+
+ return (
+ <div
+ ref={setBox}
+ style={{
+ ...rectStyle(gutter().split.rect),
+ 'pointer-events': 'none',
+ }}
+ >
+ <Gutter
+ direction={horizontal() ? 'horizontal' : 'vertical'}
+ gutterSize={props.gutter}
+ showDivider={props.showDividers}
+ offset={gutter().offset}
+ index={gutter().index}
+ resizable
+ nudge={(index, deltaPx) =>
+ nudge(gutter().split, index, deltaPx)
+ }
+ onChangeStart={() => {}}
+ onChangeEnd={() => {}}
+ root={box}
+ />
+ </div>
+ );
+ }}
+ </Index>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/app/split-layout/browser-test/fixture.tsx b/apps/web/src/components/app/split-layout/browser-test/fixture.tsx
new file mode 100644
index 0000000000..306df1da96
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/browser-test/fixture.tsx
@@ -0,0 +1,120 @@
+import {
+ createMemoryHistory,
+ createMemoryPaneStore,
+ createSplitRouter,
+ type Entry,
+ formatLocation,
+ type PaneId,
+ type SplitPanePolicy,
+ type SplitSide,
+} from '@app/lib/split-router';
+import { appRoutes } from '@app/lib/split-router/tests/fixtures';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { render } from 'solid-js/web';
+import { TiledSplits } from '../TiledSplits';
+
+const history = createMemoryHistory('/home');
+
+// The next new pane splits this one; otherwise it opens at the end.
+let nextSplit: { pane: PaneId; side: SplitSide } | undefined;
+
+const policy: SplitPanePolicy = {
+ placeNewPane: ({ panes }) => {
+ const split = nextSplit;
+ nextSplit = undefined;
+
+ return split
+ ? { split: split.pane, side: split.side }
+ : { insertAt: panes.length };
+ },
+ closeAction: ({ panes }) =>
+ panes.length > 1 ? { type: 'remove' } : { type: 'keep' },
+ activate: () => {},
+};
+
+const router = createSplitRouter({
+ routes: appRoutes,
+ history,
+ paneStore: createMemoryPaneStore<Entry>(),
+ policy,
+});
+
+Reflect.set(window, 'tiledSplitsUrl', () => formatLocation(history.read()));
+
+const DESTINATIONS = ['/drive', '/mail', '/md/d1', '/md/d2', '/md/d3'];
+let opened = 0;
+let mounts = 0;
+
+function Pane(props: { pane: PaneId }) {
+ // Counts mounts, so a test can tell a moved pane from a remounted one.
+ const mount = ++mounts;
+ const label = () =>
+ router
+ .entry(props.pane)
+ ?.location.route.matches.map((match) => match.id)
+ .filter((id) => id !== 'app')
+ .join('/');
+
+ const split = (side: SplitSide) => {
+ nextSplit = { pane: props.pane, side };
+ const destination = DESTINATIONS[opened++ % DESTINATIONS.length]!;
+ const opening = router.open(destination, {
+ newPane: true,
+ source: props.pane,
+ });
+ fireAndForget(opening, 'tiled-splits-fixture');
+ };
+
+ return (
+ <section
+ class="pane"
+ data-pane={label()}
+ data-mount={mount}
+ aria-label={label()}
+ >
+ <strong>{label()}</strong>
+ <textarea aria-label={`${label()} draft`} />
+ <button type="button" onClick={() => split('below')}>
+ Split below
+ </button>
+ <button type="button" onClick={() => split('right')}>
+ Split right
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ fireAndForget(router.close(props.pane), 'tiled-splits-fixture')
+ }
+ >
+ Close
+ </button>
+ </section>
+ );
+}
+
+function App() {
+ return (
+ <>
+ <style>{`
+ * { box-sizing: border-box; }
+ body { margin: 0; font: 14px sans-serif; }
+ .area { position: absolute; left: 0; top: 0; width: 1200px; height: 800px; }
+ .pane { width: 100%; height: 100%; display: flex; flex-direction: column; gap: 4px; padding: 8px; border: 1px solid #888; overflow: hidden; }
+ `}</style>
+ <div class="area">
+ <TiledSplits
+ layout={router.layout}
+ panes={router.panes}
+ gutter={6}
+ showDividers={false}
+ onResize={router.resizeLayout}
+ onArea={() => {}}
+ >
+ {(pane) => <Pane pane={pane} />}
+ </TiledSplits>
+ </div>
+ </>
+ );
+}
+
+render(() => <App />, document.getElementById('root')!);
diff --git a/apps/web/src/components/app/split-layout/browser-test/index.html b/apps/web/src/components/app/split-layout/browser-test/index.html
new file mode 100644
index 0000000000..762cb757c1
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/browser-test/index.html
@@ -0,0 +1,5 @@
+<!doctype html>
+<html lang="en">
+ <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Tiled splits regression</title></head>
+ <body><div id="root"></div><script type="module" src="./fixture.tsx"></script></body>
+</html>
diff --git a/apps/web/src/components/app/split-layout/browser-test/playwright.config.ts b/apps/web/src/components/app/split-layout/browser-test/playwright.config.ts
new file mode 100644
index 0000000000..a060c1230a
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/browser-test/playwright.config.ts
@@ -0,0 +1,38 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig, devices } from '@playwright/test';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../../', import.meta.url));
+const port = Number(process.env.TILED_SPLITS_BROWSER_PORT ?? 3006);
+
+export default defineConfig({
+ testDir: directory,
+ testMatch: '*.browser.e2e.ts',
+ outputDir: `${directory}/test-results`,
+ timeout: 30_000,
+ workers: 1,
+ reporter: 'line',
+ use: {
+ baseURL: `http://127.0.0.1:${port}`,
+ trace: 'retain-on-failure',
+ screenshot: 'only-on-failure',
+ },
+ webServer: {
+ command: `bunx vite --config src/components/app/split-layout/browser-test/vite.config.ts --port ${port}`,
+ cwd: webDirectory,
+ url: `http://127.0.0.1:${port}`,
+ reuseExistingServer: true,
+ },
+ projects: [
+ {
+ name: 'chromium',
+ use: {
+ ...devices['Desktop Chrome'],
+ viewport: { width: 1300, height: 900 },
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ },
+ ],
+});
diff --git a/apps/web/src/components/app/split-layout/browser-test/tiled-splits.browser.e2e.ts b/apps/web/src/components/app/split-layout/browser-test/tiled-splits.browser.e2e.ts
new file mode 100644
index 0000000000..5994fd006b
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/browser-test/tiled-splits.browser.e2e.ts
@@ -0,0 +1,101 @@
+import { expect, type Locator, type Page, test } from '@playwright/test';
+
+const pane = (page: Page, label: string) =>
+ page.locator(`section.pane[data-pane="${label}"]`);
+
+async function box(locator: Locator) {
+ const bounds = await locator.boundingBox();
+ if (!bounds) throw new Error('pane is not laid out');
+
+ return bounds;
+}
+
+const url = (page: Page) =>
+ page.evaluate(() => Reflect.get(window, 'tiledSplitsUrl')() as string);
+
+test('splitting a pane below keeps its content mounted and stacks the new pane under it', async ({
+ page,
+}) => {
+ await page.goto('/');
+ const home = pane(page, 'home');
+ await home.getByRole('textbox').fill('A draft that must survive');
+ const mount = await home.getAttribute('data-mount');
+
+ await home.getByRole('button', { name: 'Split below' }).click();
+
+ const drive = pane(page, 'drive');
+ await expect(drive).toBeVisible();
+ await expect(home).toHaveAttribute('data-mount', mount!);
+ await expect(home.getByRole('textbox')).toHaveValue(
+ 'A draft that must survive'
+ );
+
+ const top = await box(home);
+ const bottom = await box(drive);
+ expect(top).toMatchObject({ x: 0, y: 0, width: 1200, height: 397 });
+ expect(bottom).toMatchObject({ x: 0, y: 403, width: 1200, height: 397 });
+ expect(await url(page)).toBe('/home/~/drive?layout=c2pp');
+});
+
+test('dragging and nudging the gutter between stacked panes resizes them, down to the minimum height', async ({
+ page,
+}) => {
+ await page.goto('/');
+ await pane(page, 'home').getByRole('button', { name: 'Split below' }).click();
+ const gutter = page.getByRole('separator');
+ await expect(gutter).toHaveAttribute('aria-orientation', 'horizontal');
+
+ const start = await box(gutter);
+ const x = start.x + start.width / 2;
+ const y = start.y + start.height / 2;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x, y + 100, { steps: 5 });
+ await page.mouse.up();
+
+ await expect
+ .poll(async () => (await box(pane(page, 'home'))).height)
+ .toBe(497);
+ expect((await box(pane(page, 'drive'))).height).toBe(297);
+
+ await gutter.focus();
+ await page.keyboard.press('ArrowUp');
+ await expect
+ .poll(async () => (await box(pane(page, 'home'))).height)
+ .toBe(477);
+
+ const moved = await box(gutter);
+ await page.mouse.move(x, moved.y + moved.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(x, 1000, { steps: 5 });
+ await page.mouse.up();
+
+ await expect
+ .poll(async () => (await box(pane(page, 'drive'))).height)
+ .toBe(240);
+});
+
+test('closing a stacked pane gives its column back and leaves the others mounted', async ({
+ page,
+}) => {
+ await page.goto('/');
+ await pane(page, 'home').getByRole('button', { name: 'Split right' }).click();
+ const drive = pane(page, 'drive');
+ await drive.getByRole('button', { name: 'Split below' }).click();
+ const mail = pane(page, 'mail');
+ await expect(mail).toBeVisible();
+ expect(await url(page)).toBe('/home/~/drive/~/mail?layout=r2pc2pp');
+
+ const homeMount = await pane(page, 'home').getAttribute('data-mount');
+ const driveMount = await drive.getAttribute('data-mount');
+ await expect(page.getByRole('separator')).toHaveCount(2);
+
+ await mail.getByRole('button', { name: 'Close' }).click();
+
+ await expect(mail).toHaveCount(0);
+ await expect(page.getByRole('separator')).toHaveCount(1);
+ expect(await box(drive)).toMatchObject({ x: 603, y: 0, height: 800 });
+ await expect(pane(page, 'home')).toHaveAttribute('data-mount', homeMount!);
+ await expect(drive).toHaveAttribute('data-mount', driveMount!);
+ expect(await url(page)).toBe('/home/~/drive');
+});
diff --git a/apps/web/src/components/app/split-layout/browser-test/vite.config.ts b/apps/web/src/components/app/split-layout/browser-test/vite.config.ts
new file mode 100644
index 0000000000..de54378c16
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/browser-test/vite.config.ts
@@ -0,0 +1,17 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig } from 'vite';
+import solid from 'vite-plugin-solid';
+import tsconfigPaths from 'vite-tsconfig-paths';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../../', import.meta.url));
+
+export default defineConfig({
+ root: directory,
+ plugins: [
+ solid(),
+ tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),
+ ],
+ resolve: { dedupe: ['solid-js'] },
+ server: { host: '127.0.0.1', strictPort: true },
+});
diff --git a/apps/web/src/components/app/split-layout/components/SplitHeaderContextMenu.tsx b/apps/web/src/components/app/split-layout/components/SplitHeaderContextMenu.tsx
index 49585b545a..b4ecb31dac 100644
--- a/apps/web/src/components/app/split-layout/components/SplitHeaderContextMenu.tsx
+++ b/apps/web/src/components/app/split-layout/components/SplitHeaderContextMenu.tsx
@@ -15,6 +15,7 @@ import CollapseIcon from '@icon/system/regular/arrows-in.svg';
import ExpandIcon from '@icon/system/regular/arrows-out.svg';
import SplitIcon from '@icon/system/regular/columns.svg';
import CopyIcon from '@icon/system/regular/copy.svg';
+import StackIcon from '@icon/system/regular/rows.svg';
import CloseIcon from '@icon/system/regular/x.svg';
import { ContextMenu } from '@kobalte/core/context-menu';
import {
@@ -23,7 +24,7 @@ import {
} from '@kobalte/core/primitives/create-dom-collection';
import { createMemo, type ParentProps, useContext } from 'solid-js';
import { SplitLayoutContext, SplitPanelContext } from '../context';
-import type { SplitContent } from '../layoutManager';
+import type { SplitContent, SplitPlacement } from '../layoutManager';
import { shouldShowSplitCloseButton } from '../layoutUtils';
import { canSpotlight } from '../utils/canSpotlight';
@@ -51,6 +52,8 @@ export function SplitHeaderContextMenu(props: ParentProps) {
const canToggleSpotlight = createMemo(() => canSpotlight(layout.manager));
const canSwapWith = (direction: 'left' | 'right') =>
layout.manager.canSwapSplit(panel.handle.id, direction);
+ const canSplitToward = (side: SplitPlacement['side']) =>
+ layout.manager.canSplit(panel.handle.id, side);
const newSplitContent = () => ({
type: 'component' as const,
@@ -59,17 +62,15 @@ export function SplitHeaderContextMenu(props: ParentProps) {
const duplicateContent = (): SplitContent => ({ ...panel.handle.content() });
- const insertSplitBeside = (side: 'left' | 'right', content: SplitContent) => {
- const index = splitIndex();
- if (index < 0) return;
-
- const insertIndex = side === 'left' ? index : index + 1;
-
+ const insertSplitBeside = (
+ side: SplitPlacement['side'],
+ content: SplitContent
+ ) => {
layout.manager.createNewSplit({
content,
activate: true,
allowDuplicate: true,
- insertIndex,
+ beside: { split: panel.handle.id, side },
referredFrom: null,
});
};
@@ -116,19 +117,32 @@ export function SplitHeaderContextMenu(props: ParentProps) {
icon={SplitIcon}
iconClass="rotate-180"
text={t('splitMenu.newSplitLeft')}
- disabled={!layout.manager.canAppendSplit()}
+ disabled={!canSplitToward('left')}
onClick={() => insertSplitBeside('left', newSplitContent())}
/>
<MenuItem
icon={SplitIcon}
text={t('splitMenu.newSplitRight')}
- disabled={!layout.manager.canAppendSplit()}
+ disabled={!canSplitToward('right')}
onClick={() => insertSplitBeside('right', newSplitContent())}
/>
+ <MenuItem
+ icon={StackIcon}
+ text={t('splitMenu.newSplitAbove')}
+ disabled={!canSplitToward('above')}
+ onClick={() => insertSplitBeside('above', newSplitContent())}
+ />
+ <MenuItem
+ icon={StackIcon}
+ hotkeyToken={TOKENS.global.createNewSplitBelow}
+ text={t('splitMenu.newSplitBelow')}
+ disabled={!canSplitToward('below')}
+ onClick={() => insertSplitBeside('below', newSplitContent())}
+ />
<MenuItem
icon={CopyIcon}
text={t('splitMenu.duplicateSplit')}
- disabled={!layout.manager.canAppendSplit() || !canDuplicateSplit()}
+ disabled={!canSplitToward('right') || !canDuplicateSplit()}
onClick={() => insertSplitBeside('right', duplicateContent())}
/>
<MenuSeparator />
@@ -186,7 +200,7 @@ export function SplitHeaderContextMenu(props: ParentProps) {
icon={ArrowClockwise}
text={t('splitMenu.resetSizes')}
disabled={!hasOtherSplits()}
- onClick={() => layout.manager.resizeContext()?.reset()}
+ onClick={() => layout.manager.resetSizes()}
/>
<MenuSeparator />
<MenuItem
diff --git a/apps/web/src/components/app/split-layout/layout.ts b/apps/web/src/components/app/split-layout/layout.ts
index cd6ffaeeab..417ebaccf8 100644
--- a/apps/web/src/components/app/split-layout/layout.ts
+++ b/apps/web/src/components/app/split-layout/layout.ts
@@ -91,7 +91,7 @@ export function useSplitLayout() {
function insertSplit(
content: SplitContent,
referredFrom: ReferredFrom = null,
- options: Pick<OpenWithSplitOptions, 'insertIndex'> = {}
+ options: Pick<OpenWithSplitOptions, 'beside'> = {}
) {
return openWithSplit(content, {
activate: true,
diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.ts
index 3da2104921..7ae922c5d5 100644
--- a/apps/web/src/components/app/split-layout/layoutManager.ts
+++ b/apps/web/src/components/app/split-layout/layoutManager.ts
@@ -9,6 +9,7 @@ import type {
SplitNavigateOptions,
SplitRouter,
SplitSearchUpdate,
+ SplitSide,
} from '@app/lib/split-router';
import { claimOf } from '@app/lib/split-router';
import { trackNavigationLifecycle } from '@app/observability/navigation-lifecycle';
@@ -18,7 +19,6 @@ import type {
BlockComponentProps,
BlockName,
} from '@core/block';
-import type { ResizeZoneCtx } from '@core/component/Resize/types';
import { isBlockAlias, resolveBlockAlias } from '@core/constant/allBlocks';
import type {
BlockInstanceHandle,
@@ -49,7 +49,7 @@ import {
type ContentInstance,
createContentInstanceRegistry,
} from './contentInstanceRegistry';
-import { DEFAULT_SPLIT_MIN_WIDTH } from './splitContentSizing';
+import { fitsNewColumn, fitsSplit, type TileArea } from './split-geometry';
import { createViewState, type ViewState } from './view-state';
/** Checked on every route change in a pane, so entry state is captured before the pane moves. */
@@ -204,9 +204,12 @@ export type CreateNewSplitOptions = {
/** Shell components only; entity blocks are always single-instance. */
allowDuplicate?: boolean;
referredFrom: ReferredFrom;
- insertIndex?: number;
+ beside?: SplitPlacement;
};
+/** A new split beside `split`, on `side`. */
+export type SplitPlacement = { split: SplitId; side: SplitSide };
+
export type OpenWithSplitOptions = {
/** Resume an opted-in view; explicit new-split actions stay fresh. */
resume?: boolean;
@@ -224,7 +227,8 @@ export type OpenWithSplitOptions = {
replaceWhenFull?: boolean;
/** If true, prefers opening in a new split. May still replace if layout is at capacity. */
preferNewSplit?: boolean;
- insertIndex?: number;
+ /** Where a new split goes; a full-height split at the end by default. */
+ beside?: SplitPlacement;
handle?: SplitHandle;
/**
* Ask the block to land on its latest content via the `goToLatest` block
@@ -321,6 +325,8 @@ export type SplitLayoutOptions = {
stacked?: () => boolean;
/** Changing the session retires retained snapshots and ownership of existing entries. */
sessionKey?: Accessor<string | undefined>;
+ /** True once when the click that opened a new split asked for it below its source. */
+ consumeSplitBelowIntent?: () => boolean;
};
export type SplitManager = {
@@ -340,7 +346,6 @@ export type SplitManager = {
readonly activeSplit: Accessor<SplitHandle | undefined>;
readonly lastActiveSplitId: Accessor<SplitId | undefined>;
readonly events: Accessor<SplitEventWithType | undefined>;
- readonly resizeContext: Accessor<ResizeZoneCtx | undefined>;
// methods
/** Get a split by its split id */
@@ -377,8 +382,15 @@ export type SplitManager = {
getOrchestrator: () => BlockOrchestrator;
+ /** Whether a new full-height split fits beside the others. */
canAppendSplit: () => boolean;
+ /** Whether splitting `id` toward `side` leaves every split its minimum size. */
+ canSplit: (id: SplitId, side: SplitSide) => boolean;
+
+ /** Divides every split's space equally. */
+ resetSizes: () => void;
+
/** Replace all splits with a single split containing the given content. */
replaceAllSplits: (
content: SplitContent,
@@ -403,8 +415,8 @@ export type SplitManager = {
/** A function to return focus to the most recent split. */
returnFocus: () => void;
- /** Set the layout resize context from the component tree. */
- setResizeContext: (cts: ResizeZoneCtx) => void;
+ /** The area the layout measured for its splits. */
+ setTileArea: (area: TileArea) => void;
/** Create a temporary popover split that renders content in a modal dialog */
createPopoverSplit: (
@@ -589,6 +601,10 @@ function contentIdentity(content: SplitContent) {
: content;
}
+/** A split is its router pane; the ids are the same string. */
+export const paneOf = (id: SplitId) => id as string as PaneId;
+export const splitOf = (pane: PaneId) => pane as string as SplitId;
+
export function createSplitLayout(
orchestrator: BlockOrchestrator,
options: SplitLayoutOptions
@@ -669,14 +685,33 @@ export function createSplitLayout(
};
}
- const [resizeContext, setResizeContext] = createSignal<ResizeZoneCtx>();
+ // Unmeasured, as on native mobile, every split fits.
+ const [tileArea, setTileArea] = createSignal<TileArea>();
const isFront = (id: SplitId) => state.splits.at(-1)?.id === id;
const onScreen = (split: SplitState) => !stacked() || isFront(split.id);
- const canAppendSplit = createMemo(
- () => resizeContext()?.canFit({ minSize: DEFAULT_SPLIT_MIN_WIDTH }) ?? true
- );
+ const canAppendSplit = createMemo(() => {
+ const area = tileArea();
+
+ return area ? fitsNewColumn(router.layout(), area) : true;
+ });
+
+ const canSplit = (id: SplitId, side: SplitSide) => {
+ const area = tileArea();
+
+ return area ? fitsSplit(router.layout(), area, paneOf(id), side) : true;
+ };
+
+ /** Room for a new split where `beside` puts it. */
+ const hasRoomFor = (beside: SplitPlacement | undefined) =>
+ beside ? canSplit(beside.split, beside.side) : canAppendSplit();
+
+ /** The router's hint for placing a new split. */
+ const placementIntent = (beside: SplitPlacement | undefined) => ({
+ direct: true,
+ split: beside && { pane: paneOf(beside.split), side: beside.side },
+ });
const [splitNamesById, setSplitNamesById] = createStore<{
[id: SplitId]: string;
@@ -696,9 +731,6 @@ export function createSplitLayout(
const entryStateCaptors = new Map<SplitId, Map<string, () => unknown>>();
const entryStates = new Map<string, EntryState>();
- const paneOf = (id: SplitId) => id as string as PaneId;
- const splitOf = (pane: PaneId) => pane as string as SplitId;
-
function captureEntry(id: SplitId, entry: Entry): EntryState | undefined {
const captors = entryStateCaptors.get(id);
if (!captors || captors.size === 0) return;
@@ -1342,23 +1374,23 @@ export function createSplitLayout(
};
};
- /** Opens `content` in a new pane where the policy places it, after the active split by default. */
+ /** Opens `content` in a new pane where the policy places it, at the end by default. */
function openPane(
content: SplitContent,
openOptions: {
- insertIndex?: number;
+ beside?: SplitPlacement;
referredFrom?: ReferredFrom;
activate?: boolean;
allowDuplicate?: boolean;
}
): MaybePromise<NavigationResult> {
- const { insertIndex, referredFrom, activate, allowDuplicate } = openOptions;
+ const { beside, referredFrom, activate, allowDuplicate } = openOptions;
const active = state.activeSplitId;
const source = active ? paneOf(active) : undefined;
return router.open(
{ location: toLocation(content) },
- { newPane: true, source, intent: { insertIndex, direct: true } },
+ { newPane: true, source, intent: placementIntent(beside) },
{
...entryOptionsOf(content, { referredFrom, activate }),
allowDuplicate,
@@ -1369,8 +1401,7 @@ export function createSplitLayout(
function createNewSplit(
options: CreateNewSplitOptions
): SplitHandle | undefined {
- const { content, activate, referredFrom, insertIndex, allowDuplicate } =
- options;
+ const { content, activate, referredFrom, beside, allowDuplicate } = options;
const initialContent = attachAliasContext(content ?? DEFAULT_SPLIT_CONTENT);
// Direct split creation permits duplicate shells, but never duplicate entities.
@@ -1381,7 +1412,7 @@ export function createSplitLayout(
}
const result = openPane(initialContent, {
- insertIndex,
+ beside,
referredFrom,
activate: activate ?? false,
allowDuplicate,
@@ -1416,11 +1447,8 @@ export function createSplitLayout(
if (!canSwapSplit(id, direction)) return;
const index = splitIndexById(id);
const targetIndex = index + (direction === 'left' ? -1 : 1);
- const target = state.splits[targetIndex];
- batch(() => {
- resizeContext()?.swap(id, target.id);
- router.move(paneOf(id), targetIndex);
- });
+ // The tiles keep their sizes; the two splits trade places.
+ router.move(paneOf(id), targetIndex);
}
function hasSplit(type: SplitContentType, id: string): boolean {
@@ -1618,7 +1646,7 @@ export function createSplitLayout(
};
const wantsNewPane = stacked()
? !options.mergeHistory
- : options.preferNewSplit === true && canAppendSplit();
+ : options.preferNewSplit === true && hasRoomFor(options.beside);
const result =
!source || wantsNewPane
@@ -1627,7 +1655,7 @@ export function createSplitLayout(
{
newPane: true,
source: source && paneOf(source.id),
- intent: { insertIndex: options.insertIndex, direct: true },
+ intent: placementIntent(options.beside),
},
navigateOptions
)
@@ -1676,10 +1704,22 @@ export function createSplitLayout(
}
}
+ /** A Shift-click that also held Option opens below the split it came from. */
+ function withClickedSide(open: OpenWithSplitOptions): OpenWithSplitOptions {
+ if (stacked() || !open.preferNewSplit || open.beside) return open;
+ if (!options.consumeSplitBelowIntent?.()) return open;
+
+ const source = open.handle ?? activeSplit();
+ if (!source) return open;
+
+ return { ...open, beside: { split: source.id, side: 'below' } };
+ }
+
function openWithSplit(
content: SplitContent,
- options: OpenWithSplitOptions = {}
+ requested: OpenWithSplitOptions = {}
): OpenSplitResult {
+ let options = withClickedSide(requested);
const sourceOwner = options.handle?.id;
if (options.resume && !options.preferNewSplit) {
const source = options.handle ?? activeSplit();
@@ -1759,7 +1799,7 @@ export function createSplitLayout(
}
const shouldReplaceWhenFull =
- options.replaceWhenFull !== false && !canAppendSplit();
+ options.replaceWhenFull !== false && !hasRoomFor(options.beside);
const shouldReplace = stacked()
? options.mergeHistory === true
@@ -1786,7 +1826,7 @@ export function createSplitLayout(
activate: options.activate ?? true,
referredFrom: options.referredFrom ?? null,
allowDuplicate: options.allowDuplicate,
- insertIndex: options.insertIndex,
+ beside: options.beside,
});
return split
? { status: 'opened', split, sourceOwner }
@@ -1884,14 +1924,15 @@ export function createSplitLayout(
toggleSpotlightSplit,
tabTitle,
returnFocus: () => dispatchEvent(SplitEvent.ReturnFocus, undefined),
- resizeContext,
- setResizeContext,
+ setTileArea,
getOrchestrator: () => orchestrator,
createPopoverSplit,
getActivePopovers,
closeAllPopovers,
popovers: () => state.popovers,
canAppendSplit,
+ canSplit,
+ resetSizes: router.resetLayoutSizes,
getVisibleSplits,
getVisibleSplitCount: () => getVisibleSplits().length,
contentNavigationReady: router.ready,
diff --git a/apps/web/src/components/app/split-layout/split-below-intent.ts b/apps/web/src/components/app/split-layout/split-below-intent.ts
new file mode 100644
index 0000000000..ed455e66fe
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/split-below-intent.ts
@@ -0,0 +1,45 @@
+/**
+ * Remembers that the last click also held Option (Alt elsewhere) with Shift.
+ * The layout manager consumes it when a Shift-click opens a new split, which
+ * then goes below the split it came from instead of beside the others, so
+ * every Shift-click surface supports it without threading the event through.
+ */
+let armedUntil: number | undefined;
+
+/** Long enough for a navigation that follows the click, short enough that a later one can't pick it up. */
+const INTENT_EXPIRY_MS = 800;
+
+function arm(event: MouseEvent) {
+ if (event.button !== 0) return;
+
+ const opensBelow = event.altKey && event.shiftKey;
+ armedUntil = opensBelow ? performance.now() + INTENT_EXPIRY_MS : undefined;
+}
+
+/** A key press starts a keyboard navigation, which a click's intent must not reach. */
+function disarm() {
+ armedUntil = undefined;
+}
+
+/** One-shot read; a stale intent is dropped. */
+export function consumeSplitBelowIntent(): boolean {
+ const until = armedUntil;
+ armedUntil = undefined;
+
+ return until !== undefined && performance.now() <= until;
+}
+
+export function installSplitBelowIntentTracker(): () => void {
+ // Capture phase: some surfaces navigate from pointerdown handlers, others on
+ // click, and both may stop propagation.
+ window.addEventListener('pointerdown', arm, { capture: true });
+ window.addEventListener('click', arm, { capture: true });
+ window.addEventListener('keydown', disarm, { capture: true });
+
+ return () => {
+ window.removeEventListener('pointerdown', arm, { capture: true });
+ window.removeEventListener('click', arm, { capture: true });
+ window.removeEventListener('keydown', disarm, { capture: true });
+ armedUntil = undefined;
+ };
+}
diff --git a/apps/web/src/components/app/split-layout/split-geometry.ts b/apps/web/src/components/app/split-layout/split-geometry.ts
new file mode 100644
index 0000000000..9de32d7d37
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/split-geometry.ts
@@ -0,0 +1,184 @@
+import type {
+ PaneId,
+ PaneLayout,
+ SplitAxis,
+ SplitPath,
+ SplitSide,
+} from '@app/lib/split-router';
+import { computeFractionalShares } from '@core/component/Resize/solver';
+import type { Panel } from '@core/component/Resize/types';
+import {
+ DEFAULT_SPLIT_MIN_HEIGHT,
+ DEFAULT_SPLIT_MIN_WIDTH,
+} from './splitContentSizing';
+
+export type Size = { width: number; height: number };
+
+export type Rect = Size & { left: number; top: number };
+
+/** Where the splits tile, as the layout measured it, and the gap between them. */
+export type TileArea = Size & { gutter: number };
+
+/** One split as laid out: what dragging one of its gutters needs. */
+export type SolvedSplit = {
+ path: SplitPath;
+ axis: SplitAxis;
+ rect: Rect;
+ /** Rendered shares, which can differ from the intended ones when space is short. */
+ shares: readonly number[];
+ /** Each child's minimum along the axis. */
+ minimums: readonly number[];
+ /** Where each gutter starts along the axis, within `rect`. */
+ gutters: readonly number[];
+};
+
+export type TileGeometry = {
+ panes: ReadonlyMap<PaneId, Rect>;
+ splits: readonly SolvedSplit[];
+};
+
+const MIN_PANE_SIZE: Size = {
+ width: DEFAULT_SPLIT_MIN_WIDTH,
+ height: DEFAULT_SPLIT_MIN_HEIGHT,
+};
+
+const lengthAlong = (axis: SplitAxis, size: Size) =>
+ axis === 'row' ? size.width : size.height;
+
+/** The smallest size of `sizes` laid out along `axis`. */
+function joinedSize(
+ axis: SplitAxis,
+ sizes: readonly Size[],
+ gutter: number
+): Size {
+ const gutters = gutter * Math.max(0, sizes.length - 1);
+ const widths = sizes.map((size) => size.width);
+ const heights = sizes.map((size) => size.height);
+ const sum = (values: number[]) =>
+ values.reduce((total, value) => total + value, 0);
+
+ if (axis === 'row') {
+ return { width: sum(widths) + gutters, height: Math.max(...heights) };
+ }
+
+ return { width: Math.max(...widths), height: sum(heights) + gutters };
+}
+
+/**
+ * The smallest size `layout` fits in with every split at its minimum, with
+ * `grown` split in two along `axis` when given.
+ */
+function minimumSize(
+ layout: PaneLayout,
+ gutter: number,
+ grown?: { pane: PaneId; axis: SplitAxis }
+): Size {
+ if (layout.type === 'pane') {
+ if (grown?.pane !== layout.pane) return MIN_PANE_SIZE;
+
+ return joinedSize(grown.axis, [MIN_PANE_SIZE, MIN_PANE_SIZE], gutter);
+ }
+
+ const sizes = layout.children.map((child) =>
+ minimumSize(child, gutter, grown)
+ );
+
+ return joinedSize(layout.axis, sizes, gutter);
+}
+
+/** Whether a new full-height split fits beside the others. */
+export function fitsNewColumn(
+ layout: PaneLayout | undefined,
+ area: TileArea
+): boolean {
+ if (!layout) return true;
+
+ const current = minimumSize(layout, area.gutter);
+ const grown = joinedSize('row', [current, MIN_PANE_SIZE], area.gutter);
+
+ return grown.width <= area.width;
+}
+
+/** Whether splitting `pane` toward `side` leaves every split its minimum along that axis. */
+export function fitsSplit(
+ layout: PaneLayout | undefined,
+ area: TileArea,
+ pane: PaneId,
+ side: SplitSide
+): boolean {
+ if (!layout) return true;
+
+ const axis: SplitAxis =
+ side === 'left' || side === 'right' ? 'row' : 'column';
+ const grown = minimumSize(layout, area.gutter, { pane, axis });
+
+ return lengthAlong(axis, grown) <= lengthAlong(axis, area);
+}
+
+/** Lays `layout` out in `area`: a rect for each pane and the gutters of each split. */
+export function solveTiles(
+ layout: PaneLayout | undefined,
+ area: TileArea
+): TileGeometry {
+ const panes = new Map<PaneId, Rect>();
+ const splits: SolvedSplit[] = [];
+ const { gutter } = area;
+
+ const place = (node: PaneLayout, rect: Rect, path: SplitPath) => {
+ if (node.type === 'pane') {
+ panes.set(node.pane, rect);
+ return;
+ }
+
+ const minimums = node.children.map((child) =>
+ lengthAlong(node.axis, minimumSize(child, gutter))
+ );
+ const panels: Panel[] = node.children.map((_, index) => ({
+ id: String(index),
+ minSize: minimums[index]!,
+ maxSize: Infinity,
+ share: node.shares[index]!,
+ target: { kind: 'auto' },
+ }));
+ const solved = computeFractionalShares(
+ panels,
+ lengthAlong(node.axis, rect),
+ gutter
+ );
+
+ const offsets = panels.map(({ id }) => solved.offsets.get(id) ?? 0);
+ const sizes = panels.map(({ id }) => solved.sizes.get(id) ?? 0);
+
+ splits.push({
+ path,
+ axis: node.axis,
+ rect,
+ shares: panels.map(({ id }) => solved.shares.get(id) ?? 0),
+ minimums,
+ gutters: offsets
+ .slice(0, -1)
+ .map((offset, index) => offset + sizes[index]!),
+ });
+
+ node.children.forEach((child, index) => {
+ const offset = offsets[index]!;
+ const size = sizes[index]!;
+ const childRect: Rect =
+ node.axis === 'row'
+ ? { ...rect, left: rect.left + offset, width: size }
+ : { ...rect, top: rect.top + offset, height: size };
+
+ place(child, childRect, [...path, index]);
+ });
+ };
+
+ if (layout) {
+ place(
+ layout,
+ { left: 0, top: 0, width: area.width, height: area.height },
+ []
+ );
+ }
+
+ return { panes, splits };
+}
diff --git a/apps/web/src/components/app/split-layout/split-router/app-pane-policy.ts b/apps/web/src/components/app/split-layout/split-router/app-pane-policy.ts
index 08193ac914..b4f3dc5069 100644
--- a/apps/web/src/components/app/split-layout/split-router/app-pane-policy.ts
+++ b/apps/web/src/components/app/split-layout/split-router/app-pane-policy.ts
@@ -3,9 +3,23 @@ import type {
PaneId,
SplitLocation,
SplitPanePolicy,
+ SplitSide,
} from '@app/lib/split-router';
import { paneRootMatch } from '@app/routes/app-route';
-import type { SplitContent, SplitId, SplitManager } from '../layoutManager';
+import {
+ type SplitContent,
+ type SplitManager,
+ splitOf,
+} from '../layoutManager';
+
+declare module '@app/lib/split-router/panes/types' {
+ interface OpenIntent {
+ /** The manager already checked for room. */
+ readonly direct?: boolean;
+ /** Split this pane, with the new one on `side`. */
+ readonly split?: { readonly pane: PaneId; readonly side: SplitSide };
+ }
+}
type AppPanePolicyOptions = {
manager: () => SplitManager | undefined;
@@ -22,8 +36,6 @@ function isShellComponent(content: SplitContent): boolean {
return parseAgentsRoute(content.id) === undefined;
}
-const splitOf = (pane: PaneId) => pane as string as SplitId;
-
/** The app's decisions about panes: where new ones go, what closing one does, and focus. */
export function createAppPanePolicy(
options: AppPanePolicyOptions
@@ -53,9 +65,9 @@ export function createAppPanePolicy(
intent.direct !== true && !options.manager()?.canAppendSplit();
if (full && fallback) return { pane: fallback };
- const { insertIndex } = intent;
- if (typeof insertIndex === 'number') {
- return { insertAt: Math.max(0, Math.min(insertIndex, panes.length)) };
+ const { split } = intent;
+ if (split && panes.includes(split.pane)) {
+ return { split: split.pane, side: split.side };
}
return { insertAt: panes.length };
diff --git a/apps/web/src/components/app/split-layout/splitContentSizing.ts b/apps/web/src/components/app/split-layout/splitContentSizing.ts
index 2e0d6c7693..27c9943110 100644
--- a/apps/web/src/components/app/split-layout/splitContentSizing.ts
+++ b/apps/web/src/components/app/split-layout/splitContentSizing.ts
@@ -1,2 +1,5 @@
/** Default hard minimum width for split content. */
export const DEFAULT_SPLIT_MIN_WIDTH = 400;
+
+/** Default hard minimum height for split content stacked with other splits. */
+export const DEFAULT_SPLIT_MIN_HEIGHT = 240;
diff --git a/apps/web/src/components/app/split-layout/tests/fixtures.ts b/apps/web/src/components/app/split-layout/tests/fixtures.ts
index d4c1b1ca90..4c435091cc 100644
--- a/apps/web/src/components/app/split-layout/tests/fixtures.ts
+++ b/apps/web/src/components/app/split-layout/tests/fixtures.ts
@@ -4,6 +4,7 @@ import {
createSplitRouter,
type Entry,
type SplitLocation,
+ type SplitRouter,
type SplitRoutes,
} from '@app/lib/split-router';
import { paneRoute } from '@app/routes/app-route';
@@ -54,6 +55,15 @@ export function createRoutedSplitLayout(
url: string,
stacked = false
): SplitManager {
+ return createRoutedSplitLayoutWithRouter(orchestrator, url, stacked).manager;
+}
+
+/** `createRoutedSplitLayout`, with the router underneath it. */
+export function createRoutedSplitLayoutWithRouter(
+ orchestrator: BlockOrchestrator,
+ url: string,
+ stacked = false
+): { manager: SplitManager; router: SplitRouter } {
let manager: SplitManager | undefined;
const router = createSplitRouter({
routes,
@@ -72,5 +82,5 @@ export function createRoutedSplitLayout(
toContent: splitContentFromLocation,
stacked: () => stacked,
});
- return manager;
+ return { manager, router };
}
diff --git a/apps/web/src/components/app/split-layout/tests/split-geometry.test.ts b/apps/web/src/components/app/split-layout/tests/split-geometry.test.ts
new file mode 100644
index 0000000000..7669c51707
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/tests/split-geometry.test.ts
@@ -0,0 +1,106 @@
+import type { PaneId, PaneLayout } from '@app/lib/split-router';
+import { describe, expect, it } from 'vitest';
+import { fitsNewColumn, fitsSplit, solveTiles } from '../split-geometry';
+
+const [a, b, c] = ['a', 'b', 'c'] as PaneId[];
+
+const leaf = (pane: PaneId): PaneLayout => ({ type: 'pane', pane });
+
+// a | (b over c)
+const stackedBeside = (shares: number[] = [0.5, 0.5]): PaneLayout => ({
+ type: 'split',
+ axis: 'row',
+ shares,
+ children: [
+ leaf(a),
+ {
+ type: 'split',
+ axis: 'column',
+ shares: [0.5, 0.5],
+ children: [leaf(b), leaf(c)],
+ },
+ ],
+});
+
+describe('solveTiles', () => {
+ it('tiles stacked panes beside another with gutters between them', () => {
+ const tiles = solveTiles(stackedBeside(), {
+ width: 1000,
+ height: 800,
+ gutter: 6,
+ });
+
+ expect(tiles.panes.get(a)).toEqual({
+ left: 0,
+ top: 0,
+ width: 497,
+ height: 800,
+ });
+ expect(tiles.panes.get(b)).toEqual({
+ left: 503,
+ top: 0,
+ width: 497,
+ height: 397,
+ });
+ expect(tiles.panes.get(c)).toEqual({
+ left: 503,
+ top: 403,
+ width: 497,
+ height: 397,
+ });
+ expect(
+ tiles.splits.map(({ path, axis, gutters }) => ({ path, axis, gutters }))
+ ).toEqual([
+ { path: [], axis: 'row', gutters: [497] },
+ { path: [1], axis: 'column', gutters: [397] },
+ ]);
+ });
+
+ it('keeps a stack at its minimum width when its share is smaller', () => {
+ const tiles = solveTiles(stackedBeside([0.8, 0.2]), {
+ width: 900,
+ height: 800,
+ gutter: 6,
+ });
+
+ expect(tiles.panes.get(a)?.width).toBe(494);
+ expect(tiles.panes.get(b)?.width).toBe(400);
+ });
+});
+
+describe('room for another split', () => {
+ it('fits a new column only while every column keeps its minimum width', () => {
+ const area = { height: 800, gutter: 6 };
+
+ expect(fitsNewColumn(stackedBeside(), { ...area, width: 1212 })).toBe(true);
+ expect(fitsNewColumn(stackedBeside(), { ...area, width: 1211 })).toBe(
+ false
+ );
+ });
+
+ it('checks a split along its own axis', () => {
+ const area = { width: 400, gutter: 6 };
+
+ expect(fitsSplit(leaf(a), { ...area, height: 486 }, a, 'below')).toBe(true);
+ expect(fitsSplit(leaf(a), { ...area, height: 485 }, a, 'below')).toBe(
+ false
+ );
+ // Splitting b side by side widens the stack it sits in.
+ expect(
+ fitsSplit(
+ stackedBeside(),
+ { width: 1212, height: 400, gutter: 6 },
+ b,
+ 'right'
+ )
+ ).toBe(true);
+ expect(
+ fitsSplit(
+ stackedBeside(),
+ { width: 1211, height: 400, gutter: 6 },
+ b,
+ 'right'
+ )
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/src/components/app/split-layout/tests/split-placement.test.ts b/apps/web/src/components/app/split-layout/tests/split-placement.test.ts
new file mode 100644
index 0000000000..51d2fcb521
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/tests/split-placement.test.ts
@@ -0,0 +1,73 @@
+import { layoutShape } from '@app/lib/split-router/panes/layout-tree';
+import type { BlockOrchestrator } from '@core/orchestrator';
+import { createRoot } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createRoutedSplitLayoutWithRouter } from './fixtures';
+
+vi.mock('../componentRegistry', () => ({
+ resolveComponent: vi.fn((id: string, params: Record<string, string>) => ({
+ type: 'mock-component',
+ id,
+ params,
+ })),
+}));
+
+vi.mock('@core/constant/allBlocks', () => ({
+ isBlockAlias: vi.fn(() => false),
+ resolveBlockAlias: vi.fn((type: string) => type),
+}));
+
+function createMockOrchestrator(): BlockOrchestrator {
+ return {
+ isBlockMounted: vi.fn(() => false),
+ createBlockInstance: vi.fn((_type, id, _splitId) => ({
+ node: { type: 'mock-node', id },
+ detach: vi.fn(),
+ dispose: vi.fn(),
+ })),
+ } as unknown as BlockOrchestrator;
+}
+
+let dispose: (() => void) | undefined;
+
+afterEach(() => {
+ dispose?.();
+ dispose = undefined;
+});
+
+function setup(url: string) {
+ return createRoot((disposeRoot) => {
+ dispose = disposeRoot;
+
+ return createRoutedSplitLayoutWithRouter(createMockOrchestrator(), url);
+ });
+}
+
+describe('opening a split beside another', () => {
+ it('splits only the active stacked split, leaving the split above full width', async () => {
+ // Home over Channels, with Channels active.
+ const { manager, router } = setup('/home/~/channels?layout=c2pp');
+ const [above, active] = manager.splits();
+ manager.activateSplit(active!.id);
+
+ manager.openWithSplit(
+ { type: 'component', id: 'home' },
+ {
+ preferNewSplit: true,
+ allowDuplicate: true,
+ beside: { split: active!.id, side: 'right' },
+ }
+ );
+ await router.settled();
+
+ expect(layoutShape(router.layout()!)).toEqual({
+ axis: 'column',
+ children: ['pane', { axis: 'row', children: ['pane', 'pane'] }],
+ });
+ expect(manager.splits().map((split) => split.id)).toEqual([
+ above!.id,
+ active!.id,
+ expect.any(String),
+ ]);
+ });
+});
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
index 409bc44bf7..79ab44b309 100644
--- 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
@@ -6,6 +6,7 @@ import {
type SplitRouter,
type SplitRoutes,
} from '@app/lib/split-router';
+import { SplitRouterProvider } from '@app/lib/split-router/solid/context';
import { paneRoute } from '@app/routes/app-route';
import {
appRoute,
@@ -29,14 +30,14 @@ import {
} 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 { onCleanup } from 'solid-js';
+import { afterEach, beforeEach, 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.
+// A stand-in that counts mounts: the layers decide what stays mounted, not
+// the panel.
vi.mock('@components/app/split-layout/components/SplitPanel', () => ({
SplitPanel: (props: { split: { id: string } }) => {
panels.mounted += 1;
@@ -46,12 +47,6 @@ vi.mock('@components/app/split-layout/components/SplitPanel', () => ({
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: [
@@ -101,9 +96,11 @@ function setup(url: string) {
});
setGlobalTabManager(tabManager);
return (
- <SplitLayoutContext.Provider value={{ manager }}>
- <SplitLayout />
- </SplitLayoutContext.Provider>
+ <SplitRouterProvider router={router}>
+ <SplitLayoutContext.Provider value={{ manager }}>
+ <SplitLayout />
+ </SplitLayoutContext.Provider>
+ </SplitRouterProvider>
);
});
return { router, tabManager };
@@ -118,7 +115,19 @@ async function flush(router: SplitRouter) {
const layer = (id: string) =>
document.querySelector<HTMLElement>(`[data-split-layer="${id}"]`);
+// jsdom has no layout; the tiled layout only needs to observe something.
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+beforeEach(() => {
+ vi.stubGlobal('ResizeObserver', ResizeObserverStub);
+});
+
afterEach(() => {
+ vi.unstubAllGlobals();
setGlobalTabManager(undefined);
cleanup();
panels.mounted = 0;
@@ -157,6 +166,25 @@ describe('desktop tab layers', () => {
expect(layer(second)?.inert).toBe(true);
});
+ it('a stacked tab parks and comes back stacked without remounting', async () => {
+ const { router, tabManager } = setup(
+ '/channels/channel-one/~/home?layout=c2pp'
+ );
+ await flush(router);
+ const first = tabManager.activeTabId();
+ const stacked = router.layout();
+ expect(stacked).toMatchObject({ axis: 'column' });
+
+ tabManager.newTab();
+ await flush(router);
+ tabManager.activateTab(first);
+ await flush(router);
+
+ expect(router.layout()).toEqual(stacked);
+ expect(panels.mounted).toBe(3);
+ expect(panels.unmounted).toBe(0);
+ });
+
it('closing a tab unmounts only its panes', async () => {
const { router, tabManager } = setup('/channels/channel-one');
await flush(router);
diff --git a/apps/web/src/features/settings/Shortcuts.tsx b/apps/web/src/features/settings/Shortcuts.tsx
index 6667ff91af..20b43031bd 100644
--- a/apps/web/src/features/settings/Shortcuts.tsx
+++ b/apps/web/src/features/settings/Shortcuts.tsx
@@ -945,6 +945,11 @@ const shortcutSections: ShortcutSection[] = [
description: 'Spotlight split',
},
{ keys: ['\\'], codes: ['Backslash'], description: 'Create a split' },
+ {
+ keys: ['|'],
+ codes: ['ShiftLeft', 'Backslash'],
+ description: 'Create a split below',
+ },
],
},
{
diff --git a/apps/web/src/lib/analytics/app-events.ts b/apps/web/src/lib/analytics/app-events.ts
index 0161c9bec8..493dd81fc9 100644
--- a/apps/web/src/lib/analytics/app-events.ts
+++ b/apps/web/src/lib/analytics/app-events.ts
@@ -157,7 +157,8 @@ export type AppEvents = {
hotkey_use: Record<string, unknown>;
mentions_menu_use: { itemType: string };
snippets_menu_use: Record<string, unknown>;
- split_created: { from: string };
+ /** `side` is where a split opened beside another; absent, it opened at the end. */
+ split_created: { from: string; side?: 'left' | 'right' | 'above' | 'below' };
// --- Entity lifecycle ----------------------------------------------------
// Fired at data-layer chokepoints (core/util/create.ts, FileList
diff --git a/apps/web/src/lib/core/component/Resize/Resize.tsx b/apps/web/src/lib/core/component/Resize/Resize.tsx
index df797d227f..9c542f2680 100644
--- a/apps/web/src/lib/core/component/Resize/Resize.tsx
+++ b/apps/web/src/lib/core/component/Resize/Resize.tsx
@@ -217,6 +217,8 @@ function Zone(props: ParentProps<ZoneProps>) {
return (
<Show when={visibleIndex < visibleLayouts().length - 1}>
<Gutter
+ direction={direction()}
+ gutterSize={gutterPx()}
offset={panel().offset + panel().size}
index={actualIndex}
resizable={gutterEnabled()}
@@ -398,13 +400,18 @@ function Panel(props: ParentProps<PanelProps>) {
}
/**
- * Props for the Gutter component (internal).
+ * Props for the Gutter component. It fills its positioned parent across the
+ * axis, so a zone, or any layout that positions its own panels, can place one.
*
+ * @property direction - The flow of the panels it separates
+ * @property gutterSize - The layout gap it sits in, in pixels
* @property offset - The offset position of the gutter in pixels
* @property index - The index of the gutter in the layout
* @property nudge - Function to call when the gutter is moved, with index and movement amount
*/
type GutterProps = {
+ direction: 'horizontal' | 'vertical';
+ gutterSize: number;
showDivider: boolean;
offset: number;
index: number;
@@ -423,15 +430,15 @@ type GutterProps = {
*/
const GUTTER_HIT_AREA = 8;
-function Gutter(props: GutterProps) {
- const ctx = useContext(ResizeZoneContext)!;
+export function Gutter(props: GutterProps) {
+ const horizontal = () => props.direction === 'horizontal';
const hitSize = () =>
props.resizable
- ? Math.max(ctx.gutterSize(), GUTTER_HIT_AREA)
- : ctx.gutterSize();
+ ? Math.max(props.gutterSize, GUTTER_HIT_AREA)
+ : props.gutterSize;
const styles = createMemo(() => {
- const inset = (hitSize() - ctx.gutterSize()) / 2;
- if (ctx.direction() === 'horizontal') {
+ const inset = (hitSize() - props.gutterSize) / 2;
+ if (horizontal()) {
return {
top: '0px',
bottom: '0px',
@@ -461,17 +468,15 @@ function Gutter(props: GutterProps) {
if (!root) return 1;
const rect = root.getBoundingClientRect();
- const visualSize =
- ctx.direction() === 'horizontal' ? rect.width : rect.height;
- const layoutSize =
- ctx.direction() === 'horizontal' ? root.offsetWidth : root.offsetHeight;
+ const visualSize = horizontal() ? rect.width : rect.height;
+ const layoutSize = horizontal() ? root.offsetWidth : root.offsetHeight;
if (visualSize <= 0 || layoutSize <= 0) return 1;
return visualSize / layoutSize;
}
function eventPosition(ev: PointerEvent) {
- return ctx.direction() === 'horizontal' ? ev.clientX : ev.clientY;
+ return horizontal() ? ev.clientX : ev.clientY;
}
function onPointerDown(ev: PointerEvent) {
@@ -535,7 +540,7 @@ function Gutter(props: GutterProps) {
});
function onKeyDown(ev: KeyboardEvent) {
- if (ctx?.direction() === 'horizontal') {
+ if (horizontal()) {
if (ev.key !== 'ArrowLeft' && ev.key !== 'ArrowRight') return;
} else {
if (ev.key !== 'ArrowUp' && ev.key !== 'ArrowDown') return;
@@ -547,7 +552,7 @@ function Gutter(props: GutterProps) {
const step = ev.shiftKey ? 100 : 20;
props.onChangeStart();
- if (ctx?.direction() === 'horizontal') {
+ if (horizontal()) {
const sign = ev.key === 'ArrowLeft' ? -1 : 1;
props.nudge(props.index, sign * step);
} else {
@@ -557,7 +562,6 @@ function Gutter(props: GutterProps) {
queueMicrotask(props.onChangeEnd);
}
- const horizontal = () => ctx.direction() === 'horizontal';
// Centre a bar of the given thickness on the gutter axis.
const barStyle = (thickness: string) => ({
left: horizontal() ? '50%' : '0',
@@ -569,7 +573,7 @@ function Gutter(props: GutterProps) {
return (
<div
- class={cn('group', !props.resizable && 'pointer-events-none')}
+ class="group"
role="separator"
aria-orientation={horizontal() ? 'vertical' : 'horizontal'}
aria-hidden={!props.resizable}
@@ -577,6 +581,8 @@ function Gutter(props: GutterProps) {
aria-label={props.resizable ? `resize at ${props.index}` : undefined}
style={{
position: 'absolute',
+ // Inline, so a gutter inside a pass-through box still takes the drag.
+ 'pointer-events': props.resizable ? 'auto' : 'none',
cursor: props.resizable
? horizontal()
? 'col-resize'
diff --git a/apps/web/src/lib/core/component/Resize/index.ts b/apps/web/src/lib/core/component/Resize/index.ts
index 20af21f7b4..e15ffd0473 100644
--- a/apps/web/src/lib/core/component/Resize/index.ts
+++ b/apps/web/src/lib/core/component/Resize/index.ts
@@ -1 +1 @@
-export { Resize } from './Resize';
+export { Gutter, Resize } from './Resize';
diff --git a/apps/web/src/lib/core/component/Resize/solver.ts b/apps/web/src/lib/core/component/Resize/solver.ts
index d7807e31c8..fdb8ec6921 100644
--- a/apps/web/src/lib/core/component/Resize/solver.ts
+++ b/apps/web/src/lib/core/component/Resize/solver.ts
@@ -46,7 +46,7 @@ function getUsable(panelCount: number, total: number, gutter: number) {
* @param gutter The pixel gutter size
* @returns A result with
*/
-function computeFractionalShares(
+export function computeFractionalShares(
panels: Panel[],
total: number,
gutter: number
@@ -235,6 +235,108 @@ function applyRedistributionPreferences(
});
}
+/**
+ * The shares after dragging the handle between panels `index` and `index + 1`
+ * by `deltaPx`, starting from `shares`. The shrinking side gives up space from
+ * the handle outward until each panel reaches its minimum. Undefined when the
+ * handle can't move.
+ */
+export function moveHandleShares(params: {
+ panels: readonly Pick<Panel, 'minSize' | 'maxSize'>[];
+ shares: readonly number[];
+ index: number;
+ deltaPx: number;
+ usable: number;
+}): number[] | undefined {
+ const { panels, shares, index: L, usable } = params;
+ const n = shares.length;
+ if (L < 0 || L >= n - 1) return;
+ if (usable <= 0) return;
+
+ // +dShare => handle right: left grows, right stack shrinks
+ // -dShare => handle left: left stack shrinks, right grows
+ const dShare = params.deltaPx / usable;
+ if (!Number.isFinite(dShare) || dShare === 0) return;
+
+ const R = L + 1;
+
+ const bounds = (i: number) => {
+ if (i < 0 || i >= panels.length) return [0, 0];
+ const minPx = panels[i].minSize ?? 0;
+ const maxPx = panels[i].maxSize ?? Infinity;
+ const minS = Math.max(0, minPx / usable);
+ const maxS = Number.isFinite(maxPx) ? maxPx / usable : 1;
+ return [minS, maxS] as const;
+ };
+
+ const growCap = (i: number) => {
+ const [, maxS] = bounds(i);
+ return Math.max(0, maxS - shares[i]);
+ };
+
+ // Shrink panels outward from the handle until the requested space is freed.
+ const shrinkStack = (
+ newShares: number[],
+ from: number,
+ dir: 1 | -1,
+ amount: number
+ ) => {
+ let remain = amount;
+ for (let i = from; i >= 0 && i < n && remain > EPSILON; i += dir) {
+ const [minS] = bounds(i);
+ const take = Math.min(Math.max(0, newShares[i] - minS), remain);
+ newShares[i] -= take;
+ remain -= take;
+ }
+ };
+
+ const shrinkCapLeftStack = () => {
+ let cap = 0;
+ for (let i = L; i >= 0; i--) {
+ const [minS] = bounds(i);
+ cap += Math.max(0, shares[i] - minS);
+ }
+ return cap;
+ };
+
+ const shrinkCapRightStack = () => {
+ let cap = 0;
+ for (let i = R; i < n; i++) {
+ const [minS] = bounds(i);
+ cap += Math.max(0, shares[i] - minS);
+ }
+ return cap;
+ };
+
+ const newShares = shares.slice();
+
+ if (dShare < 0) {
+ // Move LEFT: shrink LEFT stack, grow RIGHT
+ const req = -dShare;
+ const applied = Math.min(req, shrinkCapLeftStack(), growCap(R));
+ if (applied <= 0) return;
+
+ // shrink from the handle outward: L, L-1, L-2, ...
+ shrinkStack(newShares, L, -1, applied);
+ newShares[R] += applied;
+ } else {
+ // dShare > 0: Move RIGHT: shrink RIGHT stack, grow LEFT
+ const req = dShare;
+ const applied = Math.min(req, shrinkCapRightStack(), growCap(L));
+ if (applied <= 0) return;
+
+ shrinkStack(newShares, R, 1, applied);
+ newShares[L] += applied;
+ }
+
+ const sum = sumArray(newShares);
+ if (Math.abs(sum - 1) > EPSILON && sum > 0 && Number.isFinite(sum)) {
+ return newShares.map((share) => share / sum);
+ }
+
+ return newShares;
+}
+
/**
* Create the internal-hiding business logic for a resize Zone.
* @param params
@@ -453,22 +555,6 @@ export function createResizeSolver(params: {
function moveHandle(ndx: number, deltaPx: number) {
const ids = order();
const n = ids.length;
- if (ndx < 0 || ndx >= n - 1) return;
-
- const panels = panelsInOrder();
- const usable = Math.max(
- 0,
- params.size() - Math.max(0, n - 1) * params.gutter()
- );
- if (usable <= 0) return;
-
- // +dShare => handle right: left grows, right stack shrinks
- // -dShare => handle left: left stack shrinks, right grows
- const dShare = deltaPx / usable;
- if (!Number.isFinite(dShare) || dShare === 0) return;
-
- const L = ndx;
- const R = ndx + 1;
// Drags anchor to the RENDERED layout (what the user sees), which can
// differ from the intent shares when constraints or pins are active.
@@ -476,94 +562,17 @@ export function createResizeSolver(params: {
// manual resizing is the one interaction that redefines intent from
// rendered reality.
const rendered = untrack(layout).shares;
- const shares = ids.map((id) => rendered.get(id) ?? panelData[id]!.share);
-
- const bounds = (i: number) => {
- if (i < 0 || i >= panels.length) return [0, 0];
- const minPx = panels[i].minSize ?? 0;
- const maxPx = panels[i].maxSize ?? Infinity;
- const minS = Math.max(0, minPx / usable);
- const maxS = Number.isFinite(maxPx) ? maxPx / usable : 1;
- return [minS, maxS] as const;
- };
-
- const growCap = (i: number) => {
- const [, maxS] = bounds(i);
- return Math.max(0, maxS - shares[i]);
- };
-
- // Shrink panels outward from the handle until the requested space is freed.
- const shrinkStack = (
- newShares: number[],
- from: number,
- dir: 1 | -1,
- amount: number
- ) => {
- let remain = amount;
- for (let i = from; i >= 0 && i < n && remain > EPSILON; i += dir) {
- const [minS] = bounds(i);
- const take = Math.min(Math.max(0, newShares[i] - minS), remain);
- newShares[i] -= take;
- remain -= take;
- }
- };
-
- const shrinkCapLeftStack = () => {
- let cap = 0;
- for (let i = L; i >= 0; i--) {
- const [minS] = bounds(i);
- cap += Math.max(0, shares[i] - minS);
- }
- return cap;
- };
-
- const shrinkCapRightStack = () => {
- let cap = 0;
- for (let i = R; i < n; i++) {
- const [minS] = bounds(i);
- cap += Math.max(0, shares[i] - minS);
- }
- return cap;
- };
-
- if (dShare < 0) {
- // Move LEFT: shrink LEFT stack, grow RIGHT
- const req = -dShare;
- const capShrinkLeft = shrinkCapLeftStack();
- const capGrowR = growCap(R);
- const applied = Math.min(req, capShrinkLeft, capGrowR);
- if (applied <= 0) return;
-
- const newShares = shares.slice();
- // shrink from the handle outward: L, L-1, L-2, ...
- shrinkStack(newShares, L, -1, applied);
- newShares[R] += applied;
-
- for (let i = 0; i < n; i++) {
- panelData[ids[i]].share = newShares[i];
- }
- } else {
- // dShare > 0: Move RIGHT: shrink RIGHT stack, grow LEFT
- const req = dShare;
- const capShrinkRight = shrinkCapRightStack();
- const capGrowL = growCap(L);
- const applied = Math.min(req, capShrinkRight, capGrowL);
- if (applied <= 0) return;
-
- const newShares = shares.slice();
- shrinkStack(newShares, R, 1, applied);
- newShares[L] += applied;
-
- for (let i = 0; i < n; i++) {
- panelData[ids[i]].share = newShares[i];
- }
- }
+ const next = moveHandleShares({
+ panels: panelsInOrder(),
+ shares: ids.map((id) => rendered.get(id) ?? panelData[id]!.share),
+ index: ndx,
+ deltaPx,
+ usable: Math.max(0, params.size() - Math.max(0, n - 1) * params.gutter()),
+ });
+ if (!next) return;
- const sum = sumArray(ids.map((id) => panelData[id]?.share ?? 0));
- if (Math.abs(sum - 1) > EPSILON && sum > 0 && Number.isFinite(sum)) {
- for (const id of ids) {
- panelData[id].share = panelData[id].share / sum;
- }
+ for (let i = 0; i < n; i++) {
+ panelData[ids[i]].share = next[i];
}
setDirty('manual');
diff --git a/apps/web/src/lib/core/hotkey/tokens.ts b/apps/web/src/lib/core/hotkey/tokens.ts
index 3e7c6f4fd2..accfb9a957 100644
--- a/apps/web/src/lib/core/hotkey/tokens.ts
+++ b/apps/web/src/lib/core/hotkey/tokens.ts
@@ -107,6 +107,7 @@ export const TOKENS = {
searchMenu: 'global.searchMenu',
toggleSettings: 'global.toggleSettings',
createNewSplit: 'global.createNewSplit',
+ createNewSplitBelow: 'global.createNewSplitBelow',
inviteTeam: 'global.inviteTeam',
undo: 'global.undo',
redo: 'global.redo',
diff --git a/apps/web/src/lib/i18n/locales/en/commands.ts b/apps/web/src/lib/i18n/locales/en/commands.ts
index e3d374aab9..de9fb846a1 100644
--- a/apps/web/src/lib/i18n/locales/en/commands.ts
+++ b/apps/web/src/lib/i18n/locales/en/commands.ts
@@ -6,6 +6,7 @@ export default {
openCategory: 'Open category',
openCategoryNamed: 'Open {{category}}',
createNewSplit: 'Create new split',
+ createNewSplitBelow: 'Create new split below',
toggleSettings: 'Toggle settings',
account: 'Account',
logout: 'Logout',
diff --git a/apps/web/src/lib/i18n/locales/en/split-menu.ts b/apps/web/src/lib/i18n/locales/en/split-menu.ts
index f79ccdd19e..225cef35ad 100644
--- a/apps/web/src/lib/i18n/locales/en/split-menu.ts
+++ b/apps/web/src/lib/i18n/locales/en/split-menu.ts
@@ -2,6 +2,8 @@ export default {
// Split header context menu.
newSplitLeft: 'New split left',
newSplitRight: 'New split right',
+ newSplitAbove: 'New split above',
+ newSplitBelow: 'New split below',
duplicateSplit: 'Duplicate split',
swapSplitLeft: 'Swap split left',
swapSplitRight: 'Swap split right',
@@ -18,6 +20,8 @@ export default {
goBack: 'Go Back',
goForward: 'Go Forward',
createNewSplit: 'Create new split',
+ createNewSplitBelow: 'Create new split below',
+ newSplit: 'New split',
close: 'Close',
previousItem: 'Previous item',
nextItem: 'Next item',
diff --git a/apps/web/src/lib/split-router/README.md b/apps/web/src/lib/split-router/README.md
index 31677c5382..dbc908783b 100644
--- a/apps/web/src/lib/split-router/README.md
+++ b/apps/web/src/lib/split-router/README.md
@@ -24,6 +24,22 @@ 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.
+## Layout tree
+
+`panes.layout()` is how the open panes tile: a tree of `row` (side by side)
+and `column` (stacked) splits with each child's share. Its panes in
+depth-first order are `panes()`, so positional `sN.*` search keys and history
+state are unchanged. A new pane either splits an open pane (placement
+`{ split, side }`) or becomes a column at `insertAt`. Removing a pane collapses
+its split; moving panes keeps the tiles and refills them in the new order.
+
+The URL records the tree only when some panes are stacked, in the `layout`
+search key: `p` is a pane and `r<n>`/`c<n>` a split of the next `n` shapes, so a
+pane beside two stacked panes is `/a/~/b/~/c?layout=r2pc2pp`. Without the key,
+or when it doesn't fit the URL's panes, the panes sit in one row. Sizes stay
+out of the URL; `resizeLayout` changes them, `layoutSnapshot` captures them,
+and `restoreLayout` brings them back.
+
## Parked layouts
`layoutSnapshot` and `restoreLayout` capture and bring back whole layouts.
@@ -32,7 +48,10 @@ To keep a layout's views mounted while another shows, park it instead:
`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.
+forgets parked panes. URL navigation never reuses a parked pane id. Parked
+panes keep their tiles: `layoutOf` says how a pane tiles, open or parked;
+`showLayout` brings a group back in its tiles; and snapshots of parked panes
+and `layoutFromHref` carry them.
## Outlets
diff --git a/apps/web/src/lib/split-router/index.ts b/apps/web/src/lib/split-router/index.ts
index 3ad56e98c2..0c503a1c49 100644
--- a/apps/web/src/lib/split-router/index.ts
+++ b/apps/web/src/lib/split-router/index.ts
@@ -13,6 +13,12 @@ export type {
HistoryAdapter,
InterceptHandler,
} from './history/types';
+export type {
+ PaneLayout,
+ SplitAxis,
+ SplitPath,
+ SplitSide,
+} from './panes/layout-tree';
export { createMemoryPaneStore } from './panes/memory-store';
export type {
OpenIntent,
diff --git a/apps/web/src/lib/split-router/panes/layout-tree.ts b/apps/web/src/lib/split-router/panes/layout-tree.ts
new file mode 100644
index 0000000000..01e6e8adf6
--- /dev/null
+++ b/apps/web/src/lib/split-router/panes/layout-tree.ts
@@ -0,0 +1,363 @@
+import type { PaneId } from './types';
+
+/** Children side by side (`row`) or stacked (`column`). */
+export type SplitAxis = 'row' | 'column';
+
+/** Where a new pane goes beside the pane it splits. */
+export type SplitSide = 'left' | 'right' | 'above' | 'below';
+
+/**
+ * How the open panes tile. A split has at least two children, never a child
+ * split along its own axis, and shares that sum to 1. Its panes in depth-first
+ * order are the open panes in order.
+ */
+export type PaneLayout =
+ | { readonly type: 'pane'; readonly pane: PaneId }
+ | {
+ readonly type: 'split';
+ readonly axis: SplitAxis;
+ readonly children: readonly PaneLayout[];
+ /** Each child's fraction of the split's length along its axis. */
+ readonly shares: readonly number[];
+ };
+
+/** A layout's structure without its panes or sizes, as a URL records it. */
+export type LayoutShape =
+ | 'pane'
+ | { readonly axis: SplitAxis; readonly children: readonly LayoutShape[] };
+
+/** Child indexes from the root down to a split. */
+export type SplitPath = readonly number[];
+
+type Part = { node: PaneLayout; share: number };
+
+const paneNode = (pane: PaneId): PaneLayout => ({ type: 'pane', pane });
+
+function partsOf(layout: PaneLayout & { type: 'split' }): Part[] {
+ return layout.children.map((node, index) => ({
+ node,
+ share: layout.shares[index]!,
+ }));
+}
+
+/**
+ * The split of `parts` along `axis`, merging child splits along the same axis
+ * into it and collapsing to the only child when one is left.
+ */
+function joined(
+ axis: SplitAxis,
+ parts: readonly Part[]
+): PaneLayout | undefined {
+ const flat = parts.flatMap(({ node, share }): Part[] => {
+ if (node.type === 'split' && node.axis === axis) {
+ return partsOf(node).map((child) => ({
+ node: child.node,
+ share: share * child.share,
+ }));
+ }
+
+ return [{ node, share }];
+ });
+
+ if (flat.length === 0) return;
+ if (flat.length === 1) return flat[0]!.node;
+
+ const total = flat.reduce((sum, part) => sum + part.share, 0);
+ const valid = total > 0 && Number.isFinite(total);
+
+ return {
+ type: 'split',
+ axis,
+ children: flat.map((part) => part.node),
+ shares: flat.map((part) => (valid ? part.share / total : 1 / flat.length)),
+ };
+}
+
+export function paneIds(layout: PaneLayout | undefined): PaneId[] {
+ if (!layout) return [];
+ if (layout.type === 'pane') return [layout.pane];
+
+ return layout.children.flatMap(paneIds);
+}
+
+/** `panes` side by side in equal shares: the layout of a URL without one. */
+export function rowLayout(panes: readonly PaneId[]): PaneLayout | undefined {
+ return joined(
+ 'row',
+ panes.map((pane) => ({ node: paneNode(pane), share: 1 }))
+ );
+}
+
+const axisOf = (side: SplitSide): SplitAxis =>
+ side === 'left' || side === 'right' ? 'row' : 'column';
+
+/** `layout` with `pane` replaced by what `replace` returns, normalized. */
+function replacePane(
+ layout: PaneLayout,
+ pane: PaneId,
+ replace: (node: PaneLayout) => PaneLayout | undefined
+): PaneLayout | undefined {
+ if (layout.type === 'pane') {
+ return layout.pane === pane ? replace(layout) : layout;
+ }
+
+ const parts = partsOf(layout).flatMap((part): Part[] => {
+ const node = replacePane(part.node, pane, replace);
+
+ return node ? [{ node, share: part.share }] : [];
+ });
+
+ return joined(layout.axis, parts);
+}
+
+/**
+ * Puts `pane` on `side` of `target`. Within a split along that axis it joins
+ * as a sibling with an equal share, the others scaling down to make room;
+ * otherwise `target` becomes a split of the two, halved.
+ */
+export function splitPane(
+ layout: PaneLayout,
+ target: PaneId,
+ pane: PaneId,
+ side: SplitSide
+): PaneLayout {
+ const axis = axisOf(side);
+ const before = side === 'left' || side === 'above';
+ const added = paneNode(pane);
+
+ const place = (node: PaneLayout): PaneLayout => {
+ if (node.type === 'pane') {
+ if (node.pane !== target) return node;
+
+ const children = before ? [added, node] : [node, added];
+
+ return { type: 'split', axis, children, shares: [0.5, 0.5] };
+ }
+
+ const at = node.children.findIndex(
+ (child) => child.type === 'pane' && child.pane === target
+ );
+ if (at < 0 || node.axis !== axis) {
+ return { ...node, children: node.children.map(place) };
+ }
+
+ const incoming = 1 / (node.children.length + 1);
+ const parts = partsOf(node).map((part) => ({
+ node: part.node,
+ share: part.share * (1 - incoming),
+ }));
+ parts.splice(before ? at : at + 1, 0, { node: added, share: incoming });
+
+ return joined(axis, parts)!;
+ };
+
+ return place(layout);
+}
+
+/**
+ * Adds `pane` as a full-height column after the column holding `after`, or
+ * first without one. The others scale down to make its equal share of room.
+ */
+export function insertColumn(
+ layout: PaneLayout | undefined,
+ pane: PaneId,
+ after: PaneId | undefined
+): PaneLayout {
+ if (!layout) return paneNode(pane);
+
+ const columns =
+ layout.type === 'split' && layout.axis === 'row'
+ ? partsOf(layout)
+ : [{ node: layout, share: 1 }];
+ const at =
+ columns.findIndex(
+ ({ node }) => after !== undefined && paneIds(node).includes(after)
+ ) + 1;
+
+ const incoming = 1 / (columns.length + 1);
+ const parts = columns.map((part) => ({
+ node: part.node,
+ share: part.share * (1 - incoming),
+ }));
+ parts.splice(at, 0, { node: paneNode(pane), share: incoming });
+
+ return joined('row', parts)!;
+}
+
+/** `layout` without `pane`; its space goes to the rest of its split. */
+export function removePane(
+ layout: PaneLayout | undefined,
+ pane: PaneId
+): PaneLayout | undefined {
+ if (!layout) return;
+
+ return replacePane(layout, pane, () => undefined);
+}
+
+/** `layout` without the panes `drop` picks, collapsing splits as `removePane` does. */
+export function withoutPanes(
+ layout: PaneLayout | undefined,
+ drop: (pane: PaneId) => boolean
+): PaneLayout | undefined {
+ return paneIds(layout)
+ .filter(drop)
+ .reduce<PaneLayout | undefined>(
+ (tiles, pane) => removePane(tiles, pane),
+ layout
+ );
+}
+
+/**
+ * How `panes` tile within `layout` once its other panes are gone; undefined
+ * unless `layout` holds every one of them, in this order.
+ */
+export function tilesFor(
+ layout: PaneLayout | undefined,
+ panes: readonly PaneId[]
+): PaneLayout | undefined {
+ const tiles = withoutPanes(layout, (pane) => !panes.includes(pane));
+ const order = paneIds(tiles);
+ const inOrder =
+ order.length === panes.length &&
+ order.every((pane, index) => pane === panes[index]);
+
+ return inOrder ? tiles : undefined;
+}
+
+/** The same tiles and sizes showing `panes`, in order, instead. */
+export function reorderPanes(
+ layout: PaneLayout | undefined,
+ panes: readonly PaneId[]
+): PaneLayout | undefined {
+ if (!layout) return;
+
+ let next = 0;
+ const fill = (node: PaneLayout): PaneLayout => {
+ if (node.type === 'pane') return paneNode(panes[next++]!);
+
+ return { ...node, children: node.children.map(fill) };
+ };
+
+ return fill(layout);
+}
+
+export function splitAt(
+ layout: PaneLayout | undefined,
+ path: SplitPath
+): (PaneLayout & { type: 'split' }) | undefined {
+ let node = layout;
+ for (const index of path) {
+ if (node?.type !== 'split') return;
+ node = node.children[index];
+ }
+
+ return node?.type === 'split' ? node : undefined;
+}
+
+/** `layout` with the split at `path` divided by `shares`. */
+export function resizeSplit(
+ layout: PaneLayout | undefined,
+ path: SplitPath,
+ shares: readonly number[]
+): PaneLayout | undefined {
+ if (!layout) return;
+
+ const resize = (node: PaneLayout, depth: number): PaneLayout => {
+ if (node.type !== 'split') return node;
+ if (depth === path.length) {
+ if (shares.length !== node.children.length) return node;
+
+ return { ...node, shares };
+ }
+
+ const index = path[depth]!;
+ const child = node.children[index];
+ if (!child) return node;
+
+ return {
+ ...node,
+ children: node.children.with(index, resize(child, depth + 1)),
+ };
+ };
+
+ return resize(layout, 0);
+}
+
+/** `layout` with every split divided equally. */
+export function resetShares(
+ layout: PaneLayout | undefined
+): PaneLayout | undefined {
+ if (layout?.type !== 'split') return layout;
+
+ return {
+ ...layout,
+ children: layout.children.map((child) => resetShares(child)!),
+ shares: layout.children.map(() => 1 / layout.children.length),
+ };
+}
+
+/** `next`, keeping the sizes of `current`'s splits wherever the two match. */
+export function withSharesFrom(
+ next: PaneLayout | undefined,
+ current: PaneLayout | undefined
+): PaneLayout | undefined {
+ if (next?.type !== 'split' || current?.type !== 'split') return next;
+
+ const sameSplit =
+ next.axis === current.axis &&
+ next.children.length === current.children.length;
+ if (!sameSplit) return next;
+
+ return {
+ ...next,
+ children: next.children.map(
+ (child, index) => withSharesFrom(child, current.children[index])!
+ ),
+ shares: current.shares,
+ };
+}
+
+export function layoutShape(layout: PaneLayout): LayoutShape {
+ if (layout.type === 'pane') return 'pane';
+
+ return { axis: layout.axis, children: layout.children.map(layoutShape) };
+}
+
+function shapePaneCount(shape: LayoutShape): number {
+ if (shape === 'pane') return 1;
+
+ return shape.children.reduce(
+ (count, child) => count + shapePaneCount(child),
+ 0
+ );
+}
+
+/** `shape` showing `panes` in equal shares; undefined unless the counts match. */
+export function fillShape(
+ shape: LayoutShape,
+ panes: readonly PaneId[]
+): PaneLayout | undefined {
+ if (shapePaneCount(shape) !== panes.length) return;
+
+ let next = 0;
+ const fill = (node: LayoutShape): PaneLayout => {
+ if (node === 'pane') return paneNode(panes[next++]!);
+
+ return {
+ type: 'split',
+ axis: node.axis,
+ children: node.children.map(fill),
+ shares: node.children.map(() => 1 / node.children.length),
+ };
+ };
+
+ return fill(shape);
+}
+
+/** Whether any panes are stacked, which a plain list of panes can't record. */
+export function hasColumns(shape: LayoutShape): boolean {
+ if (shape === 'pane') return false;
+ if (shape.axis === 'column') return true;
+
+ return shape.children.some(hasColumns);
+}
diff --git a/apps/web/src/lib/split-router/panes/panes.ts b/apps/web/src/lib/split-router/panes/panes.ts
index 2610083476..544e261116 100644
--- a/apps/web/src/lib/split-router/panes/panes.ts
+++ b/apps/web/src/lib/split-router/panes/panes.ts
@@ -12,6 +12,24 @@ import {
type PanesDiff,
} from './diff';
import { currentEntry } from './history';
+import {
+ fillShape,
+ insertColumn,
+ type LayoutShape,
+ type PaneLayout,
+ paneIds,
+ removePane,
+ reorderPanes,
+ resetShares,
+ resizeSplit,
+ rowLayout,
+ type SplitPath,
+ type SplitSide,
+ splitPane,
+ tilesFor,
+ withoutPanes,
+ withSharesFrom,
+} from './layout-tree';
import type {
CloseAction,
OpenIntent,
@@ -79,6 +97,18 @@ function historyChangeFor<E extends PaneEntry>(
return { type: 'go', index, entry };
}
+/**
+ * How panes landing together tile, in order: a URL's `shape`, keeping the
+ * current sizes where it matches, or a captured `layout` with its own sizes.
+ */
+export type Arrangement = { shape?: LayoutShape } | { layout: PaneLayout };
+
+/** Where `insert` puts a new pane. */
+export type NewPanePlacement = {
+ insertAt: number;
+ split?: { pane: PaneId; side: SplitSide };
+};
+
export type PanesOptions<E extends PaneEntry, D> = {
store: PaneStore<E>;
policy: PanePolicy<E, D>;
@@ -99,11 +129,18 @@ export function createPanes<E extends PaneEntry, D>(
const [ids, setIds] = createSignal<readonly PaneId[]>([], {
equals: sameIds,
});
+ // The open panes are this layout's panes, in order; set both together.
+ const [layout, setLayout] = createSignal<PaneLayout | undefined>();
// 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,
});
+ // How parked panes tile, one layout per group parked together, so a group
+ // shows again as it was.
+ const [parkedLayouts, setParkedLayouts] = createSignal<readonly PaneLayout[]>(
+ []
+ );
const [arrivals, setArrivals] = createStore<
Record<string, PaneArrival | undefined>
>({});
@@ -116,13 +153,57 @@ export function createPanes<E extends PaneEntry, D>(
return currentEntry(snapshot);
};
- const arrange = (next: readonly PaneId[], changes: () => void) => {
+ /**
+ * Makes `next` the open layout once `changes` ran. Open panes it leaves out
+ * that still have a history are parked, keeping their tiles.
+ */
+ const arrange = (next: PaneLayout | undefined, changes: () => void) => {
batch(() => {
+ const before = untrack(layout);
changes();
- setIds(next);
+
+ const open = paneIds(next);
+ const kept = untrack(retained);
+ const parks = (pane: PaneId) =>
+ !open.includes(pane) && kept.includes(pane);
+ const parked = withoutPanes(before, (pane) => !parks(pane));
+ setParkedLayouts((list) => {
+ const rest = list.flatMap(
+ (tiles) => withoutPanes(tiles, (pane) => open.includes(pane)) ?? []
+ );
+
+ return parked ? [...rest, parked] : rest;
+ });
+ setLayout(next);
+ setIds(open);
});
};
+ /** The layout holding `pane`: the open one, or the one it was parked in. */
+ const layoutOf = (pane: PaneId): PaneLayout | undefined =>
+ [layout(), ...parkedLayouts()].find((tiles) =>
+ paneIds(tiles).includes(pane)
+ );
+
+ /** How the panes landing in a diff tile; in a row when the arrangement doesn't fit them. */
+ const landedLayout = (
+ landed: readonly PaneId[],
+ arrangement: Arrangement
+ ): PaneLayout | undefined => {
+ if ('layout' in arrangement) {
+ const fits = paneIds(arrangement.layout).length === landed.length;
+
+ return fits
+ ? reorderPanes(arrangement.layout, landed)
+ : rowLayout(landed);
+ }
+
+ const { shape } = arrangement;
+ const shaped = shape ? fillShape(shape, landed) : undefined;
+
+ return withSharesFrom(shaped ?? rowLayout(landed), untrack(layout));
+ };
+
const addPane = (pane: PaneId, entry: E) => {
store.create(pane, entry);
setArrivals(pane, 'fresh');
@@ -133,6 +214,9 @@ export function createPanes<E extends PaneEntry, D>(
store.remove(pane);
setArrivals(pane, undefined);
setRetained((list) => list.filter((id) => id !== pane));
+ setParkedLayouts((list) =>
+ list.flatMap((tiles) => removePane(tiles, pane) ?? [])
+ );
options.onRemove?.(pane);
};
@@ -159,6 +243,8 @@ export function createPanes<E extends PaneEntry, D>(
return {
ids,
+ layout,
+ layoutOf,
retained,
read: (pane: PaneId) => store.read(pane),
current,
@@ -173,34 +259,50 @@ export function createPanes<E extends PaneEntry, D>(
});
},
- /** Adds a pane at `insertAt` as chosen against `decided`, the panes at the time. */
+ /**
+ * Adds a pane where `placement` says: splitting a pane that is still
+ * open, or else as a column at `insertAt` as chosen against `decided`,
+ * the panes at the time.
+ */
insert(
pane: PaneId,
entry: E,
- insertAt: number,
+ placement: NewPanePlacement,
decided: readonly PaneId[] = untrack(ids)
) {
- const next = [...untrack(ids)];
- const at = insertionIndex(decided, insertAt, next);
- next.splice(at, 0, pane);
+ const current = untrack(layout);
+ const open = untrack(ids);
+ const { split } = placement;
+
+ if (current && split && open.includes(split.pane)) {
+ const next = splitPane(current, split.pane, pane, split.side);
+ arrange(next, () => addPane(pane, entry));
+ return;
+ }
+
+ const at = insertionIndex(decided, placement.insertAt, open);
+ const next = insertColumn(current, pane, open[at - 1]);
arrange(next, () => addPane(pane, entry));
},
remove(pane: PaneId) {
- const next = untrack(ids).filter((id) => id !== pane);
+ const next = removePane(untrack(layout), pane);
arrange(next, () => forget(pane));
},
/**
- * Makes `next`, retained panes, the open ones. Open panes not in `next`
- * stay retained (parked) with their histories until `discard`.
+ * Makes `next`, retained panes, the open ones, in the tiles they last
+ * had together (side by side when they never tiled together). Open panes
+ * not in `next` stay retained (parked) with their histories and tiles
+ * 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);
+ const together = untrack(() => tilesFor(layoutOf(next[0]!), next));
+ arrange(together ?? rowLayout(next), () => {});
},
/** Forgets a parked pane; open panes are removed through `remove`. */
@@ -211,7 +313,11 @@ export function createPanes<E extends PaneEntry, D>(
forget(pane);
},
- /** False when `pane` isn't open or already sits at `to`. */
+ /**
+ * Moves `pane` to `to` in the order; the tiles keep their sizes and show
+ * the panes in their new order. False when `pane` isn't open or already
+ * sits at `to`.
+ */
move(pane: PaneId, to: number): boolean {
const before = untrack(ids);
if (!before.includes(pane)) return false;
@@ -221,11 +327,21 @@ export function createPanes<E extends PaneEntry, D>(
next.splice(at, 0, pane);
if (sameIds(before, next)) return false;
- setIds(next);
+ arrange(reorderPanes(untrack(layout), next), () => {});
return true;
},
+ /** Divides the split at `path` by `shares`; the URL doesn't record sizes. */
+ resize(path: SplitPath, shares: readonly number[]) {
+ setLayout(resizeSplit(untrack(layout), path, shares));
+ },
+
+ /** Divides every split equally. */
+ resetShares() {
+ setLayout(resetShares(untrack(layout)));
+ },
+
/** How `incoming` lines up with the open panes. */
diff(
incoming: readonly IncomingPane<E>[],
@@ -241,9 +357,17 @@ export function createPanes<E extends PaneEntry, D>(
return diffPanes(live, incoming, { ...diffOptions, createPaneId });
},
- /** Applies `diff`; `entries` are what its changed panes show, in order. */
- applyDiff(diff: PanesDiff<E>, entries: readonly E[]) {
- const next = diff.panes.map((item) => item.pane);
+ /**
+ * Applies `diff`; `entries` are what its changed panes show, in order,
+ * and `arrangement` is how its panes tile.
+ */
+ applyDiff(
+ diff: PanesDiff<E>,
+ entries: readonly E[],
+ arrangement: Arrangement = {}
+ ) {
+ const landed = diff.panes.map((item) => item.pane);
+ const next = landedLayout(landed, arrangement);
arrange(next, () => {
for (const pane of diff.removed) forget(pane);
diff --git a/apps/web/src/lib/split-router/panes/types.ts b/apps/web/src/lib/split-router/panes/types.ts
index be2d7b3f74..e20d4cc4dd 100644
--- a/apps/web/src/lib/split-router/panes/types.ts
+++ b/apps/web/src/lib/split-router/panes/types.ts
@@ -1,3 +1,5 @@
+import type { SplitSide } from './layout-tree';
+
/** One independent navigation history; stable for the pane's lifetime. */
export type PaneId = string & { readonly PaneId: unique symbol };
@@ -39,8 +41,14 @@ export interface PaneStore<E extends PaneEntry = PaneEntry> {
apply(pane: PaneId, change: PaneChange<E>): void;
}
-/** Where a destination lands: an existing pane, or a new pane at an index. */
-export type Placement = { pane: PaneId } | { insertAt: number };
+/**
+ * Where a destination lands: an existing pane, a new pane at an index, or a
+ * new pane splitting `split` with it on `side`.
+ */
+export type Placement =
+ | { pane: PaneId }
+ | { insertAt: number }
+ | { split: PaneId; side: SplitSide };
/** The caller's hints for placing a new pane. Policies extend this interface through declaration merging. */
export interface OpenIntent {
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 346204b79e..a1136ce7ce 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,13 @@ export function createSplitRouter(options: SplitRouterOptions) {
claims: claims.registry,
ready,
panes: panes.ids,
+ /** How the panes tile; its panes in order are `panes()`. */
+ layout: panes.layout,
+ /** How a pane tiles, open or parked: the layout it is (or was) shown in. */
+ layoutOf: panes.layoutOf,
+ /** Sizes the split at a path; sizes stay out of the URL and history. */
+ resizeLayout: panes.resize,
+ resetLayoutSizes: panes.resetShares,
/** Open and parked panes; see `openLayout` and `showLayout`. */
retainedPanes: panes.retained,
navigate: urlNavigation.navigate,
diff --git a/apps/web/src/lib/split-router/router/layout.ts b/apps/web/src/lib/split-router/router/layout.ts
index 95a0509ba7..fb53e569e4 100644
--- a/apps/web/src/lib/split-router/router/layout.ts
+++ b/apps/web/src/lib/split-router/router/layout.ts
@@ -1,5 +1,12 @@
import { batch, untrack } from 'solid-js';
import { type ChangedPane, changedPanes, type PanesDiff } from '../panes/diff';
+import {
+ fillShape,
+ layoutShape,
+ type PaneLayout,
+ rowLayout,
+ tilesFor,
+} from '../panes/layout-tree';
import type { PaneId } from '../panes/types';
import {
decodePanes,
@@ -28,9 +35,11 @@ export type LayoutPane = {
index: number;
};
-/** A whole layout: every open pane with its history, in order. */
+/** A whole layout: every open pane with its history, in order, and how they tile. */
export type LayoutSnapshot = {
panes: readonly LayoutPane[];
+ /** The tiles and their sizes; absent, the panes sit side by side. */
+ layout?: PaneLayout;
};
export type RestoreLayoutOptions = {
@@ -69,15 +78,31 @@ export function createLayout(options: {
}) {
const { routes, panes, url, runner } = options;
- /** 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) => {
+ /**
+ * The open (or the given retained) panes with their histories and tiles;
+ * entries are shared, not copied.
+ */
+ const snapshot = (only?: readonly PaneId[]): LayoutSnapshot => {
+ const captured = (only ?? untrack(panes.ids)).flatMap((pane) => {
const stored = untrack(() => panes.read(pane));
if (!stored) return [];
return [{ pane, entries: stored.entries, index: stored.index }];
- }),
- });
+ });
+ const [first] = captured;
+ if (!first) return { panes: captured };
+
+ const layout = tilesFor(
+ untrack(() => panes.layoutOf(first.pane)),
+ captured.map(({ pane }) => pane)
+ );
+
+ return layout ? { panes: captured, layout } : { panes: captured };
+ };
+
+ /** The tiles `layout` shows its panes in, in order. */
+ const tilesOf = (layout: LayoutSnapshot): PaneLayout | undefined =>
+ layout.layout ?? rowLayout(layout.panes.map(({ pane }) => pane));
/**
* Makes the captured layout the open panes in one guarded navigation: leave
@@ -109,8 +134,10 @@ export function createLayout(options: {
mode: 'push' | 'replace'
): Navigation => {
const apply = (entries: readonly Entry[]): NavigationResult => {
+ const tiles = tilesOf(layout);
+
batch(() => {
- panes.applyDiff(diff, entries);
+ panes.applyDiff(diff, entries, tiles ? { layout: tiles } : {});
// Put each captured history back; the shown entry may have been
// amended by middleware, so the live one replaces it at the cursor.
@@ -215,14 +242,19 @@ export function createLayout(options: {
/** 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,
- })),
- };
+ const captured = decoded.panes.map(({ entry }) => ({
+ pane: panes.createPaneId(),
+ entries: [entry],
+ index: 0,
+ }));
+ const layout =
+ decoded.shape &&
+ fillShape(
+ decoded.shape,
+ captured.map(({ pane }) => pane)
+ );
+
+ return layout ? { panes: captured, layout } : { panes: captured };
};
/** The mount-relative URL a captured layout shows, for saving or sharing. */
@@ -232,7 +264,12 @@ export function createLayout(options: {
entry: shownEntry(pane),
}));
- return formatLocation(encodePanes(routes, shown, untrack(url.lastKnown)));
+ const tiles = tilesOf(layout);
+ const encoded = encodePanes(routes, shown, untrack(url.lastKnown), {
+ layout: tiles && layoutShape(tiles),
+ });
+
+ return formatLocation(encoded);
};
return { snapshot, restore, open, show, discard, fromHref, href };
diff --git a/apps/web/src/lib/split-router/router/pane-list.ts b/apps/web/src/lib/split-router/router/pane-list.ts
index 60d49f0cfa..a7f4c7a451 100644
--- a/apps/web/src/lib/split-router/router/pane-list.ts
+++ b/apps/web/src/lib/split-router/router/pane-list.ts
@@ -1,5 +1,6 @@
import { fireAndForget } from '@core/util/fireAndForget';
import { match } from 'ts-pattern';
+import type { NewPanePlacement } from '../panes/panes';
import type { OpenTarget, Placement } from '../panes/types';
import { canonicalRoute, type SplitRoutesManifest } from '../routes/manifest';
import type {
@@ -123,10 +124,10 @@ export function createPaneList(options: {
*/
function openNew(
location: SplitLocation,
- placement: { insertAt: number; besides?: PaneId; source?: PaneId },
+ placement: NewPanePlacement & { besides?: PaneId; source?: PaneId },
navigateOptions: SplitNavigateOptions
): MaybePromise<NavigationResult> {
- const { insertAt, besides, source } = placement;
+ const { besides, source } = placement;
const pane = panes.createPaneId();
const entry = createEntry(routes, location, undefined, navigateOptions);
const decided = panes.ids();
@@ -139,7 +140,7 @@ export function createPaneList(options: {
const apply = ([landed]: readonly Entry[]) =>
claims.applyUnlessHeld(check, landed!, () => {
- panes.insert(pane, landed!, insertAt, decided);
+ panes.insert(pane, landed!, placement, decided);
url.write('push');
return committed(pane);
@@ -235,12 +236,19 @@ export function createPaneList(options: {
return openIn(placement.pane, location, navigateOptions);
}
- const { insertAt } = placement;
+ // A split whose pane has closed by the time it lands opens at the end.
+ const newPane: NewPanePlacement =
+ 'split' in placement
+ ? {
+ insertAt: panes.ids().length,
+ split: { pane: placement.split, side: placement.side },
+ }
+ : { insertAt: placement.insertAt };
return openNew(
location,
{
- insertAt,
+ ...newPane,
besides: holder,
source: 'pane' in target ? undefined : target.source,
},
diff --git a/apps/web/src/lib/split-router/router/url-navigation.ts b/apps/web/src/lib/split-router/router/url-navigation.ts
index dd47ed2c97..3fabd07438 100644
--- a/apps/web/src/lib/split-router/router/url-navigation.ts
+++ b/apps/web/src/lib/split-router/router/url-navigation.ts
@@ -84,7 +84,7 @@ export function createUrlNavigation(options: {
const diff = panes.diff(decoded.panes, { same: sameVisit, adopt });
const apply = (entries: readonly Entry[]): NavigationResult => {
- panes.applyDiff(diff, entries);
+ panes.applyDiff(diff, entries, { shape: decoded.shape });
url.write(mode, { landed: location });
options.markReady();
diff --git a/apps/web/src/lib/split-router/router/url.ts b/apps/web/src/lib/split-router/router/url.ts
index 2f93544b39..7da8beed86 100644
--- a/apps/web/src/lib/split-router/router/url.ts
+++ b/apps/web/src/lib/split-router/router/url.ts
@@ -1,5 +1,6 @@
import { untrack } from 'solid-js';
import type { HistoryAdapter } from '../history/types';
+import { layoutShape } from '../panes/layout-tree';
import { encodePanes, sameExternalLocation } from '../routes/codec';
import type { SplitRoutesManifest } from '../routes/manifest';
import type { ExternalLocation, PaneId, WriteMode } from '../routes/types';
@@ -40,7 +41,11 @@ export function createUrl(options: {
const { landed } = writeOptions;
const basis = landed ?? lastKnown;
const keepHash = landed !== undefined;
- const next = encodePanes(routes, shown, basis, { keepHash });
+ const layout = untrack(panes.layout);
+ const next = encodePanes(routes, shown, basis, {
+ keepHash,
+ layout: layout && layoutShape(layout),
+ });
if (sameExternalLocation(next, lastKnown)) return;
// A write that throws never reached the URL, so it isn't known yet.
diff --git a/apps/web/src/lib/split-router/routes/codec.ts b/apps/web/src/lib/split-router/routes/codec.ts
index 55f9a688e1..a37d9667b3 100644
--- a/apps/web/src/lib/split-router/routes/codec.ts
+++ b/apps/web/src/lib/split-router/routes/codec.ts
@@ -1,5 +1,11 @@
import deepEqual from 'fast-deep-equal';
+import { hasColumns, type LayoutShape } from '../panes/layout-tree';
import { createId, isRecord } from '../utils';
+import {
+ formatLayoutShape,
+ LAYOUT_SEARCH_KEY,
+ parseLayoutShape,
+} from './layout-param';
import {
decodeFirstPane,
decodePane,
@@ -29,7 +35,8 @@ import type {
} from './types';
type DecodedPane = { paneId?: PaneId; entry: Entry };
-type DecodedPanes = { panes: readonly DecodedPane[] };
+/** `shape` is how the URL tiles its panes, when it says. */
+type DecodedPanes = { panes: readonly DecodedPane[]; shape?: LayoutShape };
type EncodedPane = { paneId: PaneId; entry: Entry };
const LOCATION_BASE = 'http://split-router.invalid';
@@ -181,6 +188,8 @@ export function decodePanes(
const search = parsePaneSearch(location.search);
const stored = storedPanes(location.state, parts.length);
+ const layout = new URLSearchParams(location.search).get(LAYOUT_SEARCH_KEY);
+ const shape = layout === null ? undefined : parseLayoutShape(layout);
const panes = decoded.map((route, position): DecodedPane => {
const pane = stored?.[position];
@@ -198,7 +207,7 @@ export function decodePanes(
return pane ? { paneId: pane.pane, entry } : { entry };
});
- return { panes };
+ return shape ? { panes, shape } : { panes };
}
export function formatPanePath(
@@ -230,14 +239,15 @@ function panesPath(
function panesSearch(
routes: SplitRoutesManifest,
entries: readonly Entry[],
- previousSearch: string
+ previousSearch: string,
+ layout: LayoutShape | undefined
): string {
const owned = externalSearchKeys(routes, entries);
const keepsAll = keepsAllExternalSearch(routes, entries);
const query = new URLSearchParams();
for (const [key, value] of new URLSearchParams(previousSearch)) {
- const external = !isSplitSearchKey(key);
+ const external = !isSplitSearchKey(key) && key !== LAYOUT_SEARCH_KEY;
const keep = external && (keepsAll || owned.includes(key));
if (keep) query.append(key, value);
}
@@ -246,6 +256,9 @@ function panesSearch(
filterRouteSearch(routes, entry.location.route, entry.location.search)
);
replacePaneSearchParams(query, paneSearch);
+ if (layout && hasColumns(layout)) {
+ query.set(LAYOUT_SEARCH_KEY, formatLayoutShape(layout));
+ }
query.sort();
const search = query.toString();
@@ -261,18 +274,19 @@ function historyPane({ paneId, entry }: EncodedPane): SplitHistoryPane {
}
/**
- * The URL for `panes`. The hash from `previous` survives when the path is
- * unchanged, or with `keepHash` when rewriting the URL a URL navigation landed on.
+ * The URL for `panes`, tiled as `layout` says. The hash from `previous`
+ * survives when the path is unchanged, or with `keepHash` when rewriting the
+ * URL a URL navigation landed on.
*/
export function encodePanes(
routes: SplitRoutesManifest,
panes: readonly EncodedPane[],
previous: Pick<ExternalLocation, 'path' | 'search' | 'hash'>,
- options: { keepHash?: boolean } = {}
+ options: { keepHash?: boolean; layout?: LayoutShape } = {}
): ExternalLocation {
const entries = panes.map(({ entry }) => entry);
const path = panesPath(routes, entries);
- const search = panesSearch(routes, entries, previous.search);
+ const search = panesSearch(routes, entries, previous.search, options.layout);
const samePath = normalizePath(path) === normalizePath(previous.path);
const keepHash = options.keepHash || samePath;
diff --git a/apps/web/src/lib/split-router/routes/layout-param.ts b/apps/web/src/lib/split-router/routes/layout-param.ts
new file mode 100644
index 0000000000..6f99b82854
--- /dev/null
+++ b/apps/web/src/lib/split-router/routes/layout-param.ts
@@ -0,0 +1,58 @@
+import type { LayoutShape } from '../panes/layout-tree';
+
+/** The search key holding how the panes tile, when they don't simply sit side by side. */
+export const LAYOUT_SEARCH_KEY = 'layout';
+
+/** Longer values are not layouts the router wrote; this also bounds parse depth. */
+const MAX_LAYOUT_LENGTH = 512;
+
+/**
+ * The shape in preorder: `p` is a pane, and `r<n>` or `c<n>` is a split of
+ * the next `n` shapes side by side or stacked. A pane beside a stack of two
+ * is `r2pc2pp`.
+ */
+export function formatLayoutShape(shape: LayoutShape): string {
+ if (shape === 'pane') return 'p';
+
+ const axis = shape.axis === 'row' ? 'r' : 'c';
+
+ return `${axis}${shape.children.length}${shape.children.map(formatLayoutShape).join('')}`;
+}
+
+/** The shape `value` records; undefined unless it is one the router could write. */
+export function parseLayoutShape(value: string): LayoutShape | undefined {
+ if (value.length > MAX_LAYOUT_LENGTH) return;
+
+ let position = 0;
+
+ const parse = (parentAxis?: 'row' | 'column'): LayoutShape | undefined => {
+ const token = value[position];
+ position += 1;
+ if (token === 'p') return 'pane';
+ if (token !== 'r' && token !== 'c') return;
+
+ const axis = token === 'r' ? 'row' : 'column';
+ if (axis === parentAxis) return;
+
+ const digits = /^[1-9]\d*/.exec(value.slice(position))?.[0];
+ if (!digits) return;
+ position += digits.length;
+
+ const count = Number(digits);
+ if (count < 2) return;
+
+ const children: LayoutShape[] = [];
+ for (let index = 0; index < count; index++) {
+ const child = parse(axis);
+ if (!child) return;
+ children.push(child);
+ }
+
+ return { axis, children };
+ };
+
+ const shape = parse();
+ if (position !== value.length) return;
+
+ return shape;
+}
diff --git a/apps/web/src/lib/split-router/tests/fixtures.ts b/apps/web/src/lib/split-router/tests/fixtures.ts
index b01ea402e3..c131792fde 100644
--- a/apps/web/src/lib/split-router/tests/fixtures.ts
+++ b/apps/web/src/lib/split-router/tests/fixtures.ts
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import type { SplitSide } from '../panes/layout-tree';
import type { SplitCloseAction, SplitPanePolicy } from '../router/types';
import { defineRoute, defineRoutes } from '../routes/define';
import type { PaneId, SplitLocation } from '../routes/types';
@@ -105,6 +106,8 @@ export function createTestPolicy(
maxPanes?: number;
pinned?: readonly PaneId[];
closeLast?: SplitCloseAction;
+ /** New panes split their source on this side. */
+ split?: SplitSide;
} = {}
) {
const activated: PaneId[] = [];
@@ -117,6 +120,8 @@ export function createTestPolicy(
const { source, panes, opening } = request;
const isFull = panes.length + opening >= (options.maxPanes ?? Infinity);
if (isFull) return { pane: source ?? panes.at(-1)! };
+ if (source && options.split)
+ return { split: source, side: options.split };
const insertAt = source ? panes.indexOf(source) + 1 : panes.length;
diff --git a/apps/web/src/lib/split-router/tests/layout-tree.test.ts b/apps/web/src/lib/split-router/tests/layout-tree.test.ts
new file mode 100644
index 0000000000..01179cc0b8
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/layout-tree.test.ts
@@ -0,0 +1,173 @@
+import { describe, expect, it } from 'vitest';
+import {
+ fillShape,
+ insertColumn,
+ layoutShape,
+ type PaneLayout,
+ paneIds,
+ removePane,
+ reorderPanes,
+ resizeSplit,
+ rowLayout,
+ splitPane,
+ withSharesFrom,
+} from '../panes/layout-tree';
+import type { PaneId } from '../panes/types';
+import { formatLayoutShape, parseLayoutShape } from '../routes/layout-param';
+
+const [a, b, c, d] = ['a', 'b', 'c', 'd'] as PaneId[];
+
+const leaf = (pane: PaneId): PaneLayout => ({ type: 'pane', pane });
+
+describe('layout tree', () => {
+ it('stacks a pane below another inside a row, keeping the row', () => {
+ const layout = splitPane(rowLayout([a, b])!, b, c, 'below');
+
+ expect(layout).toEqual({
+ type: 'split',
+ axis: 'row',
+ shares: [0.5, 0.5],
+ children: [
+ leaf(a),
+ {
+ type: 'split',
+ axis: 'column',
+ shares: [0.5, 0.5],
+ children: [leaf(b), leaf(c)],
+ },
+ ],
+ });
+ expect(paneIds(layout)).toEqual(['a', 'b', 'c']);
+ });
+
+ it('adds a sibling on the same axis with an equal share', () => {
+ const layout = splitPane(rowLayout([a, b])!, a, c, 'left');
+
+ expect(layout).toEqual({
+ type: 'split',
+ axis: 'row',
+ shares: [
+ expect.closeTo(1 / 3),
+ expect.closeTo(1 / 3),
+ expect.closeTo(1 / 3),
+ ],
+ children: [leaf(c), leaf(a), leaf(b)],
+ });
+ });
+
+ it('splits a stacked pane side by side within its column', () => {
+ const stacked = splitPane(leaf(a), a, b, 'above');
+ const layout = splitPane(stacked, a, c, 'right');
+
+ expect(layoutShape(layout)).toEqual({
+ axis: 'column',
+ children: ['pane', { axis: 'row', children: ['pane', 'pane'] }],
+ });
+ expect(paneIds(layout)).toEqual(['b', 'a', 'c']);
+ });
+
+ it('adds a full-height column after the column holding the anchor', () => {
+ const layout = splitPane(rowLayout([a, b])!, a, c, 'below');
+
+ const inserted = insertColumn(layout, d, c);
+
+ expect(paneIds(inserted)).toEqual(['a', 'c', 'd', 'b']);
+ expect(inserted).toMatchObject({ axis: 'row', children: { length: 3 } });
+ expect(insertColumn(layout, d, undefined)).toMatchObject({
+ children: [leaf(d), {}, {}],
+ });
+ });
+
+ it('wraps a stacked root in a row for a new column', () => {
+ const stacked = splitPane(leaf(a), a, b, 'below');
+
+ expect(layoutShape(insertColumn(stacked, c, b))).toEqual({
+ axis: 'row',
+ children: [{ axis: 'column', children: ['pane', 'pane'] }, 'pane'],
+ });
+ });
+
+ it('collapses a split left with one pane and merges it into its parent', () => {
+ // a | (b over (c | d)): removing b leaves c and d beside a in one row.
+ let layout = splitPane(rowLayout([a, b])!, b, c, 'below');
+ layout = splitPane(layout, c, d, 'right');
+
+ const removed = removePane(layout, b);
+
+ expect(removed).toEqual({
+ type: 'split',
+ axis: 'row',
+ shares: [0.5, 0.25, 0.25],
+ children: [leaf(a), leaf(c), leaf(d)],
+ });
+ expect(removePane(removePane(removePane(removed, a), c), d)).toBe(
+ undefined
+ );
+ });
+
+ it('keeps the tiles and sizes when the panes reorder', () => {
+ const layout = resizeSplit(
+ splitPane(rowLayout([a, b])!, b, c, 'below'),
+ [],
+ [0.7, 0.3]
+ );
+
+ const reordered = reorderPanes(layout, [c, a, b]);
+
+ expect(paneIds(reordered)).toEqual(['c', 'a', 'b']);
+ expect(reordered).toMatchObject({ shares: [0.7, 0.3] });
+ expect(layoutShape(reordered!)).toEqual(layoutShape(layout!));
+ });
+
+ it('keeps the current sizes where an incoming shape matches', () => {
+ const current = resizeSplit(
+ resizeSplit(splitPane(rowLayout([a, b])!, b, c, 'below'), [], [0.7, 0.3]),
+ [1],
+ [0.2, 0.8]
+ );
+ const sameShape = fillShape(layoutShape(current!), [a, b, c]);
+ const otherShape = rowLayout([a, b, c]);
+
+ expect(withSharesFrom(sameShape, current)).toEqual(current);
+ expect(withSharesFrom(otherShape, current)).toMatchObject({
+ shares: [1 / 3, 1 / 3, 1 / 3],
+ });
+ });
+});
+
+describe('layout search value', () => {
+ it('round-trips a nested shape in preorder', () => {
+ const layout = splitPane(
+ splitPane(rowLayout([a, b])!, b, c, 'below'),
+ c,
+ d,
+ 'right'
+ );
+ const value = formatLayoutShape(layoutShape(layout));
+
+ expect(value).toBe('r2pc2pr2pp');
+ expect(parseLayoutShape(value)).toEqual(layoutShape(layout));
+ });
+
+ it('rejects values the router would never write', () => {
+ expect(parseLayoutShape('')).toBeUndefined();
+ expect(parseLayoutShape('c1p')).toBeUndefined();
+ expect(parseLayoutShape('c2pr')).toBeUndefined();
+ expect(parseLayoutShape('c2ppp')).toBeUndefined();
+ expect(parseLayoutShape('c2pc2pp')).toBeUndefined();
+ expect(parseLayoutShape('c02pp')).toBeUndefined();
+ expect(parseLayoutShape(`c2${'p'.repeat(600)}`)).toBeUndefined();
+ });
+
+ it('fills a shape only with as many panes as it has', () => {
+ const shape = parseLayoutShape('c2pp')!;
+
+ expect(fillShape(shape, [a, b])).toEqual({
+ type: 'split',
+ axis: 'column',
+ shares: [0.5, 0.5],
+ children: [leaf(a), leaf(b)],
+ });
+ expect(fillShape(shape, [a, b, c])).toBeUndefined();
+ });
+});
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 d3e8ab3e6b..5537393a02 100644
--- a/apps/web/src/lib/split-router/tests/layout.test.ts
+++ b/apps/web/src/lib/split-router/tests/layout.test.ts
@@ -1,13 +1,14 @@
import { createRoot } from 'solid-js';
import { afterEach, describe, expect, it } from 'vitest';
import { createMemoryHistory } from '../history/memory';
+import { layoutShape, type SplitSide } from '../panes/layout-tree';
import { createMemoryPaneStore } from '../panes/memory-store';
import { createSplitRouter } from '../router/create-router';
import { PANE_LEVEL } from '../router/leave-guards';
import type { Entry, PaneId } from '../routes/types';
import { appRoutes, createTestPolicy } from './fixtures';
-function setup(url: string) {
+function setup(url: string, split?: SplitSide) {
const history = createMemoryHistory(url);
const paneStore = createMemoryPaneStore<Entry>();
let created = 0;
@@ -16,7 +17,7 @@ function setup(url: string) {
routes: appRoutes,
history,
paneStore,
- policy: createTestPolicy().policy,
+ policy: createTestPolicy({ split }).policy,
createPaneId: () => `pane-${++created}` as PaneId,
}),
dispose,
@@ -123,6 +124,88 @@ describe('layout snapshot and restore', () => {
});
});
+describe('stacked panes', () => {
+ const lastUrl = (history: ReturnType<typeof createMemoryHistory>) => {
+ const last = history.entries().at(-1)!;
+
+ return `${last.path}${last.search}`;
+ };
+
+ it('records a pane opened below another in the URL', async () => {
+ const { router, history, pane } = track(setup('/home', 'below'));
+
+ await router.open('/drive', { newPane: true, source: pane(0) });
+
+ expect(router.panes()).toEqual(['pane-1', 'pane-2']);
+ expect(layoutShape(router.layout()!)).toEqual({
+ axis: 'column',
+ children: ['pane', 'pane'],
+ });
+ expect(lastUrl(history)).toBe('/home/~/drive?layout=c2pp');
+ });
+
+ it('tiles a URL as its layout says, and side by side without one', () => {
+ const stacked = track(setup('/home/~/drive/~/mail?layout=r2pc2pp'));
+ expect(layoutShape(stacked.router.layout()!)).toEqual({
+ axis: 'row',
+ children: ['pane', { axis: 'column', children: ['pane', 'pane'] }],
+ });
+ stacked.dispose();
+
+ const mismatched = track(setup('/home/~/drive?layout=r2pc2pp'));
+ expect(layoutShape(mismatched.router.layout()!)).toEqual({
+ axis: 'row',
+ children: ['pane', 'pane'],
+ });
+ });
+
+ it('brings the tiles back with Back and Forward', async () => {
+ const { router, history, pane } = track(setup('/home', 'below'));
+ await router.open('/drive', { newPane: true, source: pane(0) });
+ await router.navigatePane(pane(1), '/mail');
+
+ history.back();
+ history.back();
+ expect(router.panes()).toEqual(['pane-1']);
+
+ history.forward();
+ expect(layoutShape(router.layout()!)).toEqual({
+ axis: 'column',
+ children: ['pane', 'pane'],
+ });
+ });
+
+ it('closing a stacked pane collapses its split and the URL key', async () => {
+ const { router, history, pane } = track(
+ setup('/home/~/drive/~/mail?layout=r2pc2pp')
+ );
+
+ await router.close(pane(2));
+
+ expect(router.layout()).toMatchObject({
+ axis: 'row',
+ children: { length: 2 },
+ });
+ expect(lastUrl(history)).toBe('/home/~/drive');
+ });
+
+ it('restores captured tiles with their sizes', async () => {
+ const { router, history } = track(setup('/home/~/drive?layout=c2pp'));
+ router.resizeLayout([], [0.7, 0.3]);
+ const captured = router.layoutSnapshot();
+ expect(router.layoutHref(captured)).toBe('/home/~/drive?layout=c2pp');
+
+ await router.navigate('/mail');
+ await router.restoreLayout(captured);
+
+ expect(router.layout()).toMatchObject({
+ axis: 'column',
+ shares: [0.7, 0.3],
+ });
+ expect(lastUrl(history)).toBe('/home/~/drive?layout=c2pp');
+ });
+});
+
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'));
@@ -212,4 +295,53 @@ describe('parked layouts', () => {
expect(router.panes()).not.toContain('pane-1');
expect(router.entry('pane-1' as PaneId)).toBe(home);
});
+
+ it('parks stacked panes in their tiles and shows them again in them', async () => {
+ const { router, history } = track(setup('/home/~/drive?layout=c2pp'));
+ router.resizeLayout([], [0.7, 0.3]);
+
+ await router.openLayout(router.layoutFromHref('/mail'));
+ expect(router.layout()).toEqual({ type: 'pane', pane: 'pane-3' });
+ expect(router.layoutOf('pane-1' as PaneId)).toMatchObject({
+ axis: 'column',
+ shares: [0.7, 0.3],
+ });
+
+ await router.showLayout(['pane-1', 'pane-2'] as PaneId[]);
+ expect(router.layout()).toMatchObject({
+ axis: 'column',
+ shares: [0.7, 0.3],
+ });
+ expect(router.layoutOf('pane-3' as PaneId)).toEqual({
+ type: 'pane',
+ pane: 'pane-3',
+ });
+ expect(history.entries().at(-1)?.search).toBe('?layout=c2pp');
+ });
+
+ it('captures and links parked panes with their tiles', async () => {
+ const { router } = track(setup('/home/~/drive?layout=c2pp'));
+ await router.openLayout(router.layoutFromHref('/mail'));
+
+ const parked = router.layoutSnapshot(['pane-1', 'pane-2'] as PaneId[]);
+ expect(parked.layout).toMatchObject({ axis: 'column' });
+ expect(router.layoutHref(parked)).toBe('/home/~/drive?layout=c2pp');
+
+ const linked = router.layoutFromHref('/home/~/drive?layout=c2pp');
+ expect(layoutShape(linked.layout!)).toEqual({
+ axis: 'column',
+ children: ['pane', 'pane'],
+ });
+ });
+
+ it('a discarded parked pane leaves its tiles', async () => {
+ const { router } = track(setup('/home/~/drive?layout=c2pp'));
+ await router.openLayout(router.layoutFromHref('/mail'));
+
+ router.discardPanes(['pane-1'] as PaneId[]);
+ expect(router.layoutOf('pane-2' as PaneId)).toEqual({
+ type: 'pane',
+ pane: 'pane-2',
+ });
+ });
});
diff --git a/apps/web/src/lib/split-router/tests/panes.test.ts b/apps/web/src/lib/split-router/tests/panes.test.ts
index 517d827323..078514c24f 100644
--- a/apps/web/src/lib/split-router/tests/panes.test.ts
+++ b/apps/web/src/lib/split-router/tests/panes.test.ts
@@ -162,8 +162,8 @@ describe('panes', () => {
it('inserts, moves and removes panes in order', () => {
const { panes, removed } = setup();
- panes.insert(pane('a'), card('1'), 0);
- panes.insert(pane('b'), card('2'), 1);
+ panes.insert(pane('a'), card('1'), { insertAt: 0 });
+ panes.insert(pane('b'), card('2'), { insertAt: 1 });
expect(panes.ids()).toEqual(['a', 'b']);
expect(panes.move(pane('b'), 0)).toBe(true);
@@ -185,15 +185,15 @@ describe('panes', () => {
expect(insertionIndex([a, b], 1, [b])).toBe(1);
const { panes } = setup();
- panes.insert(a, card('1'), 0);
- panes.insert(b, card('2'), 1, [a]);
- panes.insert(c, card('3'), 1, [a]);
+ panes.insert(a, card('1'), { insertAt: 0 });
+ panes.insert(b, card('2'), { insertAt: 1 }, [a]);
+ panes.insert(c, card('3'), { insertAt: 1 }, [a]);
expect(panes.ids()).toEqual(['a', 'b', 'c']);
});
it('records each change and how the pane arrived', () => {
const { panes } = setup();
- panes.insert(pane('a'), card('1'), 0);
+ panes.insert(pane('a'), card('1'), { insertAt: 0 });
expect(panes.arrival(pane('a'))).toBe('fresh');
panes.commit(pane('a'), { type: 'push', entry: card('2') }, 'fresh');
panes.commit(pane('a'), { type: 'go', index: 0, entry: card('1') }, 'back');
@@ -203,10 +203,10 @@ describe('panes', () => {
it('applies a diff: moving through history, changing and removing panes', () => {
const { panes, removed } = setup();
- panes.insert(pane('a'), card('1', 'home'), 0);
+ panes.insert(pane('a'), card('1', 'home'), { insertAt: 0 });
panes.commit(pane('a'), { type: 'push', entry: card('2', 'mail') });
- panes.insert(pane('b'), card('3', 'drive'), 1);
- panes.insert(pane('c'), card('4', 'tasks'), 2);
+ panes.insert(pane('b'), card('3', 'drive'), { insertAt: 1 });
+ panes.insert(pane('c'), card('4', 'tasks'), { insertAt: 2 });
const diff = panes.diff(
[
@@ -242,7 +242,7 @@ describe('panes', () => {
return { type: 'keep' };
},
});
- panes.insert(pane('a'), card('1'), 0);
+ panes.insert(pane('a'), card('1'), { insertAt: 0 });
expect(panes.placeNewPane({ destination: 'doc' })).toEqual({
pane: 'a',
});
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 82d3f9a99c..cb3718f439 100644
--- a/apps/web/src/lib/split-router/tests/routes.test.ts
+++ b/apps/web/src/lib/split-router/tests/routes.test.ts
@@ -303,7 +303,11 @@ describe('panes codec', () => {
const encoded = encodePanes(
routes,
[{ paneId: 'p1' as PaneId, entry: login }],
- { path: '/home', search: '?email=a&next=b&s0.drive.sort=name', hash: '' }
+ {
+ path: '/home/~/drive',
+ search: '?email=a&layout=c2pp&next=b&s0.drive.sort=name',
+ hash: '',
+ }
);
expect(encoded.search).toBe('?email=a&next=b');
});
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index ff56d069ce..eded615797 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -8,16 +8,19 @@ Windows, Linux, and mobile layouts do not add this space.
On macOS, Back and Forward arrows beside the traffic lights navigate the active
split's history. Each arrow is
disabled when its direction has no entry. Sidebar controls remain inside each
-workspace. The top-right split icon opens another Home split, even
-when Home is already open, and is disabled when there is no room for a new split.
-Its tooltip is “New Split” and displays the registered new-split shortcut (`\`).
+workspace. The top-right split icon opens another Home split to the right of
+the active split, even when Home is already open, and is disabled when that
+split has no room to divide. Its tooltip is “New split” and displays the
+registered new-split shortcut (`\`). The icon before it, “New split below”
+(`|`), opens Home stacked below the active split.
## Desktop tabs (macOS, `enable-desktop-tabs` flag)
The title bar's center holds browser-style tabs; each tab is a whole split
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
+is instant and keeps scroll, selection, and editor state, each split keeps
+its back/forward history, and stacked splits come back stacked at the sizes
+they had. 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
@@ -294,9 +297,24 @@ Command and create-menu headers have 20px horizontal and 12px vertical padding.
Splits: the app is a tiling window manager. Active light-theme panes are white;
inactive desktop panes are slightly darker than the active pane across themes,
-while retaining the theme hue. Public variable-length routes use
+while retaining the theme hue. Any split can be divided beside or stacked:
+the split menu (right-click a split's header) offers **New split left**,
+**right**, **above**, and **below**, each splitting that split and disabled
+when it lacks room (400px wide, 240px tall per split). `\` (or Cmd+\ while
+typing) opens Home to the right of the active split, so in a stack only the
+active split divides; `|` (Shift+\, or Shift+Cmd+\ while typing) stacks Home
+below it. A new split beside others along the same axis takes an equal share.
+Option+Shift-click (Alt+Shift elsewhere) on anything that
+Shift-clicks into a new split opens it below the split it came from. Closing a
+stacked split gives its space to its neighbours; **Swap split left/right**
+trades places with the previous or next split in reading order, and the tiles
+keep their sizes. Public variable-length routes use
`~` as the boundary between panes
-(`/app/drive/folder/<uuid>/~/mail`). Legacy fixed `type/id`
+(`/app/drive/folder/<uuid>/~/mail`). Panes are listed top to bottom, left to
+right, and a `layout` key records stacking when there is any:
+`/app/home/~/drive/~/mail?layout=r2pc2pp` is Home beside Drive over Mail
+(`p` a pane, `r<n>` side by side, `c<n>` stacked). Without the key the panes
+sit side by side; sizes are not in the URL. Legacy fixed `type/id`
pane routes remain accepted. Known app-view URLs under `/app/component/` redirect
to their canonical paths above; legacy composers keep their existing paths. Split-specific view state uses positionally
namespaced query parameters such as `s0.drive.sort=created_at`. Route identity
@@ -432,8 +450,9 @@ the main title when hidden, with separate preferences per block type.
Desktop splits, including a single split in the browser or native app, appear as
individually bordered panels with 8px corners and 6px top, right, and bottom
-insets and 6px resizable gaps. The leftmost panel sits flush against the app rail,
-which has no right divider. Touch layouts keep their existing presentation.
+insets and 6px resizable gaps between them, side by side and stacked. The
+leftmost panels sit flush against the app rail, which has no right divider.
+Touch layouts keep their existing presentation.
Split focus mode (`Shift+Esc`) floats the active split in a rounded, bordered
panel over the same glass scrim as dialogs. Click the scrim or use the shortcut