| 1 |
import { useEffect, useRef, useState } from 'react'; |
| 2 |
import { Button } from '../Button'; |
| 3 |
import { ActionGroup, Form, FormGroup } from '../Form'; |
| 4 |
import { TextInput } from '../TextInput'; |
| 5 |
import { useSSRSafeId } from '../../helpers'; |
| 6 |
import { SearchInputSearchAttribute } from './SearchInput'; |
| 7 |
import { Panel, PanelMain, PanelMainBody } from '../Panel'; |
| 8 |
import { css } from '@patternfly/react-styles'; |
| 9 |
|
| 10 |
export interface AdvancedSearchMenuProps extends Omit<React.HTMLProps<HTMLDivElement>, 'onChange'> { |
| 11 |
/** Delimiter in the query string for pairing attributes with search values. |
| 12 |
* Required whenever attributes are passed as props. |
| 13 |
*/ |
| 14 |
advancedSearchDelimiter?: string; |
| 15 |
/** Array of attribute values used for dynamically generated advanced search. */ |
| 16 |
attributes?: string[] | SearchInputSearchAttribute[]; |
| 17 |
/** Additional classes added to the advanced search menu. */ |
| 18 |
className?: string; |
| 19 |
/* Additional elements added after the attributes in the form. |
| 20 |
* The new form elements can be wrapped in a form group component for automatic formatting. */ |
| 21 |
formAdditionalItems?: React.ReactNode; |
| 22 |
/** Function which builds an attribute-value map by parsing the value in the search input. */ |
| 23 |
getAttrValueMap?: () => { [key: string]: string }; |
| 24 |
/** Attribute label for strings unassociated with one of the provided listed attributes. */ |
| 25 |
hasWordsAttrLabel?: React.ReactNode; |
| 26 |
/** Flag for toggling the open/close state of the advanced search menu. */ |
| 27 |
isSearchMenuOpen?: boolean; |
| 28 |
/** A callback for when the input value changes. */ |
| 29 |
onChange?: (event: React.FormEvent<HTMLInputElement>, value: string) => void; |
| 30 |
/** A callback for when the user clicks the clear button. */ |
| 31 |
onClear?: (event: React.SyntheticEvent<HTMLButtonElement>) => void; |
| 32 |
/** A callback for when the search button is clicked. */ |
| 33 |
onSearch?: ( |
| 34 |
event: React.SyntheticEvent<HTMLButtonElement>, |
| 35 |
value: string, |
| 36 |
attrValueMap: { [key: string]: string } |
| 37 |
) => void; |
| 38 |
/** A callback for when the open advanced search button is clicked. */ |
| 39 |
onToggleAdvancedMenu?: (e: React.SyntheticEvent<HTMLButtonElement>) => void; |
| 40 |
/** Ref of the input element within the search input. */ |
| 41 |
parentInputRef?: React.RefObject<any>; |
| 42 |
/** Ref of the div wrapping the whole search input. */ |
| 43 |
parentRef?: React.RefObject<any>; |
| 44 |
/** Label for the button which resets the advanced search form and clears the search input. */ |
| 45 |
resetButtonLabel?: string; |
| 46 |
/** Label for the button which calls the onSearch event handler. */ |
| 47 |
submitSearchButtonLabel?: string; |
| 48 |
/** Value of the search input. */ |
| 49 |
value?: string; |
| 50 |
} |
| 51 |
|
| 52 |
export const AdvancedSearchMenu: React.FunctionComponent<AdvancedSearchMenuProps> = ({ |
| 53 |
className, |
| 54 |
parentRef, |
| 55 |
parentInputRef, |
| 56 |
value = '', |
| 57 |
attributes = [] as string[], |
| 58 |
formAdditionalItems, |
| 59 |
hasWordsAttrLabel = 'Has words', |
| 60 |
advancedSearchDelimiter, |
| 61 |
getAttrValueMap, |
| 62 |
onChange, |
| 63 |
onSearch, |
| 64 |
onClear, |
| 65 |
resetButtonLabel = 'Reset', |
| 66 |
submitSearchButtonLabel = 'Search', |
| 67 |
isSearchMenuOpen, |
| 68 |
onToggleAdvancedMenu |
| 69 |
}: AdvancedSearchMenuProps) => { |
| 70 |
const hasWordsId = useSSRSafeId(); |
| 71 |
const firstAttrRef = useRef(null); |
| 72 |
const [putFocusBackOnInput, setPutFocusBackOnInput] = useState(false); |
| 73 |
|
| 74 |
useEffect(() => { |
| 75 |
if (attributes.length > 0 && !advancedSearchDelimiter) { |
| 76 |
// eslint-disable-next-line no-console |
| 77 |
console.error( |
| 78 |
'AdvancedSearchMenu: An advancedSearchDelimiter prop is required when advanced search attributes are provided using the attributes prop' |
| 79 |
); |
| 80 |
} |
| 81 |
}); |
| 82 |
|
| 83 |
useEffect(() => { |
| 84 |
if (isSearchMenuOpen && firstAttrRef && firstAttrRef.current) { |
| 85 |
firstAttrRef.current.focus(); |
| 86 |
setPutFocusBackOnInput(true); |
| 87 |
} else if (!isSearchMenuOpen && putFocusBackOnInput && parentInputRef && parentInputRef.current) { |
| 88 |
parentInputRef.current.focus(); |
| 89 |
} |
| 90 |
}, [isSearchMenuOpen]); |
| 91 |
|
| 92 |
useEffect(() => { |
| 93 |
const onDocClick = (event: Event) => { |
| 94 |
const clickedWithinSearchInput = parentRef && parentRef.current.contains(event.target as Node); |
| 95 |
if (isSearchMenuOpen && !clickedWithinSearchInput) { |
| 96 |
onToggleAdvancedMenu(event as any); |
| 97 |
} |
| 98 |
}; |
| 99 |
|
| 100 |
const onEscPress = (event: KeyboardEvent) => { |
| 101 |
if (event.key === 'Escape' && isSearchMenuOpen) { |
| 102 |
onToggleAdvancedMenu(event as any); |
| 103 |
} |
| 104 |
}; |
| 105 |
|
| 106 |
document.addEventListener('mousedown', onDocClick); |
| 107 |
document.addEventListener('touchstart', onDocClick); |
| 108 |
document.addEventListener('keydown', onEscPress); |
| 109 |
|
| 110 |
return function cleanup() { |
| 111 |
document.removeEventListener('mousedown', onDocClick); |
| 112 |
document.removeEventListener('touchstart', onDocClick); |
| 113 |
document.removeEventListener('keydown', onEscPress); |
| 114 |
}; |
| 115 |
}, [isSearchMenuOpen, parentRef, onToggleAdvancedMenu]); |
| 116 |
|
| 117 |
const onSearchHandler = (event: React.SyntheticEvent<HTMLButtonElement>) => { |
| 118 |
event.preventDefault(); |
| 119 |
if (onSearch) { |
| 120 |
onSearch(event, value, getAttrValueMap()); |
| 121 |
} |
| 122 |
if (isSearchMenuOpen) { |
| 123 |
onToggleAdvancedMenu(event as any); |
| 124 |
} |
| 125 |
}; |
| 126 |
|
| 127 |
const handleValueChange = (attribute: string, newValue: string, event: React.FormEvent<HTMLInputElement>) => { |
| 128 |
const newMap = getAttrValueMap(); |
| 129 |
|
| 130 |
newMap[attribute] = newValue; |
| 131 |
let updatedValue = ''; |
| 132 |
Object.entries(newMap).forEach(([k, v]) => { |
| 133 |
if (v.trim() !== '') { |
| 134 |
/* Wrap the value in quotes if it contains spaces */ |
| 135 |
const quoteWrappedValue = v.includes(' ') ? `'${v.replace(/(^'|'$)/g, '')}'` : v; |
| 136 |
|
| 137 |
if (k !== 'haswords') { |
| 138 |
updatedValue = `${updatedValue} ${k}${advancedSearchDelimiter}${quoteWrappedValue}`; |
| 139 |
} else { |
| 140 |
updatedValue = `${updatedValue} ${quoteWrappedValue}`; |
| 141 |
} |
| 142 |
} |
| 143 |
}); |
| 144 |
|
| 145 |
if (onChange) { |
| 146 |
onChange(event, updatedValue.replace(/^\s+/g, '')); |
| 147 |
} |
| 148 |
}; |
| 149 |
|
| 150 |
const getValue = (attribute: string) => { |
| 151 |
const map = getAttrValueMap(); |
| 152 |
return map.hasOwnProperty(attribute) ? map[attribute] : ''; |
| 153 |
}; |
| 154 |
|
| 155 |
const buildFormGroups = () => { |
| 156 |
const formGroups = [] as React.ReactNode[]; |
| 157 |
attributes.forEach((attribute: string | SearchInputSearchAttribute, index: number) => { |
| 158 |
const display = typeof attribute === 'string' ? attribute : attribute.display; |
| 159 |
const queryAttr = typeof attribute === 'string' ? attribute : attribute.attr; |
| 160 |
if (index === 0) { |
| 161 |
formGroups.push( |
| 162 |
<FormGroup label={display} fieldId={`${queryAttr}_${index}`} key={`${attribute}_${index}`}> |
| 163 |
<TextInput |
| 164 |
ref={firstAttrRef} |
| 165 |
type="text" |
| 166 |
id={`${queryAttr}_${index}`} |
| 167 |
value={getValue(queryAttr)} |
| 168 |
onChange={(evt, value) => handleValueChange(queryAttr, value, evt)} |
| 169 |
/> |
| 170 |
</FormGroup> |
| 171 |
); |
| 172 |
} else { |
| 173 |
formGroups.push( |
| 174 |
<FormGroup label={display} fieldId={`${queryAttr}_${index}`} key={`${attribute}_${index}`}> |
| 175 |
<TextInput |
| 176 |
type="text" |
| 177 |
id={`${queryAttr}_${index}`} |
| 178 |
value={getValue(queryAttr)} |
| 179 |
onChange={(evt, value) => handleValueChange(queryAttr, value, evt)} |
| 180 |
/> |
| 181 |
</FormGroup> |
| 182 |
); |
| 183 |
} |
| 184 |
}); |
| 185 |
formGroups.push( |
| 186 |
<FormGroup key="hasWords" label={hasWordsAttrLabel} fieldId={hasWordsId}> |
| 187 |
<TextInput |
| 188 |
type="text" |
| 189 |
id={hasWordsId} |
| 190 |
value={getValue('haswords')} |
| 191 |
onChange={(evt, value) => handleValueChange('haswords', value, evt)} |
| 192 |
/> |
| 193 |
</FormGroup> |
| 194 |
); |
| 195 |
return formGroups; |
| 196 |
}; |
| 197 |
|
| 198 |
return isSearchMenuOpen ? ( |
| 199 |
<Panel variant="raised" className={css(className)}> |
| 200 |
<PanelMain> |
| 201 |
<PanelMainBody> |
| 202 |
<Form> |
| 203 |
{buildFormGroups()} |
| 204 |
{formAdditionalItems ? formAdditionalItems : null} |
| 205 |
<ActionGroup> |
| 206 |
<Button variant="primary" type="submit" onClick={onSearchHandler} isDisabled={!value}> |
| 207 |
{submitSearchButtonLabel} |
| 208 |
</Button> |
| 209 |
{!!onClear && ( |
| 210 |
<Button variant="link" type="reset" onClick={onClear}> |
| 211 |
{resetButtonLabel} |
| 212 |
</Button> |
| 213 |
)} |
| 214 |
</ActionGroup> |
| 215 |
</Form> |
| 216 |
</PanelMainBody> |
| 217 |
</PanelMain> |
| 218 |
</Panel> |
| 219 |
) : null; |
| 220 |
}; |
| 221 |
AdvancedSearchMenu.displayName = 'SearchInput'; |