import { useRef, useState } from "react"; import { Autocomplete, AutocompleteProps } from "./Autocomplete"; import { Option, OptionLike } from "../select-legacy"; import { useIsomorphicLayoutEffect } from "../../hooks"; import { getOptionLabel } from "./util"; // eslint-disable-next-line @typescript-eslint/no-empty-object-type interface Props extends Omit< AutocompleteProps, "searchValue" | "onChangeSearchValue" | "loading" | "clearSearchButton" | "selectOnFocus" > {} export function SimpleAutocomplete({ options, selection = null, onChangeSelection, ...rest }: Props) { const [searchValue, setSearchValue] = useState(selection ? getOptionLabel(selection) : ""); const searchValueRef = useRef(searchValue); searchValueRef.current = searchValue; const inputRef = useRef(null!); // side effect, update the searchValue value when // selection come from outside useIsomorphicLayoutEffect(() => { if (selection === null) { if (document.activeElement !== inputRef.current) { setSearchValue(""); } return; } // we need the fresh value of searchValue but we don't // want searchValue as useEffect dependency const selectionLabel = getOptionLabel(selection); if (searchValueRef.current !== getOptionLabel(selection)) { setSearchValue(selectionLabel); } }, [selection, setSearchValue]); const filteredOptions = selection !== null ? [] : options.filter((option) => { const optionLabel = getOptionLabel(option); return optionLabel.toLowerCase().startsWith(searchValue.toLowerCase()); }); return ( ); }