Debian Codegraph @

pkg/lib/cockpit-components-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 TypeaheadSelect.tsx from
8
9 https://github.com/patternfly/patternfly-react/blob/v5/packages/react-templates/src/components/Select/TypeaheadSelect.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 - There is a new "selectedIsTrusted" option to say that the the
18 "selected" value should always be assumed to be right even if it
19 is not in the list of "selectOptions".
20
21 This option is automatically set to "true" when isCreatable is
22 true. Thus, when allowing creation of things, you don't need to
23 put artificial entries into selectOptions for things that don't
24 yet exist.
25
26 Setting selectIsTrusted to true is also useful when the
27 "selected" and "selectOptions" properties are produced
28 asynchronously from each other. Maybe you know "selected" already
29 but "selectOptions" isn't ready yet.
30
31 - When not actively filtering, the "clear" button is only shown
32 when there is also a onClearSelection function (and when
33 something is selected). Without such a function, nothing will
34 change when hitting the clear button.
35
36 - Allow dividers.
37
38 [
39 ...
40 { decorator: "divider", key: "..." },
41 ...
42 ]
43
44 - Allow headers.
45
46 [
47 ...
48 { decorator: "header", content: _("Nice things"), key: "..." }
49 { value: "icecream", content: _("Icecream") },
50 ...
51 ]
52
53 Note that PatternFly uses SelectGroup and MenuGroup instead of
54 headers, but their recursive nature makes them harder to
55 implement here, mostly because of how keyboard navigation is
56 done. And there is no visual nesting going on anyway. Keeping the
57 options a flat list is just all around easier.
58
59 - Support for a footer.
60
61 */
62
63 /* eslint-disable */
64
65 import cockpit from "cockpit";
66 import React from 'react';
67 import { MenuToggle, MenuToggleProps, MenuToggleElement } from '@patternfly/react-core/dist/esm/components/MenuToggle/index.js';
68 import { Button } from '@patternfly/react-core/dist/esm/components/Button/index.js';
69 import { Divider } from '@patternfly/react-core/dist/esm/components/Divider/index.js';
70 import { MenuFooter } from '@patternfly/react-core/dist/esm/components/Menu/index.js';
71 import { Select, SelectOption, SelectList, SelectOptionProps, SelectProps } from '@patternfly/react-core/dist/esm/components/Select/index.js';
72 import { TextInputGroup, TextInputGroupMain, TextInputGroupUtilities } from '@patternfly/react-core/dist/esm/components/TextInputGroup/index.js';
73 import RhMicronsCloseIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-close-icon';
74 import "cockpit-components-select.scss";
75
76 const _ = cockpit.gettext;
77
78 export interface TypeaheadSelectDividerOption {
79 decorator: "divider";
80
81 key: string | number;
82 };
83
84 export interface TypeaheadSelectHeaderOption {
85 decorator: "header";
86
87 content: string | number;
88 key: string | number;
89 };
90
91 export interface TypeaheadSelectMenuOption extends Omit<SelectOptionProps, 'content' | 'isSelected'> {
92 decorator?: undefined;
93
94 /** Content of the select option. */
95 content: string | number;
96 /** Value of the select option. */
97 value: string | number;
98 /** Indicator for option being selected */
99 isSelected?: boolean;
100 }
101
102 export type TypeaheadSelectOption = TypeaheadSelectMenuOption |
103 TypeaheadSelectDividerOption |
104 TypeaheadSelectHeaderOption;
105
106 export interface TypeaheadSelectProps extends Omit<SelectProps, 'toggle' | 'onSelect'> {
107 /** @hide Forwarded ref */
108 innerRef?: React.Ref<any>;
109 /** Options of the select */
110 selectOptions: TypeaheadSelectOption[];
111 /** Is the selected option valid even when it is not in the list? */
112 selectedIsTrusted?: boolean;
113 /** Callback triggered on selection. */
114 onSelect?: (
115 _event: React.MouseEvent<Element, MouseEvent> | React.KeyboardEvent<HTMLInputElement> | undefined,
116 selection: string | number
117 ) => void;
118 /** Callback triggered when the select opens or closes. */
119 onToggle?: (nextIsOpen: boolean) => void;
120 /** Callback triggered when the text in the input field changes. */
121 onInputChange?: (newValue: string) => void;
122 /** Function to return items matching the current filter value */
123 filterFunction?: (filterValue: string, options: TypeaheadSelectOption[]) => TypeaheadSelectOption[];
124 /** Callback triggered when the clear button is selected */
125 onClearSelection?: () => void;
126 /** Placeholder text for the select input. */
127 placeholder?: string;
128 /** Flag to indicate if the typeahead select allows new items */
129 isCreatable?: boolean;
130 /** Flag to indicate if create option should be at top of typeahead */
131 isCreateOptionOnTop?: boolean;
132 /** Message to display to create a new option */
133 createOptionMessage?: string | ((newValue: string) => string);
134 /** Message to display when no options are available. */
135 noOptionsAvailableMessage?: string;
136 /** Message to display when no options match the filter. */
137 noOptionsFoundMessage?: string | ((filter: string) => string);
138 /** Flag indicating the select should be disabled. */
139 isDisabled?: boolean;
140 /** Optional footer */
141 footer?: React.ReactNode;
142 /** Width of the toggle. */
143 toggleWidth?: string;
144 /** Additional props passed to the toggle. */
145 toggleProps?: MenuToggleProps;
146 }
147
148 const defaultFilterFunction = (filterValue: string, options: TypeaheadSelectOption[]) => {
149 // Filter by search term, keep headers and dividers
150 const filtered = options.filter((o) => {
151 return o.decorator || String(o.content).toLowerCase().includes(filterValue.toLowerCase());
152 });
153
154 // Remove headers that have nothing following them, and dividers that have nothing in front of them.
155 const filtered2 = filtered.filter((o, i) => {
156 if (o.decorator == "header" && (i >= filtered.length - 1 || filtered[i + 1].decorator))
157 return false;
158 if (o.decorator == "divider" && (i <= 0 || filtered[i - 1].decorator))
159 return false;
160 return true;
161 });
162
163 // If the last item is now a divider, remove it as well.
164 if (filtered2.length > 0 && filtered2[filtered2.length-1].decorator == "divider")
165 filtered2.pop();
166
167 return filtered2;
168 };
169
170 export const TypeaheadSelectBase: React.FunctionComponent<TypeaheadSelectProps> = ({
171 innerRef,
172 selectOptions,
173 selectedIsTrusted,
174 onSelect,
175 onToggle,
176 onInputChange,
177 filterFunction = defaultFilterFunction,
178 onClearSelection,
179 placeholder = _("Select an option"),
180 noOptionsAvailableMessage = _("No results found"),
181 noOptionsFoundMessage = _("No results found"),
182 isCreatable = false,
183 isCreateOptionOnTop = false,
184 createOptionMessage = "",
185 isDisabled = false,
186 footer = null,
187 toggleWidth,
188 toggleProps,
189 ...props
190 }: TypeaheadSelectProps) => {
191 const [isOpen, setIsOpen] = React.useState(false);
192 const [filterValue, setFilterValue] = React.useState<string>('');
193 const [isFiltering, setIsFiltering] = React.useState<boolean>(false);
194 const [focusedItemIndex, setFocusedItemIndex] = React.useState<number | null>(null);
195 const [activeItemId, setActiveItemId] = React.useState<string | null>(null);
196 const textInputRef = React.useRef<HTMLInputElement>();
197
198 const NO_RESULTS = 'no results';
199
200 if (isCreatable && !createOptionMessage)
201 throw "isCreatable requires createOptionMessage";
202
203 if (isCreatable)
204 selectedIsTrusted = true;
205
206 const isMenu = (o: TypeaheadSelectOption): o is TypeaheadSelectMenuOption => !o.decorator;
207 const isEnabledMenu = (o: TypeaheadSelectOption): o is TypeaheadSelectMenuOption => !(o.decorator || o.isDisabled);
208
209 const selected = React.useMemo(
210 () => {
211 let res = selectOptions?.find((o): o is TypeaheadSelectMenuOption =>
212 (isEnabledMenu(o) &&
213 (o.value === props.selected || !!o.isSelected)));
214 if (!res && props.selected && selectedIsTrusted)
215 res = { value: props.selected, content: props.selected };
216 return res;
217 },
218 [props.selected, selectOptions]
219 );
220
221 const filteredSelections = React.useMemo(() => {
222 let newSelectOptions: TypeaheadSelectOption[] = selectOptions;
223
224 // Filter menu items based on the text input value when one exists
225 if (isFiltering && filterValue) {
226 newSelectOptions = filterFunction(filterValue, selectOptions);
227
228 if (
229 isCreatable &&
230 filterValue.trim() &&
231 !newSelectOptions.find((o) => isMenu(o) && String(o.content).toLowerCase() === filterValue.toLowerCase())
232 ) {
233 const createOption = {
234 content: typeof createOptionMessage === 'string' ? createOptionMessage : createOptionMessage(filterValue),
235 value: filterValue
236 };
237 newSelectOptions = isCreateOptionOnTop
238 ? [createOption, ...newSelectOptions]
239 : [...newSelectOptions, createOption];
240 }
241
242 // When no options are found after filtering, display 'No results found'
243 if (!newSelectOptions.length) {
244 newSelectOptions = [
245 {
246 isAriaDisabled: true,
247 isDisabled: true,
248 content:
249 typeof noOptionsFoundMessage === 'string' ? noOptionsFoundMessage : noOptionsFoundMessage(filterValue),
250 value: NO_RESULTS
251 }
252 ];
253 }
254 }
255
256 // When no options are available, display 'No options available'
257 if (!newSelectOptions.length) {
258 newSelectOptions = [
259 {
260 isAriaDisabled: true,
261 isDisabled: true,
262 content: noOptionsAvailableMessage,
263 value: NO_RESULTS
264 }
265 ];
266 }
267
268 return newSelectOptions;
269 }, [
270 isFiltering,
271 filterValue,
272 filterFunction,
273 selectOptions,
274 noOptionsFoundMessage,
275 isCreatable,
276 isCreateOptionOnTop,
277 createOptionMessage,
278 noOptionsAvailableMessage
279 ]);
280
281 React.useEffect(() => {
282 if (isFiltering) {
283 openMenu();
284 }
285 // Don't update on openMenu changes
286 // eslint-disable-next-line react-hooks/exhaustive-deps
287 }, [isFiltering]);
288
289 const setActiveAndFocusedItem = (itemIndex: number) => {
290 setFocusedItemIndex(itemIndex);
291 const focusedItem = filteredSelections[itemIndex] as TypeaheadSelectMenuOption;
292 setActiveItemId(String(focusedItem.value));
293 };
294
295 const resetActiveAndFocusedItem = () => {
296 setFocusedItemIndex(null);
297 setActiveItemId(null);
298 };
299
300 const openMenu = () => {
301 if (!isOpen) {
302 onToggle && onToggle(true);
303 setIsOpen(true);
304 setTimeout(() => {
305 textInputRef.current?.focus();
306 }, 100);
307 }
308 };
309
310 const closeMenu = () => {
311 onToggle && onToggle(false);
312 setIsOpen(false);
313 resetActiveAndFocusedItem();
314 setIsFiltering(false);
315 setFilterValue(String(selected?.content ?? ''));
316 };
317
318 const onInputClick = () => {
319 if (!isOpen) {
320 openMenu();
321 } else if (isFiltering) {
322 closeMenu();
323 }
324 };
325
326 const selectOption = (
327 _event: React.MouseEvent<Element, MouseEvent> | React.KeyboardEvent<HTMLInputElement> | undefined,
328 option: TypeaheadSelectMenuOption
329 ) => {
330 onSelect && onSelect(_event, option.value);
331 closeMenu();
332 };
333
334 const _onSelect = (_event: React.MouseEvent<Element, MouseEvent> | undefined, value: string | number | undefined) => {
335 if (value && value !== NO_RESULTS) {
336 const optionToSelect = selectOptions.find(
337 (option): option is TypeaheadSelectMenuOption => isMenu(option) && option.value === value);
338 if (optionToSelect) {
339 selectOption(_event, optionToSelect);
340 } else if (isCreatable) {
341 selectOption(_event, { value, content: value });
342 }
343 }
344 };
345
346 const onTextInputChange = (_event: React.FormEvent<HTMLInputElement>, value: string) => {
347 setIsFiltering(true);
348 setFilterValue(value || '');
349 onInputChange && onInputChange(value);
350
351 resetActiveAndFocusedItem();
352 };
353
354 const handleMenuArrowKeys = (key: string) => {
355 let indexToFocus = 0;
356
357 openMenu();
358
359 if (filteredSelections.every(o => !isEnabledMenu(o))) {
360 return;
361 }
362
363 if (key === 'ArrowUp') {
364 // When no index is set or at the first index, focus to the last, otherwise decrement focus index
365 if (focusedItemIndex === null || focusedItemIndex === 0) {
366 indexToFocus = filteredSelections.length - 1;
367 } else {
368 indexToFocus = focusedItemIndex - 1;
369 }
370
371 // Skip non-items
372 while (!isEnabledMenu(filteredSelections[indexToFocus])) {
373 indexToFocus--;
374 if (indexToFocus === -1) {
375 indexToFocus = filteredSelections.length - 1;
376 }
377 }
378 }
379
380 if (key === 'ArrowDown') {
381 // When no index is set or at the last index, focus to the first, otherwise increment focus index
382 if (focusedItemIndex === null || focusedItemIndex === filteredSelections.length - 1) {
383 indexToFocus = 0;
384 } else {
385 indexToFocus = focusedItemIndex + 1;
386 }
387
388 // Skip non-items
389 while (!isEnabledMenu(filteredSelections[indexToFocus])) {
390 indexToFocus++;
391 if (indexToFocus === filteredSelections.length) {
392 indexToFocus = 0;
393 }
394 }
395 }
396
397 setActiveAndFocusedItem(indexToFocus);
398 };
399
400 const onInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
401 const focusedItem = (focusedItemIndex !== null ? filteredSelections[focusedItemIndex] : null) as TypeaheadSelectMenuOption | null;
402
403 switch (event.key) {
404 case 'Enter':
405 if (isOpen && focusedItem && focusedItem.value !== NO_RESULTS && !focusedItem.isAriaDisabled) {
406 selectOption(event, focusedItem);
407 }
408
409 openMenu();
410
411 break;
412 case 'ArrowUp':
413 case 'ArrowDown':
414 event.preventDefault();
415 handleMenuArrowKeys(event.key);
416 break;
417 }
418 };
419
420 const onToggleClick = () => {
421 if (!isOpen) {
422 openMenu();
423 } else {
424 closeMenu();
425 }
426 textInputRef.current?.focus();
427 };
428
429 const onClearButtonClick = () => {
430 if (selected && onSelect) {
431 onSelect(undefined, selected.value);
432 }
433 setFilterValue('');
434 onInputChange && onInputChange('');
435 setIsFiltering(false);
436 resetActiveAndFocusedItem();
437 textInputRef.current?.focus();
438 onClearSelection && onClearSelection();
439 };
440
441 const toggle = (toggleRef: React.Ref<MenuToggleElement>) => (
442 <MenuToggle
443 ref={toggleRef}
444 variant="typeahead"
445 aria-label="Typeahead menu toggle"
446 onClick={onToggleClick}
447 isExpanded={isOpen}
448 isDisabled={isDisabled}
449 isFullWidth
450 style={
451 {
452 width: toggleWidth
453 } as React.CSSProperties
454 }
455 {...toggleProps}
456 >
457 <TextInputGroup isPlain>
458 <TextInputGroupMain
459 value={isFiltering ? filterValue : (selected?.content ?? '')}
460 onClick={onInputClick}
461 onChange={onTextInputChange}
462 onKeyDown={onInputKeyDown}
463 autoComplete="off"
464 innerRef={textInputRef}
465 placeholder={placeholder}
466 {...(activeItemId && { 'aria-activedescendant': activeItemId })}
467 role="combobox"
468 isExpanded={isOpen}
469 aria-controls="select-typeahead-listbox"
470 />
471 <TextInputGroupUtilities
472 {...(!(isFiltering && filterValue) && !(selected && onClearSelection) ? { style: { display: 'none' } } : {})}
473 >
474 <Button icon={<RhMicronsCloseIcon aria-hidden />} variant="plain" onClick={onClearButtonClick} aria-label="Clear input value" />
475 </TextInputGroupUtilities>
476 </TextInputGroup>
477 </MenuToggle>
478 );
479
480 return (
481 <Select
482 isOpen={isOpen}
483 selected={selected}
484 onSelect={_onSelect}
485 onOpenChange={(isOpen) => !isOpen && closeMenu()}
486 toggle={toggle}
487 variant="typeahead"
488 ref={innerRef}
489 {...props}
490 >
491 <SelectList>
492 {filteredSelections.map((option, index) => {
493 if (option.decorator == "divider")
494 return <Divider key={option.key} component="li" />;
495
496 if (option.decorator == "header") {
497 return (
498 <SelectOption key={option.key}
499 isDisabled
500 className="ct-select-header">
501 {option.content}
502 </SelectOption>
503 );
504 }
505
506 const { content, value, ...props } = option;
507 return (
508 <SelectOption key={value} value={value} isFocused={focusedItemIndex === index} {...props}>
509 {content}
510 </SelectOption>
511 );
512 })}
513 </SelectList>
514 { footer && <MenuFooter>{footer}</MenuFooter> }
515 </Select>
516 );
517 };
518 TypeaheadSelectBase.displayName = 'TypeaheadSelectBase';
519
520 export const TypeaheadSelect = React.forwardRef((props: TypeaheadSelectProps, ref: React.Ref<any>) => (
521 <TypeaheadSelectBase {...props} innerRef={ref} />
522 ));
523
524 TypeaheadSelect.displayName = 'TypeaheadSelect';