FrontPastel/node_modules/@mui/base/node/utils/useTextNavigation.js

42 lines
2.2 KiB
JavaScript
Raw Normal View History

2024-04-17 13:55:11 +00:00
"use strict";
'use client';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useTextNavigation = useTextNavigation;
var React = _interopRequireWildcard(require("react"));
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
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]);
}