-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathLayout.tsx
More file actions
413 lines (370 loc) · 11.5 KB
/
Layout.tsx
File metadata and controls
413 lines (370 loc) · 11.5 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
import { useResizeObserver } from '@react-aria/utils';
import {
CSSProperties,
FocusEvent,
ForwardedRef,
forwardRef,
HTMLAttributes,
KeyboardEvent,
ReactNode,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import {
BaseProps,
BlockStyleProps,
ColorStyleProps,
extractStyles,
filterBaseProps,
FlowStyleProps,
INNER_STYLES,
mergeStyles,
OUTER_STYLES,
OuterStyleProps,
Styles,
tasty,
} from '../../../tasty';
import { isDevEnv } from '../../../tasty/utils/is-dev-env';
import { useCombinedRefs } from '../../../utils/react';
import { Alert } from '../Alert';
import {
LayoutProvider,
useLayoutActionsContext,
useLayoutRefsContext,
useLayoutStateContext,
} from './LayoutContext';
const LayoutElement = tasty({
as: 'div',
qa: 'Layout',
styles: {
position: 'relative',
display: 'block',
overflow: {
'': 'visible',
'do-not-overflow': 'hidden',
},
flexGrow: 1,
placeSelf: 'stretch',
height: {
'': 'auto',
'auto-height': 'fixed 100%',
collapsed: '6x',
},
'$content-padding': '1x',
// Auto-border size for sub-components (set when layout is vertical)
'$layout-border-size': {
'': '0',
vertical: '1bw',
},
Inner: {
// .base-class[data-hover] > [data-element="Inner"] { ...}
// Direct child selector required for nested layouts
$: '>',
container: 'layout / inline-size',
position: 'absolute',
inset: '$inset-top $inset-right $inset-bottom $inset-left',
display: 'flex',
flow: 'column',
placeContent: 'stretch',
placeItems: 'stretch',
// Disable transition during panel resize for snappy feedback
// Also disable transition when not ready to prevent initial animation
// Only animate when has-transition is enabled (and not dragging/not-ready)
transition: {
'': 'none',
'has-transition': 'inset $transition ease-out',
'dragging | not-ready': 'none',
},
},
},
});
export interface CubeLayoutProps
extends BaseProps,
OuterStyleProps,
BlockStyleProps,
ColorStyleProps,
FlowStyleProps {
/** Switch to grid display mode */
isGrid?: boolean;
/** Grid template columns (when isGrid=true) */
columns?: Styles['gridColumns'];
/** Grid template rows (when isGrid=true) */
rows?: Styles['gridRows'];
/** Grid template shorthand */
template?: Styles['gridTemplate'];
/** Padding for content areas (Layout.Content components). Default: '1x' */
contentPadding?: Styles['padding'];
/** Enable transition animation for Inner content when panels open/close */
hasTransition?: boolean;
/** Minimum size reserved for the content area between panels. Default: 320 */
minContentSize?: number;
/** Styles for wrapper and Inner sub-element */
styles?: Styles;
children?: ReactNode;
/** Ref for the inner content element */
innerRef?: ForwardedRef<HTMLDivElement>;
/** Props to spread on the Inner sub-element */
innerProps?: HTMLAttributes<HTMLDivElement>;
/**
* @internal Force show dev warning even in production (for storybook testing)
*/
_forceShowDevWarning?: boolean;
/**
* When true, applies overflow: hidden to the root element.
* By default, overflow is visible.
*/
doNotOverflow?: boolean;
}
function LayoutInner(
props: CubeLayoutProps & { forwardedRef?: ForwardedRef<HTMLDivElement> },
) {
const layoutActions = useLayoutActionsContext();
const layoutState = useLayoutStateContext();
const layoutRefs = useLayoutRefsContext();
const localRef = useRef<HTMLDivElement>(null);
const [isAutoHeight, setIsAutoHeight] = useState(false);
const [isCollapsed, setIsCollapsed] = useState(false);
const {
isGrid,
columns,
rows,
template,
contentPadding,
hasTransition = false,
minContentSize,
styles,
children,
style,
forwardedRef,
innerRef: innerRefProp,
innerProps,
_forceShowDevWarning,
doNotOverflow,
...otherProps
} = props;
const combinedInnerRef = useCombinedRefs(innerRefProp);
const updateContainerSize = layoutActions?.updateContainerSize;
useResizeObserver({
ref: localRef,
onResize: useCallback(() => {
if (localRef.current) {
updateContainerSize?.(
localRef.current.offsetWidth,
localRef.current.offsetHeight,
);
}
}, [updateContainerSize]),
});
// Extract outer wrapper styles and inner content styles
const outerStyles = extractStyles(otherProps, OUTER_STYLES);
const innerStyles = extractStyles(otherProps, INNER_STYLES);
// Calculate if the layout flow is vertical (for auto-border feature)
// Default flow is 'column' (vertical), only horizontal when explicitly set to 'row'
const isVertical = useMemo(() => {
const flowFromProp = innerStyles?.flow;
const flowFromStyles = (styles?.Inner as Record<string, unknown>)?.flow;
const flowValue = flowFromProp ?? flowFromStyles;
return typeof flowValue !== 'string' || !flowValue.startsWith('row');
}, [innerStyles?.flow, styles?.Inner]);
// Merge styles using the same pattern as LayoutPane
const finalStyles = useMemo(() => {
// Handle grid mode and grid properties
const gridStyles: Styles = {};
if (isGrid) {
gridStyles.display = 'grid';
}
if (columns) {
gridStyles.gridColumns = columns;
}
if (rows) {
gridStyles.gridRows = rows;
}
if (template) {
gridStyles.gridTemplate = template;
}
return mergeStyles(
outerStyles,
contentPadding != null ? { '$content-padding': contentPadding } : null,
styles,
{ Inner: mergeStyles(innerStyles, gridStyles, styles?.Inner as Styles) },
);
}, [
outerStyles,
innerStyles,
contentPadding,
styles,
isGrid,
columns,
rows,
template,
]);
// Calculate inset values from panel sizes
const panelSizes = layoutState?.panelSizes ?? {
left: 0,
top: 0,
right: 0,
bottom: 0,
};
const isDragging = layoutState?.isDragging ?? false;
const isReady = layoutState?.isReady ?? true;
const markReady = layoutActions?.markReady;
const dismissOverlayPanels = layoutActions?.dismissOverlayPanels;
const hasOverlayPanels = layoutState?.hasOverlayPanels ?? false;
// Mark layout as ready after first paint
// Using useEffect + requestAnimationFrame ensures:
// 1. Panels register in useLayoutEffect → correct insets before first paint
// 2. First paint with not-ready=true (transition disabled)
// 3. After paint completes → enables transitions for subsequent changes
useEffect(() => {
const frameId = requestAnimationFrame(() => {
markReady?.();
});
return () => cancelAnimationFrame(frameId);
}, [markReady]);
// Auto-height detection: if layout collapses to 0 height after initialization,
// automatically set height to 100% to prevent invisible layout
useEffect(() => {
if (isReady && localRef.current && localRef.current.offsetHeight === 0) {
setIsAutoHeight(true);
}
}, [isReady]);
// Second check: if still 0 height after auto-height was applied,
// show collapsed state with warning
useEffect(() => {
if (isAutoHeight && localRef.current) {
// Use requestAnimationFrame to check after styles have been applied
const frameId = requestAnimationFrame(() => {
if (localRef.current && localRef.current.offsetHeight === 0) {
setIsCollapsed(true);
}
});
return () => cancelAnimationFrame(frameId);
}
}, [isAutoHeight]);
const insetStyle = useMemo(() => {
const baseStyle: Record<string, string> = {
'--inset-top': `${panelSizes.top}px`,
'--inset-right': `${panelSizes.right}px`,
'--inset-bottom': `${panelSizes.bottom}px`,
'--inset-left': `${panelSizes.left}px`,
};
if (style) {
return { ...baseStyle, ...style } as CSSProperties;
}
return baseStyle as CSSProperties;
}, [panelSizes, style]);
const mods = useMemo(
() => ({
dragging: isDragging,
'not-ready': !isReady,
'has-transition': hasTransition,
'auto-height': isAutoHeight && !isCollapsed,
collapsed: isCollapsed,
vertical: isVertical,
'do-not-overflow': doNotOverflow,
}),
[
isDragging,
isReady,
hasTransition,
isAutoHeight,
isCollapsed,
isVertical,
doNotOverflow,
],
);
// Combine local ref with forwarded ref
const setRefs = (element: HTMLDivElement | null) => {
localRef.current = element;
if (typeof forwardedRef === 'function') {
forwardedRef(element);
} else if (forwardedRef) {
forwardedRef.current = element;
}
};
// Show dev warning when collapsed and in dev mode (or forced for stories)
const showDevWarning = isCollapsed && (_forceShowDevWarning || isDevEnv());
// Handle focus entering the Inner element - dismiss overlay panels
const handleInnerFocus = useCallback(
(e: FocusEvent<HTMLDivElement>) => {
// Only dismiss if there are overlay panels
if (!hasOverlayPanels) return;
// Check if focus is coming from outside the Inner element
const inner = e.currentTarget;
const relatedTarget = e.relatedTarget as Node | null;
// If relatedTarget is null or not inside the Inner element,
// focus is entering from outside - dismiss overlay panels
if (!relatedTarget || !inner.contains(relatedTarget)) {
dismissOverlayPanels?.();
}
},
[hasOverlayPanels, dismissOverlayPanels],
);
// Handle Escape key anywhere in the Layout - dismiss overlay panels
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
if (hasOverlayPanels && e.key === 'Escape') {
e.preventDefault();
e.stopPropagation();
dismissOverlayPanels?.();
}
},
[hasOverlayPanels, dismissOverlayPanels],
);
return (
<LayoutElement
ref={setRefs}
{...filterBaseProps(otherProps, { eventProps: true })}
mods={mods}
styles={finalStyles}
style={insetStyle}
onKeyDown={hasOverlayPanels ? handleKeyDown : undefined}
>
{showDevWarning ? (
<Alert theme="danger">
<b>UIKit:</b> <b><Layout/></b> has collapsed to <b>0</b> height.
Ensure the parent container has a defined height or use the{' '}
<b>height</b> prop on <b><Layout/></b>.
</Alert>
) : (
<>
{/* All children go inside the Inner element - panels will portal themselves out */}
<div
ref={combinedInnerRef}
data-element="Inner"
onFocus={handleInnerFocus}
{...innerProps}
>
{children}
</div>
{/* Container for panels to portal into - rendered after Inner so panels paint on top via DOM order */}
<div
ref={layoutRefs?.setPanelContainer}
data-element="PanelContainer"
/>
</>
)}
</LayoutElement>
);
}
/**
* Layout component provides a vertical flex layout with overflow-safe content.
* Uses a two-element architecture (wrapper + content) to ensure content never overflows.
*/
function Layout(props: CubeLayoutProps, ref: ForwardedRef<HTMLDivElement>) {
const { hasTransition, minContentSize } = props;
return (
<LayoutProvider
hasTransition={hasTransition}
minContentSize={minContentSize}
>
<LayoutInner {...props} forwardedRef={ref} />
</LayoutProvider>
);
}
const _Layout = forwardRef(Layout);
_Layout.displayName = 'Layout';
export { _Layout as Layout };