react-resizable-panels 2.1.9 → 3.0.1

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