@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
package/src/index.ts ADDED
@@ -0,0 +1,1514 @@
1
+ import { raf } from "@react-spring/rafz";
2
+ import { createMachine, assign, enqueueActions, fromPromise } from "xstate";
3
+ import invariant from "invariant";
4
+ import * as easings from "d3-ease";
5
+
6
+ // #region Constants
7
+
8
+ /** The default amount a user can `dragOvershoot` before the panel collapses */
9
+ const COLLAPSE_THRESHOLD = 50;
10
+
11
+ // #endregion
12
+
13
+ // #region Types
14
+
15
+ type PixelUnit = `${number}px`;
16
+ type PercentUnit = `${number}%`;
17
+ export type Unit = PixelUnit | PercentUnit;
18
+ type Orientation = "horizontal" | "vertical";
19
+
20
+ interface ParsedPercentUnit {
21
+ type: "percent";
22
+ value: number;
23
+ }
24
+
25
+ interface ParsedPixelUnit {
26
+ type: "pixel";
27
+ value: number;
28
+ }
29
+
30
+ type ParsedUnit = ParsedPercentUnit | ParsedPixelUnit;
31
+
32
+ function makePercentUnit(value: number): ParsedPercentUnit {
33
+ return { type: "percent", value };
34
+ }
35
+
36
+ function makePixelUnit(value: number): ParsedPixelUnit {
37
+ return { type: "pixel", value };
38
+ }
39
+
40
+ interface MoveMoveEvent {
41
+ shiftKey: boolean;
42
+ ctrlKey: boolean;
43
+ metaKey: boolean;
44
+ altKey: boolean;
45
+ deltaX: number;
46
+ deltaY: number;
47
+ }
48
+
49
+ export interface Constraints<T extends ParsedUnit | Unit = ParsedUnit> {
50
+ /** The minimum size of the panel */
51
+ min?: T;
52
+ /** The maximum size of the panel */
53
+ max?: T;
54
+ /** The default size of the panel */
55
+ default?: T;
56
+ /** Whether the panel is collapsible */
57
+ collapsible?: boolean;
58
+ /** Whether the panel should initially render as collapsed */
59
+ defaultCollapsed?: boolean;
60
+ /** The size of the panel once collapsed */
61
+ collapsedSize?: T;
62
+ }
63
+
64
+ interface Order {
65
+ /**
66
+ * When dynamically rendering panels/handles you need to add the order prop.
67
+ * This tells the component what place the items should be in once rendered.
68
+ */
69
+ order?: number;
70
+ }
71
+
72
+ export interface PanelData
73
+ extends Omit<Constraints, "min" | "max" | "collapsedSize">,
74
+ Required<Pick<Constraints, "min" | "collapsedSize">>,
75
+ Order {
76
+ max: ParsedUnit | "1fr";
77
+ type: "panel";
78
+ id: string;
79
+ /** Whether the collapsed state is controlled by the consumer or not */
80
+ collapseIsControlled?: boolean;
81
+ /** A ref to the latest "collapseChange" function provided by the user */
82
+ onCollapseChange?: {
83
+ current: ((isCollapsed: boolean) => void) | null | undefined;
84
+ };
85
+ /**
86
+ * The current value for the item in the grid
87
+ */
88
+ currentValue: ParsedUnit;
89
+ /** Whether the panel is currently collapsed */
90
+ collapsed: boolean | undefined;
91
+ /**
92
+ * The size the panel was before being collapsed.
93
+ * This is used to re-open the panel at the same size.
94
+ * If the panel starts out collapsed it will use the `min`.
95
+ */
96
+ sizeBeforeCollapse: number | undefined;
97
+ /** Animate the collapse/expand */
98
+ collapseAnimation?:
99
+ | CollapseAnimation
100
+ | { duration: number; easing: CollapseAnimation | ((t: number) => number) };
101
+ }
102
+
103
+ function getCollapseAnimation(panel: PanelData) {
104
+ let easeFn = collapseAnimations.linear;
105
+ let duration = 300;
106
+
107
+ if (panel.collapseAnimation) {
108
+ if (typeof panel.collapseAnimation === "string") {
109
+ easeFn = collapseAnimations[panel.collapseAnimation];
110
+ } else if ("duration" in panel.collapseAnimation) {
111
+ duration = panel.collapseAnimation.duration ?? duration;
112
+ easeFn =
113
+ typeof panel.collapseAnimation.easing === "function"
114
+ ? panel.collapseAnimation.easing
115
+ : collapseAnimations[panel.collapseAnimation.easing];
116
+ }
117
+ }
118
+
119
+ return { ease: easeFn, duration };
120
+ }
121
+
122
+ const collapseAnimations = {
123
+ "ease-in-out": easings.easeQuadInOut,
124
+ bounce: easings.easeBackInOut,
125
+ linear: easings.easeLinear,
126
+ };
127
+
128
+ type CollapseAnimation = keyof typeof collapseAnimations;
129
+
130
+ export interface PanelHandleData extends Order {
131
+ type: "handle";
132
+ id: string;
133
+ /**
134
+ * The size of the panel handle.
135
+ * Needed to correctly calculate the percentage of modified panels.
136
+ */
137
+ size: ParsedPixelUnit;
138
+ }
139
+
140
+ export type Item = PanelData | PanelHandleData;
141
+
142
+ interface RegisterPanelEvent {
143
+ /** Register a new panel with the state machine */
144
+ type: "registerPanel";
145
+ data: Omit<PanelData, "type" | "currentValue" | "defaultCollapsed">;
146
+ }
147
+
148
+ interface RegisterDynamicPanelEvent extends Omit<RegisterPanelEvent, "type"> {
149
+ /** Register a new panel with the state machine */
150
+ type: "registerDynamicPanel";
151
+ }
152
+
153
+ interface UnregisterPanelEvent {
154
+ /** Remove a panel from the state machine */
155
+ type: "unregisterPanel";
156
+ id: string;
157
+ }
158
+
159
+ export type InitializePanelHandleData = Omit<PanelHandleData, "type">;
160
+
161
+ interface RegisterPanelHandleEvent {
162
+ /** Register a new panel handle with the state machine */
163
+ type: "registerPanelHandle";
164
+ data: InitializePanelHandleData;
165
+ }
166
+
167
+ interface UnregisterPanelHandleEvent {
168
+ /** Remove a panel handle from the state machine */
169
+ type: "unregisterPanelHandle";
170
+ id: string;
171
+ }
172
+
173
+ interface DragHandleStartEvent {
174
+ /** Start a drag interaction */
175
+ type: "dragHandleStart";
176
+ /** The handle being interacted with */
177
+ handleId: string;
178
+ }
179
+
180
+ interface DragHandleEvent {
181
+ /** Update the layout according to how the handle moved */
182
+ type: "dragHandle";
183
+ /** The handle being interacted with */
184
+ handleId: string;
185
+ value: MoveMoveEvent;
186
+ }
187
+
188
+ interface DragHandleEndEvent {
189
+ /** End a drag interaction */
190
+ type: "dragHandleEnd";
191
+ /** The handle being interacted with */
192
+ handleId: string;
193
+ }
194
+
195
+ export interface Rect {
196
+ width: number;
197
+ height: number;
198
+ }
199
+
200
+ interface SetSizeEvent {
201
+ /** Set the size of the whole group */
202
+ type: "setSize";
203
+ size: Rect;
204
+ }
205
+
206
+ interface SetActualItemsSizeEvent {
207
+ /** Set the size of the whole group */
208
+ type: "setActualItemsSize";
209
+ childrenSizes: Record<string, Rect>;
210
+ }
211
+
212
+ interface ApplyDeltaEvent {
213
+ type: "applyDelta";
214
+ delta: number;
215
+ handleId: string;
216
+ }
217
+
218
+ interface SetOrientationEvent {
219
+ /** Set the orientation of the group */
220
+ type: "setOrientation";
221
+ orientation: Orientation;
222
+ }
223
+
224
+ interface ControlledCollapseToggle {
225
+ /**
226
+ * This is used to react to the controlled panel "collapse" prop updating.
227
+ * This will force an update to be applied and skip calling the user's `onCollapseChanged`
228
+ */
229
+ controlled?: boolean;
230
+ }
231
+
232
+ interface CollapsePanelEvent extends ControlledCollapseToggle {
233
+ /** Collapse a panel */
234
+ type: "collapsePanel";
235
+ /** The panel to collapse */
236
+ panelId: string;
237
+ }
238
+
239
+ interface ExpandPanelEvent extends ControlledCollapseToggle {
240
+ /** Expand a panel */
241
+ type: "expandPanel";
242
+ /** The panel to expand */
243
+ panelId: string;
244
+ }
245
+
246
+ interface SetPanelPixelSizeEvent {
247
+ /**
248
+ * This event is used by the imperative panel API.
249
+ * With this the user can set the panel's size to an explicit value.
250
+ * This is done by faking interaction with the handles so min/max will still
251
+ * be respected.
252
+ */
253
+ type: "setPanelPixelSize";
254
+ /** The panel to apply the size to */
255
+ panelId: string;
256
+ /** The size to apply to the panel */
257
+ size: Unit;
258
+ }
259
+
260
+ export interface GroupMachineContextValue {
261
+ /** The items in the group */
262
+ items: Array<Item>;
263
+ /** The available space in the group */
264
+ size: Rect;
265
+ /** The orientation of the grid */
266
+ orientation: Orientation;
267
+ /** How much the drag has overshot the handle */
268
+ dragOvershoot: number;
269
+ /** An id to use for autosaving the layout */
270
+ autosaveId?: string;
271
+ groupId: string;
272
+ }
273
+
274
+ export type GroupMachineEvent =
275
+ | RegisterPanelEvent
276
+ | RegisterDynamicPanelEvent
277
+ | UnregisterPanelEvent
278
+ | RegisterPanelHandleEvent
279
+ | UnregisterPanelHandleEvent
280
+ | DragHandleEvent
281
+ | SetSizeEvent
282
+ | SetOrientationEvent
283
+ | DragHandleStartEvent
284
+ | DragHandleEndEvent
285
+ | CollapsePanelEvent
286
+ | ExpandPanelEvent
287
+ | SetPanelPixelSizeEvent
288
+ | ApplyDeltaEvent
289
+ | SetActualItemsSizeEvent;
290
+
291
+ type EventForType<T extends GroupMachineEvent["type"]> = Extract<
292
+ GroupMachineEvent,
293
+ { type: T }
294
+ >;
295
+
296
+ // #endregion
297
+
298
+ // #region Helpers
299
+
300
+ /** Assert that the provided event is one of the accepted types */
301
+ function isEvent<T extends GroupMachineEvent["type"]>(
302
+ event: GroupMachineEvent,
303
+ eventType: T[]
304
+ ): asserts event is EventForType<T> {
305
+ invariant(
306
+ eventType.includes(event.type as T),
307
+ `Invalid event type: ${eventType}. Expected: ${eventType.join(" | ")}`
308
+ );
309
+ }
310
+
311
+ /** Determine if an item is a panel */
312
+ export function isPanelData(value: unknown): value is PanelData {
313
+ return Boolean(
314
+ value &&
315
+ typeof value === "object" &&
316
+ "type" in value &&
317
+ value.type === "panel"
318
+ );
319
+ }
320
+
321
+ /** Determine if an item is a panel handle */
322
+ export function isPanelHandle(value: unknown): value is PanelHandleData {
323
+ return Boolean(
324
+ value &&
325
+ typeof value === "object" &&
326
+ "type" in value &&
327
+ value.type === "handle"
328
+ );
329
+ }
330
+
331
+ interface InitializePanelOptions {
332
+ min?: Unit;
333
+ max?: Unit;
334
+ default?: Unit;
335
+ collapsible?: boolean;
336
+ collapsed?: boolean;
337
+ collapsedSize?: Unit;
338
+ onCollapseChange?: {
339
+ current: ((isCollapsed: boolean) => void) | null | undefined;
340
+ };
341
+ collapseAnimation?: PanelData["collapseAnimation"];
342
+ defaultCollapsed?: boolean;
343
+ id?: string;
344
+ }
345
+
346
+ type InitializePanelOptionsWithId = InitializePanelOptions & { id: string };
347
+
348
+ export function initializePanel(item: InitializePanelOptionsWithId): PanelData;
349
+ export function initializePanel(
350
+ item: InitializePanelOptions
351
+ ): Omit<PanelData, "id">;
352
+ export function initializePanel(
353
+ item: InitializePanelOptions | InitializePanelOptionsWithId
354
+ ): PanelData | Omit<PanelData, "id"> {
355
+ const data = {
356
+ type: "panel" as const,
357
+ min: parseUnit(item.min || "0px"),
358
+ max: item.max ? parseUnit(item.max) : "1fr",
359
+ collapsed: item.collapsible
360
+ ? (item.collapsed ?? item.defaultCollapsed ?? false)
361
+ : undefined,
362
+ collapsible: item.collapsible,
363
+ collapsedSize: parseUnit(item.collapsedSize ?? "0px"),
364
+ onCollapseChange: item.onCollapseChange,
365
+ collapseIsControlled: typeof item.collapsed !== "undefined",
366
+ sizeBeforeCollapse: undefined,
367
+ id: item.id,
368
+ collapseAnimation: item.collapseAnimation,
369
+ default: item.default ? parseUnit(item.default) : undefined,
370
+ } satisfies Omit<PanelData, "id" | "currentValue"> & { id?: string };
371
+
372
+ return { ...data, currentValue: makePixelUnit(-1) } satisfies Omit<
373
+ PanelData,
374
+ "id"
375
+ >;
376
+ }
377
+
378
+ /** Parse a `Unit` string or `clamp` value */
379
+ export function parseUnit(unit: Unit | "1fr"): ParsedUnit {
380
+ if (unit === "1fr") {
381
+ unit = "100%";
382
+ }
383
+
384
+ if (unit.endsWith("px")) {
385
+ return makePixelUnit(parseFloat(unit));
386
+ }
387
+
388
+ if (unit.endsWith("%")) {
389
+ return makePercentUnit(parseFloat(unit));
390
+ }
391
+
392
+ throw new Error(`Invalid unit: ${unit}`);
393
+ }
394
+
395
+ /** Convert a `Unit` to a percentage of the group size */
396
+ export function getUnitPercentageValue(groupsSize: number, unit: ParsedUnit) {
397
+ if (unit.type === "pixel") {
398
+ return unit.value / groupsSize;
399
+ }
400
+
401
+ return unit.value;
402
+ }
403
+
404
+ export function getGroupSize(context: GroupMachineContextValue) {
405
+ return context.orientation === "horizontal"
406
+ ? context.size.width
407
+ : context.size.height;
408
+ }
409
+
410
+ /** Get the size of a panel in pixels */
411
+ export function getUnitPixelValue(
412
+ context: GroupMachineContextValue,
413
+ unit: ParsedUnit | "1fr"
414
+ ) {
415
+ const parsed = unit === "1fr" ? parseUnit(unit) : unit;
416
+ return parsed.type === "pixel"
417
+ ? parsed.value
418
+ : (parsed.value / 100) * getGroupSize(context);
419
+ }
420
+
421
+ /** Clamp a new `currentValue` given the panel's constraints. */
422
+ function clampUnit(
423
+ context: GroupMachineContextValue,
424
+ item: PanelData,
425
+ value: number
426
+ ) {
427
+ return Math.min(
428
+ Math.max(value, getUnitPixelValue(context, item.min)),
429
+ getUnitPixelValue(context, item.max)
430
+ );
431
+ }
432
+
433
+ /** Get a panel with a particular ID. */
434
+ export function getPanelWithId(
435
+ context: GroupMachineContextValue,
436
+ panelId: string
437
+ ) {
438
+ const item = context.items.find((i) => i.id === panelId);
439
+
440
+ if (item && isPanelData(item)) {
441
+ return item;
442
+ }
443
+
444
+ throw new Error(`Expected panel with id: ${panelId}`);
445
+ }
446
+
447
+ /** Get a panel with a particular ID. */
448
+ function getPanelHandleIndex(
449
+ context: GroupMachineContextValue,
450
+ handleId: string
451
+ ) {
452
+ const item = context.items.findIndex((i) => i.id === handleId);
453
+
454
+ if (item !== -1 && isPanelHandle(context.items[item])) {
455
+ return item;
456
+ }
457
+
458
+ throw new Error(`Expected panel handle with id: ${handleId}`);
459
+ }
460
+
461
+ /**
462
+ * Get the panel that's collapsible next to a resize handle.
463
+ * Will first check the left panel then the right.
464
+ */
465
+ export function getCollapsiblePanelForHandleId(
466
+ context: GroupMachineContextValue,
467
+ handleId: string
468
+ ) {
469
+ if (!context.items.length) {
470
+ throw new Error("No items in group");
471
+ }
472
+
473
+ const handleIndex = getPanelHandleIndex(context, handleId);
474
+ const panelBefore = context.items[handleIndex - 1];
475
+ const panelAfter = context.items[handleIndex + 1];
476
+
477
+ if (panelBefore && isPanelData(panelBefore) && panelBefore.collapsible) {
478
+ return panelBefore;
479
+ }
480
+
481
+ if (panelAfter && isPanelData(panelAfter) && panelAfter.collapsible) {
482
+ return panelAfter;
483
+ }
484
+
485
+ throw new Error(`No collapsible panel found for handle: ${handleId}`);
486
+ }
487
+
488
+ /**
489
+ * Get the handle closest to the target panel.
490
+ * This is used to simulate collapse/expand
491
+ */
492
+ function getHandleForPanelId(
493
+ context: GroupMachineContextValue,
494
+ panelId: string
495
+ ) {
496
+ const panelIndex = context.items.findIndex((item) => item.id === panelId);
497
+
498
+ invariant(panelIndex !== -1, `Expected panel before: ${panelId}`);
499
+
500
+ let item = context.items[panelIndex + 1];
501
+
502
+ if (item && isPanelHandle(item)) {
503
+ return { item, direction: 1 as const };
504
+ }
505
+
506
+ item = context.items[panelIndex - 1];
507
+
508
+ if (item && isPanelHandle(item)) {
509
+ return { item, direction: -1 as const };
510
+ }
511
+
512
+ throw new Error(`Cant find handle for panel: ${panelId}`);
513
+ }
514
+
515
+ /** Given the specified order props and default order of the items, order the items */
516
+ function sortWithOrder(items: Array<Item>) {
517
+ const defaultPlacement: Record<string, number> = {};
518
+ const takenPlacements = items
519
+ .map((i) => i.order)
520
+ .filter((i): i is number => i !== undefined);
521
+
522
+ let defaultOrder = 0;
523
+
524
+ // Generate default orders for items that don't have it
525
+ for (const item of items) {
526
+ if (item.order === undefined) {
527
+ while (
528
+ takenPlacements.includes(defaultOrder) ||
529
+ Object.values(defaultPlacement).includes(defaultOrder)
530
+ ) {
531
+ defaultOrder++;
532
+ }
533
+
534
+ defaultPlacement[item.id] = defaultOrder;
535
+ }
536
+ }
537
+
538
+ const withoutOrder = items.filter((i) => i.order === undefined);
539
+ const sortedWithOrder = items
540
+ .filter((i) => i.order !== undefined)
541
+ .sort((a, b) => a.order! - b.order!);
542
+
543
+ for (const item of sortedWithOrder) {
544
+ // insert item at order index
545
+ withoutOrder.splice(item.order!, 0, item);
546
+ }
547
+
548
+ return withoutOrder;
549
+ }
550
+
551
+ /** Check if the panel has space available to add to */
552
+ function panelHasSpace(context: GroupMachineContextValue, item: PanelData) {
553
+ invariant(
554
+ item.currentValue.type === "pixel",
555
+ `panelHasSpace only works with number values: ${item.id} ${item.currentValue}`
556
+ );
557
+
558
+ if (item.collapsible && !item.collapsed) {
559
+ return true;
560
+ }
561
+
562
+ return item.currentValue.value > getUnitPixelValue(context, item.min);
563
+ }
564
+
565
+ /** Search in a `direction` for a panel that still has space to expand. */
566
+ function findPanelWithSpace(
567
+ context: GroupMachineContextValue,
568
+ items: Array<Item>,
569
+ start: number,
570
+ direction: number,
571
+ disregardCollapseBuffer?: boolean
572
+ ) {
573
+ const slice =
574
+ direction === -1 ? items.slice(0, start + 1).reverse() : items.slice(start);
575
+
576
+ for (const panel of slice) {
577
+ if (!isPanelData(panel)) {
578
+ continue;
579
+ }
580
+
581
+ const targetPanel = disregardCollapseBuffer
582
+ ? createUnrestrainedPanel(context, panel)
583
+ : panel;
584
+
585
+ if (panelHasSpace(context, targetPanel)) {
586
+ return panel;
587
+ }
588
+ }
589
+ }
590
+
591
+ /** Add up all the static values in the layout */
592
+ function getStaticWidth(context: GroupMachineContextValue) {
593
+ let width = 0;
594
+
595
+ for (const item of context.items) {
596
+ if (isPanelHandle(item)) {
597
+ width += item.size.value;
598
+ } else if (
599
+ isPanelData(item) &&
600
+ item.collapsed &&
601
+ item.currentValue.type === "pixel"
602
+ ) {
603
+ width += item.currentValue.value;
604
+ } else if (
605
+ isPanelData(item) &&
606
+ item.default &&
607
+ item.default.type === "pixel"
608
+ ) {
609
+ width += item.default.value;
610
+ }
611
+ }
612
+
613
+ return width;
614
+ }
615
+
616
+ function formatUnit(unit: ParsedUnit): Unit {
617
+ if (unit.type === "pixel") {
618
+ return `${unit.value}px`;
619
+ }
620
+
621
+ return `${unit.value}%`;
622
+ }
623
+
624
+ /** Build the grid template from the item values. */
625
+ export function buildTemplate(context: GroupMachineContextValue) {
626
+ const staticWidth = getStaticWidth(context);
627
+
628
+ return context.items
629
+ .map((item) => {
630
+ if (item.type === "panel") {
631
+ const min = formatUnit(item.min);
632
+
633
+ if (
634
+ item.currentValue.type === "pixel" &&
635
+ item.currentValue.value !== -1
636
+ ) {
637
+ return formatUnit(item.currentValue);
638
+ } else if (item.currentValue.type === "percent") {
639
+ const max = item.max === "1fr" ? "100%" : formatUnit(item.max);
640
+ return `minmax(${min}, min(calc(${item.currentValue.value} * (100% - ${staticWidth}px)), ${max}))`;
641
+ } else if (item.collapsible && item.collapsed) {
642
+ return formatUnit(item.collapsedSize);
643
+ } else if (item.default) {
644
+ return formatUnit(item.default);
645
+ }
646
+
647
+ const max = item.max === "1fr" ? "1fr" : formatUnit(item.max);
648
+ return `minmax(${min}, ${max})`;
649
+ }
650
+
651
+ return formatUnit(item.size);
652
+ })
653
+ .join(" ");
654
+ }
655
+
656
+ function addDeDuplicatedItems(items: Array<Item>, newItem: Item) {
657
+ const currentItemIndex = items.findIndex(
658
+ (item) =>
659
+ item.id === newItem.id ||
660
+ (typeof item.order === "number" && item.order === newItem.order)
661
+ );
662
+
663
+ let restItems = items;
664
+
665
+ if (currentItemIndex !== -1) {
666
+ restItems = items.filter((_, index) => index !== currentItemIndex);
667
+ }
668
+
669
+ return sortWithOrder([...restItems, newItem]);
670
+ }
671
+
672
+ function createUnrestrainedPanel(
673
+ context: GroupMachineContextValue,
674
+ data: PanelData
675
+ ) {
676
+ return {
677
+ ...data,
678
+ min: makePixelUnit(0),
679
+ max: makePixelUnit(getGroupSize(context)),
680
+ };
681
+ }
682
+
683
+ // #endregion
684
+
685
+ // #region Update Logic
686
+
687
+ /**
688
+ * This is the main meat of the layout logic.
689
+ * It's responsible for figuring out how to distribute the space
690
+ * amongst the panels.
691
+ *
692
+ * It's built around applying small deltas to panels relative to their
693
+ * the resize handles.
694
+ *
695
+ * As much as possible we try to rely on the browser to do the layout.
696
+ * During the initial layout we rely on CSS grid and a group might be
697
+ * defined like this:
698
+ *
699
+ * ```css
700
+ * grid-template-columns: minmax(100px, 1fr) 1px minmax(100px, 300px);
701
+ * ```
702
+ *
703
+ * Without any resizing this is nice and simple and the components don't do much.
704
+ *
705
+ * Once the user starts resizing the layout will be more complex.
706
+ *
707
+ * It's broken down into 3 phases:
708
+ *
709
+ * 1. `prepareItems` - The size of the group has been measure and we
710
+ * can convert all the panel sizes into pixels. Converting into pixels
711
+ * makes doing the math for the updates easier.
712
+ *
713
+ * ```css
714
+ * grid-template-columns: 500px 1px 300px;
715
+ * ```
716
+ *
717
+ * 2. `updateLayout` - This is where the actual updates are applied.
718
+ * This is where the user's drag interactions are applied. We also
719
+ * use this to collapse/expand panels by simulating a drag interaction.
720
+ *
721
+ * ```css
722
+ * grid-template-columns: 490px 1px 310px;
723
+ * ```
724
+ *
725
+ * 3. `commitLayout` - Once the updates have been applied we convert the
726
+ * updated sizes back into a format that allows for easy resizing without
727
+ * lots of updates.
728
+ *
729
+ * ```css
730
+ * grid-template-columns: minmax(100px, min(calc(0.06117 * (100% - 1px)), 100%)) 1px minmax(100px, min(calc(0.0387 * (100% - 1px)), 300px));
731
+ * ```
732
+ *
733
+ * When another update loop is triggered the above template will be converted back to pixels.
734
+ */
735
+
736
+ /** Converts the items to pixels */
737
+ export function prepareItems(context: GroupMachineContextValue) {
738
+ const newItems = [...context.items];
739
+ const staticWidth = getStaticWidth(context);
740
+
741
+ for (const item of newItems) {
742
+ if (!item || !isPanelData(item)) {
743
+ continue;
744
+ }
745
+
746
+ if (item.currentValue.type === "pixel") {
747
+ continue;
748
+ }
749
+
750
+ // TODO: Decimal proposal
751
+ item.currentValue = makePixelUnit(
752
+ Math.round(
753
+ (getGroupSize(context) - staticWidth) * item.currentValue.value
754
+ )
755
+ );
756
+ }
757
+
758
+ return newItems;
759
+ }
760
+
761
+ /** On every mouse move we distribute the space added */
762
+ function updateLayout(
763
+ context: GroupMachineContextValue,
764
+ dragEvent:
765
+ | (DragHandleEvent & {
766
+ controlled?: boolean;
767
+ disregardCollapseBuffer?: never;
768
+ })
769
+ | {
770
+ type: "collapsePanel";
771
+ value: MoveMoveEvent;
772
+ handleId: string;
773
+ controlled?: boolean;
774
+ disregardCollapseBuffer?: boolean;
775
+ }
776
+ ): Partial<GroupMachineContextValue> {
777
+ const handleIndex = getPanelHandleIndex(context, dragEvent.handleId);
778
+ const handle = context.items[handleIndex] as PanelHandleData;
779
+ const newItems = [...context.items];
780
+
781
+ let moveAmount =
782
+ context.orientation === "horizontal"
783
+ ? dragEvent.value.deltaX
784
+ : dragEvent.value.deltaY;
785
+
786
+ if (dragEvent.value.shiftKey) {
787
+ moveAmount *= 15;
788
+ }
789
+
790
+ if (moveAmount === 0) {
791
+ return {};
792
+ }
793
+
794
+ const moveDirection = moveAmount / Math.abs(moveAmount);
795
+
796
+ // Go forward into the shrinking panels to find a panel that still has space.
797
+ const panelBefore = findPanelWithSpace(
798
+ context,
799
+ newItems,
800
+ handleIndex + moveDirection,
801
+ moveDirection,
802
+ dragEvent.disregardCollapseBuffer
803
+ );
804
+
805
+ // No panel with space, just record the drag overshoot
806
+ if (!panelBefore) {
807
+ return {
808
+ dragOvershoot: context.dragOvershoot + moveAmount,
809
+ };
810
+ }
811
+
812
+ invariant(isPanelData(panelBefore), `Expected panel before: ${handle.id}`);
813
+
814
+ const panelAfter = newItems[handleIndex - moveDirection];
815
+
816
+ invariant(
817
+ panelAfter && isPanelData(panelAfter),
818
+ `Expected panel after: ${handle.id}`
819
+ );
820
+
821
+ const newDragOvershoot = context.dragOvershoot + moveAmount;
822
+
823
+ // Don't let the panel expand until the threshold is reached
824
+ if (!dragEvent.disregardCollapseBuffer) {
825
+ if (panelAfter.collapsible && panelAfter.collapsed) {
826
+ const isInLeftBuffer = newDragOvershoot < 0 && moveDirection > 0;
827
+ const isInLeftOvershoot = newDragOvershoot > 0 && moveDirection > 0;
828
+ const isInRightBuffer = newDragOvershoot > 0 && moveDirection < 0;
829
+ const isInRightOvershoot = newDragOvershoot < 0 && moveDirection < 0;
830
+ const potentialNewValue =
831
+ panelAfter.currentValue.value +
832
+ newDragOvershoot * (isInRightBuffer ? moveDirection : 1);
833
+ const min = getUnitPixelValue(context, panelAfter.min);
834
+
835
+ if (
836
+ (newDragOvershoot === 0 ||
837
+ isInRightBuffer ||
838
+ isInLeftBuffer ||
839
+ ((isInLeftOvershoot || isInRightOvershoot) &&
840
+ Math.abs(newDragOvershoot) < COLLAPSE_THRESHOLD)) &&
841
+ potentialNewValue < min
842
+ ) {
843
+ return { dragOvershoot: newDragOvershoot };
844
+ }
845
+ }
846
+ // Don't let the panel collapse until the threshold is reached
847
+ else if (
848
+ panelBefore.collapsible &&
849
+ panelBefore.currentValue.value ===
850
+ getUnitPixelValue(context, panelBefore.min)
851
+ ) {
852
+ const potentialNewValue =
853
+ panelBefore.currentValue.value - Math.abs(newDragOvershoot);
854
+
855
+ if (
856
+ Math.abs(newDragOvershoot) < COLLAPSE_THRESHOLD &&
857
+ potentialNewValue >
858
+ getUnitPixelValue(context, panelBefore.collapsedSize)
859
+ ) {
860
+ return { dragOvershoot: newDragOvershoot };
861
+ }
862
+ }
863
+ }
864
+
865
+ // Apply the move amount to the panel before the slider
866
+ const unrestrainedPanelBefore = createUnrestrainedPanel(context, panelBefore);
867
+ const panelBeforePreviousValue = panelBefore.currentValue.value;
868
+ const panelBeforeNewValueRaw =
869
+ panelBefore.currentValue.value - moveAmount * moveDirection;
870
+ let panelBeforeNewValue = dragEvent.disregardCollapseBuffer
871
+ ? clampUnit(context, unrestrainedPanelBefore, panelBeforeNewValueRaw)
872
+ : clampUnit(context, panelBefore, panelBeforeNewValueRaw);
873
+
874
+ // Also apply the move amount the panel after the slider
875
+ const unrestrainedPanelAfter = createUnrestrainedPanel(context, panelAfter);
876
+ const panelAfterPreviousValue = panelAfter.currentValue.value;
877
+ const applied = panelBeforePreviousValue - panelBeforeNewValue;
878
+ const panelAfterNewValueRaw = panelAfter.currentValue.value + applied;
879
+ let panelAfterNewValue = dragEvent.disregardCollapseBuffer
880
+ ? clampUnit(context, unrestrainedPanelAfter, panelAfterNewValueRaw)
881
+ : clampUnit(context, panelAfter, panelAfterNewValueRaw);
882
+
883
+ if (dragEvent.disregardCollapseBuffer) {
884
+ if (panelAfter.collapsible && panelAfter.collapsed) {
885
+ panelAfter.collapsed = false;
886
+ }
887
+ }
888
+ // If the panel was collapsed, expand it
889
+ // We need to re-apply the move amount since the the expansion of the
890
+ // collapsed panel disregards that.
891
+ else if (panelAfter.collapsible && panelAfter.collapsed) {
892
+ if (
893
+ panelAfter.onCollapseChange?.current &&
894
+ panelAfter.collapseIsControlled &&
895
+ !dragEvent.controlled
896
+ ) {
897
+ panelAfter.onCollapseChange.current(false);
898
+ return { dragOvershoot: newDragOvershoot };
899
+ }
900
+
901
+ // Calculate the amount "extra" after the minSize the panel should grow
902
+ const extra =
903
+ // Take the size it was at
904
+ getUnitPixelValue(context, panelAfter.collapsedSize) +
905
+ // Add in the full overshoot so the cursor is near the slider
906
+ Math.abs(context.dragOvershoot) -
907
+ // Subtract the min size of the panel
908
+ panelAfterNewValue +
909
+ // Then re-add the move amount
910
+ Math.abs(moveAmount);
911
+
912
+ panelAfter.collapsed = false;
913
+ if (extra > 0) {
914
+ panelAfterNewValue += extra;
915
+ }
916
+ panelBeforeNewValue -=
917
+ // Subtract the delta of the after panel's size
918
+ panelAfterNewValue -
919
+ panelAfterPreviousValue -
920
+ // And then re-apply the movement value
921
+ Math.abs(moveAmount);
922
+
923
+ if (
924
+ panelAfter.onCollapseChange?.current &&
925
+ !panelAfter.collapseIsControlled &&
926
+ !dragEvent.controlled
927
+ ) {
928
+ panelAfter.onCollapseChange.current(false);
929
+ }
930
+ }
931
+
932
+ const panelBeforeIsAboutToCollapse =
933
+ panelBefore.currentValue.value ===
934
+ getUnitPixelValue(context, panelBefore.min);
935
+
936
+ // If the panel was expanded and now is at it's min size, collapse it
937
+ if (
938
+ !dragEvent.disregardCollapseBuffer &&
939
+ panelBefore.collapsible &&
940
+ panelBeforeIsAboutToCollapse
941
+ ) {
942
+ if (
943
+ panelBefore.onCollapseChange?.current &&
944
+ panelBefore.collapseIsControlled &&
945
+ !dragEvent.controlled
946
+ ) {
947
+ panelBefore.onCollapseChange.current(true);
948
+ return { dragOvershoot: newDragOvershoot };
949
+ }
950
+
951
+ // Make it collapsed
952
+ panelBefore.collapsed = true;
953
+ panelBeforeNewValue = getUnitPixelValue(context, panelBefore.collapsedSize);
954
+ // Add the extra space created to the before panel
955
+ panelAfterNewValue += panelBeforePreviousValue - panelBeforeNewValue;
956
+
957
+ if (
958
+ panelBefore.onCollapseChange?.current &&
959
+ !panelBefore.collapseIsControlled &&
960
+ !dragEvent.controlled
961
+ ) {
962
+ panelBefore.onCollapseChange.current(true);
963
+ }
964
+ }
965
+
966
+ panelBefore.currentValue = makePixelUnit(panelBeforeNewValue);
967
+ panelAfter.currentValue = makePixelUnit(panelAfterNewValue);
968
+
969
+ const leftoverSpace =
970
+ getGroupSize(context) -
971
+ newItems.reduce(
972
+ (acc, b) =>
973
+ acc +
974
+ // in updateLayout the panel units will always be numbers
975
+ (isPanelData(b) ? b.currentValue.value : b.size.value),
976
+ 0
977
+ );
978
+
979
+ // TODO: this is wrong?
980
+ panelBefore.currentValue.value += leftoverSpace;
981
+
982
+ return { items: newItems, dragOvershoot: 0 };
983
+ }
984
+
985
+ /** Converts the items to percentages */
986
+ export function commitLayout(context: GroupMachineContextValue) {
987
+ const newItems = [...context.items];
988
+
989
+ // First set all the static width
990
+ newItems.forEach((item, index) => {
991
+ if (item.type !== "panel") {
992
+ return;
993
+ }
994
+
995
+ if (item.collapsed) {
996
+ newItems[index] = {
997
+ ...item,
998
+ currentValue: item.collapsedSize,
999
+ };
1000
+ }
1001
+ });
1002
+
1003
+ const staticWidth = getStaticWidth({ ...context, items: newItems });
1004
+
1005
+ newItems.forEach((item, index) => {
1006
+ if (item.type !== "panel" || item.collapsed) {
1007
+ return;
1008
+ }
1009
+
1010
+ newItems[index] = {
1011
+ ...item,
1012
+ currentValue: makePercentUnit(
1013
+ item.currentValue.value / (getGroupSize(context) - staticWidth)
1014
+ ),
1015
+ };
1016
+ });
1017
+
1018
+ return newItems;
1019
+ }
1020
+
1021
+ export function dragHandlePayload({
1022
+ delta,
1023
+ orientation,
1024
+ shiftKey = false,
1025
+ }: {
1026
+ delta: number;
1027
+ orientation: Orientation;
1028
+ shiftKey?: boolean;
1029
+ }) {
1030
+ return {
1031
+ type: "move",
1032
+ pointerType: "keyboard",
1033
+ shiftKey,
1034
+ ctrlKey: false,
1035
+ altKey: false,
1036
+ metaKey: false,
1037
+ deltaX: orientation === "horizontal" ? delta : 0,
1038
+ deltaY: orientation === "horizontal" ? 0 : delta,
1039
+ } as const;
1040
+ }
1041
+
1042
+ /** Iteratively applies a large delta value simulating a user's drag */
1043
+ function iterativelyUpdateLayout({
1044
+ context,
1045
+ handleId,
1046
+ delta,
1047
+ direction,
1048
+ controlled,
1049
+ disregardCollapseBuffer,
1050
+ }: {
1051
+ context: GroupMachineContextValue;
1052
+ handleId: string;
1053
+ delta: number;
1054
+ direction: -1 | 1;
1055
+ controlled?: boolean;
1056
+ disregardCollapseBuffer?: boolean;
1057
+ }) {
1058
+ let newContext: Partial<GroupMachineContextValue> = context;
1059
+
1060
+ for (let i = 0; i < Math.abs(delta); i++) {
1061
+ newContext = updateLayout(
1062
+ {
1063
+ ...context,
1064
+ ...newContext,
1065
+ },
1066
+ {
1067
+ handleId,
1068
+ type: "collapsePanel",
1069
+ controlled,
1070
+ disregardCollapseBuffer,
1071
+ value: dragHandlePayload({
1072
+ delta: direction,
1073
+ orientation: context.orientation,
1074
+ }),
1075
+ }
1076
+ );
1077
+ }
1078
+
1079
+ return newContext;
1080
+ }
1081
+
1082
+ function applyDeltaInBothDirections(
1083
+ context: GroupMachineContextValue,
1084
+ newItems: Array<Item>,
1085
+ itemIndex: number,
1086
+ delta: number
1087
+ ) {
1088
+ let hasTriedBothDirections = false;
1089
+ let direction = 1;
1090
+
1091
+ // Starting from where the items was removed add space to the panels around it.
1092
+ // This is only needed for conditional rendering.
1093
+ while (delta !== 0) {
1094
+ const targetPanel = findPanelWithSpace(
1095
+ context,
1096
+ newItems,
1097
+ itemIndex + direction,
1098
+ direction
1099
+ );
1100
+
1101
+ if (!targetPanel) {
1102
+ if (hasTriedBothDirections) {
1103
+ break;
1104
+ } else {
1105
+ direction = direction === 1 ? -1 : 1;
1106
+ hasTriedBothDirections = true;
1107
+ continue;
1108
+ }
1109
+ }
1110
+
1111
+ const oldValue = targetPanel.currentValue.value;
1112
+ const newValue = clampUnit(context, targetPanel, oldValue + delta);
1113
+
1114
+ targetPanel.currentValue.value = newValue;
1115
+ delta -= newValue - oldValue;
1116
+ direction = direction === 1 ? -1 : 1;
1117
+ }
1118
+ }
1119
+
1120
+ // #endregion
1121
+
1122
+ // #region Machine
1123
+
1124
+ interface AnimationActorInput {
1125
+ context: GroupMachineContextValue;
1126
+ event: CollapsePanelEvent | ExpandPanelEvent;
1127
+ send: (event: GroupMachineEvent) => void;
1128
+ }
1129
+
1130
+ interface AnimationActorOutput {
1131
+ panelId: string;
1132
+ action: "expand" | "collapse";
1133
+ }
1134
+
1135
+ const animationActor = fromPromise<
1136
+ AnimationActorOutput | undefined,
1137
+ AnimationActorInput
1138
+ >(
1139
+ ({ input: { send, context, event } }) =>
1140
+ new Promise<AnimationActorOutput | undefined>((resolve) => {
1141
+ const panel = getPanelWithId(context, event.panelId);
1142
+ const handle = getHandleForPanelId(context, event.panelId);
1143
+
1144
+ let direction = handle.direction;
1145
+ let fullDelta = 0;
1146
+
1147
+ if (event.type === "expandPanel") {
1148
+ fullDelta =
1149
+ (panel.sizeBeforeCollapse ?? getUnitPixelValue(context, panel.min)) -
1150
+ panel.currentValue.value;
1151
+ } else {
1152
+ const collapsedSize = getUnitPixelValue(context, panel.collapsedSize);
1153
+
1154
+ panel.sizeBeforeCollapse = panel.currentValue.value;
1155
+ direction *= -1 as -1 | 1;
1156
+ fullDelta = panel.currentValue.value - collapsedSize;
1157
+ }
1158
+
1159
+ const fps = 60;
1160
+ const { duration, ease } = getCollapseAnimation(panel);
1161
+ const totalFrames = Math.ceil(
1162
+ panel.collapseAnimation ? duration / (1000 / fps) : 1
1163
+ );
1164
+ let frame = 0;
1165
+ let appliedDelta = 0;
1166
+
1167
+ function renderFrame() {
1168
+ const progress = (frame++ + 1) / totalFrames;
1169
+ const e = panel.collapseAnimation ? ease(progress) : 1;
1170
+ const delta = (e * fullDelta - appliedDelta) * direction;
1171
+
1172
+ send({ type: "applyDelta", handleId: handle.item.id, delta });
1173
+ appliedDelta +=
1174
+ Math.abs(delta) *
1175
+ ((delta > 0 && direction === -1) || (delta < 0 && direction === 1)
1176
+ ? -1
1177
+ : 1);
1178
+
1179
+ if (e === 1) {
1180
+ const action = event.type === "expandPanel" ? "expand" : "collapse";
1181
+ resolve({ panelId: panel.id, action });
1182
+ return false;
1183
+ }
1184
+
1185
+ return true;
1186
+ }
1187
+
1188
+ raf(renderFrame);
1189
+ })
1190
+ );
1191
+
1192
+ export const groupMachine = createMachine(
1193
+ {
1194
+ initial: "idle",
1195
+ types: {
1196
+ context: {} as GroupMachineContextValue,
1197
+ events: {} as GroupMachineEvent,
1198
+ input: {} as {
1199
+ autosaveId?: string;
1200
+ orientation?: Orientation;
1201
+ groupId: string;
1202
+ initialItems?: Item[];
1203
+ },
1204
+ },
1205
+ context: ({ input }) => ({
1206
+ size: { width: 0, height: 0 },
1207
+ items: input.initialItems || [],
1208
+ orientation: input.orientation || "horizontal",
1209
+ dragOvershoot: 0,
1210
+ autosaveId: input.autosaveId,
1211
+ groupId: input.groupId,
1212
+ }),
1213
+ states: {
1214
+ idle: {
1215
+ on: {
1216
+ setActualItemsSize: { actions: ["recordActualItemSize"] },
1217
+ dragHandleStart: { target: "dragging" },
1218
+ setPanelPixelSize: {
1219
+ actions: ["prepare", "onSetPanelSize", "commit"],
1220
+ },
1221
+ collapsePanel: [
1222
+ {
1223
+ actions: "notifyCollapseToggle",
1224
+ guard: "shouldNotifyCollapseToggle",
1225
+ },
1226
+ { target: "togglingCollapse" },
1227
+ ],
1228
+ expandPanel: [
1229
+ {
1230
+ actions: "notifyCollapseToggle",
1231
+ guard: "shouldNotifyCollapseToggle",
1232
+ },
1233
+ { target: "togglingCollapse" },
1234
+ ],
1235
+ },
1236
+ },
1237
+ dragging: {
1238
+ entry: ["prepare"],
1239
+ on: {
1240
+ dragHandle: { actions: ["onDragHandle"] },
1241
+ dragHandleEnd: { target: "idle" },
1242
+ collapsePanel: {
1243
+ guard: "shouldCollapseToggle",
1244
+ actions: "runCollapseToggle",
1245
+ },
1246
+ expandPanel: {
1247
+ guard: "shouldCollapseToggle",
1248
+ actions: "runCollapseToggle",
1249
+ },
1250
+ },
1251
+ exit: ["commit", "onAutosave"],
1252
+ },
1253
+ togglingCollapse: {
1254
+ entry: ["prepare"],
1255
+ invoke: {
1256
+ src: "animation",
1257
+ input: (i) => ({ ...i, send: i.self.send }),
1258
+ onDone: {
1259
+ target: "idle",
1260
+ actions: ["onToggleCollapseComplete", "commit", "onAutosave"],
1261
+ },
1262
+ },
1263
+ on: {
1264
+ applyDelta: { actions: ["onApplyDelta"] },
1265
+ },
1266
+ },
1267
+ },
1268
+ on: {
1269
+ registerPanel: { actions: ["assignPanelData"] },
1270
+ registerDynamicPanel: {
1271
+ actions: ["prepare", "onRegisterDynamicPanel", "commit", "onAutosave"],
1272
+ },
1273
+ unregisterPanel: {
1274
+ actions: ["prepare", "removeItem", "commit", "onAutosave"],
1275
+ },
1276
+ registerPanelHandle: { actions: ["assignPanelHandleData"] },
1277
+ unregisterPanelHandle: {
1278
+ actions: ["prepare", "removeItem", "commit", "onAutosave"],
1279
+ },
1280
+ setSize: { actions: ["updateSize"] },
1281
+ setOrientation: { actions: ["updateOrientation"] },
1282
+ },
1283
+ },
1284
+ {
1285
+ guards: {
1286
+ shouldNotifyCollapseToggle: ({ context, event }) => {
1287
+ isEvent(event, ["collapsePanel", "expandPanel"]);
1288
+ const panel = getPanelWithId(context, event.panelId);
1289
+ return !event.controlled && panel.collapseIsControlled === true;
1290
+ },
1291
+ shouldCollapseToggle: ({ context, event }) => {
1292
+ isEvent(event, ["collapsePanel", "expandPanel"]);
1293
+ const panel = getPanelWithId(context, event.panelId);
1294
+ return panel.collapseIsControlled === true;
1295
+ },
1296
+ },
1297
+ actors: {
1298
+ animation: animationActor,
1299
+ },
1300
+ actions: {
1301
+ notifyCollapseToggle: ({ context, event }) => {
1302
+ isEvent(event, ["collapsePanel", "expandPanel"]);
1303
+ const panel = getPanelWithId(context, event.panelId);
1304
+ panel.onCollapseChange?.current?.(!panel.collapsed);
1305
+ },
1306
+ runCollapseToggle: enqueueActions(({ context, event, enqueue }) => {
1307
+ isEvent(event, ["collapsePanel", "expandPanel"]);
1308
+
1309
+ const handle = getHandleForPanelId(context, event.panelId);
1310
+ // When collapsing a panel it will be in the opposite direction
1311
+ // that handle assumes
1312
+ const delta =
1313
+ event.type === "collapsePanel"
1314
+ ? handle.direction * -1
1315
+ : handle.direction;
1316
+ const newContext = updateLayout(context, {
1317
+ handleId: handle.item.id,
1318
+ type: "dragHandle",
1319
+ controlled: event.controlled,
1320
+ value: dragHandlePayload({ delta, orientation: context.orientation }),
1321
+ });
1322
+
1323
+ enqueue.assign(newContext);
1324
+ }),
1325
+ onToggleCollapseComplete: assign({
1326
+ items: ({ context, event: e }) => {
1327
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1328
+ const output = (e as any).output as AnimationActorOutput;
1329
+ invariant(output, "Expected output from animation actor");
1330
+
1331
+ const panel = getPanelWithId(context, output.panelId);
1332
+ panel.collapsed = output.action === "collapse";
1333
+
1334
+ if (panel.collapsed) {
1335
+ panel.currentValue = panel.collapsedSize;
1336
+ }
1337
+
1338
+ return context.items;
1339
+ },
1340
+ }),
1341
+ updateSize: assign({
1342
+ size: ({ event }) => {
1343
+ isEvent(event, ["setSize"]);
1344
+ return event.size;
1345
+ },
1346
+ }),
1347
+ recordActualItemSize: assign({
1348
+ items: ({ context, event }) => {
1349
+ isEvent(event, ["setActualItemsSize"]);
1350
+
1351
+ const orientation = context.orientation;
1352
+
1353
+ for (const [id, size] of Object.entries(event.childrenSizes)) {
1354
+ const item = context.items.find((i) => i.id === id);
1355
+
1356
+ if (!isPanelData(item)) {
1357
+ continue;
1358
+ }
1359
+
1360
+ item.currentValue = makePixelUnit(
1361
+ orientation === "horizontal" ? size.width : size.height
1362
+ );
1363
+ }
1364
+
1365
+ return commitLayout(context);
1366
+ },
1367
+ }),
1368
+ updateOrientation: assign({
1369
+ orientation: ({ event }) => {
1370
+ isEvent(event, ["setOrientation"]);
1371
+ return event.orientation;
1372
+ },
1373
+ }),
1374
+ assignPanelData: assign({
1375
+ items: ({ context, event }) => {
1376
+ isEvent(event, ["registerPanel"]);
1377
+
1378
+ return addDeDuplicatedItems(context.items, {
1379
+ type: "panel",
1380
+ currentValue: makePixelUnit(-1),
1381
+ ...event.data,
1382
+ });
1383
+ },
1384
+ }),
1385
+ onRegisterDynamicPanel: assign({
1386
+ items: ({ context, event }) => {
1387
+ isEvent(event, ["registerDynamicPanel"]);
1388
+
1389
+ let currentValue: ParsedUnit = makePixelUnit(0);
1390
+
1391
+ if (
1392
+ event.data.collapsible &&
1393
+ event.data.collapsed &&
1394
+ event.data.collapsedSize
1395
+ ) {
1396
+ currentValue = event.data.collapsedSize;
1397
+ } else if (event.data.default) {
1398
+ currentValue = event.data.default;
1399
+ } else {
1400
+ currentValue = event.data.min;
1401
+ }
1402
+
1403
+ const newItems = addDeDuplicatedItems(context.items, {
1404
+ type: "panel",
1405
+ ...event.data,
1406
+ currentValue,
1407
+ });
1408
+ const itemIndex = newItems.findIndex(
1409
+ (item) => item.id === event.data.id
1410
+ );
1411
+ const newContext = { ...context, items: newItems };
1412
+ const overflowDueToHandles =
1413
+ context.items.reduce((acc, i) => {
1414
+ if (isPanelHandle(i)) {
1415
+ return acc + getUnitPixelValue(context, i.size);
1416
+ }
1417
+
1418
+ return acc + i.currentValue.value;
1419
+ }, 0) - getGroupSize(context);
1420
+
1421
+ applyDeltaInBothDirections(
1422
+ newContext,
1423
+ newItems,
1424
+ itemIndex,
1425
+ -1 * (currentValue.value + overflowDueToHandles)
1426
+ );
1427
+
1428
+ return newItems;
1429
+ },
1430
+ }),
1431
+ assignPanelHandleData: assign({
1432
+ items: ({ context, event }) => {
1433
+ isEvent(event, ["registerPanelHandle"]);
1434
+
1435
+ return addDeDuplicatedItems(context.items, {
1436
+ type: "handle",
1437
+ ...event.data,
1438
+ size: event.data.size as ParsedPixelUnit,
1439
+ });
1440
+ },
1441
+ }),
1442
+ removeItem: assign({
1443
+ items: ({ context, event }) => {
1444
+ isEvent(event, ["unregisterPanel", "unregisterPanelHandle"]);
1445
+ const itemIndex = context.items.findIndex(
1446
+ (item) => item.id === event.id
1447
+ );
1448
+ const item = context.items[itemIndex];
1449
+
1450
+ if (!item) {
1451
+ return context.items;
1452
+ }
1453
+
1454
+ const newItems = context.items.filter((i) => i.id !== event.id);
1455
+ const removedSize = isPanelData(item)
1456
+ ? item.currentValue.value
1457
+ : item.size.value;
1458
+
1459
+ applyDeltaInBothDirections(context, newItems, itemIndex, removedSize);
1460
+
1461
+ return newItems;
1462
+ },
1463
+ }),
1464
+ prepare: assign({
1465
+ items: ({ context }) => prepareItems(context),
1466
+ }),
1467
+ onDragHandle: enqueueActions(({ context, event, enqueue }) => {
1468
+ isEvent(event, ["dragHandle"]);
1469
+ enqueue.assign(updateLayout(context, event));
1470
+ }),
1471
+ commit: assign({
1472
+ dragOvershoot: 0,
1473
+ items: ({ context }) => commitLayout(context),
1474
+ }),
1475
+ onApplyDelta: assign(({ context, event }) => {
1476
+ isEvent(event, ["applyDelta"]);
1477
+ return updateLayout(context, {
1478
+ handleId: event.handleId,
1479
+ type: "collapsePanel",
1480
+ disregardCollapseBuffer: true,
1481
+ value: dragHandlePayload({
1482
+ delta: event.delta,
1483
+ orientation: context.orientation,
1484
+ }),
1485
+ });
1486
+ }),
1487
+ onSetPanelSize: enqueueActions(({ context, event, enqueue }) => {
1488
+ isEvent(event, ["setPanelPixelSize"]);
1489
+
1490
+ const panel = getPanelWithId(context, event.panelId);
1491
+ const handle = getHandleForPanelId(context, event.panelId);
1492
+ const current = panel.currentValue.value;
1493
+ const newSize = clampUnit(
1494
+ context,
1495
+ panel,
1496
+ getUnitPixelValue(context, parseUnit(event.size))
1497
+ );
1498
+ const isBigger = newSize > current;
1499
+ const delta = isBigger ? newSize - current : current - newSize;
1500
+
1501
+ enqueue.assign(
1502
+ iterativelyUpdateLayout({
1503
+ context,
1504
+ direction: (handle.direction * (isBigger ? 1 : -1)) as -1 | 1,
1505
+ handleId: handle.item.id,
1506
+ delta,
1507
+ })
1508
+ );
1509
+ }),
1510
+ },
1511
+ }
1512
+ );
1513
+
1514
+ // #endregion