/
DOMModernPluginEventSystem.js
976 lines (925 loc) · 28.3 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
/**
* 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 {TopLevelType, DOMTopLevelEventType} from './TopLevelEventTypes';
import type {EventSystemFlags} from './EventSystemFlags';
import type {
AnyNativeEvent,
DispatchQueue,
DispatchQueueItem,
DispatchQueueItemPhase,
DispatchQueueItemPhaseEntry,
} from './PluginModuleType';
import type {ReactSyntheticEvent} from './ReactSyntheticEventType';
import type {
ElementListenerMap,
ElementListenerMapEntry,
} from '../client/ReactDOMComponentTree';
import type {EventPriority, ReactScopeInstance} from 'shared/ReactTypes';
import type {Fiber} from 'react-reconciler/src/ReactInternalTypes';
import {registrationNameDependencies} from './EventRegistry';
import {
PLUGIN_EVENT_SYSTEM,
LEGACY_FB_SUPPORT,
IS_REPLAYED,
IS_TARGET_PHASE_ONLY,
IS_CAPTURE_PHASE,
} from './EventSystemFlags';
import {
HostRoot,
HostPortal,
HostComponent,
HostText,
ScopeComponent,
} from 'react-reconciler/src/ReactWorkTags';
import getEventTarget from './getEventTarget';
import {
TOP_LOAD,
TOP_ABORT,
TOP_CANCEL,
TOP_INVALID,
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,
TOP_SELECTION_CHANGE,
TOP_AFTER_BLUR,
getRawEventName,
} from './DOMTopLevelEventTypes';
import {
getClosestInstanceFromNode,
getEventListenerMap,
getEventHandlerListeners,
} from '../client/ReactDOMComponentTree';
import {COMMENT_NODE} from '../shared/HTMLNodeType';
import {batchedEventUpdates} from './ReactDOMUpdateBatching';
import getListener from './getListener';
import {passiveBrowserEventsSupported} from './checkPassiveEvents';
import {
enableLegacyFBSupport,
enableCreateEventHandleAPI,
enableScopeAPI,
} from 'shared/ReactFeatureFlags';
import {
invokeGuardedCallbackAndCatchFirstError,
rethrowCaughtError,
} from 'shared/ReactErrorUtils';
import {createEventListenerWrapperWithPriority} from './ReactDOMEventListener';
import {
removeEventListener,
addEventCaptureListener,
addEventBubbleListener,
addEventBubbleListenerWithPassiveFlag,
addEventCaptureListenerWithPassiveFlag,
} from './EventListener';
import {removeTrappedEventListener} from './DeprecatedDOMEventResponderSystem';
import {topLevelEventsToReactNames} from './DOMEventProperties';
import * as ModernBeforeInputEventPlugin from './plugins/ModernBeforeInputEventPlugin';
import * as ModernChangeEventPlugin from './plugins/ModernChangeEventPlugin';
import * as ModernEnterLeaveEventPlugin from './plugins/ModernEnterLeaveEventPlugin';
import * as ModernSelectEventPlugin from './plugins/ModernSelectEventPlugin';
import * as ModernSimpleEventPlugin from './plugins/ModernSimpleEventPlugin';
// TODO: remove top-level side effect.
ModernSimpleEventPlugin.registerEvents();
ModernEnterLeaveEventPlugin.registerEvents();
ModernChangeEventPlugin.registerEvents();
ModernSelectEventPlugin.registerEvents();
ModernBeforeInputEventPlugin.registerEvents();
function extractEvents(
dispatchQueue: DispatchQueue,
topLevelType: TopLevelType,
targetInst: null | Fiber,
nativeEvent: AnyNativeEvent,
nativeEventTarget: null | EventTarget,
eventSystemFlags: EventSystemFlags,
targetContainer: null | EventTarget,
) {
ModernSimpleEventPlugin.extractEvents(
dispatchQueue,
topLevelType,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
ModernEnterLeaveEventPlugin.extractEvents(
dispatchQueue,
topLevelType,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
ModernChangeEventPlugin.extractEvents(
dispatchQueue,
topLevelType,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
ModernSelectEventPlugin.extractEvents(
dispatchQueue,
topLevelType,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
ModernBeforeInputEventPlugin.extractEvents(
dispatchQueue,
topLevelType,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
}
export const capturePhaseEvents: Set<DOMTopLevelEventType> = new Set([
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,
]);
if (enableCreateEventHandleAPI) {
capturePhaseEvents.add(TOP_AFTER_BLUR);
}
function executeDispatch(
event: ReactSyntheticEvent,
listener: Function,
currentTarget: EventTarget,
): void {
const type = event.type || 'unknown-event';
event.currentTarget = currentTarget;
invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
event.currentTarget = null;
}
function executeDispatchesInOrder(
event: ReactSyntheticEvent,
capture: DispatchQueueItemPhase,
bubble: DispatchQueueItemPhase,
): void {
let previousInstance;
// Dispatch capture phase first.
for (let i = capture.length - 1; i >= 0; i--) {
const {instance, currentTarget, listener} = capture[i];
if (instance !== previousInstance && event.isPropagationStopped()) {
return;
}
executeDispatch(event, listener, currentTarget);
previousInstance = instance;
}
previousInstance = undefined;
// Dispatch bubble phase second.
for (let i = 0; i < bubble.length; i++) {
const {instance, currentTarget, listener} = bubble[i];
if (instance !== previousInstance && event.isPropagationStopped()) {
return;
}
executeDispatch(event, listener, currentTarget);
previousInstance = instance;
}
}
export function dispatchEventsInBatch(dispatchQueue: DispatchQueue): void {
for (let i = 0; i < dispatchQueue.length; i++) {
const dispatchQueueItem: DispatchQueueItem = dispatchQueue[i];
const {event, capture, bubble} = dispatchQueueItem;
executeDispatchesInOrder(event, capture, bubble);
// Modern event system doesn't use pooling.
}
// This would be a good time to rethrow if any of the event handlers threw.
rethrowCaughtError();
}
function dispatchEventsForPlugins(
topLevelType: DOMTopLevelEventType,
eventSystemFlags: EventSystemFlags,
nativeEvent: AnyNativeEvent,
targetInst: null | Fiber,
targetContainer: EventTarget,
): void {
const nativeEventTarget = getEventTarget(nativeEvent);
const dispatchQueue: DispatchQueue = [];
extractEvents(
dispatchQueue,
topLevelType,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
dispatchEventsInBatch(dispatchQueue);
}
function shouldUpgradeListener(
listenerEntry: void | ElementListenerMapEntry,
passive: void | boolean,
): boolean {
return (
listenerEntry !== undefined && listenerEntry.passive === true && !passive
);
}
export function listenToTopLevelEvent(
topLevelType: DOMTopLevelEventType,
target: EventTarget,
listenerMap: ElementListenerMap,
eventSystemFlags: EventSystemFlags,
capture: boolean,
passive?: boolean,
priority?: EventPriority,
): void {
// TOP_SELECTION_CHANGE needs to be attached to the document
// otherwise it won't capture incoming events that are only
// triggered on the document directly.
if (topLevelType === TOP_SELECTION_CHANGE) {
target = (target: any).ownerDocument || target;
listenerMap = getEventListenerMap(target);
}
const listenerMapKey = getListenerMapKey(topLevelType, capture);
const listenerEntry = ((listenerMap.get(
listenerMapKey,
): any): ElementListenerMapEntry | void);
const shouldUpgrade = shouldUpgradeListener(listenerEntry, passive);
// If the listener entry is empty or we should upgrade, then
// we need to trap an event listener onto the target.
if (listenerEntry === undefined || shouldUpgrade) {
// If we should upgrade, then we need to remove the existing trapped
// event listener for the target container.
if (shouldUpgrade) {
removeTrappedEventListener(
target,
topLevelType,
capture,
((listenerEntry: any): ElementListenerMapEntry).listener,
);
}
if (capture) {
eventSystemFlags |= IS_CAPTURE_PHASE;
}
const listener = addTrappedEventListener(
target,
topLevelType,
eventSystemFlags,
capture,
false,
passive,
priority,
);
listenerMap.set(listenerMapKey, {passive, listener});
}
}
export function listenToReactPropEvent(
reactPropEvent: string,
rootContainerElement: Element,
): void {
const listenerMap = getEventListenerMap(rootContainerElement);
// For optimization, let's check if we have the registration name
// on the rootContainerElement.
if (listenerMap.has(reactPropEvent)) {
return;
}
// Add the registration name to the map, so we can avoid processing
// this React prop event again.
listenerMap.set(reactPropEvent, null);
const dependencies = registrationNameDependencies[reactPropEvent];
for (let i = 0; i < dependencies.length; i++) {
const dependency = dependencies[i];
const capture = capturePhaseEvents.has(dependency);
listenToTopLevelEvent(
dependency,
rootContainerElement,
listenerMap,
PLUGIN_EVENT_SYSTEM,
capture,
);
}
}
function addTrappedEventListener(
targetContainer: EventTarget,
topLevelType: DOMTopLevelEventType,
eventSystemFlags: EventSystemFlags,
capture: boolean,
isDeferredListenerForLegacyFBSupport?: boolean,
passive?: boolean,
priority?: EventPriority,
): any => void {
let listener = createEventListenerWrapperWithPriority(
targetContainer,
topLevelType,
eventSystemFlags,
priority,
);
// If passive option is not supported, then the event will be
// active and not passive.
if (passive === true && !passiveBrowserEventsSupported) {
passive = false;
}
targetContainer =
enableLegacyFBSupport && isDeferredListenerForLegacyFBSupport
? (targetContainer: any).ownerDocument
: targetContainer;
const rawEventName = getRawEventName(topLevelType);
let unsubscribeListener;
// When legacyFBSupport is enabled, it's for when we
// want to add a one time event listener to a container.
// This should only be used with enableLegacyFBSupport
// due to requirement to provide compatibility with
// internal FB www event tooling. This works by removing
// the event listener as soon as it is invoked. We could
// also attempt to use the {once: true} param on
// addEventListener, but that requires support and some
// browsers do not support this today, and given this is
// to support legacy code patterns, it's likely they'll
// need support for such browsers.
if (enableLegacyFBSupport && isDeferredListenerForLegacyFBSupport) {
const originalListener = listener;
listener = function(...p) {
try {
return originalListener.apply(this, p);
} finally {
removeEventListener(
targetContainer,
rawEventName,
unsubscribeListener,
capture,
);
}
};
}
if (capture) {
if (enableCreateEventHandleAPI && passive !== undefined) {
unsubscribeListener = addEventCaptureListenerWithPassiveFlag(
targetContainer,
rawEventName,
listener,
passive,
);
} else {
unsubscribeListener = addEventCaptureListener(
targetContainer,
rawEventName,
listener,
);
}
} else {
if (enableCreateEventHandleAPI && passive !== undefined) {
unsubscribeListener = addEventBubbleListenerWithPassiveFlag(
targetContainer,
rawEventName,
listener,
passive,
);
} else {
unsubscribeListener = addEventBubbleListener(
targetContainer,
rawEventName,
listener,
);
}
}
return unsubscribeListener;
}
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,
PLUGIN_EVENT_SYSTEM | LEGACY_FB_SUPPORT,
false,
isDeferredListenerForLegacyFBSupport,
);
return true;
}
function isMatchingRootContainer(
grandContainer: Element,
targetContainer: EventTarget,
): boolean {
return (
grandContainer === targetContainer ||
(grandContainer.nodeType === COMMENT_NODE &&
grandContainer.parentNode === targetContainer)
);
}
export function dispatchEventForPluginEventSystem(
topLevelType: DOMTopLevelEventType,
eventSystemFlags: EventSystemFlags,
nativeEvent: AnyNativeEvent,
targetInst: null | Fiber,
targetContainer: EventTarget,
): void {
let ancestorInst = targetInst;
if (eventSystemFlags & IS_TARGET_PHASE_ONLY) {
// For TargetEvent nodes (i.e. document, window)
ancestorInst = null;
} else {
const targetContainerNode = ((targetContainer: any): Node);
// 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;
}
if (targetInst !== null) {
// 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;
mainLoop: while (true) {
if (node === null) {
return;
}
const nodeTag = node.tag;
if (nodeTag === HostRoot || nodeTag === HostPortal) {
let container = node.stateNode.containerInfo;
if (isMatchingRootContainer(container, targetContainerNode)) {
break;
}
if (nodeTag === 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) {
const grandTag = grandNode.tag;
if (grandTag === HostRoot || grandTag === HostPortal) {
const grandContainer = grandNode.stateNode.containerInfo;
if (
isMatchingRootContainer(grandContainer, targetContainerNode)
) {
// 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;
}
}
// Now we need to find it's corresponding host fiber in the other
// tree. To do this we can use getClosestInstanceFromNode, but we
// need to validate that the fiber is a host instance, otherwise
// we need to traverse up through the DOM till we find the correct
// node that is from the other tree.
while (container !== null) {
const parentNode = getClosestInstanceFromNode(container);
if (parentNode === null) {
return;
}
const parentTag = parentNode.tag;
if (parentTag === HostComponent || parentTag === HostText) {
node = ancestorInst = parentNode;
continue mainLoop;
}
container = container.parentNode;
}
}
node = node.return;
}
}
}
batchedEventUpdates(() =>
dispatchEventsForPlugins(
topLevelType,
eventSystemFlags,
nativeEvent,
ancestorInst,
targetContainer,
),
);
}
function createDispatchQueueItemPhaseEntry(
instance: null | Fiber,
listener: Function,
currentTarget: EventTarget,
): DispatchQueueItemPhaseEntry {
return {
instance,
listener,
currentTarget,
};
}
function createDispatchQueueItem(
event: ReactSyntheticEvent,
capture: DispatchQueueItemPhase,
bubble: DispatchQueueItemPhase,
): DispatchQueueItem {
return {
event,
capture,
bubble,
};
}
export function accumulateTwoPhaseListeners(
targetFiber: Fiber | null,
dispatchQueue: DispatchQueue,
event: ReactSyntheticEvent,
accumulateEventHandleListeners?: boolean,
): void {
const bubbled = event._reactName;
const captured = bubbled !== null ? bubbled + 'Capture' : null;
const capturePhase: DispatchQueueItemPhase = [];
const bubblePhase: DispatchQueueItemPhase = [];
// If we are not handling EventTarget only phase, then we're doing the
// usual two phase accumulation using the React fiber tree to pick up
// all relevant useEvent and on* prop events.
let instance = targetFiber;
let lastHostComponent = null;
const targetType = event.type;
// Accumulate all instances and listeners via the target -> root path.
while (instance !== null) {
const {stateNode, tag} = instance;
// Handle listeners that are on HostComponents (i.e. <div>)
if (tag === HostComponent && stateNode !== null) {
const currentTarget = stateNode;
lastHostComponent = currentTarget;
// For Event Handle listeners
if (enableCreateEventHandleAPI && accumulateEventHandleListeners) {
const listeners = getEventHandlerListeners(currentTarget);
if (listeners !== null) {
const listenersArr = Array.from(listeners);
for (let i = 0; i < listenersArr.length; i++) {
const listener = listenersArr[i];
const {callback, capture, type} = listener;
if (type === targetType) {
if (capture === true) {
capturePhase.push(
createDispatchQueueItemPhaseEntry(
instance,
callback,
currentTarget,
),
);
} else {
bubblePhase.push(
createDispatchQueueItemPhaseEntry(
instance,
callback,
currentTarget,
),
);
}
}
}
}
}
// Standard React on* listeners, i.e. onClick prop
if (captured !== null) {
const captureListener = getListener(instance, captured);
if (captureListener != null) {
capturePhase.push(
createDispatchQueueItemPhaseEntry(
instance,
captureListener,
currentTarget,
),
);
}
}
if (bubbled !== null) {
const bubbleListener = getListener(instance, bubbled);
if (bubbleListener != null) {
bubblePhase.push(
createDispatchQueueItemPhaseEntry(
instance,
bubbleListener,
currentTarget,
),
);
}
}
} else if (
enableCreateEventHandleAPI &&
enableScopeAPI &&
accumulateEventHandleListeners &&
tag === ScopeComponent &&
lastHostComponent !== null
) {
const reactScopeInstance = stateNode;
const listeners = getEventHandlerListeners(reactScopeInstance);
const lastCurrentTarget = ((lastHostComponent: any): Element);
if (listeners !== null) {
const listenersArr = Array.from(listeners);
for (let i = 0; i < listenersArr.length; i++) {
const listener = listenersArr[i];
const {callback, capture, type} = listener;
if (type === targetType) {
if (capture === true) {
capturePhase.push(
createDispatchQueueItemPhaseEntry(
instance,
callback,
lastCurrentTarget,
),
);
} else {
bubblePhase.push(
createDispatchQueueItemPhaseEntry(
instance,
callback,
lastCurrentTarget,
),
);
}
}
}
}
}
instance = instance.return;
}
if (capturePhase.length !== 0 || bubblePhase.length !== 0) {
dispatchQueue.push(
createDispatchQueueItem(event, capturePhase, bubblePhase),
);
}
}
function getParent(inst: Fiber | null): Fiber | null {
if (inst === null) {
return null;
}
do {
inst = inst.return;
// TODO: If this is a HostRoot we might want to bail out.
// That is depending on if we want nested subtrees (layers) to bubble
// events to their parent. We could also go through parentNode on the
// host node but that wouldn't work for React Native and doesn't let us
// do the portal feature.
} while (inst && inst.tag !== HostComponent);
if (inst) {
return inst;
}
return null;
}
/**
* Return the lowest common ancestor of A and B, or null if they are in
* different trees.
*/
function getLowestCommonAncestor(instA: Fiber, instB: Fiber): Fiber | null {
let nodeA = instA;
let nodeB = instB;
let depthA = 0;
for (let tempA = nodeA; tempA; tempA = getParent(tempA)) {
depthA++;
}
let depthB = 0;
for (let tempB = nodeB; tempB; tempB = getParent(tempB)) {
depthB++;
}
// If A is deeper, crawl up.
while (depthA - depthB > 0) {
nodeA = getParent(nodeA);
depthA--;
}
// If B is deeper, crawl up.
while (depthB - depthA > 0) {
nodeB = getParent(nodeB);
depthB--;
}
// Walk in lockstep until we find a match.
let depth = depthA;
while (depth--) {
if (nodeA === nodeB || (nodeB !== null && nodeA === nodeB.alternate)) {
return nodeA;
}
nodeA = getParent(nodeA);
nodeB = getParent(nodeB);
}
return null;
}
function accumulateEnterLeaveListenersForEvent(
dispatchQueue: DispatchQueue,
event: ReactSyntheticEvent,
target: Fiber,
common: Fiber | null,
capture: boolean,
): void {
const registrationName = event._reactName;
if (registrationName === undefined) {
return;
}
const capturePhase: DispatchQueueItemPhase = [];
const bubblePhase: DispatchQueueItemPhase = [];
let instance = target;
while (instance !== null) {
if (instance === common) {
break;
}
const {alternate, stateNode, tag} = instance;
if (alternate !== null && alternate === common) {
break;
}
if (tag === HostComponent && stateNode !== null) {
const currentTarget = stateNode;
if (capture) {
const captureListener = getListener(instance, registrationName);
if (captureListener != null) {
capturePhase.push(
createDispatchQueueItemPhaseEntry(
instance,
captureListener,
currentTarget,
),
);
}
} else {
const bubbleListener = getListener(instance, registrationName);
if (bubbleListener != null) {
bubblePhase.push(
createDispatchQueueItemPhaseEntry(
instance,
bubbleListener,
currentTarget,
),
);
}
}
}
instance = instance.return;
}
if (capturePhase.length !== 0 || bubblePhase.length !== 0) {
dispatchQueue.push(
createDispatchQueueItem(event, capturePhase, bubblePhase),
);
}
}
export function accumulateEnterLeaveListeners(
dispatchQueue: DispatchQueue,
leaveEvent: ReactSyntheticEvent,
enterEvent: null | ReactSyntheticEvent,
from: Fiber | null,
to: Fiber | null,
): void {
const common = from && to ? getLowestCommonAncestor(from, to) : null;
if (from !== null) {
accumulateEnterLeaveListenersForEvent(
dispatchQueue,
leaveEvent,
from,
common,
false,
);
}
if (to !== null && enterEvent !== null) {
accumulateEnterLeaveListenersForEvent(
dispatchQueue,
enterEvent,
to,
common,
true,
);
}
}
export function accumulateEventHandleTargetListeners(
dispatchQueue: DispatchQueue,
event: ReactSyntheticEvent,
currentTarget: EventTarget,
inCapturePhase: boolean,
): void {
const capturePhase: DispatchQueueItemPhase = [];
const bubblePhase: DispatchQueueItemPhase = [];
const eventListeners = getEventHandlerListeners(currentTarget);
if (eventListeners !== null) {
const listenersArr = Array.from(eventListeners);
const targetType = ((event.type: any): DOMTopLevelEventType);
for (let i = 0; i < listenersArr.length; i++) {
const listener = listenersArr[i];
const {callback, capture, type} = listener;
if (type === targetType) {
if (inCapturePhase && capture) {
capturePhase.push(
createDispatchQueueItemPhaseEntry(null, callback, currentTarget),
);
} else if (!inCapturePhase && !capture) {
bubblePhase.push(
createDispatchQueueItemPhaseEntry(null, callback, currentTarget),
);
}
}
}
}
if (capturePhase.length !== 0 || bubblePhase.length !== 0) {
dispatchQueue.push(
createDispatchQueueItem(event, capturePhase, bubblePhase),
);
}
}
export function addEventTypeToDispatchConfig(type: DOMTopLevelEventType): void {
const reactName = topLevelEventsToReactNames.get(type);
// If we don't have a reactName, then we're dealing with
// an event type that React does not know about (i.e. a custom event).
// We need to register an event config for this or the SimpleEventPlugin
// will not appropriately provide a SyntheticEvent, so we use out empty
// dispatch config for custom events.
if (reactName === undefined) {
topLevelEventsToReactNames.set(type, null);
}
}
export function clearEventHandleListenersForTarget(
target: EventTarget | ReactScopeInstance,
): void {
// It's unfortunate that we have to do this cleanup, but
// it's necessary otherwise we will leak the host instances
// on the createEventHandle API "listeners" Map. We call destroy
// on each listener to ensure we properly remove the instance
// from the listeners Map. Note: we have this Map so that we
// can track listeners for the handle.clear() API call.
const listeners = getEventHandlerListeners(target);
if (listeners !== null) {
const listenersArr = Array.from(listeners);
for (let i = 0; i < listenersArr.length; i++) {
listenersArr[i].destroy(target);
}
}
}
export function getListenerMapKey(
topLevelType: DOMTopLevelEventType,
capture: boolean,
): string {
return `${getRawEventName(topLevelType)}__${capture ? 'capture' : 'bubble'}`;
}