UNPKG

@awsui/components-react

Version:

AWS UI is a collection of [React](https://reactjs.org/) components that help create intuitive, responsive, and accessible user experiences for web applications. It is developed by Amazon Web Services (AWS). This work is available under the terms of the [A

60 lines (59 loc) 2.55 kB
import { useCallback, useRef } from 'react'; import { KeyCode } from '../../../keycode'; import { filterOptions } from './filter-options'; import debounce from '../../../debounce'; export var isChar = function (keyCode) { return [0, KeyCode.enter, KeyCode.space, KeyCode.tab].indexOf(keyCode) === -1; }; export var isRepeatedChar = function (str) { var repeatedChar = Array.prototype.reduce.call(str, function (a, b) { return a === b ? b : null; }, str[0]); return Boolean(repeatedChar); }; export var useNativeSearch = function (_a) { var options = _a.options, isKeyboard = _a.isKeyboard, highlightOption = _a.highlightOption, highlightedOption = _a.highlightedOption, isInteractive = _a.isInteractive; var value = useRef(''); var delayedResetValue = useCallback(debounce(function () { value.current = ''; }, 500), [debounce, value]); var filter = useCallback(function (searchText) { return filterOptions(options, searchText, true).filter(function (option) { return option.type !== 'parent' && isInteractive(option); }); }, [options, isInteractive]); var handleNewValue = useCallback(function (newValue) { var matchingOptions = filter(newValue); if (matchingOptions.length === 1) { highlightOption(matchingOptions[0]); return; } if (newValue.length > 1 && isRepeatedChar(newValue)) { var matchingOptions_1 = filter(newValue[0]); if (matchingOptions_1.length > 0) { var active = matchingOptions_1 .map(function (_a) { var option = _a.option; return option.value; }) .indexOf(highlightedOption.value); active += 1; active = active % matchingOptions_1.length; highlightOption(matchingOptions_1[active]); return; } } if (matchingOptions.length > 0) { highlightOption(matchingOptions[0]); } }, [filter, highlightOption, isRepeatedChar, highlightedOption, highlightOption]); return useCallback(function (e) { isKeyboard.current = true; var charCode = e.charCode; if (!isChar(charCode)) { return; } delayedResetValue(); var newValue = value.current + String.fromCharCode(charCode); value.current = newValue; handleNewValue(newValue); }, [isKeyboard, isChar, delayedResetValue, handleNewValue]); };