/
DOMModernPluginEventSystem.js
432 lines (409 loc) · 13.2 KB
/
DOMModernPluginEventSystem.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {AnyNativeEvent} from 'legacy-events/PluginModuleType';
import type {DOMTopLevelEventType} from 'legacy-events/TopLevelEventTypes';
import type {
ElementListenerMap,
ElementListenerMapEntry,
} from '../events/DOMEventListenerMap';
import type {EventSystemFlags} from 'legacy-events/EventSystemFlags';
import type {EventPriority} from 'shared/ReactTypes';
import type {Fiber} from 'react-reconciler/src/ReactFiber';
import type {PluginModule} from 'legacy-events/PluginModuleType';
import type {ReactSyntheticEvent} from 'legacy-events/ReactSyntheticEventType';
import type {ReactDOMListener} from 'shared/ReactDOMTypes';
import {registrationNameDependencies} from 'legacy-events/EventPluginRegistry';
import {batchedEventUpdates} from 'legacy-events/ReactGenericBatching';
import {executeDispatchesInOrder} from 'legacy-events/EventPluginUtils';
import {plugins} from 'legacy-events/EventPluginRegistry';
import {LEGACY_FB_SUPPORT, IS_REPLAYED} from 'legacy-events/EventSystemFlags';
import {HostRoot, HostPortal} from 'shared/ReactWorkTags';
import {
addTrappedEventListener,
removeTrappedEventListener,
} from './ReactDOMEventListener';
import getEventTarget from './getEventTarget';
import {getListenerMapForElement} from './DOMEventListenerMap';
import {
TOP_FOCUS,
TOP_LOAD,
TOP_ABORT,
TOP_CANCEL,
TOP_INVALID,
TOP_BLUR,
TOP_SCROLL,
TOP_CLOSE,
TOP_RESET,
TOP_SUBMIT,
TOP_CAN_PLAY,
TOP_CAN_PLAY_THROUGH,
TOP_DURATION_CHANGE,
TOP_EMPTIED,
TOP_ENCRYPTED,
TOP_ENDED,
TOP_ERROR,
TOP_WAITING,
TOP_VOLUME_CHANGE,
TOP_TIME_UPDATE,
TOP_SUSPEND,
TOP_STALLED,
TOP_SEEKING,
TOP_SEEKED,
TOP_PLAY,
TOP_PAUSE,
TOP_LOAD_START,
TOP_LOADED_DATA,
TOP_LOADED_METADATA,
TOP_RATE_CHANGE,
TOP_PROGRESS,
TOP_PLAYING,
TOP_CLICK,
} from './DOMTopLevelEventTypes';
import {
getClosestInstanceFromNode,
getListenersFromTarget,
initListenersSet,
} from '../client/ReactDOMComponentTree';
import {
DOCUMENT_NODE,
COMMENT_NODE,
ELEMENT_NODE,
} from '../shared/HTMLNodeType';
import {enableLegacyFBSupport} from 'shared/ReactFeatureFlags';
const capturePhaseEvents = new Set([
TOP_FOCUS,
TOP_BLUR,
TOP_SCROLL,
TOP_LOAD,
TOP_ABORT,
TOP_CANCEL,
TOP_CLOSE,
TOP_INVALID,
TOP_RESET,
TOP_SUBMIT,
TOP_ABORT,
TOP_CAN_PLAY,
TOP_CAN_PLAY_THROUGH,
TOP_DURATION_CHANGE,
TOP_EMPTIED,
TOP_ENCRYPTED,
TOP_ENDED,
TOP_ERROR,
TOP_LOADED_DATA,
TOP_LOADED_METADATA,
TOP_LOAD_START,
TOP_PAUSE,
TOP_PLAY,
TOP_PLAYING,
TOP_PROGRESS,
TOP_RATE_CHANGE,
TOP_SEEKED,
TOP_SEEKING,
TOP_STALLED,
TOP_SUSPEND,
TOP_TIME_UPDATE,
TOP_VOLUME_CHANGE,
TOP_WAITING,
]);
const isArray = Array.isArray;
function dispatchEventsForPlugins(
topLevelType: DOMTopLevelEventType,
eventSystemFlags: EventSystemFlags,
nativeEvent: AnyNativeEvent,
targetInst: null | Fiber,
targetContainer: null | EventTarget,
): void {
const nativeEventTarget = getEventTarget(nativeEvent);
const syntheticEvents: Array<ReactSyntheticEvent> = [];
for (let i = 0; i < plugins.length; i++) {
const possiblePlugin: PluginModule<AnyNativeEvent> = plugins[i];
if (possiblePlugin !== undefined) {
const extractedEvents = possiblePlugin.extractEvents(
topLevelType,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
if (isArray(extractedEvents)) {
// Flow complains about @@iterator being missing in ReactSyntheticEvent,
// so we cast to avoid the Flow error.
const arrOfExtractedEvents = ((extractedEvents: any): Array<ReactSyntheticEvent>);
syntheticEvents.push(...arrOfExtractedEvents);
} else if (extractedEvents != null) {
syntheticEvents.push(extractedEvents);
}
}
}
for (let i = 0; i < syntheticEvents.length; i++) {
const syntheticEvent = syntheticEvents[i];
executeDispatchesInOrder(syntheticEvent);
// Release the event from the pool if needed
if (!syntheticEvent.isPersistent()) {
syntheticEvent.constructor.release(syntheticEvent);
}
}
}
function shouldUpgradeListener(
listenerEntry: void | ElementListenerMapEntry,
passive: void | boolean,
): boolean {
if (listenerEntry === undefined) {
return false;
}
// Upgrade from passive to active.
if (passive !== true && listenerEntry.passive) {
return true;
}
// Upgrade from default-active (browser default) to active.
if (passive === false && listenerEntry.passive === undefined) {
return true;
}
// Otherwise, do not upgrade
return false;
}
export function listenToTopLevelEvent(
topLevelType: DOMTopLevelEventType,
targetContainer: EventTarget,
listenerMap: ElementListenerMap,
passive?: boolean,
priority?: EventPriority,
): void {
const listenerEntry = listenerMap.get(topLevelType);
const shouldUpgrade = shouldUpgradeListener(listenerEntry, passive);
if (listenerEntry === undefined || shouldUpgrade) {
const isCapturePhase = capturePhaseEvents.has(topLevelType);
// If we should upgrade, then we need to remove the existing trapped
// event listener for the target container.
if (shouldUpgrade) {
removeTrappedEventListener(
targetContainer,
topLevelType,
isCapturePhase,
((listenerEntry: any): ElementListenerMapEntry).listener,
);
}
const listener = addTrappedEventListener(
targetContainer,
topLevelType,
isCapturePhase,
false,
passive,
priority,
);
listenerMap.set(topLevelType, {passive, listener});
}
}
export function listenToEvent(
registrationName: string,
rootContainerElement: Element,
): void {
const listenerMap = getListenerMapForElement(rootContainerElement);
const dependencies = registrationNameDependencies[registrationName];
for (let i = 0; i < dependencies.length; i++) {
const dependency = dependencies[i];
listenToTopLevelEvent(dependency, rootContainerElement, listenerMap);
}
}
function willDeferLaterForLegacyFBSupport(
topLevelType: DOMTopLevelEventType,
targetContainer: EventTarget,
): boolean {
if (topLevelType !== TOP_CLICK) {
return false;
}
// We defer all click events with legacy FB support mode on.
// This means we add a one time event listener to trigger
// after the FB delegated listeners fire.
const isDeferredListenerForLegacyFBSupport = true;
addTrappedEventListener(
targetContainer,
topLevelType,
false,
isDeferredListenerForLegacyFBSupport,
);
return true;
}
function isMatchingRootContainer(
grandContainer: Element,
targetContainer: EventTarget,
): boolean {
return (
grandContainer === targetContainer ||
(grandContainer.nodeType === COMMENT_NODE &&
grandContainer.parentNode === targetContainer)
);
}
export function isDOMElement(target: EventTarget): boolean {
const nodeType = ((target: any): Node).nodeType;
return (nodeType: any) && nodeType === ELEMENT_NODE;
}
export function isDOMDocument(target: EventTarget): boolean {
const nodeType = ((target: any): Node).nodeType;
return nodeType === DOCUMENT_NODE;
}
export function dispatchEventForPluginEventSystem(
topLevelType: DOMTopLevelEventType,
eventSystemFlags: EventSystemFlags,
nativeEvent: AnyNativeEvent,
targetInst: null | Fiber,
targetContainer: null | EventTarget,
): void {
let ancestorInst = targetInst;
if (targetContainer !== null) {
const possibleTargetContainerNode = ((targetContainer: any): Node);
// Given the rootContainer can be any EventTarget, if the
// target is not a valid DOM element then we'll skip this part.
if (
possibleTargetContainerNode === window ||
!isDOMElement(possibleTargetContainerNode)
) {
// TODO: useEvent for document and window
return;
}
// If we are using the legacy FB support flag, we
// defer the event to the null with a one
// time event listener so we can defer the event.
if (
enableLegacyFBSupport &&
// We do not want to defer if the event system has already been
// set to LEGACY_FB_SUPPORT. LEGACY_FB_SUPPORT only gets set when
// we call willDeferLaterForLegacyFBSupport, thus not bailing out
// will result in endless cycles like an infinite loop.
(eventSystemFlags & LEGACY_FB_SUPPORT) === 0 &&
// We also don't want to defer during event replaying.
(eventSystemFlags & IS_REPLAYED) === 0 &&
willDeferLaterForLegacyFBSupport(topLevelType, targetContainer)
) {
return;
}
// The below logic attempts to work out if we need to change
// the target fiber to a different ancestor. We had similar logic
// in the legacy event system, except the big difference between
// systems is that the modern event system now has an event listener
// attached to each React Root and React Portal Root. Together,
// the DOM nodes representing these roots are the "rootContainer".
// To figure out which ancestor instance we should use, we traverse
// up the fiber tree from the target instance and attempt to find
// root boundaries that match that of our current "rootContainer".
// If we find that "rootContainer", we find the parent fiber
// sub-tree for that root and make that our ancestor instance.
let node = targetInst;
while (true) {
if (node === null) {
return;
}
if (node.tag === HostRoot || node.tag === HostPortal) {
const container = node.stateNode.containerInfo;
if (isMatchingRootContainer(container, possibleTargetContainerNode)) {
break;
}
if (node.tag === HostPortal) {
// The target is a portal, but it's not the rootContainer we're looking for.
// Normally portals handle their own events all the way down to the root.
// So we should be able to stop now. However, we don't know if this portal
// was part of *our* root.
let grandNode = node.return;
while (grandNode !== null) {
if (grandNode.tag === HostRoot || grandNode.tag === HostPortal) {
const grandContainer = grandNode.stateNode.containerInfo;
if (
isMatchingRootContainer(
grandContainer,
possibleTargetContainerNode,
)
) {
// This is the rootContainer we're looking for and we found it as
// a parent of the Portal. That means we can ignore it because the
// Portal will bubble through to us.
return;
}
}
grandNode = grandNode.return;
}
}
const parentSubtreeInst = getClosestInstanceFromNode(container);
if (parentSubtreeInst === null) {
return;
}
node = ancestorInst = parentSubtreeInst;
continue;
}
node = node.return;
}
}
batchedEventUpdates(() =>
dispatchEventsForPlugins(
topLevelType,
eventSystemFlags,
nativeEvent,
ancestorInst,
targetContainer,
),
);
}
function getNearestRootOrPortalContainer(instance: Element): Element {
let node = getClosestInstanceFromNode(instance);
while (node !== null) {
const tag = node.tag;
// Once we encounter a host container or root container
// we can return their DOM instance.
if (tag === HostRoot || tag === HostPortal) {
return node.stateNode.containerInfo;
}
node = node.return;
}
return instance;
}
export function attachElementListener(listener: ReactDOMListener): void {
const {event, target} = listener;
const {passive, priority, type} = event;
let containerEventTarget = target;
// If we the target is a managed React element, then we need to
// find the nearest root/portal contained to attach the event listener
// to. If it's not managed, i.e. the window, then we just attach
// the listener to the target.
if (isDOMElement(target)) {
const possibleManagedTarget = ((target: any): Element);
if (getClosestInstanceFromNode(possibleManagedTarget)) {
containerEventTarget = getNearestRootOrPortalContainer(
possibleManagedTarget,
);
}
}
const listenerMap = getListenerMapForElement(containerEventTarget);
// Add the event listener to the target container (falling back to
// the target if we didn't find one).
listenToTopLevelEvent(
((type: any): DOMTopLevelEventType),
containerEventTarget,
listenerMap,
passive,
priority,
);
// Get the internal listeners Set from the target instance.
let listeners = getListenersFromTarget(target);
// If we don't have any listeners, then we need to init them.
if (listeners === null) {
listeners = new Set();
initListenersSet(target, listeners);
}
// Finally, add our listener to the listeners Set.
listeners.add(listener);
}
export function detachElementListener(listener: ReactDOMListener): void {
const {target} = listener;
// Get the internal listeners Set from the target instance.
const listeners = getListenersFromTarget(target);
if (listeners !== null) {
// Remove out listener from the listeners Set.
listeners.delete(listener);
}
}