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