UNPKG

1.34 kBJavaScriptView Raw
1import * as React from 'react';
2const TEXT_NAVIGATION_RESET_TIMEOUT = 500; // milliseconds
3
4/**
5 * @ignore - internal hook.
6 *
7 * Provides a handler for text navigation.
8 * It's used to navigate a list by typing the first letters of the options.
9 *
10 * @param callback A function to be called when the navigation should be performed.
11 * @returns A function to be used in a keydown event handler.
12 */
13export default function useTextNavigation(callback) {
14 const textCriteriaRef = React.useRef({
15 searchString: '',
16 lastTime: null
17 });
18 return React.useCallback(event => {
19 if (event.key.length === 1 && event.key !== ' ') {
20 const textCriteria = textCriteriaRef.current;
21 const lowerKey = event.key.toLowerCase();
22 const currentTime = performance.now();
23 if (textCriteria.searchString.length > 0 && textCriteria.lastTime && currentTime - textCriteria.lastTime > TEXT_NAVIGATION_RESET_TIMEOUT) {
24 textCriteria.searchString = lowerKey;
25 } else if (textCriteria.searchString.length !== 1 || lowerKey !== textCriteria.searchString) {
26 // If there is just one character in the buffer and the key is the same, do not append
27 textCriteria.searchString += lowerKey;
28 }
29 textCriteria.lastTime = currentTime;
30 callback(textCriteria.searchString, event);
31 }
32 }, [callback]);
33}
\No newline at end of file