Debian Codegraph @

node/@patternfly/react-core/src/components/Popover/Popover.tsx

raw
1 import { ReactElement, useEffect, useRef, useState } from 'react';
2 import { KeyTypes } from '../../helpers/constants';
3 import styles from '@patternfly/react-styles/css/components/Popover/popover';
4 import { css } from '@patternfly/react-styles';
5 import { PopoverContext } from './PopoverContext';
6 import { PopoverContent } from './PopoverContent';
7 import { PopoverBody } from './PopoverBody';
8 import { PopoverHeader } from './PopoverHeader';
9 import { PopoverFooter } from './PopoverFooter';
10 import { PopoverCloseButton } from './PopoverCloseButton';
11 import { PopoverArrow } from './PopoverArrow';
12 import popoverMaxWidth from '@patternfly/react-tokens/dist/esm/c_popover_MaxWidth';
13 import popoverMinWidth from '@patternfly/react-tokens/dist/esm/c_popover_MinWidth';
14 import { FocusTrap } from '../../helpers';
15 import { Popper } from '../../helpers/Popper/Popper';
16 import { useSSRSafeId } from '../../helpers';
17
18 export enum PopoverPosition {
19 auto = 'auto',
20 top = 'top',
21 bottom = 'bottom',
22 left = 'left',
23 right = 'right',
24 topStart = 'top-start',
25 topEnd = 'top-end',
26 bottomStart = 'bottom-start',
27 bottomEnd = 'bottom-end',
28 leftStart = 'left-start',
29 leftEnd = 'left-end',
30 rightStart = 'right-start',
31 rightEnd = 'right-end'
32 }
33
34 /** The main popover component. The following properties can also be passed into another component
35 * that has a property specifically for passing in popover properties.
36 */
37
38 export interface PopoverProps {
39 /** Text announced by screen reader when alert severity variant is set to indicate
40 * severity level.
41 */
42 alertSeverityScreenReaderText?: string;
43 /** Severity variants for an alert popover. This modifies the color of the header to
44 * match the severity.
45 */
46 alertSeverityVariant?: 'custom' | 'info' | 'warning' | 'success' | 'danger';
47 /** The duration of the CSS fade transition animation. */
48 animationDuration?: number;
49 /** The element to append the popover to. Defaults to "inline". */
50 appendTo?: HTMLElement | ((ref?: HTMLElement) => HTMLElement) | 'inline';
51 /** Accessible label for the popover, required when header is not present. */
52 'aria-label'?: string;
53 /**
54 * Body content of the popover. If you want to close the popover after an action within the
55 * body content, you can use the isVisible prop for manual control, or you can provide a
56 * function which will receive a callback as an argument to hide the popover, i.e.
57 * bodyContent={hide => <Button onClick={() => hide()}>Close</Button>}
58 */
59 bodyContent: React.ReactNode | ((hide: () => void) => React.ReactNode);
60 /**
61 * The trigger reference element to which the popover is relatively placed to. If you cannot wrap
62 * the element with the Popover, you can use the triggerRef prop instead.
63 * Usage: <Popover><Button>Reference</Button></Popover>
64 */
65 children?: ReactElement<any>;
66 /**
67 * The trigger reference element to which the popover is relatively placed to. If you can wrap the
68 * element with the popover, you can use the children prop instead, or both props together.
69 * When passed along with the trigger prop, the div element that wraps the trigger will be removed.
70 * Usage: <Popover triggerRef={() => document.getElementById('reference-element')} />
71 */
72 triggerRef?: HTMLElement | (() => HTMLElement) | React.RefObject<any>;
73 /** Additional classes added to the popover. */
74 className?: string;
75 /** Accessible label for the close button. */
76 closeBtnAriaLabel?: string;
77 /** Distance of the popover to its target. Defaults to 25. */
78 distance?: number;
79 /** The element to focus when the popover becomes visible. By default the first
80 * focusable element will receive focus.
81 */
82 elementToFocus?: HTMLElement | SVGElement | string;
83 /**
84 * If true, tries to keep the popover in view by flipping it if necessary.
85 * If the position is set to 'auto', this prop is ignored.
86 */
87 enableFlip?: boolean;
88 /**
89 * The desired position to flip the popover to if the initial position is not possible.
90 * By setting this prop to 'flip' it attempts to flip the popover to the opposite side if
91 * there is no space.
92 * You can also pass an array of positions that determines the flip order. It should contain
93 * the initial position followed by alternative positions if that position is unavailable.
94 * Example: Initial position is 'top'. Button with popover is in the top right corner.
95 * 'flipBehavior' is set to ['top', 'right', 'left']. Since there is no space to the top, it
96 * checks if right is available. There's also no space to the right, so it finally shows the
97 * popover on the left.
98 */
99 flipBehavior?:
100 | 'flip'
101 | (
102 | 'top'
103 | 'bottom'
104 | 'left'
105 | 'right'
106 | 'top-start'
107 | 'top-end'
108 | 'bottom-start'
109 | 'bottom-end'
110 | 'left-start'
111 | 'left-end'
112 | 'right-start'
113 | 'right-end'
114 )[];
115 /**
116 * Footer content of the popover. If you want to close the popover after an action within the
117 * footer content, you can use the isVisible prop for manual control, or you can provide a
118 * function which will receive a callback as an argument to hide the popover, i.e.
119 * footerContent={hide => <Button onClick={() => hide()}>Close</Button>}
120 */
121 footerContent?: React.ReactNode | ((hide: () => void) => React.ReactNode);
122 /** Removes fixed-width and allows width to be defined by contents. */
123 hasAutoWidth?: boolean;
124 /** Allows content to touch edges of popover container. */
125 hasNoPadding?: boolean;
126 /** Sets the heading level to use for the popover header. Defaults to h6. */
127 headerComponent?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
128 /**
129 * Simple header content to be placed within a title. If you want to close the popover after
130 * an action within the header content, you can use the isVisible prop for manual control,
131 * or you can provide a function which will receive a callback as an argument to hide the
132 * popover, i.e. headerContent={hide => <Button onClick={() => hide()}>Close</Button>}
133 */
134 headerContent?: React.ReactNode | ((hide: () => void) => React.ReactNode);
135 /** Icon to be displayed in the popover header. **/
136 headerIcon?: React.ReactNode;
137 /** Hides the popover when a click occurs outside (only works if isVisible is not controlled
138 * by the user).
139 */
140 hideOnOutsideClick?: boolean;
141 /** Id used as part of the various popover elements (popover-${id}-header/body/footer). */
142 id?: string;
143 /**
144 * True to show the popover programmatically. Used in conjunction with the shouldClose prop.
145 * By default, the popover child element handles click events automatically. If you want to
146 * control this programmatically, the popover will not auto-close if the close button is
147 * clicked, the escape key is used, or if a click occurs outside the popover. Instead, the
148 * consumer is responsible for closing the popover themselves by adding a callback listener
149 * for the shouldClose prop.
150 */
151 isVisible?: boolean;
152 /** Maximum width of the popover (default 18.75rem). */
153 maxWidth?: string;
154 /** Minimum width of the popover (default 6.25rem). */
155 minWidth?: string;
156 /**
157 * Lifecycle function invoked when the popover has fully transitioned out.
158 */
159 onHidden?: () => void;
160 /**
161 * Lifecycle function invoked when the popover begins to transition out.
162 */
163 onHide?: (event: MouseEvent | KeyboardEvent) => void;
164 /**
165 * Lifecycle function invoked when the popover has been mounted to the DOM.
166 */
167 onMount?: () => void;
168 /**
169 * Lifecycle function invoked when the popover begins to transition in.
170 */
171 onShow?: (event: MouseEvent | KeyboardEvent) => void;
172 /**
173 * Lifecycle function invoked when the popover has fully transitioned in.
174 */
175 onShown?: () => void;
176 /**
177 * Popover position. Note: With the enableFlip property set to true, it will change the
178 * position if there is not enough space for the starting position. The behavior of where it
179 * flips to can be controlled through the flipBehavior property.
180 */
181 position?:
182 | PopoverPosition
183 | 'auto'
184 | 'top'
185 | 'bottom'
186 | 'left'
187 | 'right'
188 | 'top-start'
189 | 'top-end'
190 | 'bottom-start'
191 | 'bottom-end'
192 | 'left-start'
193 | 'left-end'
194 | 'right-start'
195 | 'right-end';
196 /**
197 * Callback function that is only invoked when isVisible is also controlled. Called when the
198 * popover close button is clicked, the enter key was used on it, or the escape key is used.
199 */
200 shouldClose?: (event: MouseEvent | KeyboardEvent, hideFunction?: () => void) => void;
201 /**
202 * Callback function that is only invoked when isVisible is also controlled. Called when the
203 * enter key is used on the focused trigger.
204 */
205 shouldOpen?: (event: MouseEvent | KeyboardEvent, showFunction?: () => void) => void;
206 /** Flag indicating whether the close button should be shown. */
207 showClose?: boolean;
208 /** @deprecated Sets an interaction to open popover, defaults to "click" */
209 triggerAction?: 'click' | 'hover';
210 /** Whether to trap focus in the popover. When using a triggerAction of "hover", this will be set to false
211 * by default and must remain false.
212 */
213 withFocusTrap?: boolean;
214 /** The z-index of the popover. */
215 zIndex?: number;
216 }
217
218 const alertStyle = {
219 custom: styles.modifiers.custom,
220 info: styles.modifiers.info,
221 success: styles.modifiers.success,
222 warning: styles.modifiers.warning,
223 danger: styles.modifiers.danger
224 };
225
226 export const Popover: React.FunctionComponent<PopoverProps> = ({
227 children,
228 position = 'top',
229 enableFlip = true,
230 className = '',
231 isVisible = null as boolean,
232 shouldClose = (): void => null,
233 shouldOpen = (): void => null,
234 'aria-label': ariaLabel = '',
235 bodyContent,
236 headerContent = null,
237 headerComponent = 'h6',
238 headerIcon = null,
239 alertSeverityVariant,
240 alertSeverityScreenReaderText,
241 footerContent = null,
242 appendTo = () => document.body,
243 hideOnOutsideClick = true,
244 onHide = (): void => null,
245 onHidden = (): void => null,
246 onShow = (): void => null,
247 onShown = (): void => null,
248 onMount = (): void => null,
249 zIndex = 9999,
250 triggerAction = 'click',
251 minWidth = popoverMinWidth && popoverMinWidth.value,
252 maxWidth = popoverMaxWidth && popoverMaxWidth.value,
253 closeBtnAriaLabel = 'Close',
254 showClose = true,
255 distance = 25,
256 flipBehavior = [
257 'top',
258 'bottom',
259 'left',
260 'right',
261 'top-start',
262 'top-end',
263 'bottom-start',
264 'bottom-end',
265 'left-start',
266 'left-end',
267 'right-start',
268 'right-end'
269 ],
270 animationDuration = 300,
271 id,
272 withFocusTrap: propWithFocusTrap = triggerAction === 'hover' ? false : undefined,
273 triggerRef,
274 hasNoPadding = false,
275 hasAutoWidth = false,
276 elementToFocus,
277 ...rest
278 }: PopoverProps) => {
279 // could make this a prop in the future (true | false | 'toggle')
280 // const hideOnClick = true;
281 const generatedId = useSSRSafeId();
282 const uniqueId = id || generatedId;
283 const triggerManually = isVisible !== null;
284 const [visible, setVisible] = useState(false);
285 const [focusTrapActive, setFocusTrapActive] = useState(Boolean(propWithFocusTrap));
286 const popoverRef = useRef(null);
287
288 useEffect(() => {
289 onMount();
290 }, []);
291 useEffect(() => {
292 if (triggerManually) {
293 if (isVisible) {
294 show(undefined, true);
295 } else {
296 hide();
297 }
298 }
299 }, [isVisible, triggerManually]);
300 const show = (event?: MouseEvent | KeyboardEvent, withFocusTrap?: boolean) => {
301 event && onShow(event);
302 setVisible(true);
303 propWithFocusTrap !== false && withFocusTrap && setFocusTrapActive(true);
304 };
305
306 const hide = (event?: MouseEvent | KeyboardEvent) => {
307 event && onHide(event);
308 setVisible(false);
309 };
310
311 const positionModifiers = {
312 top: styles.modifiers.top,
313 bottom: styles.modifiers.bottom,
314 left: styles.modifiers.left,
315 right: styles.modifiers.right,
316 'top-start': styles.modifiers.topLeft,
317 'top-end': styles.modifiers.topRight,
318 'bottom-start': styles.modifiers.bottomLeft,
319 'bottom-end': styles.modifiers.bottomRight,
320 'left-start': styles.modifiers.leftTop,
321 'left-end': styles.modifiers.leftBottom,
322 'right-start': styles.modifiers.rightTop,
323 'right-end': styles.modifiers.rightBottom
324 };
325 const hasCustomMinWidth = minWidth !== popoverMinWidth.value;
326 const hasCustomMaxWidth = maxWidth !== popoverMaxWidth.value;
327 const onDocumentKeyDown = (event: KeyboardEvent) => {
328 if (event.key === KeyTypes.Escape && visible) {
329 if (triggerManually) {
330 shouldClose(event, hide);
331 } else {
332 hide(event);
333 }
334 }
335 };
336 const onDocumentClick = (event: MouseEvent, triggerElement: HTMLElement, popperElement: HTMLElement) => {
337 if (hideOnOutsideClick && visible) {
338 const isFromChild = popperElement && popperElement.contains(event.target as Node);
339 const isFromTrigger = triggerElement && triggerElement.contains(event.target as Node);
340 if (isFromChild || isFromTrigger) {
341 // if clicked within the popper or on the trigger, ignore this event
342 return;
343 }
344 if (triggerManually) {
345 shouldClose(event, hide);
346 } else {
347 hide(event);
348 }
349 }
350 };
351 const onTriggerClick = (event: MouseEvent) => {
352 if (triggerManually) {
353 if (visible) {
354 shouldClose(event, hide);
355 } else {
356 shouldOpen(event, show);
357 }
358 } else {
359 if (visible) {
360 hide(event);
361 } else {
362 show(event, true);
363 }
364 }
365 };
366
367 const onContentMouseDown = () => {
368 if (focusTrapActive) {
369 setFocusTrapActive(false);
370 }
371 };
372
373 const onMouseEnter = (event: MouseEvent) => {
374 if (triggerManually) {
375 shouldOpen(event as MouseEvent, show);
376 } else {
377 show(event as MouseEvent, false);
378 }
379 };
380
381 const onMouseLeave = (event: MouseEvent) => {
382 if (triggerManually) {
383 shouldClose(event as MouseEvent, hide);
384 } else {
385 hide(event);
386 }
387 };
388
389 const onFocus = (event: FocusEvent) => {
390 if (triggerManually) {
391 shouldOpen(event as MouseEvent | KeyboardEvent, show);
392 } else {
393 show(event as MouseEvent | KeyboardEvent, false);
394 }
395 };
396
397 const onBlur = (event: FocusEvent) => {
398 if (triggerManually) {
399 shouldClose(event as MouseEvent | KeyboardEvent, hide);
400 } else {
401 hide(event as MouseEvent | KeyboardEvent);
402 }
403 };
404
405 const closePopover = (event: MouseEvent) => {
406 event.stopPropagation();
407 if (triggerManually) {
408 shouldClose(event, hide);
409 } else {
410 hide(event);
411 }
412 };
413
414 const content = (
415 <FocusTrap
416 ref={popoverRef}
417 active={focusTrapActive}
418 focusTrapOptions={{
419 returnFocusOnDeactivate: propWithFocusTrap !== false,
420 clickOutsideDeactivates: true,
421 // FocusTrap's initialFocus can accept false as a value to prevent initial focus.
422 // We want to prevent this in case false is ever passed in.
423 initialFocus: elementToFocus || undefined,
424 checkCanFocusTrap: (containers) =>
425 new Promise((resolve) => {
426 const interval = setInterval(() => {
427 if (containers.every((container) => getComputedStyle(container).visibility !== 'hidden')) {
428 clearInterval(interval);
429 resolve();
430 }
431 }, 10);
432
433 // Clear interval if promise is never resolved (component unmount)
434 const timeout = setTimeout(() => {
435 clearInterval(interval);
436 resolve(); // Resolve to prevent hanging promise
437 }, 5000); // 5 second timeout as safety net
438
439 // Store cleanup function for potential external cleanup
440 (resolve as any)._cleanup = () => {
441 clearInterval(interval);
442 clearTimeout(timeout);
443 };
444 }),
445 tabbableOptions: { displayCheck: 'none' },
446
447 fallbackFocus: () => {
448 // If the popover's trigger is focused but scrolled out of view,
449 // FocusTrap will throw an error when the Enter button is used on the trigger.
450 // That is because the Popover is hidden when its trigger is out of view.
451 // Provide a fallback in that case.
452 let node = null;
453 if (document && document.activeElement) {
454 node = document.activeElement as HTMLElement;
455 }
456 return node;
457 }
458 }}
459 preventScrollOnDeactivate
460 className={css(
461 styles.popover,
462 alertSeverityVariant && alertStyle[alertSeverityVariant],
463 hasNoPadding && styles.modifiers.noPadding,
464 hasAutoWidth && styles.modifiers.widthAuto,
465 className
466 )}
467 role="dialog"
468 aria-modal="true"
469 aria-label={headerContent ? undefined : ariaLabel}
470 aria-labelledby={headerContent ? `popover-${uniqueId}-header` : undefined}
471 aria-describedby={`popover-${uniqueId}-body`}
472 onMouseDown={onContentMouseDown}
473 style={{
474 minWidth: hasCustomMinWidth ? minWidth : null,
475 maxWidth: hasCustomMaxWidth ? maxWidth : null
476 }}
477 {...rest}
478 >
479 <PopoverArrow />
480 <PopoverContent>
481 {showClose && triggerAction === 'click' && (
482 <PopoverCloseButton onClose={closePopover} aria-label={closeBtnAriaLabel} />
483 )}
484 {headerContent && (
485 <PopoverHeader
486 id={`popover-${uniqueId}-header`}
487 icon={headerIcon}
488 alertSeverityVariant={alertSeverityVariant}
489 alertSeverityScreenReaderText={alertSeverityScreenReaderText || `${alertSeverityVariant} alert:`}
490 titleHeadingLevel={headerComponent}
491 >
492 {typeof headerContent === 'function' ? headerContent(hide) : headerContent}
493 </PopoverHeader>
494 )}
495 <PopoverBody id={`popover-${uniqueId}-body`}>
496 {typeof bodyContent === 'function' ? bodyContent(hide) : bodyContent}
497 </PopoverBody>
498 {footerContent && (
499 <PopoverFooter id={`popover-${uniqueId}-footer`}>
500 {typeof footerContent === 'function' ? footerContent(hide) : footerContent}
501 </PopoverFooter>
502 )}
503 </PopoverContent>
504 </FocusTrap>
505 );
506
507 return (
508 <PopoverContext.Provider value={{ headerComponent }}>
509 <Popper
510 trigger={children}
511 triggerRef={triggerRef}
512 popper={content}
513 popperRef={popoverRef}
514 minWidth={minWidth}
515 appendTo={appendTo}
516 isVisible={visible}
517 onMouseEnter={triggerAction === 'hover' && onMouseEnter}
518 onMouseLeave={triggerAction === 'hover' && onMouseLeave}
519 onPopperMouseEnter={triggerAction === 'hover' && onMouseEnter}
520 onPopperMouseLeave={triggerAction === 'hover' && onMouseLeave}
521 onFocus={triggerAction === 'hover' && onFocus}
522 onBlur={triggerAction === 'hover' && onBlur}
523 positionModifiers={positionModifiers}
524 distance={distance}
525 placement={position}
526 onTriggerClick={triggerAction === 'click' && onTriggerClick}
527 onDocumentClick={onDocumentClick}
528 onDocumentKeyDown={onDocumentKeyDown}
529 enableFlip={enableFlip}
530 zIndex={zIndex}
531 flipBehavior={flipBehavior}
532 animationDuration={animationDuration}
533 onHidden={onHidden}
534 onShown={onShown}
535 onHide={() => setFocusTrapActive(false)}
536 />
537 </PopoverContext.Provider>
538 );
539 };
540 Popover.displayName = 'Popover';