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