@window-splitter/state 0.2.3--canary.823a479.0 → 0.2.3

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