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