Debian Codegraph @

pkg/lib/cockpit-components-multi-typeahead-select.tsx

raw
1 /*
2 SPDX-License-Identifier: MIT
3
4 Copyright (c) 2019 Red Hat, Inc.
5 */
6
7 /* This is a copy of MultiTypeaheadSelect.tsx from
8
9 https://github.com/patternfly/patternfly-react/blob/v5/packages/react-templates/src/components/Select/MultiTypeaheadSelect.tsx
10
11 We don't use it directly from the @patternfly/react-templates node
12 module since we want to add features to it, and also to isolate us
13 from gratuitous upstream changes.
14
15 Our changes:
16
17 - The selection is controlled from the outside and not maintained
18 as internal state. This is how things should work with React.
19
20 - Changes are announced via incremental onAdd and onRemove
21 handlers.
22
23 - We use Labels instead of Chips, since we want colors.
24
25 - The clear button clears the input text, not the selection.
26
27 */
28
29 /* eslint-disable */
30
31 import cockpit from "cockpit";
32 import React from 'react';
33 import { MenuToggle, MenuToggleProps, MenuToggleElement } from '@patternfly/react-core/dist/esm/components/MenuToggle/index.js';
34 import { Button } from '@patternfly/react-core/dist/esm/components/Button/index.js';
35 import { Select, SelectOption, SelectList, SelectOptionProps, SelectProps } from '@patternfly/react-core/dist/esm/components/Select/index.js';
36 import { TextInputGroup, TextInputGroupMain, TextInputGroupUtilities } from '@patternfly/react-core/dist/esm/components/TextInputGroup/index.js';
37 import { Label, LabelGroup, LabelProps } from "@patternfly/react-core/dist/esm/components/Label/index.js";
38 import RhMicronsCloseIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-close-icon';
39
40
41 const _ = cockpit.gettext;
42
43 export interface MultiTypeaheadSelectOption extends Omit<SelectOptionProps, 'content' | 'isSelected'> {
44 /** Content of the select option. */
45 content: string | number;
46 /** Value of the select option. */
47 value: string | number;
48 /** Color */
49 color?: LabelProps["color"];
50 }
51
52 export interface MultiTypeaheadSelectProps extends Omit<SelectProps, 'toggle' | 'onSelect'> {
53 /** @hide Forwarded ref */
54 innerRef?: React.Ref<any>;
55 /** Options of the select. */
56 options: MultiTypeaheadSelectOption[];
57 /** Selected values */
58 selected: (string | number)[];
59 /** Callback triggered when an option is added. */
60 onAdd: (value: (string | number)) => void;
61 /** Callback triggered when an option is removed. */
62 onRemove: (value: (string | number)) => void;
63 /** Callback triggered when the select opens or closes. */
64 onToggle?: (nextIsOpen: boolean) => void;
65 /** Callback triggered when the text in the input field changes. */
66 onInputChange?: (newValue: string) => void;
67 /** Placeholder text for the select input. */
68 placeholder?: string;
69 /** Message to display when no options match the filter. */
70 noOptionsFoundMessage?: string | ((filter: string) => string);
71 /** Flag indicating the select should be disabled. */
72 isDisabled?: boolean;
73 /** Width of the toggle. */
74 toggleWidth?: string;
75 /** Additional props passed to the toggle. */
76 toggleProps?: MenuToggleProps;
77 }
78
79 export const MultiTypeaheadSelectBase: React.FunctionComponent<MultiTypeaheadSelectProps> = ({
80 innerRef,
81 options,
82 selected,
83 onAdd,
84 onRemove,
85 onToggle,
86 onInputChange,
87 placeholder = '',
88 noOptionsFoundMessage = _filter => _("No results found"),
89 isDisabled = false,
90 toggleWidth,
91 toggleProps,
92 ...props
93 }: MultiTypeaheadSelectProps) => {
94 const [isOpen, setIsOpen] = React.useState(false);
95 const [inputValue, setInputValue] = React.useState<string>("");
96 const [selectOptions, setSelectOptions] = React.useState<MultiTypeaheadSelectOption[]>(options);
97 const [focusedItemIndex, setFocusedItemIndex] = React.useState<number | null>(null);
98 const [activeItemId, setActiveItemId] = React.useState<string | null>(null);
99 const textInputRef = React.useRef<HTMLInputElement>();
100
101 const NO_RESULTS = 'no results';
102
103 const openMenu = () => {
104 onToggle && onToggle(true);
105 setIsOpen(true);
106 };
107
108 React.useEffect(() => {
109 let newSelectOptions: MultiTypeaheadSelectOption[] = options;
110
111 // Filter menu items based on the text input value when one exists
112 if (inputValue) {
113 newSelectOptions = options.filter((option) =>
114 String(option.content).toLowerCase().includes(inputValue.toLowerCase())
115 );
116
117 // When no options are found after filtering, display 'No results found'
118 if (!newSelectOptions.length) {
119 newSelectOptions = [
120 {
121 isAriaDisabled: true,
122 isDisabled: true,
123 content:
124 typeof noOptionsFoundMessage === 'string' ? noOptionsFoundMessage : noOptionsFoundMessage(inputValue),
125 value: NO_RESULTS
126 }
127 ];
128 }
129
130 // Open the menu when the input value changes and the new value is not empty
131 if (!isOpen) {
132 openMenu();
133 }
134 }
135
136 setSelectOptions(newSelectOptions);
137 // eslint-disable-next-line react-hooks/exhaustive-deps
138 }, [inputValue, options]);
139
140 const setActiveAndFocusedItem = (itemIndex: number) => {
141 setFocusedItemIndex(itemIndex);
142 const focusedItem = selectOptions[itemIndex];
143 setActiveItemId(focusedItem.value as string);
144 };
145
146 const resetActiveAndFocusedItem = () => {
147 setFocusedItemIndex(null);
148 setActiveItemId(null);
149 };
150
151 const closeMenu = () => {
152 onToggle && onToggle(false);
153 setIsOpen(false);
154 resetActiveAndFocusedItem();
155 setInputValue('');
156 };
157
158 const onInputClick = () => {
159 if (!isOpen) {
160 openMenu();
161 } else if (!inputValue) {
162 closeMenu();
163 }
164 };
165
166 const selectOption = (option: string | number) => {
167 if (selected.includes(option))
168 onRemove(option);
169 else
170 onAdd(option);
171 };
172
173 const _onSelect = (_event: React.MouseEvent<Element, MouseEvent> | undefined, value: string | number | undefined) => {
174 if (value && value !== NO_RESULTS) {
175 selectOption(value);
176 closeMenu();
177 }
178 };
179
180 const onTextInputChange = (_event: React.FormEvent<HTMLInputElement>, value: string) => {
181 setInputValue(value);
182 onInputChange && onInputChange(value);
183
184 resetActiveAndFocusedItem();
185 };
186
187 const handleMenuArrowKeys = (key: string) => {
188 let indexToFocus = 0;
189
190 if (!isOpen) {
191 openMenu();
192 }
193
194 if (selectOptions.every((option) => option.isDisabled)) {
195 return;
196 }
197
198 if (key === 'ArrowUp') {
199 // When no index is set or at the first index, focus to the last, otherwise decrement focus index
200 if (focusedItemIndex === null || focusedItemIndex === 0) {
201 indexToFocus = selectOptions.length - 1;
202 } else {
203 indexToFocus = focusedItemIndex - 1;
204 }
205
206 // Skip disabled options
207 while (selectOptions[indexToFocus].isDisabled) {
208 indexToFocus--;
209 if (indexToFocus === -1) {
210 indexToFocus = selectOptions.length - 1;
211 }
212 }
213 }
214
215 if (key === 'ArrowDown') {
216 // When no index is set or at the last index, focus to the first, otherwise increment focus index
217 if (focusedItemIndex === null || focusedItemIndex === selectOptions.length - 1) {
218 indexToFocus = 0;
219 } else {
220 indexToFocus = focusedItemIndex + 1;
221 }
222
223 // Skip disabled options
224 while (selectOptions[indexToFocus].isDisabled) {
225 indexToFocus++;
226 if (indexToFocus === selectOptions.length) {
227 indexToFocus = 0;
228 }
229 }
230 }
231
232 setActiveAndFocusedItem(indexToFocus);
233 };
234
235 const onInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
236 const focusedItem = focusedItemIndex !== null ? selectOptions[focusedItemIndex] : null;
237
238 switch (event.key) {
239 case 'Enter':
240 if (isOpen && focusedItem && focusedItem.value !== NO_RESULTS && !focusedItem.isAriaDisabled) {
241 selectOption(focusedItem?.value);
242 }
243
244 if (!isOpen) {
245 onToggle && onToggle(true);
246 setIsOpen(true);
247 }
248
249 break;
250 case 'ArrowUp':
251 case 'ArrowDown':
252 event.preventDefault();
253 handleMenuArrowKeys(event.key);
254 break;
255 }
256 };
257
258 const onToggleClick = () => {
259 onToggle && onToggle(!isOpen);
260 setIsOpen(!isOpen);
261 textInputRef?.current?.focus();
262 };
263
264 const onClearButtonClick = (_ev: React.MouseEvent) => {
265 setInputValue('');
266 onInputChange && onInputChange('');
267 resetActiveAndFocusedItem();
268 textInputRef?.current?.focus();
269 };
270
271 const toggle = (toggleRef: React.Ref<MenuToggleElement>) => (
272 <MenuToggle
273 ref={toggleRef}
274 variant="typeahead"
275 onClick={onToggleClick}
276 isExpanded={isOpen}
277 isDisabled={isDisabled}
278 isFullWidth
279 style={
280 {
281 width: toggleWidth
282 } as React.CSSProperties
283 }
284 {...toggleProps}
285 >
286 <TextInputGroup isPlain>
287 <TextInputGroupMain
288 value={inputValue}
289 onClick={onInputClick}
290 onChange={onTextInputChange}
291 onKeyDown={onInputKeyDown}
292 autoComplete="off"
293 innerRef={textInputRef}
294 placeholder={placeholder}
295 {...(activeItemId && { 'aria-activedescendant': activeItemId })}
296 role="combobox"
297 isExpanded={isOpen}
298 aria-controls="select-typeahead-listbox"
299 >
300 <LabelGroup numLabels={10}>
301 {selected.map((selection) => {
302 const option = options.find((o) => o.value === selection);
303 if (!option)
304 return null;
305 const { content, color } = option;
306 function onClose(ev: React.MouseEvent<Element, MouseEvent>) {
307 ev.stopPropagation();
308 onRemove(selection);
309 }
310 return (
311 <Label key={selection}
312 {...(!option.isDisabled ? { onClose } : { }) }
313 {...(color ? { color } : { }) } >
314 {content}
315 </Label>
316 );
317 })}
318 </LabelGroup>
319 </TextInputGroupMain>
320 <TextInputGroupUtilities {...(!inputValue ? { style: { display: 'none' } } : {})}>
321 <Button icon={<RhMicronsCloseIcon aria-hidden />} variant="plain" onClick={onClearButtonClick} aria-label={_("Clear input value")} />
322 </TextInputGroupUtilities>
323 </TextInputGroup>
324 </MenuToggle>
325 );
326
327 return (
328 <Select
329 isOpen={isOpen}
330 selected={selected}
331 onSelect={_onSelect}
332 onOpenChange={(isOpen) => {
333 !isOpen && closeMenu();
334 }}
335 toggle={toggle}
336 variant="typeahead"
337 ref={innerRef}
338 {...props}
339 >
340 <SelectList>
341 {selectOptions.map((option, index) => {
342 const { content, value, ...props } = option;
343
344 return (
345 <SelectOption key={value} value={value} isFocused={focusedItemIndex === index} {...props}>
346 {content}
347 </SelectOption>
348 );
349 })}
350 </SelectList>
351 </Select>
352 );
353 };
354
355 MultiTypeaheadSelectBase.displayName = 'MultiTypeaheadSelectBase';
356
357 export const MultiTypeaheadSelect = React.forwardRef((props: MultiTypeaheadSelectProps, ref: React.Ref<any>) => (
358 <MultiTypeaheadSelectBase {...props} innerRef={ref} />
359 ));
360
361 MultiTypeaheadSelect.displayName = 'MultiTypeaheadSelect';