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