@iamevan/react-resizable-panels 3.0.6

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 (30) hide show
  1. package/README.md +260 -0
  2. package/dist/declarations/src/Panel.d.ts +70 -0
  3. package/dist/declarations/src/PanelGroup.d.ts +38 -0
  4. package/dist/declarations/src/PanelResizeHandle.d.ts +23 -0
  5. package/dist/declarations/src/PanelResizeHandleRegistry.d.ts +19 -0
  6. package/dist/declarations/src/constants.d.ts +15 -0
  7. package/dist/declarations/src/hooks/usePanelGroupContext.d.ts +4 -0
  8. package/dist/declarations/src/index.d.ts +23 -0
  9. package/dist/declarations/src/types.d.ts +3 -0
  10. package/dist/declarations/src/utils/assert.d.ts +1 -0
  11. package/dist/declarations/src/utils/csp.d.ts +2 -0
  12. package/dist/declarations/src/utils/cursor.d.ts +18 -0
  13. package/dist/declarations/src/utils/dom/getPanelElement.d.ts +1 -0
  14. package/dist/declarations/src/utils/dom/getPanelElementsForGroup.d.ts +1 -0
  15. package/dist/declarations/src/utils/dom/getPanelGroupElement.d.ts +1 -0
  16. package/dist/declarations/src/utils/dom/getResizeHandleElement.d.ts +1 -0
  17. package/dist/declarations/src/utils/dom/getResizeHandleElementIndex.d.ts +1 -0
  18. package/dist/declarations/src/utils/dom/getResizeHandleElementsForGroup.d.ts +1 -0
  19. package/dist/declarations/src/utils/dom/getResizeHandlePanelIds.d.ts +2 -0
  20. package/dist/declarations/src/utils/rects/getIntersectingRectangle.d.ts +2 -0
  21. package/dist/declarations/src/utils/rects/intersects.d.ts +2 -0
  22. package/dist/declarations/src/utils/rects/types.d.ts +6 -0
  23. package/dist/iamevan-react-resizable-panels.browser.development.js +2592 -0
  24. package/dist/iamevan-react-resizable-panels.browser.js +2486 -0
  25. package/dist/iamevan-react-resizable-panels.d.ts +2 -0
  26. package/dist/iamevan-react-resizable-panels.development.edge-light.js +2365 -0
  27. package/dist/iamevan-react-resizable-panels.development.js +2599 -0
  28. package/dist/iamevan-react-resizable-panels.edge-light.js +2264 -0
  29. package/dist/iamevan-react-resizable-panels.js +2488 -0
  30. package/package.json +84 -0
@@ -0,0 +1,2592 @@
1
+ import * as React from 'react';
2
+ import { createContext, useLayoutEffect, useRef, forwardRef, createElement, useContext, useImperativeHandle, useState, useCallback, useEffect, useMemo } from 'react';
3
+
4
+ // The "contextmenu" event is not supported as a PointerEvent in all browsers yet, so MouseEvent still need to be handled
5
+
6
+ const PanelGroupContext = createContext(null);
7
+ PanelGroupContext.displayName = "PanelGroupContext";
8
+
9
+ const DATA_ATTRIBUTES = {
10
+ group: "data-panel-group",
11
+ groupDirection: "data-panel-group-direction",
12
+ groupId: "data-panel-group-id",
13
+ panel: "data-panel",
14
+ panelCollapsible: "data-panel-collapsible",
15
+ panelId: "data-panel-id",
16
+ panelSize: "data-panel-size",
17
+ resizeHandle: "data-resize-handle",
18
+ resizeHandleActive: "data-resize-handle-active",
19
+ resizeHandleEnabled: "data-panel-resize-handle-enabled",
20
+ resizeHandleId: "data-panel-resize-handle-id",
21
+ resizeHandleState: "data-resize-handle-state"
22
+ };
23
+ const PRECISION = 10;
24
+
25
+ const useIsomorphicLayoutEffect = useLayoutEffect ;
26
+
27
+ const useId = React["useId".toString()];
28
+ const wrappedUseId = typeof useId === "function" ? useId : () => null;
29
+ let counter = 0;
30
+ function useUniqueId(idFromParams = null) {
31
+ const idFromUseId = wrappedUseId();
32
+ const idRef = useRef(idFromParams || idFromUseId || null);
33
+ if (idRef.current === null) {
34
+ idRef.current = "" + counter++;
35
+ }
36
+ return idFromParams !== null && idFromParams !== void 0 ? idFromParams : idRef.current;
37
+ }
38
+
39
+ function PanelWithForwardedRef({
40
+ children,
41
+ className: classNameFromProps = "",
42
+ collapsedSize,
43
+ collapsible,
44
+ defaultSize,
45
+ forwardedRef,
46
+ id: idFromProps,
47
+ maxSize,
48
+ minSize,
49
+ onCollapse,
50
+ onExpand,
51
+ onResize,
52
+ order,
53
+ style: styleFromProps,
54
+ tagName: Type = "div",
55
+ ...rest
56
+ }) {
57
+ const context = useContext(PanelGroupContext);
58
+ if (context === null) {
59
+ throw Error(`Panel components must be rendered within a PanelGroup container`);
60
+ }
61
+ const {
62
+ collapsePanel,
63
+ expandPanel,
64
+ getPanelSize,
65
+ getPanelStyle,
66
+ groupId,
67
+ isPanelCollapsed,
68
+ reevaluatePanelConstraints,
69
+ registerPanel,
70
+ resizePanel,
71
+ unregisterPanel
72
+ } = context;
73
+ const panelId = useUniqueId(idFromProps);
74
+ const panelDataRef = useRef({
75
+ callbacks: {
76
+ onCollapse,
77
+ onExpand,
78
+ onResize
79
+ },
80
+ constraints: {
81
+ collapsedSize,
82
+ collapsible,
83
+ defaultSize,
84
+ maxSize,
85
+ minSize
86
+ },
87
+ id: panelId,
88
+ idIsFromProps: idFromProps !== undefined,
89
+ order
90
+ });
91
+ const devWarningsRef = useRef({
92
+ didLogMissingDefaultSizeWarning: false
93
+ });
94
+
95
+ // Normally we wouldn't log a warning during render,
96
+ // but effects don't run on the server, so we can't do it there
97
+ {
98
+ if (!devWarningsRef.current.didLogMissingDefaultSizeWarning) ;
99
+ }
100
+ useIsomorphicLayoutEffect(() => {
101
+ const {
102
+ callbacks,
103
+ constraints
104
+ } = panelDataRef.current;
105
+ const prevConstraints = {
106
+ ...constraints
107
+ };
108
+ panelDataRef.current.id = panelId;
109
+ panelDataRef.current.idIsFromProps = idFromProps !== undefined;
110
+ panelDataRef.current.order = order;
111
+ callbacks.onCollapse = onCollapse;
112
+ callbacks.onExpand = onExpand;
113
+ callbacks.onResize = onResize;
114
+ constraints.collapsedSize = collapsedSize;
115
+ constraints.collapsible = collapsible;
116
+ constraints.defaultSize = defaultSize;
117
+ constraints.maxSize = maxSize;
118
+ constraints.minSize = minSize;
119
+
120
+ // If constraints have changed, we should revisit panel sizes.
121
+ // This is uncommon but may happen if people are trying to implement pixel based constraints.
122
+ if (prevConstraints.collapsedSize !== constraints.collapsedSize || prevConstraints.collapsible !== constraints.collapsible || prevConstraints.maxSize !== constraints.maxSize || prevConstraints.minSize !== constraints.minSize) {
123
+ reevaluatePanelConstraints(panelDataRef.current, prevConstraints);
124
+ }
125
+ });
126
+ useIsomorphicLayoutEffect(() => {
127
+ const panelData = panelDataRef.current;
128
+ registerPanel(panelData);
129
+ return () => {
130
+ unregisterPanel(panelData);
131
+ };
132
+ }, [order, panelId, registerPanel, unregisterPanel]);
133
+ useImperativeHandle(forwardedRef, () => ({
134
+ collapse: () => {
135
+ collapsePanel(panelDataRef.current);
136
+ },
137
+ expand: minSize => {
138
+ expandPanel(panelDataRef.current, minSize);
139
+ },
140
+ getId() {
141
+ return panelId;
142
+ },
143
+ getSize() {
144
+ return getPanelSize(panelDataRef.current);
145
+ },
146
+ isCollapsed() {
147
+ return isPanelCollapsed(panelDataRef.current);
148
+ },
149
+ isExpanded() {
150
+ return !isPanelCollapsed(panelDataRef.current);
151
+ },
152
+ resize: size => {
153
+ resizePanel(panelDataRef.current, size);
154
+ }
155
+ }), [collapsePanel, expandPanel, getPanelSize, isPanelCollapsed, panelId, resizePanel]);
156
+ const style = getPanelStyle(panelDataRef.current, defaultSize);
157
+ return createElement(Type, {
158
+ ...rest,
159
+ children,
160
+ className: classNameFromProps,
161
+ id: panelId,
162
+ style: {
163
+ ...style,
164
+ ...styleFromProps
165
+ },
166
+ // CSS selectors
167
+ [DATA_ATTRIBUTES.groupId]: groupId,
168
+ [DATA_ATTRIBUTES.panel]: "",
169
+ [DATA_ATTRIBUTES.panelCollapsible]: collapsible || undefined,
170
+ [DATA_ATTRIBUTES.panelId]: panelId,
171
+ [DATA_ATTRIBUTES.panelSize]: parseFloat("" + style.flexGrow).toFixed(1)
172
+ });
173
+ }
174
+ const Panel = forwardRef((props, ref) => createElement(PanelWithForwardedRef, {
175
+ ...props,
176
+ forwardedRef: ref
177
+ }));
178
+ PanelWithForwardedRef.displayName = "Panel";
179
+ Panel.displayName = "forwardRef(Panel)";
180
+
181
+ let nonce;
182
+ function getNonce() {
183
+ return nonce;
184
+ }
185
+ function setNonce(value) {
186
+ nonce = value;
187
+ }
188
+
189
+ let currentCursorStyle = null;
190
+ let enabled = true;
191
+ let getCustomCursorStyleFunction = null;
192
+ let prevRuleIndex = -1;
193
+ let styleElement = null;
194
+ function customizeGlobalCursorStyles(callback) {
195
+ getCustomCursorStyleFunction = callback;
196
+ }
197
+ function disableGlobalCursorStyles() {
198
+ enabled = false;
199
+ }
200
+ function enableGlobalCursorStyles() {
201
+ enabled = true;
202
+ }
203
+ function getCursorStyle(state, constraintFlags, isPointerDown) {
204
+ const horizontalMin = (constraintFlags & EXCEEDED_HORIZONTAL_MIN) !== 0;
205
+ const horizontalMax = (constraintFlags & EXCEEDED_HORIZONTAL_MAX) !== 0;
206
+ const verticalMin = (constraintFlags & EXCEEDED_VERTICAL_MIN) !== 0;
207
+ const verticalMax = (constraintFlags & EXCEEDED_VERTICAL_MAX) !== 0;
208
+ if (getCustomCursorStyleFunction) {
209
+ return getCustomCursorStyleFunction({
210
+ exceedsHorizontalMaximum: horizontalMax,
211
+ exceedsHorizontalMinimum: horizontalMin,
212
+ exceedsVerticalMaximum: verticalMax,
213
+ exceedsVerticalMinimum: verticalMin,
214
+ intersectsHorizontalDragHandle: state === "horizontal" || state === "intersection",
215
+ intersectsVerticalDragHandle: state === "vertical" || state === "intersection",
216
+ isPointerDown
217
+ });
218
+ }
219
+ if (constraintFlags) {
220
+ if (horizontalMin) {
221
+ if (verticalMin) {
222
+ return "se-resize";
223
+ } else if (verticalMax) {
224
+ return "ne-resize";
225
+ } else {
226
+ return "e-resize";
227
+ }
228
+ } else if (horizontalMax) {
229
+ if (verticalMin) {
230
+ return "sw-resize";
231
+ } else if (verticalMax) {
232
+ return "nw-resize";
233
+ } else {
234
+ return "w-resize";
235
+ }
236
+ } else if (verticalMin) {
237
+ return "s-resize";
238
+ } else if (verticalMax) {
239
+ return "n-resize";
240
+ }
241
+ }
242
+ switch (state) {
243
+ case "horizontal":
244
+ return "ew-resize";
245
+ case "intersection":
246
+ return "move";
247
+ case "vertical":
248
+ return "ns-resize";
249
+ }
250
+ }
251
+ function resetGlobalCursorStyle() {
252
+ if (styleElement !== null) {
253
+ document.head.removeChild(styleElement);
254
+ currentCursorStyle = null;
255
+ styleElement = null;
256
+ prevRuleIndex = -1;
257
+ }
258
+ }
259
+ function setGlobalCursorStyle(state, constraintFlags, isPointerDown) {
260
+ var _styleElement$sheet$i, _styleElement$sheet2;
261
+ if (!enabled) {
262
+ return;
263
+ }
264
+ const style = getCursorStyle(state, constraintFlags, isPointerDown);
265
+ if (currentCursorStyle === style) {
266
+ return;
267
+ }
268
+ currentCursorStyle = style;
269
+ if (styleElement === null) {
270
+ styleElement = document.createElement("style");
271
+ const nonce = getNonce();
272
+ if (nonce) {
273
+ styleElement.setAttribute("nonce", nonce);
274
+ }
275
+ document.head.appendChild(styleElement);
276
+ }
277
+ if (prevRuleIndex >= 0) {
278
+ var _styleElement$sheet;
279
+ (_styleElement$sheet = styleElement.sheet) === null || _styleElement$sheet === void 0 ? void 0 : _styleElement$sheet.removeRule(prevRuleIndex);
280
+ }
281
+ prevRuleIndex = (_styleElement$sheet$i = (_styleElement$sheet2 = styleElement.sheet) === null || _styleElement$sheet2 === void 0 ? void 0 : _styleElement$sheet2.insertRule(`*{cursor: ${style} !important;}`)) !== null && _styleElement$sheet$i !== void 0 ? _styleElement$sheet$i : -1;
282
+ }
283
+
284
+ function isKeyDown(event) {
285
+ return event.type === "keydown";
286
+ }
287
+ function isPointerEvent(event) {
288
+ return event.type.startsWith("pointer");
289
+ }
290
+ function isMouseEvent(event) {
291
+ return event.type.startsWith("mouse");
292
+ }
293
+
294
+ function getResizeEventCoordinates(event) {
295
+ if (isPointerEvent(event)) {
296
+ if (event.isPrimary) {
297
+ return {
298
+ x: event.clientX,
299
+ y: event.clientY
300
+ };
301
+ }
302
+ } else if (isMouseEvent(event)) {
303
+ return {
304
+ x: event.clientX,
305
+ y: event.clientY
306
+ };
307
+ }
308
+ return {
309
+ x: Infinity,
310
+ y: Infinity
311
+ };
312
+ }
313
+
314
+ function getInputType() {
315
+ if (typeof matchMedia === "function") {
316
+ return matchMedia("(pointer:coarse)").matches ? "coarse" : "fine";
317
+ }
318
+ }
319
+
320
+ function intersects(rectOne, rectTwo, strict) {
321
+ if (strict) {
322
+ return rectOne.x < rectTwo.x + rectTwo.width && rectOne.x + rectOne.width > rectTwo.x && rectOne.y < rectTwo.y + rectTwo.height && rectOne.y + rectOne.height > rectTwo.y;
323
+ } else {
324
+ return rectOne.x <= rectTwo.x + rectTwo.width && rectOne.x + rectOne.width >= rectTwo.x && rectOne.y <= rectTwo.y + rectTwo.height && rectOne.y + rectOne.height >= rectTwo.y;
325
+ }
326
+ }
327
+
328
+ // Forked from NPM stacking-order@2.0.0
329
+
330
+ /**
331
+ * Determine which of two nodes appears in front of the other —
332
+ * if `a` is in front, returns 1, otherwise returns -1
333
+ * @param {HTMLElement | SVGElement} a
334
+ * @param {HTMLElement | SVGElement} b
335
+ */
336
+ function compare(a, b) {
337
+ if (a === b) throw new Error("Cannot compare node with itself");
338
+ const ancestors = {
339
+ a: get_ancestors(a),
340
+ b: get_ancestors(b)
341
+ };
342
+ let common_ancestor;
343
+
344
+ // remove shared ancestors
345
+ while (ancestors.a.at(-1) === ancestors.b.at(-1)) {
346
+ a = ancestors.a.pop();
347
+ b = ancestors.b.pop();
348
+ common_ancestor = a;
349
+ }
350
+ assert(common_ancestor, "Stacking order can only be calculated for elements with a common ancestor");
351
+ const z_indexes = {
352
+ a: get_z_index(find_stacking_context(ancestors.a)),
353
+ b: get_z_index(find_stacking_context(ancestors.b))
354
+ };
355
+ if (z_indexes.a === z_indexes.b) {
356
+ const children = common_ancestor.childNodes;
357
+ const furthest_ancestors = {
358
+ a: ancestors.a.at(-1),
359
+ b: ancestors.b.at(-1)
360
+ };
361
+ let i = children.length;
362
+ while (i--) {
363
+ const child = children[i];
364
+ if (child === furthest_ancestors.a) return 1;
365
+ if (child === furthest_ancestors.b) return -1;
366
+ }
367
+ }
368
+ return Math.sign(z_indexes.a - z_indexes.b);
369
+ }
370
+ const props = /\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;
371
+
372
+ /** @param {HTMLElement | SVGElement} node */
373
+ function is_flex_item(node) {
374
+ var _get_parent;
375
+ // @ts-ignore
376
+ const display = getComputedStyle((_get_parent = get_parent(node)) !== null && _get_parent !== void 0 ? _get_parent : node).display;
377
+ return display === "flex" || display === "inline-flex";
378
+ }
379
+
380
+ /** @param {HTMLElement | SVGElement} node */
381
+ function creates_stacking_context(node) {
382
+ const style = getComputedStyle(node);
383
+
384
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context
385
+ if (style.position === "fixed") return true;
386
+ // Forked to fix upstream bug https://github.com/Rich-Harris/stacking-order/issues/3
387
+ // if (
388
+ // (style.zIndex !== "auto" && style.position !== "static") ||
389
+ // is_flex_item(node)
390
+ // )
391
+ if (style.zIndex !== "auto" && (style.position !== "static" || is_flex_item(node))) return true;
392
+ if (+style.opacity < 1) return true;
393
+ if ("transform" in style && style.transform !== "none") return true;
394
+ if ("webkitTransform" in style && style.webkitTransform !== "none") return true;
395
+ if ("mixBlendMode" in style && style.mixBlendMode !== "normal") return true;
396
+ if ("filter" in style && style.filter !== "none") return true;
397
+ if ("webkitFilter" in style && style.webkitFilter !== "none") return true;
398
+ if ("isolation" in style && style.isolation === "isolate") return true;
399
+ if (props.test(style.willChange)) return true;
400
+ // @ts-expect-error
401
+ if (style.webkitOverflowScrolling === "touch") return true;
402
+ return false;
403
+ }
404
+
405
+ /** @param {(HTMLElement| SVGElement)[]} nodes */
406
+ function find_stacking_context(nodes) {
407
+ let i = nodes.length;
408
+ while (i--) {
409
+ const node = nodes[i];
410
+ assert(node, "Missing node");
411
+ if (creates_stacking_context(node)) return node;
412
+ }
413
+ return null;
414
+ }
415
+
416
+ /** @param {HTMLElement | SVGElement} node */
417
+ function get_z_index(node) {
418
+ return node && Number(getComputedStyle(node).zIndex) || 0;
419
+ }
420
+
421
+ /** @param {HTMLElement} node */
422
+ function get_ancestors(node) {
423
+ const ancestors = [];
424
+ while (node) {
425
+ ancestors.push(node);
426
+ // @ts-ignore
427
+ node = get_parent(node);
428
+ }
429
+ return ancestors; // [ node, ... <body>, <html>, document ]
430
+ }
431
+
432
+ /** @param {HTMLElement} node */
433
+ function get_parent(node) {
434
+ const {
435
+ parentNode
436
+ } = node;
437
+ if (parentNode && parentNode instanceof ShadowRoot) {
438
+ return parentNode.host;
439
+ }
440
+ return parentNode;
441
+ }
442
+
443
+ const EXCEEDED_HORIZONTAL_MIN = 0b0001;
444
+ const EXCEEDED_HORIZONTAL_MAX = 0b0010;
445
+ const EXCEEDED_VERTICAL_MIN = 0b0100;
446
+ const EXCEEDED_VERTICAL_MAX = 0b1000;
447
+ const isCoarsePointer = getInputType() === "coarse";
448
+ let intersectingHandles = [];
449
+ let isPointerDown = false;
450
+ let ownerDocumentCounts = new Map();
451
+ let panelConstraintFlags = new Map();
452
+ const registeredResizeHandlers = new Set();
453
+ function registerResizeHandle(resizeHandleId, element, direction, hitAreaMargins, setResizeHandlerState) {
454
+ var _ownerDocumentCounts$;
455
+ const {
456
+ ownerDocument
457
+ } = element;
458
+ const data = {
459
+ direction,
460
+ element,
461
+ hitAreaMargins,
462
+ setResizeHandlerState
463
+ };
464
+ const count = (_ownerDocumentCounts$ = ownerDocumentCounts.get(ownerDocument)) !== null && _ownerDocumentCounts$ !== void 0 ? _ownerDocumentCounts$ : 0;
465
+ ownerDocumentCounts.set(ownerDocument, count + 1);
466
+ registeredResizeHandlers.add(data);
467
+ updateListeners();
468
+ return function unregisterResizeHandle() {
469
+ var _ownerDocumentCounts$2;
470
+ panelConstraintFlags.delete(resizeHandleId);
471
+ registeredResizeHandlers.delete(data);
472
+ const count = (_ownerDocumentCounts$2 = ownerDocumentCounts.get(ownerDocument)) !== null && _ownerDocumentCounts$2 !== void 0 ? _ownerDocumentCounts$2 : 1;
473
+ ownerDocumentCounts.set(ownerDocument, count - 1);
474
+ updateListeners();
475
+ if (count === 1) {
476
+ ownerDocumentCounts.delete(ownerDocument);
477
+ }
478
+
479
+ // If the resize handle that is currently unmounting is intersecting with the pointer,
480
+ // update the global pointer to account for the change
481
+ if (intersectingHandles.includes(data)) {
482
+ const index = intersectingHandles.indexOf(data);
483
+ if (index >= 0) {
484
+ intersectingHandles.splice(index, 1);
485
+ }
486
+ updateCursor();
487
+
488
+ // Also instruct the handle to stop dragging; this prevents the parent group from being left in an inconsistent state
489
+ // See github.com/bvaughn/react-resizable-panels/issues/402
490
+ setResizeHandlerState("up", true, null);
491
+ }
492
+ };
493
+ }
494
+ function handlePointerDown(event) {
495
+ const {
496
+ target
497
+ } = event;
498
+ const {
499
+ x,
500
+ y
501
+ } = getResizeEventCoordinates(event);
502
+ isPointerDown = true;
503
+ recalculateIntersectingHandles({
504
+ target,
505
+ x,
506
+ y
507
+ });
508
+ updateListeners();
509
+ if (intersectingHandles.length > 0) {
510
+ updateResizeHandlerStates("down", event);
511
+
512
+ // Update cursor based on return value(s) from active handles
513
+ updateCursor();
514
+ event.preventDefault();
515
+ if (!isWithinResizeHandle(target)) {
516
+ event.stopImmediatePropagation();
517
+ }
518
+ }
519
+ }
520
+ function handlePointerMove(event) {
521
+ const {
522
+ x,
523
+ y
524
+ } = getResizeEventCoordinates(event);
525
+
526
+ // Edge case (see #340)
527
+ // Detect when the pointer has been released outside an iframe on a different domain
528
+ if (isPointerDown &&
529
+ // Skip this check for "pointerleave" events, else Firefox triggers a false positive (see #514)
530
+ event.type !== "pointerleave" && event.buttons === 0) {
531
+ isPointerDown = false;
532
+ updateResizeHandlerStates("up", event);
533
+ }
534
+ if (!isPointerDown) {
535
+ const {
536
+ target
537
+ } = event;
538
+
539
+ // Recalculate intersecting handles whenever the pointer moves, except if it has already been pressed
540
+ // at that point, the handles may not move with the pointer (depending on constraints)
541
+ // but the same set of active handles should be locked until the pointer is released
542
+ recalculateIntersectingHandles({
543
+ target,
544
+ x,
545
+ y
546
+ });
547
+ }
548
+ updateResizeHandlerStates("move", event);
549
+
550
+ // Update cursor based on return value(s) from active handles
551
+ updateCursor();
552
+ if (intersectingHandles.length > 0) {
553
+ event.preventDefault();
554
+ }
555
+ }
556
+ function handlePointerUp(event) {
557
+ const {
558
+ target
559
+ } = event;
560
+ const {
561
+ x,
562
+ y
563
+ } = getResizeEventCoordinates(event);
564
+ panelConstraintFlags.clear();
565
+ isPointerDown = false;
566
+ if (intersectingHandles.length > 0) {
567
+ event.preventDefault();
568
+ if (!isWithinResizeHandle(target)) {
569
+ event.stopImmediatePropagation();
570
+ }
571
+ }
572
+ updateResizeHandlerStates("up", event);
573
+ recalculateIntersectingHandles({
574
+ target,
575
+ x,
576
+ y
577
+ });
578
+ updateCursor();
579
+ updateListeners();
580
+ }
581
+ function isWithinResizeHandle(element) {
582
+ let currentElement = element;
583
+ while (currentElement) {
584
+ if (currentElement.hasAttribute(DATA_ATTRIBUTES.resizeHandle)) {
585
+ return true;
586
+ }
587
+ currentElement = currentElement.parentElement;
588
+ }
589
+ return false;
590
+ }
591
+ function recalculateIntersectingHandles({
592
+ target,
593
+ x,
594
+ y
595
+ }) {
596
+ intersectingHandles.splice(0);
597
+ let targetElement = null;
598
+ if (target instanceof HTMLElement || target instanceof SVGElement) {
599
+ targetElement = target;
600
+ }
601
+ registeredResizeHandlers.forEach(data => {
602
+ const {
603
+ element: dragHandleElement,
604
+ hitAreaMargins
605
+ } = data;
606
+ const dragHandleRect = dragHandleElement.getBoundingClientRect();
607
+ const {
608
+ bottom,
609
+ left,
610
+ right,
611
+ top
612
+ } = dragHandleRect;
613
+ const margin = isCoarsePointer ? hitAreaMargins.coarse : hitAreaMargins.fine;
614
+ const eventIntersects = x >= left - margin && x <= right + margin && y >= top - margin && y <= bottom + margin;
615
+ if (eventIntersects) {
616
+ // TRICKY
617
+ // We listen for pointers events at the root in order to support hit area margins
618
+ // (determining when the pointer is close enough to an element to be considered a "hit")
619
+ // Clicking on an element "above" a handle (e.g. a modal) should prevent a hit though
620
+ // so at this point we need to compare stacking order of a potentially intersecting drag handle,
621
+ // and the element that was actually clicked/touched
622
+ if (targetElement !== null && document.contains(targetElement) && dragHandleElement !== targetElement && !dragHandleElement.contains(targetElement) && !targetElement.contains(dragHandleElement) &&
623
+ // Calculating stacking order has a cost, so we should avoid it if possible
624
+ // That is why we only check potentially intersecting handles,
625
+ // and why we skip if the event target is within the handle's DOM
626
+ compare(targetElement, dragHandleElement) > 0) {
627
+ // If the target is above the drag handle, then we also need to confirm they overlap
628
+ // If they are beside each other (e.g. a panel and its drag handle) then the handle is still interactive
629
+ //
630
+ // It's not enough to compare only the target
631
+ // The target might be a small element inside of a larger container
632
+ // (For example, a SPAN or a DIV inside of a larger modal dialog)
633
+ let currentElement = targetElement;
634
+ let didIntersect = false;
635
+ while (currentElement) {
636
+ if (currentElement.contains(dragHandleElement)) {
637
+ break;
638
+ } else if (intersects(currentElement.getBoundingClientRect(), dragHandleRect, true)) {
639
+ didIntersect = true;
640
+ break;
641
+ }
642
+ currentElement = currentElement.parentElement;
643
+ }
644
+ if (didIntersect) {
645
+ return;
646
+ }
647
+ }
648
+ intersectingHandles.push(data);
649
+ }
650
+ });
651
+ }
652
+ function reportConstraintsViolation(resizeHandleId, flag) {
653
+ panelConstraintFlags.set(resizeHandleId, flag);
654
+ }
655
+ function updateCursor() {
656
+ let intersectsHorizontal = false;
657
+ let intersectsVertical = false;
658
+ intersectingHandles.forEach(data => {
659
+ const {
660
+ direction
661
+ } = data;
662
+ if (direction === "horizontal") {
663
+ intersectsHorizontal = true;
664
+ } else {
665
+ intersectsVertical = true;
666
+ }
667
+ });
668
+ let constraintFlags = 0;
669
+ panelConstraintFlags.forEach(flag => {
670
+ constraintFlags |= flag;
671
+ });
672
+ if (intersectsHorizontal && intersectsVertical) {
673
+ setGlobalCursorStyle("intersection", constraintFlags, isPointerDown);
674
+ } else if (intersectsHorizontal) {
675
+ setGlobalCursorStyle("horizontal", constraintFlags, isPointerDown);
676
+ } else if (intersectsVertical) {
677
+ setGlobalCursorStyle("vertical", constraintFlags, isPointerDown);
678
+ } else {
679
+ resetGlobalCursorStyle();
680
+ }
681
+ }
682
+ let listenersAbortController;
683
+ function updateListeners() {
684
+ var _listenersAbortContro;
685
+ (_listenersAbortContro = listenersAbortController) === null || _listenersAbortContro === void 0 ? void 0 : _listenersAbortContro.abort();
686
+ listenersAbortController = new AbortController();
687
+ const options = {
688
+ capture: true,
689
+ signal: listenersAbortController.signal
690
+ };
691
+ if (!registeredResizeHandlers.size) {
692
+ return;
693
+ }
694
+ if (isPointerDown) {
695
+ if (intersectingHandles.length > 0) {
696
+ ownerDocumentCounts.forEach((count, ownerDocument) => {
697
+ const {
698
+ body
699
+ } = ownerDocument;
700
+ if (count > 0) {
701
+ body.addEventListener("contextmenu", handlePointerUp, options);
702
+ body.addEventListener("pointerleave", handlePointerMove, options);
703
+ body.addEventListener("pointermove", handlePointerMove, options);
704
+ }
705
+ });
706
+ }
707
+ ownerDocumentCounts.forEach((_, ownerDocument) => {
708
+ const {
709
+ body
710
+ } = ownerDocument;
711
+ body.addEventListener("pointerup", handlePointerUp, options);
712
+ body.addEventListener("pointercancel", handlePointerUp, options);
713
+ });
714
+ } else {
715
+ ownerDocumentCounts.forEach((count, ownerDocument) => {
716
+ const {
717
+ body
718
+ } = ownerDocument;
719
+ if (count > 0) {
720
+ body.addEventListener("pointerdown", handlePointerDown, options);
721
+ body.addEventListener("pointermove", handlePointerMove, options);
722
+ }
723
+ });
724
+ }
725
+ }
726
+ function updateResizeHandlerStates(action, event) {
727
+ registeredResizeHandlers.forEach(data => {
728
+ const {
729
+ setResizeHandlerState
730
+ } = data;
731
+ const isActive = intersectingHandles.includes(data);
732
+ setResizeHandlerState(action, isActive, event);
733
+ });
734
+ }
735
+
736
+ function useForceUpdate() {
737
+ const [_, setCount] = useState(0);
738
+ return useCallback(() => setCount(prevCount => prevCount + 1), []);
739
+ }
740
+
741
+ function assert(expectedCondition, message) {
742
+ if (!expectedCondition) {
743
+ console.error(message);
744
+ throw Error(message);
745
+ }
746
+ }
747
+
748
+ function fuzzyCompareNumbers(actual, expected, fractionDigits = PRECISION) {
749
+ if (actual.toFixed(fractionDigits) === expected.toFixed(fractionDigits)) {
750
+ return 0;
751
+ } else {
752
+ return actual > expected ? 1 : -1;
753
+ }
754
+ }
755
+ function fuzzyNumbersEqual$1(actual, expected, fractionDigits = PRECISION) {
756
+ return fuzzyCompareNumbers(actual, expected, fractionDigits) === 0;
757
+ }
758
+
759
+ function fuzzyNumbersEqual(actual, expected, fractionDigits) {
760
+ return fuzzyCompareNumbers(actual, expected, fractionDigits) === 0;
761
+ }
762
+
763
+ function fuzzyLayoutsEqual(actual, expected, fractionDigits) {
764
+ if (actual.length !== expected.length) {
765
+ return false;
766
+ }
767
+ for (let index = 0; index < actual.length; index++) {
768
+ const actualSize = actual[index];
769
+ const expectedSize = expected[index];
770
+ if (!fuzzyNumbersEqual(actualSize, expectedSize, fractionDigits)) {
771
+ return false;
772
+ }
773
+ }
774
+ return true;
775
+ }
776
+
777
+ // Panel size must be in percentages; pixel values should be pre-converted
778
+ function resizePanel({
779
+ panelConstraints: panelConstraintsArray,
780
+ panelIndex,
781
+ size
782
+ }) {
783
+ const panelConstraints = panelConstraintsArray[panelIndex];
784
+ assert(panelConstraints != null, `Panel constraints not found for index ${panelIndex}`);
785
+ let {
786
+ collapsedSize = 0,
787
+ collapsible,
788
+ maxSize = 100,
789
+ minSize = 0
790
+ } = panelConstraints;
791
+ if (fuzzyCompareNumbers(size, minSize) < 0) {
792
+ if (collapsible) {
793
+ // Collapsible panels should snap closed or open only once they cross the halfway point between collapsed and min size.
794
+ const halfwayPoint = (collapsedSize + minSize) / 2;
795
+ if (fuzzyCompareNumbers(size, halfwayPoint) < 0) {
796
+ size = collapsedSize;
797
+ } else {
798
+ size = minSize;
799
+ }
800
+ } else {
801
+ size = minSize;
802
+ }
803
+ }
804
+ size = Math.min(maxSize, size);
805
+ size = parseFloat(size.toFixed(PRECISION));
806
+ return size;
807
+ }
808
+
809
+ // All units must be in percentages; pixel values should be pre-converted
810
+ function adjustLayoutByDelta({
811
+ delta,
812
+ initialLayout,
813
+ panelConstraints: panelConstraintsArray,
814
+ pivotIndices,
815
+ prevLayout,
816
+ trigger
817
+ }) {
818
+ if (fuzzyNumbersEqual(delta, 0)) {
819
+ return initialLayout;
820
+ }
821
+ const nextLayout = [...initialLayout];
822
+ const [firstPivotIndex, secondPivotIndex] = pivotIndices;
823
+ assert(firstPivotIndex != null, "Invalid first pivot index");
824
+ assert(secondPivotIndex != null, "Invalid second pivot index");
825
+ let deltaApplied = 0;
826
+
827
+ // const DEBUG = [];
828
+ // DEBUG.push(`adjustLayoutByDelta()`);
829
+ // DEBUG.push(` initialLayout: ${initialLayout.join(", ")}`);
830
+ // DEBUG.push(` prevLayout: ${prevLayout.join(", ")}`);
831
+ // DEBUG.push(` delta: ${delta}`);
832
+ // DEBUG.push(` pivotIndices: ${pivotIndices.join(", ")}`);
833
+ // DEBUG.push(` trigger: ${trigger}`);
834
+ // DEBUG.push("");
835
+
836
+ // A resizing panel affects the panels before or after it.
837
+ //
838
+ // A negative delta means the panel(s) immediately after the resize handle should grow/expand by decreasing its offset.
839
+ // Other panels may also need to shrink/contract (and shift) to make room, depending on the min weights.
840
+ //
841
+ // A positive delta means the panel(s) immediately before the resize handle should "expand".
842
+ // This is accomplished by shrinking/contracting (and shifting) one or more of the panels after the resize handle.
843
+
844
+ {
845
+ // If this is a resize triggered by a keyboard event, our logic for expanding/collapsing is different.
846
+ // We no longer check the halfway threshold because this may prevent the panel from expanding at all.
847
+ if (trigger === "keyboard") {
848
+ {
849
+ // Check if we should expand a collapsed panel
850
+ const index = delta < 0 ? secondPivotIndex : firstPivotIndex;
851
+ const panelConstraints = panelConstraintsArray[index];
852
+ assert(panelConstraints, `Panel constraints not found for index ${index}`);
853
+ const {
854
+ collapsedSize = 0,
855
+ collapsible,
856
+ minSize = 0
857
+ } = panelConstraints;
858
+
859
+ // DEBUG.push(`edge case check 1: ${index}`);
860
+ // DEBUG.push(` -> collapsible? ${collapsible}`);
861
+ if (collapsible) {
862
+ const prevSize = initialLayout[index];
863
+ assert(prevSize != null, `Previous layout not found for panel index ${index}`);
864
+ if (fuzzyNumbersEqual(prevSize, collapsedSize)) {
865
+ const localDelta = minSize - prevSize;
866
+ // DEBUG.push(` -> expand delta: ${localDelta}`);
867
+
868
+ if (fuzzyCompareNumbers(localDelta, Math.abs(delta)) > 0) {
869
+ delta = delta < 0 ? 0 - localDelta : localDelta;
870
+ // DEBUG.push(` -> delta: ${delta}`);
871
+ }
872
+ }
873
+ }
874
+ }
875
+
876
+ {
877
+ // Check if we should collapse a panel at its minimum size
878
+ const index = delta < 0 ? firstPivotIndex : secondPivotIndex;
879
+ const panelConstraints = panelConstraintsArray[index];
880
+ assert(panelConstraints, `No panel constraints found for index ${index}`);
881
+ const {
882
+ collapsedSize = 0,
883
+ collapsible,
884
+ minSize = 0
885
+ } = panelConstraints;
886
+
887
+ // DEBUG.push(`edge case check 2: ${index}`);
888
+ // DEBUG.push(` -> collapsible? ${collapsible}`);
889
+ if (collapsible) {
890
+ const prevSize = initialLayout[index];
891
+ assert(prevSize != null, `Previous layout not found for panel index ${index}`);
892
+ if (fuzzyNumbersEqual(prevSize, minSize)) {
893
+ const localDelta = prevSize - collapsedSize;
894
+ // DEBUG.push(` -> expand delta: ${localDelta}`);
895
+
896
+ if (fuzzyCompareNumbers(localDelta, Math.abs(delta)) > 0) {
897
+ delta = delta < 0 ? 0 - localDelta : localDelta;
898
+ // DEBUG.push(` -> delta: ${delta}`);
899
+ }
900
+ }
901
+ }
902
+ }
903
+ }
904
+ // DEBUG.push("");
905
+ }
906
+
907
+ {
908
+ // Pre-calculate max available delta in the opposite direction of our pivot.
909
+ // This will be the maximum amount we're allowed to expand/contract the panels in the primary direction.
910
+ // If this amount is less than the requested delta, adjust the requested delta.
911
+ // If this amount is greater than the requested delta, that's useful information too–
912
+ // as an expanding panel might change from collapsed to min size.
913
+
914
+ const increment = delta < 0 ? 1 : -1;
915
+ let index = delta < 0 ? secondPivotIndex : firstPivotIndex;
916
+ let maxAvailableDelta = 0;
917
+
918
+ // DEBUG.push("pre calc...");
919
+ while (true) {
920
+ const prevSize = initialLayout[index];
921
+ assert(prevSize != null, `Previous layout not found for panel index ${index}`);
922
+ const maxSafeSize = resizePanel({
923
+ panelConstraints: panelConstraintsArray,
924
+ panelIndex: index,
925
+ size: 100
926
+ });
927
+ const delta = maxSafeSize - prevSize;
928
+ // DEBUG.push(` ${index}: ${prevSize} -> ${maxSafeSize}`);
929
+
930
+ maxAvailableDelta += delta;
931
+ index += increment;
932
+ if (index < 0 || index >= panelConstraintsArray.length) {
933
+ break;
934
+ }
935
+ }
936
+
937
+ // DEBUG.push(` -> max available delta: ${maxAvailableDelta}`);
938
+ const minAbsDelta = Math.min(Math.abs(delta), Math.abs(maxAvailableDelta));
939
+ delta = delta < 0 ? 0 - minAbsDelta : minAbsDelta;
940
+ // DEBUG.push(` -> adjusted delta: ${delta}`);
941
+ // DEBUG.push("");
942
+ }
943
+
944
+ {
945
+ // Delta added to a panel needs to be subtracted from other panels (within the constraints that those panels allow).
946
+
947
+ const pivotIndex = delta < 0 ? firstPivotIndex : secondPivotIndex;
948
+ let index = pivotIndex;
949
+ while (index >= 0 && index < panelConstraintsArray.length) {
950
+ const deltaRemaining = Math.abs(delta) - Math.abs(deltaApplied);
951
+ const prevSize = initialLayout[index];
952
+ assert(prevSize != null, `Previous layout not found for panel index ${index}`);
953
+ const unsafeSize = prevSize - deltaRemaining;
954
+ const safeSize = resizePanel({
955
+ panelConstraints: panelConstraintsArray,
956
+ panelIndex: index,
957
+ size: unsafeSize
958
+ });
959
+ if (!fuzzyNumbersEqual(prevSize, safeSize)) {
960
+ deltaApplied += prevSize - safeSize;
961
+ nextLayout[index] = safeSize;
962
+ if (deltaApplied.toFixed(3).localeCompare(Math.abs(delta).toFixed(3), undefined, {
963
+ numeric: true
964
+ }) >= 0) {
965
+ break;
966
+ }
967
+ }
968
+ if (delta < 0) {
969
+ index--;
970
+ } else {
971
+ index++;
972
+ }
973
+ }
974
+ }
975
+ // DEBUG.push(`after 1: ${nextLayout.join(", ")}`);
976
+ // DEBUG.push(` deltaApplied: ${deltaApplied}`);
977
+ // DEBUG.push("");
978
+
979
+ // If we were unable to resize any of the panels panels, return the previous state.
980
+ // This will essentially bailout and ignore e.g. drags past a panel's boundaries
981
+ if (fuzzyLayoutsEqual(prevLayout, nextLayout)) {
982
+ // DEBUG.push(`bailout to previous layout: ${prevLayout.join(", ")}`);
983
+ // console.log(DEBUG.join("\n"));
984
+
985
+ return prevLayout;
986
+ }
987
+ {
988
+ // Now distribute the applied delta to the panels in the other direction
989
+ const pivotIndex = delta < 0 ? secondPivotIndex : firstPivotIndex;
990
+ const prevSize = initialLayout[pivotIndex];
991
+ assert(prevSize != null, `Previous layout not found for panel index ${pivotIndex}`);
992
+ const unsafeSize = prevSize + deltaApplied;
993
+ const safeSize = resizePanel({
994
+ panelConstraints: panelConstraintsArray,
995
+ panelIndex: pivotIndex,
996
+ size: unsafeSize
997
+ });
998
+
999
+ // Adjust the pivot panel before, but only by the amount that surrounding panels were able to shrink/contract.
1000
+ nextLayout[pivotIndex] = safeSize;
1001
+
1002
+ // Edge case where expanding or contracting one panel caused another one to change collapsed state
1003
+ if (!fuzzyNumbersEqual(safeSize, unsafeSize)) {
1004
+ let deltaRemaining = unsafeSize - safeSize;
1005
+ const pivotIndex = delta < 0 ? secondPivotIndex : firstPivotIndex;
1006
+ let index = pivotIndex;
1007
+ while (index >= 0 && index < panelConstraintsArray.length) {
1008
+ const prevSize = nextLayout[index];
1009
+ assert(prevSize != null, `Previous layout not found for panel index ${index}`);
1010
+ const unsafeSize = prevSize + deltaRemaining;
1011
+ const safeSize = resizePanel({
1012
+ panelConstraints: panelConstraintsArray,
1013
+ panelIndex: index,
1014
+ size: unsafeSize
1015
+ });
1016
+ if (!fuzzyNumbersEqual(prevSize, safeSize)) {
1017
+ deltaRemaining -= safeSize - prevSize;
1018
+ nextLayout[index] = safeSize;
1019
+ }
1020
+ if (fuzzyNumbersEqual(deltaRemaining, 0)) {
1021
+ break;
1022
+ }
1023
+ if (delta > 0) {
1024
+ index--;
1025
+ } else {
1026
+ index++;
1027
+ }
1028
+ }
1029
+ }
1030
+ }
1031
+ // DEBUG.push(`after 2: ${nextLayout.join(", ")}`);
1032
+ // DEBUG.push(` deltaApplied: ${deltaApplied}`);
1033
+ // DEBUG.push("");
1034
+
1035
+ const totalSize = nextLayout.reduce((total, size) => size + total, 0);
1036
+ // DEBUG.push(`total size: ${totalSize}`);
1037
+
1038
+ // If our new layout doesn't add up to 100%, that means the requested delta can't be applied
1039
+ // In that case, fall back to our most recent valid layout
1040
+ if (!fuzzyNumbersEqual(totalSize, 100)) {
1041
+ // DEBUG.push(`bailout to previous layout: ${prevLayout.join(", ")}`);
1042
+ // console.log(DEBUG.join("\n"));
1043
+
1044
+ return prevLayout;
1045
+ }
1046
+
1047
+ // console.log(DEBUG.join("\n"));
1048
+ return nextLayout;
1049
+ }
1050
+
1051
+ function calculateAriaValues({
1052
+ layout,
1053
+ panelsArray,
1054
+ pivotIndices
1055
+ }) {
1056
+ let currentMinSize = 0;
1057
+ let currentMaxSize = 100;
1058
+ let totalMinSize = 0;
1059
+ let totalMaxSize = 0;
1060
+ const firstIndex = pivotIndices[0];
1061
+ assert(firstIndex != null, "No pivot index found");
1062
+
1063
+ // A panel's effective min/max sizes also need to account for other panel's sizes.
1064
+ panelsArray.forEach((panelData, index) => {
1065
+ const {
1066
+ constraints
1067
+ } = panelData;
1068
+ const {
1069
+ maxSize = 100,
1070
+ minSize = 0
1071
+ } = constraints;
1072
+ if (index === firstIndex) {
1073
+ currentMinSize = minSize;
1074
+ currentMaxSize = maxSize;
1075
+ } else {
1076
+ totalMinSize += minSize;
1077
+ totalMaxSize += maxSize;
1078
+ }
1079
+ });
1080
+ const valueMax = Math.min(currentMaxSize, 100 - totalMinSize);
1081
+ const valueMin = Math.max(currentMinSize, 100 - totalMaxSize);
1082
+ const valueNow = layout[firstIndex];
1083
+ return {
1084
+ valueMax,
1085
+ valueMin,
1086
+ valueNow
1087
+ };
1088
+ }
1089
+
1090
+ function getResizeHandleElementsForGroup(groupId, scope = document) {
1091
+ return Array.from(scope.querySelectorAll(`[${DATA_ATTRIBUTES.resizeHandleId}][data-panel-group-id="${groupId}"]`));
1092
+ }
1093
+
1094
+ function getResizeHandleElementIndex(groupId, id, scope = document) {
1095
+ const handles = getResizeHandleElementsForGroup(groupId, scope);
1096
+ const index = handles.findIndex(handle => handle.getAttribute(DATA_ATTRIBUTES.resizeHandleId) === id);
1097
+ return index !== null && index !== void 0 ? index : null;
1098
+ }
1099
+
1100
+ function determinePivotIndices(groupId, dragHandleId, panelGroupElement) {
1101
+ const index = getResizeHandleElementIndex(groupId, dragHandleId, panelGroupElement);
1102
+ return index != null ? [index, index + 1] : [-1, -1];
1103
+ }
1104
+
1105
+ function isHTMLElement(target) {
1106
+ if (target instanceof HTMLElement) {
1107
+ return true;
1108
+ }
1109
+
1110
+ // Fallback to duck typing to handle edge case of portals within a popup window
1111
+ return typeof target === "object" && target !== null && "tagName" in target && "getAttribute" in target;
1112
+ }
1113
+
1114
+ function getPanelGroupElement(id, rootElement = document) {
1115
+ // If the root element is the PanelGroup
1116
+ if (isHTMLElement(rootElement) && rootElement.dataset.panelGroupId == id) {
1117
+ return rootElement;
1118
+ }
1119
+
1120
+ // Else query children
1121
+ const element = rootElement.querySelector(`[data-panel-group][data-panel-group-id="${id}"]`);
1122
+ if (element) {
1123
+ return element;
1124
+ }
1125
+ return null;
1126
+ }
1127
+
1128
+ function getResizeHandleElement(id, scope = document) {
1129
+ const element = scope.querySelector(`[${DATA_ATTRIBUTES.resizeHandleId}="${id}"]`);
1130
+ if (element) {
1131
+ return element;
1132
+ }
1133
+ return null;
1134
+ }
1135
+
1136
+ function getResizeHandlePanelIds(groupId, handleId, panelsArray, scope = document) {
1137
+ var _panelsArray$index$id, _panelsArray$index, _panelsArray$id, _panelsArray;
1138
+ const handle = getResizeHandleElement(handleId, scope);
1139
+ const handles = getResizeHandleElementsForGroup(groupId, scope);
1140
+ const index = handle ? handles.indexOf(handle) : -1;
1141
+ const idBefore = (_panelsArray$index$id = (_panelsArray$index = panelsArray[index]) === null || _panelsArray$index === void 0 ? void 0 : _panelsArray$index.id) !== null && _panelsArray$index$id !== void 0 ? _panelsArray$index$id : null;
1142
+ const idAfter = (_panelsArray$id = (_panelsArray = panelsArray[index + 1]) === null || _panelsArray === void 0 ? void 0 : _panelsArray.id) !== null && _panelsArray$id !== void 0 ? _panelsArray$id : null;
1143
+ return [idBefore, idAfter];
1144
+ }
1145
+
1146
+ // https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/
1147
+
1148
+ function useWindowSplitterPanelGroupBehavior({
1149
+ committedValuesRef,
1150
+ eagerValuesRef,
1151
+ groupId,
1152
+ layout,
1153
+ panelDataArray,
1154
+ panelGroupElement,
1155
+ setLayout
1156
+ }) {
1157
+ const devWarningsRef = useRef({
1158
+ didWarnAboutMissingResizeHandle: false
1159
+ });
1160
+ useIsomorphicLayoutEffect(() => {
1161
+ if (!panelGroupElement) {
1162
+ return;
1163
+ }
1164
+ const resizeHandleElements = getResizeHandleElementsForGroup(groupId, panelGroupElement);
1165
+ for (let index = 0; index < panelDataArray.length - 1; index++) {
1166
+ const {
1167
+ valueMax,
1168
+ valueMin,
1169
+ valueNow
1170
+ } = calculateAriaValues({
1171
+ layout,
1172
+ panelsArray: panelDataArray,
1173
+ pivotIndices: [index, index + 1]
1174
+ });
1175
+ const resizeHandleElement = resizeHandleElements[index];
1176
+ if (resizeHandleElement == null) {
1177
+ {
1178
+ const {
1179
+ didWarnAboutMissingResizeHandle
1180
+ } = devWarningsRef.current;
1181
+ if (!didWarnAboutMissingResizeHandle) {
1182
+ devWarningsRef.current.didWarnAboutMissingResizeHandle = true;
1183
+ console.warn(`WARNING: Missing resize handle for PanelGroup "${groupId}"`);
1184
+ }
1185
+ }
1186
+ } else {
1187
+ const panelData = panelDataArray[index];
1188
+ assert(panelData, `No panel data found for index "${index}"`);
1189
+ resizeHandleElement.setAttribute("aria-controls", panelData.id);
1190
+ resizeHandleElement.setAttribute("aria-valuemax", "" + Math.round(valueMax));
1191
+ resizeHandleElement.setAttribute("aria-valuemin", "" + Math.round(valueMin));
1192
+ resizeHandleElement.setAttribute("aria-valuenow", valueNow != null ? "" + Math.round(valueNow) : "");
1193
+ }
1194
+ }
1195
+ return () => {
1196
+ resizeHandleElements.forEach((resizeHandleElement, index) => {
1197
+ resizeHandleElement.removeAttribute("aria-controls");
1198
+ resizeHandleElement.removeAttribute("aria-valuemax");
1199
+ resizeHandleElement.removeAttribute("aria-valuemin");
1200
+ resizeHandleElement.removeAttribute("aria-valuenow");
1201
+ });
1202
+ };
1203
+ }, [groupId, layout, panelDataArray, panelGroupElement]);
1204
+ useEffect(() => {
1205
+ if (!panelGroupElement) {
1206
+ return;
1207
+ }
1208
+ const eagerValues = eagerValuesRef.current;
1209
+ assert(eagerValues, `Eager values not found`);
1210
+ const {
1211
+ panelDataArray
1212
+ } = eagerValues;
1213
+ const groupElement = getPanelGroupElement(groupId, panelGroupElement);
1214
+ assert(groupElement != null, `No group found for id "${groupId}"`);
1215
+ const handles = getResizeHandleElementsForGroup(groupId, panelGroupElement);
1216
+ assert(handles, `No resize handles found for group id "${groupId}"`);
1217
+ const cleanupFunctions = handles.map(handle => {
1218
+ const handleId = handle.getAttribute(DATA_ATTRIBUTES.resizeHandleId);
1219
+ assert(handleId, `Resize handle element has no handle id attribute`);
1220
+ const [idBefore, idAfter] = getResizeHandlePanelIds(groupId, handleId, panelDataArray, panelGroupElement);
1221
+ if (idBefore == null || idAfter == null) {
1222
+ return () => {};
1223
+ }
1224
+ const onKeyDown = event => {
1225
+ if (event.defaultPrevented) {
1226
+ return;
1227
+ }
1228
+ switch (event.key) {
1229
+ case "Enter":
1230
+ {
1231
+ event.preventDefault();
1232
+ const index = panelDataArray.findIndex(panelData => panelData.id === idBefore);
1233
+ if (index >= 0) {
1234
+ const panelData = panelDataArray[index];
1235
+ assert(panelData, `No panel data found for index ${index}`);
1236
+ const size = layout[index];
1237
+ const {
1238
+ collapsedSize = 0,
1239
+ collapsible,
1240
+ minSize = 0
1241
+ } = panelData.constraints;
1242
+ if (size != null && collapsible) {
1243
+ const nextLayout = adjustLayoutByDelta({
1244
+ delta: fuzzyNumbersEqual(size, collapsedSize) ? minSize - collapsedSize : collapsedSize - size,
1245
+ initialLayout: layout,
1246
+ panelConstraints: panelDataArray.map(panelData => panelData.constraints),
1247
+ pivotIndices: determinePivotIndices(groupId, handleId, panelGroupElement),
1248
+ prevLayout: layout,
1249
+ trigger: "keyboard"
1250
+ });
1251
+ if (layout !== nextLayout) {
1252
+ setLayout(nextLayout);
1253
+ }
1254
+ }
1255
+ }
1256
+ break;
1257
+ }
1258
+ }
1259
+ };
1260
+ handle.addEventListener("keydown", onKeyDown);
1261
+ return () => {
1262
+ handle.removeEventListener("keydown", onKeyDown);
1263
+ };
1264
+ });
1265
+ return () => {
1266
+ cleanupFunctions.forEach(cleanupFunction => cleanupFunction());
1267
+ };
1268
+ }, [panelGroupElement, committedValuesRef, eagerValuesRef, groupId, layout, panelDataArray, setLayout]);
1269
+ }
1270
+
1271
+ function areEqual(arrayA, arrayB) {
1272
+ if (arrayA.length !== arrayB.length) {
1273
+ return false;
1274
+ }
1275
+ for (let index = 0; index < arrayA.length; index++) {
1276
+ if (arrayA[index] !== arrayB[index]) {
1277
+ return false;
1278
+ }
1279
+ }
1280
+ return true;
1281
+ }
1282
+
1283
+ function getResizeEventCursorPosition(direction, event) {
1284
+ const isHorizontal = direction === "horizontal";
1285
+ const {
1286
+ x,
1287
+ y
1288
+ } = getResizeEventCoordinates(event);
1289
+ return isHorizontal ? x : y;
1290
+ }
1291
+
1292
+ function calculateDragOffsetPercentage(event, dragHandleId, direction, initialDragState, panelGroupElement) {
1293
+ const isHorizontal = direction === "horizontal";
1294
+ const handleElement = getResizeHandleElement(dragHandleId, panelGroupElement);
1295
+ assert(handleElement, `No resize handle element found for id "${dragHandleId}"`);
1296
+ const groupId = handleElement.getAttribute(DATA_ATTRIBUTES.groupId);
1297
+ assert(groupId, `Resize handle element has no group id attribute`);
1298
+ let {
1299
+ initialCursorPosition
1300
+ } = initialDragState;
1301
+ const cursorPosition = getResizeEventCursorPosition(direction, event);
1302
+ const groupElement = getPanelGroupElement(groupId, panelGroupElement);
1303
+ assert(groupElement, `No group element found for id "${groupId}"`);
1304
+ const groupRect = groupElement.getBoundingClientRect();
1305
+ const groupSizeInPixels = isHorizontal ? groupRect.width : groupRect.height;
1306
+ const offsetPixels = cursorPosition - initialCursorPosition;
1307
+ const offsetPercentage = offsetPixels / groupSizeInPixels * 100;
1308
+ return offsetPercentage;
1309
+ }
1310
+
1311
+ // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX
1312
+ function calculateDeltaPercentage(event, dragHandleId, direction, initialDragState, keyboardResizeBy, panelGroupElement) {
1313
+ if (isKeyDown(event)) {
1314
+ const isHorizontal = direction === "horizontal";
1315
+ let delta = 0;
1316
+ if (event.shiftKey) {
1317
+ delta = 100;
1318
+ } else if (keyboardResizeBy != null) {
1319
+ delta = keyboardResizeBy;
1320
+ } else {
1321
+ delta = 10;
1322
+ }
1323
+ let movement = 0;
1324
+ switch (event.key) {
1325
+ case "ArrowDown":
1326
+ movement = isHorizontal ? 0 : delta;
1327
+ break;
1328
+ case "ArrowLeft":
1329
+ movement = isHorizontal ? -delta : 0;
1330
+ break;
1331
+ case "ArrowRight":
1332
+ movement = isHorizontal ? delta : 0;
1333
+ break;
1334
+ case "ArrowUp":
1335
+ movement = isHorizontal ? 0 : -delta;
1336
+ break;
1337
+ case "End":
1338
+ movement = 100;
1339
+ break;
1340
+ case "Home":
1341
+ movement = -100;
1342
+ break;
1343
+ }
1344
+ return movement;
1345
+ } else {
1346
+ if (initialDragState == null) {
1347
+ return 0;
1348
+ }
1349
+ return calculateDragOffsetPercentage(event, dragHandleId, direction, initialDragState, panelGroupElement);
1350
+ }
1351
+ }
1352
+
1353
+ function calculateUnsafeDefaultLayout({
1354
+ panelDataArray
1355
+ }) {
1356
+ const layout = Array(panelDataArray.length);
1357
+ const panelConstraintsArray = panelDataArray.map(panelData => panelData.constraints);
1358
+ let numPanelsWithSizes = 0;
1359
+ let remainingSize = 100;
1360
+
1361
+ // Distribute default sizes first
1362
+ for (let index = 0; index < panelDataArray.length; index++) {
1363
+ const panelConstraints = panelConstraintsArray[index];
1364
+ assert(panelConstraints, `Panel constraints not found for index ${index}`);
1365
+ const {
1366
+ defaultSize
1367
+ } = panelConstraints;
1368
+ if (defaultSize != null) {
1369
+ numPanelsWithSizes++;
1370
+ layout[index] = defaultSize;
1371
+ remainingSize -= defaultSize;
1372
+ }
1373
+ }
1374
+
1375
+ // Remaining size should be distributed evenly between panels without default sizes
1376
+ for (let index = 0; index < panelDataArray.length; index++) {
1377
+ const panelConstraints = panelConstraintsArray[index];
1378
+ assert(panelConstraints, `Panel constraints not found for index ${index}`);
1379
+ const {
1380
+ defaultSize
1381
+ } = panelConstraints;
1382
+ if (defaultSize != null) {
1383
+ continue;
1384
+ }
1385
+ const numRemainingPanels = panelDataArray.length - numPanelsWithSizes;
1386
+ const size = remainingSize / numRemainingPanels;
1387
+ numPanelsWithSizes++;
1388
+ layout[index] = size;
1389
+ remainingSize -= size;
1390
+ }
1391
+ return layout;
1392
+ }
1393
+
1394
+ // Layout should be pre-converted into percentages
1395
+ function callPanelCallbacks(panelsArray, layout, panelIdToLastNotifiedSizeMap) {
1396
+ layout.forEach((size, index) => {
1397
+ const panelData = panelsArray[index];
1398
+ assert(panelData, `Panel data not found for index ${index}`);
1399
+ const {
1400
+ callbacks,
1401
+ constraints,
1402
+ id: panelId
1403
+ } = panelData;
1404
+ const {
1405
+ collapsedSize = 0,
1406
+ collapsible
1407
+ } = constraints;
1408
+ const lastNotifiedSize = panelIdToLastNotifiedSizeMap[panelId];
1409
+ if (lastNotifiedSize == null || size !== lastNotifiedSize) {
1410
+ panelIdToLastNotifiedSizeMap[panelId] = size;
1411
+ const {
1412
+ onCollapse,
1413
+ onExpand,
1414
+ onResize
1415
+ } = callbacks;
1416
+ if (onResize) {
1417
+ onResize(size, lastNotifiedSize);
1418
+ }
1419
+ if (collapsible && (onCollapse || onExpand)) {
1420
+ if (onExpand && (lastNotifiedSize == null || fuzzyNumbersEqual$1(lastNotifiedSize, collapsedSize)) && !fuzzyNumbersEqual$1(size, collapsedSize)) {
1421
+ onExpand();
1422
+ }
1423
+ if (onCollapse && (lastNotifiedSize == null || !fuzzyNumbersEqual$1(lastNotifiedSize, collapsedSize)) && fuzzyNumbersEqual$1(size, collapsedSize)) {
1424
+ onCollapse();
1425
+ }
1426
+ }
1427
+ }
1428
+ });
1429
+ }
1430
+
1431
+ function compareLayouts(a, b) {
1432
+ if (a.length !== b.length) {
1433
+ return false;
1434
+ } else {
1435
+ for (let index = 0; index < a.length; index++) {
1436
+ if (a[index] != b[index]) {
1437
+ return false;
1438
+ }
1439
+ }
1440
+ }
1441
+ return true;
1442
+ }
1443
+
1444
+ // This method returns a number between 1 and 100 representing
1445
+
1446
+ // the % of the group's overall space this panel should occupy.
1447
+ function computePanelFlexBoxStyle({
1448
+ defaultSize,
1449
+ dragState,
1450
+ layout,
1451
+ panelData,
1452
+ panelIndex,
1453
+ precision = 3
1454
+ }) {
1455
+ const size = layout[panelIndex];
1456
+ let flexGrow;
1457
+ if (size == null) {
1458
+ // Initial render (before panels have registered themselves)
1459
+ // In order to support server rendering, fall back to default size if provided
1460
+ flexGrow = defaultSize != undefined ? defaultSize.toFixed(precision) : "1";
1461
+ } else if (panelData.length === 1) {
1462
+ // Special case: Single panel group should always fill full width/height
1463
+ flexGrow = "1";
1464
+ } else {
1465
+ flexGrow = size.toFixed(precision);
1466
+ }
1467
+ return {
1468
+ flexBasis: 0,
1469
+ flexGrow,
1470
+ flexShrink: 1,
1471
+ // Without this, Panel sizes may be unintentionally overridden by their content
1472
+ overflow: "hidden",
1473
+ // Disable pointer events inside of a panel during resize
1474
+ // This avoid edge cases like nested iframes
1475
+ pointerEvents: dragState !== null ? "none" : undefined
1476
+ };
1477
+ }
1478
+
1479
+ function debounce(callback, durationMs = 10) {
1480
+ let timeoutId = null;
1481
+ let callable = (...args) => {
1482
+ if (timeoutId !== null) {
1483
+ clearTimeout(timeoutId);
1484
+ }
1485
+ timeoutId = setTimeout(() => {
1486
+ callback(...args);
1487
+ }, durationMs);
1488
+ };
1489
+ return callable;
1490
+ }
1491
+
1492
+ // PanelGroup might be rendering in a server-side environment where localStorage is not available
1493
+ // or on a browser with cookies/storage disabled.
1494
+ // In either case, this function avoids accessing localStorage until needed,
1495
+ // and avoids throwing user-visible errors.
1496
+ function initializeDefaultStorage(storageObject) {
1497
+ try {
1498
+ if (typeof localStorage !== "undefined") {
1499
+ // Bypass this check for future calls
1500
+ storageObject.getItem = name => {
1501
+ return localStorage.getItem(name);
1502
+ };
1503
+ storageObject.setItem = (name, value) => {
1504
+ localStorage.setItem(name, value);
1505
+ };
1506
+ } else {
1507
+ throw new Error("localStorage not supported in this environment");
1508
+ }
1509
+ } catch (error) {
1510
+ console.error(error);
1511
+ storageObject.getItem = () => null;
1512
+ storageObject.setItem = () => {};
1513
+ }
1514
+ }
1515
+
1516
+ function getPanelGroupKey(autoSaveId) {
1517
+ return `react-resizable-panels:${autoSaveId}`;
1518
+ }
1519
+
1520
+ // Note that Panel ids might be user-provided (stable) or useId generated (non-deterministic)
1521
+ // so they should not be used as part of the serialization key.
1522
+ // Using the min/max size attributes should work well enough as a backup.
1523
+ // Pre-sorting by minSize allows remembering layouts even if panels are re-ordered/dragged.
1524
+ function getPanelKey(panels) {
1525
+ return panels.map(panel => {
1526
+ const {
1527
+ constraints,
1528
+ id,
1529
+ idIsFromProps,
1530
+ order
1531
+ } = panel;
1532
+ if (idIsFromProps) {
1533
+ return id;
1534
+ } else {
1535
+ return order ? `${order}:${JSON.stringify(constraints)}` : JSON.stringify(constraints);
1536
+ }
1537
+ }).sort((a, b) => a.localeCompare(b)).join(",");
1538
+ }
1539
+ function loadSerializedPanelGroupState(autoSaveId, storage) {
1540
+ try {
1541
+ const panelGroupKey = getPanelGroupKey(autoSaveId);
1542
+ const serialized = storage.getItem(panelGroupKey);
1543
+ if (serialized) {
1544
+ const parsed = JSON.parse(serialized);
1545
+ if (typeof parsed === "object" && parsed != null) {
1546
+ return parsed;
1547
+ }
1548
+ }
1549
+ } catch (error) {}
1550
+ return null;
1551
+ }
1552
+ function loadPanelGroupState(autoSaveId, panels, storage) {
1553
+ var _loadSerializedPanelG, _state$panelKey;
1554
+ const state = (_loadSerializedPanelG = loadSerializedPanelGroupState(autoSaveId, storage)) !== null && _loadSerializedPanelG !== void 0 ? _loadSerializedPanelG : {};
1555
+ const panelKey = getPanelKey(panels);
1556
+ return (_state$panelKey = state[panelKey]) !== null && _state$panelKey !== void 0 ? _state$panelKey : null;
1557
+ }
1558
+ function savePanelGroupState(autoSaveId, panels, panelSizesBeforeCollapse, sizes, storage) {
1559
+ var _loadSerializedPanelG2;
1560
+ const panelGroupKey = getPanelGroupKey(autoSaveId);
1561
+ const panelKey = getPanelKey(panels);
1562
+ const state = (_loadSerializedPanelG2 = loadSerializedPanelGroupState(autoSaveId, storage)) !== null && _loadSerializedPanelG2 !== void 0 ? _loadSerializedPanelG2 : {};
1563
+ state[panelKey] = {
1564
+ expandToSizes: Object.fromEntries(panelSizesBeforeCollapse.entries()),
1565
+ layout: sizes
1566
+ };
1567
+ try {
1568
+ storage.setItem(panelGroupKey, JSON.stringify(state));
1569
+ } catch (error) {
1570
+ console.error(error);
1571
+ }
1572
+ }
1573
+
1574
+ function validatePanelConstraints({
1575
+ panelConstraints: panelConstraintsArray,
1576
+ panelId,
1577
+ panelIndex
1578
+ }) {
1579
+ {
1580
+ const warnings = [];
1581
+ const panelConstraints = panelConstraintsArray[panelIndex];
1582
+ assert(panelConstraints, `No panel constraints found for index ${panelIndex}`);
1583
+ const {
1584
+ collapsedSize = 0,
1585
+ collapsible = false,
1586
+ defaultSize,
1587
+ maxSize = 100,
1588
+ minSize = 0
1589
+ } = panelConstraints;
1590
+ if (minSize > maxSize) {
1591
+ warnings.push(`min size (${minSize}%) should not be greater than max size (${maxSize}%)`);
1592
+ }
1593
+ if (defaultSize != null) {
1594
+ if (defaultSize < 0) {
1595
+ warnings.push("default size should not be less than 0");
1596
+ } else if (defaultSize < minSize && (!collapsible || defaultSize !== collapsedSize)) {
1597
+ warnings.push("default size should not be less than min size");
1598
+ }
1599
+ if (defaultSize > 100) {
1600
+ warnings.push("default size should not be greater than 100");
1601
+ } else if (defaultSize > maxSize) {
1602
+ warnings.push("default size should not be greater than max size");
1603
+ }
1604
+ }
1605
+ if (collapsedSize > minSize) {
1606
+ warnings.push("collapsed size should not be greater than min size");
1607
+ }
1608
+ if (warnings.length > 0) {
1609
+ const name = panelId != null ? `Panel "${panelId}"` : "Panel";
1610
+ console.warn(`${name} has an invalid configuration:\n\n${warnings.join("\n")}`);
1611
+ return false;
1612
+ }
1613
+ }
1614
+ return true;
1615
+ }
1616
+
1617
+ // All units must be in percentages; pixel values should be pre-converted
1618
+ function validatePanelGroupLayout({
1619
+ layout: prevLayout,
1620
+ panelConstraints
1621
+ }) {
1622
+ const nextLayout = [...prevLayout];
1623
+ const nextLayoutTotalSize = nextLayout.reduce((accumulated, current) => accumulated + current, 0);
1624
+
1625
+ // Validate layout expectations
1626
+ if (nextLayout.length !== panelConstraints.length) {
1627
+ throw Error(`Invalid ${panelConstraints.length} panel layout: ${nextLayout.map(size => `${size}%`).join(", ")}`);
1628
+ } else if (!fuzzyNumbersEqual(nextLayoutTotalSize, 100) && nextLayout.length > 0) {
1629
+ // This is not ideal so we should warn about it, but it may be recoverable in some cases
1630
+ // (especially if the amount is small)
1631
+ {
1632
+ console.warn(`WARNING: Invalid layout total size: ${nextLayout.map(size => `${size}%`).join(", ")}. Layout normalization will be applied.`);
1633
+ }
1634
+ for (let index = 0; index < panelConstraints.length; index++) {
1635
+ const unsafeSize = nextLayout[index];
1636
+ assert(unsafeSize != null, `No layout data found for index ${index}`);
1637
+ const safeSize = 100 / nextLayoutTotalSize * unsafeSize;
1638
+ nextLayout[index] = safeSize;
1639
+ }
1640
+ }
1641
+ let remainingSize = 0;
1642
+
1643
+ // First pass: Validate the proposed layout given each panel's constraints
1644
+ for (let index = 0; index < panelConstraints.length; index++) {
1645
+ const unsafeSize = nextLayout[index];
1646
+ assert(unsafeSize != null, `No layout data found for index ${index}`);
1647
+ const safeSize = resizePanel({
1648
+ panelConstraints,
1649
+ panelIndex: index,
1650
+ size: unsafeSize
1651
+ });
1652
+ if (unsafeSize != safeSize) {
1653
+ remainingSize += unsafeSize - safeSize;
1654
+ nextLayout[index] = safeSize;
1655
+ }
1656
+ }
1657
+
1658
+ // If there is additional, left over space, assign it to any panel(s) that permits it
1659
+ // (It's not worth taking multiple additional passes to evenly distribute)
1660
+ if (!fuzzyNumbersEqual(remainingSize, 0)) {
1661
+ for (let index = 0; index < panelConstraints.length; index++) {
1662
+ const prevSize = nextLayout[index];
1663
+ assert(prevSize != null, `No layout data found for index ${index}`);
1664
+ const unsafeSize = prevSize + remainingSize;
1665
+ const safeSize = resizePanel({
1666
+ panelConstraints,
1667
+ panelIndex: index,
1668
+ size: unsafeSize
1669
+ });
1670
+ if (prevSize !== safeSize) {
1671
+ remainingSize -= safeSize - prevSize;
1672
+ nextLayout[index] = safeSize;
1673
+
1674
+ // Once we've used up the remainder, bail
1675
+ if (fuzzyNumbersEqual(remainingSize, 0)) {
1676
+ break;
1677
+ }
1678
+ }
1679
+ }
1680
+ }
1681
+ return nextLayout;
1682
+ }
1683
+
1684
+ const LOCAL_STORAGE_DEBOUNCE_INTERVAL = 100;
1685
+ const defaultStorage = {
1686
+ getItem: name => {
1687
+ initializeDefaultStorage(defaultStorage);
1688
+ return defaultStorage.getItem(name);
1689
+ },
1690
+ setItem: (name, value) => {
1691
+ initializeDefaultStorage(defaultStorage);
1692
+ defaultStorage.setItem(name, value);
1693
+ }
1694
+ };
1695
+ const debounceMap = {};
1696
+ function PanelGroupWithForwardedRef({
1697
+ autoSaveId = null,
1698
+ children,
1699
+ className: classNameFromProps = "",
1700
+ direction,
1701
+ forwardedRef,
1702
+ id: idFromProps = null,
1703
+ onLayout = null,
1704
+ keyboardResizeBy = null,
1705
+ storage = defaultStorage,
1706
+ style: styleFromProps,
1707
+ tagName: Type = "div",
1708
+ ...rest
1709
+ }) {
1710
+ const groupId = useUniqueId(idFromProps);
1711
+ const panelGroupElementRef = useRef(null);
1712
+ const [dragState, setDragState] = useState(null);
1713
+ const [layout, setLayout] = useState([]);
1714
+ const forceUpdate = useForceUpdate();
1715
+ const panelIdToLastNotifiedSizeMapRef = useRef({});
1716
+ const panelSizeBeforeCollapseRef = useRef(new Map());
1717
+ const prevDeltaRef = useRef(0);
1718
+ const committedValuesRef = useRef({
1719
+ autoSaveId,
1720
+ direction,
1721
+ dragState,
1722
+ id: groupId,
1723
+ keyboardResizeBy,
1724
+ onLayout,
1725
+ storage
1726
+ });
1727
+ const eagerValuesRef = useRef({
1728
+ layout,
1729
+ panelDataArray: [],
1730
+ panelDataArrayChanged: false
1731
+ });
1732
+ const devWarningsRef = useRef({
1733
+ didLogIdAndOrderWarning: false,
1734
+ didLogPanelConstraintsWarning: false,
1735
+ prevPanelIds: []
1736
+ });
1737
+ useImperativeHandle(forwardedRef, () => ({
1738
+ getId: () => committedValuesRef.current.id,
1739
+ getLayout: () => {
1740
+ const {
1741
+ layout
1742
+ } = eagerValuesRef.current;
1743
+ return layout;
1744
+ },
1745
+ setLayout: unsafeLayout => {
1746
+ const {
1747
+ onLayout
1748
+ } = committedValuesRef.current;
1749
+ const {
1750
+ layout: prevLayout,
1751
+ panelDataArray
1752
+ } = eagerValuesRef.current;
1753
+ const safeLayout = validatePanelGroupLayout({
1754
+ layout: unsafeLayout,
1755
+ panelConstraints: panelDataArray.map(panelData => panelData.constraints)
1756
+ });
1757
+ if (!areEqual(prevLayout, safeLayout)) {
1758
+ setLayout(safeLayout);
1759
+ eagerValuesRef.current.layout = safeLayout;
1760
+ if (onLayout) {
1761
+ onLayout(safeLayout);
1762
+ }
1763
+ callPanelCallbacks(panelDataArray, safeLayout, panelIdToLastNotifiedSizeMapRef.current);
1764
+ }
1765
+ }
1766
+ }), []);
1767
+ useIsomorphicLayoutEffect(() => {
1768
+ committedValuesRef.current.autoSaveId = autoSaveId;
1769
+ committedValuesRef.current.direction = direction;
1770
+ committedValuesRef.current.dragState = dragState;
1771
+ committedValuesRef.current.id = groupId;
1772
+ committedValuesRef.current.onLayout = onLayout;
1773
+ committedValuesRef.current.storage = storage;
1774
+ });
1775
+ useWindowSplitterPanelGroupBehavior({
1776
+ committedValuesRef,
1777
+ eagerValuesRef,
1778
+ groupId,
1779
+ layout,
1780
+ panelDataArray: eagerValuesRef.current.panelDataArray,
1781
+ setLayout,
1782
+ panelGroupElement: panelGroupElementRef.current
1783
+ });
1784
+ useEffect(() => {
1785
+ const {
1786
+ panelDataArray
1787
+ } = eagerValuesRef.current;
1788
+
1789
+ // If this panel has been configured to persist sizing information, save sizes to local storage.
1790
+ if (autoSaveId) {
1791
+ if (layout.length === 0 || layout.length !== panelDataArray.length) {
1792
+ return;
1793
+ }
1794
+ let debouncedSave = debounceMap[autoSaveId];
1795
+
1796
+ // Limit the frequency of localStorage updates.
1797
+ if (debouncedSave == null) {
1798
+ debouncedSave = debounce(savePanelGroupState, LOCAL_STORAGE_DEBOUNCE_INTERVAL);
1799
+ debounceMap[autoSaveId] = debouncedSave;
1800
+ }
1801
+
1802
+ // Clone mutable data before passing to the debounced function,
1803
+ // else we run the risk of saving an incorrect combination of mutable and immutable values to state.
1804
+ const clonedPanelDataArray = [...panelDataArray];
1805
+ const clonedPanelSizesBeforeCollapse = new Map(panelSizeBeforeCollapseRef.current);
1806
+ debouncedSave(autoSaveId, clonedPanelDataArray, clonedPanelSizesBeforeCollapse, layout, storage);
1807
+ }
1808
+ }, [autoSaveId, layout, storage]);
1809
+
1810
+ // DEV warnings
1811
+ useEffect(() => {
1812
+ {
1813
+ const {
1814
+ panelDataArray
1815
+ } = eagerValuesRef.current;
1816
+ const {
1817
+ didLogIdAndOrderWarning,
1818
+ didLogPanelConstraintsWarning,
1819
+ prevPanelIds
1820
+ } = devWarningsRef.current;
1821
+ if (!didLogIdAndOrderWarning) {
1822
+ const panelIds = panelDataArray.map(({
1823
+ id
1824
+ }) => id);
1825
+ devWarningsRef.current.prevPanelIds = panelIds;
1826
+ const panelsHaveChanged = prevPanelIds.length > 0 && !areEqual(prevPanelIds, panelIds);
1827
+ if (panelsHaveChanged) {
1828
+ if (panelDataArray.find(({
1829
+ idIsFromProps,
1830
+ order
1831
+ }) => !idIsFromProps || order == null)) {
1832
+ devWarningsRef.current.didLogIdAndOrderWarning = true;
1833
+ console.warn(`WARNING: Panel id and order props recommended when panels are dynamically rendered`);
1834
+ }
1835
+ }
1836
+ }
1837
+ if (!didLogPanelConstraintsWarning) {
1838
+ const panelConstraints = panelDataArray.map(panelData => panelData.constraints);
1839
+ for (let panelIndex = 0; panelIndex < panelConstraints.length; panelIndex++) {
1840
+ const panelData = panelDataArray[panelIndex];
1841
+ assert(panelData, `Panel data not found for index ${panelIndex}`);
1842
+ const isValid = validatePanelConstraints({
1843
+ panelConstraints,
1844
+ panelId: panelData.id,
1845
+ panelIndex
1846
+ });
1847
+ if (!isValid) {
1848
+ devWarningsRef.current.didLogPanelConstraintsWarning = true;
1849
+ break;
1850
+ }
1851
+ }
1852
+ }
1853
+ }
1854
+ });
1855
+
1856
+ // External APIs are safe to memoize via committed values ref
1857
+ const collapsePanel = useCallback(panelData => {
1858
+ const {
1859
+ onLayout
1860
+ } = committedValuesRef.current;
1861
+ const {
1862
+ layout: prevLayout,
1863
+ panelDataArray
1864
+ } = eagerValuesRef.current;
1865
+ if (panelData.constraints.collapsible) {
1866
+ const panelConstraintsArray = panelDataArray.map(panelData => panelData.constraints);
1867
+ const {
1868
+ collapsedSize = 0,
1869
+ panelSize,
1870
+ pivotIndices
1871
+ } = panelDataHelper(panelDataArray, panelData, prevLayout);
1872
+ assert(panelSize != null, `Panel size not found for panel "${panelData.id}"`);
1873
+ if (!fuzzyNumbersEqual$1(panelSize, collapsedSize)) {
1874
+ // Store size before collapse;
1875
+ // This is the size that gets restored if the expand() API is used.
1876
+ panelSizeBeforeCollapseRef.current.set(panelData.id, panelSize);
1877
+ const isLastPanel = findPanelDataIndex(panelDataArray, panelData) === panelDataArray.length - 1;
1878
+ const delta = isLastPanel ? panelSize - collapsedSize : collapsedSize - panelSize;
1879
+ const nextLayout = adjustLayoutByDelta({
1880
+ delta,
1881
+ initialLayout: prevLayout,
1882
+ panelConstraints: panelConstraintsArray,
1883
+ pivotIndices,
1884
+ prevLayout,
1885
+ trigger: "imperative-api"
1886
+ });
1887
+ if (!compareLayouts(prevLayout, nextLayout)) {
1888
+ setLayout(nextLayout);
1889
+ eagerValuesRef.current.layout = nextLayout;
1890
+ if (onLayout) {
1891
+ onLayout(nextLayout);
1892
+ }
1893
+ callPanelCallbacks(panelDataArray, nextLayout, panelIdToLastNotifiedSizeMapRef.current);
1894
+ }
1895
+ }
1896
+ }
1897
+ }, []);
1898
+
1899
+ // External APIs are safe to memoize via committed values ref
1900
+ const expandPanel = useCallback((panelData, minSizeOverride) => {
1901
+ const {
1902
+ onLayout
1903
+ } = committedValuesRef.current;
1904
+ const {
1905
+ layout: prevLayout,
1906
+ panelDataArray
1907
+ } = eagerValuesRef.current;
1908
+ if (panelData.constraints.collapsible) {
1909
+ const panelConstraintsArray = panelDataArray.map(panelData => panelData.constraints);
1910
+ const {
1911
+ collapsedSize = 0,
1912
+ panelSize = 0,
1913
+ minSize: minSizeFromProps = 0,
1914
+ pivotIndices
1915
+ } = panelDataHelper(panelDataArray, panelData, prevLayout);
1916
+ const minSize = minSizeOverride !== null && minSizeOverride !== void 0 ? minSizeOverride : minSizeFromProps;
1917
+ if (fuzzyNumbersEqual$1(panelSize, collapsedSize)) {
1918
+ // Restore this panel to the size it was before it was collapsed, if possible.
1919
+ const prevPanelSize = panelSizeBeforeCollapseRef.current.get(panelData.id);
1920
+ const baseSize = prevPanelSize != null && prevPanelSize >= minSize ? prevPanelSize : minSize;
1921
+ const isLastPanel = findPanelDataIndex(panelDataArray, panelData) === panelDataArray.length - 1;
1922
+ const delta = isLastPanel ? panelSize - baseSize : baseSize - panelSize;
1923
+ const nextLayout = adjustLayoutByDelta({
1924
+ delta,
1925
+ initialLayout: prevLayout,
1926
+ panelConstraints: panelConstraintsArray,
1927
+ pivotIndices,
1928
+ prevLayout,
1929
+ trigger: "imperative-api"
1930
+ });
1931
+ if (!compareLayouts(prevLayout, nextLayout)) {
1932
+ setLayout(nextLayout);
1933
+ eagerValuesRef.current.layout = nextLayout;
1934
+ if (onLayout) {
1935
+ onLayout(nextLayout);
1936
+ }
1937
+ callPanelCallbacks(panelDataArray, nextLayout, panelIdToLastNotifiedSizeMapRef.current);
1938
+ }
1939
+ }
1940
+ }
1941
+ }, []);
1942
+
1943
+ // External APIs are safe to memoize via committed values ref
1944
+ const getPanelSize = useCallback(panelData => {
1945
+ const {
1946
+ layout,
1947
+ panelDataArray
1948
+ } = eagerValuesRef.current;
1949
+ const {
1950
+ panelSize
1951
+ } = panelDataHelper(panelDataArray, panelData, layout);
1952
+ assert(panelSize != null, `Panel size not found for panel "${panelData.id}"`);
1953
+ return panelSize;
1954
+ }, []);
1955
+
1956
+ // This API should never read from committedValuesRef
1957
+ const getPanelStyle = useCallback((panelData, defaultSize) => {
1958
+ const {
1959
+ panelDataArray
1960
+ } = eagerValuesRef.current;
1961
+ const panelIndex = findPanelDataIndex(panelDataArray, panelData);
1962
+ return computePanelFlexBoxStyle({
1963
+ defaultSize,
1964
+ dragState,
1965
+ layout,
1966
+ panelData: panelDataArray,
1967
+ panelIndex
1968
+ });
1969
+ }, [dragState, layout]);
1970
+
1971
+ // External APIs are safe to memoize via committed values ref
1972
+ const isPanelCollapsed = useCallback(panelData => {
1973
+ const {
1974
+ layout,
1975
+ panelDataArray
1976
+ } = eagerValuesRef.current;
1977
+ const {
1978
+ collapsedSize = 0,
1979
+ collapsible,
1980
+ panelSize
1981
+ } = panelDataHelper(panelDataArray, panelData, layout);
1982
+ assert(panelSize != null, `Panel size not found for panel "${panelData.id}"`);
1983
+ return collapsible === true && fuzzyNumbersEqual$1(panelSize, collapsedSize);
1984
+ }, []);
1985
+
1986
+ // External APIs are safe to memoize via committed values ref
1987
+ const isPanelExpanded = useCallback(panelData => {
1988
+ const {
1989
+ layout,
1990
+ panelDataArray
1991
+ } = eagerValuesRef.current;
1992
+ const {
1993
+ collapsedSize = 0,
1994
+ collapsible,
1995
+ panelSize
1996
+ } = panelDataHelper(panelDataArray, panelData, layout);
1997
+ assert(panelSize != null, `Panel size not found for panel "${panelData.id}"`);
1998
+ return !collapsible || fuzzyCompareNumbers(panelSize, collapsedSize) > 0;
1999
+ }, []);
2000
+ const registerPanel = useCallback(panelData => {
2001
+ const {
2002
+ panelDataArray
2003
+ } = eagerValuesRef.current;
2004
+ panelDataArray.push(panelData);
2005
+ panelDataArray.sort((panelA, panelB) => {
2006
+ const orderA = panelA.order;
2007
+ const orderB = panelB.order;
2008
+ if (orderA == null && orderB == null) {
2009
+ return 0;
2010
+ } else if (orderA == null) {
2011
+ return -1;
2012
+ } else if (orderB == null) {
2013
+ return 1;
2014
+ } else {
2015
+ return orderA - orderB;
2016
+ }
2017
+ });
2018
+ eagerValuesRef.current.panelDataArrayChanged = true;
2019
+ forceUpdate();
2020
+ }, [forceUpdate]);
2021
+
2022
+ // (Re)calculate group layout whenever panels are registered or unregistered.
2023
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2024
+ useIsomorphicLayoutEffect(() => {
2025
+ if (eagerValuesRef.current.panelDataArrayChanged) {
2026
+ eagerValuesRef.current.panelDataArrayChanged = false;
2027
+ const {
2028
+ autoSaveId,
2029
+ onLayout,
2030
+ storage
2031
+ } = committedValuesRef.current;
2032
+ const {
2033
+ layout: prevLayout,
2034
+ panelDataArray
2035
+ } = eagerValuesRef.current;
2036
+
2037
+ // If this panel has been configured to persist sizing information,
2038
+ // default size should be restored from local storage if possible.
2039
+ let unsafeLayout = null;
2040
+ if (autoSaveId) {
2041
+ const state = loadPanelGroupState(autoSaveId, panelDataArray, storage);
2042
+ if (state) {
2043
+ panelSizeBeforeCollapseRef.current = new Map(Object.entries(state.expandToSizes));
2044
+ unsafeLayout = state.layout;
2045
+ }
2046
+ }
2047
+ if (unsafeLayout == null) {
2048
+ unsafeLayout = calculateUnsafeDefaultLayout({
2049
+ panelDataArray
2050
+ });
2051
+ }
2052
+
2053
+ // Validate even saved layouts in case something has changed since last render
2054
+ // e.g. for pixel groups, this could be the size of the window
2055
+ const nextLayout = validatePanelGroupLayout({
2056
+ layout: unsafeLayout,
2057
+ panelConstraints: panelDataArray.map(panelData => panelData.constraints)
2058
+ });
2059
+ if (!areEqual(prevLayout, nextLayout)) {
2060
+ setLayout(nextLayout);
2061
+ eagerValuesRef.current.layout = nextLayout;
2062
+ if (onLayout) {
2063
+ onLayout(nextLayout);
2064
+ }
2065
+ callPanelCallbacks(panelDataArray, nextLayout, panelIdToLastNotifiedSizeMapRef.current);
2066
+ }
2067
+ }
2068
+ });
2069
+
2070
+ // Reset the cached layout if hidden by the Activity/Offscreen API
2071
+ useIsomorphicLayoutEffect(() => {
2072
+ const eagerValues = eagerValuesRef.current;
2073
+ return () => {
2074
+ eagerValues.layout = [];
2075
+ };
2076
+ }, []);
2077
+ const registerResizeHandle = useCallback(dragHandleId => {
2078
+ let isRTL = false;
2079
+ const panelGroupElement = panelGroupElementRef.current;
2080
+ if (panelGroupElement) {
2081
+ const style = window.getComputedStyle(panelGroupElement, null);
2082
+ if (style.getPropertyValue("direction") === "rtl") {
2083
+ isRTL = true;
2084
+ }
2085
+ }
2086
+ return function resizeHandler(event) {
2087
+ event.preventDefault();
2088
+ const panelGroupElement = panelGroupElementRef.current;
2089
+ if (!panelGroupElement) {
2090
+ return () => null;
2091
+ }
2092
+ const {
2093
+ direction,
2094
+ dragState,
2095
+ id: groupId,
2096
+ keyboardResizeBy,
2097
+ onLayout
2098
+ } = committedValuesRef.current;
2099
+ const {
2100
+ layout: prevLayout,
2101
+ panelDataArray
2102
+ } = eagerValuesRef.current;
2103
+ const {
2104
+ initialLayout
2105
+ } = dragState !== null && dragState !== void 0 ? dragState : {};
2106
+ const pivotIndices = determinePivotIndices(groupId, dragHandleId, panelGroupElement);
2107
+ let delta = calculateDeltaPercentage(event, dragHandleId, direction, dragState, keyboardResizeBy, panelGroupElement);
2108
+ const isHorizontal = direction === "horizontal";
2109
+ if (isHorizontal && isRTL) {
2110
+ delta = -delta;
2111
+ }
2112
+ const panelConstraints = panelDataArray.map(panelData => panelData.constraints);
2113
+ const nextLayout = adjustLayoutByDelta({
2114
+ delta,
2115
+ initialLayout: initialLayout !== null && initialLayout !== void 0 ? initialLayout : prevLayout,
2116
+ panelConstraints,
2117
+ pivotIndices,
2118
+ prevLayout,
2119
+ trigger: isKeyDown(event) ? "keyboard" : "mouse-or-touch"
2120
+ });
2121
+ const layoutChanged = !compareLayouts(prevLayout, nextLayout);
2122
+
2123
+ // Only update the cursor for layout changes triggered by touch/mouse events (not keyboard)
2124
+ // Update the cursor even if the layout hasn't changed (we may need to show an invalid cursor state)
2125
+ if (isPointerEvent(event) || isMouseEvent(event)) {
2126
+ // Watch for multiple subsequent deltas; this might occur for tiny cursor movements.
2127
+ // In this case, Panel sizes might not change–
2128
+ // but updating cursor in this scenario would cause a flicker.
2129
+ if (prevDeltaRef.current != delta) {
2130
+ prevDeltaRef.current = delta;
2131
+ if (!layoutChanged && delta !== 0) {
2132
+ // If the pointer has moved too far to resize the panel any further, note this so we can update the cursor.
2133
+ // This mimics VS Code behavior.
2134
+ if (isHorizontal) {
2135
+ reportConstraintsViolation(dragHandleId, delta < 0 ? EXCEEDED_HORIZONTAL_MIN : EXCEEDED_HORIZONTAL_MAX);
2136
+ } else {
2137
+ reportConstraintsViolation(dragHandleId, delta < 0 ? EXCEEDED_VERTICAL_MIN : EXCEEDED_VERTICAL_MAX);
2138
+ }
2139
+ } else {
2140
+ reportConstraintsViolation(dragHandleId, 0);
2141
+ }
2142
+ }
2143
+ }
2144
+ if (layoutChanged) {
2145
+ setLayout(nextLayout);
2146
+ eagerValuesRef.current.layout = nextLayout;
2147
+ if (onLayout) {
2148
+ onLayout(nextLayout);
2149
+ }
2150
+ callPanelCallbacks(panelDataArray, nextLayout, panelIdToLastNotifiedSizeMapRef.current);
2151
+ }
2152
+ };
2153
+ }, []);
2154
+
2155
+ // External APIs are safe to memoize via committed values ref
2156
+ const resizePanel = useCallback((panelData, unsafePanelSize) => {
2157
+ const {
2158
+ onLayout
2159
+ } = committedValuesRef.current;
2160
+ const {
2161
+ layout: prevLayout,
2162
+ panelDataArray
2163
+ } = eagerValuesRef.current;
2164
+ const panelConstraintsArray = panelDataArray.map(panelData => panelData.constraints);
2165
+ const {
2166
+ panelSize,
2167
+ pivotIndices
2168
+ } = panelDataHelper(panelDataArray, panelData, prevLayout);
2169
+ assert(panelSize != null, `Panel size not found for panel "${panelData.id}"`);
2170
+ const isLastPanel = findPanelDataIndex(panelDataArray, panelData) === panelDataArray.length - 1;
2171
+ const delta = isLastPanel ? panelSize - unsafePanelSize : unsafePanelSize - panelSize;
2172
+ const nextLayout = adjustLayoutByDelta({
2173
+ delta,
2174
+ initialLayout: prevLayout,
2175
+ panelConstraints: panelConstraintsArray,
2176
+ pivotIndices,
2177
+ prevLayout,
2178
+ trigger: "imperative-api"
2179
+ });
2180
+ if (!compareLayouts(prevLayout, nextLayout)) {
2181
+ setLayout(nextLayout);
2182
+ eagerValuesRef.current.layout = nextLayout;
2183
+ if (onLayout) {
2184
+ onLayout(nextLayout);
2185
+ }
2186
+ callPanelCallbacks(panelDataArray, nextLayout, panelIdToLastNotifiedSizeMapRef.current);
2187
+ }
2188
+ }, []);
2189
+ const reevaluatePanelConstraints = useCallback((panelData, prevConstraints) => {
2190
+ const {
2191
+ layout,
2192
+ panelDataArray
2193
+ } = eagerValuesRef.current;
2194
+ const {
2195
+ collapsedSize: prevCollapsedSize = 0,
2196
+ collapsible: prevCollapsible
2197
+ } = prevConstraints;
2198
+ const {
2199
+ collapsedSize: nextCollapsedSize = 0,
2200
+ collapsible: nextCollapsible,
2201
+ maxSize: nextMaxSize = 100,
2202
+ minSize: nextMinSize = 0
2203
+ } = panelData.constraints;
2204
+ const {
2205
+ panelSize: prevPanelSize
2206
+ } = panelDataHelper(panelDataArray, panelData, layout);
2207
+ if (prevPanelSize == null) {
2208
+ // It's possible that the panels in this group have changed since the last render
2209
+ return;
2210
+ }
2211
+ if (prevCollapsible && nextCollapsible && fuzzyNumbersEqual$1(prevPanelSize, prevCollapsedSize)) {
2212
+ if (!fuzzyNumbersEqual$1(prevCollapsedSize, nextCollapsedSize)) {
2213
+ resizePanel(panelData, nextCollapsedSize);
2214
+ }
2215
+ } else if (prevPanelSize < nextMinSize) {
2216
+ resizePanel(panelData, nextMinSize);
2217
+ } else if (prevPanelSize > nextMaxSize) {
2218
+ resizePanel(panelData, nextMaxSize);
2219
+ }
2220
+ }, [resizePanel]);
2221
+
2222
+ // TODO Multiple drag handles can be active at the same time so this API is a bit awkward now
2223
+ const startDragging = useCallback((dragHandleId, event) => {
2224
+ const {
2225
+ direction
2226
+ } = committedValuesRef.current;
2227
+ const {
2228
+ layout
2229
+ } = eagerValuesRef.current;
2230
+ if (!panelGroupElementRef.current) {
2231
+ return;
2232
+ }
2233
+ const handleElement = getResizeHandleElement(dragHandleId, panelGroupElementRef.current);
2234
+ assert(handleElement, `Drag handle element not found for id "${dragHandleId}"`);
2235
+ const initialCursorPosition = getResizeEventCursorPosition(direction, event);
2236
+ setDragState({
2237
+ dragHandleId,
2238
+ dragHandleRect: handleElement.getBoundingClientRect(),
2239
+ initialCursorPosition,
2240
+ initialLayout: layout
2241
+ });
2242
+ }, []);
2243
+ const stopDragging = useCallback(() => {
2244
+ setDragState(null);
2245
+ }, []);
2246
+ const unregisterPanel = useCallback(panelData => {
2247
+ const {
2248
+ panelDataArray
2249
+ } = eagerValuesRef.current;
2250
+ const index = findPanelDataIndex(panelDataArray, panelData);
2251
+ if (index >= 0) {
2252
+ panelDataArray.splice(index, 1);
2253
+
2254
+ // TRICKY
2255
+ // When a panel is removed from the group, we should delete the most recent prev-size entry for it.
2256
+ // If we don't do this, then a conditionally rendered panel might not call onResize when it's re-mounted.
2257
+ // Strict effects mode makes this tricky though because all panels will be registered, unregistered, then re-registered on mount.
2258
+ delete panelIdToLastNotifiedSizeMapRef.current[panelData.id];
2259
+ eagerValuesRef.current.panelDataArrayChanged = true;
2260
+ forceUpdate();
2261
+ }
2262
+ }, [forceUpdate]);
2263
+ const context = useMemo(() => ({
2264
+ collapsePanel,
2265
+ direction,
2266
+ dragState,
2267
+ expandPanel,
2268
+ getPanelSize,
2269
+ getPanelStyle,
2270
+ groupId,
2271
+ isPanelCollapsed,
2272
+ isPanelExpanded,
2273
+ reevaluatePanelConstraints,
2274
+ registerPanel,
2275
+ registerResizeHandle,
2276
+ resizePanel,
2277
+ startDragging,
2278
+ stopDragging,
2279
+ unregisterPanel,
2280
+ panelGroupElement: panelGroupElementRef.current
2281
+ }), [collapsePanel, dragState, direction, expandPanel, getPanelSize, getPanelStyle, groupId, isPanelCollapsed, isPanelExpanded, reevaluatePanelConstraints, registerPanel, registerResizeHandle, resizePanel, startDragging, stopDragging, unregisterPanel]);
2282
+ const style = {
2283
+ display: "flex",
2284
+ flexDirection: direction === "horizontal" ? "row" : "column",
2285
+ height: "100%",
2286
+ overflow: "hidden",
2287
+ width: "100%"
2288
+ };
2289
+ return createElement(PanelGroupContext.Provider, {
2290
+ value: context
2291
+ }, createElement(Type, {
2292
+ ...rest,
2293
+ children,
2294
+ className: classNameFromProps,
2295
+ id: idFromProps,
2296
+ ref: panelGroupElementRef,
2297
+ style: {
2298
+ ...style,
2299
+ ...styleFromProps
2300
+ },
2301
+ // CSS selectors
2302
+ [DATA_ATTRIBUTES.group]: "",
2303
+ [DATA_ATTRIBUTES.groupDirection]: direction,
2304
+ [DATA_ATTRIBUTES.groupId]: groupId
2305
+ }));
2306
+ }
2307
+ const PanelGroup = forwardRef((props, ref) => createElement(PanelGroupWithForwardedRef, {
2308
+ ...props,
2309
+ forwardedRef: ref
2310
+ }));
2311
+ PanelGroupWithForwardedRef.displayName = "PanelGroup";
2312
+ PanelGroup.displayName = "forwardRef(PanelGroup)";
2313
+ function findPanelDataIndex(panelDataArray, panelData) {
2314
+ return panelDataArray.findIndex(prevPanelData => prevPanelData === panelData || prevPanelData.id === panelData.id);
2315
+ }
2316
+ function panelDataHelper(panelDataArray, panelData, layout) {
2317
+ const panelIndex = findPanelDataIndex(panelDataArray, panelData);
2318
+ const isLastPanel = panelIndex === panelDataArray.length - 1;
2319
+ const pivotIndices = isLastPanel ? [panelIndex - 1, panelIndex] : [panelIndex, panelIndex + 1];
2320
+ const panelSize = layout[panelIndex];
2321
+ return {
2322
+ ...panelData.constraints,
2323
+ panelSize,
2324
+ pivotIndices
2325
+ };
2326
+ }
2327
+
2328
+ // https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/
2329
+
2330
+ function useWindowSplitterResizeHandlerBehavior({
2331
+ disabled,
2332
+ handleId,
2333
+ resizeHandler,
2334
+ panelGroupElement
2335
+ }) {
2336
+ useEffect(() => {
2337
+ if (disabled || resizeHandler == null || panelGroupElement == null) {
2338
+ return;
2339
+ }
2340
+ const handleElement = getResizeHandleElement(handleId, panelGroupElement);
2341
+ if (handleElement == null) {
2342
+ return;
2343
+ }
2344
+ const onKeyDown = event => {
2345
+ if (event.defaultPrevented) {
2346
+ return;
2347
+ }
2348
+ switch (event.key) {
2349
+ case "ArrowDown":
2350
+ case "ArrowLeft":
2351
+ case "ArrowRight":
2352
+ case "ArrowUp":
2353
+ case "End":
2354
+ case "Home":
2355
+ {
2356
+ event.preventDefault();
2357
+ resizeHandler(event);
2358
+ break;
2359
+ }
2360
+ case "F6":
2361
+ {
2362
+ event.preventDefault();
2363
+ const groupId = handleElement.getAttribute(DATA_ATTRIBUTES.groupId);
2364
+ assert(groupId, `No group element found for id "${groupId}"`);
2365
+ const handles = getResizeHandleElementsForGroup(groupId, panelGroupElement);
2366
+ const index = getResizeHandleElementIndex(groupId, handleId, panelGroupElement);
2367
+ assert(index !== null, `No resize element found for id "${handleId}"`);
2368
+ const nextIndex = event.shiftKey ? index > 0 ? index - 1 : handles.length - 1 : index + 1 < handles.length ? index + 1 : 0;
2369
+ const nextHandle = handles[nextIndex];
2370
+ nextHandle.focus();
2371
+ break;
2372
+ }
2373
+ }
2374
+ };
2375
+ handleElement.addEventListener("keydown", onKeyDown);
2376
+ return () => {
2377
+ handleElement.removeEventListener("keydown", onKeyDown);
2378
+ };
2379
+ }, [panelGroupElement, disabled, handleId, resizeHandler]);
2380
+ }
2381
+
2382
+ function PanelResizeHandle({
2383
+ children = null,
2384
+ className: classNameFromProps = "",
2385
+ disabled = false,
2386
+ hitAreaMargins,
2387
+ id: idFromProps,
2388
+ onBlur,
2389
+ onClick,
2390
+ onDragging,
2391
+ onFocus,
2392
+ onPointerDown,
2393
+ onPointerUp,
2394
+ style: styleFromProps = {},
2395
+ tabIndex = 0,
2396
+ tagName: Type = "div",
2397
+ ...rest
2398
+ }) {
2399
+ var _hitAreaMargins$coars, _hitAreaMargins$fine;
2400
+ const elementRef = useRef(null);
2401
+
2402
+ // Use a ref to guard against users passing inline props
2403
+ const callbacksRef = useRef({
2404
+ onClick,
2405
+ onDragging,
2406
+ onPointerDown,
2407
+ onPointerUp
2408
+ });
2409
+ useEffect(() => {
2410
+ callbacksRef.current.onClick = onClick;
2411
+ callbacksRef.current.onDragging = onDragging;
2412
+ callbacksRef.current.onPointerDown = onPointerDown;
2413
+ callbacksRef.current.onPointerUp = onPointerUp;
2414
+ });
2415
+ const panelGroupContext = useContext(PanelGroupContext);
2416
+ if (panelGroupContext === null) {
2417
+ throw Error(`PanelResizeHandle components must be rendered within a PanelGroup container`);
2418
+ }
2419
+ const {
2420
+ direction,
2421
+ groupId,
2422
+ registerResizeHandle: registerResizeHandleWithParentGroup,
2423
+ startDragging,
2424
+ stopDragging,
2425
+ panelGroupElement
2426
+ } = panelGroupContext;
2427
+ const resizeHandleId = useUniqueId(idFromProps);
2428
+ const [state, setState] = useState("inactive");
2429
+ const [isFocused, setIsFocused] = useState(false);
2430
+ const [resizeHandler, setResizeHandler] = useState(null);
2431
+ const committedValuesRef = useRef({
2432
+ state
2433
+ });
2434
+ useIsomorphicLayoutEffect(() => {
2435
+ committedValuesRef.current.state = state;
2436
+ });
2437
+ useEffect(() => {
2438
+ if (disabled) {
2439
+ setResizeHandler(null);
2440
+ } else {
2441
+ const resizeHandler = registerResizeHandleWithParentGroup(resizeHandleId);
2442
+ setResizeHandler(() => resizeHandler);
2443
+ }
2444
+ }, [disabled, resizeHandleId, registerResizeHandleWithParentGroup]);
2445
+
2446
+ // Extract hit area margins before passing them to the effect's dependency array
2447
+ // so that inline object values won't trigger re-renders
2448
+ const coarseHitAreaMargins = (_hitAreaMargins$coars = hitAreaMargins === null || hitAreaMargins === void 0 ? void 0 : hitAreaMargins.coarse) !== null && _hitAreaMargins$coars !== void 0 ? _hitAreaMargins$coars : 15;
2449
+ const fineHitAreaMargins = (_hitAreaMargins$fine = hitAreaMargins === null || hitAreaMargins === void 0 ? void 0 : hitAreaMargins.fine) !== null && _hitAreaMargins$fine !== void 0 ? _hitAreaMargins$fine : 5;
2450
+ useEffect(() => {
2451
+ if (disabled || resizeHandler == null) {
2452
+ return;
2453
+ }
2454
+ const element = elementRef.current;
2455
+ assert(element, "Element ref not attached");
2456
+ let didMove = false;
2457
+ const setResizeHandlerState = (action, isActive, event) => {
2458
+ if (!isActive) {
2459
+ setState("inactive");
2460
+ return;
2461
+ }
2462
+ switch (action) {
2463
+ case "down":
2464
+ {
2465
+ setState("drag");
2466
+ didMove = false;
2467
+ assert(event, 'Expected event to be defined for "down" action');
2468
+ startDragging(resizeHandleId, event);
2469
+ const {
2470
+ onDragging,
2471
+ onPointerDown
2472
+ } = callbacksRef.current;
2473
+ onDragging === null || onDragging === void 0 ? void 0 : onDragging(true);
2474
+ onPointerDown === null || onPointerDown === void 0 ? void 0 : onPointerDown();
2475
+ break;
2476
+ }
2477
+ case "move":
2478
+ {
2479
+ const {
2480
+ state
2481
+ } = committedValuesRef.current;
2482
+ didMove = true;
2483
+ if (state !== "drag") {
2484
+ setState("hover");
2485
+ }
2486
+ assert(event, 'Expected event to be defined for "move" action');
2487
+ resizeHandler(event);
2488
+ break;
2489
+ }
2490
+ case "up":
2491
+ {
2492
+ setState("hover");
2493
+ stopDragging();
2494
+ const {
2495
+ onClick,
2496
+ onDragging,
2497
+ onPointerUp
2498
+ } = callbacksRef.current;
2499
+ onDragging === null || onDragging === void 0 ? void 0 : onDragging(false);
2500
+ onPointerUp === null || onPointerUp === void 0 ? void 0 : onPointerUp();
2501
+ if (!didMove) {
2502
+ onClick === null || onClick === void 0 ? void 0 : onClick();
2503
+ }
2504
+ break;
2505
+ }
2506
+ }
2507
+ };
2508
+ return registerResizeHandle(resizeHandleId, element, direction, {
2509
+ coarse: coarseHitAreaMargins,
2510
+ fine: fineHitAreaMargins
2511
+ }, setResizeHandlerState);
2512
+ }, [coarseHitAreaMargins, direction, disabled, fineHitAreaMargins, registerResizeHandleWithParentGroup, resizeHandleId, resizeHandler, startDragging, stopDragging]);
2513
+ useWindowSplitterResizeHandlerBehavior({
2514
+ disabled,
2515
+ handleId: resizeHandleId,
2516
+ resizeHandler,
2517
+ panelGroupElement
2518
+ });
2519
+ const style = {
2520
+ touchAction: "none",
2521
+ userSelect: "none"
2522
+ };
2523
+ return createElement(Type, {
2524
+ ...rest,
2525
+ children,
2526
+ className: classNameFromProps,
2527
+ id: idFromProps,
2528
+ onBlur: () => {
2529
+ setIsFocused(false);
2530
+ onBlur === null || onBlur === void 0 ? void 0 : onBlur();
2531
+ },
2532
+ onFocus: () => {
2533
+ setIsFocused(true);
2534
+ onFocus === null || onFocus === void 0 ? void 0 : onFocus();
2535
+ },
2536
+ ref: elementRef,
2537
+ role: "separator",
2538
+ style: {
2539
+ ...style,
2540
+ ...styleFromProps
2541
+ },
2542
+ tabIndex,
2543
+ // CSS selectors
2544
+ [DATA_ATTRIBUTES.groupDirection]: direction,
2545
+ [DATA_ATTRIBUTES.groupId]: groupId,
2546
+ [DATA_ATTRIBUTES.resizeHandle]: "",
2547
+ [DATA_ATTRIBUTES.resizeHandleActive]: state === "drag" ? "pointer" : isFocused ? "keyboard" : undefined,
2548
+ [DATA_ATTRIBUTES.resizeHandleEnabled]: !disabled,
2549
+ [DATA_ATTRIBUTES.resizeHandleId]: resizeHandleId,
2550
+ [DATA_ATTRIBUTES.resizeHandleState]: state
2551
+ });
2552
+ }
2553
+ PanelResizeHandle.displayName = "PanelResizeHandle";
2554
+
2555
+ function usePanelGroupContext() {
2556
+ const context = useContext(PanelGroupContext);
2557
+ return {
2558
+ direction: context === null || context === void 0 ? void 0 : context.direction,
2559
+ groupId: context === null || context === void 0 ? void 0 : context.groupId
2560
+ };
2561
+ }
2562
+
2563
+ function getPanelElement(id, scope = document) {
2564
+ const element = scope.querySelector(`[data-panel-id="${id}"]`);
2565
+ if (element) {
2566
+ return element;
2567
+ }
2568
+ return null;
2569
+ }
2570
+
2571
+ function getPanelElementsForGroup(groupId, scope = document) {
2572
+ return Array.from(scope.querySelectorAll(`[data-panel][data-panel-group-id="${groupId}"]`));
2573
+ }
2574
+
2575
+ function getIntersectingRectangle(rectOne, rectTwo, strict) {
2576
+ if (!intersects(rectOne, rectTwo, strict)) {
2577
+ return {
2578
+ x: 0,
2579
+ y: 0,
2580
+ width: 0,
2581
+ height: 0
2582
+ };
2583
+ }
2584
+ return {
2585
+ x: Math.max(rectOne.x, rectTwo.x),
2586
+ y: Math.max(rectOne.y, rectTwo.y),
2587
+ width: Math.min(rectOne.x + rectOne.width, rectTwo.x + rectTwo.width) - Math.max(rectOne.x, rectTwo.x),
2588
+ height: Math.min(rectOne.y + rectOne.height, rectTwo.y + rectTwo.height) - Math.max(rectOne.y, rectTwo.y)
2589
+ };
2590
+ }
2591
+
2592
+ export { DATA_ATTRIBUTES, Panel, PanelGroup, PanelResizeHandle, assert, customizeGlobalCursorStyles, disableGlobalCursorStyles, enableGlobalCursorStyles, getIntersectingRectangle, getPanelElement, getPanelElementsForGroup, getPanelGroupElement, getResizeHandleElement, getResizeHandleElementIndex, getResizeHandleElementsForGroup, getResizeHandlePanelIds, intersects, setNonce, usePanelGroupContext };