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