Debian Codegraph @

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

raw
1 import { forwardRef, useEffect, useRef, useState } from 'react';
2 import { css } from '@patternfly/react-styles';
3 import { Button, ButtonVariant } from '../Button';
4 import { Badge } from '../Badge';
5 import { Icon } from '../Icon';
6 import AngleUpIcon from '@patternfly/react-icons/dist/esm/icons/angle-up-icon';
7 import RhMicronsCloseIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-close-icon';
8 import SearchIcon from '@patternfly/react-icons/dist/esm/icons/search-icon';
9 import RhMicronsCaretRightIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-caret-right-icon';
10 import RhMicronsCaretDownFillIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-caret-down-fill-icon';
11 import { AdvancedSearchMenu } from './AdvancedSearchMenu';
12 import { TextInputGroup, TextInputGroupMain, TextInputGroupUtilities } from '../TextInputGroup';
13 import { InputGroup, InputGroupItem } from '../InputGroup';
14 import { Popper } from '../../helpers';
15 import { useHasAnimations } from '../../helpers';
16 import textInputGroupStyles from '@patternfly/react-styles/css/components/TextInputGroup/text-input-group';
17 import inputGroupStyles from '@patternfly/react-styles/css/components/InputGroup/input-group';
18
19 /** Properties for adding search attributes to an advanced search input. These properties must
20 * be passed in as an object within an array to the search input component's attribute property.
21 */
22
23 export interface SearchInputSearchAttribute {
24 /** The search attribute's value to be provided in the search input's query string.
25 * It should have no spaces and be unique for every attribute.
26 */
27 attr: string;
28 /** The search attribute's display name. It is used to label the field in the advanced
29 * search menu.
30 */
31 display: React.ReactNode;
32 }
33
34 /** Properties for creating an expandable search input. These properties should be passed into
35 * the search input component's expandableInput property.
36 */
37
38 export interface SearchInputExpandable {
39 /** Flag to indicate if the search input is expanded. */
40 isExpanded: boolean;
41 /** Callback function to toggle the expandable search input. */
42 onToggleExpand: (event: React.SyntheticEvent<HTMLButtonElement>, isExpanded: boolean) => void;
43 /** An accessible label for the expandable search input toggle. */
44 toggleAriaLabel: string;
45 /** Flag indicating animations should be enabled when the search input expands and collapses. Note: this will change the component's DOM structure. In a future breaking change release, this will become the default behavior and will no longer be needed. */
46 hasAnimations?: boolean;
47 }
48
49 /** The main search input component. */
50
51 export interface SearchInputProps extends Omit<React.HTMLProps<HTMLDivElement>, 'onChange' | 'results' | 'ref'> {
52 /** Delimiter in the query string for pairing attributes with search values.
53 * Required whenever attributes are passed as props.
54 */
55 advancedSearchDelimiter?: string;
56 /** The container to append the menu to.
57 * If your menu is being cut off you can append it to an element higher up the DOM tree.
58 * Some examples:
59 * appendTo={() => document.body}
60 * appendTo={document.getElementById('target')}
61 */
62 appendTo?: HTMLElement | (() => HTMLElement) | 'inline';
63 /** An accessible label for the search input. */
64 'aria-label'?: string;
65 /** Flag to indicate utilities should be displayed. By default if this prop is undefined or false, utilities will only be displayed when the search input has a value. */
66
67 areUtilitiesDisplayed?: boolean;
68 /** Array of attribute values used for dynamically generated advanced search. */
69 attributes?: string[] | SearchInputSearchAttribute[];
70 /** Additional classes added to the search input. */
71 className?: string;
72 /** Object that makes the search input expandable/collapsible. */
73 expandableInput?: SearchInputExpandable;
74 /* Additional elements added after the attributes in the form.
75 * The new form elements can be wrapped in a form group component for automatic formatting. */
76 formAdditionalItems?: React.ReactNode;
77 /** Attribute label for strings unassociated with one of the provided listed attributes. */
78 hasWordsAttrLabel?: React.ReactNode;
79 /** A suggestion for autocompleting. */
80 hint?: string;
81 /** Id for the search input */
82 searchInputId?: string;
83 /** @hide A reference object to attach to the input box. */
84 innerRef?: React.RefObject<any>;
85 /** A flag for controlling the open state of a custom advanced search implementation. */
86 isAdvancedSearchOpen?: boolean;
87 /** Flag indicating if search input is disabled. */
88 isDisabled?: boolean;
89 /** Flag indicating if the next navigation button is disabled. */
90 isNextNavigationButtonDisabled?: boolean;
91 /** Flag indicating if the previous navigation button is disabled. */
92 isPreviousNavigationButtonDisabled?: boolean;
93 /** Accessible label for the button to navigate to next result. */
94 nextNavigationButtonAriaLabel?: string;
95 /** A callback for when the input value changes. */
96 onChange?: (event: React.FormEvent<HTMLInputElement>, value: string) => void;
97 /** A callback for when the user clicks the clear button. */
98 onClear?: (event: React.SyntheticEvent<HTMLButtonElement>) => void;
99 /** A callback for when the user clicks to navigate to next result. */
100 onNextClick?: (event: React.SyntheticEvent<HTMLButtonElement>) => void;
101 /** A callback for when the user clicks to navigate to previous result. */
102 onPreviousClick?: (event: React.SyntheticEvent<HTMLButtonElement>) => void;
103 /** A callback for when the search button is clicked. */
104 onSearch?: (
105 event: React.SyntheticEvent<HTMLButtonElement>,
106 value: string,
107 attrValueMap: { [key: string]: string }
108 ) => void;
109 /** A callback for when the open advanced search button is clicked. */
110 onToggleAdvancedSearch?: (event: React.SyntheticEvent<HTMLButtonElement>, isOpen?: boolean) => void;
111 /** Accessible label for the button which opens the advanced search form menu. */
112 openMenuButtonAriaLabel?: string;
113 /** Placeholder text of the search input. */
114 placeholder?: string;
115 /** Accessible label for the button to navigate to previous result. */
116 previousNavigationButtonAriaLabel?: string;
117 /** z-index of the advanced search form when appendTo is not inline. */
118 zIndex?: number;
119 /** Label for the button which resets the advanced search form and clears the search input. */
120 resetButtonLabel?: string;
121 /** The number of search results returned. Either a total number of results,
122 * or a string representing the current result over the total number of results. i.e. "1 / 5". */
123 resultsCount?: number | string;
124 /** Screenreader text that will appear after resultsCount to give context for what that value represents to assistive technologies. */
125 resultsCountContext?: string;
126 /** Label for the button which calls the onSearch event handler. */
127 submitSearchButtonLabel?: string;
128 /** Value of the search input. */
129 value?: string;
130 /** Name attribute for the search input */
131 name?: string;
132 /** Additional props to spread to the search input element. */
133 inputProps?: any;
134 }
135
136 const SearchInputBase: React.FunctionComponent<SearchInputProps> = ({
137 className,
138 searchInputId,
139 value = '',
140 attributes = [] as string[],
141 formAdditionalItems,
142 hasWordsAttrLabel = 'Has words',
143 advancedSearchDelimiter,
144 placeholder,
145 hint,
146 onChange,
147 onSearch,
148 onClear,
149 onToggleAdvancedSearch,
150 isAdvancedSearchOpen = false,
151 resultsCount,
152 resultsCountContext = ' results',
153 onNextClick,
154 onPreviousClick,
155 innerRef,
156 expandableInput,
157 'aria-label': ariaLabel = 'Search input',
158 resetButtonLabel = 'Reset',
159 openMenuButtonAriaLabel = 'Open advanced search',
160 previousNavigationButtonAriaLabel = 'Previous',
161 isPreviousNavigationButtonDisabled = false,
162 isNextNavigationButtonDisabled = false,
163 nextNavigationButtonAriaLabel = 'Next',
164 submitSearchButtonLabel = 'Search',
165 isDisabled = false,
166 appendTo,
167 zIndex = 9999,
168 name,
169 areUtilitiesDisplayed,
170 inputProps,
171 ...props
172 }: SearchInputProps) => {
173 const [isSearchMenuOpen, setIsSearchMenuOpen] = useState(false);
174 const [searchValue, setSearchValue] = useState(value);
175 const searchInputRef = useRef(null);
176 const ref = useRef(null);
177 const searchInputInputRef = innerRef || ref;
178 const searchInputExpandableToggleRef = useRef(null);
179 const triggerRef = useRef(null);
180 const popperRef = useRef(null);
181 const [focusAfterExpandChange, setFocusAfterExpandChange] = useState(false);
182
183 const { isExpanded, onToggleExpand, toggleAriaLabel, hasAnimations: hasAnimationsProp } = expandableInput || {};
184 const hasAnimations = useHasAnimations(hasAnimationsProp);
185
186 useEffect(() => {
187 // this effect and the focusAfterExpandChange variable are needed to focus the input/toggle as needed when the
188 // expansion toggle is fired without focusing on mount
189 if (!focusAfterExpandChange) {
190 return;
191 } else if (isExpanded) {
192 searchInputInputRef?.current?.focus();
193 } else {
194 if (!hasAnimations) {
195 searchInputExpandableToggleRef?.current?.focus();
196 }
197 }
198 if (!hasAnimations) {
199 setFocusAfterExpandChange(false);
200 }
201 }, [focusAfterExpandChange, isExpanded, searchInputInputRef, searchInputExpandableToggleRef]);
202
203 useEffect(() => {
204 setSearchValue(value);
205 }, [value]);
206
207 useEffect(() => {
208 if (attributes.length > 0 && !advancedSearchDelimiter) {
209 // eslint-disable-next-line no-console
210 console.error(
211 'An advancedSearchDelimiter prop is required when advanced search attributes are provided using the attributes prop'
212 );
213 }
214 });
215
216 useEffect(() => {
217 setIsSearchMenuOpen(isAdvancedSearchOpen);
218 }, [isAdvancedSearchOpen]);
219
220 const onChangeHandler = (event: React.FormEvent<HTMLInputElement>, value: string) => {
221 if (onChange) {
222 onChange(event, value);
223 }
224 setSearchValue(value);
225 };
226
227 const onToggle = (e: React.SyntheticEvent<HTMLButtonElement>) => {
228 const isOpen = !isSearchMenuOpen;
229 setIsSearchMenuOpen(isOpen);
230 if (onToggleAdvancedSearch) {
231 onToggleAdvancedSearch(e, isOpen);
232 }
233 };
234
235 const onSearchHandler = (event: React.SyntheticEvent<HTMLButtonElement>) => {
236 event.preventDefault();
237 if (onSearch) {
238 onSearch(event, value, getAttrValueMap());
239 }
240 setIsSearchMenuOpen(false);
241 };
242
243 const splitStringExceptInQuotes = (str: string) => {
244 let quoteType: string;
245
246 return str.match(/\\?.|^$/g).reduce(
247 (p: any, c: string) => {
248 if (c === "'" || c === '"') {
249 if (!quoteType) {
250 quoteType = c;
251 }
252 if (c === quoteType) {
253 p.quote = !p.quote;
254 }
255 } else if (!p.quote && c === ' ') {
256 p.a.push('');
257 } else {
258 p.a[p.a.length - 1] += c.replace(/\\(.)/, '$1');
259 }
260 return p;
261 },
262 { a: [''] }
263 ).a;
264 };
265
266 const getAttrValueMap = () => {
267 const attrValue: { [key: string]: string } = {};
268 const pairs = splitStringExceptInQuotes(searchValue);
269 pairs.map((pair: string) => {
270 const splitPair = pair.split(advancedSearchDelimiter);
271 if (splitPair.length === 2) {
272 attrValue[splitPair[0]] = splitPair[1].replace(/(^'|'$)/g, '');
273 } else if (splitPair.length === 1) {
274 attrValue.haswords = attrValue.hasOwnProperty('haswords')
275 ? `${attrValue.haswords} ${splitPair[0]}`
276 : splitPair[0];
277 }
278 });
279 return attrValue;
280 };
281
282 const onEnter = (event: React.KeyboardEvent<any>) => {
283 if (event.key === 'Enter') {
284 onSearchHandler(event);
285 }
286 };
287
288 const onClearInput = (e: React.SyntheticEvent<HTMLButtonElement>) => {
289 if (onClear) {
290 onClear(e);
291 }
292 if (searchInputInputRef && searchInputInputRef.current) {
293 searchInputInputRef.current.focus();
294 }
295 };
296
297 const onExpandHandler = (event: React.SyntheticEvent<HTMLButtonElement>) => {
298 setSearchValue('');
299 onToggleExpand(event, isExpanded);
300 setFocusAfterExpandChange(true);
301 };
302
303 const renderUtilities =
304 value && (resultsCount || (!!onNextClick && !!onPreviousClick) || (!!onClear && !expandableInput));
305
306 const buildTextInputGroup = ({ ...searchInputProps } = {}) => (
307 <TextInputGroup isDisabled={isDisabled} {...searchInputProps}>
308 <TextInputGroupMain
309 hint={hint}
310 icon={<SearchIcon />}
311 innerRef={searchInputInputRef}
312 value={searchValue}
313 placeholder={placeholder}
314 aria-label={ariaLabel}
315 onKeyDown={onEnter}
316 onChange={onChangeHandler}
317 name={name}
318 inputId={searchInputId}
319 inputProps={inputProps}
320 />
321 {(renderUtilities || areUtilitiesDisplayed) && (
322 <TextInputGroupUtilities>
323 {resultsCount && (
324 <Badge isRead screenReaderText={resultsCountContext}>
325 {resultsCount}
326 </Badge>
327 )}
328 {!!onNextClick && !!onPreviousClick && (
329 <div className={textInputGroupStyles.textInputGroupGroup}>
330 <Button
331 variant={ButtonVariant.plain}
332 aria-label={previousNavigationButtonAriaLabel}
333 isDisabled={isDisabled || isPreviousNavigationButtonDisabled}
334 onClick={onPreviousClick}
335 icon={<AngleUpIcon />}
336 />
337 <Button
338 variant={ButtonVariant.plain}
339 aria-label={nextNavigationButtonAriaLabel}
340 isDisabled={isDisabled || isNextNavigationButtonDisabled}
341 onClick={onNextClick}
342 icon={<RhMicronsCaretDownFillIcon />}
343 />
344 </div>
345 )}
346 {!!onClear && !expandableInput && (
347 <Button
348 variant={ButtonVariant.plain}
349 isDisabled={isDisabled}
350 aria-label={resetButtonLabel}
351 onClick={onClearInput}
352 icon={<RhMicronsCloseIcon />}
353 />
354 )}
355 </TextInputGroupUtilities>
356 )}
357 </TextInputGroup>
358 );
359
360 const expandToggleButton = (
361 <Button
362 variant={ButtonVariant.plain}
363 aria-label={toggleAriaLabel}
364 aria-expanded={isExpanded}
365 icon={<SearchIcon />}
366 onClick={onExpandHandler}
367 ref={searchInputExpandableToggleRef}
368 />
369 );
370
371 const collapseToggleButton = (
372 <Button
373 variant={ButtonVariant.plain}
374 aria-label={toggleAriaLabel}
375 aria-expanded={isExpanded}
376 icon={<RhMicronsCloseIcon />}
377 onClick={onExpandHandler}
378 />
379 );
380
381 const singleButtonToggle = (
382 <Button
383 variant={ButtonVariant.plain}
384 aria-label={toggleAriaLabel}
385 aria-expanded={isExpanded}
386 icon={isExpanded ? <RhMicronsCloseIcon /> : <SearchIcon />}
387 onClick={onExpandHandler}
388 ref={searchInputExpandableToggleRef}
389 />
390 );
391
392 const onTransitionEnd = () => {
393 !isExpanded && focusAfterExpandChange && searchInputExpandableToggleRef?.current?.focus();
394 setFocusAfterExpandChange(false);
395 };
396
397 const expandableToggle = (
398 <>
399 {!hasAnimations && <InputGroupItem isPlain>{singleButtonToggle}</InputGroupItem>}
400 {hasAnimations && (
401 <>
402 <InputGroupItem
403 className={inputGroupStyles.modifiers.searchExpand}
404 isPlain
405 onTransitionEnd={onTransitionEnd}
406 {...(isExpanded && { inert: '' })}
407 >
408 {expandToggleButton}
409 </InputGroupItem>
410 <InputGroupItem
411 className={inputGroupStyles.modifiers.searchAction}
412 isPlain
413 {...(!isExpanded && { inert: '' })}
414 >
415 {collapseToggleButton}
416 </InputGroupItem>
417 </>
418 )}
419 </>
420 );
421
422 const buildExpandableSearchInput = ({ ...searchInputProps }: any = {}) => (
423 <InputGroup {...searchInputProps}>
424 <InputGroupItem
425 {...(!hasAnimations && { isFill: true })}
426 {...(hasAnimations && { className: inputGroupStyles.modifiers.searchInput })}
427 {...(!isExpanded && {
428 inert: ''
429 })}
430 >
431 {buildTextInputGroup()}
432 </InputGroupItem>
433 {expandableToggle}
434 </InputGroup>
435 );
436
437 const buildSearchTextInputGroup = ({ ...searchInputProps } = {}) => {
438 if (expandableInput) {
439 return buildExpandableSearchInput({ ...searchInputProps });
440 }
441
442 return buildTextInputGroup({ ...searchInputProps });
443 };
444
445 const buildSearchTextInputGroupWithExtraButtons = ({ ...searchInputProps } = {}) => (
446 <InputGroup ref={triggerRef} {...searchInputProps}>
447 <InputGroupItem
448 {...(!hasAnimations && { isFill: true })}
449 {...(expandableInput && hasAnimations && { className: inputGroupStyles.modifiers.searchInput })}
450 {...(expandableInput &&
451 hasAnimations &&
452 !isExpanded && {
453 inert: ''
454 })}
455 >
456 {buildTextInputGroup()}
457 </InputGroupItem>
458 {(attributes.length > 0 || onToggleAdvancedSearch) && (
459 <InputGroupItem isPlain {...(hasAnimations && { className: inputGroupStyles.modifiers.searchAction })}>
460 <Button
461 className={isSearchMenuOpen && 'pf-m-expanded'}
462 variant={ButtonVariant.control}
463 aria-label={openMenuButtonAriaLabel}
464 onClick={onToggle}
465 isDisabled={isDisabled}
466 aria-expanded={isSearchMenuOpen}
467 icon={<RhMicronsCaretDownFillIcon />}
468 />
469 </InputGroupItem>
470 )}
471 {!!onSearch && (
472 <InputGroupItem {...(hasAnimations && { className: inputGroupStyles.modifiers.searchAction })}>
473 <Button
474 type="submit"
475 variant={ButtonVariant.control}
476 aria-label={submitSearchButtonLabel}
477 onClick={onSearchHandler}
478 isDisabled={isDisabled}
479 icon={
480 <Icon shouldMirrorRTL>
481 <RhMicronsCaretRightIcon />
482 </Icon>
483 }
484 />
485 </InputGroupItem>
486 )}
487 {expandableInput && <InputGroupItem>{expandableToggle}</InputGroupItem>}
488 </InputGroup>
489 );
490
491 const searchInputProps = {
492 ...props,
493 className: css(
494 expandableInput && hasAnimations && inputGroupStyles.modifiers.searchExpandable,
495 expandableInput && hasAnimations && isExpanded && inputGroupStyles.modifiers.expanded,
496 className && css(className)
497 ),
498 innerRef: searchInputRef
499 };
500
501 if (!!expandableInput && !isExpanded && !hasAnimations) {
502 return (
503 <InputGroup {...searchInputProps}>
504 <InputGroupItem>{expandableToggle}</InputGroupItem>
505 </InputGroup>
506 );
507 }
508
509 if (!!onSearch || attributes.length > 0 || !!onToggleAdvancedSearch) {
510 if (attributes.length > 0) {
511 const AdvancedSearch = (
512 <div ref={popperRef}>
513 <AdvancedSearchMenu
514 value={value}
515 parentRef={searchInputRef}
516 parentInputRef={searchInputInputRef}
517 onSearch={onSearch}
518 onClear={onClear}
519 onChange={onChange}
520 onToggleAdvancedMenu={onToggle}
521 resetButtonLabel={resetButtonLabel}
522 submitSearchButtonLabel={submitSearchButtonLabel}
523 attributes={attributes}
524 formAdditionalItems={formAdditionalItems}
525 hasWordsAttrLabel={hasWordsAttrLabel}
526 advancedSearchDelimiter={advancedSearchDelimiter}
527 getAttrValueMap={getAttrValueMap}
528 isSearchMenuOpen={isSearchMenuOpen}
529 />
530 </div>
531 );
532
533 const advancedSearchInputProps = hasAnimations
534 ? {
535 className: css(
536 expandableInput && inputGroupStyles.modifiers.searchExpandable,
537 expandableInput && isExpanded && inputGroupStyles.modifiers.expanded
538 )
539 }
540 : {};
541
542 const AdvancedSearchWithPopper = (
543 <div className={css(className)} ref={searchInputRef} {...props}>
544 <Popper
545 trigger={buildSearchTextInputGroupWithExtraButtons(advancedSearchInputProps)}
546 triggerRef={triggerRef}
547 popper={AdvancedSearch}
548 popperRef={popperRef}
549 isVisible={isSearchMenuOpen}
550 enableFlip={true}
551 appendTo={() => appendTo || searchInputRef.current}
552 zIndex={zIndex}
553 />
554 </div>
555 );
556
557 const AdvancedSearchInline = (
558 <div className={css(className)} ref={searchInputRef} {...props}>
559 {buildSearchTextInputGroupWithExtraButtons(advancedSearchInputProps)}
560 {AdvancedSearch}
561 </div>
562 );
563
564 return appendTo !== 'inline' ? AdvancedSearchWithPopper : AdvancedSearchInline;
565 }
566 return buildSearchTextInputGroupWithExtraButtons({ ...searchInputProps });
567 }
568 return buildSearchTextInputGroup(searchInputProps);
569 };
570 SearchInputBase.displayName = 'SearchInputBase';
571
572 export const SearchInput = forwardRef((props: SearchInputProps, ref: React.Ref<HTMLInputElement>) => (
573 <SearchInputBase {...props} innerRef={ref as React.MutableRefObject<any>} />
574 ));
575 SearchInput.displayName = 'SearchInput';