UNPKG

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