@andrewcyuan/focusgrid 0.2.1 → 0.3.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.
@@ -8,37 +8,35 @@ function createId(prefix = "node") {
8
8
  }
9
9
  //#endregion
10
10
  //#region core/src/layout/geometry.ts
11
+ const HANDLE_SIZE = 3;
11
12
  function computeLayout(state) {
12
- const geometry = {
13
+ const collector = {
13
14
  panes: [],
14
15
  handles: [],
15
16
  rectByNodeId: /* @__PURE__ */ new Map()
16
17
  };
17
- const root = computeNode(state.root, {
18
+ const rect = {
18
19
  x: 0,
19
20
  y: 0,
20
21
  width: Math.max(0, state.container.width),
21
22
  height: Math.max(0, state.container.height)
22
- }, geometry, state.activePaneId);
23
+ };
24
+ const root = computeNode(state.root, rect, collector, state.activePaneId);
23
25
  return {
24
- ...geometry,
26
+ ...collector,
25
27
  root
26
28
  };
27
29
  }
28
30
  function normalizeSplitSizes(sizes, expectedLength) {
29
- const fallback = () => Array.from({ length: expectedLength }, () => 1 / expectedLength);
30
- if (sizes.length !== expectedLength) return fallback();
31
31
  const total = sizes.reduce((sum, size) => sum + Math.max(0, size), 0);
32
- if (total <= 0) return fallback();
32
+ if (sizes.length !== expectedLength || total <= 0) return Array.from({ length: expectedLength }, () => 1 / expectedLength);
33
33
  return sizes.map((size) => Math.max(0, size) / total);
34
34
  }
35
- function getMinimumSize(node, direction, minWidth = 0, minHeight = 0) {
36
- if (node.kind === "pane") return direction === "horizontal" ? minWidth : minHeight;
37
- if (node.orientation === direction) return node.children.reduce((sum, child) => sum + getMinimumSize(child, direction, minWidth, minHeight), 0) + Math.max(0, node.children.length - 1) * 3;
38
- return Math.max(0, ...node.children.map((child) => getMinimumSize(child, direction, minWidth, minHeight)));
35
+ function getHandlesSize(split) {
36
+ return Math.max(0, split.children.length - 1) * HANDLE_SIZE;
39
37
  }
40
- function computeNode(node, rect, geometry, activePaneId) {
41
- geometry.rectByNodeId.set(node.id, rect);
38
+ function computeNode(node, rect, collector, activePaneId) {
39
+ collector.rectByNodeId.set(node.id, rect);
42
40
  if (node.kind === "pane") {
43
41
  const pane = {
44
42
  paneId: node.paneId,
@@ -46,7 +44,7 @@ function computeNode(node, rect, geometry, activePaneId) {
46
44
  rect,
47
45
  active: node.paneId === activePaneId
48
46
  };
49
- geometry.panes.push(pane);
47
+ collector.panes.push(pane);
50
48
  return {
51
49
  kind: "pane",
52
50
  pane
@@ -56,14 +54,13 @@ function computeNode(node, rect, geometry, activePaneId) {
56
54
  const horizontal = node.orientation === "horizontal";
57
55
  const axisSize = horizontal ? rect.width : rect.height;
58
56
  const axisStart = horizontal ? rect.x : rect.y;
59
- const handleTotal = Math.max(0, node.children.length - 1) * 3;
60
- const contentSize = Math.max(0, axisSize - handleTotal);
57
+ const contentSize = Math.max(0, axisSize - getHandlesSize(node));
61
58
  let cursor = axisStart;
62
59
  const handles = [];
63
60
  const children = node.children.map((child, index) => {
64
61
  const isLast = index === node.children.length - 1;
65
62
  const childSize = isLast ? axisStart + axisSize - cursor : Math.floor(contentSize * (sizes[index] ?? 0));
66
- const computedChild = computeNode(child, createChildRect(node.orientation, rect, cursor, childSize), geometry, activePaneId);
63
+ const computedChild = computeNode(child, createChildRect(node.orientation, rect, cursor, childSize), collector, activePaneId);
67
64
  cursor += childSize;
68
65
  if (!isLast) {
69
66
  const handle = {
@@ -71,11 +68,11 @@ function computeNode(node, rect, geometry, activePaneId) {
71
68
  splitId: node.id,
72
69
  index,
73
70
  direction: node.orientation,
74
- rect: createChildRect(node.orientation, rect, cursor, 3)
71
+ rect: createChildRect(node.orientation, rect, cursor, HANDLE_SIZE)
75
72
  };
76
73
  handles.push(handle);
77
- geometry.handles.push(handle);
78
- cursor += 3;
74
+ collector.handles.push(handle);
75
+ cursor += HANDLE_SIZE;
79
76
  }
80
77
  return computedChild;
81
78
  });
@@ -101,139 +98,91 @@ function createChildRect(direction, rect, cursor, size) {
101
98
  }
102
99
  //#endregion
103
100
  //#region core/src/layout/resize.ts
104
- function resizeSplit(split, totalPx, index, deltaPx, snapshotSizes, minWidth = 0, minHeight = 0) {
101
+ function getMinimumSize(node, direction, paneMinSize) {
102
+ if (node.kind === "pane") return paneMinSize;
103
+ const childMinimums = node.children.map((child) => getMinimumSize(child, direction, paneMinSize));
104
+ if (node.orientation !== direction) return Math.max(0, ...childMinimums);
105
+ return childMinimums.reduce((sum, size) => sum + size, 0) + getHandlesSize(node);
106
+ }
107
+ function resizeSplit(split, totalPx, index, deltaPx, snapshotSizes, paneMinSize) {
105
108
  if (totalPx <= 0 || index < 0 || index >= split.children.length - 1) return split;
106
- const baseSizes = normalizeSplitSizes(snapshotSizes ?? split.sizes, split.children.length);
109
+ const nextSizes = normalizeSplitSizes(snapshotSizes ?? split.sizes, split.children.length);
107
110
  const deltaRatio = deltaPx / totalPx;
108
- const nextSizes = [...baseSizes];
109
111
  nextSizes[index] += deltaRatio;
110
112
  nextSizes[index + 1] -= deltaRatio;
111
- const minSizes = split.children.map((child) => getMinimumSize(child, split.orientation, minWidth, minHeight) / totalPx);
112
- const currentSizes = normalizeSplitSizes(split.sizes, split.children.length);
113
- const clamped = clampAdjacentPair(nextSizes, minSizes, index);
114
- const fitted = fitNodeToAxisSize({
113
+ const minSizes = split.children.map((child) => getMinimumSize(child, split.orientation, paneMinSize) / totalPx);
114
+ const fitted = fitSplitToAxisSize({
115
115
  ...split,
116
- sizes: clamped
117
- }, split.orientation, totalPx, minWidth, minHeight);
118
- if (fitted.kind !== "split" || sizesEqual(fitted.sizes, currentSizes)) return split;
119
- return fitted;
116
+ sizes: clampAdjacentPair(nextSizes, minSizes, index)
117
+ }, split.orientation, totalPx, paneMinSize);
118
+ return sizesEqual(fitted.sizes, normalizeSplitSizes(split.sizes, split.children.length)) ? split : fitted;
120
119
  }
121
120
  function sizesEqual(a, b) {
122
- if (a.length !== b.length) return false;
123
- return a.every((value, index) => value === b[index]);
124
- }
125
- function fitNodeToAxisSize(node, direction, axisSize, minWidth, minHeight) {
126
- if (node.kind === "pane") return node;
127
- if (node.orientation !== direction) {
128
- let changed = false;
129
- const children = node.children.map((child) => {
130
- const nextChild = fitNodeToAxisSize(child, direction, axisSize, minWidth, minHeight);
131
- changed ||= nextChild !== child;
132
- return nextChild;
133
- });
134
- return changed ? {
135
- ...node,
136
- children
137
- } : node;
138
- }
139
- const sizes = normalizeSplitSizes(node.sizes, node.children.length);
140
- const handleTotal = Math.max(0, node.children.length - 1) * 3;
141
- const contentSize = Math.max(0, axisSize - handleTotal);
142
- const fittedSizes = fitSizesToMinimums(sizes, node.children.map((child) => getMinimumSize(child, direction, minWidth, minHeight)), contentSize);
143
- let changed = !sizesEqual(fittedSizes, sizes);
144
- const children = node.children.map((child, index) => {
145
- const nextChild = fitNodeToAxisSize(child, direction, contentSize * (fittedSizes[index] ?? 0), minWidth, minHeight);
121
+ return a.length === b.length && a.every((value, index) => value === b[index]);
122
+ }
123
+ function fitSplitToAxisSize(split, direction, axisSize, paneMinSize) {
124
+ const sameAxis = split.orientation === direction;
125
+ const contentSize = Math.max(0, axisSize - getHandlesSize(split));
126
+ const normalized = normalizeSplitSizes(split.sizes, split.children.length);
127
+ const sizes = sameAxis ? fitSizesToMinimums(normalized, split.children.map((child) => getMinimumSize(child, direction, paneMinSize)), contentSize) : split.sizes;
128
+ let changed = sameAxis && !sizesEqual(sizes, normalized);
129
+ const children = split.children.map((child, index) => {
130
+ if (child.kind === "pane") return child;
131
+ const nextChild = fitSplitToAxisSize(child, direction, sameAxis ? contentSize * (sizes[index] ?? 0) : axisSize, paneMinSize);
146
132
  changed ||= nextChild !== child;
147
133
  return nextChild;
148
134
  });
149
135
  return changed ? {
150
- ...node,
136
+ ...split,
151
137
  children,
152
- sizes: fittedSizes
153
- } : node;
138
+ sizes
139
+ } : split;
154
140
  }
155
141
  function fitSizesToMinimums(sizes, minSizes, contentSize) {
156
142
  const normalized = normalizeSplitSizes(sizes, sizes.length);
157
143
  if (contentSize <= 0) return normalized;
158
- if (normalized.map((size) => size * contentSize).every((size, index) => size >= (minSizes[index] ?? 0))) return normalized;
144
+ if (normalized.every((size, index) => size * contentSize >= (minSizes[index] ?? 0))) return normalized;
159
145
  const out = Array.from({ length: normalized.length }, () => 0);
160
146
  const fixed = Array.from({ length: normalized.length }, () => false);
161
147
  let remainingSize = contentSize;
162
148
  let remainingWeight = normalized.reduce((sum, size) => sum + size, 0);
149
+ const shareOf = (index) => remainingSize * (remainingWeight > 0 ? normalized[index] / remainingWeight : 0);
163
150
  let changed = true;
164
151
  while (changed) {
165
152
  changed = false;
166
153
  for (let index = 0; index < normalized.length; index += 1) {
167
- if (fixed[index]) continue;
168
- const weight = remainingWeight > 0 ? normalized[index] / remainingWeight : 0;
169
- const allocated = remainingSize * weight;
170
154
  const minSize = minSizes[index] ?? 0;
171
- if (allocated < minSize) {
172
- out[index] = minSize;
173
- fixed[index] = true;
174
- remainingSize -= minSize;
175
- remainingWeight -= normalized[index];
176
- changed = true;
177
- }
155
+ if (fixed[index] || shareOf(index) >= minSize) continue;
156
+ out[index] = minSize;
157
+ fixed[index] = true;
158
+ remainingSize -= minSize;
159
+ remainingWeight -= normalized[index];
160
+ changed = true;
178
161
  }
179
162
  }
180
- for (let index = 0; index < normalized.length; index += 1) {
181
- if (fixed[index]) continue;
182
- const weight = remainingWeight > 0 ? normalized[index] / remainingWeight : 0;
183
- out[index] = Math.max(0, remainingSize * weight);
184
- }
163
+ for (let index = 0; index < normalized.length; index += 1) if (!fixed[index]) out[index] = Math.max(0, shareOf(index));
185
164
  const total = out.reduce((sum, size) => sum + size, 0);
186
- if (total <= 0) return normalized;
187
- return out.map((size) => size / total);
165
+ return total <= 0 ? normalized : out.map((size) => size / total);
188
166
  }
189
167
  function clampAdjacentPair(sizes, minSizes, index) {
190
168
  const out = [...sizes];
191
169
  const pairTotal = out[index] + out[index + 1];
192
170
  const leftMin = minSizes[index] ?? 0;
193
- const rightMin = minSizes[index + 1] ?? 0;
194
- const maxLeft = Math.max(leftMin, pairTotal - rightMin);
171
+ const maxLeft = Math.max(leftMin, pairTotal - (minSizes[index + 1] ?? 0));
195
172
  out[index] = Math.min(Math.max(out[index], leftMin), maxLeft);
196
173
  out[index + 1] = pairTotal - out[index];
197
174
  return normalizeSplitSizes(out, out.length);
198
175
  }
199
176
  //#endregion
200
- //#region core/src/layout/types.ts
201
- const cardinalDirections = [
202
- "left",
203
- "right",
204
- "up",
205
- "down"
206
- ];
207
- let PaneCommandCapability = /* @__PURE__ */ function(PaneCommandCapability) {
208
- PaneCommandCapability["ResizeX"] = "canResizeX";
209
- PaneCommandCapability["ResizeY"] = "canResizeY";
210
- PaneCommandCapability["Remove"] = "canRemove";
211
- PaneCommandCapability["SplitHorizontal"] = "canSplitHorizontal";
212
- PaneCommandCapability["SplitVertical"] = "canSplitVertical";
213
- PaneCommandCapability["SwapX"] = "canSwapX";
214
- PaneCommandCapability["SwapY"] = "canSwapY";
215
- PaneCommandCapability["Focus"] = "canFocus";
216
- return PaneCommandCapability;
217
- }({});
218
- //#endregion
219
177
  //#region core/src/layout/tree.ts
220
- function buildLayoutIndex(root) {
221
- const index = {
222
- nodeById: /* @__PURE__ */ new Map(),
223
- paneNodeByPaneId: /* @__PURE__ */ new Map(),
224
- parentByNodeId: /* @__PURE__ */ new Map()
225
- };
226
- visit(root, null);
227
- return index;
228
- function visit(node, parent) {
229
- index.nodeById.set(node.id, node);
230
- index.parentByNodeId.set(node.id, parent);
231
- if (node.kind === "pane") {
232
- index.paneNodeByPaneId.set(node.paneId, node);
233
- return;
234
- }
235
- for (const child of node.children) visit(child, node);
178
+ function findNode(root, nodeId) {
179
+ if (root.id === nodeId) return root;
180
+ if (root.kind === "pane") return null;
181
+ for (const child of root.children) {
182
+ const node = findNode(child, nodeId);
183
+ if (node) return node;
236
184
  }
185
+ return null;
237
186
  }
238
187
  function findPaneNode(root, paneId) {
239
188
  if (!paneId) return null;
@@ -244,12 +193,14 @@ function findPaneNode(root, paneId) {
244
193
  }
245
194
  return null;
246
195
  }
247
- function findSplitNode(root, splitId) {
248
- if (root.kind === "pane") return null;
249
- if (root.id === splitId) return root;
250
- for (const child of root.children) {
251
- const split = findSplitNode(child, splitId);
252
- if (split) return split;
196
+ function findPanePath(root, paneId) {
197
+ if (root.kind === "pane") return root.paneId === paneId ? [] : null;
198
+ for (const [childIndex, child] of root.children.entries()) {
199
+ const path = findPanePath(child, paneId);
200
+ if (path) return [{
201
+ split: root,
202
+ childIndex
203
+ }, ...path];
253
204
  }
254
205
  return null;
255
206
  }
@@ -274,19 +225,11 @@ function updatePane(root, paneId, update) {
274
225
  return transformLayout(root, (node) => node.kind === "pane" && node.paneId === paneId ? update(node) : node);
275
226
  }
276
227
  function markFocusedPanePath(root, paneId) {
277
- const index = buildLayoutIndex(root);
278
- const pane = index.paneNodeByPaneId.get(paneId);
279
- if (!pane) return root;
280
- const path = /* @__PURE__ */ new Map();
281
- let childId = pane.id;
282
- let parent = index.parentByNodeId.get(childId);
283
- while (parent) {
284
- path.set(parent.id, childId);
285
- childId = parent.id;
286
- parent = index.parentByNodeId.get(childId);
287
- }
228
+ const path = paneId ? findPanePath(root, paneId) : null;
229
+ if (!path) return root;
230
+ const focusedChildIds = new Map(path.map(({ split, childIndex }) => [split.id, split.children[childIndex].id]));
288
231
  return transformLayout(root, (node) => {
289
- const focusedChildId = path.get(node.id);
232
+ const focusedChildId = focusedChildIds.get(node.id);
290
233
  return node.kind === "split" && focusedChildId !== void 0 && node.lastFocusedChildId !== focusedChildId ? {
291
234
  ...node,
292
235
  lastFocusedChildId: focusedChildId
@@ -297,15 +240,14 @@ function removePaneNode(node, paneId) {
297
240
  if (node.kind === "pane") return node.paneId === paneId ? null : node;
298
241
  const children = [];
299
242
  const sizes = [];
300
- for (let i = 0; i < node.children.length; i += 1) {
301
- const child = removePaneNode(node.children[i], paneId);
302
- if (child) {
303
- children.push(child);
304
- sizes.push(node.sizes[i] ?? 1);
243
+ node.children.forEach((child, index) => {
244
+ const nextChild = removePaneNode(child, paneId);
245
+ if (nextChild) {
246
+ children.push(nextChild);
247
+ sizes.push(node.sizes[index] ?? 1);
305
248
  }
306
- }
307
- if (children.length === 0) return null;
308
- if (children.length === 1) return children[0];
249
+ });
250
+ if (children.length <= 1) return children[0] ?? null;
309
251
  return {
310
252
  ...node,
311
253
  children,
@@ -313,112 +255,66 @@ function removePaneNode(node, paneId) {
313
255
  };
314
256
  }
315
257
  //#endregion
316
- //#region core/src/layout/spatial.ts
258
+ //#region core/src/layout/types.ts
259
+ let PaneCommandCapability = /* @__PURE__ */ function(PaneCommandCapability) {
260
+ PaneCommandCapability["ResizeX"] = "canResizeX";
261
+ PaneCommandCapability["ResizeY"] = "canResizeY";
262
+ PaneCommandCapability["Remove"] = "canRemove";
263
+ PaneCommandCapability["SplitHorizontal"] = "canSplitHorizontal";
264
+ PaneCommandCapability["SplitVertical"] = "canSplitVertical";
265
+ PaneCommandCapability["SwapX"] = "canSwapX";
266
+ PaneCommandCapability["SwapY"] = "canSwapY";
267
+ PaneCommandCapability["Focus"] = "canFocus";
268
+ return PaneCommandCapability;
269
+ }({});
270
+ //#endregion
271
+ //#region core/src/layout/navigation.ts
317
272
  function isHorizontalDirection(direction) {
318
273
  return direction === "left" || direction === "right";
319
274
  }
320
- function isRectInDirection(rect, activeRect, direction) {
321
- const epsilon = .001;
322
- if (direction === "right") return rect.x >= activeRect.x + activeRect.width - epsilon;
323
- if (direction === "left") return rect.x + rect.width <= activeRect.x + epsilon;
324
- if (direction === "down") return rect.y >= activeRect.y + activeRect.height - epsilon;
325
- return rect.y + rect.height <= activeRect.y + epsilon;
326
- }
327
- function getEnteringEdge(rect, direction) {
328
- if (direction === "right") return rect.x;
329
- if (direction === "left") return rect.x + rect.width;
330
- if (direction === "down") return rect.y;
331
- return rect.y + rect.height;
332
- }
333
- function compareEnteringEdge(first, second, direction) {
334
- return direction === "left" || direction === "up" ? second - first : first - second;
335
- }
336
- function getPerpendicularCenter(rect, direction) {
337
- const center = getRectCenter(rect);
338
- return isHorizontalDirection(direction) ? center.y : center.x;
339
- }
340
- function getRectCenter(rect) {
341
- return {
342
- x: rect.x + rect.width / 2,
343
- y: rect.y + rect.height / 2
344
- };
275
+ function isForwardDirection(direction) {
276
+ return direction === "right" || direction === "down";
345
277
  }
346
- function getCenterDistance(rect, center) {
347
- const rectCenter = getRectCenter(rect);
348
- return Math.abs(rectCenter.x - center.x) + Math.abs(rectCenter.y - center.y);
278
+ function nearestSplitsOnAxis(path, direction) {
279
+ const horizontal = isHorizontalDirection(direction);
280
+ return path.filter(({ split }) => split.orientation === "horizontal" === horizontal).toReversed();
349
281
  }
350
- //#endregion
351
- //#region core/src/layout/navigation.ts
352
282
  function findPaneInDirection(root, layout, paneId, direction) {
353
- const index = buildLayoutIndex(root);
354
- const paneNode = index.paneNodeByPaneId.get(paneId);
355
- if (!paneNode) return null;
356
283
  const activePane = layout.panes.find((pane) => pane.paneId === paneId);
357
- if (!activePane) return null;
358
- let currentId = paneNode.id;
359
- let parent = index.parentByNodeId.get(currentId) ?? null;
360
- while (parent) {
361
- const sibling = findDirectionalSibling(parent, currentId, direction);
362
- if (sibling) return findTargetPaneInSubtree(sibling, layout.panes, activePane, direction);
363
- currentId = parent.id;
364
- parent = index.parentByNodeId.get(currentId) ?? null;
284
+ const path = findPanePath(root, paneId);
285
+ if (!activePane || !path) return null;
286
+ for (const { split, childIndex } of nearestSplitsOnAxis(path, direction)) {
287
+ const sibling = split.children[childIndex + (isForwardDirection(direction) ? 1 : -1)];
288
+ if (!sibling) continue;
289
+ const siblingPaneIds = new Set(collectPaneIds(sibling));
290
+ return findClosestPane(layout.panes.filter((pane) => siblingPaneIds.has(pane.paneId)), activePane, direction, (candidateId) => getFocusMemoryRank(sibling, candidateId));
365
291
  }
366
292
  return null;
367
293
  }
368
294
  function findPaneForFocusCommand(root, layout, paneId, direction, overflow) {
369
295
  const activePane = layout.panes.find((pane) => pane.paneId === paneId);
370
296
  if (!activePane) return null;
371
- const index = buildLayoutIndex(root);
372
- const candidates = layout.panes.filter((pane) => pane.paneId !== paneId && index.paneNodeByPaneId.get(pane.paneId)?.["canFocus"] !== false);
373
- const target = sortFocusCandidates(candidates.filter((pane) => isRectInDirection(pane.rect, activePane.rect, direction)), activePane, direction)[0]?.paneId ?? null;
297
+ const candidates = layout.panes.filter((pane) => pane.paneId !== paneId && findPaneNode(root, pane.paneId)?.["canFocus"] !== false);
298
+ const target = findClosestPane(candidates.filter((pane) => isRectInDirection(pane.rect, activePane.rect, direction)), activePane, direction, () => 0);
374
299
  if (target || !overflow) return target;
375
- return sortOverflowCandidates(candidates, direction)[0]?.paneId ?? null;
376
- }
377
- function sortFocusCandidates(candidates, activePane, direction) {
378
- const activeCenter = getRectCenter(activePane.rect);
379
- return [...candidates].sort((first, second) => {
380
- const edgeDelta = compareEnteringEdge(getEnteringEdge(first.rect, direction), getEnteringEdge(second.rect, direction), direction);
381
- if (edgeDelta !== 0) return edgeDelta;
382
- const firstPerpendicular = Math.abs(getPerpendicularCenter(first.rect, direction) - getPerpendicularCenter(activePane.rect, direction));
383
- const secondPerpendicular = Math.abs(getPerpendicularCenter(second.rect, direction) - getPerpendicularCenter(activePane.rect, direction));
384
- if (firstPerpendicular !== secondPerpendicular) return firstPerpendicular - secondPerpendicular;
385
- return getCenterDistance(first.rect, activeCenter) - getCenterDistance(second.rect, activeCenter);
386
- });
387
- }
388
- function sortOverflowCandidates(candidates, direction) {
389
- return [...candidates].sort((first, second) => {
390
- if (direction === "right") return first.rect.x - second.rect.x;
391
- if (direction === "left") return second.rect.x + second.rect.width - (first.rect.x + first.rect.width);
392
- if (direction === "down") return first.rect.y - second.rect.y;
393
- return second.rect.y + second.rect.height - (first.rect.y + first.rect.height);
300
+ return candidates.toSorted((first, second) => enteringEdgeOrder(first.rect, direction) - enteringEdgeOrder(second.rect, direction))[0]?.paneId ?? null;
301
+ }
302
+ function findClosestPane(candidates, activePane, direction, focusMemoryRank) {
303
+ const activeCenter = rectCenter(activePane.rect);
304
+ const ranked = candidates.map((pane) => {
305
+ const center = rectCenter(pane.rect);
306
+ const dx = Math.abs(center.x - activeCenter.x);
307
+ const dy = Math.abs(center.y - activeCenter.y);
308
+ return {
309
+ paneId: pane.paneId,
310
+ edge: enteringEdgeOrder(pane.rect, direction),
311
+ memory: focusMemoryRank(pane.paneId),
312
+ perpendicular: isHorizontalDirection(direction) ? dy : dx,
313
+ centerDistance: dx + dy
314
+ };
394
315
  });
395
- }
396
- function findDirectionalSibling(parent, childId, direction) {
397
- const childIndex = parent.children.findIndex((child) => child.id === childId);
398
- if (childIndex === -1) return null;
399
- const horizontal = direction === "left" || direction === "right";
400
- if (horizontal && parent.orientation === "horizontal") {
401
- if (direction === "right") return parent.children[childIndex + 1] ?? null;
402
- return parent.children[childIndex - 1] ?? null;
403
- }
404
- if (!horizontal && parent.orientation === "vertical") {
405
- if (direction === "down") return parent.children[childIndex + 1] ?? null;
406
- return parent.children[childIndex - 1] ?? null;
407
- }
408
- return null;
409
- }
410
- function findTargetPaneInSubtree(subtree, panes, activePane, direction) {
411
- const subtreePaneIds = new Set(collectPaneIds(subtree));
412
- const candidates = panes.filter((pane) => subtreePaneIds.has(pane.paneId));
413
- if (candidates.length === 0) return null;
414
- const activeCenter = getRectCenter(activePane.rect);
415
- return candidates.map((pane) => ({
416
- pane,
417
- edge: getEnteringEdge(pane.rect, direction),
418
- perpendicularDistance: Math.abs(getPerpendicularCenter(pane.rect, direction) - getPerpendicularCenter(activePane.rect, direction)),
419
- focusMemoryRank: getFocusMemoryRank(subtree, pane.paneId),
420
- centerDistance: getCenterDistance(pane.rect, activeCenter)
421
- })).sort((first, second) => compareEnteringEdge(first.edge, second.edge, direction) || first.focusMemoryRank - second.focusMemoryRank || first.perpendicularDistance - second.perpendicularDistance || first.centerDistance - second.centerDistance)[0].pane.paneId;
316
+ ranked.sort((first, second) => first.edge - second.edge || first.memory - second.memory || first.perpendicular - second.perpendicular || first.centerDistance - second.centerDistance);
317
+ return ranked[0]?.paneId ?? null;
422
318
  }
423
319
  function getFocusMemoryRank(subtree, paneId) {
424
320
  if (subtree.kind === "pane") return Number.POSITIVE_INFINITY;
@@ -428,24 +324,24 @@ function getFocusMemoryRank(subtree, paneId) {
428
324
  const nestedRank = getFocusMemoryRank(rememberedChild, paneId);
429
325
  return Number.isFinite(nestedRank) ? nestedRank : 1;
430
326
  }
431
- function resolvePaneResizeBoundary(index, nodeId, direction) {
432
- let currentId = nodeId;
433
- let parent = index.parentByNodeId.get(currentId) ?? null;
434
- while (parent) {
435
- const childIndex = parent.children.findIndex((child) => child.id === currentId);
436
- if (childIndex === -1) return null;
437
- if (isHorizontalDirection(direction) === (parent.orientation === "horizontal")) {
438
- const boundaryIndex = childIndex > 0 ? childIndex - 1 : childIndex < parent.children.length - 1 ? childIndex : null;
439
- if (boundaryIndex !== null) return {
440
- splitId: parent.id,
441
- index: boundaryIndex,
442
- deltaPxSign: direction === "right" || direction === "down" ? 1 : -1
443
- };
444
- }
445
- currentId = parent.id;
446
- parent = index.parentByNodeId.get(currentId) ?? null;
447
- }
448
- return null;
327
+ function isRectInDirection(rect, activeRect, direction) {
328
+ const epsilon = .001;
329
+ if (direction === "right") return rect.x >= activeRect.x + activeRect.width - epsilon;
330
+ if (direction === "left") return rect.x + rect.width <= activeRect.x + epsilon;
331
+ if (direction === "down") return rect.y >= activeRect.y + activeRect.height - epsilon;
332
+ return rect.y + rect.height <= activeRect.y + epsilon;
333
+ }
334
+ function enteringEdgeOrder(rect, direction) {
335
+ if (direction === "right") return rect.x;
336
+ if (direction === "left") return -(rect.x + rect.width);
337
+ if (direction === "down") return rect.y;
338
+ return -(rect.y + rect.height);
339
+ }
340
+ function rectCenter(rect) {
341
+ return {
342
+ x: rect.x + rect.width / 2,
343
+ y: rect.y + rect.height / 2
344
+ };
449
345
  }
450
346
  //#endregion
451
347
  //#region core/src/validation.ts
@@ -459,10 +355,6 @@ var FocusGridStateValidationException = class extends Error {
459
355
  this.name = "FocusGridStateValidationException";
460
356
  }
461
357
  };
462
- function assertValidFocusGridControllerState(input) {
463
- const result = validateFocusGridControllerState(input);
464
- if (!result.ok) throw new FocusGridStateValidationException(result.errors);
465
- }
466
358
  function validateFocusGridControllerState(input) {
467
359
  const errors = [];
468
360
  const nodeIds = /* @__PURE__ */ new Set();
@@ -478,9 +370,6 @@ function validateFocusGridControllerState(input) {
478
370
  function fields(value, path, allowed, meta = {}) {
479
371
  for (const field of Object.keys(value)) if (!allowed.has(field)) add("unknown-field", `${path}.${field}`, `Unknown field "${field}".`, meta);
480
372
  }
481
- function size(value, path, label, meta = {}) {
482
- if (!isSize(value)) add("invalid-number", path, `${label} must be a finite, non-negative number.`, meta);
483
- }
484
373
  function id(value, seen, kind, path, meta) {
485
374
  const label = kind === "pane" ? "Pane" : "Node";
486
375
  if (typeof value !== "string" || value.length === 0) add(`invalid-${kind}-id`, path, `${label} id must be a non-empty string.`, meta);
@@ -524,7 +413,7 @@ function validateFocusGridControllerState(input) {
524
413
  });
525
414
  }
526
415
  if (value.lastFocusedChildId !== void 0 && typeof value.lastFocusedChildId !== "string") add("invalid-last-focused-child", `${path}.lastFocusedChildId`, "lastFocusedChildId must be a node id string when provided.", meta);
527
- if (typeof value.lastFocusedChildId === "string" && Array.isArray(value.children) && !value.children.some((child) => isRecord(child) && child.id === value.lastFocusedChildId)) add("invalid-last-focused-child", `${path}.lastFocusedChildId`, "lastFocusedChildId must reference one of the split's direct children.", {
416
+ else if (typeof value.lastFocusedChildId === "string" && Array.isArray(value.children) && !value.children.some((child) => isRecord(child) && child.id === value.lastFocusedChildId)) add("invalid-last-focused-child", `${path}.lastFocusedChildId`, "lastFocusedChildId must reference one of the split's direct children.", {
528
417
  ...meta,
529
418
  nodeId: value.lastFocusedChildId
530
419
  });
@@ -542,7 +431,7 @@ function validateFocusGridControllerState(input) {
542
431
  else {
543
432
  fields(input.container, "$.container", CONTAINER_FIELDS);
544
433
  for (const key of CONTAINER_FIELDS) if (!(key in input.container)) add("missing-field", `$.container.${key}`, `${key} is required.`);
545
- else size(input.container[key], `$.container.${key}`, `container ${key}`);
434
+ else if (!isSize(input.container[key])) add("invalid-number", `$.container.${key}`, `container ${key} must be a finite, non-negative number.`);
546
435
  }
547
436
  }
548
437
  return errors.length ? {
@@ -593,7 +482,8 @@ var FocusGridController = class {
593
482
  listeners = /* @__PURE__ */ new Set();
594
483
  constructor({ paneDefaults = {}, minWidth = 0, minHeight = 0, directionalFocusOverflow = false, ...state }, domController) {
595
484
  this.domController = domController;
596
- assertValidFocusGridControllerState(state);
485
+ const validation = validateFocusGridControllerState(state);
486
+ if (!validation.ok) throw new FocusGridStateValidationException(validation.errors);
597
487
  if (![minWidth, minHeight].every((value) => Number.isFinite(value) && value >= 0)) throw new RangeError("Minimum pane dimensions must be finite, non-negative numbers.");
598
488
  this.minWidth = minWidth;
599
489
  this.minHeight = minHeight;
@@ -605,7 +495,6 @@ var FocusGridController = class {
605
495
  root
606
496
  };
607
497
  }
608
- /** Computed render data; stable until the next committed change. */
609
498
  getLayout() {
610
499
  return this.cachedLayout ??= computeLayout(this.currentState);
611
500
  }
@@ -617,8 +506,8 @@ var FocusGridController = class {
617
506
  return { ...this.currentState.container };
618
507
  }
619
508
  getSplitSizes(splitId) {
620
- const split = findSplitNode(this.currentState.root, splitId);
621
- return split ? [...split.sizes] : null;
509
+ const split = findNode(this.currentState.root, splitId);
510
+ return split?.kind === "split" ? [...split.sizes] : null;
622
511
  }
623
512
  splitActive(side) {
624
513
  const pane = findPaneNode(this.currentState.root, this.currentState.activePaneId);
@@ -654,32 +543,36 @@ var FocusGridController = class {
654
543
  deltaPx
655
544
  }) : false;
656
545
  }
657
- split(paneNodeId, props) {
546
+ split(paneNodeId, { side, newPaneId, newPaneNodeId, splitId: requestedSplitId, preserveActivePane, ...capabilities }) {
658
547
  const state = this.currentState;
659
- const index = buildLayoutIndex(state.root);
660
- const target = index.nodeById.get(paneNodeId);
548
+ const target = findNode(state.root, paneNodeId);
661
549
  if (target?.kind !== "pane") return null;
662
- const paneId = props.newPaneId ?? createId("pane");
663
- const id = props.newPaneNodeId ?? createId("node");
664
- const splitId = props.splitId ?? createId("split");
665
- if (index.paneNodeByPaneId.has(paneId) || index.nodeById.has(id) || index.nodeById.has(splitId) || id === splitId) return null;
666
- const { side, newPaneId, newPaneNodeId, splitId: suppliedSplitId, preserveActivePane, ...paneProps } = props;
550
+ const paneId = newPaneId ?? createId("pane");
551
+ const id = newPaneNodeId ?? createId("node");
552
+ const splitId = requestedSplitId ?? createId("split");
553
+ if (findPaneNode(state.root, paneId) || findNode(state.root, id) || findNode(state.root, splitId) || id === splitId) return null;
667
554
  const pane = withPaneDefaults({
668
555
  kind: "pane",
669
556
  id,
670
557
  paneId,
671
- ...paneProps
558
+ ...capabilities
672
559
  }, this.paneDefaults);
673
- const root = updatePane(state.root, target.paneId, () => ({
560
+ const horizontal = isHorizontalDirection(side);
561
+ const split = {
674
562
  kind: "split",
675
563
  id: splitId,
676
- orientation: isHorizontalDirection(side) ? "horizontal" : "vertical",
677
- children: side === "left" || side === "up" ? [pane, target] : [target, pane],
564
+ orientation: horizontal ? "horizontal" : "vertical",
565
+ children: isForwardDirection(side) ? [target, pane] : [pane, target],
678
566
  sizes: [.5, .5]
679
- }));
567
+ };
568
+ const paneMinSize = horizontal ? this.minWidth : this.minHeight;
569
+ const rect = this.getLayout().rectByNodeId.get(target.id);
570
+ const available = horizontal ? rect.width : rect.height;
571
+ if (paneMinSize > 0 && available < getMinimumSize(split, split.orientation, paneMinSize)) return null;
572
+ const root = updatePane(state.root, target.paneId, () => split);
680
573
  const activePaneId = preserveActivePane ? state.activePaneId : paneId;
681
574
  this.commit({
682
- root: activePaneId ? markFocusedPanePath(root, activePaneId) : root,
575
+ root: markFocusedPanePath(root, activePaneId),
683
576
  activePaneId
684
577
  });
685
578
  return paneId;
@@ -691,16 +584,15 @@ var FocusGridController = class {
691
584
  const root = removePaneNode(state.root, paneId);
692
585
  const activePaneId = state.activePaneId === paneId ? collectPaneIds(root)[0] : state.activePaneId;
693
586
  return this.commit({
694
- root: activePaneId ? markFocusedPanePath(root, activePaneId) : root,
587
+ root: markFocusedPanePath(root, activePaneId),
695
588
  activePaneId
696
589
  });
697
590
  }
698
591
  swap(firstPaneId, secondPaneId) {
699
592
  if (firstPaneId === secondPaneId) return false;
700
593
  const state = this.currentState;
701
- const index = buildLayoutIndex(state.root);
702
- const first = index.paneNodeByPaneId.get(firstPaneId);
703
- const second = index.paneNodeByPaneId.get(secondPaneId);
594
+ const first = findPaneNode(state.root, firstPaneId);
595
+ const second = findPaneNode(state.root, secondPaneId);
704
596
  if (!first || !second) return false;
705
597
  const root = transformLayout(state.root, (node) => {
706
598
  if (node.id === first.id) return {
@@ -713,23 +605,22 @@ var FocusGridController = class {
713
605
  };
714
606
  return node;
715
607
  });
716
- return this.commit({ root: state.activePaneId ? markFocusedPanePath(root, state.activePaneId) : root });
717
- }
718
- resize(paneId, props) {
719
- const index = buildLayoutIndex(this.currentState.root);
720
- const pane = index.paneNodeByPaneId.get(paneId);
721
- if (!pane) return false;
722
- const boundary = resolvePaneResizeBoundary(index, pane.id, props.direction);
723
- return boundary ? this.resizeHandle(boundary.splitId, {
724
- index: boundary.index,
725
- deltaPx: boundary.deltaPxSign * props.deltaPx
726
- }) : false;
608
+ return this.commit({ root: markFocusedPanePath(root, state.activePaneId) });
609
+ }
610
+ resize(paneId, { direction, deltaPx }) {
611
+ const path = findPanePath(this.currentState.root, paneId);
612
+ const nearest = path ? nearestSplitsOnAxis(path, direction)[0] : void 0;
613
+ if (!nearest) return false;
614
+ return this.resizeHandle(nearest.split.id, {
615
+ index: Math.max(0, nearest.childIndex - 1),
616
+ deltaPx: isForwardDirection(direction) ? deltaPx : -deltaPx
617
+ });
727
618
  }
728
619
  resizeHandle(splitId, props) {
729
620
  const state = this.currentState;
730
621
  const rect = this.getLayout().rectByNodeId.get(splitId);
731
622
  if (!rect) return false;
732
- const root = transformLayout(state.root, (node) => node.kind === "split" && node.id === splitId ? resizeSplit(node, node.orientation === "horizontal" ? rect.width : rect.height, props.index, props.deltaPx, props.snapshotSizes, this.minWidth, this.minHeight) : node);
623
+ const root = transformLayout(state.root, (node) => node.kind === "split" && node.id === splitId ? resizeSplit(node, node.orientation === "horizontal" ? rect.width : rect.height, props.index, props.deltaPx, props.snapshotSizes, node.orientation === "horizontal" ? this.minWidth : this.minHeight) : node);
733
624
  return this.commit({ root });
734
625
  }
735
626
  focus(paneId) {
@@ -742,10 +633,10 @@ var FocusGridController = class {
742
633
  });
743
634
  }
744
635
  updatePane(paneId, patch) {
745
- const root = updatePane(this.currentState.root, paneId, (pane) => Object.entries(patch).every(([key, value]) => Object.is(pane[key], value)) ? pane : Object.fromEntries(Object.entries({
636
+ const root = updatePane(this.currentState.root, paneId, (pane) => keepPaneIfUnchanged(pane, withoutUndefined({
746
637
  ...pane,
747
638
  ...patch
748
- }).filter(([, value]) => value !== void 0)));
639
+ })));
749
640
  return this.commit({ root });
750
641
  }
751
642
  setContainerSize(width, height) {
@@ -796,12 +687,17 @@ var FocusGridController = class {
796
687
  }
797
688
  };
798
689
  function withPaneDefaults(pane, defaults) {
799
- const definedPane = Object.fromEntries(Object.entries(pane).filter(([, value]) => value !== void 0));
800
- const next = Object.fromEntries(Object.entries({
690
+ return keepPaneIfUnchanged(pane, withoutUndefined({
801
691
  ...defaults,
802
- ...definedPane
803
- }).filter(([, value]) => value !== void 0));
804
- return Object.keys(next).length === Object.keys(pane).length && Object.entries(next).every(([key, value]) => Object.is(pane[key], value)) ? pane : next;
692
+ ...withoutUndefined(pane)
693
+ }));
694
+ }
695
+ function withoutUndefined(value) {
696
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0));
697
+ }
698
+ function keepPaneIfUnchanged(pane, next) {
699
+ const keys = Object.keys(next);
700
+ return keys.length === Object.keys(pane).length && keys.every((key) => Object.is(pane[key], next[key])) ? pane : next;
805
701
  }
806
702
  //#endregion
807
- export { FocusGridController, FocusGridStateValidationException, PaneCommandCapability, cardinalDirections, validateFocusGridControllerState };
703
+ export { FocusGridController, FocusGridStateValidationException, PaneCommandCapability, validateFocusGridControllerState };