react-resizable-panels 2.1.8 → 3.0.0

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