Debian Codegraph @

node/@patternfly/react-core/src/components/Pagination/PaginationOptionsMenu.tsx

raw
1 import { useEffect, useRef, useState } from 'react';
2 import { css } from '@patternfly/react-styles';
3 import styles from '@patternfly/react-styles/css/components/Pagination/pagination';
4 import { Menu, MenuContent, MenuList, MenuItem } from '../Menu';
5 import { MenuToggle } from '../MenuToggle';
6 import { Popper } from '../../helpers/Popper/Popper';
7 import { PaginationToggleTemplateProps, ToggleTemplate } from './ToggleTemplate';
8 import { PerPageOptions, OnPerPageSelect } from './Pagination';
9 import { fillTemplate } from '../../helpers';
10
11 export interface PaginationOptionsMenuProps extends React.HTMLProps<HTMLDivElement> {
12 /** Custom class name added to the pagination options menu. */
13 className?: string;
14 /** Id added to the title of the pagination options menu. */
15 widgetId?: string;
16 /** Flag indicating if pagination options menu is disabled. */
17 isDisabled?: boolean;
18 /** Menu will open up or open down from the options menu toggle. */
19 dropDirection?: 'up' | 'down';
20 /** Minimum width of the pagination options menu. If set to "trigger", the minimum width will be set to the toggle width. */
21 minWidth?: string | 'trigger';
22 /** Array of titles and values which will be the options on the options menu dropdown. */
23 perPageOptions?: PerPageOptions[];
24 /** The title of the pagination options menu. */
25 itemsPerPageTitle?: string;
26 /** Current page number. */
27 page?: number;
28 /** The suffix to be displayed after each option on the options menu dropdown. */
29 perPageSuffix?: string;
30 /** The type or title of the items being paginated. */
31 itemsTitle?: string;
32 /** Accessible label for the options toggle. */
33 optionsToggleAriaLabel?: string;
34 /** The total number of items being paginated. */
35 itemCount?: number;
36 /** The first index of the items being paginated. */
37 firstIndex?: number;
38 /** The last index of the items being paginated. */
39 lastIndex?: number;
40 /** Flag to indicate whether to show last full page of results when user selects perPage
41 * value that is greater than remaining rows.
42 */
43 isLastFullPageShown?: boolean;
44 /** The number of items to be displayed per page. */
45 perPage?: number;
46 /** The number of the last page. */
47 lastPage?: number;
48 /** This will be shown in pagination toggle span. You can use firstIndex, lastIndex,
49 * itemCount, and/or itemsTitle props.
50 */
51 toggleTemplate: ((props: PaginationToggleTemplateProps) => React.ReactElement<any>) | string;
52 /** Function called when user selects number of items per page. */
53 onPerPageSelect?: OnPerPageSelect;
54 /** Label for the English word "of". */
55 ofWord?: string;
56 /** React ref for the container to append the options menu to. This is a static ref provided by the main pagination component. */
57 containerRef?: React.RefObject<HTMLDivElement | null>;
58 /** @beta The container to append the pagination options menu to. Overrides the containerRef prop. */
59 appendTo?: HTMLElement | (() => HTMLElement) | 'inline';
60 /** Flag indicating if scroll on focus of the first menu item should occur. */
61 shouldPreventScrollOnItemFocus?: boolean;
62 /** Time in ms to wait before firing the toggles' focus event. Defaults to 0 */
63 focusTimeoutDelay?: number;
64 }
65
66 export const PaginationOptionsMenu: React.FunctionComponent<PaginationOptionsMenuProps> = ({
67 className,
68 widgetId,
69 page: pageProp,
70 itemCount,
71 isDisabled = false,
72 minWidth,
73 dropDirection = 'down',
74 perPageOptions = [] as PerPageOptions[],
75 // eslint-disable-next-line @typescript-eslint/no-unused-vars
76 itemsPerPageTitle = 'Items per page',
77 perPageSuffix = 'per page',
78 optionsToggleAriaLabel,
79 ofWord = 'of',
80 perPage = 0,
81 firstIndex = 0,
82 lastIndex = 0,
83 isLastFullPageShown = false,
84 itemsTitle = '',
85 toggleTemplate,
86 onPerPageSelect = () => null as any,
87 containerRef,
88 appendTo,
89 shouldPreventScrollOnItemFocus = true,
90 focusTimeoutDelay = 0
91 }: PaginationOptionsMenuProps) => {
92 const [isOpen, setIsOpen] = useState(false);
93 const toggleRef = useRef<HTMLButtonElement>(null);
94 const menuRef = useRef<HTMLDivElement>(null);
95
96 const onToggle = () => {
97 setIsOpen((prevState) => !prevState);
98 };
99
100 const onSelect = () => {
101 setIsOpen((prevState) => !prevState);
102 toggleRef.current?.focus();
103 };
104
105 const handleNewPerPage = (_evt: React.MouseEvent | React.KeyboardEvent | MouseEvent, newPerPage: number) => {
106 let newPage = pageProp;
107
108 while (Math.ceil(itemCount / newPerPage) < newPage) {
109 newPage--;
110 }
111
112 if (isLastFullPageShown) {
113 if (itemCount / newPerPage !== newPage) {
114 while (newPage > 1 && itemCount - newPerPage * newPage < 0) {
115 newPage--;
116 }
117 }
118 }
119 const startIdx = (newPage - 1) * newPerPage;
120 const endIdx = newPage * newPerPage;
121 return onPerPageSelect(_evt, newPerPage, newPage, startIdx, endIdx);
122 };
123
124 useEffect(() => {
125 const handleMenuKeys = (event: KeyboardEvent) => {
126 // Close the menu on tab or escape
127 if (
128 (isOpen && menuRef.current?.contains(event.target as Node)) ||
129 toggleRef.current?.contains(event.target as Node)
130 ) {
131 if (event.key === 'Escape' || event.key === 'Tab') {
132 setIsOpen(false);
133 toggleRef.current?.focus();
134 }
135 }
136 };
137
138 const handleClick = (event: MouseEvent) => {
139 // Focus the first non-disabled menu item on toggle 'click'
140 if (isOpen && toggleRef.current?.contains(event.target as Node)) {
141 setTimeout(() => {
142 const firstElement = menuRef?.current?.querySelector('li button:not(:disabled)');
143 firstElement && (firstElement as HTMLElement).focus({ preventScroll: shouldPreventScrollOnItemFocus });
144 }, focusTimeoutDelay);
145 }
146
147 // If the event is not on the toggle, close the menu
148 if (
149 isOpen &&
150 !toggleRef?.current?.contains(event.target as Node) &&
151 !menuRef.current?.contains(event.target as Node)
152 ) {
153 setIsOpen(false);
154 }
155 };
156
157 window.addEventListener('keydown', handleMenuKeys);
158 window.addEventListener('click', handleClick);
159
160 return () => {
161 window.removeEventListener('keydown', handleMenuKeys);
162 window.removeEventListener('click', handleClick);
163 };
164 }, [focusTimeoutDelay, isOpen, menuRef, shouldPreventScrollOnItemFocus]);
165
166 const renderItems = () =>
167 perPageOptions.map(({ value, title }) => (
168 <MenuItem
169 key={value}
170 data-action={`per-page-${value}`}
171 isSelected={perPage === value}
172 onClick={(event) => handleNewPerPage(event, value)}
173 >
174 {title}
175 {` ${perPageSuffix}`}
176 </MenuItem>
177 ));
178
179 const toggle = (
180 <div className={css(styles.paginationPageMenu)}>
181 <MenuToggle
182 ref={toggleRef}
183 onClick={onToggle}
184 {...(optionsToggleAriaLabel && { 'aria-label': optionsToggleAriaLabel })}
185 isDisabled={isDisabled || (itemCount && itemCount <= 0)}
186 isExpanded={isOpen}
187 {...(widgetId && { id: `${widgetId}-toggle` })}
188 variant="plainText"
189 aria-haspopup="listbox"
190 >
191 {toggleTemplate &&
192 typeof toggleTemplate === 'string' &&
193 fillTemplate(toggleTemplate, { firstIndex, lastIndex, ofWord, itemCount, itemsTitle })}
194 {toggleTemplate &&
195 typeof toggleTemplate !== 'string' &&
196 (toggleTemplate as (props: PaginationToggleTemplateProps) => React.ReactElement<any>)({
197 firstIndex,
198 lastIndex,
199 ofWord,
200 itemCount,
201 itemsTitle
202 })}
203 {!toggleTemplate && (
204 <ToggleTemplate
205 firstIndex={firstIndex}
206 lastIndex={lastIndex}
207 ofWord={ofWord}
208 itemCount={itemCount}
209 itemsTitle={itemsTitle}
210 />
211 )}
212 </MenuToggle>
213 </div>
214 );
215
216 const menu = (
217 <Menu className={css(className)} onSelect={onSelect} ref={menuRef}>
218 <MenuContent>
219 <MenuList>{renderItems()}</MenuList>
220 </MenuContent>
221 </Menu>
222 );
223
224 const containerToAppendTo = appendTo ?? (containerRef?.current || undefined);
225 return (
226 <Popper
227 trigger={toggle}
228 triggerRef={toggleRef}
229 popper={menu}
230 popperRef={menuRef}
231 isVisible={isOpen}
232 direction={dropDirection}
233 appendTo={containerToAppendTo}
234 minWidth={minWidth !== undefined ? minWidth : 'revert'}
235 />
236 );
237 };
238
239 PaginationOptionsMenu.displayName = 'PaginationOptionsMenu';