react-resizable-panels 0.0.53 → 0.0.55

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 (41) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/declarations/src/Panel.d.ts +6 -5
  3. package/dist/declarations/src/PanelGroup.d.ts +8 -4
  4. package/dist/declarations/src/PanelResizeHandle.d.ts +5 -2
  5. package/dist/declarations/src/index.d.ts +9 -8
  6. package/dist/declarations/src/types.d.ts +4 -2
  7. package/dist/declarations/src/utils/group.d.ts +29 -0
  8. package/dist/react-resizable-panels.browser.cjs.js +1709 -0
  9. package/dist/react-resizable-panels.browser.cjs.mjs +6 -0
  10. package/dist/react-resizable-panels.browser.development.cjs.js +1764 -0
  11. package/dist/react-resizable-panels.browser.development.cjs.mjs +6 -0
  12. package/dist/react-resizable-panels.browser.development.esm.js +1737 -0
  13. package/dist/react-resizable-panels.browser.esm.js +1682 -0
  14. package/dist/react-resizable-panels.cjs.js +395 -126
  15. package/dist/react-resizable-panels.cjs.js.map +1 -0
  16. package/dist/react-resizable-panels.cjs.mjs +2 -1
  17. package/dist/react-resizable-panels.development.cjs.js +452 -135
  18. package/dist/react-resizable-panels.development.cjs.mjs +6 -0
  19. package/dist/react-resizable-panels.development.esm.js +452 -136
  20. package/dist/react-resizable-panels.development.node.cjs.js +1579 -0
  21. package/dist/react-resizable-panels.development.node.cjs.mjs +6 -0
  22. package/dist/react-resizable-panels.development.node.esm.js +1552 -0
  23. package/dist/react-resizable-panels.esm.js +395 -127
  24. package/dist/react-resizable-panels.esm.js.map +1 -0
  25. package/dist/react-resizable-panels.node.cjs.js +1523 -0
  26. package/dist/react-resizable-panels.node.cjs.mjs +6 -0
  27. package/dist/react-resizable-panels.node.esm.js +1496 -0
  28. package/package.json +26 -1
  29. package/src/Panel.ts +37 -37
  30. package/src/PanelContexts.ts +5 -6
  31. package/src/PanelGroup.ts +269 -121
  32. package/src/PanelResizeHandle.ts +1 -4
  33. package/src/env-conditions/browser.ts +1 -0
  34. package/src/env-conditions/node.ts +1 -0
  35. package/src/env-conditions/unknown.ts +1 -0
  36. package/src/hooks/useIsomorphicEffect.ts +2 -9
  37. package/src/hooks/useWindowSplitterBehavior.ts +14 -11
  38. package/src/index.ts +11 -3
  39. package/src/types.ts +3 -1
  40. package/src/utils/group.ts +327 -28
  41. package/src/utils/ssr.ts +0 -7
@@ -0,0 +1,1709 @@
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
+ // This module exists to work around Webpack issue https://github.com/webpack/webpack/issues/14814
28
+
29
+ // eslint-disable-next-line no-restricted-imports
30
+
31
+ const {
32
+ createElement,
33
+ createContext,
34
+ forwardRef,
35
+ useCallback,
36
+ useContext,
37
+ useEffect,
38
+ useImperativeHandle,
39
+ useLayoutEffect,
40
+ useMemo,
41
+ useRef,
42
+ useState
43
+ } = React__namespace;
44
+
45
+ // `toString()` prevents bundlers from trying to `import { useId } from 'react'`
46
+ const useId = React__namespace["useId".toString()];
47
+
48
+ const useIsomorphicLayoutEffect = useLayoutEffect ;
49
+
50
+ const wrappedUseId = typeof useId === "function" ? useId : () => null;
51
+ let counter = 0;
52
+ function useUniqueId(idFromParams = null) {
53
+ const idFromUseId = wrappedUseId();
54
+ const idRef = useRef(idFromParams || idFromUseId || null);
55
+ if (idRef.current === null) {
56
+ idRef.current = "" + counter++;
57
+ }
58
+ return idRef.current;
59
+ }
60
+
61
+ const PanelGroupContext = createContext(null);
62
+ PanelGroupContext.displayName = "PanelGroupContext";
63
+
64
+ function PanelWithForwardedRef({
65
+ children = null,
66
+ className: classNameFromProps = "",
67
+ collapsedSize = 0,
68
+ collapsible = false,
69
+ defaultSize = null,
70
+ forwardedRef,
71
+ id: idFromProps = null,
72
+ maxSize = null,
73
+ minSize,
74
+ onCollapse = null,
75
+ onResize = null,
76
+ order = null,
77
+ style: styleFromProps = {},
78
+ tagName: Type = "div"
79
+ }) {
80
+ const context = useContext(PanelGroupContext);
81
+ if (context === null) {
82
+ throw Error(`Panel components must be rendered within a PanelGroup container`);
83
+ }
84
+ const panelId = useUniqueId(idFromProps);
85
+ const {
86
+ collapsePanel,
87
+ expandPanel,
88
+ getPanelSize,
89
+ getPanelStyle,
90
+ registerPanel,
91
+ resizePanel,
92
+ units,
93
+ unregisterPanel
94
+ } = context;
95
+ if (minSize == null) {
96
+ if (units === "percentages") {
97
+ // Mimics legacy default value for percentage based panel groups
98
+ minSize = 10;
99
+ } else {
100
+ // There is no meaningful minimum pixel default we can provide
101
+ minSize = 0;
102
+ }
103
+ }
104
+
105
+ // Use a ref to guard against users passing inline props
106
+ const callbacksRef = useRef({
107
+ onCollapse,
108
+ onResize
109
+ });
110
+ useEffect(() => {
111
+ callbacksRef.current.onCollapse = onCollapse;
112
+ callbacksRef.current.onResize = onResize;
113
+ });
114
+ const style = getPanelStyle(panelId, defaultSize);
115
+ const committedValuesRef = useRef({
116
+ size: parseSizeFromStyle(style)
117
+ });
118
+ const panelDataRef = useRef({
119
+ callbacksRef,
120
+ collapsedSize,
121
+ collapsible,
122
+ defaultSize,
123
+ id: panelId,
124
+ idWasAutoGenerated: idFromProps == null,
125
+ maxSize,
126
+ minSize,
127
+ order
128
+ });
129
+ useIsomorphicLayoutEffect(() => {
130
+ committedValuesRef.current.size = parseSizeFromStyle(style);
131
+ panelDataRef.current.callbacksRef = callbacksRef;
132
+ panelDataRef.current.collapsedSize = collapsedSize;
133
+ panelDataRef.current.collapsible = collapsible;
134
+ panelDataRef.current.defaultSize = defaultSize;
135
+ panelDataRef.current.id = panelId;
136
+ panelDataRef.current.idWasAutoGenerated = idFromProps == null;
137
+ panelDataRef.current.maxSize = maxSize;
138
+ panelDataRef.current.minSize = minSize;
139
+ panelDataRef.current.order = order;
140
+ });
141
+ useIsomorphicLayoutEffect(() => {
142
+ registerPanel(panelId, panelDataRef);
143
+ return () => {
144
+ unregisterPanel(panelId);
145
+ };
146
+ }, [order, panelId, registerPanel, unregisterPanel]);
147
+ useImperativeHandle(forwardedRef, () => ({
148
+ collapse: () => collapsePanel(panelId),
149
+ expand: () => expandPanel(panelId),
150
+ getCollapsed() {
151
+ return committedValuesRef.current.size === 0;
152
+ },
153
+ getId() {
154
+ return panelId;
155
+ },
156
+ getSize(units) {
157
+ return getPanelSize(panelId, units);
158
+ },
159
+ resize: (percentage, units) => resizePanel(panelId, percentage, units)
160
+ }), [collapsePanel, expandPanel, getPanelSize, panelId, resizePanel]);
161
+ return createElement(Type, {
162
+ children,
163
+ className: classNameFromProps,
164
+ "data-panel": "",
165
+ "data-panel-collapsible": collapsible || undefined,
166
+ "data-panel-id": panelId,
167
+ "data-panel-size": parseFloat("" + style.flexGrow).toFixed(1),
168
+ id: `data-panel-id-${panelId}`,
169
+ style: {
170
+ ...style,
171
+ ...styleFromProps
172
+ }
173
+ });
174
+ }
175
+ const Panel = forwardRef((props, ref) => createElement(PanelWithForwardedRef, {
176
+ ...props,
177
+ forwardedRef: ref
178
+ }));
179
+ PanelWithForwardedRef.displayName = "Panel";
180
+ Panel.displayName = "forwardRef(Panel)";
181
+
182
+ // HACK
183
+ function parseSizeFromStyle(style) {
184
+ const {
185
+ flexGrow
186
+ } = style;
187
+ if (typeof flexGrow === "string") {
188
+ return parseFloat(flexGrow);
189
+ } else {
190
+ return flexGrow;
191
+ }
192
+ }
193
+
194
+ const PRECISION = 10;
195
+
196
+ function adjustByDelta(event, committedValues, idBefore, idAfter, deltaPixels, prevSizes, panelSizeBeforeCollapse, initialDragState) {
197
+ const {
198
+ id: groupId,
199
+ panels,
200
+ units
201
+ } = committedValues;
202
+ const groupSizePixels = units === "pixels" ? getAvailableGroupSizePixels(groupId) : NaN;
203
+ const {
204
+ sizes: initialSizes
205
+ } = initialDragState || {};
206
+
207
+ // If we're resizing by mouse or touch, use the initial sizes as a base.
208
+ // This has the benefit of causing force-collapsed panels to spring back open if drag is reversed.
209
+ const baseSizes = initialSizes || prevSizes;
210
+ const panelsArray = panelsMapToSortedArray(panels);
211
+ const nextSizes = baseSizes.concat();
212
+ let deltaApplied = 0;
213
+
214
+ // A resizing panel affects the panels before or after it.
215
+ //
216
+ // A negative delta means the panel immediately after the resizer should grow/expand by decreasing its offset.
217
+ // Other panels may also need to shrink/contract (and shift) to make room, depending on the min weights.
218
+ //
219
+ // A positive delta means the panel immediately before the resizer should "expand".
220
+ // This is accomplished by shrinking/contracting (and shifting) one or more of the panels after the resizer.
221
+
222
+ // Max-bounds check the panel being expanded first.
223
+ {
224
+ const pivotId = deltaPixels < 0 ? idAfter : idBefore;
225
+ const index = panelsArray.findIndex(panel => panel.current.id === pivotId);
226
+ const panel = panelsArray[index];
227
+ const baseSize = baseSizes[index];
228
+ const nextSize = safeResizePanel(units, groupSizePixels, panel, baseSize, baseSize + Math.abs(deltaPixels), event);
229
+ if (baseSize === nextSize) {
230
+ // If there's no room for the pivot panel to grow, we can ignore this drag update.
231
+ return baseSizes;
232
+ } else {
233
+ if (nextSize === 0 && baseSize > 0) {
234
+ panelSizeBeforeCollapse.set(pivotId, baseSize);
235
+ }
236
+ deltaPixels = deltaPixels < 0 ? baseSize - nextSize : nextSize - baseSize;
237
+ }
238
+ }
239
+ let pivotId = deltaPixels < 0 ? idBefore : idAfter;
240
+ let index = panelsArray.findIndex(panel => panel.current.id === pivotId);
241
+ while (true) {
242
+ const panel = panelsArray[index];
243
+ const baseSize = baseSizes[index];
244
+ const deltaRemaining = Math.abs(deltaPixels) - Math.abs(deltaApplied);
245
+ const nextSize = safeResizePanel(units, groupSizePixels, panel, baseSize, baseSize - deltaRemaining, event);
246
+ if (baseSize !== nextSize) {
247
+ if (nextSize === 0 && baseSize > 0) {
248
+ panelSizeBeforeCollapse.set(panel.current.id, baseSize);
249
+ }
250
+ deltaApplied += baseSize - nextSize;
251
+ nextSizes[index] = nextSize;
252
+ if (deltaApplied.toPrecision(PRECISION).localeCompare(Math.abs(deltaPixels).toPrecision(PRECISION), undefined, {
253
+ numeric: true
254
+ }) >= 0) {
255
+ break;
256
+ }
257
+ }
258
+ if (deltaPixels < 0) {
259
+ if (--index < 0) {
260
+ break;
261
+ }
262
+ } else {
263
+ if (++index >= panelsArray.length) {
264
+ break;
265
+ }
266
+ }
267
+ }
268
+
269
+ // If we were unable to resize any of the panels panels, return the previous state.
270
+ // This will essentially bailout and ignore the "mousemove" event.
271
+ if (deltaApplied === 0) {
272
+ return baseSizes;
273
+ }
274
+
275
+ // Adjust the pivot panel before, but only by the amount that surrounding panels were able to shrink/contract.
276
+ pivotId = deltaPixels < 0 ? idAfter : idBefore;
277
+ index = panelsArray.findIndex(panel => panel.current.id === pivotId);
278
+ nextSizes[index] = baseSizes[index] + deltaApplied;
279
+ return nextSizes;
280
+ }
281
+ function callPanelCallbacks(panelsArray, sizes, panelIdToLastNotifiedSizeMap) {
282
+ sizes.forEach((size, index) => {
283
+ const panelRef = panelsArray[index];
284
+ if (!panelRef) {
285
+ // Handle initial mount (when panels are registered too late to be in the panels array)
286
+ // The subsequent render+effects will handle the resize notification
287
+ return;
288
+ }
289
+ const {
290
+ callbacksRef,
291
+ collapsedSize,
292
+ collapsible,
293
+ id
294
+ } = panelRef.current;
295
+ const lastNotifiedSize = panelIdToLastNotifiedSizeMap[id];
296
+ if (lastNotifiedSize !== size) {
297
+ panelIdToLastNotifiedSizeMap[id] = size;
298
+ const {
299
+ onCollapse,
300
+ onResize
301
+ } = callbacksRef.current;
302
+ if (onResize) {
303
+ onResize(size, lastNotifiedSize);
304
+ }
305
+ if (collapsible && onCollapse) {
306
+ if ((lastNotifiedSize == null || lastNotifiedSize === collapsedSize) && size !== collapsedSize) {
307
+ onCollapse(false);
308
+ } else if (lastNotifiedSize !== collapsedSize && size === collapsedSize) {
309
+ onCollapse(true);
310
+ }
311
+ }
312
+ }
313
+ });
314
+ }
315
+ function calculateDefaultLayout({
316
+ groupId,
317
+ panels,
318
+ units
319
+ }) {
320
+ const groupSizePixels = units === "pixels" ? getAvailableGroupSizePixels(groupId) : NaN;
321
+ const panelsArray = panelsMapToSortedArray(panels);
322
+ const sizes = Array(panelsArray.length);
323
+ let numPanelsWithSizes = 0;
324
+ let remainingSize = 100;
325
+
326
+ // Assigning default sizes requires a couple of passes:
327
+ // First, all panels with defaultSize should be set as-is
328
+ for (let index = 0; index < panelsArray.length; index++) {
329
+ const panel = panelsArray[index];
330
+ const {
331
+ defaultSize
332
+ } = panel.current;
333
+ if (defaultSize != null) {
334
+ numPanelsWithSizes++;
335
+ sizes[index] = units === "pixels" ? defaultSize / groupSizePixels * 100 : defaultSize;
336
+ remainingSize -= sizes[index];
337
+ }
338
+ }
339
+
340
+ // Remaining total size should be distributed evenly between panels
341
+ // This may require two passes, depending on min/max constraints
342
+ for (let index = 0; index < panelsArray.length; index++) {
343
+ const panel = panelsArray[index];
344
+ let {
345
+ defaultSize,
346
+ id,
347
+ maxSize,
348
+ minSize
349
+ } = panel.current;
350
+ if (defaultSize != null) {
351
+ continue;
352
+ }
353
+ if (units === "pixels") {
354
+ minSize = minSize / groupSizePixels * 100;
355
+ if (maxSize != null) {
356
+ maxSize = maxSize / groupSizePixels * 100;
357
+ }
358
+ }
359
+ const remainingPanels = panelsArray.length - numPanelsWithSizes;
360
+ const size = Math.min(maxSize != null ? maxSize : 100, Math.max(minSize, remainingSize / remainingPanels));
361
+ sizes[index] = size;
362
+ numPanelsWithSizes++;
363
+ remainingSize -= size;
364
+ }
365
+
366
+ // If there is additional, left over space, assign it to any panel(s) that permits it
367
+ // (It's not worth taking multiple additional passes to evenly distribute)
368
+ if (remainingSize !== 0) {
369
+ for (let index = 0; index < panelsArray.length; index++) {
370
+ const panel = panelsArray[index];
371
+ let {
372
+ maxSize,
373
+ minSize
374
+ } = panel.current;
375
+ if (units === "pixels") {
376
+ minSize = minSize / groupSizePixels * 100;
377
+ if (maxSize != null) {
378
+ maxSize = maxSize / groupSizePixels * 100;
379
+ }
380
+ }
381
+ const size = Math.min(maxSize != null ? maxSize : 100, Math.max(minSize, sizes[index] + remainingSize));
382
+ if (size !== sizes[index]) {
383
+ remainingSize -= size - sizes[index];
384
+ sizes[index] = size;
385
+
386
+ // Fuzzy comparison to account for imprecise floating point math
387
+ if (Math.abs(remainingSize).toFixed(3) === "0.000") {
388
+ break;
389
+ }
390
+ }
391
+ }
392
+ }
393
+
394
+ // Finally, if there is still left-over size, log an error
395
+ if (Math.abs(remainingSize).toFixed(3) !== "0.000") ;
396
+ return sizes;
397
+ }
398
+ function getBeforeAndAfterIds(id, panelsArray) {
399
+ if (panelsArray.length < 2) {
400
+ return [null, null];
401
+ }
402
+ const index = panelsArray.findIndex(panel => panel.current.id === id);
403
+ if (index < 0) {
404
+ return [null, null];
405
+ }
406
+ const isLastPanel = index === panelsArray.length - 1;
407
+ const idBefore = isLastPanel ? panelsArray[index - 1].current.id : id;
408
+ const idAfter = isLastPanel ? id : panelsArray[index + 1].current.id;
409
+ return [idBefore, idAfter];
410
+ }
411
+ function getAvailableGroupSizePixels(groupId) {
412
+ const panelGroupElement = getPanelGroup(groupId);
413
+ if (panelGroupElement == null) {
414
+ return NaN;
415
+ }
416
+ const direction = panelGroupElement.getAttribute("data-panel-group-direction");
417
+ const resizeHandles = getResizeHandlesForGroup(groupId);
418
+ if (direction === "horizontal") {
419
+ return panelGroupElement.offsetWidth - resizeHandles.reduce((accumulated, handle) => {
420
+ return accumulated + handle.offsetWidth;
421
+ }, 0);
422
+ } else {
423
+ return panelGroupElement.offsetHeight - resizeHandles.reduce((accumulated, handle) => {
424
+ return accumulated + handle.offsetHeight;
425
+ }, 0);
426
+ }
427
+ }
428
+
429
+ // This method returns a number between 1 and 100 representing
430
+ // the % of the group's overall space this panel should occupy.
431
+ function getFlexGrow(panels, id, sizes) {
432
+ if (panels.size === 1) {
433
+ return "100";
434
+ }
435
+ const panelsArray = panelsMapToSortedArray(panels);
436
+ const index = panelsArray.findIndex(panel => panel.current.id === id);
437
+ const size = sizes[index];
438
+ if (size == null) {
439
+ return "0";
440
+ }
441
+ return size.toPrecision(PRECISION);
442
+ }
443
+ function getPanel(id) {
444
+ const element = document.querySelector(`[data-panel-id="${id}"]`);
445
+ if (element) {
446
+ return element;
447
+ }
448
+ return null;
449
+ }
450
+ function getPanelGroup(id) {
451
+ const element = document.querySelector(`[data-panel-group-id="${id}"]`);
452
+ if (element) {
453
+ return element;
454
+ }
455
+ return null;
456
+ }
457
+ function getResizeHandle(id) {
458
+ const element = document.querySelector(`[data-panel-resize-handle-id="${id}"]`);
459
+ if (element) {
460
+ return element;
461
+ }
462
+ return null;
463
+ }
464
+ function getResizeHandleIndex(id) {
465
+ const handles = getResizeHandles();
466
+ const index = handles.findIndex(handle => handle.getAttribute("data-panel-resize-handle-id") === id);
467
+ return index ?? null;
468
+ }
469
+ function getResizeHandles() {
470
+ return Array.from(document.querySelectorAll(`[data-panel-resize-handle-id]`));
471
+ }
472
+ function getResizeHandlesForGroup(groupId) {
473
+ return Array.from(document.querySelectorAll(`[data-panel-resize-handle-id][data-panel-group-id="${groupId}"]`));
474
+ }
475
+ function getResizeHandlePanelIds(groupId, handleId, panelsArray) {
476
+ const handle = getResizeHandle(handleId);
477
+ const handles = getResizeHandlesForGroup(groupId);
478
+ const index = handle ? handles.indexOf(handle) : -1;
479
+ const idBefore = panelsArray[index]?.current?.id ?? null;
480
+ const idAfter = panelsArray[index + 1]?.current?.id ?? null;
481
+ return [idBefore, idAfter];
482
+ }
483
+ function panelsMapToSortedArray(panels) {
484
+ return Array.from(panels.values()).sort((panelA, panelB) => {
485
+ const orderA = panelA.current.order;
486
+ const orderB = panelB.current.order;
487
+ if (orderA == null && orderB == null) {
488
+ return 0;
489
+ } else if (orderA == null) {
490
+ return -1;
491
+ } else if (orderB == null) {
492
+ return 1;
493
+ } else {
494
+ return orderA - orderB;
495
+ }
496
+ });
497
+ }
498
+ function safeResizePanel(units, groupSizePixels, panel, prevSize, nextSize, event = null) {
499
+ let {
500
+ collapsedSize,
501
+ collapsible,
502
+ maxSize,
503
+ minSize
504
+ } = panel.current;
505
+ if (units === "pixels") {
506
+ collapsedSize = collapsedSize / groupSizePixels * 100;
507
+ if (maxSize != null) {
508
+ maxSize = maxSize / groupSizePixels * 100;
509
+ }
510
+ minSize = minSize / groupSizePixels * 100;
511
+ }
512
+ if (collapsible) {
513
+ if (prevSize > collapsedSize) {
514
+ // Mimic VS COde behavior; collapse a panel if it's smaller than half of its min-size
515
+ if (nextSize <= minSize / 2 + collapsedSize) {
516
+ return collapsedSize;
517
+ }
518
+ } else {
519
+ const isKeyboardEvent = event?.type?.startsWith("key");
520
+ if (!isKeyboardEvent) {
521
+ // Keyboard events should expand a collapsed panel to the min size,
522
+ // but mouse events should wait until the panel has reached its min size
523
+ // to avoid a visual flickering when dragging between collapsed and min size.
524
+ if (nextSize < minSize) {
525
+ return collapsedSize;
526
+ }
527
+ }
528
+ }
529
+ }
530
+ return Math.min(maxSize != null ? maxSize : 100, Math.max(minSize, nextSize));
531
+ }
532
+ function validatePanelProps(units, panelData) {
533
+ const {
534
+ collapsible,
535
+ defaultSize,
536
+ maxSize,
537
+ minSize
538
+ } = panelData.current;
539
+
540
+ // Basic props validation
541
+ if (minSize < 0 || units === "percentages" && minSize > 100) {
542
+ panelData.current.minSize = 0;
543
+ }
544
+ if (maxSize != null) {
545
+ if (maxSize < 0 || units === "percentages" && maxSize > 100) {
546
+ panelData.current.maxSize = null;
547
+ }
548
+ }
549
+ if (defaultSize !== null) {
550
+ if (defaultSize < 0 || units === "percentages" && defaultSize > 100) {
551
+ panelData.current.defaultSize = null;
552
+ } else if (defaultSize < minSize && !collapsible) {
553
+ panelData.current.defaultSize = minSize;
554
+ } else if (maxSize != null && defaultSize > maxSize) {
555
+ panelData.current.defaultSize = maxSize;
556
+ }
557
+ }
558
+ }
559
+ function validatePanelGroupLayout({
560
+ groupId,
561
+ panels,
562
+ nextSizes,
563
+ prevSizes,
564
+ units
565
+ }) {
566
+ // Clone because this method modifies
567
+ nextSizes = [...nextSizes];
568
+ const panelsArray = panelsMapToSortedArray(panels);
569
+ const groupSizePixels = units === "pixels" ? getAvailableGroupSizePixels(groupId) : NaN;
570
+ let remainingSize = 0;
571
+
572
+ // First, check all of the proposed sizes against the min/max constraints
573
+ for (let index = 0; index < panelsArray.length; index++) {
574
+ const panel = panelsArray[index];
575
+ const prevSize = prevSizes[index];
576
+ const nextSize = nextSizes[index];
577
+ const safeNextSize = safeResizePanel(units, groupSizePixels, panel, prevSize, nextSize);
578
+ if (nextSize != safeNextSize) {
579
+ remainingSize += nextSize - safeNextSize;
580
+ nextSizes[index] = safeNextSize;
581
+ }
582
+ }
583
+
584
+ // If there is additional, left over space, assign it to any panel(s) that permits it
585
+ // (It's not worth taking multiple additional passes to evenly distribute)
586
+ if (remainingSize.toFixed(3) !== "0.000") {
587
+ for (let index = 0; index < panelsArray.length; index++) {
588
+ const panel = panelsArray[index];
589
+ let {
590
+ maxSize,
591
+ minSize
592
+ } = panel.current;
593
+ if (units === "pixels") {
594
+ minSize = minSize / groupSizePixels * 100;
595
+ if (maxSize != null) {
596
+ maxSize = maxSize / groupSizePixels * 100;
597
+ }
598
+ }
599
+ const size = Math.min(maxSize != null ? maxSize : 100, Math.max(minSize, nextSizes[index] + remainingSize));
600
+ if (size !== nextSizes[index]) {
601
+ remainingSize -= size - nextSizes[index];
602
+ nextSizes[index] = size;
603
+
604
+ // Fuzzy comparison to account for imprecise floating point math
605
+ if (Math.abs(remainingSize).toFixed(3) === "0.000") {
606
+ break;
607
+ }
608
+ }
609
+ }
610
+ }
611
+
612
+ // If we still have remainder, the requested layout wasn't valid and we should warn about it
613
+ if (remainingSize.toFixed(3) !== "0.000") ;
614
+ return nextSizes;
615
+ }
616
+
617
+ function assert(expectedCondition, message = "Assertion failed!") {
618
+ if (!expectedCondition) {
619
+ console.error(message);
620
+ throw Error(message);
621
+ }
622
+ }
623
+
624
+ // https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/
625
+
626
+ function useWindowSplitterPanelGroupBehavior({
627
+ committedValuesRef,
628
+ groupId,
629
+ panels,
630
+ setSizes,
631
+ sizes,
632
+ panelSizeBeforeCollapse
633
+ }) {
634
+ useEffect(() => {
635
+ const {
636
+ direction,
637
+ panels
638
+ } = committedValuesRef.current;
639
+ const groupElement = getPanelGroup(groupId);
640
+ assert(groupElement != null, `No group found for id "${groupId}"`);
641
+ const {
642
+ height,
643
+ width
644
+ } = groupElement.getBoundingClientRect();
645
+ const handles = getResizeHandlesForGroup(groupId);
646
+ const cleanupFunctions = handles.map(handle => {
647
+ const handleId = handle.getAttribute("data-panel-resize-handle-id");
648
+ const panelsArray = panelsMapToSortedArray(panels);
649
+ const [idBefore, idAfter] = getResizeHandlePanelIds(groupId, handleId, panelsArray);
650
+ if (idBefore == null || idAfter == null) {
651
+ return () => {};
652
+ }
653
+ let currentMinSize = 0;
654
+ let currentMaxSize = 100;
655
+ let totalMinSize = 0;
656
+ let totalMaxSize = 0;
657
+
658
+ // A panel's effective min/max sizes also need to account for other panel's sizes.
659
+ panelsArray.forEach(panelData => {
660
+ const {
661
+ id,
662
+ maxSize,
663
+ minSize
664
+ } = panelData.current;
665
+ if (id === idBefore) {
666
+ currentMinSize = minSize;
667
+ currentMaxSize = maxSize != null ? maxSize : 100;
668
+ } else {
669
+ totalMinSize += minSize;
670
+ totalMaxSize += maxSize != null ? maxSize : 100;
671
+ }
672
+ });
673
+ const ariaValueMax = Math.min(currentMaxSize, 100 - totalMinSize);
674
+ const ariaValueMin = Math.max(currentMinSize, (panelsArray.length - 1) * 100 - totalMaxSize);
675
+ const flexGrow = getFlexGrow(panels, idBefore, sizes);
676
+ handle.setAttribute("aria-valuemax", "" + Math.round(ariaValueMax));
677
+ handle.setAttribute("aria-valuemin", "" + Math.round(ariaValueMin));
678
+ handle.setAttribute("aria-valuenow", "" + Math.round(parseInt(flexGrow)));
679
+ const onKeyDown = event => {
680
+ if (event.defaultPrevented) {
681
+ return;
682
+ }
683
+ switch (event.key) {
684
+ case "Enter":
685
+ {
686
+ event.preventDefault();
687
+ const index = panelsArray.findIndex(panel => panel.current.id === idBefore);
688
+ if (index >= 0) {
689
+ const panelData = panelsArray[index];
690
+ const size = sizes[index];
691
+ if (size != null) {
692
+ let delta = 0;
693
+ if (size.toPrecision(PRECISION) <= panelData.current.minSize.toPrecision(PRECISION)) {
694
+ delta = direction === "horizontal" ? width : height;
695
+ } else {
696
+ delta = -(direction === "horizontal" ? width : height);
697
+ }
698
+ const nextSizes = adjustByDelta(event, committedValuesRef.current, idBefore, idAfter, delta, sizes, panelSizeBeforeCollapse.current, null);
699
+ if (sizes !== nextSizes) {
700
+ setSizes(nextSizes);
701
+ }
702
+ }
703
+ }
704
+ break;
705
+ }
706
+ }
707
+ };
708
+ handle.addEventListener("keydown", onKeyDown);
709
+ const panelBefore = getPanel(idBefore);
710
+ if (panelBefore != null) {
711
+ handle.setAttribute("aria-controls", panelBefore.id);
712
+ }
713
+ return () => {
714
+ handle.removeAttribute("aria-valuemax");
715
+ handle.removeAttribute("aria-valuemin");
716
+ handle.removeAttribute("aria-valuenow");
717
+ handle.removeEventListener("keydown", onKeyDown);
718
+ if (panelBefore != null) {
719
+ handle.removeAttribute("aria-controls");
720
+ }
721
+ };
722
+ });
723
+ return () => {
724
+ cleanupFunctions.forEach(cleanupFunction => cleanupFunction());
725
+ };
726
+ }, [committedValuesRef, groupId, panels, panelSizeBeforeCollapse, setSizes, sizes]);
727
+ }
728
+ function useWindowSplitterResizeHandlerBehavior({
729
+ disabled,
730
+ handleId,
731
+ resizeHandler
732
+ }) {
733
+ useEffect(() => {
734
+ if (disabled || resizeHandler == null) {
735
+ return;
736
+ }
737
+ const handleElement = getResizeHandle(handleId);
738
+ if (handleElement == null) {
739
+ return;
740
+ }
741
+ const onKeyDown = event => {
742
+ if (event.defaultPrevented) {
743
+ return;
744
+ }
745
+ switch (event.key) {
746
+ case "ArrowDown":
747
+ case "ArrowLeft":
748
+ case "ArrowRight":
749
+ case "ArrowUp":
750
+ case "End":
751
+ case "Home":
752
+ {
753
+ event.preventDefault();
754
+ resizeHandler(event);
755
+ break;
756
+ }
757
+ case "F6":
758
+ {
759
+ event.preventDefault();
760
+ const handles = getResizeHandles();
761
+ const index = getResizeHandleIndex(handleId);
762
+ assert(index !== null);
763
+ const nextIndex = event.shiftKey ? index > 0 ? index - 1 : handles.length - 1 : index + 1 < handles.length ? index + 1 : 0;
764
+ const nextHandle = handles[nextIndex];
765
+ nextHandle.focus();
766
+ break;
767
+ }
768
+ }
769
+ };
770
+ handleElement.addEventListener("keydown", onKeyDown);
771
+ return () => {
772
+ handleElement.removeEventListener("keydown", onKeyDown);
773
+ };
774
+ }, [disabled, handleId, resizeHandler]);
775
+ }
776
+
777
+ function areEqual(arrayA, arrayB) {
778
+ if (arrayA.length !== arrayB.length) {
779
+ return false;
780
+ }
781
+ for (let index = 0; index < arrayA.length; index++) {
782
+ if (arrayA[index] !== arrayB[index]) {
783
+ return false;
784
+ }
785
+ }
786
+ return true;
787
+ }
788
+
789
+ function getDragOffset(event, handleId, direction, initialOffset = 0, initialHandleElementRect = null) {
790
+ const isHorizontal = direction === "horizontal";
791
+ let pointerOffset = 0;
792
+ if (isMouseEvent(event)) {
793
+ pointerOffset = isHorizontal ? event.clientX : event.clientY;
794
+ } else if (isTouchEvent(event)) {
795
+ const firstTouch = event.touches[0];
796
+ pointerOffset = isHorizontal ? firstTouch.screenX : firstTouch.screenY;
797
+ } else {
798
+ return 0;
799
+ }
800
+ const handleElement = getResizeHandle(handleId);
801
+ const rect = initialHandleElementRect || handleElement.getBoundingClientRect();
802
+ const elementOffset = isHorizontal ? rect.left : rect.top;
803
+ return pointerOffset - elementOffset - initialOffset;
804
+ }
805
+
806
+ // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX
807
+ function getMovement(event, groupId, handleId, panelsArray, direction, prevSizes, initialDragState) {
808
+ const {
809
+ dragOffset = 0,
810
+ dragHandleRect,
811
+ sizes: initialSizes
812
+ } = initialDragState || {};
813
+
814
+ // If we're resizing by mouse or touch, use the initial sizes as a base.
815
+ // This has the benefit of causing force-collapsed panels to spring back open if drag is reversed.
816
+ const baseSizes = initialSizes || prevSizes;
817
+ if (isKeyDown(event)) {
818
+ const isHorizontal = direction === "horizontal";
819
+ const groupElement = getPanelGroup(groupId);
820
+ const rect = groupElement.getBoundingClientRect();
821
+ const groupSizeInPixels = isHorizontal ? rect.width : rect.height;
822
+ const denominator = event.shiftKey ? 10 : 100;
823
+ const delta = groupSizeInPixels / denominator;
824
+ let movement = 0;
825
+ switch (event.key) {
826
+ case "ArrowDown":
827
+ movement = isHorizontal ? 0 : delta;
828
+ break;
829
+ case "ArrowLeft":
830
+ movement = isHorizontal ? -delta : 0;
831
+ break;
832
+ case "ArrowRight":
833
+ movement = isHorizontal ? delta : 0;
834
+ break;
835
+ case "ArrowUp":
836
+ movement = isHorizontal ? 0 : -delta;
837
+ break;
838
+ case "End":
839
+ movement = groupSizeInPixels;
840
+ break;
841
+ case "Home":
842
+ movement = -groupSizeInPixels;
843
+ break;
844
+ }
845
+
846
+ // If the Panel being resized is collapsible,
847
+ // we need to special case resizing around the minSize boundary.
848
+ // If contracting, Panels should shrink to their minSize and then snap to fully collapsed.
849
+ // If expanding from collapsed, they should snap back to their minSize.
850
+ const [idBefore, idAfter] = getResizeHandlePanelIds(groupId, handleId, panelsArray);
851
+ const targetPanelId = movement < 0 ? idBefore : idAfter;
852
+ const targetPanelIndex = panelsArray.findIndex(panel => panel.current.id === targetPanelId);
853
+ const targetPanel = panelsArray[targetPanelIndex];
854
+ if (targetPanel.current.collapsible) {
855
+ const baseSize = baseSizes[targetPanelIndex];
856
+ if (baseSize === 0 || baseSize.toPrecision(PRECISION) === targetPanel.current.minSize.toPrecision(PRECISION)) {
857
+ movement = movement < 0 ? -targetPanel.current.minSize * groupSizeInPixels : targetPanel.current.minSize * groupSizeInPixels;
858
+ }
859
+ }
860
+ return movement;
861
+ } else {
862
+ return getDragOffset(event, handleId, direction, dragOffset, dragHandleRect);
863
+ }
864
+ }
865
+ function isKeyDown(event) {
866
+ return event.type === "keydown";
867
+ }
868
+ function isMouseEvent(event) {
869
+ return event.type.startsWith("mouse");
870
+ }
871
+ function isTouchEvent(event) {
872
+ return event.type.startsWith("touch");
873
+ }
874
+
875
+ let currentState = null;
876
+ let element = null;
877
+ function getCursorStyle(state) {
878
+ switch (state) {
879
+ case "horizontal":
880
+ return "ew-resize";
881
+ case "horizontal-max":
882
+ return "w-resize";
883
+ case "horizontal-min":
884
+ return "e-resize";
885
+ case "vertical":
886
+ return "ns-resize";
887
+ case "vertical-max":
888
+ return "n-resize";
889
+ case "vertical-min":
890
+ return "s-resize";
891
+ }
892
+ }
893
+ function resetGlobalCursorStyle() {
894
+ if (element !== null) {
895
+ document.head.removeChild(element);
896
+ currentState = null;
897
+ element = null;
898
+ }
899
+ }
900
+ function setGlobalCursorStyle(state) {
901
+ if (currentState === state) {
902
+ return;
903
+ }
904
+ currentState = state;
905
+ const style = getCursorStyle(state);
906
+ if (element === null) {
907
+ element = document.createElement("style");
908
+ document.head.appendChild(element);
909
+ }
910
+ element.innerHTML = `*{cursor: ${style}!important;}`;
911
+ }
912
+
913
+ function debounce(callback, durationMs = 10) {
914
+ let timeoutId = null;
915
+ let callable = (...args) => {
916
+ if (timeoutId !== null) {
917
+ clearTimeout(timeoutId);
918
+ }
919
+ timeoutId = setTimeout(() => {
920
+ callback(...args);
921
+ }, durationMs);
922
+ };
923
+ return callable;
924
+ }
925
+
926
+ // Note that Panel ids might be user-provided (stable) or useId generated (non-deterministic)
927
+ // so they should not be used as part of the serialization key.
928
+ // Using an attribute like minSize instead should work well enough.
929
+ // Pre-sorting by minSize allows remembering layouts even if panels are re-ordered/dragged.
930
+ function getSerializationKey(panels) {
931
+ return panels.map(panel => {
932
+ const {
933
+ minSize,
934
+ order
935
+ } = panel.current;
936
+ return order ? `${order}:${minSize}` : `${minSize}`;
937
+ }).sort((a, b) => a.localeCompare(b)).join(",");
938
+ }
939
+ function loadSerializedPanelGroupState(autoSaveId, storage) {
940
+ try {
941
+ const serialized = storage.getItem(`PanelGroup:sizes:${autoSaveId}`);
942
+ if (serialized) {
943
+ const parsed = JSON.parse(serialized);
944
+ if (typeof parsed === "object" && parsed != null) {
945
+ return parsed;
946
+ }
947
+ }
948
+ } catch (error) {}
949
+ return null;
950
+ }
951
+ function loadPanelLayout(autoSaveId, panels, storage) {
952
+ const state = loadSerializedPanelGroupState(autoSaveId, storage);
953
+ if (state) {
954
+ const key = getSerializationKey(panels);
955
+ return state[key] ?? null;
956
+ }
957
+ return null;
958
+ }
959
+ function savePanelGroupLayout(autoSaveId, panels, sizes, storage) {
960
+ const key = getSerializationKey(panels);
961
+ const state = loadSerializedPanelGroupState(autoSaveId, storage) || {};
962
+ state[key] = sizes;
963
+ try {
964
+ storage.setItem(`PanelGroup:sizes:${autoSaveId}`, JSON.stringify(state));
965
+ } catch (error) {
966
+ console.error(error);
967
+ }
968
+ }
969
+
970
+ const debounceMap = {};
971
+
972
+ // PanelGroup might be rendering in a server-side environment where localStorage is not available
973
+ // or on a browser with cookies/storage disabled.
974
+ // In either case, this function avoids accessing localStorage until needed,
975
+ // and avoids throwing user-visible errors.
976
+ function initializeDefaultStorage(storageObject) {
977
+ try {
978
+ if (typeof localStorage !== "undefined") {
979
+ // Bypass this check for future calls
980
+ storageObject.getItem = name => {
981
+ return localStorage.getItem(name);
982
+ };
983
+ storageObject.setItem = (name, value) => {
984
+ localStorage.setItem(name, value);
985
+ };
986
+ } else {
987
+ throw new Error("localStorage not supported in this environment");
988
+ }
989
+ } catch (error) {
990
+ console.error(error);
991
+ storageObject.getItem = () => null;
992
+ storageObject.setItem = () => {};
993
+ }
994
+ }
995
+ const defaultStorage = {
996
+ getItem: name => {
997
+ initializeDefaultStorage(defaultStorage);
998
+ return defaultStorage.getItem(name);
999
+ },
1000
+ setItem: (name, value) => {
1001
+ initializeDefaultStorage(defaultStorage);
1002
+ defaultStorage.setItem(name, value);
1003
+ }
1004
+ };
1005
+
1006
+ // Initial drag state serves a few purposes:
1007
+ // * dragOffset:
1008
+ // Resize is calculated by the distance between the current pointer event and the resize handle being "dragged"
1009
+ // This value accounts for the initial offset when the touch/click starts, so the handle doesn't appear to "jump"
1010
+ // * dragHandleRect, sizes:
1011
+ // When resizing is done via mouse/touch event– some initial state is stored
1012
+ // so that any panels that contract will also expand if drag direction is reversed.
1013
+ function PanelGroupWithForwardedRef({
1014
+ autoSaveId,
1015
+ children = null,
1016
+ className: classNameFromProps = "",
1017
+ direction,
1018
+ disablePointerEventsDuringResize = false,
1019
+ forwardedRef,
1020
+ id: idFromProps = null,
1021
+ onLayout,
1022
+ storage = defaultStorage,
1023
+ style: styleFromProps = {},
1024
+ tagName: Type = "div",
1025
+ units = "percentages"
1026
+ }) {
1027
+ const groupId = useUniqueId(idFromProps);
1028
+ const [activeHandleId, setActiveHandleId] = useState(null);
1029
+ const [panels, setPanels] = useState(new Map());
1030
+
1031
+ // When resizing is done via mouse/touch event–
1032
+ // We store the initial Panel sizes in this ref, and apply move deltas to them instead of to the current sizes.
1033
+ // This has the benefit of causing force-collapsed panels to spring back open if drag is reversed.
1034
+ const initialDragStateRef = useRef(null);
1035
+ useRef({
1036
+ didLogDefaultSizeWarning: false,
1037
+ didLogIdAndOrderWarning: false,
1038
+ didLogInvalidLayoutWarning: false,
1039
+ prevPanelIds: []
1040
+ });
1041
+
1042
+ // Use a ref to guard against users passing inline props
1043
+ const callbacksRef = useRef({
1044
+ onLayout
1045
+ });
1046
+ useEffect(() => {
1047
+ callbacksRef.current.onLayout = onLayout;
1048
+ });
1049
+ const panelIdToLastNotifiedSizeMapRef = useRef({});
1050
+
1051
+ // 0-1 values representing the relative size of each panel.
1052
+ const [sizes, setSizes] = useState([]);
1053
+
1054
+ // Used to support imperative collapse/expand API.
1055
+ const panelSizeBeforeCollapse = useRef(new Map());
1056
+ const prevDeltaRef = useRef(0);
1057
+
1058
+ // Store committed values to avoid unnecessarily re-running memoization/effects functions.
1059
+ const committedValuesRef = useRef({
1060
+ direction,
1061
+ id: groupId,
1062
+ panels,
1063
+ sizes,
1064
+ units
1065
+ });
1066
+ useImperativeHandle(forwardedRef, () => ({
1067
+ getId: () => groupId,
1068
+ getLayout: unitsFromParams => {
1069
+ const {
1070
+ sizes,
1071
+ units: unitsFromProps
1072
+ } = committedValuesRef.current;
1073
+ const units = unitsFromParams ?? unitsFromProps;
1074
+ if (units === "pixels") {
1075
+ const groupSizePixels = getAvailableGroupSizePixels(groupId);
1076
+ return sizes.map(size => size / 100 * groupSizePixels);
1077
+ } else {
1078
+ return sizes;
1079
+ }
1080
+ },
1081
+ setLayout: (sizes, unitsFromParams) => {
1082
+ const {
1083
+ id: groupId,
1084
+ panels,
1085
+ sizes: prevSizes,
1086
+ units
1087
+ } = committedValuesRef.current;
1088
+ if ((unitsFromParams || units) === "pixels") {
1089
+ const groupSizePixels = getAvailableGroupSizePixels(groupId);
1090
+ sizes = sizes.map(size => size / groupSizePixels * 100);
1091
+ }
1092
+ const panelIdToLastNotifiedSizeMap = panelIdToLastNotifiedSizeMapRef.current;
1093
+ const panelsArray = panelsMapToSortedArray(panels);
1094
+ const nextSizes = validatePanelGroupLayout({
1095
+ groupId,
1096
+ panels,
1097
+ nextSizes: sizes,
1098
+ prevSizes,
1099
+ units
1100
+ });
1101
+ if (!areEqual(prevSizes, nextSizes)) {
1102
+ setSizes(nextSizes);
1103
+ callPanelCallbacks(panelsArray, nextSizes, panelIdToLastNotifiedSizeMap);
1104
+ }
1105
+ }
1106
+ }), [groupId]);
1107
+ useIsomorphicLayoutEffect(() => {
1108
+ committedValuesRef.current.direction = direction;
1109
+ committedValuesRef.current.id = groupId;
1110
+ committedValuesRef.current.panels = panels;
1111
+ committedValuesRef.current.sizes = sizes;
1112
+ committedValuesRef.current.units = units;
1113
+ });
1114
+ useWindowSplitterPanelGroupBehavior({
1115
+ committedValuesRef,
1116
+ groupId,
1117
+ panels,
1118
+ setSizes,
1119
+ sizes,
1120
+ panelSizeBeforeCollapse
1121
+ });
1122
+
1123
+ // Notify external code when sizes have changed.
1124
+ useEffect(() => {
1125
+ const {
1126
+ onLayout
1127
+ } = callbacksRef.current;
1128
+ const {
1129
+ panels,
1130
+ sizes
1131
+ } = committedValuesRef.current;
1132
+
1133
+ // Don't commit layout until all panels have registered and re-rendered with their actual sizes.
1134
+ if (sizes.length > 0) {
1135
+ if (onLayout) {
1136
+ onLayout(sizes);
1137
+ }
1138
+ const panelIdToLastNotifiedSizeMap = panelIdToLastNotifiedSizeMapRef.current;
1139
+
1140
+ // When possible, we notify before the next render so that rendering work can be batched together.
1141
+ // Some cases are difficult to detect though,
1142
+ // for example– panels that are conditionally rendered can affect the size of neighboring panels.
1143
+ // In this case, the best we can do is notify on commit.
1144
+ // The callPanelCallbacks() uses its own memoization to avoid notifying panels twice in these cases.
1145
+ const panelsArray = panelsMapToSortedArray(panels);
1146
+ callPanelCallbacks(panelsArray, sizes, panelIdToLastNotifiedSizeMap);
1147
+ }
1148
+ }, [sizes]);
1149
+
1150
+ // Once all panels have registered themselves,
1151
+ // Compute the initial sizes based on default weights.
1152
+ // This assumes that panels register during initial mount (no conditional rendering)!
1153
+ useIsomorphicLayoutEffect(() => {
1154
+ const {
1155
+ id: groupId,
1156
+ sizes,
1157
+ units
1158
+ } = committedValuesRef.current;
1159
+ if (sizes.length === panels.size) {
1160
+ // Only compute (or restore) default sizes once per panel configuration.
1161
+ return;
1162
+ }
1163
+
1164
+ // If this panel has been configured to persist sizing information,
1165
+ // default size should be restored from local storage if possible.
1166
+ let defaultSizes = null;
1167
+ if (autoSaveId) {
1168
+ const panelsArray = panelsMapToSortedArray(panels);
1169
+ defaultSizes = loadPanelLayout(autoSaveId, panelsArray, storage);
1170
+ }
1171
+ if (defaultSizes != null) {
1172
+ // Validate saved sizes in case something has changed since last render
1173
+ // e.g. for pixel groups, this could be the size of the window
1174
+ const validatedSizes = validatePanelGroupLayout({
1175
+ groupId,
1176
+ panels,
1177
+ nextSizes: defaultSizes,
1178
+ prevSizes: defaultSizes,
1179
+ units
1180
+ });
1181
+ setSizes(validatedSizes);
1182
+ } else {
1183
+ const sizes = calculateDefaultLayout({
1184
+ groupId,
1185
+ panels,
1186
+ units
1187
+ });
1188
+ setSizes(sizes);
1189
+ }
1190
+ }, [autoSaveId, panels, storage]);
1191
+ useEffect(() => {
1192
+ // If this panel has been configured to persist sizing information, save sizes to local storage.
1193
+ if (autoSaveId) {
1194
+ if (sizes.length === 0 || sizes.length !== panels.size) {
1195
+ return;
1196
+ }
1197
+ const panelsArray = panelsMapToSortedArray(panels);
1198
+
1199
+ // Limit the frequency of localStorage updates.
1200
+ if (!debounceMap[autoSaveId]) {
1201
+ debounceMap[autoSaveId] = debounce(savePanelGroupLayout, 100);
1202
+ }
1203
+ debounceMap[autoSaveId](autoSaveId, panelsArray, sizes, storage);
1204
+ }
1205
+ }, [autoSaveId, panels, sizes, storage]);
1206
+ useIsomorphicLayoutEffect(() => {
1207
+ // Pixel panel constraints need to be reassessed after a group resize
1208
+ // We can avoid the ResizeObserver overhead for relative layouts
1209
+ if (units === "pixels") {
1210
+ const resizeObserver = new ResizeObserver(() => {
1211
+ const {
1212
+ panels,
1213
+ sizes: prevSizes
1214
+ } = committedValuesRef.current;
1215
+ const nextSizes = validatePanelGroupLayout({
1216
+ groupId,
1217
+ panels,
1218
+ nextSizes: prevSizes,
1219
+ prevSizes,
1220
+ units
1221
+ });
1222
+ if (!areEqual(prevSizes, nextSizes)) {
1223
+ setSizes(nextSizes);
1224
+ }
1225
+ });
1226
+ resizeObserver.observe(getPanelGroup(groupId));
1227
+ return () => {
1228
+ resizeObserver.disconnect();
1229
+ };
1230
+ }
1231
+ }, [groupId, units]);
1232
+ const getPanelSize = useCallback((id, unitsFromParams) => {
1233
+ const {
1234
+ panels,
1235
+ units: unitsFromProps
1236
+ } = committedValuesRef.current;
1237
+ const panelsArray = panelsMapToSortedArray(panels);
1238
+ const index = panelsArray.findIndex(panel => panel.current.id === id);
1239
+ const size = sizes[index];
1240
+ const units = unitsFromParams ?? unitsFromProps;
1241
+ if (units === "pixels") {
1242
+ const groupSizePixels = getAvailableGroupSizePixels(groupId);
1243
+ return size / 100 * groupSizePixels;
1244
+ } else {
1245
+ return size;
1246
+ }
1247
+ }, [groupId, sizes]);
1248
+ const getPanelStyle = useCallback((id, defaultSize) => {
1249
+ const {
1250
+ panels
1251
+ } = committedValuesRef.current;
1252
+
1253
+ // Before mounting, Panels will not yet have registered themselves.
1254
+ // This includes server rendering.
1255
+ // At this point the best we can do is render everything with the same size.
1256
+ if (panels.size === 0) {
1257
+ return {
1258
+ flexBasis: 0,
1259
+ flexGrow: defaultSize != null ? defaultSize : undefined,
1260
+ flexShrink: 1,
1261
+ // Without this, Panel sizes may be unintentionally overridden by their content.
1262
+ overflow: "hidden"
1263
+ };
1264
+ }
1265
+ const flexGrow = getFlexGrow(panels, id, sizes);
1266
+ return {
1267
+ flexBasis: 0,
1268
+ flexGrow,
1269
+ flexShrink: 1,
1270
+ // Without this, Panel sizes may be unintentionally overridden by their content.
1271
+ overflow: "hidden",
1272
+ // Disable pointer events inside of a panel during resize.
1273
+ // This avoid edge cases like nested iframes.
1274
+ pointerEvents: disablePointerEventsDuringResize && activeHandleId !== null ? "none" : undefined
1275
+ };
1276
+ }, [activeHandleId, disablePointerEventsDuringResize, sizes]);
1277
+ const registerPanel = useCallback((id, panelRef) => {
1278
+ const {
1279
+ units
1280
+ } = committedValuesRef.current;
1281
+ validatePanelProps(units, panelRef);
1282
+ setPanels(prevPanels => {
1283
+ if (prevPanels.has(id)) {
1284
+ return prevPanels;
1285
+ }
1286
+ const nextPanels = new Map(prevPanels);
1287
+ nextPanels.set(id, panelRef);
1288
+ return nextPanels;
1289
+ });
1290
+ }, []);
1291
+ const registerResizeHandle = useCallback(handleId => {
1292
+ const resizeHandler = event => {
1293
+ event.preventDefault();
1294
+ const {
1295
+ direction,
1296
+ panels,
1297
+ sizes: prevSizes
1298
+ } = committedValuesRef.current;
1299
+ const panelsArray = panelsMapToSortedArray(panels);
1300
+ const [idBefore, idAfter] = getResizeHandlePanelIds(groupId, handleId, panelsArray);
1301
+ if (idBefore == null || idAfter == null) {
1302
+ return;
1303
+ }
1304
+ let movement = getMovement(event, groupId, handleId, panelsArray, direction, prevSizes, initialDragStateRef.current);
1305
+ if (movement === 0) {
1306
+ return;
1307
+ }
1308
+ const groupElement = getPanelGroup(groupId);
1309
+ const rect = groupElement.getBoundingClientRect();
1310
+ const isHorizontal = direction === "horizontal";
1311
+
1312
+ // Support RTL layouts
1313
+ if (document.dir === "rtl" && isHorizontal) {
1314
+ movement = -movement;
1315
+ }
1316
+ const size = isHorizontal ? rect.width : rect.height;
1317
+ const delta = movement / size * 100;
1318
+
1319
+ // If a validateLayout method has been provided
1320
+ // it's important to use it before updating the mouse cursor
1321
+ const nextSizes = adjustByDelta(event, committedValuesRef.current, idBefore, idAfter, delta, prevSizes, panelSizeBeforeCollapse.current, initialDragStateRef.current);
1322
+ const sizesChanged = !areEqual(prevSizes, nextSizes);
1323
+
1324
+ // Don't update cursor for resizes triggered by keyboard interactions.
1325
+ if (isMouseEvent(event) || isTouchEvent(event)) {
1326
+ // Watch for multiple subsequent deltas; this might occur for tiny cursor movements.
1327
+ // In this case, Panel sizes might not change–
1328
+ // but updating cursor in this scenario would cause a flicker.
1329
+ if (prevDeltaRef.current != delta) {
1330
+ if (!sizesChanged) {
1331
+ // If the pointer has moved too far to resize the panel any further,
1332
+ // update the cursor style for a visual clue.
1333
+ // This mimics VS Code behavior.
1334
+
1335
+ if (isHorizontal) {
1336
+ setGlobalCursorStyle(movement < 0 ? "horizontal-min" : "horizontal-max");
1337
+ } else {
1338
+ setGlobalCursorStyle(movement < 0 ? "vertical-min" : "vertical-max");
1339
+ }
1340
+ } else {
1341
+ // Reset the cursor style to the the normal resize cursor.
1342
+ setGlobalCursorStyle(isHorizontal ? "horizontal" : "vertical");
1343
+ }
1344
+ }
1345
+ }
1346
+ if (sizesChanged) {
1347
+ const panelIdToLastNotifiedSizeMap = panelIdToLastNotifiedSizeMapRef.current;
1348
+
1349
+ // It's okay to bypass in this case because we already validated above
1350
+ setSizes(nextSizes);
1351
+
1352
+ // If resize change handlers have been declared, this is the time to call them.
1353
+ // Trigger user callbacks after updating state, so that user code can override the sizes.
1354
+ callPanelCallbacks(panelsArray, nextSizes, panelIdToLastNotifiedSizeMap);
1355
+ }
1356
+ prevDeltaRef.current = delta;
1357
+ };
1358
+ return resizeHandler;
1359
+ }, [groupId]);
1360
+ const unregisterPanel = useCallback(id => {
1361
+ setPanels(prevPanels => {
1362
+ if (!prevPanels.has(id)) {
1363
+ return prevPanels;
1364
+ }
1365
+ const nextPanels = new Map(prevPanels);
1366
+ nextPanels.delete(id);
1367
+ return nextPanels;
1368
+ });
1369
+ }, []);
1370
+ const collapsePanel = useCallback(id => {
1371
+ const {
1372
+ panels,
1373
+ sizes: prevSizes
1374
+ } = committedValuesRef.current;
1375
+ const panel = panels.get(id);
1376
+ if (panel == null) {
1377
+ return;
1378
+ }
1379
+ const {
1380
+ collapsedSize,
1381
+ collapsible
1382
+ } = panel.current;
1383
+ if (!collapsible) {
1384
+ return;
1385
+ }
1386
+ const panelsArray = panelsMapToSortedArray(panels);
1387
+ const index = panelsArray.indexOf(panel);
1388
+ if (index < 0) {
1389
+ return;
1390
+ }
1391
+ const currentSize = prevSizes[index];
1392
+ if (currentSize === collapsedSize) {
1393
+ // Panel is already collapsed.
1394
+ return;
1395
+ }
1396
+ panelSizeBeforeCollapse.current.set(id, currentSize);
1397
+ const [idBefore, idAfter] = getBeforeAndAfterIds(id, panelsArray);
1398
+ if (idBefore == null || idAfter == null) {
1399
+ return;
1400
+ }
1401
+ const isLastPanel = index === panelsArray.length - 1;
1402
+ const delta = isLastPanel ? currentSize : collapsedSize - currentSize;
1403
+ const nextSizes = adjustByDelta(null, committedValuesRef.current, idBefore, idAfter, delta, prevSizes, panelSizeBeforeCollapse.current, null);
1404
+ if (prevSizes !== nextSizes) {
1405
+ const panelIdToLastNotifiedSizeMap = panelIdToLastNotifiedSizeMapRef.current;
1406
+ setSizes(nextSizes);
1407
+
1408
+ // If resize change handlers have been declared, this is the time to call them.
1409
+ // Trigger user callbacks after updating state, so that user code can override the sizes.
1410
+ callPanelCallbacks(panelsArray, nextSizes, panelIdToLastNotifiedSizeMap);
1411
+ }
1412
+ }, []);
1413
+ const expandPanel = useCallback(id => {
1414
+ const {
1415
+ panels,
1416
+ sizes: prevSizes
1417
+ } = committedValuesRef.current;
1418
+ const panel = panels.get(id);
1419
+ if (panel == null) {
1420
+ return;
1421
+ }
1422
+ const {
1423
+ collapsedSize,
1424
+ minSize
1425
+ } = panel.current;
1426
+ const sizeBeforeCollapse = panelSizeBeforeCollapse.current.get(id) || minSize;
1427
+ if (!sizeBeforeCollapse) {
1428
+ return;
1429
+ }
1430
+ const panelsArray = panelsMapToSortedArray(panels);
1431
+ const index = panelsArray.indexOf(panel);
1432
+ if (index < 0) {
1433
+ return;
1434
+ }
1435
+ const currentSize = prevSizes[index];
1436
+ if (currentSize !== collapsedSize) {
1437
+ // Panel is already expanded.
1438
+ return;
1439
+ }
1440
+ const [idBefore, idAfter] = getBeforeAndAfterIds(id, panelsArray);
1441
+ if (idBefore == null || idAfter == null) {
1442
+ return;
1443
+ }
1444
+ const isLastPanel = index === panelsArray.length - 1;
1445
+ const delta = isLastPanel ? collapsedSize - sizeBeforeCollapse : sizeBeforeCollapse;
1446
+ const nextSizes = adjustByDelta(null, committedValuesRef.current, idBefore, idAfter, delta, prevSizes, panelSizeBeforeCollapse.current, null);
1447
+ if (prevSizes !== nextSizes) {
1448
+ const panelIdToLastNotifiedSizeMap = panelIdToLastNotifiedSizeMapRef.current;
1449
+ setSizes(nextSizes);
1450
+
1451
+ // If resize change handlers have been declared, this is the time to call them.
1452
+ // Trigger user callbacks after updating state, so that user code can override the sizes.
1453
+ callPanelCallbacks(panelsArray, nextSizes, panelIdToLastNotifiedSizeMap);
1454
+ }
1455
+ }, []);
1456
+ const resizePanel = useCallback((id, nextSize, unitsFromParams) => {
1457
+ const {
1458
+ id: groupId,
1459
+ panels,
1460
+ sizes: prevSizes,
1461
+ units
1462
+ } = committedValuesRef.current;
1463
+ if ((unitsFromParams || units) === "pixels") {
1464
+ const groupSizePixels = getAvailableGroupSizePixels(groupId);
1465
+ nextSize = nextSize / groupSizePixels * 100;
1466
+ }
1467
+ const panel = panels.get(id);
1468
+ if (panel == null) {
1469
+ return;
1470
+ }
1471
+ let {
1472
+ collapsedSize,
1473
+ collapsible,
1474
+ maxSize,
1475
+ minSize
1476
+ } = panel.current;
1477
+ if (units === "pixels") {
1478
+ const groupSizePixels = getAvailableGroupSizePixels(groupId);
1479
+ minSize = minSize / groupSizePixels * 100;
1480
+ if (maxSize != null) {
1481
+ maxSize = maxSize / groupSizePixels * 100;
1482
+ }
1483
+ }
1484
+ const panelsArray = panelsMapToSortedArray(panels);
1485
+ const index = panelsArray.indexOf(panel);
1486
+ if (index < 0) {
1487
+ return;
1488
+ }
1489
+ const currentSize = prevSizes[index];
1490
+ if (currentSize === nextSize) {
1491
+ return;
1492
+ }
1493
+ if (collapsible && nextSize === collapsedSize) ; else {
1494
+ nextSize = Math.min(maxSize != null ? maxSize : 100, Math.max(minSize, nextSize));
1495
+ }
1496
+ const [idBefore, idAfter] = getBeforeAndAfterIds(id, panelsArray);
1497
+ if (idBefore == null || idAfter == null) {
1498
+ return;
1499
+ }
1500
+ const isLastPanel = index === panelsArray.length - 1;
1501
+ const delta = isLastPanel ? currentSize - nextSize : nextSize - currentSize;
1502
+ const nextSizes = adjustByDelta(null, committedValuesRef.current, idBefore, idAfter, delta, prevSizes, panelSizeBeforeCollapse.current, null);
1503
+ if (prevSizes !== nextSizes) {
1504
+ const panelIdToLastNotifiedSizeMap = panelIdToLastNotifiedSizeMapRef.current;
1505
+ setSizes(nextSizes);
1506
+
1507
+ // If resize change handlers have been declared, this is the time to call them.
1508
+ // Trigger user callbacks after updating state, so that user code can override the sizes.
1509
+ callPanelCallbacks(panelsArray, nextSizes, panelIdToLastNotifiedSizeMap);
1510
+ }
1511
+ }, []);
1512
+ const context = useMemo(() => ({
1513
+ activeHandleId,
1514
+ collapsePanel,
1515
+ direction,
1516
+ expandPanel,
1517
+ getPanelSize,
1518
+ getPanelStyle,
1519
+ groupId,
1520
+ registerPanel,
1521
+ registerResizeHandle,
1522
+ resizePanel,
1523
+ startDragging: (id, event) => {
1524
+ setActiveHandleId(id);
1525
+ if (isMouseEvent(event) || isTouchEvent(event)) {
1526
+ const handleElement = getResizeHandle(id);
1527
+ initialDragStateRef.current = {
1528
+ dragHandleRect: handleElement.getBoundingClientRect(),
1529
+ dragOffset: getDragOffset(event, id, direction),
1530
+ sizes: committedValuesRef.current.sizes
1531
+ };
1532
+ }
1533
+ },
1534
+ stopDragging: () => {
1535
+ resetGlobalCursorStyle();
1536
+ setActiveHandleId(null);
1537
+ initialDragStateRef.current = null;
1538
+ },
1539
+ units,
1540
+ unregisterPanel
1541
+ }), [activeHandleId, collapsePanel, direction, expandPanel, getPanelSize, getPanelStyle, groupId, registerPanel, registerResizeHandle, resizePanel, units, unregisterPanel]);
1542
+ const style = {
1543
+ display: "flex",
1544
+ flexDirection: direction === "horizontal" ? "row" : "column",
1545
+ height: "100%",
1546
+ overflow: "hidden",
1547
+ width: "100%"
1548
+ };
1549
+ return createElement(PanelGroupContext.Provider, {
1550
+ children: createElement(Type, {
1551
+ children,
1552
+ className: classNameFromProps,
1553
+ "data-panel-group": "",
1554
+ "data-panel-group-direction": direction,
1555
+ "data-panel-group-id": groupId,
1556
+ "data-panel-group-units": units,
1557
+ style: {
1558
+ ...style,
1559
+ ...styleFromProps
1560
+ }
1561
+ }),
1562
+ value: context
1563
+ });
1564
+ }
1565
+ const PanelGroup = forwardRef((props, ref) => createElement(PanelGroupWithForwardedRef, {
1566
+ ...props,
1567
+ forwardedRef: ref
1568
+ }));
1569
+ PanelGroupWithForwardedRef.displayName = "PanelGroup";
1570
+ PanelGroup.displayName = "forwardRef(PanelGroup)";
1571
+
1572
+ function PanelResizeHandle({
1573
+ children = null,
1574
+ className: classNameFromProps = "",
1575
+ disabled = false,
1576
+ id: idFromProps = null,
1577
+ onDragging,
1578
+ style: styleFromProps = {},
1579
+ tagName: Type = "div"
1580
+ }) {
1581
+ const divElementRef = useRef(null);
1582
+
1583
+ // Use a ref to guard against users passing inline props
1584
+ const callbacksRef = useRef({
1585
+ onDragging
1586
+ });
1587
+ useEffect(() => {
1588
+ callbacksRef.current.onDragging = onDragging;
1589
+ });
1590
+ const panelGroupContext = useContext(PanelGroupContext);
1591
+ if (panelGroupContext === null) {
1592
+ throw Error(`PanelResizeHandle components must be rendered within a PanelGroup container`);
1593
+ }
1594
+ const {
1595
+ activeHandleId,
1596
+ direction,
1597
+ groupId,
1598
+ registerResizeHandle,
1599
+ startDragging,
1600
+ stopDragging
1601
+ } = panelGroupContext;
1602
+ const resizeHandleId = useUniqueId(idFromProps);
1603
+ const isDragging = activeHandleId === resizeHandleId;
1604
+ const [isFocused, setIsFocused] = useState(false);
1605
+ const [resizeHandler, setResizeHandler] = useState(null);
1606
+ const stopDraggingAndBlur = useCallback(() => {
1607
+ // Clicking on the drag handle shouldn't leave it focused;
1608
+ // That would cause the PanelGroup to think it was still active.
1609
+ const div = divElementRef.current;
1610
+ div.blur();
1611
+ stopDragging();
1612
+ const {
1613
+ onDragging
1614
+ } = callbacksRef.current;
1615
+ if (onDragging) {
1616
+ onDragging(false);
1617
+ }
1618
+ }, [stopDragging]);
1619
+ useEffect(() => {
1620
+ if (disabled) {
1621
+ setResizeHandler(null);
1622
+ } else {
1623
+ const resizeHandler = registerResizeHandle(resizeHandleId);
1624
+ setResizeHandler(() => resizeHandler);
1625
+ }
1626
+ }, [disabled, resizeHandleId, registerResizeHandle]);
1627
+ useEffect(() => {
1628
+ if (disabled || resizeHandler == null || !isDragging) {
1629
+ return;
1630
+ }
1631
+ const onMove = event => {
1632
+ resizeHandler(event);
1633
+ };
1634
+ const onMouseLeave = event => {
1635
+ resizeHandler(event);
1636
+ };
1637
+ const divElement = divElementRef.current;
1638
+ const targetDocument = divElement.ownerDocument;
1639
+ targetDocument.body.addEventListener("contextmenu", stopDraggingAndBlur);
1640
+ targetDocument.body.addEventListener("mousemove", onMove);
1641
+ targetDocument.body.addEventListener("touchmove", onMove);
1642
+ targetDocument.body.addEventListener("mouseleave", onMouseLeave);
1643
+ window.addEventListener("mouseup", stopDraggingAndBlur);
1644
+ window.addEventListener("touchend", stopDraggingAndBlur);
1645
+ return () => {
1646
+ targetDocument.body.removeEventListener("contextmenu", stopDraggingAndBlur);
1647
+ targetDocument.body.removeEventListener("mousemove", onMove);
1648
+ targetDocument.body.removeEventListener("touchmove", onMove);
1649
+ targetDocument.body.removeEventListener("mouseleave", onMouseLeave);
1650
+ window.removeEventListener("mouseup", stopDraggingAndBlur);
1651
+ window.removeEventListener("touchend", stopDraggingAndBlur);
1652
+ };
1653
+ }, [direction, disabled, isDragging, resizeHandler, stopDraggingAndBlur]);
1654
+ useWindowSplitterResizeHandlerBehavior({
1655
+ disabled,
1656
+ handleId: resizeHandleId,
1657
+ resizeHandler
1658
+ });
1659
+ const style = {
1660
+ cursor: getCursorStyle(direction),
1661
+ touchAction: "none",
1662
+ userSelect: "none"
1663
+ };
1664
+ return createElement(Type, {
1665
+ children,
1666
+ className: classNameFromProps,
1667
+ "data-resize-handle-active": isDragging ? "pointer" : isFocused ? "keyboard" : undefined,
1668
+ "data-panel-group-direction": direction,
1669
+ "data-panel-group-id": groupId,
1670
+ "data-panel-resize-handle-enabled": !disabled,
1671
+ "data-panel-resize-handle-id": resizeHandleId,
1672
+ onBlur: () => setIsFocused(false),
1673
+ onFocus: () => setIsFocused(true),
1674
+ onMouseDown: event => {
1675
+ startDragging(resizeHandleId, event.nativeEvent);
1676
+ const {
1677
+ onDragging
1678
+ } = callbacksRef.current;
1679
+ if (onDragging) {
1680
+ onDragging(true);
1681
+ }
1682
+ },
1683
+ onMouseUp: stopDraggingAndBlur,
1684
+ onTouchCancel: stopDraggingAndBlur,
1685
+ onTouchEnd: stopDraggingAndBlur,
1686
+ onTouchStart: event => {
1687
+ startDragging(resizeHandleId, event.nativeEvent);
1688
+ const {
1689
+ onDragging
1690
+ } = callbacksRef.current;
1691
+ if (onDragging) {
1692
+ onDragging(true);
1693
+ }
1694
+ },
1695
+ ref: divElementRef,
1696
+ role: "separator",
1697
+ style: {
1698
+ ...style,
1699
+ ...styleFromProps
1700
+ },
1701
+ tabIndex: 0
1702
+ });
1703
+ }
1704
+ PanelResizeHandle.displayName = "PanelResizeHandle";
1705
+
1706
+ exports.Panel = Panel;
1707
+ exports.PanelGroup = PanelGroup;
1708
+ exports.PanelResizeHandle = PanelResizeHandle;
1709
+ exports.getAvailableGroupSizePixels = getAvailableGroupSizePixels;