UNPKG

@gechiui/compose

Version:
56 lines (48 loc) 1.3 kB
/** * GeChiUI dependencies */ import { useRef, useEffect, useCallback } from '@gechiui/element'; import { focus } from '@gechiui/dom'; /** * Hook used to focus the first tabbable element on mount. * * @param {boolean | 'firstElement'} focusOnMount Focus on mount mode. * @return {import('react').RefCallback<HTMLElement>} Ref callback. * * @example * ```js * import { useFocusOnMount } from '@gechiui/compose'; * * const WithFocusOnMount = () => { * const ref = useFocusOnMount() * return ( * <div ref={ ref }> * <Button /> * <Button /> * </div> * ); * } * ``` */ export default function useFocusOnMount( focusOnMount = 'firstElement' ) { const focusOnMountRef = useRef( focusOnMount ); useEffect( () => { focusOnMountRef.current = focusOnMount; }, [ focusOnMount ] ); return useCallback( ( node ) => { if ( ! node || focusOnMountRef.current === false ) { return; } if ( node.contains( node.ownerDocument?.activeElement ?? null ) ) { return; } let target = node; if ( focusOnMountRef.current === 'firstElement' ) { const firstTabbable = focus.tabbable.find( node )[ 0 ]; if ( firstTabbable ) { target = /** @type {HTMLElement} */ ( firstTabbable ); } } target.focus(); }, [] ); }