-
Notifications
You must be signed in to change notification settings - Fork 4k
/
index.js
84 lines (73 loc) · 1.92 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* WordPress dependencies
*/
import { useRef, useEffect, useCallback } from '@wordpress/element';
import { focus } from '@wordpress/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 '@wordpress/compose';
*
* const WithFocusOnMount = () => {
* const ref = useFocusOnMount()
* return (
* <div ref={ ref }>
* <Button />
* <Button />
* </div>
* );
* }
* ```
*/
export default function useFocusOnMount( focusOnMount = 'firstElement' ) {
const focusOnMountRef = useRef( focusOnMount );
/**
* Sets focus on a DOM element.
*
* @param {HTMLElement} target The DOM element to set focus to.
* @return {void}
*/
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,
} );
};
/** @type {import('react').MutableRefObject<ReturnType<setTimeout> | undefined>} */
const timerId = useRef();
useEffect( () => {
focusOnMountRef.current = focusOnMount;
}, [ focusOnMount ] );
useEffect( () => {
return () => {
if ( timerId.current ) {
clearTimeout( timerId.current );
}
};
}, [] );
return useCallback( ( node ) => {
if ( ! node || focusOnMountRef.current === false ) {
return;
}
if ( node.contains( node.ownerDocument?.activeElement ?? null ) ) {
return;
}
if ( focusOnMountRef.current === 'firstElement' ) {
timerId.current = setTimeout( () => {
const firstTabbable = focus.tabbable.find( node )[ 0 ];
if ( firstTabbable ) {
setFocus( firstTabbable );
}
}, 0 );
return;
}
setFocus( node );
}, [] );
}