UNPKG

@wordpress/compose

Version:
59 lines (58 loc) 1.86 kB
// packages/compose/src/hooks/use-focus-on-mount/index.js import { useRef, useEffect } from "@wordpress/element"; import { focus } from "@wordpress/dom"; import useRefEffect from "../use-ref-effect"; function useFocusOnMount(focusOnMount = "firstElement") { const focusOnMountRef = useRef(focusOnMount); const setFocus = (target) => { target.focus({ // When focusing newly mounted dialogs, // the position of the popover is often not right on the first render // This prevents the layout shifts when focusing the dialogs. preventScroll: true }); }; const timerIdRef = useRef(); useEffect(() => { focusOnMountRef.current = focusOnMount; }, [focusOnMount]); return useRefEffect((node) => { if (!node || focusOnMountRef.current === false) { return; } if (node.contains(node.ownerDocument?.activeElement ?? null)) { return; } if (focusOnMountRef.current !== "firstElement" && focusOnMountRef.current !== "firstInputElement") { setFocus(node); return; } timerIdRef.current = setTimeout(() => { if (focusOnMountRef.current === "firstInputElement") { let formInput = null; if (typeof window !== "undefined" && node instanceof window.Element) { formInput = node.querySelector( 'input:not([type="hidden"]):not([disabled]), select:not([disabled]), textarea:not([disabled])' ); } if (formInput) { setFocus(formInput); return; } } const firstTabbable = focus.tabbable.find(node)[0]; if (firstTabbable) { setFocus(firstTabbable); } }, 0); return () => { if (timerIdRef.current) { clearTimeout(timerIdRef.current); } }; }, []); } export { useFocusOnMount as default }; //# sourceMappingURL=index.js.map