Debian Codegraph @

node/@patternfly/react-core/src/components/Drawer/DrawerPanelContent.tsx

raw
1 import { Fragment, useCallback, useContext, useEffect, useRef, useState } from 'react';
2 import styles from '@patternfly/react-styles/css/components/Drawer/drawer';
3 import { css } from '@patternfly/react-styles';
4 import { DrawerColorVariant, DrawerContext } from './Drawer';
5 import { formatBreakpointMods, getLanguageDirection } from '../../helpers/util';
6 import { useSSRSafeId } from '../../helpers';
7 import { FocusTrap } from '../../helpers/FocusTrap/FocusTrap';
8 import cssPanelMdFlexBasis from '@patternfly/react-tokens/dist/esm/c_drawer__panel_md_FlexBasis';
9 import cssPanelMdFlexBasisMin from '@patternfly/react-tokens/dist/esm/c_drawer__panel_md_FlexBasis_min';
10 import cssPanelMdFlexBasisMax from '@patternfly/react-tokens/dist/esm/c_drawer__panel_md_FlexBasis_max';
11
12 export interface DrawerPanelFocusTrapObject {
13 /** Enables a focus trap on the drawer panel content. This will also automatically
14 * handle focus management when the panel expands and when it collapses. Do not pass
15 * this prop if the isStatic prop on the drawer component is true.
16 */
17 enabled?: boolean;
18 /** The element to focus when the drawer panel content expands. By default the
19 * first focusable element will receive focus. If there are no focusable elements, the
20 * panel itself will receive focus.
21 */
22 elementToFocusOnExpand?: HTMLElement | SVGElement | string;
23 /** One or more id's to use for the drawer panel content's accessible label. */
24 'aria-labelledby'?: string;
25 }
26
27 export interface DrawerPanelContentProps extends Omit<React.HTMLProps<HTMLDivElement>, 'onResize'> {
28 /** Additional classes added to the drawer. */
29 className?: string;
30 /** ID of the drawer panel */
31 id?: string;
32 /** Content to be rendered in the drawer panel. */
33 children?: React.ReactNode;
34 /** Flag indicating that the drawer panel should not have a border. */
35 hasNoBorder?: boolean;
36 /** Flag indicating that the drawer panel should be resizable. */
37 isResizable?: boolean;
38 /** @beta Flag indicating that the drawer panel should disable glass styles. This prop is intended to work with isPill drawers. */
39 hasNoGlass?: boolean;
40 /** @beta Flag indicating that the drawer panel should use glass styles when in glass theme */
41 isGlass?: boolean;
42 /** @beta Flag indicating that the drawer panel should use plain styles. This only applies when the drawer is static or inline. */
43 isPlain?: boolean;
44 /** @beta Flag indicating that plain styles should be disabled when glass styles are used. This only applies when the drawer is static or inline. */
45 isNoPlainOnGlass?: boolean;
46 /** Callback for resize end. */
47 onResize?: (event: MouseEvent | TouchEvent | React.KeyboardEvent, width: number, id: string) => void;
48 /** The minimum size of a drawer. */
49 minSize?: string;
50 /** The starting size of a drawer. */
51 defaultSize?: string;
52 /** The maximum size of a drawer. */
53 maxSize?: string;
54 /** The increment amount for keyboard drawer resizing. */
55 increment?: number;
56 /** Aria label for the resizable drawer splitter. */
57 resizeAriaLabel?: string;
58 /** Width for drawer panel at various breakpoints. Overridden by resizable drawer minSize and defaultSize. */
59 widths?: {
60 default?: 'width_25' | 'width_33' | 'width_50' | 'width_66' | 'width_75' | 'width_100';
61 lg?: 'width_25' | 'width_33' | 'width_50' | 'width_66' | 'width_75' | 'width_100';
62 xl?: 'width_25' | 'width_33' | 'width_50' | 'width_66' | 'width_75' | 'width_100';
63 '2xl'?: 'width_25' | 'width_33' | 'width_50' | 'width_66' | 'width_75' | 'width_100';
64 };
65 /**
66 * Color variant of the background of the drawer panel.
67 * The `no-background`is deprecated; use the `isPlain` prop instead.
68 */
69 colorVariant?: DrawerColorVariant | 'no-background' | 'default' | 'secondary';
70 /** Adds and customizes a focus trap on the drawer panel content. */
71 focusTrap?: DrawerPanelFocusTrapObject;
72 }
73 let isResizing: boolean = null;
74 let newSize: number = 0;
75
76 export const DrawerPanelContent: React.FunctionComponent<DrawerPanelContentProps> = ({
77 className,
78 id,
79 children,
80 hasNoBorder = false,
81 isResizable = false,
82 hasNoGlass = false,
83 isGlass = false,
84 isPlain = false,
85 isNoPlainOnGlass = false,
86 onResize,
87 minSize,
88 defaultSize,
89 maxSize,
90 increment = 5,
91 resizeAriaLabel = 'Resize',
92 widths,
93 colorVariant = DrawerColorVariant.default,
94 focusTrap,
95 style,
96 ...props
97 }: DrawerPanelContentProps) => {
98 const panelId = useSSRSafeId('pf-drawer-panel-');
99 const panel = useRef<HTMLDivElement>(undefined);
100 const splitterRef = useRef<HTMLDivElement>(undefined);
101 const [separatorValue, setSeparatorValue] = useState(0);
102 const { position, isExpanded, isStatic, onExpand, drawerRef, drawerContentRef, isInline } = useContext(DrawerContext);
103 const hidden = isStatic ? false : !isExpanded;
104 const [isExpandedInternal, setIsExpandedInternal] = useState(!hidden);
105 const [isFocusTrapActive, setIsFocusTrapActive] = useState(false);
106 const [shouldCollapseSpace, setShouldCollapseSpace] = useState(hidden);
107 const previouslyFocusedElement = useRef(null);
108 const resizeState = useRef({
109 initialPointerPos: 0,
110 initialPanelSize: 0,
111 currWidth: 0
112 });
113
114 if (isStatic && focusTrap?.enabled) {
115 // eslint-disable-next-line no-console
116 console.warn(
117 `DrawerPanelContent: The focusTrap.enabled prop cannot be true if the Drawer's isStatic prop is true. This will cause a permanent focus trap.`
118 );
119 }
120
121 useEffect(() => {
122 if (!isStatic && isExpanded) {
123 setIsExpandedInternal(isExpanded);
124 setShouldCollapseSpace(false);
125 }
126 }, [isStatic, isExpanded]);
127
128 const calcValueNow = () => {
129 let splitterPos;
130 let drawerSize;
131 const isRTL = getLanguageDirection(panel.current) === 'rtl';
132
133 if (isInline && (position === 'end' || position === 'right')) {
134 if (isRTL) {
135 splitterPos = panel.current.getBoundingClientRect().left - splitterRef.current.getBoundingClientRect().right;
136 drawerSize = drawerRef.current.getBoundingClientRect().left - drawerRef.current.getBoundingClientRect().right;
137 } else {
138 splitterPos = panel.current.getBoundingClientRect().right - splitterRef.current.getBoundingClientRect().left;
139 drawerSize = drawerRef.current.getBoundingClientRect().right - drawerRef.current.getBoundingClientRect().left;
140 }
141 } else if (isInline && (position === 'start' || position === 'left')) {
142 if (isRTL) {
143 splitterPos = splitterRef.current.getBoundingClientRect().left - panel.current.getBoundingClientRect().right;
144 drawerSize = drawerRef.current.getBoundingClientRect().left - drawerRef.current.getBoundingClientRect().right;
145 } else {
146 splitterPos = splitterRef.current.getBoundingClientRect().right - panel.current.getBoundingClientRect().left;
147 drawerSize = drawerRef.current.getBoundingClientRect().right - drawerRef.current.getBoundingClientRect().left;
148 }
149 } else if (position === 'end' || position === 'right') {
150 if (isRTL) {
151 splitterPos =
152 drawerContentRef.current.getBoundingClientRect().left - splitterRef.current.getBoundingClientRect().right;
153 drawerSize =
154 drawerContentRef.current.getBoundingClientRect().left -
155 drawerContentRef.current.getBoundingClientRect().right;
156 } else {
157 splitterPos =
158 drawerContentRef.current.getBoundingClientRect().right - splitterRef.current.getBoundingClientRect().left;
159 drawerSize =
160 drawerContentRef.current.getBoundingClientRect().right -
161 drawerContentRef.current.getBoundingClientRect().left;
162 }
163 } else if (position === 'start' || position === 'left') {
164 if (isRTL) {
165 splitterPos =
166 splitterRef.current.getBoundingClientRect().left - drawerContentRef.current.getBoundingClientRect().right;
167 drawerSize =
168 drawerContentRef.current.getBoundingClientRect().left -
169 drawerContentRef.current.getBoundingClientRect().right;
170 } else {
171 splitterPos =
172 splitterRef.current.getBoundingClientRect().right - drawerContentRef.current.getBoundingClientRect().left;
173 drawerSize =
174 drawerContentRef.current.getBoundingClientRect().right -
175 drawerContentRef.current.getBoundingClientRect().left;
176 }
177 } else if (position === 'bottom') {
178 splitterPos =
179 drawerContentRef.current.getBoundingClientRect().bottom - splitterRef.current.getBoundingClientRect().top;
180 drawerSize =
181 drawerContentRef.current.getBoundingClientRect().bottom - drawerContentRef.current.getBoundingClientRect().top;
182 }
183
184 const newSplitterPos = (splitterPos / drawerSize) * 100;
185 return Math.round((newSplitterPos + Number.EPSILON) * 100) / 100;
186 };
187
188 const setInitialResizeState = (controlPosition: number) => {
189 const panelRect = panel.current.getBoundingClientRect();
190 const initialPanelSize = position === 'bottom' ? panelRect.height : panelRect.width;
191
192 resizeState.current = {
193 initialPointerPos: controlPosition,
194 initialPanelSize,
195 currWidth: initialPanelSize
196 };
197 };
198
199 const handleTouchStart = (e: React.TouchEvent) => {
200 e.stopPropagation();
201 setInitialResizeState(position === 'bottom' ? e.touches[0].clientY : e.touches[0].clientX);
202 document.addEventListener('touchmove', callbackTouchMove, { passive: false });
203 document.addEventListener('touchend', callbackTouchEnd);
204 isResizing = true;
205 };
206
207 const handleMousedown = (e: React.MouseEvent) => {
208 e.stopPropagation();
209 e.preventDefault();
210 setInitialResizeState(position === 'bottom' ? e.clientY : e.clientX);
211 document.addEventListener('mousemove', callbackMouseMove);
212 document.addEventListener('mouseup', callbackMouseUp);
213 drawerRef.current.classList.add(css(styles.modifiers.resizing));
214 isResizing = true;
215 };
216
217 const handleMouseMove = (e: MouseEvent) => {
218 const mousePos = position === 'bottom' ? e.clientY : e.clientX;
219 handleControlMove(e, mousePos);
220 };
221
222 const handleTouchMove = (e: TouchEvent) => {
223 e.preventDefault();
224 e.stopImmediatePropagation();
225 const touchPos = position === 'bottom' ? e.touches[0].clientY : e.touches[0].clientX;
226 handleControlMove(e, touchPos);
227 };
228
229 const handleControlMove = (e: MouseEvent | TouchEvent, controlPosition: number) => {
230 const isRTL = getLanguageDirection(panel.current) === 'rtl';
231
232 e.stopPropagation();
233 if (!isResizing) {
234 return;
235 }
236
237 const { initialPointerPos, initialPanelSize } = resizeState.current;
238 const delta = controlPosition - initialPointerPos;
239 let newSize = 0;
240 if (position === 'end' || position === 'right') {
241 newSize = isRTL ? initialPanelSize + delta : initialPanelSize - delta;
242 } else if (position === 'start' || position === 'left') {
243 newSize = isRTL ? initialPanelSize - delta : initialPanelSize + delta;
244 } else {
245 newSize = initialPanelSize - delta;
246 }
247
248 if (position === 'bottom') {
249 panel.current.style.overflowAnchor = 'none';
250 }
251 panel.current.style.setProperty(cssPanelMdFlexBasis.name, newSize + 'px');
252 resizeState.current.currWidth = newSize;
253 setSeparatorValue(calcValueNow());
254 };
255
256 const handleMouseup = (e: MouseEvent) => {
257 if (!isResizing) {
258 return;
259 }
260 drawerRef.current.classList.remove(css(styles.modifiers.resizing));
261 isResizing = false;
262 onResize && onResize(e, resizeState.current.currWidth, id);
263 document.removeEventListener('mousemove', callbackMouseMove);
264 document.removeEventListener('mouseup', callbackMouseUp);
265 };
266
267 const handleTouchEnd = (e: TouchEvent) => {
268 e.stopPropagation();
269 if (!isResizing) {
270 return;
271 }
272 isResizing = false;
273 onResize && onResize(e, resizeState.current.currWidth, id);
274 document.removeEventListener('touchmove', callbackTouchMove);
275 document.removeEventListener('touchend', callbackTouchEnd);
276 };
277
278 const callbackMouseMove = useCallback(handleMouseMove, []);
279 const callbackTouchEnd = useCallback(handleTouchEnd, []);
280 const callbackTouchMove = useCallback(handleTouchMove, []);
281 const callbackMouseUp = useCallback(handleMouseup, []);
282
283 const handleKeys = (e: React.KeyboardEvent) => {
284 const isRTL = getLanguageDirection(panel.current) === 'rtl';
285
286 const key = e.key;
287 if (
288 key !== 'Escape' &&
289 key !== 'Enter' &&
290 key !== 'ArrowUp' &&
291 key !== 'ArrowDown' &&
292 key !== 'ArrowLeft' &&
293 key !== 'ArrowRight'
294 ) {
295 if (isResizing) {
296 e.preventDefault();
297 }
298 return;
299 }
300 e.preventDefault();
301
302 if (key === 'Escape' || key === 'Enter') {
303 onResize && onResize(e, resizeState.current.currWidth, id);
304 }
305 const panelRect = panel.current.getBoundingClientRect();
306 newSize = position === 'bottom' ? panelRect.height : panelRect.width;
307 let delta = 0;
308 if (key === 'ArrowRight') {
309 if (isRTL) {
310 delta = position === 'left' || position === 'start' ? -increment : increment;
311 } else {
312 delta = position === 'left' || position === 'start' ? increment : -increment;
313 }
314 } else if (key === 'ArrowLeft') {
315 if (isRTL) {
316 delta = position === 'left' || position === 'start' ? increment : -increment;
317 } else {
318 delta = position === 'left' || position === 'start' ? -increment : increment;
319 }
320 } else if (key === 'ArrowUp') {
321 delta = increment;
322 } else if (key === 'ArrowDown') {
323 delta = -increment;
324 }
325 newSize = newSize + delta;
326 if (position === 'bottom') {
327 panel.current.style.overflowAnchor = 'none';
328 }
329 panel.current.style.setProperty(cssPanelMdFlexBasis.name, newSize + 'px');
330 resizeState.current.currWidth = newSize;
331 setSeparatorValue(calcValueNow());
332 };
333 const boundaryCssVars: any = {};
334 if (defaultSize) {
335 boundaryCssVars[cssPanelMdFlexBasis.name] = defaultSize;
336 }
337 if (minSize) {
338 boundaryCssVars[cssPanelMdFlexBasisMin.name] = minSize;
339 }
340 if (maxSize) {
341 boundaryCssVars[cssPanelMdFlexBasisMax.name] = maxSize;
342 }
343
344 const isValidFocusTrap = focusTrap?.enabled && !isStatic;
345 const Component = isValidFocusTrap ? FocusTrap : 'div';
346
347 const focusTrapProps = {
348 tabIndex: -1,
349 'aria-modal': true,
350 role: 'dialog',
351 active: isFocusTrapActive,
352 'aria-labelledby': focusTrap?.['aria-labelledby'] || id || panelId,
353 focusTrapOptions: {
354 fallbackFocus: () => panel.current,
355 onActivate: () => {
356 if (previouslyFocusedElement.current !== document.activeElement) {
357 previouslyFocusedElement.current = document.activeElement;
358 }
359 },
360 onDeactivate: () => {
361 previouslyFocusedElement.current &&
362 previouslyFocusedElement.current.focus &&
363 previouslyFocusedElement.current.focus();
364 },
365 clickOutsideDeactivates: true,
366 returnFocusOnDeactivate: false,
367 // FocusTrap's initialFocus can accept false as a value to prevent initial focus.
368 // We want to prevent this in case false is ever passed in.
369 initialFocus: focusTrap?.elementToFocusOnExpand || undefined,
370 escapeDeactivates: false
371 }
372 };
373
374 return (
375 <Component
376 {...(isValidFocusTrap && focusTrapProps)}
377 id={id || panelId}
378 className={css(
379 styles.drawerPanel,
380 isResizable && styles.modifiers.resizable,
381 hasNoGlass && 'pf-m-no-glass',
382 isGlass && styles.modifiers.glass,
383 isPlain && styles.modifiers.plain,
384 isNoPlainOnGlass && styles.modifiers.noPlainOnGlass,
385 hasNoBorder && styles.modifiers.noBorder,
386 formatBreakpointMods(widths, styles),
387 colorVariant === DrawerColorVariant.noBackground && styles.modifiers.noBackground,
388 colorVariant === DrawerColorVariant.secondary && styles.modifiers.secondary,
389 className
390 )}
391 onTransitionEnd={(ev) => {
392 if ((ev.target as HTMLElement) === panel.current) {
393 if (!hidden && ev.nativeEvent.propertyName === 'transform') {
394 onExpand(ev);
395 }
396 setIsExpandedInternal(!hidden);
397 // We also need to collapse the space when the panel is hidden to prevent automation from scrolling to it
398 if (hidden && ev.nativeEvent.propertyName === 'transform') {
399 setShouldCollapseSpace(true);
400 }
401 if (isValidFocusTrap && ev.nativeEvent.propertyName === 'transform') {
402 setIsFocusTrapActive((prevIsFocusTrapActive) => !prevIsFocusTrapActive);
403 }
404 }
405 }}
406 hidden={hidden}
407 style={{
408 ...((defaultSize || minSize || maxSize) && boundaryCssVars),
409 ...style
410 }}
411 {...(shouldCollapseSpace && { inert: '' })}
412 {...props}
413 ref={panel}
414 >
415 {isExpandedInternal && (
416 <Fragment>
417 {isResizable && (
418 <Fragment>
419 <div
420 className={css(styles.drawerSplitter, position !== 'bottom' && styles.modifiers.vertical)}
421 role="separator"
422 tabIndex={0}
423 aria-orientation={position === 'bottom' ? 'horizontal' : 'vertical'}
424 aria-label={resizeAriaLabel}
425 aria-valuenow={separatorValue}
426 aria-valuemin={0}
427 aria-valuemax={100}
428 aria-controls={id || panelId}
429 onMouseDown={handleMousedown}
430 onKeyDown={handleKeys}
431 onTouchStart={handleTouchStart}
432 ref={splitterRef}
433 >
434 <div className={css(styles.drawerSplitterHandle)} aria-hidden></div>
435 </div>
436 <div className={css(styles.drawerPanelMain)}>{children}</div>
437 </Fragment>
438 )}
439 {!isResizable && children}
440 </Fragment>
441 )}
442 </Component>
443 );
444 };
445 DrawerPanelContent.displayName = 'DrawerPanelContent';