-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathLayoutPanel.tsx
More file actions
871 lines (789 loc) · 25.1 KB
/
LayoutPanel.tsx
File metadata and controls
871 lines (789 loc) · 25.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
import {
BaseProps,
CONTAINER_STYLES,
ContainerStyleProps,
filterBaseProps,
mergeStyles,
Styles,
tasty,
} from '@tenphi/tasty';
import {
ForwardedRef,
forwardRef,
HTMLAttributes,
ReactNode,
RefCallback,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useFocusRing, useHover, useMove } from 'react-aria';
import { createPortal } from 'react-dom';
import { useDebouncedValue } from '../../../_internal/hooks';
import {
mergeProps,
useCombinedRefs,
useLocalStorage,
} from '../../../utils/react';
import { extractStyles } from '../../../utils/styles';
import { DisplayTransition } from '../../helpers/DisplayTransition/DisplayTransition';
import { Dialog } from '../../overlays/Dialog';
import {
CubeDialogContainerProps,
DialogContainer,
} from '../../overlays/Dialog/DialogContainer';
import {
LayoutContextReset,
LayoutPanelContext,
Side,
useLayoutActionsContext,
useLayoutRefsContext,
useLayoutStateContext,
} from './LayoutContext';
import { clampSize, getOppositeSide, resolveCssSize } from './utils';
// Resize handler dimensions
const HANDLER_WIDTH = 9;
// How far from panel edge to position handler's inner edge (centers the 3px track on the edge)
const HANDLER_OFFSET = 4;
// Extra inset added for resizable panels (to accommodate handler grab area)
const RESIZABLE_INSET_OFFSET = 2;
const PanelElement = tasty({
as: 'div',
qa: 'LayoutPanel',
styles: {
container: 'panel / inline-size',
position: 'absolute',
display: 'flex',
flow: 'column',
overflow: 'hidden',
boxSizing: 'border-box',
'$content-padding': '1x',
// Auto-border size for sub-components (panels are always vertical)
'$layout-border-size': '1bw',
// Position based on side prop
top: {
'': 0,
'side=bottom': 'initial',
},
right: {
'': 0,
'side=left': 'initial',
},
bottom: {
'': 0,
'side=top': 'initial',
},
left: {
'': 0,
'side=right': 'initial',
},
// Size handling with CSS-level min/max clamping
width: {
'': '$min-size $panel-size $max-size',
'side=top | side=bottom': '100%',
},
height: {
'': '100%',
'side=top | side=bottom': '$min-size $panel-size $max-size',
},
// Visual styling
border: {
'': false,
'side=left': 'right',
'side=right': 'left',
'side=top': 'bottom',
'side=bottom': 'top',
},
fill: '#white',
// Transition styles - offscreen mod controls slide animation
transform: {
'': 'translateX(0) translateY(0)',
'offscreen & side=left': 'translateX(-100%)',
'offscreen & side=right': 'translateX(100%)',
'offscreen & side=top': 'translateY(-100%)',
'offscreen & side=bottom': 'translateY(100%)',
},
transition: {
'': 'none',
'has-transition': 'transform $transition ease-out',
},
},
});
// Handler is positioned as sibling to panel (in Fragment), relative to Layout
const ResizeHandlerElement = tasty({
qa: 'PanelResizeHandler',
styles: {
position: 'absolute',
// Handler size
width: {
'': '100%',
horizontal: `${HANDLER_WIDTH}px`,
'disabled & horizontal': '1bw',
},
height: {
'': `${HANDLER_WIDTH}px`,
horizontal: '100%',
'disabled & !horizontal': '1bw',
},
// Position handler with direct offset (no centering needed)
top: {
'': 0,
'side=top': `calc($panel-size - ${HANDLER_OFFSET}px)`,
'side=bottom': 'initial',
},
bottom: {
'': 0,
'side=bottom': `calc($panel-size - ${HANDLER_OFFSET}px)`,
'side=top': 'initial',
},
left: {
'': 0,
'side=left': `calc($panel-size - ${HANDLER_OFFSET}px)`,
'side=right': 'initial',
},
right: {
'': 0,
'side=right': `calc($panel-size - ${HANDLER_OFFSET}px)`,
'side=left': 'initial',
},
// Offscreen transforms only (no centering needed with direct offset positioning)
transform: {
'': 'translateX(0)',
'offscreen & side=left': `translateX(calc(-1 * $panel-size - ${HANDLER_WIDTH - HANDLER_OFFSET}px))`,
'offscreen & side=right': `translateX(calc($panel-size + ${HANDLER_WIDTH - HANDLER_OFFSET}px))`,
'offscreen & side=top': `translateY(calc(-1 * $panel-size - ${HANDLER_WIDTH - HANDLER_OFFSET}px))`,
'offscreen & side=bottom': `translateY(calc($panel-size + ${HANDLER_WIDTH - HANDLER_OFFSET}px))`,
},
cursor: {
'': 'row-resize',
horizontal: 'col-resize',
disabled: 'not-allowed',
},
touchAction: {
'': 'none',
disabled: 'auto',
},
padding: 0,
outline: 0,
boxSizing: 'border-box',
// Transition must match panel for synchronized animation
transition: {
'': 'theme',
'has-transition': 'transform $transition ease-out, theme',
},
Track: {
width: {
'': 'initial',
horizontal: '3px',
'disabled & horizontal': '1px',
},
height: {
'': '3px',
horizontal: 'initial',
'disabled & !horizontal': '1px',
},
position: 'absolute',
inset: {
'': '3px 0',
horizontal: '0 3px',
disabled: '0 0',
},
fill: {
'': '#border',
'(hovered | drag | focused) & !disabled': '#purple-03',
},
border: 0,
transition: 'theme',
outline: {
'': '1bw #primary-text.0',
'drag | focused': '1bw #primary-text',
},
outlineOffset: 1,
},
Drag: {
display: 'grid',
gap: '2bw',
border: 0,
flow: {
'': 'row',
horizontal: 'column',
},
gridColumns: {
'': '3px 3px 3px 3px 3px',
horizontal: 'auto',
},
gridRows: {
'': 'auto',
horizontal: '3px 3px 3px 3px 3px',
},
width: {
'': 'auto',
horizontal: '1px',
},
height: {
'': '1px',
horizontal: 'auto',
},
inset: {
'': '4px 50% auto auto',
horizontal: '50% 4px auto auto',
},
transform: {
'': 'translate(-50%, 0)',
horizontal: 'translate(0, -50%)',
},
position: 'absolute',
transition: 'theme',
},
DragPart: {
radius: true,
fill: {
'': '#dark-03',
'hovered | drag | focused': '#primary-text',
disabled: '#dark-04',
},
},
},
});
// Overlay backdrop for overlay mode - covers the content area behind the panel
const OverlayBackdrop = tasty({
qa: 'PanelOverlay',
styles: {
position: 'absolute',
inset: 0,
// fill: '#white.2',
backdropFilter: 'invert(.15)',
cursor: 'pointer',
opacity: {
'': 0,
visible: 1,
},
pointerEvents: {
'': 'none',
visible: 'auto',
},
transition: 'opacity .15s ease-out',
},
});
interface ResizeHandlerProps {
side: Side;
isDisabled?: boolean;
mods?: Record<string, boolean>;
moveProps: ReturnType<typeof useMove>['moveProps'];
style?: Record<string, string | number | null | undefined>;
onDoubleClick?: () => void;
}
function ResizeHandler(props: ResizeHandlerProps) {
const { side, isDisabled, mods, moveProps, style, onDoubleClick } = props;
const { hoverProps, isHovered } = useHover({});
const { focusProps, isFocusVisible } = useFocusRing();
const isHorizontal = side === 'left' || side === 'right';
const localIsHovered = useDebouncedValue(isHovered, 150);
return (
<ResizeHandlerElement
{...mergeProps(hoverProps, focusProps, moveProps, {
mods: {
hovered: localIsHovered,
horizontal: isHorizontal,
disabled: isDisabled,
focused: isFocusVisible,
side,
...mods,
},
style,
tabIndex: isDisabled ? undefined : 0,
role: 'separator',
'aria-orientation': isHorizontal ? 'vertical' : 'horizontal',
'aria-label': `Resize ${side} panel`,
onDoubleClick: isDisabled ? undefined : onDoubleClick,
})}
>
<div data-element="Track" />
{!isDisabled && (
<div data-element="Drag">
<div data-element="DragPart" />
<div data-element="DragPart" />
<div data-element="DragPart" />
<div data-element="DragPart" />
<div data-element="DragPart" />
</div>
)}
</ResizeHandlerElement>
);
}
/** Panel rendering mode */
export type LayoutPanelMode = 'default' | 'sticky' | 'overlay' | 'dialog';
export interface CubeLayoutPanelProps extends BaseProps, ContainerStyleProps {
/** Side of the layout where panel is positioned */
side: Side;
/**
* Panel rendering mode:
* - `default`: Standard panel that pushes content aside
* - `sticky`: Panel floats over content without pushing it
* - `overlay`: Panel with dismissable backdrop overlay
* - `dialog`: Panel renders as a modal dialog
*/
mode?: LayoutPanelMode;
/** Panel size (width for left/right, height for top/bottom) - controlled */
size?: number | string;
/** Default panel size for uncontrolled state */
defaultSize?: number | string;
/** Minimum panel size */
minSize?: number | string;
/** Maximum panel size */
maxSize?: number | string;
/** Enable resize functionality */
isResizable?: boolean;
/** Size change callback */
onSizeChange?: (size: number) => void;
/** Controlled open state */
isOpen?: boolean;
/** Default open state */
defaultIsOpen?: boolean;
/** Open state change callback */
onOpenChange?: (isOpen: boolean) => void;
/** Enable slide transition on open/close */
hasTransition?: boolean;
/**
* Whether the panel can be dismissed by clicking the overlay (overlay mode) or pressing Escape.
* Only applies to `overlay` and `dialog` modes. Default: true
*/
isDismissable?: boolean;
/** Styles for the overlay backdrop in overlay mode */
overlayStyles?: Styles;
/**
* @deprecated Use `mode="dialog"` instead. Switch to dialog mode (renders panel inside Dialog)
*/
isDialog?: boolean;
/** Controlled dialog open state (used with mode="dialog") */
isDialogOpen?: boolean;
/** Default dialog open state */
defaultIsDialogOpen?: boolean;
/** Dialog open state change callback */
onDialogOpenChange?: (isOpen: boolean) => void;
/** Props passed to Dialog component when in dialog mode */
dialogProps?: Omit<
CubeDialogContainerProps,
'isDismissable' | 'onDismiss' | 'isOpen'
>;
/** Padding for content areas inside the panel. Default: '1x' */
contentPadding?: Styles['padding'];
/** localStorage key for persisting panel size. When provided, size is stored and restored across instances. */
sizeStorageKey?: string;
/** Styles for the panel */
styles?: Styles;
children?: ReactNode;
}
function LayoutPanel(
props: CubeLayoutPanelProps,
ref: ForwardedRef<HTMLDivElement>,
) {
const layoutActions = useLayoutActionsContext();
const layoutState = useLayoutStateContext();
const layoutRefs = useLayoutRefsContext();
if (!layoutActions || !layoutState || !layoutRefs) {
throw new Error(
'Layout.Panel must be used within a Layout component. ' +
'Ensure your panel is rendered inside a <Layout> parent.',
);
}
const {
side = 'left',
mode: modeProp,
size: providedSize,
defaultSize = 280,
minSize = 200,
maxSize,
isResizable = false,
onSizeChange,
isOpen: providedIsOpen,
defaultIsOpen = true,
onOpenChange,
hasTransition: hasTransitionProp,
isDismissable = true,
overlayStyles,
// Deprecated prop - use mode="dialog" instead
isDialog = false,
isDialogOpen: providedIsDialogOpen,
defaultIsDialogOpen = false,
onDialogOpenChange,
dialogProps,
contentPadding,
sizeStorageKey,
children,
styles,
mods,
...otherProps
} = props;
// Resolve mode from prop or deprecated isDialog
const mode: LayoutPanelMode = modeProp ?? (isDialog ? 'dialog' : 'default');
const isDialogMode = mode === 'dialog';
const isOverlayMode = mode === 'overlay';
const isStickyMode = mode === 'sticky';
// Use prop value if provided, otherwise fall back to context value
const hasTransition = hasTransitionProp ?? layoutActions.hasTransition;
const combinedRef = useCombinedRefs(ref);
const prevProvidedSizeRef = useRef(providedSize);
const isHorizontal = side === 'left' || side === 'right';
// Natural boundary computation
const { containerWidth, containerHeight } = layoutState;
const { minContentSize } = layoutActions;
const containerDimension = isHorizontal ? containerWidth : containerHeight;
const oppositeSide = getOppositeSide(side);
const oppositePanelSize = layoutState.panelSizes[oppositeSide];
const ownInsetOffset = isResizable ? RESIZABLE_INSET_OFFSET : 0;
const naturalMax = useMemo(
() =>
containerDimension > 0
? Math.max(
0,
containerDimension -
oppositePanelSize -
minContentSize -
ownInsetOffset,
)
: Infinity,
[containerDimension, oppositePanelSize, minContentSize, ownInsetOffset],
);
// Panel open state
const [internalIsOpen, setInternalIsOpen] = useState(defaultIsOpen);
const isOpen = providedIsOpen ?? internalIsOpen;
// Dialog open state
const [internalIsDialogOpen, setInternalIsDialogOpen] =
useState(defaultIsDialogOpen);
const dialogOpen = providedIsDialogOpen ?? internalIsDialogOpen;
// Persistent size storage
const [storedSize, setStoredSize] = useLocalStorage<number | null>(
sizeStorageKey ?? null,
null,
);
// Resize state
const [isDragging, setIsDragging] = useState(false);
const [size, setSize] = useState<number>(() => {
const initialSize =
typeof providedSize === 'number'
? providedSize
: storedSize != null
? storedSize
: typeof defaultSize === 'number'
? defaultSize
: 280;
return clampSize(initialSize, minSize, maxSize);
});
const extractedStyles = extractStyles(otherProps, CONTAINER_STYLES);
// Merge styles with contentPadding support
const finalStyles = useMemo(
() =>
mergeStyles(
styles,
contentPadding != null ? { '$content-padding': contentPadding } : null,
extractedStyles,
),
[extractedStyles, contentPadding, styles],
);
// Resolve user's maxSize to pixels for JS-level clamping.
// String values (e.g. "50%") can only be resolved once we know the container size.
const resolvedMax = useMemo(() => {
if (typeof maxSize === 'number') return maxSize;
if (typeof maxSize === 'string' && containerDimension > 0) {
return resolveCssSize(maxSize, containerDimension);
}
return undefined;
}, [maxSize, containerDimension]);
// Effective max combines user's maxSize with natural boundary
const effectiveMax = useMemo(() => {
const values: number[] = [];
if (resolvedMax != null) values.push(resolvedMax);
if (Number.isFinite(naturalMax)) values.push(naturalMax);
return values.length > 0 ? Math.min(...values) : undefined;
}, [resolvedMax, naturalMax]);
// Clamp size to min/max constraints (including natural boundaries)
const clampValue = useCallback(
(value: number) => clampSize(value, minSize, undefined, effectiveMax),
[minSize, effectiveMax],
);
const setContextDragging = layoutActions.setDragging;
const { moveProps } = useMove({
onMoveStart() {
if (!isResizable) return;
setIsDragging(true);
setContextDragging(true);
},
onMove(e) {
if (!isResizable) return;
let delta: number;
if (e.pointerType === 'keyboard') {
// Keyboard resize: 10px per step, 50px with Shift
const step = e.shiftKey ? 50 : 10;
// For keyboard, deltaX/deltaY are direction indicators (-1, 0, 1)
const rawDelta = isHorizontal ? e.deltaX : e.deltaY;
const direction = side === 'right' || side === 'bottom' ? -1 : 1;
delta = rawDelta * step * direction;
} else {
// Pointer resize: use exact delta values
delta = isHorizontal
? e.deltaX * (side === 'right' ? -1 : 1)
: e.deltaY * (side === 'bottom' ? -1 : 1);
}
setSize((currentSize) => clampValue(currentSize + delta));
},
onMoveEnd() {
setIsDragging(false);
setContextDragging(false);
// Round to integer on release and notify parent
setSize((currentSize) => {
const finalSize = Math.round(clampValue(currentSize));
// Call onSizeChange synchronously to ensure parent state is updated
onSizeChange?.(finalSize);
// Persist to localStorage if key is provided
setStoredSize(finalSize);
return finalSize;
});
},
});
// Sync provided size with internal state (only when providedSize actually changes)
// This prevents resetting size when only isDragging changes (which would cause a flash)
useEffect(() => {
if (prevProvidedSizeRef.current !== providedSize) {
prevProvidedSizeRef.current = providedSize;
if (typeof providedSize === 'number' && !isDragging) {
setSize(clampValue(providedSize));
}
}
}, [providedSize, isDragging, clampValue]);
// Auto-shrink: re-clamp when container resizes or opposite panel changes
useEffect(() => {
if (!isDragging && containerDimension > 0) {
setSize((prev) => {
const clamped = clampValue(prev);
if (clamped !== prev) {
onSizeChange?.(Math.round(clamped));
setStoredSize(Math.round(clamped));
}
return clamped;
});
}
}, [isDragging, clampValue, containerDimension]);
// Register panel with layout context
// Include handler outside portion (minus border overlap) for proper content inset
// In sticky, overlay, and dialog modes, panel doesn't push content, so size is 0
// NOTE: We intentionally use `size` (not `clampValue(size)`) here to avoid a feedback
// loop. `clampValue` depends on the opposite panel's context size, so clamping here
// would create a period-2 oscillation through shared context. CSS --max-size handles
// visual clamping immediately; the auto-shrink effect converges `size` state.
const effectivePanelSize = isOpen && mode === 'default' ? size : 0;
const effectiveInsetSize = Math.round(
effectivePanelSize +
(isResizable && effectivePanelSize > 0 ? RESIZABLE_INSET_OFFSET : 0),
);
const { registerPanel, unregisterPanel, updatePanelSize } = layoutActions;
const { isReady } = layoutState;
// Track the last reported size to prevent unnecessary updates
const lastSizeRef = useRef<number>(effectiveInsetSize);
// Register on mount, unregister on unmount
// Using useLayoutEffect ensures registration happens before browser paint
useLayoutEffect(() => {
registerPanel(side, lastSizeRef.current);
return () => {
unregisterPanel(side);
};
}, [side, registerPanel, unregisterPanel]);
// Update size when it changes (after initial mount)
// Using useLayoutEffect ensures size updates happen before browser paint
useLayoutEffect(() => {
if (lastSizeRef.current !== effectiveInsetSize) {
lastSizeRef.current = effectiveInsetSize;
updatePanelSize(side, effectiveInsetSize);
}
}, [side, effectiveInsetSize, updatePanelSize]);
const handleOpenChange = useCallback(
(newIsOpen: boolean) => {
setInternalIsOpen(newIsOpen);
onOpenChange?.(newIsOpen);
},
[onOpenChange],
);
// Dismiss handler for overlay mode (click on overlay)
const handleDismiss = useCallback(() => {
if (isDismissable) {
handleOpenChange(false);
}
}, [isDismissable, handleOpenChange]);
// Register overlay panel with Layout context for coordinated dismissal
const { registerOverlayPanel } = layoutActions;
useEffect(() => {
// Only register if in overlay mode, open, and dismissable
if (isOverlayMode && isOpen && isDismissable) {
const unregister = registerOverlayPanel(() => handleOpenChange(false));
return unregister;
}
}, [
isOverlayMode,
isOpen,
isDismissable,
registerOverlayPanel,
handleOpenChange,
]);
const handleDialogOpenChange = useCallback(
(newIsOpen: boolean) => {
setInternalIsDialogOpen(newIsOpen);
onDialogOpenChange?.(newIsOpen);
},
[onDialogOpenChange],
);
// Panel context value for child components (like LayoutPanelHeader)
const panelContextValue = useMemo(
() => ({
onOpenChange: handleOpenChange,
isOpen,
}),
[handleOpenChange, isOpen],
);
// Dialog mode context value - uses dialog state instead of panel state
const dialogPanelContextValue = useMemo(
() => ({
onOpenChange: handleDialogOpenChange,
isOpen: dialogOpen,
}),
[handleDialogOpenChange, dialogOpen],
);
const panelMods = useMemo(
() => ({
side,
drag: isDragging,
horizontal: isHorizontal,
// Only enable transition after layout is ready to prevent initial animation
'has-transition': hasTransition && isReady,
...mods,
}),
[side, isDragging, isHorizontal, hasTransition, isReady, mods],
);
// Build --max-size CSS variable combining user maxSize and natural boundary
const maxSizeCss = useMemo(() => {
const parts: string[] = [];
if (maxSize != null) {
parts.push(typeof maxSize === 'number' ? `${maxSize}px` : maxSize);
}
if (containerDimension > 0 && Number.isFinite(naturalMax)) {
parts.push(`${naturalMax}px`);
}
if (parts.length === 0) return undefined;
return parts.length === 1 ? parts[0] : `min(${parts.join(', ')})`;
}, [maxSize, naturalMax, containerDimension]);
const panelStyle = useMemo(
() => ({
'--panel-size': `${size}px`,
'--min-size': typeof minSize === 'number' ? `${minSize}px` : minSize,
'--max-size': maxSizeCss,
}),
[size, minSize, maxSizeCss],
);
// Combine refs for panel element
const panelRefCallback = useCallback(
(node: HTMLDivElement | null, transitionRef?: RefCallback<HTMLElement>) => {
// Update the combined ref
(combinedRef as { current: HTMLDivElement | null }).current = node;
// Call transition ref if provided
transitionRef?.(node);
},
[combinedRef],
);
// Reset to default size on double-click
const handleResetSize = useCallback(() => {
const resetSize =
typeof defaultSize === 'number' ? defaultSize : parseInt(defaultSize, 10);
const clampedSize = clampValue(resetSize || 280);
setSize(clampedSize);
onSizeChange?.(clampedSize);
setStoredSize(clampedSize);
}, [defaultSize, clampValue, onSizeChange, setStoredSize]);
const renderPanelContent = (
offscreen = false,
transitionRef?: RefCallback<HTMLElement>,
) => {
const showOverlay = isOverlayMode && !offscreen;
return (
<>
{/* Overlay backdrop for overlay mode */}
{isOverlayMode && (
<OverlayBackdrop
mods={{ visible: showOverlay }}
styles={overlayStyles}
aria-hidden="true"
onClick={handleDismiss}
/>
)}
<PanelElement
ref={(node: HTMLDivElement | null) =>
panelRefCallback(node, transitionRef)
}
{...filterBaseProps(otherProps, { eventProps: true })}
mods={{ ...panelMods, offscreen }}
styles={finalStyles}
style={panelStyle}
data-side={side}
>
<LayoutPanelContext.Provider value={panelContextValue}>
<LayoutContextReset>{children}</LayoutContextReset>
</LayoutPanelContext.Provider>
</PanelElement>
{isResizable && (
<ResizeHandler
side={side}
isDisabled={!isResizable}
mods={{
drag: isDragging,
offscreen,
'has-transition': hasTransition && isReady,
}}
moveProps={moveProps}
style={panelStyle}
onDoubleClick={handleResetSize}
/>
)}
</>
);
};
// Dialog mode - uses its own portal via DialogContainer
if (isDialogMode) {
return (
<DialogContainer
isOpen={dialogOpen}
isDismissable={isDismissable}
onDismiss={() => handleDialogOpenChange(false)}
{...dialogProps}
>
<Dialog isDismissable={false}>
<LayoutPanelContext.Provider value={dialogPanelContextValue}>
<LayoutContextReset>{children}</LayoutContextReset>
</LayoutPanelContext.Provider>
</Dialog>
</DialogContainer>
);
}
// Wait for portal container to be ready before rendering
if (!layoutRefs.isPanelContainerReady) {
return null;
}
const portalContainer = layoutRefs.panelContainerRef.current!;
// Panel with transition - portal to panel container
if (hasTransition) {
return createPortal(
<DisplayTransition isShown={isOpen} animateOnMount={false}>
{({ isShown, ref: transitionRef }) =>
renderPanelContent(!isShown, transitionRef)
}
</DisplayTransition>,
portalContainer,
);
}
// Simple panel (no transition) - portal to panel container
if (!isOpen) return null;
return createPortal(renderPanelContent(false), portalContainer);
}
const _LayoutPanel = forwardRef(LayoutPanel);
_LayoutPanel.displayName = 'Layout.Panel';
export { _LayoutPanel as LayoutPanel };