UNPKG

@wordpress/compose

Version:
64 lines (54 loc) 1.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useFocusOnMount; var _element = require("@wordpress/element"); var _dom = require("@wordpress/dom"); /** * WordPress dependencies */ /** * Hook used to focus the first tabbable element on mount. * * @param {boolean|string} focusOnMount Focus on mount mode. * @return {Function} Ref callback. * * @example * ```js * import { useFocusOnMount } from '@wordpress/compose'; * * const WithFocusOnMount = () => { * const ref = useFocusOnMount() * return ( * <div ref={ ref }> * <Button /> * <Button /> * </div> * ); * } * ``` */ function useFocusOnMount(focusOnMount = 'firstElement') { const focusOnMountRef = (0, _element.useRef)(focusOnMount); (0, _element.useEffect)(() => { focusOnMountRef.current = focusOnMount; }, [focusOnMount]); return (0, _element.useCallback)(node => { if (!node || focusOnMountRef.current === false) { return; } if (node.contains(node.ownerDocument.activeElement)) { return; } let target = node; if (focusOnMountRef.current === 'firstElement') { const firstTabbable = _dom.focus.tabbable.find(node)[0]; if (firstTabbable) { target = firstTabbable; } } target.focus(); }, []); } //# sourceMappingURL=index.js.map