@carbon/ibm-products
Version:
Carbon for IBM Products
44 lines (42 loc) • 1.29 kB
JavaScript
/**
* Copyright IBM Corp. 2020, 2026
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
require("../../../_virtual/_rolldown/runtime.js");
let react = require("react");
//#region src/components/AddSelect/hooks/useFocus.js
/**
* Copyright IBM Corp. 2024
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
const useFocus = (size) => {
const [currentFocus, setCurrentFocus] = (0, react.useState)("");
const handleKeyDown = (0, react.useCallback)((e) => {
const focus = currentFocus === "" ? 0 : currentFocus;
if (e.keyCode === 40) {
e.preventDefault();
setCurrentFocus(focus === size - 1 ? 0 : focus + 1);
} else if (e.keyCode === 38) {
e.preventDefault();
setCurrentFocus(focus === 0 ? size - 1 : focus - 1);
}
}, [
size,
currentFocus,
setCurrentFocus
]);
(0, react.useEffect)(() => {
const el = document.querySelector("#add-select-focus");
el.addEventListener("keydown", handleKeyDown, false);
return () => {
el.removeEventListener("keydown", handleKeyDown, false);
};
}, [handleKeyDown]);
return [currentFocus, setCurrentFocus];
};
//#endregion
exports.default = useFocus;