react-resizable-panels 0.0.52 → 0.0.54

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