-
Notifications
You must be signed in to change notification settings - Fork 4k
/
index.js
193 lines (170 loc) · 5.71 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/**
* WordPress dependencies
*/
import { useCallback, useEffect, useRef } from '@wordpress/element';
/**
* Input types which are classified as button types, for use in considering
* whether element is a (focus-normalized) button.
*
* @type {string[]}
*/
const INPUT_BUTTON_TYPES = [ 'button', 'submit' ];
/**
* @typedef {HTMLButtonElement | HTMLLinkElement | HTMLInputElement} FocusNormalizedButton
*/
// Disable reason: Rule doesn't support predicate return types.
/* eslint-disable jsdoc/valid-types */
/**
* Returns true if the given element is a button element subject to focus
* normalization, or false otherwise.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus
*
* @param {EventTarget} eventTarget The target from a mouse or touch event.
*
* @return {eventTarget is FocusNormalizedButton} Whether element is a button.
*/
function isFocusNormalizedButton( eventTarget ) {
if ( ! ( eventTarget instanceof window.HTMLElement ) ) {
return false;
}
switch ( eventTarget.nodeName ) {
case 'A':
case 'BUTTON':
return true;
case 'INPUT':
return INPUT_BUTTON_TYPES.includes(
/** @type {HTMLInputElement} */ ( eventTarget ).type
);
}
return false;
}
/* eslint-enable jsdoc/valid-types */
/**
* @typedef {import('react').SyntheticEvent} SyntheticEvent
*/
/**
* @callback EventCallback
* @param {SyntheticEvent} event input related event.
*/
/**
* @typedef FocusOutsideReactElement
* @property {EventCallback} handleFocusOutside callback for a focus outside event.
*/
/**
* @typedef {import('react').MutableRefObject<FocusOutsideReactElement | undefined>} FocusOutsideRef
*/
/**
* @typedef {Object} FocusOutsideReturnValue
* @property {EventCallback} onFocus An event handler for focus events.
* @property {EventCallback} onBlur An event handler for blur events.
* @property {EventCallback} onMouseDown An event handler for mouse down events.
* @property {EventCallback} onMouseUp An event handler for mouse up events.
* @property {EventCallback} onTouchStart An event handler for touch start events.
* @property {EventCallback} onTouchEnd An event handler for touch end events.
*/
/**
* A react hook that can be used to check whether focus has moved outside the
* element the event handlers are bound to.
*
* @param {EventCallback} onFocusOutside A callback triggered when focus moves outside
* the element the event handlers are bound to.
*
* @return {FocusOutsideReturnValue} An object containing event handlers. Bind the event handlers
* to a wrapping element element to capture when focus moves
* outside that element.
*/
export default function useFocusOutside( onFocusOutside ) {
const currentOnFocusOutside = useRef( onFocusOutside );
useEffect( () => {
currentOnFocusOutside.current = onFocusOutside;
}, [ onFocusOutside ] );
const preventBlurCheck = useRef( false );
/**
* @type {import('react').MutableRefObject<number | undefined>}
*/
const blurCheckTimeoutId = useRef();
/**
* Cancel a blur check timeout.
*/
const cancelBlurCheck = useCallback( () => {
clearTimeout( blurCheckTimeoutId.current );
}, [] );
// Cancel blur checks on unmount.
useEffect( () => {
return () => cancelBlurCheck();
}, [] );
// Cancel a blur check if the callback or ref is no longer provided.
useEffect( () => {
if ( ! onFocusOutside ) {
cancelBlurCheck();
}
}, [ onFocusOutside, cancelBlurCheck ] );
/**
* Handles a mousedown or mouseup event to respectively assign and
* unassign a flag for preventing blur check on button elements. Some
* browsers, namely Firefox and Safari, do not emit a focus event on
* button elements when clicked, while others do. The logic here
* intends to normalize this as treating click on buttons as focus.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus
*/
const normalizeButtonFocus = useCallback(
/**
* @param {SyntheticEvent} event Event for mousedown or mouseup.
*/
( event ) => {
const { type, target } = event;
const isInteractionEnd = [ 'mouseup', 'touchend' ].includes( type );
if ( isInteractionEnd ) {
preventBlurCheck.current = false;
} else if ( isFocusNormalizedButton( target ) ) {
preventBlurCheck.current = true;
}
},
[]
);
/**
* A callback triggered when a blur event occurs on the element the handler
* is bound to.
*
* Calls the `onFocusOutside` callback in an immediate timeout if focus has
* move outside the bound element and is still within the document.
*/
const queueBlurCheck = useCallback(
/**
* @param {SyntheticEvent} event Blur event.
*/
( event ) => {
// React does not allow using an event reference asynchronously
// due to recycling behavior, except when explicitly persisted.
event.persist();
// Skip blur check if clicking button. See `normalizeButtonFocus`.
if ( preventBlurCheck.current ) {
return;
}
blurCheckTimeoutId.current = setTimeout( () => {
// If document is not focused then focus should remain
// inside the wrapped component and therefore we cancel
// this blur event thereby leaving focus in place.
// https://developer.mozilla.org/en-US/docs/Web/API/Document/hasFocus.
if ( ! document.hasFocus() ) {
event.preventDefault();
return;
}
if ( 'function' === typeof currentOnFocusOutside.current ) {
currentOnFocusOutside.current( event );
}
}, 0 );
},
[]
);
return {
onFocus: cancelBlurCheck,
onMouseDown: normalizeButtonFocus,
onMouseUp: normalizeButtonFocus,
onTouchStart: normalizeButtonFocus,
onTouchEnd: normalizeButtonFocus,
onBlur: queueBlurCheck,
};
}