@mui/base
Version:
A library of headless ('unstyled') React UI components and low-level hooks.
41 lines (39 loc) • 2.58 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useTextNavigation;
var React = _interopRequireWildcard(require("react"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const TEXT_NAVIGATION_RESET_TIMEOUT = 500; // milliseconds
/**
* @ignore - internal hook.
*
* Provides a handler for text navigation.
* It's used to navigate a list by typing the first letters of the options.
*
* @param callback A function to be called when the navigation should be performed.
* @returns A function to be used in a keydown event handler.
*/
function useTextNavigation(callback) {
const textCriteriaRef = React.useRef({
searchString: '',
lastTime: null
});
return React.useCallback(event => {
if (event.key.length === 1 && event.key !== ' ') {
const textCriteria = textCriteriaRef.current;
const lowerKey = event.key.toLowerCase();
const currentTime = performance.now();
if (textCriteria.searchString.length > 0 && textCriteria.lastTime && currentTime - textCriteria.lastTime > TEXT_NAVIGATION_RESET_TIMEOUT) {
textCriteria.searchString = lowerKey;
} else if (textCriteria.searchString.length !== 1 || lowerKey !== textCriteria.searchString) {
// If there is just one character in the buffer and the key is the same, do not append
textCriteria.searchString += lowerKey;
}
textCriteria.lastTime = currentTime;
callback(textCriteria.searchString, event);
}
}, [callback]);
}
;