Debian Codegraph @

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

raw
1 import { forwardRef, useEffect, useRef } from 'react';
2 import { css } from '@patternfly/react-styles';
3 import { Menu, MenuContent, MenuProps } from '../Menu';
4 import { Popper, PopperOptions } from '../../helpers/Popper/Popper';
5 import type { DropdownItemProps } from './DropdownItem';
6 import { useOUIAProps, OUIAProps, onToggleArrowKeydownDefault } from '../../helpers';
7
8 /** @deprecated Use PopperOptions instead */
9 export type DropdownPopperProps = PopperOptions;
10
11 export interface DropdownToggleProps {
12 /** Dropdown toggle node. */
13 toggleNode: React.ReactNode;
14 /** Reference to the toggle. */
15 toggleRef?: React.RefObject<HTMLButtonElement | null>;
16 }
17
18 /**
19 * See the Menu documentation for additional props that may be passed.
20 */
21 export interface DropdownProps extends MenuProps, OUIAProps {
22 /** Anything which can be rendered in a dropdown. */
23 children?: React.ReactNode;
24 /** Classes applied to root element of dropdown. */
25 className?: string;
26 /** Dropdown toggle. The toggle should either be a renderer function which forwards the given toggle ref, or a direct ReactNode that should be passed along with the toggleRef property. */
27 toggle: DropdownToggleProps | ((toggleRef: React.RefObject<any>) => React.ReactNode);
28 /** Flag to indicate if menu is opened.*/
29 isOpen?: boolean;
30 /** Flag indicating the toggle should be focused after a selection. If this use case is too restrictive, the optional toggleRef property with a node toggle may be used to control focus. */
31 shouldFocusToggleOnSelect?: boolean;
32 /** Function callback called when user selects item. */
33 onSelect?: (event?: React.MouseEvent<Element, MouseEvent>, value?: DropdownItemProps['value']) => void;
34 /** Callback to allow the dropdown component to change the open state of the menu.
35 * Triggered by clicking outside of the menu, or by pressing any keys specified in onOpenChangeKeys. */
36 onOpenChange?: (isOpen: boolean) => void;
37 /** Keys that trigger onOpenChange, defaults to tab and escape. It is highly recommended to include Escape in the array, while Tab may be omitted if the menu contains non-menu items that are focusable. */
38 onOpenChangeKeys?: string[];
39 /** Callback to override the toggle keydown behavior. By default, when the toggle has focus and the menu is open, pressing the up/down arrow keys will focus a valid non-disabled menu item - the first item for the down arrow key and last item for the up arrow key. */
40 onToggleKeydown?: (event: KeyboardEvent) => void;
41 /** Indicates if the menu should be without the outer box-shadow. */
42 isPlain?: boolean;
43 /** Indicates if the menu should be scrollable. */
44 isScrollable?: boolean;
45 /** @hide Forwarded ref */
46 innerRef?: React.Ref<any>;
47 /** Value to overwrite the randomly generated data-ouia-component-id.*/
48 ouiaId?: number | string;
49 /** Set the value of data-ouia-safe. Only set to true when the component is in a static state, i.e. no animations are occurring. At all other times, this value must be false. */
50 ouiaSafe?: boolean;
51 /** When applied, wraps dropdown in a container with a data-ouia-component-id.*/
52 containerOuiaId?: number | string;
53 /** Set the value of data-ouia-safe for the container when containerOuiaId is applied. Only set to true when the component is in a static state, i.e. no animations are occurring. At all other times, this value must be false. */
54 containerOuiaSafe?: boolean;
55 /** Sets the base component to render for the container. Defaults to <span> */
56 containerComponent?: React.ReactNode;
57 /** z-index of the dropdown menu */
58 zIndex?: number;
59 /** Additional properties to pass to the Popper */
60 popperProps?: PopperOptions;
61 /** Height of the dropdown menu */
62 menuHeight?: string;
63 /** Maximum height of dropdown menu */
64 maxMenuHeight?: string;
65 /** @beta Flag indicating the first menu item should be focused after opening the dropdown. */
66 shouldFocusFirstItemOnOpen?: boolean;
67 /** Flag indicating if scroll on focus of the first menu item should occur. */
68 shouldPreventScrollOnItemFocus?: boolean;
69 /** Time in ms to wait before firing the toggles' focus event. Defaults to 0 */
70 focusTimeoutDelay?: number;
71 }
72
73 const DropdownBase: React.FunctionComponent<DropdownProps> = ({
74 children,
75 className,
76 onSelect,
77 isOpen,
78 toggle,
79 shouldFocusToggleOnSelect = false,
80 onOpenChange,
81 onToggleKeydown,
82 isPlain,
83 isScrollable,
84 innerRef,
85 ouiaId,
86 ouiaSafe = true,
87 zIndex = 9999,
88 popperProps,
89 onOpenChangeKeys = ['Escape', 'Tab'],
90 menuHeight,
91 maxMenuHeight,
92 shouldFocusFirstItemOnOpen = false,
93 shouldPreventScrollOnItemFocus = true,
94 focusTimeoutDelay = 0,
95 containerOuiaId,
96 containerOuiaSafe = true,
97 containerComponent = 'span',
98 ...props
99 }: DropdownProps) => {
100 const localMenuRef = useRef<HTMLDivElement>(undefined);
101 const localToggleRef = useRef<HTMLButtonElement>(undefined);
102 const ouiaProps = useOUIAProps(Dropdown.displayName, ouiaId, ouiaSafe);
103 const ContainerComponent = containerComponent as any;
104 const containerOuiaProps = useOUIAProps('Dropdown container', containerOuiaId, containerOuiaSafe);
105
106 const menuRef = (innerRef as React.RefObject<HTMLDivElement | null>) || localMenuRef;
107 const toggleRef =
108 typeof toggle === 'function' || (typeof toggle !== 'function' && !toggle.toggleRef)
109 ? localToggleRef
110 : (toggle?.toggleRef as React.RefObject<HTMLButtonElement | null>);
111
112 const prevIsOpen = useRef<boolean>(isOpen);
113 useEffect(() => {
114 // menu was opened, focus on first menu item
115 if (prevIsOpen.current === false && isOpen === true && shouldFocusFirstItemOnOpen) {
116 setTimeout(() => {
117 const firstElement = menuRef?.current?.querySelector(
118 'li button:not(:disabled),li input:not(:disabled),li a:not([aria-disabled="true"])'
119 );
120 firstElement && (firstElement as HTMLElement).focus({ preventScroll: shouldPreventScrollOnItemFocus });
121 }, focusTimeoutDelay);
122 }
123
124 prevIsOpen.current = isOpen;
125 // eslint-disable-next-line react-hooks/exhaustive-deps
126 }, [isOpen]);
127
128 useEffect(() => {
129 const handleMenuKeys = (event: KeyboardEvent) => {
130 // Close the menu on tab or escape if onOpenChange is provided
131 if (
132 isOpen &&
133 onOpenChange &&
134 (menuRef.current?.contains(event.target as Node) || toggleRef.current?.contains(event.target as Node))
135 ) {
136 if (onOpenChangeKeys.includes(event.key)) {
137 onOpenChange(false);
138 toggleRef.current?.focus();
139 }
140 }
141
142 if (toggleRef.current?.contains(event.target as Node)) {
143 if (onToggleKeydown) {
144 onToggleKeydown(event);
145 } else if (isOpen) {
146 onToggleArrowKeydownDefault(event, menuRef);
147 }
148 }
149 };
150
151 const handleClick = (event: MouseEvent) => {
152 // If the event is not on the toggle and onOpenChange callback is provided, close the menu
153 if (isOpen && onOpenChange && !toggleRef?.current?.contains(event.target as Node)) {
154 if (isOpen && !menuRef.current?.contains(event.target as Node)) {
155 onOpenChange(false);
156 }
157 }
158 };
159
160 window.addEventListener('keydown', handleMenuKeys);
161 window.addEventListener('click', handleClick);
162
163 return () => {
164 window.removeEventListener('keydown', handleMenuKeys);
165 window.removeEventListener('click', handleClick);
166 };
167 }, [
168 isOpen,
169 menuRef,
170 toggleRef,
171 onOpenChange,
172 onOpenChangeKeys,
173 onToggleKeydown,
174 shouldPreventScrollOnItemFocus,
175 shouldFocusFirstItemOnOpen,
176 focusTimeoutDelay
177 ]);
178
179 const scrollable = maxMenuHeight !== undefined || menuHeight !== undefined || isScrollable;
180
181 const menu = (
182 <Menu
183 className={css(className)}
184 ref={menuRef}
185 onSelect={(event, value) => {
186 onSelect && onSelect(event, value);
187 shouldFocusToggleOnSelect && toggleRef.current?.focus();
188 }}
189 isPlain={isPlain}
190 isScrollable={scrollable}
191 {...props}
192 {...ouiaProps}
193 >
194 <MenuContent menuHeight={menuHeight} maxMenuHeight={maxMenuHeight}>
195 {children}
196 </MenuContent>
197 </Menu>
198 );
199
200 const popper = (
201 <Popper
202 trigger={typeof toggle === 'function' ? toggle(toggleRef) : toggle.toggleNode}
203 triggerRef={toggleRef}
204 popper={menu}
205 popperRef={menuRef}
206 isVisible={isOpen}
207 zIndex={zIndex}
208 {...popperProps}
209 />
210 );
211
212 return containerOuiaId ? <ContainerComponent {...containerOuiaProps}>{popper}</ContainerComponent> : popper;
213 };
214
215 export const Dropdown = forwardRef((props: DropdownProps, ref: React.Ref<any>) => (
216 <DropdownBase innerRef={ref} {...props} />
217 ));
218 Dropdown.displayName = 'Dropdown';