UNPKG

@wordpress/components

Version:
49 lines (48 loc) • 1.94 kB
import removeAccents from "remove-accents"; import { debounce } from "@wordpress/compose"; import { useLayoutEffect, useState } from "@wordpress/element"; import { escapeRegExp } from "../utils/strings.mjs"; // packages/components/src/autocomplete/get-default-use-items.tsx function filterOptions(search, options = [], maxResults = 10) { const filtered = []; for (let i = 0; i < options.length; i++) { const option = options[i]; let { keywords = [] } = option; if ("string" === typeof option.label) keywords = [...keywords, option.label]; if (!keywords.some((keyword) => search.test(removeAccents(keyword)))) continue; filtered.push(option); if (filtered.length === maxResults) break; } return filtered; } function getDefaultUseItems(autocompleter) { return (filterValue) => { const [items, setItems] = useState([]); useLayoutEffect(() => { let isCanceled = false; const { options, isDebounced } = autocompleter; const loadOptions = debounce(() => { return Promise.resolve(typeof options === "function" ? options(filterValue) : options).then((optionsData) => { if (isCanceled) return; const keyedOptions = optionsData.map((optionData, optionIndex) => ({ key: `${autocompleter.name}-${optionIndex}`, value: optionData, label: autocompleter.getOptionLabel(optionData), keywords: autocompleter.getOptionKeywords ? autocompleter.getOptionKeywords(optionData) : [], isDisabled: autocompleter.isOptionDisabled ? autocompleter.isOptionDisabled(optionData) : false })); const search = new RegExp("(?:\\b|\\s|^)" + escapeRegExp(filterValue), "i"); setItems(filterOptions(search, keyedOptions)); }); }, isDebounced ? 250 : 0); loadOptions(); return () => { isCanceled = true; loadOptions.cancel(); }; }, [filterValue]); return [items]; }; } export { getDefaultUseItems as default }; //# sourceMappingURL=get-default-use-items.mjs.map