@eserstack/mux 0.0.0-bootstrap.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +151 -0
  3. package/dist/engine/effects.d.ts +52 -0
  4. package/dist/engine/effects.js +2 -0
  5. package/dist/engine/geometry.d.ts +57 -0
  6. package/dist/engine/geometry.js +170 -0
  7. package/dist/engine/mod.d.ts +13 -0
  8. package/dist/engine/mod.js +5 -0
  9. package/dist/engine/reducer.d.ts +15 -0
  10. package/dist/engine/reducer.js +325 -0
  11. package/dist/engine/sanitize.d.ts +60 -0
  12. package/dist/engine/sanitize.js +64 -0
  13. package/dist/engine/split-tree.d.ts +41 -0
  14. package/dist/engine/split-tree.js +117 -0
  15. package/dist/engine/types.d.ts +192 -0
  16. package/dist/engine/types.js +2 -0
  17. package/dist/frontends/frontend.d.ts +17 -0
  18. package/dist/frontends/frontend.js +2 -0
  19. package/dist/frontends/tui/compositor.d.ts +23 -0
  20. package/dist/frontends/tui/compositor.js +72 -0
  21. package/dist/frontends/tui/frame.d.ts +9 -0
  22. package/dist/frontends/tui/frame.js +2 -0
  23. package/dist/frontends/tui/input-source.d.ts +21 -0
  24. package/dist/frontends/tui/input-source.js +40 -0
  25. package/dist/frontends/tui/tui-frontend.d.ts +36 -0
  26. package/dist/frontends/tui/tui-frontend.js +188 -0
  27. package/dist/ipc/protocol.d.ts +41 -0
  28. package/dist/ipc/protocol.js +2 -0
  29. package/dist/ipc/transport-inprocess.d.ts +9 -0
  30. package/dist/ipc/transport-inprocess.js +35 -0
  31. package/dist/ipc/transport-ws.d.ts +19 -0
  32. package/dist/ipc/transport-ws.js +37 -0
  33. package/dist/keybindings/defaults.d.ts +3 -0
  34. package/dist/keybindings/defaults.js +80 -0
  35. package/dist/keybindings/mod.d.ts +10 -0
  36. package/dist/keybindings/mod.js +4 -0
  37. package/dist/keybindings/modes.d.ts +19 -0
  38. package/dist/keybindings/modes.js +18 -0
  39. package/dist/keybindings/registry.d.ts +20 -0
  40. package/dist/keybindings/registry.js +37 -0
  41. package/dist/mod.d.ts +28 -0
  42. package/dist/mod.js +21 -0
  43. package/dist/render/scheduler.d.ts +18 -0
  44. package/dist/render/scheduler.js +33 -0
  45. package/dist/runner/inprocess.d.ts +10 -0
  46. package/dist/runner/inprocess.js +60 -0
  47. package/dist/scene/diff.d.ts +26 -0
  48. package/dist/scene/diff.js +83 -0
  49. package/dist/scene/mod.d.ts +9 -0
  50. package/dist/scene/mod.js +3 -0
  51. package/dist/scene/scene.d.ts +30 -0
  52. package/dist/scene/scene.js +54 -0
  53. package/dist/server/pty-host.d.ts +25 -0
  54. package/dist/server/pty-host.js +81 -0
  55. package/dist/server/server.d.ts +58 -0
  56. package/dist/server/server.js +204 -0
  57. package/package.json +51 -1
@@ -0,0 +1,325 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ import * as geometry from "./geometry.js";
3
+ import * as tree from "./split-tree.js";
4
+ const RESIZE_DELTA = 0.05;
5
+ const RENDER = [{ type: "render" }];
6
+ /** Create an empty engine state; dispatch `newTab` to open the first tab. */
7
+ export const createInitialState = (viewport) => ({
8
+ panes: {},
9
+ tabs: [],
10
+ activeTab: 0,
11
+ mode: "normal",
12
+ viewport,
13
+ running: true,
14
+ nextPaneSeq: 1,
15
+ nextTabSeq: 1,
16
+ });
17
+ const noop = (state) => ({ state, effects: [] });
18
+ const activeTabOf = (state) => state.tabs[state.activeTab];
19
+ const replaceActiveTab = (state, tab) => ({
20
+ ...state,
21
+ tabs: state.tabs.map((t, i) => (i === state.activeTab ? tab : t)),
22
+ });
23
+ const makePane = (state, spec) => {
24
+ const id = `pane-${state.nextPaneSeq}`;
25
+ const pane = {
26
+ id,
27
+ kind: spec.kind ?? "terminal",
28
+ title: spec.title ?? spec.command ?? "shell",
29
+ cwd: spec.cwd,
30
+ command: spec.command,
31
+ args: spec.args,
32
+ meta: spec.meta,
33
+ };
34
+ return {
35
+ pane,
36
+ state: {
37
+ ...state,
38
+ panes: { ...state.panes, [id]: pane },
39
+ nextPaneSeq: state.nextPaneSeq + 1,
40
+ },
41
+ };
42
+ };
43
+ /**
44
+ * Close the tab at `index`, killing all its panes; exits when it was the last
45
+ * tab. Closing a tab other than the active one leaves the user's view in place:
46
+ * activeTab only shifts to track the same tab (decrement when a lower-indexed
47
+ * tab is removed) or clamps when the active tab itself is closed.
48
+ */
49
+ const closeTabAt = (state, index) => {
50
+ const tab = state.tabs[index];
51
+ if (tab === undefined)
52
+ return noop(state);
53
+ const paneIds = tree.collectLeaves(tab.root);
54
+ const kills = paneIds.map((p) => ({ type: "killPty", pane: p }));
55
+ const panes = { ...state.panes };
56
+ for (const p of paneIds)
57
+ delete panes[p];
58
+ const tabs = state.tabs.filter((_, i) => i !== index);
59
+ if (tabs.length === 0) {
60
+ return {
61
+ state: { ...state, panes, tabs, running: false },
62
+ effects: [...kills, { type: "exit" }],
63
+ };
64
+ }
65
+ const activeTab = index < state.activeTab
66
+ ? state.activeTab - 1
67
+ : Math.min(state.activeTab, tabs.length - 1);
68
+ return {
69
+ state: { ...state, panes, tabs, activeTab },
70
+ effects: [...kills, { type: "render" }],
71
+ };
72
+ };
73
+ /** Close the active tab. */
74
+ const closeActiveTab = (state) => closeTabAt(state, state.activeTab);
75
+ const addPane = (state, direction, spec) => {
76
+ const tab = activeTabOf(state);
77
+ if (tab === undefined)
78
+ return noop(state);
79
+ const { pane, state: s1 } = makePane(state, spec);
80
+ const root = tree.splitLeaf(tab.root, tab.focusedPane, direction, pane.id);
81
+ const newTab = {
82
+ ...tab,
83
+ root,
84
+ focusedPane: pane.id,
85
+ fullscreenPane: undefined,
86
+ };
87
+ return {
88
+ state: replaceActiveTab(s1, newTab),
89
+ effects: [{ type: "spawnPty", pane: pane.id }, { type: "render" }],
90
+ };
91
+ };
92
+ export const reduce = (state, action) => {
93
+ switch (action.type) {
94
+ case "switchMode":
95
+ return { state: { ...state, mode: action.mode }, effects: RENDER };
96
+ case "splitPane":
97
+ return addPane(state, action.direction, {});
98
+ case "newPane":
99
+ return addPane(state, action.direction ?? "vertical", {
100
+ kind: action.kind,
101
+ command: action.command,
102
+ args: action.args,
103
+ cwd: action.cwd,
104
+ title: action.title,
105
+ meta: action.meta,
106
+ });
107
+ case "closeFocusedPane": {
108
+ const tab = activeTabOf(state);
109
+ if (tab === undefined)
110
+ return noop(state);
111
+ const closed = tab.focusedPane;
112
+ const { root, promoted } = tree.removeLeaf(tab.root, closed);
113
+ if (root === null)
114
+ return closeActiveTab(state);
115
+ const panes = { ...state.panes };
116
+ delete panes[closed];
117
+ const newTab = {
118
+ ...tab,
119
+ root,
120
+ focusedPane: promoted ?? tree.firstLeaf(root),
121
+ fullscreenPane: undefined,
122
+ };
123
+ return {
124
+ state: replaceActiveTab({ ...state, panes }, newTab),
125
+ effects: [{ type: "killPty", pane: closed }, { type: "render" }],
126
+ };
127
+ }
128
+ case "focusDirection": {
129
+ const tab = activeTabOf(state);
130
+ if (tab === undefined)
131
+ return noop(state);
132
+ const geoms = geometry.computeTabGeoms(tab, state.viewport, geometry.DEFAULT_CHROME);
133
+ const next = geometry.neighborInDirection(geoms, tab.focusedPane, action.direction);
134
+ if (next === null)
135
+ return noop(state);
136
+ return {
137
+ state: replaceActiveTab(state, { ...tab, focusedPane: next }),
138
+ effects: RENDER,
139
+ };
140
+ }
141
+ case "focusNext":
142
+ case "focusPrev": {
143
+ const tab = activeTabOf(state);
144
+ if (tab === undefined)
145
+ return noop(state);
146
+ const leaves = tree.collectLeaves(tab.root);
147
+ if (leaves.length <= 1)
148
+ return noop(state);
149
+ const idx = leaves.indexOf(tab.focusedPane);
150
+ const step = action.type === "focusNext" ? 1 : -1;
151
+ const focusedPane = leaves[(idx + step + leaves.length) % leaves.length];
152
+ return {
153
+ state: replaceActiveTab(state, { ...tab, focusedPane }),
154
+ effects: RENDER,
155
+ };
156
+ }
157
+ case "focusPane": {
158
+ const tab = activeTabOf(state);
159
+ if (tab === undefined || !tree.hasLeaf(tab.root, action.pane)) {
160
+ return noop(state);
161
+ }
162
+ return {
163
+ state: replaceActiveTab(state, { ...tab, focusedPane: action.pane }),
164
+ effects: RENDER,
165
+ };
166
+ }
167
+ case "toggleFullscreen": {
168
+ const tab = activeTabOf(state);
169
+ if (tab === undefined)
170
+ return noop(state);
171
+ const fullscreenPane = tab.fullscreenPane === tab.focusedPane ? undefined : tab.focusedPane;
172
+ return {
173
+ state: replaceActiveTab(state, { ...tab, fullscreenPane }),
174
+ effects: RENDER,
175
+ };
176
+ }
177
+ case "resizePane": {
178
+ const tab = activeTabOf(state);
179
+ if (tab === undefined)
180
+ return noop(state);
181
+ const root = tree.resizeFocused(tab.root, tab.focusedPane, action.direction, RESIZE_DELTA);
182
+ if (root === tab.root)
183
+ return noop(state);
184
+ return {
185
+ state: replaceActiveTab(state, { ...tab, root }),
186
+ effects: RENDER,
187
+ };
188
+ }
189
+ case "newTab": {
190
+ const id = `tab-${state.nextTabSeq}`;
191
+ const { pane, state: s1 } = makePane(state, {
192
+ kind: action.kind,
193
+ command: action.command,
194
+ args: action.args,
195
+ cwd: action.cwd,
196
+ title: action.title,
197
+ meta: action.meta,
198
+ });
199
+ const tab = {
200
+ id,
201
+ name: action.title ?? `tab ${state.nextTabSeq}`,
202
+ root: tree.leaf(pane.id),
203
+ focusedPane: pane.id,
204
+ };
205
+ const tabs = [...s1.tabs, tab];
206
+ return {
207
+ state: {
208
+ ...s1,
209
+ tabs,
210
+ activeTab: tabs.length - 1,
211
+ nextTabSeq: s1.nextTabSeq + 1,
212
+ },
213
+ effects: [{ type: "spawnPty", pane: pane.id }, { type: "render" }],
214
+ };
215
+ }
216
+ case "closeTab":
217
+ return closeTabAt(state, action.index ?? state.activeTab);
218
+ case "gotoTab": {
219
+ if (action.index < 0 || action.index >= state.tabs.length) {
220
+ return noop(state);
221
+ }
222
+ return { state: { ...state, activeTab: action.index }, effects: RENDER };
223
+ }
224
+ case "nextTab":
225
+ case "prevTab": {
226
+ if (state.tabs.length <= 1)
227
+ return noop(state);
228
+ const step = action.type === "nextTab" ? 1 : -1;
229
+ const activeTab = (state.activeTab + step + state.tabs.length) % state.tabs.length;
230
+ return { state: { ...state, activeTab }, effects: RENDER };
231
+ }
232
+ case "scroll": {
233
+ const tab = activeTabOf(state);
234
+ if (tab === undefined)
235
+ return noop(state);
236
+ return {
237
+ state,
238
+ effects: [
239
+ {
240
+ type: "scrollPane",
241
+ pane: tab.focusedPane,
242
+ action: action.action,
243
+ },
244
+ ],
245
+ };
246
+ }
247
+ case "writeInput": {
248
+ const tab = activeTabOf(state);
249
+ if (tab === undefined)
250
+ return noop(state);
251
+ return {
252
+ state,
253
+ effects: [
254
+ {
255
+ type: "writePty",
256
+ pane: tab.focusedPane,
257
+ data: action.data,
258
+ },
259
+ ],
260
+ };
261
+ }
262
+ case "writeToPane": {
263
+ // Address a specific pane regardless of focus (e.g. agent driving, or a
264
+ // web client notifying the pane bound to a spec). Ignore unknown panes.
265
+ if (state.panes[action.pane] === undefined)
266
+ return noop(state);
267
+ return {
268
+ state,
269
+ effects: [{ type: "writePty", pane: action.pane, data: action.data }],
270
+ };
271
+ }
272
+ case "resizeViewport":
273
+ return {
274
+ state: { ...state, viewport: { cols: action.cols, rows: action.rows } },
275
+ effects: RENDER,
276
+ };
277
+ case "paneExited": {
278
+ const tabIndex = state.tabs.findIndex((t) => tree.hasLeaf(t.root, action.pane));
279
+ if (tabIndex < 0)
280
+ return noop(state);
281
+ const tab = state.tabs[tabIndex];
282
+ const { root, promoted } = tree.removeLeaf(tab.root, action.pane);
283
+ const panes = { ...state.panes };
284
+ delete panes[action.pane];
285
+ if (root === null) {
286
+ const tabs = state.tabs.filter((_, i) => i !== tabIndex);
287
+ if (tabs.length === 0) {
288
+ return {
289
+ state: { ...state, panes, tabs, running: false },
290
+ effects: [{ type: "exit" }],
291
+ };
292
+ }
293
+ // A tab before the active one shifts every later index down by one, so
294
+ // decrement to keep viewing the same tab; otherwise just clamp.
295
+ const activeTab = tabIndex < state.activeTab
296
+ ? state.activeTab - 1
297
+ : Math.min(state.activeTab, tabs.length - 1);
298
+ return {
299
+ state: { ...state, panes, tabs, activeTab },
300
+ effects: RENDER,
301
+ };
302
+ }
303
+ const focusedPane = tab.focusedPane === action.pane
304
+ ? (promoted ?? tree.firstLeaf(root))
305
+ : tab.focusedPane;
306
+ const fullscreenPane = tab.fullscreenPane === action.pane ? undefined : tab.fullscreenPane;
307
+ const newTab = { ...tab, root, focusedPane, fullscreenPane };
308
+ return {
309
+ state: {
310
+ ...state,
311
+ panes,
312
+ tabs: state.tabs.map((t, i) => (i === tabIndex ? newTab : t)),
313
+ },
314
+ effects: RENDER,
315
+ };
316
+ }
317
+ case "detach":
318
+ return { state, effects: [{ type: "detach" }] };
319
+ case "quit":
320
+ return {
321
+ state: { ...state, running: false },
322
+ effects: [{ type: "exit" }],
323
+ };
324
+ }
325
+ };
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Trust-boundary sanitizer for actions arriving over the network.
3
+ *
4
+ * {@link Action} is shared by two very different callers. The local TUI is the
5
+ * user driving their own terminal: naming a command to run is the entire point,
6
+ * and restricting it there would be nonsense. A client on the far end of a
7
+ * socket is a different trust level entirely — there, an action carrying
8
+ * `command` / `args` / `cwd` is a request to execute arbitrary argv with the
9
+ * server process's full environment.
10
+ *
11
+ * So the capability stays in the engine and is stripped at ingress: a remote
12
+ * client names a pane *kind*, and the server's spawn resolver decides what that
13
+ * actually runs. This is defence in depth behind whatever authentication the
14
+ * transport applies, not a replacement for it.
15
+ *
16
+ * It lives in the engine rather than in one frontend because there is more than
17
+ * one remote path into a mux server, and a sanitizer only one of them calls is
18
+ * not a trust boundary. It previously sat in `@eserstack/noskills-web` and was
19
+ * applied only on the in-process WebSocket bridge; the daemon relayed frames to
20
+ * `mux-worker` untouched.
21
+ *
22
+ * @module
23
+ */
24
+ import type { Action } from "./types.ts";
25
+ import type { FrontendToServer } from "../ipc/protocol.ts";
26
+ /**
27
+ * Strip process-spawning fields from an action received over the network.
28
+ *
29
+ * Returns the action unchanged when it carries no such fields, so the common
30
+ * case allocates nothing.
31
+ *
32
+ * Both spawning actions are covered. `newPane` carries the same
33
+ * `command`/`args`/`cwd` triple as `newTab` and was previously passed through
34
+ * untouched, so the guard on `newTab` could be walked straight around by
35
+ * splitting a pane instead of opening a tab.
36
+ */
37
+ export declare const sanitizeRemoteAction: (action: Action) => Action;
38
+ /** Apply {@link sanitizeRemoteAction} to any frontend message that carries one. */
39
+ export declare const sanitizeRemoteMessage: (msg: FrontendToServer) => FrontendToServer;
40
+ /**
41
+ * The inbound half of a transport, which is all sanitizing needs to see.
42
+ *
43
+ * Declared structurally rather than importing the full `Transport` type so this
44
+ * module stays in the engine, with no dependency on the server package.
45
+ */
46
+ export type InboundTransport<T> = {
47
+ onMessage(handler: (msg: T) => void): void;
48
+ };
49
+ /**
50
+ * Wrap a transport so every inbound message is sanitized before it reaches the
51
+ * server.
52
+ *
53
+ * This exists because "remember to call the sanitizer" is not a trust boundary.
54
+ * There are two remote routes into a mux server and only one of them called it;
55
+ * the daemon's WebTransport route relayed frames through untouched for as long
56
+ * as it has existed. Wrapping the transport puts the filter where the untrusted
57
+ * bytes arrive, so a new remote route has to actively opt out of it rather than
58
+ * silently forget to opt in.
59
+ */
60
+ export declare const sanitizeRemoteTransport: <T extends InboundTransport<FrontendToServer>>(transport: T) => T;
@@ -0,0 +1,64 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Strip process-spawning fields from an action received over the network.
4
+ *
5
+ * Returns the action unchanged when it carries no such fields, so the common
6
+ * case allocates nothing.
7
+ *
8
+ * Both spawning actions are covered. `newPane` carries the same
9
+ * `command`/`args`/`cwd` triple as `newTab` and was previously passed through
10
+ * untouched, so the guard on `newTab` could be walked straight around by
11
+ * splitting a pane instead of opening a tab.
12
+ */
13
+ export const sanitizeRemoteAction = (action) => {
14
+ if (action.type !== "newTab" && action.type !== "newPane") {
15
+ return action;
16
+ }
17
+ if (action.command === undefined &&
18
+ action.args === undefined &&
19
+ action.cwd === undefined) {
20
+ return action;
21
+ }
22
+ // Keep only the fields a remote client is allowed to choose. `kind` selects
23
+ // between the configured pane flavours; the resolver decides the argv.
24
+ const base = {
25
+ ...(action.kind === undefined ? {} : { kind: action.kind }),
26
+ ...(action.title === undefined ? {} : { title: action.title }),
27
+ ...(action.meta === undefined ? {} : { meta: action.meta }),
28
+ };
29
+ if (action.type === "newPane") {
30
+ return {
31
+ type: "newPane",
32
+ ...(action.direction === undefined
33
+ ? {}
34
+ : { direction: action.direction }),
35
+ ...base,
36
+ };
37
+ }
38
+ return { type: "newTab", ...base };
39
+ };
40
+ /** Apply {@link sanitizeRemoteAction} to any frontend message that carries one. */
41
+ export const sanitizeRemoteMessage = (msg) => {
42
+ if (msg.t !== "action") {
43
+ return msg;
44
+ }
45
+ const sanitized = sanitizeRemoteAction(msg.action);
46
+ return sanitized === msg.action ? msg : { ...msg, action: sanitized };
47
+ };
48
+ /**
49
+ * Wrap a transport so every inbound message is sanitized before it reaches the
50
+ * server.
51
+ *
52
+ * This exists because "remember to call the sanitizer" is not a trust boundary.
53
+ * There are two remote routes into a mux server and only one of them called it;
54
+ * the daemon's WebTransport route relayed frames through untouched for as long
55
+ * as it has existed. Wrapping the transport puts the filter where the untrusted
56
+ * bytes arrive, so a new remote route has to actively opt out of it rather than
57
+ * silently forget to opt in.
58
+ */
59
+ export const sanitizeRemoteTransport = (transport) => ({
60
+ ...transport,
61
+ onMessage: (handler) => {
62
+ transport.onMessage((msg) => handler(sanitizeRemoteMessage(msg)));
63
+ },
64
+ });
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Pure operations over the binary split tree ({@link SplitNode}).
3
+ *
4
+ * Every function is immutable: it returns a new tree (or leaf list) and never
5
+ * mutates its input. These are the building blocks the reducer composes.
6
+ *
7
+ * @module
8
+ */
9
+ import type { Direction, PaneId, SplitDirection, SplitNode } from "./types.ts";
10
+ /** Construct a leaf node. */
11
+ export declare const leaf: (pane: PaneId) => SplitNode;
12
+ /** All pane ids in left-to-right, depth-first order. */
13
+ export declare const collectLeaves: (node: SplitNode) => PaneId[];
14
+ /** Whether `pane` appears anywhere in the tree. */
15
+ export declare const hasLeaf: (node: SplitNode, pane: PaneId) => boolean;
16
+ /** The first (left/top-most) pane id in the tree. */
17
+ export declare const firstLeaf: (node: SplitNode) => PaneId;
18
+ /**
19
+ * Replace the leaf for `target` with a branch splitting it and `newPane`.
20
+ * Returns the tree unchanged if `target` is not present.
21
+ */
22
+ export declare const splitLeaf: (node: SplitNode, target: PaneId, direction: SplitDirection, newPane: PaneId, ratio?: number) => SplitNode;
23
+ /** Result of removing a leaf: the new tree (null if it emptied) and the pane to focus next. */
24
+ export type RemoveResult = {
25
+ readonly root: SplitNode | null;
26
+ readonly promoted: PaneId | null;
27
+ };
28
+ /**
29
+ * Remove the leaf for `target`. The containing branch collapses to its sibling,
30
+ * and `promoted` is the sibling's first leaf so the caller can move focus there.
31
+ */
32
+ export declare const removeLeaf: (node: SplitNode, target: PaneId) => RemoveResult;
33
+ /**
34
+ * Grow/shrink the focused pane by adjusting the nearest enclosing branch whose
35
+ * axis matches `direction`. `delta` is a ratio fraction (e.g. 0.05).
36
+ *
37
+ * The sign depends only on the direction (not which side the pane is on): for a
38
+ * vertical branch `right` grows `first`, `left` shrinks it; for a horizontal
39
+ * branch `down` grows `first`, `up` shrinks it.
40
+ */
41
+ export declare const resizeFocused: (node: SplitNode, target: PaneId, direction: Direction, delta: number) => SplitNode;
@@ -0,0 +1,117 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ const MIN_RATIO = 0.1;
3
+ const MAX_RATIO = 0.9;
4
+ const clampRatio = (r) => r < MIN_RATIO ? MIN_RATIO : r > MAX_RATIO ? MAX_RATIO : r;
5
+ /** Construct a leaf node. */
6
+ export const leaf = (pane) => ({ kind: "leaf", pane });
7
+ /** All pane ids in left-to-right, depth-first order. */
8
+ export const collectLeaves = (node) => {
9
+ if (node.kind === "leaf")
10
+ return [node.pane];
11
+ return [...collectLeaves(node.first), ...collectLeaves(node.second)];
12
+ };
13
+ /** Whether `pane` appears anywhere in the tree. */
14
+ export const hasLeaf = (node, pane) => {
15
+ if (node.kind === "leaf")
16
+ return node.pane === pane;
17
+ return hasLeaf(node.first, pane) || hasLeaf(node.second, pane);
18
+ };
19
+ /** The first (left/top-most) pane id in the tree. */
20
+ export const firstLeaf = (node) => {
21
+ let cur = node;
22
+ while (cur.kind === "branch")
23
+ cur = cur.first;
24
+ return cur.pane;
25
+ };
26
+ /**
27
+ * Replace the leaf for `target` with a branch splitting it and `newPane`.
28
+ * Returns the tree unchanged if `target` is not present.
29
+ */
30
+ export const splitLeaf = (node, target, direction, newPane, ratio = 0.5) => {
31
+ if (node.kind === "leaf") {
32
+ if (node.pane !== target)
33
+ return node;
34
+ return {
35
+ kind: "branch",
36
+ direction,
37
+ first: node,
38
+ second: leaf(newPane),
39
+ ratio: clampRatio(ratio),
40
+ };
41
+ }
42
+ if (hasLeaf(node.first, target)) {
43
+ return {
44
+ ...node,
45
+ first: splitLeaf(node.first, target, direction, newPane, ratio),
46
+ };
47
+ }
48
+ if (hasLeaf(node.second, target)) {
49
+ return {
50
+ ...node,
51
+ second: splitLeaf(node.second, target, direction, newPane, ratio),
52
+ };
53
+ }
54
+ return node;
55
+ };
56
+ /**
57
+ * Remove the leaf for `target`. The containing branch collapses to its sibling,
58
+ * and `promoted` is the sibling's first leaf so the caller can move focus there.
59
+ */
60
+ export const removeLeaf = (node, target) => {
61
+ if (node.kind === "leaf") {
62
+ return node.pane === target
63
+ ? { root: null, promoted: null }
64
+ : { root: node, promoted: null };
65
+ }
66
+ if (node.first.kind === "leaf" && node.first.pane === target) {
67
+ return { root: node.second, promoted: firstLeaf(node.second) };
68
+ }
69
+ if (node.second.kind === "leaf" && node.second.pane === target) {
70
+ return { root: node.first, promoted: firstLeaf(node.first) };
71
+ }
72
+ if (hasLeaf(node.first, target)) {
73
+ const r = removeLeaf(node.first, target);
74
+ if (r.root === null) {
75
+ return { root: node.second, promoted: firstLeaf(node.second) };
76
+ }
77
+ return { root: { ...node, first: r.root }, promoted: r.promoted };
78
+ }
79
+ if (hasLeaf(node.second, target)) {
80
+ const r = removeLeaf(node.second, target);
81
+ if (r.root === null) {
82
+ return { root: node.first, promoted: firstLeaf(node.first) };
83
+ }
84
+ return { root: { ...node, second: r.root }, promoted: r.promoted };
85
+ }
86
+ return { root: node, promoted: null };
87
+ };
88
+ /**
89
+ * Grow/shrink the focused pane by adjusting the nearest enclosing branch whose
90
+ * axis matches `direction`. `delta` is a ratio fraction (e.g. 0.05).
91
+ *
92
+ * The sign depends only on the direction (not which side the pane is on): for a
93
+ * vertical branch `right` grows `first`, `left` shrinks it; for a horizontal
94
+ * branch `down` grows `first`, `up` shrinks it.
95
+ */
96
+ export const resizeFocused = (node, target, direction, delta) => {
97
+ if (node.kind === "leaf")
98
+ return node;
99
+ const childKey = hasLeaf(node.first, target)
100
+ ? "first"
101
+ : hasLeaf(node.second, target)
102
+ ? "second"
103
+ : null;
104
+ if (childKey === null)
105
+ return node;
106
+ // Prefer the deepest matching branch: recurse first.
107
+ const child = node[childKey];
108
+ const adjustedChild = resizeFocused(child, target, direction, delta);
109
+ if (adjustedChild !== child) {
110
+ return { ...node, [childKey]: adjustedChild };
111
+ }
112
+ const axis = direction === "left" || direction === "right" ? "vertical" : "horizontal";
113
+ if (node.direction !== axis)
114
+ return node;
115
+ const sign = direction === "right" || direction === "down" ? 1 : -1;
116
+ return { ...node, ratio: clampRatio(node.ratio + sign * delta) };
117
+ };