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