react-resizable-panels 2.1.8 → 3.0.0

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