@window-splitter/state 0.2.2

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 (52) hide show
  1. package/.tshy/build.json +8 -0
  2. package/.tshy/commonjs.json +17 -0
  3. package/.tshy/esm.json +16 -0
  4. package/.turbo/turbo-build.log +5 -0
  5. package/.turbo/turbo-lint.log +5 -0
  6. package/.turbo/turbo-test.log +278 -0
  7. package/CHANGELOG.md +191 -0
  8. package/README.md +13 -0
  9. package/coverage/base.css +224 -0
  10. package/coverage/block-navigation.js +87 -0
  11. package/coverage/clover.xml +350 -0
  12. package/coverage/coverage-final.json +2 -0
  13. package/coverage/favicon.png +0 -0
  14. package/coverage/index.html +116 -0
  15. package/coverage/index.ts.html +4627 -0
  16. package/coverage/prettify.css +1 -0
  17. package/coverage/prettify.js +2 -0
  18. package/coverage/sort-arrow-sprite.png +0 -0
  19. package/coverage/sorter.js +196 -0
  20. package/dist/commonjs/index.d.ts +314 -0
  21. package/dist/commonjs/index.d.ts.map +1 -0
  22. package/dist/commonjs/index.js +932 -0
  23. package/dist/commonjs/index.js.map +1 -0
  24. package/dist/commonjs/machine.test.d.ts +5 -0
  25. package/dist/commonjs/machine.test.d.ts.map +1 -0
  26. package/dist/commonjs/machine.test.js +1038 -0
  27. package/dist/commonjs/machine.test.js.map +1 -0
  28. package/dist/commonjs/package.json +3 -0
  29. package/dist/commonjs/utils.test.d.ts +2 -0
  30. package/dist/commonjs/utils.test.d.ts.map +1 -0
  31. package/dist/commonjs/utils.test.js +79 -0
  32. package/dist/commonjs/utils.test.js.map +1 -0
  33. package/dist/esm/index.d.ts +314 -0
  34. package/dist/esm/index.d.ts.map +1 -0
  35. package/dist/esm/index.js +890 -0
  36. package/dist/esm/index.js.map +1 -0
  37. package/dist/esm/machine.test.d.ts +5 -0
  38. package/dist/esm/machine.test.d.ts.map +1 -0
  39. package/dist/esm/machine.test.js +1036 -0
  40. package/dist/esm/machine.test.js.map +1 -0
  41. package/dist/esm/package.json +3 -0
  42. package/dist/esm/utils.test.d.ts +2 -0
  43. package/dist/esm/utils.test.d.ts.map +1 -0
  44. package/dist/esm/utils.test.js +77 -0
  45. package/dist/esm/utils.test.js.map +1 -0
  46. package/eslint.config.js +3 -0
  47. package/package.json +79 -0
  48. package/src/index.ts +1514 -0
  49. package/src/machine.test.ts +1316 -0
  50. package/src/utils.test.ts +104 -0
  51. package/tsconfig.json +3 -0
  52. package/vitest.config.ts +16 -0
@@ -0,0 +1,932 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.groupMachine = void 0;
30
+ exports.isPanelData = isPanelData;
31
+ exports.isPanelHandle = isPanelHandle;
32
+ exports.initializePanel = initializePanel;
33
+ exports.parseUnit = parseUnit;
34
+ exports.getUnitPercentageValue = getUnitPercentageValue;
35
+ exports.getGroupSize = getGroupSize;
36
+ exports.getUnitPixelValue = getUnitPixelValue;
37
+ exports.getPanelWithId = getPanelWithId;
38
+ exports.getCollapsiblePanelForHandleId = getCollapsiblePanelForHandleId;
39
+ exports.buildTemplate = buildTemplate;
40
+ exports.prepareItems = prepareItems;
41
+ exports.commitLayout = commitLayout;
42
+ exports.dragHandlePayload = dragHandlePayload;
43
+ const rafz_1 = require("@react-spring/rafz");
44
+ const xstate_1 = require("xstate");
45
+ const invariant_1 = __importDefault(require("invariant"));
46
+ const easings = __importStar(require("d3-ease"));
47
+ // #region Constants
48
+ /** The default amount a user can `dragOvershoot` before the panel collapses */
49
+ const COLLAPSE_THRESHOLD = 50;
50
+ function makePercentUnit(value) {
51
+ return { type: "percent", value };
52
+ }
53
+ function makePixelUnit(value) {
54
+ return { type: "pixel", value };
55
+ }
56
+ function getCollapseAnimation(panel) {
57
+ let easeFn = collapseAnimations.linear;
58
+ let duration = 300;
59
+ if (panel.collapseAnimation) {
60
+ if (typeof panel.collapseAnimation === "string") {
61
+ easeFn = collapseAnimations[panel.collapseAnimation];
62
+ }
63
+ else if ("duration" in panel.collapseAnimation) {
64
+ duration = panel.collapseAnimation.duration ?? duration;
65
+ easeFn =
66
+ typeof panel.collapseAnimation.easing === "function"
67
+ ? panel.collapseAnimation.easing
68
+ : collapseAnimations[panel.collapseAnimation.easing];
69
+ }
70
+ }
71
+ return { ease: easeFn, duration };
72
+ }
73
+ const collapseAnimations = {
74
+ "ease-in-out": easings.easeQuadInOut,
75
+ bounce: easings.easeBackInOut,
76
+ linear: easings.easeLinear,
77
+ };
78
+ // #endregion
79
+ // #region Helpers
80
+ /** Assert that the provided event is one of the accepted types */
81
+ function isEvent(event, eventType) {
82
+ (0, invariant_1.default)(eventType.includes(event.type), `Invalid event type: ${eventType}. Expected: ${eventType.join(" | ")}`);
83
+ }
84
+ /** Determine if an item is a panel */
85
+ function isPanelData(value) {
86
+ return Boolean(value &&
87
+ typeof value === "object" &&
88
+ "type" in value &&
89
+ value.type === "panel");
90
+ }
91
+ /** Determine if an item is a panel handle */
92
+ function isPanelHandle(value) {
93
+ return Boolean(value &&
94
+ typeof value === "object" &&
95
+ "type" in value &&
96
+ value.type === "handle");
97
+ }
98
+ function initializePanel(item) {
99
+ const data = {
100
+ type: "panel",
101
+ min: parseUnit(item.min || "0px"),
102
+ max: item.max ? parseUnit(item.max) : "1fr",
103
+ collapsed: item.collapsible
104
+ ? (item.collapsed ?? item.defaultCollapsed ?? false)
105
+ : undefined,
106
+ collapsible: item.collapsible,
107
+ collapsedSize: parseUnit(item.collapsedSize ?? "0px"),
108
+ onCollapseChange: item.onCollapseChange,
109
+ collapseIsControlled: typeof item.collapsed !== "undefined",
110
+ sizeBeforeCollapse: undefined,
111
+ id: item.id,
112
+ collapseAnimation: item.collapseAnimation,
113
+ default: item.default ? parseUnit(item.default) : undefined,
114
+ };
115
+ return { ...data, currentValue: makePixelUnit(-1) };
116
+ }
117
+ /** Parse a `Unit` string or `clamp` value */
118
+ function parseUnit(unit) {
119
+ if (unit === "1fr") {
120
+ unit = "100%";
121
+ }
122
+ if (unit.endsWith("px")) {
123
+ return makePixelUnit(parseFloat(unit));
124
+ }
125
+ if (unit.endsWith("%")) {
126
+ return makePercentUnit(parseFloat(unit));
127
+ }
128
+ throw new Error(`Invalid unit: ${unit}`);
129
+ }
130
+ /** Convert a `Unit` to a percentage of the group size */
131
+ function getUnitPercentageValue(groupsSize, unit) {
132
+ if (unit.type === "pixel") {
133
+ return unit.value / groupsSize;
134
+ }
135
+ return unit.value;
136
+ }
137
+ function getGroupSize(context) {
138
+ return context.orientation === "horizontal"
139
+ ? context.size.width
140
+ : context.size.height;
141
+ }
142
+ /** Get the size of a panel in pixels */
143
+ function getUnitPixelValue(context, unit) {
144
+ const parsed = unit === "1fr" ? parseUnit(unit) : unit;
145
+ return parsed.type === "pixel"
146
+ ? parsed.value
147
+ : (parsed.value / 100) * getGroupSize(context);
148
+ }
149
+ /** Clamp a new `currentValue` given the panel's constraints. */
150
+ function clampUnit(context, item, value) {
151
+ return Math.min(Math.max(value, getUnitPixelValue(context, item.min)), getUnitPixelValue(context, item.max));
152
+ }
153
+ /** Get a panel with a particular ID. */
154
+ function getPanelWithId(context, panelId) {
155
+ const item = context.items.find((i) => i.id === panelId);
156
+ if (item && isPanelData(item)) {
157
+ return item;
158
+ }
159
+ throw new Error(`Expected panel with id: ${panelId}`);
160
+ }
161
+ /** Get a panel with a particular ID. */
162
+ function getPanelHandleIndex(context, handleId) {
163
+ const item = context.items.findIndex((i) => i.id === handleId);
164
+ if (item !== -1 && isPanelHandle(context.items[item])) {
165
+ return item;
166
+ }
167
+ throw new Error(`Expected panel handle with id: ${handleId}`);
168
+ }
169
+ /**
170
+ * Get the panel that's collapsible next to a resize handle.
171
+ * Will first check the left panel then the right.
172
+ */
173
+ function getCollapsiblePanelForHandleId(context, handleId) {
174
+ if (!context.items.length) {
175
+ throw new Error("No items in group");
176
+ }
177
+ const handleIndex = getPanelHandleIndex(context, handleId);
178
+ const panelBefore = context.items[handleIndex - 1];
179
+ const panelAfter = context.items[handleIndex + 1];
180
+ if (panelBefore && isPanelData(panelBefore) && panelBefore.collapsible) {
181
+ return panelBefore;
182
+ }
183
+ if (panelAfter && isPanelData(panelAfter) && panelAfter.collapsible) {
184
+ return panelAfter;
185
+ }
186
+ throw new Error(`No collapsible panel found for handle: ${handleId}`);
187
+ }
188
+ /**
189
+ * Get the handle closest to the target panel.
190
+ * This is used to simulate collapse/expand
191
+ */
192
+ function getHandleForPanelId(context, panelId) {
193
+ const panelIndex = context.items.findIndex((item) => item.id === panelId);
194
+ (0, invariant_1.default)(panelIndex !== -1, `Expected panel before: ${panelId}`);
195
+ let item = context.items[panelIndex + 1];
196
+ if (item && isPanelHandle(item)) {
197
+ return { item, direction: 1 };
198
+ }
199
+ item = context.items[panelIndex - 1];
200
+ if (item && isPanelHandle(item)) {
201
+ return { item, direction: -1 };
202
+ }
203
+ throw new Error(`Cant find handle for panel: ${panelId}`);
204
+ }
205
+ /** Given the specified order props and default order of the items, order the items */
206
+ function sortWithOrder(items) {
207
+ const defaultPlacement = {};
208
+ const takenPlacements = items
209
+ .map((i) => i.order)
210
+ .filter((i) => i !== undefined);
211
+ let defaultOrder = 0;
212
+ // Generate default orders for items that don't have it
213
+ for (const item of items) {
214
+ if (item.order === undefined) {
215
+ while (takenPlacements.includes(defaultOrder) ||
216
+ Object.values(defaultPlacement).includes(defaultOrder)) {
217
+ defaultOrder++;
218
+ }
219
+ defaultPlacement[item.id] = defaultOrder;
220
+ }
221
+ }
222
+ const withoutOrder = items.filter((i) => i.order === undefined);
223
+ const sortedWithOrder = items
224
+ .filter((i) => i.order !== undefined)
225
+ .sort((a, b) => a.order - b.order);
226
+ for (const item of sortedWithOrder) {
227
+ // insert item at order index
228
+ withoutOrder.splice(item.order, 0, item);
229
+ }
230
+ return withoutOrder;
231
+ }
232
+ /** Check if the panel has space available to add to */
233
+ function panelHasSpace(context, item) {
234
+ (0, invariant_1.default)(item.currentValue.type === "pixel", `panelHasSpace only works with number values: ${item.id} ${item.currentValue}`);
235
+ if (item.collapsible && !item.collapsed) {
236
+ return true;
237
+ }
238
+ return item.currentValue.value > getUnitPixelValue(context, item.min);
239
+ }
240
+ /** Search in a `direction` for a panel that still has space to expand. */
241
+ function findPanelWithSpace(context, items, start, direction, disregardCollapseBuffer) {
242
+ const slice = direction === -1 ? items.slice(0, start + 1).reverse() : items.slice(start);
243
+ for (const panel of slice) {
244
+ if (!isPanelData(panel)) {
245
+ continue;
246
+ }
247
+ const targetPanel = disregardCollapseBuffer
248
+ ? createUnrestrainedPanel(context, panel)
249
+ : panel;
250
+ if (panelHasSpace(context, targetPanel)) {
251
+ return panel;
252
+ }
253
+ }
254
+ }
255
+ /** Add up all the static values in the layout */
256
+ function getStaticWidth(context) {
257
+ let width = 0;
258
+ for (const item of context.items) {
259
+ if (isPanelHandle(item)) {
260
+ width += item.size.value;
261
+ }
262
+ else if (isPanelData(item) &&
263
+ item.collapsed &&
264
+ item.currentValue.type === "pixel") {
265
+ width += item.currentValue.value;
266
+ }
267
+ else if (isPanelData(item) &&
268
+ item.default &&
269
+ item.default.type === "pixel") {
270
+ width += item.default.value;
271
+ }
272
+ }
273
+ return width;
274
+ }
275
+ function formatUnit(unit) {
276
+ if (unit.type === "pixel") {
277
+ return `${unit.value}px`;
278
+ }
279
+ return `${unit.value}%`;
280
+ }
281
+ /** Build the grid template from the item values. */
282
+ function buildTemplate(context) {
283
+ const staticWidth = getStaticWidth(context);
284
+ return context.items
285
+ .map((item) => {
286
+ if (item.type === "panel") {
287
+ const min = formatUnit(item.min);
288
+ if (item.currentValue.type === "pixel" &&
289
+ item.currentValue.value !== -1) {
290
+ return formatUnit(item.currentValue);
291
+ }
292
+ else if (item.currentValue.type === "percent") {
293
+ const max = item.max === "1fr" ? "100%" : formatUnit(item.max);
294
+ return `minmax(${min}, min(calc(${item.currentValue.value} * (100% - ${staticWidth}px)), ${max}))`;
295
+ }
296
+ else if (item.collapsible && item.collapsed) {
297
+ return formatUnit(item.collapsedSize);
298
+ }
299
+ else if (item.default) {
300
+ return formatUnit(item.default);
301
+ }
302
+ const max = item.max === "1fr" ? "1fr" : formatUnit(item.max);
303
+ return `minmax(${min}, ${max})`;
304
+ }
305
+ return formatUnit(item.size);
306
+ })
307
+ .join(" ");
308
+ }
309
+ function addDeDuplicatedItems(items, newItem) {
310
+ const currentItemIndex = items.findIndex((item) => item.id === newItem.id ||
311
+ (typeof item.order === "number" && item.order === newItem.order));
312
+ let restItems = items;
313
+ if (currentItemIndex !== -1) {
314
+ restItems = items.filter((_, index) => index !== currentItemIndex);
315
+ }
316
+ return sortWithOrder([...restItems, newItem]);
317
+ }
318
+ function createUnrestrainedPanel(context, data) {
319
+ return {
320
+ ...data,
321
+ min: makePixelUnit(0),
322
+ max: makePixelUnit(getGroupSize(context)),
323
+ };
324
+ }
325
+ // #endregion
326
+ // #region Update Logic
327
+ /**
328
+ * This is the main meat of the layout logic.
329
+ * It's responsible for figuring out how to distribute the space
330
+ * amongst the panels.
331
+ *
332
+ * It's built around applying small deltas to panels relative to their
333
+ * the resize handles.
334
+ *
335
+ * As much as possible we try to rely on the browser to do the layout.
336
+ * During the initial layout we rely on CSS grid and a group might be
337
+ * defined like this:
338
+ *
339
+ * ```css
340
+ * grid-template-columns: minmax(100px, 1fr) 1px minmax(100px, 300px);
341
+ * ```
342
+ *
343
+ * Without any resizing this is nice and simple and the components don't do much.
344
+ *
345
+ * Once the user starts resizing the layout will be more complex.
346
+ *
347
+ * It's broken down into 3 phases:
348
+ *
349
+ * 1. `prepareItems` - The size of the group has been measure and we
350
+ * can convert all the panel sizes into pixels. Converting into pixels
351
+ * makes doing the math for the updates easier.
352
+ *
353
+ * ```css
354
+ * grid-template-columns: 500px 1px 300px;
355
+ * ```
356
+ *
357
+ * 2. `updateLayout` - This is where the actual updates are applied.
358
+ * This is where the user's drag interactions are applied. We also
359
+ * use this to collapse/expand panels by simulating a drag interaction.
360
+ *
361
+ * ```css
362
+ * grid-template-columns: 490px 1px 310px;
363
+ * ```
364
+ *
365
+ * 3. `commitLayout` - Once the updates have been applied we convert the
366
+ * updated sizes back into a format that allows for easy resizing without
367
+ * lots of updates.
368
+ *
369
+ * ```css
370
+ * grid-template-columns: minmax(100px, min(calc(0.06117 * (100% - 1px)), 100%)) 1px minmax(100px, min(calc(0.0387 * (100% - 1px)), 300px));
371
+ * ```
372
+ *
373
+ * When another update loop is triggered the above template will be converted back to pixels.
374
+ */
375
+ /** Converts the items to pixels */
376
+ function prepareItems(context) {
377
+ const newItems = [...context.items];
378
+ const staticWidth = getStaticWidth(context);
379
+ for (const item of newItems) {
380
+ if (!item || !isPanelData(item)) {
381
+ continue;
382
+ }
383
+ if (item.currentValue.type === "pixel") {
384
+ continue;
385
+ }
386
+ // TODO: Decimal proposal
387
+ item.currentValue = makePixelUnit(Math.round((getGroupSize(context) - staticWidth) * item.currentValue.value));
388
+ }
389
+ return newItems;
390
+ }
391
+ /** On every mouse move we distribute the space added */
392
+ function updateLayout(context, dragEvent) {
393
+ const handleIndex = getPanelHandleIndex(context, dragEvent.handleId);
394
+ const handle = context.items[handleIndex];
395
+ const newItems = [...context.items];
396
+ let moveAmount = context.orientation === "horizontal"
397
+ ? dragEvent.value.deltaX
398
+ : dragEvent.value.deltaY;
399
+ if (dragEvent.value.shiftKey) {
400
+ moveAmount *= 15;
401
+ }
402
+ if (moveAmount === 0) {
403
+ return {};
404
+ }
405
+ const moveDirection = moveAmount / Math.abs(moveAmount);
406
+ // Go forward into the shrinking panels to find a panel that still has space.
407
+ const panelBefore = findPanelWithSpace(context, newItems, handleIndex + moveDirection, moveDirection, dragEvent.disregardCollapseBuffer);
408
+ // No panel with space, just record the drag overshoot
409
+ if (!panelBefore) {
410
+ return {
411
+ dragOvershoot: context.dragOvershoot + moveAmount,
412
+ };
413
+ }
414
+ (0, invariant_1.default)(isPanelData(panelBefore), `Expected panel before: ${handle.id}`);
415
+ const panelAfter = newItems[handleIndex - moveDirection];
416
+ (0, invariant_1.default)(panelAfter && isPanelData(panelAfter), `Expected panel after: ${handle.id}`);
417
+ const newDragOvershoot = context.dragOvershoot + moveAmount;
418
+ // Don't let the panel expand until the threshold is reached
419
+ if (!dragEvent.disregardCollapseBuffer) {
420
+ if (panelAfter.collapsible && panelAfter.collapsed) {
421
+ const isInLeftBuffer = newDragOvershoot < 0 && moveDirection > 0;
422
+ const isInLeftOvershoot = newDragOvershoot > 0 && moveDirection > 0;
423
+ const isInRightBuffer = newDragOvershoot > 0 && moveDirection < 0;
424
+ const isInRightOvershoot = newDragOvershoot < 0 && moveDirection < 0;
425
+ const potentialNewValue = panelAfter.currentValue.value +
426
+ newDragOvershoot * (isInRightBuffer ? moveDirection : 1);
427
+ const min = getUnitPixelValue(context, panelAfter.min);
428
+ if ((newDragOvershoot === 0 ||
429
+ isInRightBuffer ||
430
+ isInLeftBuffer ||
431
+ ((isInLeftOvershoot || isInRightOvershoot) &&
432
+ Math.abs(newDragOvershoot) < COLLAPSE_THRESHOLD)) &&
433
+ potentialNewValue < min) {
434
+ return { dragOvershoot: newDragOvershoot };
435
+ }
436
+ }
437
+ // Don't let the panel collapse until the threshold is reached
438
+ else if (panelBefore.collapsible &&
439
+ panelBefore.currentValue.value ===
440
+ getUnitPixelValue(context, panelBefore.min)) {
441
+ const potentialNewValue = panelBefore.currentValue.value - Math.abs(newDragOvershoot);
442
+ if (Math.abs(newDragOvershoot) < COLLAPSE_THRESHOLD &&
443
+ potentialNewValue >
444
+ getUnitPixelValue(context, panelBefore.collapsedSize)) {
445
+ return { dragOvershoot: newDragOvershoot };
446
+ }
447
+ }
448
+ }
449
+ // Apply the move amount to the panel before the slider
450
+ const unrestrainedPanelBefore = createUnrestrainedPanel(context, panelBefore);
451
+ const panelBeforePreviousValue = panelBefore.currentValue.value;
452
+ const panelBeforeNewValueRaw = panelBefore.currentValue.value - moveAmount * moveDirection;
453
+ let panelBeforeNewValue = dragEvent.disregardCollapseBuffer
454
+ ? clampUnit(context, unrestrainedPanelBefore, panelBeforeNewValueRaw)
455
+ : clampUnit(context, panelBefore, panelBeforeNewValueRaw);
456
+ // Also apply the move amount the panel after the slider
457
+ const unrestrainedPanelAfter = createUnrestrainedPanel(context, panelAfter);
458
+ const panelAfterPreviousValue = panelAfter.currentValue.value;
459
+ const applied = panelBeforePreviousValue - panelBeforeNewValue;
460
+ const panelAfterNewValueRaw = panelAfter.currentValue.value + applied;
461
+ let panelAfterNewValue = dragEvent.disregardCollapseBuffer
462
+ ? clampUnit(context, unrestrainedPanelAfter, panelAfterNewValueRaw)
463
+ : clampUnit(context, panelAfter, panelAfterNewValueRaw);
464
+ if (dragEvent.disregardCollapseBuffer) {
465
+ if (panelAfter.collapsible && panelAfter.collapsed) {
466
+ panelAfter.collapsed = false;
467
+ }
468
+ }
469
+ // If the panel was collapsed, expand it
470
+ // We need to re-apply the move amount since the the expansion of the
471
+ // collapsed panel disregards that.
472
+ else if (panelAfter.collapsible && panelAfter.collapsed) {
473
+ if (panelAfter.onCollapseChange?.current &&
474
+ panelAfter.collapseIsControlled &&
475
+ !dragEvent.controlled) {
476
+ panelAfter.onCollapseChange.current(false);
477
+ return { dragOvershoot: newDragOvershoot };
478
+ }
479
+ // Calculate the amount "extra" after the minSize the panel should grow
480
+ const extra =
481
+ // Take the size it was at
482
+ getUnitPixelValue(context, panelAfter.collapsedSize) +
483
+ // Add in the full overshoot so the cursor is near the slider
484
+ Math.abs(context.dragOvershoot) -
485
+ // Subtract the min size of the panel
486
+ panelAfterNewValue +
487
+ // Then re-add the move amount
488
+ Math.abs(moveAmount);
489
+ panelAfter.collapsed = false;
490
+ if (extra > 0) {
491
+ panelAfterNewValue += extra;
492
+ }
493
+ panelBeforeNewValue -=
494
+ // Subtract the delta of the after panel's size
495
+ panelAfterNewValue -
496
+ panelAfterPreviousValue -
497
+ // And then re-apply the movement value
498
+ Math.abs(moveAmount);
499
+ if (panelAfter.onCollapseChange?.current &&
500
+ !panelAfter.collapseIsControlled &&
501
+ !dragEvent.controlled) {
502
+ panelAfter.onCollapseChange.current(false);
503
+ }
504
+ }
505
+ const panelBeforeIsAboutToCollapse = panelBefore.currentValue.value ===
506
+ getUnitPixelValue(context, panelBefore.min);
507
+ // If the panel was expanded and now is at it's min size, collapse it
508
+ if (!dragEvent.disregardCollapseBuffer &&
509
+ panelBefore.collapsible &&
510
+ panelBeforeIsAboutToCollapse) {
511
+ if (panelBefore.onCollapseChange?.current &&
512
+ panelBefore.collapseIsControlled &&
513
+ !dragEvent.controlled) {
514
+ panelBefore.onCollapseChange.current(true);
515
+ return { dragOvershoot: newDragOvershoot };
516
+ }
517
+ // Make it collapsed
518
+ panelBefore.collapsed = true;
519
+ panelBeforeNewValue = getUnitPixelValue(context, panelBefore.collapsedSize);
520
+ // Add the extra space created to the before panel
521
+ panelAfterNewValue += panelBeforePreviousValue - panelBeforeNewValue;
522
+ if (panelBefore.onCollapseChange?.current &&
523
+ !panelBefore.collapseIsControlled &&
524
+ !dragEvent.controlled) {
525
+ panelBefore.onCollapseChange.current(true);
526
+ }
527
+ }
528
+ panelBefore.currentValue = makePixelUnit(panelBeforeNewValue);
529
+ panelAfter.currentValue = makePixelUnit(panelAfterNewValue);
530
+ const leftoverSpace = getGroupSize(context) -
531
+ newItems.reduce((acc, b) => acc +
532
+ // in updateLayout the panel units will always be numbers
533
+ (isPanelData(b) ? b.currentValue.value : b.size.value), 0);
534
+ // TODO: this is wrong?
535
+ panelBefore.currentValue.value += leftoverSpace;
536
+ return { items: newItems, dragOvershoot: 0 };
537
+ }
538
+ /** Converts the items to percentages */
539
+ function commitLayout(context) {
540
+ const newItems = [...context.items];
541
+ // First set all the static width
542
+ newItems.forEach((item, index) => {
543
+ if (item.type !== "panel") {
544
+ return;
545
+ }
546
+ if (item.collapsed) {
547
+ newItems[index] = {
548
+ ...item,
549
+ currentValue: item.collapsedSize,
550
+ };
551
+ }
552
+ });
553
+ const staticWidth = getStaticWidth({ ...context, items: newItems });
554
+ newItems.forEach((item, index) => {
555
+ if (item.type !== "panel" || item.collapsed) {
556
+ return;
557
+ }
558
+ newItems[index] = {
559
+ ...item,
560
+ currentValue: makePercentUnit(item.currentValue.value / (getGroupSize(context) - staticWidth)),
561
+ };
562
+ });
563
+ return newItems;
564
+ }
565
+ function dragHandlePayload({ delta, orientation, shiftKey = false, }) {
566
+ return {
567
+ type: "move",
568
+ pointerType: "keyboard",
569
+ shiftKey,
570
+ ctrlKey: false,
571
+ altKey: false,
572
+ metaKey: false,
573
+ deltaX: orientation === "horizontal" ? delta : 0,
574
+ deltaY: orientation === "horizontal" ? 0 : delta,
575
+ };
576
+ }
577
+ /** Iteratively applies a large delta value simulating a user's drag */
578
+ function iterativelyUpdateLayout({ context, handleId, delta, direction, controlled, disregardCollapseBuffer, }) {
579
+ let newContext = context;
580
+ for (let i = 0; i < Math.abs(delta); i++) {
581
+ newContext = updateLayout({
582
+ ...context,
583
+ ...newContext,
584
+ }, {
585
+ handleId,
586
+ type: "collapsePanel",
587
+ controlled,
588
+ disregardCollapseBuffer,
589
+ value: dragHandlePayload({
590
+ delta: direction,
591
+ orientation: context.orientation,
592
+ }),
593
+ });
594
+ }
595
+ return newContext;
596
+ }
597
+ function applyDeltaInBothDirections(context, newItems, itemIndex, delta) {
598
+ let hasTriedBothDirections = false;
599
+ let direction = 1;
600
+ // Starting from where the items was removed add space to the panels around it.
601
+ // This is only needed for conditional rendering.
602
+ while (delta !== 0) {
603
+ const targetPanel = findPanelWithSpace(context, newItems, itemIndex + direction, direction);
604
+ if (!targetPanel) {
605
+ if (hasTriedBothDirections) {
606
+ break;
607
+ }
608
+ else {
609
+ direction = direction === 1 ? -1 : 1;
610
+ hasTriedBothDirections = true;
611
+ continue;
612
+ }
613
+ }
614
+ const oldValue = targetPanel.currentValue.value;
615
+ const newValue = clampUnit(context, targetPanel, oldValue + delta);
616
+ targetPanel.currentValue.value = newValue;
617
+ delta -= newValue - oldValue;
618
+ direction = direction === 1 ? -1 : 1;
619
+ }
620
+ }
621
+ const animationActor = (0, xstate_1.fromPromise)(({ input: { send, context, event } }) => new Promise((resolve) => {
622
+ const panel = getPanelWithId(context, event.panelId);
623
+ const handle = getHandleForPanelId(context, event.panelId);
624
+ let direction = handle.direction;
625
+ let fullDelta = 0;
626
+ if (event.type === "expandPanel") {
627
+ fullDelta =
628
+ (panel.sizeBeforeCollapse ?? getUnitPixelValue(context, panel.min)) -
629
+ panel.currentValue.value;
630
+ }
631
+ else {
632
+ const collapsedSize = getUnitPixelValue(context, panel.collapsedSize);
633
+ panel.sizeBeforeCollapse = panel.currentValue.value;
634
+ direction *= -1;
635
+ fullDelta = panel.currentValue.value - collapsedSize;
636
+ }
637
+ const fps = 60;
638
+ const { duration, ease } = getCollapseAnimation(panel);
639
+ const totalFrames = Math.ceil(panel.collapseAnimation ? duration / (1000 / fps) : 1);
640
+ let frame = 0;
641
+ let appliedDelta = 0;
642
+ function renderFrame() {
643
+ const progress = (frame++ + 1) / totalFrames;
644
+ const e = panel.collapseAnimation ? ease(progress) : 1;
645
+ const delta = (e * fullDelta - appliedDelta) * direction;
646
+ send({ type: "applyDelta", handleId: handle.item.id, delta });
647
+ appliedDelta +=
648
+ Math.abs(delta) *
649
+ ((delta > 0 && direction === -1) || (delta < 0 && direction === 1)
650
+ ? -1
651
+ : 1);
652
+ if (e === 1) {
653
+ const action = event.type === "expandPanel" ? "expand" : "collapse";
654
+ resolve({ panelId: panel.id, action });
655
+ return false;
656
+ }
657
+ return true;
658
+ }
659
+ (0, rafz_1.raf)(renderFrame);
660
+ }));
661
+ exports.groupMachine = (0, xstate_1.createMachine)({
662
+ initial: "idle",
663
+ types: {
664
+ context: {},
665
+ events: {},
666
+ input: {},
667
+ },
668
+ context: ({ input }) => ({
669
+ size: { width: 0, height: 0 },
670
+ items: input.initialItems || [],
671
+ orientation: input.orientation || "horizontal",
672
+ dragOvershoot: 0,
673
+ autosaveId: input.autosaveId,
674
+ groupId: input.groupId,
675
+ }),
676
+ states: {
677
+ idle: {
678
+ on: {
679
+ setActualItemsSize: { actions: ["recordActualItemSize"] },
680
+ dragHandleStart: { target: "dragging" },
681
+ setPanelPixelSize: {
682
+ actions: ["prepare", "onSetPanelSize", "commit"],
683
+ },
684
+ collapsePanel: [
685
+ {
686
+ actions: "notifyCollapseToggle",
687
+ guard: "shouldNotifyCollapseToggle",
688
+ },
689
+ { target: "togglingCollapse" },
690
+ ],
691
+ expandPanel: [
692
+ {
693
+ actions: "notifyCollapseToggle",
694
+ guard: "shouldNotifyCollapseToggle",
695
+ },
696
+ { target: "togglingCollapse" },
697
+ ],
698
+ },
699
+ },
700
+ dragging: {
701
+ entry: ["prepare"],
702
+ on: {
703
+ dragHandle: { actions: ["onDragHandle"] },
704
+ dragHandleEnd: { target: "idle" },
705
+ collapsePanel: {
706
+ guard: "shouldCollapseToggle",
707
+ actions: "runCollapseToggle",
708
+ },
709
+ expandPanel: {
710
+ guard: "shouldCollapseToggle",
711
+ actions: "runCollapseToggle",
712
+ },
713
+ },
714
+ exit: ["commit", "onAutosave"],
715
+ },
716
+ togglingCollapse: {
717
+ entry: ["prepare"],
718
+ invoke: {
719
+ src: "animation",
720
+ input: (i) => ({ ...i, send: i.self.send }),
721
+ onDone: {
722
+ target: "idle",
723
+ actions: ["onToggleCollapseComplete", "commit", "onAutosave"],
724
+ },
725
+ },
726
+ on: {
727
+ applyDelta: { actions: ["onApplyDelta"] },
728
+ },
729
+ },
730
+ },
731
+ on: {
732
+ registerPanel: { actions: ["assignPanelData"] },
733
+ registerDynamicPanel: {
734
+ actions: ["prepare", "onRegisterDynamicPanel", "commit", "onAutosave"],
735
+ },
736
+ unregisterPanel: {
737
+ actions: ["prepare", "removeItem", "commit", "onAutosave"],
738
+ },
739
+ registerPanelHandle: { actions: ["assignPanelHandleData"] },
740
+ unregisterPanelHandle: {
741
+ actions: ["prepare", "removeItem", "commit", "onAutosave"],
742
+ },
743
+ setSize: { actions: ["updateSize"] },
744
+ setOrientation: { actions: ["updateOrientation"] },
745
+ },
746
+ }, {
747
+ guards: {
748
+ shouldNotifyCollapseToggle: ({ context, event }) => {
749
+ isEvent(event, ["collapsePanel", "expandPanel"]);
750
+ const panel = getPanelWithId(context, event.panelId);
751
+ return !event.controlled && panel.collapseIsControlled === true;
752
+ },
753
+ shouldCollapseToggle: ({ context, event }) => {
754
+ isEvent(event, ["collapsePanel", "expandPanel"]);
755
+ const panel = getPanelWithId(context, event.panelId);
756
+ return panel.collapseIsControlled === true;
757
+ },
758
+ },
759
+ actors: {
760
+ animation: animationActor,
761
+ },
762
+ actions: {
763
+ notifyCollapseToggle: ({ context, event }) => {
764
+ isEvent(event, ["collapsePanel", "expandPanel"]);
765
+ const panel = getPanelWithId(context, event.panelId);
766
+ panel.onCollapseChange?.current?.(!panel.collapsed);
767
+ },
768
+ runCollapseToggle: (0, xstate_1.enqueueActions)(({ context, event, enqueue }) => {
769
+ isEvent(event, ["collapsePanel", "expandPanel"]);
770
+ const handle = getHandleForPanelId(context, event.panelId);
771
+ // When collapsing a panel it will be in the opposite direction
772
+ // that handle assumes
773
+ const delta = event.type === "collapsePanel"
774
+ ? handle.direction * -1
775
+ : handle.direction;
776
+ const newContext = updateLayout(context, {
777
+ handleId: handle.item.id,
778
+ type: "dragHandle",
779
+ controlled: event.controlled,
780
+ value: dragHandlePayload({ delta, orientation: context.orientation }),
781
+ });
782
+ enqueue.assign(newContext);
783
+ }),
784
+ onToggleCollapseComplete: (0, xstate_1.assign)({
785
+ items: ({ context, event: e }) => {
786
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
787
+ const output = e.output;
788
+ (0, invariant_1.default)(output, "Expected output from animation actor");
789
+ const panel = getPanelWithId(context, output.panelId);
790
+ panel.collapsed = output.action === "collapse";
791
+ if (panel.collapsed) {
792
+ panel.currentValue = panel.collapsedSize;
793
+ }
794
+ return context.items;
795
+ },
796
+ }),
797
+ updateSize: (0, xstate_1.assign)({
798
+ size: ({ event }) => {
799
+ isEvent(event, ["setSize"]);
800
+ return event.size;
801
+ },
802
+ }),
803
+ recordActualItemSize: (0, xstate_1.assign)({
804
+ items: ({ context, event }) => {
805
+ isEvent(event, ["setActualItemsSize"]);
806
+ const orientation = context.orientation;
807
+ for (const [id, size] of Object.entries(event.childrenSizes)) {
808
+ const item = context.items.find((i) => i.id === id);
809
+ if (!isPanelData(item)) {
810
+ continue;
811
+ }
812
+ item.currentValue = makePixelUnit(orientation === "horizontal" ? size.width : size.height);
813
+ }
814
+ return commitLayout(context);
815
+ },
816
+ }),
817
+ updateOrientation: (0, xstate_1.assign)({
818
+ orientation: ({ event }) => {
819
+ isEvent(event, ["setOrientation"]);
820
+ return event.orientation;
821
+ },
822
+ }),
823
+ assignPanelData: (0, xstate_1.assign)({
824
+ items: ({ context, event }) => {
825
+ isEvent(event, ["registerPanel"]);
826
+ return addDeDuplicatedItems(context.items, {
827
+ type: "panel",
828
+ currentValue: makePixelUnit(-1),
829
+ ...event.data,
830
+ });
831
+ },
832
+ }),
833
+ onRegisterDynamicPanel: (0, xstate_1.assign)({
834
+ items: ({ context, event }) => {
835
+ isEvent(event, ["registerDynamicPanel"]);
836
+ let currentValue = makePixelUnit(0);
837
+ if (event.data.collapsible &&
838
+ event.data.collapsed &&
839
+ event.data.collapsedSize) {
840
+ currentValue = event.data.collapsedSize;
841
+ }
842
+ else if (event.data.default) {
843
+ currentValue = event.data.default;
844
+ }
845
+ else {
846
+ currentValue = event.data.min;
847
+ }
848
+ const newItems = addDeDuplicatedItems(context.items, {
849
+ type: "panel",
850
+ ...event.data,
851
+ currentValue,
852
+ });
853
+ const itemIndex = newItems.findIndex((item) => item.id === event.data.id);
854
+ const newContext = { ...context, items: newItems };
855
+ const overflowDueToHandles = context.items.reduce((acc, i) => {
856
+ if (isPanelHandle(i)) {
857
+ return acc + getUnitPixelValue(context, i.size);
858
+ }
859
+ return acc + i.currentValue.value;
860
+ }, 0) - getGroupSize(context);
861
+ applyDeltaInBothDirections(newContext, newItems, itemIndex, -1 * (currentValue.value + overflowDueToHandles));
862
+ return newItems;
863
+ },
864
+ }),
865
+ assignPanelHandleData: (0, xstate_1.assign)({
866
+ items: ({ context, event }) => {
867
+ isEvent(event, ["registerPanelHandle"]);
868
+ return addDeDuplicatedItems(context.items, {
869
+ type: "handle",
870
+ ...event.data,
871
+ size: event.data.size,
872
+ });
873
+ },
874
+ }),
875
+ removeItem: (0, xstate_1.assign)({
876
+ items: ({ context, event }) => {
877
+ isEvent(event, ["unregisterPanel", "unregisterPanelHandle"]);
878
+ const itemIndex = context.items.findIndex((item) => item.id === event.id);
879
+ const item = context.items[itemIndex];
880
+ if (!item) {
881
+ return context.items;
882
+ }
883
+ const newItems = context.items.filter((i) => i.id !== event.id);
884
+ const removedSize = isPanelData(item)
885
+ ? item.currentValue.value
886
+ : item.size.value;
887
+ applyDeltaInBothDirections(context, newItems, itemIndex, removedSize);
888
+ return newItems;
889
+ },
890
+ }),
891
+ prepare: (0, xstate_1.assign)({
892
+ items: ({ context }) => prepareItems(context),
893
+ }),
894
+ onDragHandle: (0, xstate_1.enqueueActions)(({ context, event, enqueue }) => {
895
+ isEvent(event, ["dragHandle"]);
896
+ enqueue.assign(updateLayout(context, event));
897
+ }),
898
+ commit: (0, xstate_1.assign)({
899
+ dragOvershoot: 0,
900
+ items: ({ context }) => commitLayout(context),
901
+ }),
902
+ onApplyDelta: (0, xstate_1.assign)(({ context, event }) => {
903
+ isEvent(event, ["applyDelta"]);
904
+ return updateLayout(context, {
905
+ handleId: event.handleId,
906
+ type: "collapsePanel",
907
+ disregardCollapseBuffer: true,
908
+ value: dragHandlePayload({
909
+ delta: event.delta,
910
+ orientation: context.orientation,
911
+ }),
912
+ });
913
+ }),
914
+ onSetPanelSize: (0, xstate_1.enqueueActions)(({ context, event, enqueue }) => {
915
+ isEvent(event, ["setPanelPixelSize"]);
916
+ const panel = getPanelWithId(context, event.panelId);
917
+ const handle = getHandleForPanelId(context, event.panelId);
918
+ const current = panel.currentValue.value;
919
+ const newSize = clampUnit(context, panel, getUnitPixelValue(context, parseUnit(event.size)));
920
+ const isBigger = newSize > current;
921
+ const delta = isBigger ? newSize - current : current - newSize;
922
+ enqueue.assign(iterativelyUpdateLayout({
923
+ context,
924
+ direction: (handle.direction * (isBigger ? 1 : -1)),
925
+ handleId: handle.item.id,
926
+ delta,
927
+ }));
928
+ }),
929
+ },
930
+ });
931
+ // #endregion
932
+ //# sourceMappingURL=index.js.map