UNPKG

@wordpress/compose

Version:
40 lines (39 loc) 1.27 kB
// packages/compose/src/hooks/use-constrained-tabbing/index.ts import { focus } from "@wordpress/dom"; import useRefEffect from "../use-ref-effect/index.mjs"; function useConstrainedTabbing() { return useRefEffect((node) => { function onKeyDown(event) { const { key, shiftKey, target } = event; if (key !== "Tab") { return; } const action = shiftKey ? "findPrevious" : "findNext"; const nextElement = focus.tabbable[action](target) || null; if (target.contains(nextElement)) { event.preventDefault(); nextElement?.focus(); return; } if (node.contains(nextElement)) { return; } const domAction = shiftKey ? "append" : "prepend"; const { ownerDocument } = node; const trap = ownerDocument.createElement("div"); trap.tabIndex = -1; node[domAction](trap); trap.addEventListener("blur", () => node.removeChild(trap)); trap.focus(); } node.addEventListener("keydown", onKeyDown); return () => { node.removeEventListener("keydown", onKeyDown); }; }, []); } var use_constrained_tabbing_default = useConstrainedTabbing; export { use_constrained_tabbing_default as default }; //# sourceMappingURL=index.mjs.map