UNPKG

@wordpress/compose

Version:
80 lines (68 loc) 1.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _keycodes = require("@wordpress/keycodes"); var _dom = require("@wordpress/dom"); var _element = require("@wordpress/element"); /** * WordPress dependencies */ /** * In Dialogs/modals, the tabbing must be constrained to the content of * the wrapper element. This hook adds the behavior to the returned ref. * * @return {Object|Function} Element Ref. * * @example * ```js * import { useConstrainedTabbing } from '@wordpress/compose'; * * const ConstrainedTabbingExample = () => { * const constrainedTabbingRef = useConstrainedTabbing() * return ( * <div ref={ constrainedTabbingRef }> * <Button /> * <Button /> * </div> * ); * } * ``` */ function useConstrainedTabbing() { const ref = (0, _element.useCallback)(node => { if (!node) { return; } node.addEventListener('keydown', event => { if (event.keyCode !== _keycodes.TAB) { return; } const tabbables = _dom.focus.tabbable.find(node); if (!tabbables.length) { return; } const firstTabbable = tabbables[0]; const lastTabbable = tabbables[tabbables.length - 1]; if (event.shiftKey && event.target === firstTabbable) { event.preventDefault(); lastTabbable.focus(); } else if (!event.shiftKey && event.target === lastTabbable) { event.preventDefault(); firstTabbable.focus(); /* * When pressing Tab and none of the tabbables has focus, the keydown * event happens on the wrapper div: move focus on the first tabbable. */ } else if (!tabbables.includes(event.target)) { event.preventDefault(); firstTabbable.focus(); } }); }, []); return ref; } var _default = useConstrainedTabbing; exports.default = _default; //# sourceMappingURL=index.js.map