-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathutils.ts
More file actions
197 lines (170 loc) · 7.77 KB
/
utils.ts
File metadata and controls
197 lines (170 loc) · 7.77 KB
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
194
195
196
197
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {FocusableElement} from '@react-types/shared';
import {focusWithoutScrolling} from '../utils/focusWithoutScrolling';
import {getActiveElement, getEventTarget, nodeContains} from '../utils/shadowdom/DOMFunctions';
import {getOwnerWindow, isShadowRoot} from '../utils/domHelpers';
import {isFocusable} from '../utils/isFocusable';
import {FocusEvent as ReactFocusEvent, SyntheticEvent, useCallback, useRef} from 'react';
import {useLayoutEffect} from '../utils/useLayoutEffect';
// Turn a native event into a React synthetic event.
export function createSyntheticEvent<E extends SyntheticEvent>(nativeEvent: Event): E {
let event = nativeEvent as any as E;
event.nativeEvent = nativeEvent;
event.isDefaultPrevented = () => event.defaultPrevented;
// cancelBubble is technically deprecated in the spec, but still supported in all browsers.
event.isPropagationStopped = () => (event as any).cancelBubble;
event.persist = () => {};
return event;
}
export function setEventTarget(event: Event, target: Element): void {
Object.defineProperty(event, 'target', {value: target});
Object.defineProperty(event, 'currentTarget', {value: target});
}
export function useSyntheticBlurEvent<Target extends Element = Element>(onBlur: (e: ReactFocusEvent<Target>) => void): (e: ReactFocusEvent<Target>) => void {
let stateRef = useRef({
isFocused: false,
observer: null as MutationObserver | null
});
// Clean up MutationObserver on unmount. See below.
useLayoutEffect(() => {
const state = stateRef.current;
return () => {
if (state.observer) {
state.observer.disconnect();
state.observer = null;
}
};
}, []);
// This function is called during a React onFocus event.
return useCallback((e: ReactFocusEvent<Target>) => {
// React does not fire onBlur when an element is disabled. https://github.com/facebook/react/issues/9142
// Most browsers fire a native focusout event in this case, except for Firefox. In that case, we use a
// MutationObserver to watch for the disabled attribute, and dispatch these events ourselves.
// For browsers that do, focusout fires before the MutationObserver, so onBlur should not fire twice.
let eventTarget = getEventTarget(e);
if (
eventTarget instanceof HTMLButtonElement ||
eventTarget instanceof HTMLInputElement ||
eventTarget instanceof HTMLTextAreaElement ||
eventTarget instanceof HTMLSelectElement
) {
stateRef.current.isFocused = true;
let target = eventTarget;
let onBlurHandler: EventListenerOrEventListenerObject | null = (e) => {
stateRef.current.isFocused = false;
if (target.disabled) {
// For backward compatibility, dispatch a (fake) React synthetic event.
let event = createSyntheticEvent<ReactFocusEvent<Target>>(e);
onBlur?.(event);
}
// We no longer need the MutationObserver once the target is blurred.
if (stateRef.current.observer) {
stateRef.current.observer.disconnect();
stateRef.current.observer = null;
}
};
target.addEventListener('focusout', onBlurHandler, {once: true});
stateRef.current.observer = new MutationObserver(() => {
if (stateRef.current.isFocused && target.disabled) {
stateRef.current.observer?.disconnect();
let relatedTargetEl = target === getActiveElement() ? null : getActiveElement();
target.dispatchEvent(new FocusEvent('blur', {relatedTarget: relatedTargetEl}));
target.dispatchEvent(new FocusEvent('focusout', {bubbles: true, relatedTarget: relatedTargetEl}));
}
});
stateRef.current.observer.observe(target, {attributes: true, attributeFilter: ['disabled']});
}
}, [onBlur]);
}
export let ignoreFocusEvent = false;
/**
* This function prevents the next focus event fired on `target`, without using `event.preventDefault()`.
* It works by waiting for the series of focus events to occur, and reverts focus back to where it was before.
* It also makes these events mostly non-observable by using a capturing listener on the window and stopping propagation.
*/
export function preventFocus(target: FocusableElement | null): (() => void) | undefined {
// The browser will focus the nearest focusable ancestor of our target.
while (target && !isFocusable(target)) {
target = target.parentElement;
}
let window = getOwnerWindow(target);
let activeElement = getActiveElement(window.document) as FocusableElement | null;
if (!activeElement || activeElement === target) {
return;
}
// Listen on the target's root (document or shadow root) so we catch focus events inside
// shadow DOM; they do not reach the main window.
let targetRoot = target?.getRootNode();
let root =
(targetRoot != null && isShadowRoot(targetRoot))
? targetRoot
: getOwnerWindow(target);
// Focus is "moving to target" when it moves to the button or to a descendant of the button
// (e.g. SVG icon)
let isFocusMovingToTarget = (focusTarget: Element | null) =>
focusTarget === target || (focusTarget != null && nodeContains(target, focusTarget));
// Blur/focusout events have their target as the element losing focus. Stop propagation when
// that is the previously focused element (activeElement) or a descendant (e.g. in shadow DOM).
let isBlurFromActiveElement = (eventTarget: Element | null) =>
eventTarget === activeElement ||
(activeElement != null && eventTarget != null && nodeContains(activeElement, eventTarget));
ignoreFocusEvent = true;
let isRefocusing = false;
let onBlur: EventListener = (e) => {
if (isBlurFromActiveElement(getEventTarget(e) as Element) || isRefocusing) {
e.stopImmediatePropagation();
}
};
let onFocusOut: EventListener = (e) => {
if (isBlurFromActiveElement(getEventTarget(e) as Element) || isRefocusing) {
e.stopImmediatePropagation();
// If there was no focusable ancestor, we don't expect a focus event.
// Re-focus the original active element here.
if (!target && !isRefocusing) {
isRefocusing = true;
focusWithoutScrolling(activeElement);
cleanup();
}
}
};
let onFocus: EventListener = (e) => {
if (isFocusMovingToTarget(getEventTarget(e) as Element) || isRefocusing) {
e.stopImmediatePropagation();
}
};
let onFocusIn: EventListener = (e) => {
if (isFocusMovingToTarget(getEventTarget(e) as Element) || isRefocusing) {
e.stopImmediatePropagation();
if (!isRefocusing) {
isRefocusing = true;
focusWithoutScrolling(activeElement);
cleanup();
}
}
};
root.addEventListener('blur', onBlur, true);
root.addEventListener('focusout', onFocusOut, true);
root.addEventListener('focusin', onFocusIn, true);
root.addEventListener('focus', onFocus, true);
let cleanup = () => {
cancelAnimationFrame(raf);
root.removeEventListener('blur', onBlur, true);
root.removeEventListener('focusout', onFocusOut, true);
root.removeEventListener('focusin', onFocusIn, true);
root.removeEventListener('focus', onFocus, true);
ignoreFocusEvent = false;
isRefocusing = false;
};
let raf = requestAnimationFrame(cleanup);
return cleanup;
}