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