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