({
name,
isLoading,
options,
label,
onChange,
onSelect,
onBlur: onBlurProp,
selectedValue,
defaultValue,
resetOnBlur = true,
...restProps
}: AutocompleteProps)
| 24 | } |
| 25 | |
| 26 | const Autocomplete = ({ |
| 27 | name, |
| 28 | isLoading, |
| 29 | options, |
| 30 | label, |
| 31 | onChange, |
| 32 | onSelect, |
| 33 | onBlur: onBlurProp, |
| 34 | selectedValue, |
| 35 | defaultValue, |
| 36 | resetOnBlur = true, |
| 37 | ...restProps |
| 38 | }: AutocompleteProps) => { |
| 39 | const [input, setInput] = useState(defaultValue || ''); |
| 40 | const [isFocused, setIsFocused] = useState(false); |
| 41 | const inputRef = useRef<HTMLInputElement | null>(null); |
| 42 | const [selectedOption, setSelectedOption] = useState(undefined); |
| 43 | |
| 44 | /* |
| 45 | To prevent flickering of the selected option image as the user types. |
| 46 | We want to set the selected option only when the selected value changes or the user clears the selected value. |
| 47 | */ |
| 48 | useEffect(() => { |
| 49 | if (!selectedValue) { |
| 50 | setSelectedOption(undefined); |
| 51 | return; |
| 52 | } |
| 53 | if (selectedOption?.value !== selectedValue) { |
| 54 | setSelectedOption(options.find((opt) => opt.value === selectedValue)); |
| 55 | } |
| 56 | }, [selectedValue, options, selectedOption]); |
| 57 | |
| 58 | const handleChange = (val: string) => { |
| 59 | setInput(val); |
| 60 | onChange(val); |
| 61 | }; |
| 62 | |
| 63 | const handleSelect = (opt: AutocompleteOption) => { |
| 64 | setInput(opt.label); |
| 65 | onSelect(opt.value); |
| 66 | setIsFocused(false); |
| 67 | inputRef.current?.focus(); |
| 68 | }; |
| 69 | const handleBlur = () => { |
| 70 | setIsFocused(false); |
| 71 | if (resetOnBlur) { |
| 72 | setInput(options.find((opt) => opt.value === selectedValue)?.label || ''); |
| 73 | } |
| 74 | onBlurProp?.(); |
| 75 | }; |
| 76 | |
| 77 | const isSecondaryField = restProps.fieldType === 'secondary'; |
| 78 | |
| 79 | return ( |
| 80 | <div className="flex flex-col gap-2"> |
| 81 | {!isSecondaryField && ( |
| 82 | <Typography type={TypographyType.Callout} bold> |
| 83 | {label} |
nothing calls this directly
no test coverage detected