UNPKG

61.6 kBJavaScriptView Raw
1/** @license React v16.12.0
2 * react-dom-unstable-native-dependencies.development.js
3 *
4 * Copyright (c) Facebook, Inc. and its affiliates.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE file in the root directory of this source tree.
8 */
9
10'use strict';
11
12(function (global, factory) {
13 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react-dom'), require('react')) :
14 typeof define === 'function' && define.amd ? define(['react-dom', 'react'], factory) :
15 (global.ReactDOMUnstableNativeDependencies = factory(global.ReactDOM,global.React));
16}(this, (function (ReactDOM,React) { 'use strict';
17
18// Do not require this module directly! Use normal `invariant` calls with
19// template literal strings. The messages will be replaced with error codes
20// during build.
21
22/**
23 * Use invariant() to assert state which your program assumes to be true.
24 *
25 * Provide sprintf-style format (only %s is supported) and arguments
26 * to provide information about what broke and what you were
27 * expecting.
28 *
29 * The invariant message will be stripped in production, but the invariant
30 * will remain to ensure logic does not differ in production.
31 */
32
33{
34 // In DEV mode, we swap out invokeGuardedCallback for a special version
35 // that plays more nicely with the browser's DevTools. The idea is to preserve
36 // "Pause on exceptions" behavior. Because React wraps all user-provided
37 // functions in invokeGuardedCallback, and the production version of
38 // invokeGuardedCallback uses a try-catch, all user exceptions are treated
39 // like caught exceptions, and the DevTools won't pause unless the developer
40 // takes the extra step of enabling pause on caught exceptions. This is
41 // unintuitive, though, because even though React has caught the error, from
42 // the developer's perspective, the error is uncaught.
43 //
44 // To preserve the expected "Pause on exceptions" behavior, we don't use a
45 // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
46 // DOM node, and call the user-provided callback from inside an event handler
47 // for that fake event. If the callback throws, the error is "captured" using
48 // a global event handler. But because the error happens in a different
49 // event loop context, it does not interrupt the normal program flow.
50 // Effectively, this gives us try-catch behavior without actually using
51 // try-catch. Neat!
52 // Check that the browser supports the APIs we need to implement our special
53 // DEV version of invokeGuardedCallback
54 if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
55 var fakeNode = document.createElement('react');
56
57
58 }
59}
60
61/**
62 * Call a function while guarding against errors that happens within it.
63 * Returns an error if it throws, otherwise null.
64 *
65 * In production, this is implemented using a try-catch. The reason we don't
66 * use a try-catch directly is so that we can swap out a different
67 * implementation in DEV mode.
68 *
69 * @param {String} name of the guard to use for logging or debugging
70 * @param {Function} func The function to invoke
71 * @param {*} context The context to use when calling the function
72 * @param {...*} args Arguments for function
73 */
74
75
76/**
77 * Same as invokeGuardedCallback, but instead of returning an error, it stores
78 * it in a global so it can be rethrown by `rethrowCaughtError` later.
79 * TODO: See if caughtError and rethrowError can be unified.
80 *
81 * @param {String} name of the guard to use for logging or debugging
82 * @param {Function} func The function to invoke
83 * @param {*} context The context to use when calling the function
84 * @param {...*} args Arguments for function
85 */
86
87
88/**
89 * During execution of guarded functions we will capture the first error which
90 * we will rethrow to be handled by the top level error handler.
91 */
92
93/**
94 * Similar to invariant but only logs a warning if the condition is not met.
95 * This can be used to log issues in development environments in critical
96 * paths. Removing the logging code for production environments will keep the
97 * same logic and follow the same code paths.
98 */
99var warningWithoutStack = function () {};
100
101{
102 warningWithoutStack = function (condition, format) {
103 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
104 args[_key - 2] = arguments[_key];
105 }
106
107 if (format === undefined) {
108 throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
109 }
110
111 if (args.length > 8) {
112 // Check before the condition to catch violations early.
113 throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
114 }
115
116 if (condition) {
117 return;
118 }
119
120 if (typeof console !== 'undefined') {
121 var argsWithFormat = args.map(function (item) {
122 return '' + item;
123 });
124 argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
125 // breaks IE9: https://github.com/facebook/react/issues/13610
126
127 Function.prototype.apply.call(console.error, console, argsWithFormat);
128 }
129
130 try {
131 // --- Welcome to debugging React ---
132 // This error was thrown as a convenience so that you can use this stack
133 // to find the callsite that caused this warning to fire.
134 var argIndex = 0;
135 var message = 'Warning: ' + format.replace(/%s/g, function () {
136 return args[argIndex++];
137 });
138 throw new Error(message);
139 } catch (x) {}
140 };
141}
142
143var warningWithoutStack$1 = warningWithoutStack;
144
145var getFiberCurrentPropsFromNode$1 = null;
146var getInstanceFromNode$1 = null;
147var getNodeFromInstance$1 = null;
148function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) {
149 getFiberCurrentPropsFromNode$1 = getFiberCurrentPropsFromNodeImpl;
150 getInstanceFromNode$1 = getInstanceFromNodeImpl;
151 getNodeFromInstance$1 = getNodeFromInstanceImpl;
152
153 {
154 !(getNodeFromInstance$1 && getInstanceFromNode$1) ? warningWithoutStack$1(false, 'EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0;
155 }
156}
157var validateEventDispatches;
158
159{
160 validateEventDispatches = function (event) {
161 var dispatchListeners = event._dispatchListeners;
162 var dispatchInstances = event._dispatchInstances;
163 var listenersIsArr = Array.isArray(dispatchListeners);
164 var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
165 var instancesIsArr = Array.isArray(dispatchInstances);
166 var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
167 !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, 'EventPluginUtils: Invalid `event`.') : void 0;
168 };
169}
170/**
171 * Dispatch the event to the listener.
172 * @param {SyntheticEvent} event SyntheticEvent to handle
173 * @param {function} listener Application-level callback
174 * @param {*} inst Internal component instance
175 */
176
177
178
179/**
180 * Standard/simple iteration through an event's collected dispatches.
181 */
182
183
184/**
185 * Standard/simple iteration through an event's collected dispatches, but stops
186 * at the first dispatch execution returning true, and returns that id.
187 *
188 * @return {?string} id of the first dispatch execution who's listener returns
189 * true, or null if no listener returned true.
190 */
191
192function executeDispatchesInOrderStopAtTrueImpl(event) {
193 var dispatchListeners = event._dispatchListeners;
194 var dispatchInstances = event._dispatchInstances;
195
196 {
197 validateEventDispatches(event);
198 }
199
200 if (Array.isArray(dispatchListeners)) {
201 for (var i = 0; i < dispatchListeners.length; i++) {
202 if (event.isPropagationStopped()) {
203 break;
204 } // Listeners and Instances are two parallel arrays that are always in sync.
205
206
207 if (dispatchListeners[i](event, dispatchInstances[i])) {
208 return dispatchInstances[i];
209 }
210 }
211 } else if (dispatchListeners) {
212 if (dispatchListeners(event, dispatchInstances)) {
213 return dispatchInstances;
214 }
215 }
216
217 return null;
218}
219/**
220 * @see executeDispatchesInOrderStopAtTrueImpl
221 */
222
223
224function executeDispatchesInOrderStopAtTrue(event) {
225 var ret = executeDispatchesInOrderStopAtTrueImpl(event);
226 event._dispatchInstances = null;
227 event._dispatchListeners = null;
228 return ret;
229}
230/**
231 * Execution of a "direct" dispatch - there must be at most one dispatch
232 * accumulated on the event or it is considered an error. It doesn't really make
233 * sense for an event with multiple dispatches (bubbled) to keep track of the
234 * return values at each dispatch execution, but it does tend to make sense when
235 * dealing with "direct" dispatches.
236 *
237 * @return {*} The return value of executing the single dispatch.
238 */
239
240function executeDirectDispatch(event) {
241 {
242 validateEventDispatches(event);
243 }
244
245 var dispatchListener = event._dispatchListeners;
246 var dispatchInstance = event._dispatchInstances;
247
248 if (!!Array.isArray(dispatchListener)) {
249 {
250 throw Error("executeDirectDispatch(...): Invalid `event`.");
251 }
252 }
253
254 event.currentTarget = dispatchListener ? getNodeFromInstance$1(dispatchInstance) : null;
255 var res = dispatchListener ? dispatchListener(event) : null;
256 event.currentTarget = null;
257 event._dispatchListeners = null;
258 event._dispatchInstances = null;
259 return res;
260}
261/**
262 * @param {SyntheticEvent} event
263 * @return {boolean} True iff number of dispatches accumulated is greater than 0.
264 */
265
266function hasDispatches(event) {
267 return !!event._dispatchListeners;
268}
269
270// Before we know whether it is function or class
271
272 // Root of a host tree. Could be nested inside another node.
273
274 // A subtree. Could be an entry point to a different renderer.
275
276var HostComponent = 5;
277
278function getParent(inst) {
279 do {
280 inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
281 // That is depending on if we want nested subtrees (layers) to bubble
282 // events to their parent. We could also go through parentNode on the
283 // host node but that wouldn't work for React Native and doesn't let us
284 // do the portal feature.
285 } while (inst && inst.tag !== HostComponent);
286
287 if (inst) {
288 return inst;
289 }
290
291 return null;
292}
293/**
294 * Return the lowest common ancestor of A and B, or null if they are in
295 * different trees.
296 */
297
298
299function getLowestCommonAncestor(instA, instB) {
300 var depthA = 0;
301
302 for (var tempA = instA; tempA; tempA = getParent(tempA)) {
303 depthA++;
304 }
305
306 var depthB = 0;
307
308 for (var tempB = instB; tempB; tempB = getParent(tempB)) {
309 depthB++;
310 } // If A is deeper, crawl up.
311
312
313 while (depthA - depthB > 0) {
314 instA = getParent(instA);
315 depthA--;
316 } // If B is deeper, crawl up.
317
318
319 while (depthB - depthA > 0) {
320 instB = getParent(instB);
321 depthB--;
322 } // Walk in lockstep until we find a match.
323
324
325 var depth = depthA;
326
327 while (depth--) {
328 if (instA === instB || instA === instB.alternate) {
329 return instA;
330 }
331
332 instA = getParent(instA);
333 instB = getParent(instB);
334 }
335
336 return null;
337}
338/**
339 * Return if A is an ancestor of B.
340 */
341
342function isAncestor(instA, instB) {
343 while (instB) {
344 if (instA === instB || instA === instB.alternate) {
345 return true;
346 }
347
348 instB = getParent(instB);
349 }
350
351 return false;
352}
353/**
354 * Return the parent instance of the passed-in instance.
355 */
356
357function getParentInstance(inst) {
358 return getParent(inst);
359}
360/**
361 * Simulates the traversal of a two-phase, capture/bubble event dispatch.
362 */
363
364function traverseTwoPhase(inst, fn, arg) {
365 var path = [];
366
367 while (inst) {
368 path.push(inst);
369 inst = getParent(inst);
370 }
371
372 var i;
373
374 for (i = path.length; i-- > 0;) {
375 fn(path[i], 'captured', arg);
376 }
377
378 for (i = 0; i < path.length; i++) {
379 fn(path[i], 'bubbled', arg);
380 }
381}
382/**
383 * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
384 * should would receive a `mouseEnter` or `mouseLeave` event.
385 *
386 * Does not invoke the callback on the nearest common ancestor because nothing
387 * "entered" or "left" that element.
388 */
389
390/**
391 * Registers plugins so that they can extract and dispatch events.
392 *
393 * @see {EventPluginHub}
394 */
395
396/**
397 * Ordered list of injected plugins.
398 */
399
400
401
402/**
403 * Mapping from event name to dispatch config
404 */
405
406
407/**
408 * Mapping from registration name to plugin module
409 */
410
411
412/**
413 * Mapping from registration name to event name
414 */
415
416
417/**
418 * Mapping from lowercase registration names to the properly cased version,
419 * used to warn in the case of missing event handlers. Available
420 * only in true.
421 * @type {Object}
422 */
423
424 // Trust the developer to only use possibleRegistrationNames in true
425
426/**
427 * Injects an ordering of plugins (by plugin name). This allows the ordering
428 * to be decoupled from injection of the actual plugins so that ordering is
429 * always deterministic regardless of packaging, on-the-fly injection, etc.
430 *
431 * @param {array} InjectedEventPluginOrder
432 * @internal
433 * @see {EventPluginHub.injection.injectEventPluginOrder}
434 */
435
436
437/**
438 * Injects plugins to be used by `EventPluginHub`. The plugin names must be
439 * in the ordering injected by `injectEventPluginOrder`.
440 *
441 * Plugins can be injected as part of page initialization or on-the-fly.
442 *
443 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
444 * @internal
445 * @see {EventPluginHub.injection.injectEventPluginsByName}
446 */
447
448/**
449 * Accumulates items that must not be null or undefined into the first one. This
450 * is used to conserve memory by avoiding array allocations, and thus sacrifices
451 * API cleanness. Since `current` can be null before being passed in and not
452 * null after this function, make sure to assign it back to `current`:
453 *
454 * `a = accumulateInto(a, b);`
455 *
456 * This API should be sparingly used. Try `accumulate` for something cleaner.
457 *
458 * @return {*|array<*>} An accumulation of items.
459 */
460
461function accumulateInto(current, next) {
462 if (!(next != null)) {
463 {
464 throw Error("accumulateInto(...): Accumulated items must not be null or undefined.");
465 }
466 }
467
468 if (current == null) {
469 return next;
470 } // Both are not empty. Warning: Never call x.concat(y) when you are not
471 // certain that x is an Array (x could be a string with concat method).
472
473
474 if (Array.isArray(current)) {
475 if (Array.isArray(next)) {
476 current.push.apply(current, next);
477 return current;
478 }
479
480 current.push(next);
481 return current;
482 }
483
484 if (Array.isArray(next)) {
485 // A bit too dangerous to mutate `next`.
486 return [current].concat(next);
487 }
488
489 return [current, next];
490}
491
492/**
493 * @param {array} arr an "accumulation" of items which is either an Array or
494 * a single item. Useful when paired with the `accumulate` module. This is a
495 * simple utility that allows us to reason about a collection of items, but
496 * handling the case when there is exactly one item (and we do not need to
497 * allocate an array).
498 * @param {function} cb Callback invoked with each element or a collection.
499 * @param {?} [scope] Scope used as `this` in a callback.
500 */
501function forEachAccumulated(arr, cb, scope) {
502 if (Array.isArray(arr)) {
503 arr.forEach(cb, scope);
504 } else if (arr) {
505 cb.call(scope, arr);
506 }
507}
508
509function isInteractive(tag) {
510 return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
511}
512
513function shouldPreventMouseEvent(name, type, props) {
514 switch (name) {
515 case 'onClick':
516 case 'onClickCapture':
517 case 'onDoubleClick':
518 case 'onDoubleClickCapture':
519 case 'onMouseDown':
520 case 'onMouseDownCapture':
521 case 'onMouseMove':
522 case 'onMouseMoveCapture':
523 case 'onMouseUp':
524 case 'onMouseUpCapture':
525 return !!(props.disabled && isInteractive(type));
526
527 default:
528 return false;
529 }
530}
531/**
532 * This is a unified interface for event plugins to be installed and configured.
533 *
534 * Event plugins can implement the following properties:
535 *
536 * `extractEvents` {function(string, DOMEventTarget, string, object): *}
537 * Required. When a top-level event is fired, this method is expected to
538 * extract synthetic events that will in turn be queued and dispatched.
539 *
540 * `eventTypes` {object}
541 * Optional, plugins that fire events must publish a mapping of registration
542 * names that are used to register listeners. Values of this mapping must
543 * be objects that contain `registrationName` or `phasedRegistrationNames`.
544 *
545 * `executeDispatch` {function(object, function, string)}
546 * Optional, allows plugins to override how an event gets dispatched. By
547 * default, the listener is simply invoked.
548 *
549 * Each plugin that is injected into `EventsPluginHub` is immediately operable.
550 *
551 * @public
552 */
553
554/**
555 * Methods for injecting dependencies.
556 */
557
558
559
560/**
561 * @param {object} inst The instance, which is the source of events.
562 * @param {string} registrationName Name of listener (e.g. `onClick`).
563 * @return {?function} The stored callback.
564 */
565
566function getListener(inst, registrationName) {
567 var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
568 // live here; needs to be moved to a better place soon
569
570 var stateNode = inst.stateNode;
571
572 if (!stateNode) {
573 // Work in progress (ex: onload events in incremental mode).
574 return null;
575 }
576
577 var props = getFiberCurrentPropsFromNode$1(stateNode);
578
579 if (!props) {
580 // Work in progress.
581 return null;
582 }
583
584 listener = props[registrationName];
585
586 if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
587 return null;
588 }
589
590 if (!(!listener || typeof listener === 'function')) {
591 {
592 throw Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
593 }
594 }
595
596 return listener;
597}
598
599/**
600 * Some event types have a notion of different registration names for different
601 * "phases" of propagation. This finds listeners by a given phase.
602 */
603function listenerAtPhase(inst, event, propagationPhase) {
604 var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
605 return getListener(inst, registrationName);
606}
607/**
608 * A small set of propagation patterns, each of which will accept a small amount
609 * of information, and generate a set of "dispatch ready event objects" - which
610 * are sets of events that have already been annotated with a set of dispatched
611 * listener functions/ids. The API is designed this way to discourage these
612 * propagation strategies from actually executing the dispatches, since we
613 * always want to collect the entire set of dispatches before executing even a
614 * single one.
615 */
616
617/**
618 * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
619 * here, allows us to not have to bind or create functions for each event.
620 * Mutating the event's members allows us to not have to create a wrapping
621 * "dispatch" object that pairs the event with the listener.
622 */
623
624
625function accumulateDirectionalDispatches(inst, phase, event) {
626 {
627 !inst ? warningWithoutStack$1(false, 'Dispatching inst must not be null') : void 0;
628 }
629
630 var listener = listenerAtPhase(inst, event, phase);
631
632 if (listener) {
633 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
634 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
635 }
636}
637/**
638 * Collect dispatches (must be entirely collected before dispatching - see unit
639 * tests). Lazily allocate the array to conserve memory. We must loop through
640 * each event and perform the traversal for each one. We cannot perform a
641 * single traversal for the entire collection of events because each event may
642 * have a different target.
643 */
644
645
646function accumulateTwoPhaseDispatchesSingle(event) {
647 if (event && event.dispatchConfig.phasedRegistrationNames) {
648 traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
649 }
650}
651/**
652 * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
653 */
654
655
656function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
657 if (event && event.dispatchConfig.phasedRegistrationNames) {
658 var targetInst = event._targetInst;
659 var parentInst = targetInst ? getParentInstance(targetInst) : null;
660 traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event);
661 }
662}
663/**
664 * Accumulates without regard to direction, does not look for phased
665 * registration names. Same as `accumulateDirectDispatchesSingle` but without
666 * requiring that the `dispatchMarker` be the same as the dispatched ID.
667 */
668
669
670function accumulateDispatches(inst, ignoredDirection, event) {
671 if (inst && event && event.dispatchConfig.registrationName) {
672 var registrationName = event.dispatchConfig.registrationName;
673 var listener = getListener(inst, registrationName);
674
675 if (listener) {
676 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
677 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
678 }
679 }
680}
681/**
682 * Accumulates dispatches on an `SyntheticEvent`, but only for the
683 * `dispatchMarker`.
684 * @param {SyntheticEvent} event
685 */
686
687
688function accumulateDirectDispatchesSingle(event) {
689 if (event && event.dispatchConfig.registrationName) {
690 accumulateDispatches(event._targetInst, null, event);
691 }
692}
693
694function accumulateTwoPhaseDispatches(events) {
695 forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
696}
697function accumulateTwoPhaseDispatchesSkipTarget(events) {
698 forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
699}
700
701function accumulateDirectDispatches(events) {
702 forEachAccumulated(events, accumulateDirectDispatchesSingle);
703}
704
705var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
706var _assign = ReactInternals.assign;
707
708/* eslint valid-typeof: 0 */
709var EVENT_POOL_SIZE = 10;
710/**
711 * @interface Event
712 * @see http://www.w3.org/TR/DOM-Level-3-Events/
713 */
714
715var EventInterface = {
716 type: null,
717 target: null,
718 // currentTarget is set when dispatching; no use in copying it here
719 currentTarget: function () {
720 return null;
721 },
722 eventPhase: null,
723 bubbles: null,
724 cancelable: null,
725 timeStamp: function (event) {
726 return event.timeStamp || Date.now();
727 },
728 defaultPrevented: null,
729 isTrusted: null
730};
731
732function functionThatReturnsTrue() {
733 return true;
734}
735
736function functionThatReturnsFalse() {
737 return false;
738}
739/**
740 * Synthetic events are dispatched by event plugins, typically in response to a
741 * top-level event delegation handler.
742 *
743 * These systems should generally use pooling to reduce the frequency of garbage
744 * collection. The system should check `isPersistent` to determine whether the
745 * event should be released into the pool after being dispatched. Users that
746 * need a persisted event should invoke `persist`.
747 *
748 * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
749 * normalizing browser quirks. Subclasses do not necessarily have to implement a
750 * DOM interface; custom application-specific events can also subclass this.
751 *
752 * @param {object} dispatchConfig Configuration used to dispatch this event.
753 * @param {*} targetInst Marker identifying the event target.
754 * @param {object} nativeEvent Native browser event.
755 * @param {DOMEventTarget} nativeEventTarget Target node.
756 */
757
758
759function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
760 {
761 // these have a getter/setter for warnings
762 delete this.nativeEvent;
763 delete this.preventDefault;
764 delete this.stopPropagation;
765 delete this.isDefaultPrevented;
766 delete this.isPropagationStopped;
767 }
768
769 this.dispatchConfig = dispatchConfig;
770 this._targetInst = targetInst;
771 this.nativeEvent = nativeEvent;
772 var Interface = this.constructor.Interface;
773
774 for (var propName in Interface) {
775 if (!Interface.hasOwnProperty(propName)) {
776 continue;
777 }
778
779 {
780 delete this[propName]; // this has a getter/setter for warnings
781 }
782
783 var normalize = Interface[propName];
784
785 if (normalize) {
786 this[propName] = normalize(nativeEvent);
787 } else {
788 if (propName === 'target') {
789 this.target = nativeEventTarget;
790 } else {
791 this[propName] = nativeEvent[propName];
792 }
793 }
794 }
795
796 var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
797
798 if (defaultPrevented) {
799 this.isDefaultPrevented = functionThatReturnsTrue;
800 } else {
801 this.isDefaultPrevented = functionThatReturnsFalse;
802 }
803
804 this.isPropagationStopped = functionThatReturnsFalse;
805 return this;
806}
807
808_assign(SyntheticEvent.prototype, {
809 preventDefault: function () {
810 this.defaultPrevented = true;
811 var event = this.nativeEvent;
812
813 if (!event) {
814 return;
815 }
816
817 if (event.preventDefault) {
818 event.preventDefault();
819 } else if (typeof event.returnValue !== 'unknown') {
820 event.returnValue = false;
821 }
822
823 this.isDefaultPrevented = functionThatReturnsTrue;
824 },
825 stopPropagation: function () {
826 var event = this.nativeEvent;
827
828 if (!event) {
829 return;
830 }
831
832 if (event.stopPropagation) {
833 event.stopPropagation();
834 } else if (typeof event.cancelBubble !== 'unknown') {
835 // The ChangeEventPlugin registers a "propertychange" event for
836 // IE. This event does not support bubbling or cancelling, and
837 // any references to cancelBubble throw "Member not found". A
838 // typeof check of "unknown" circumvents this issue (and is also
839 // IE specific).
840 event.cancelBubble = true;
841 }
842
843 this.isPropagationStopped = functionThatReturnsTrue;
844 },
845
846 /**
847 * We release all dispatched `SyntheticEvent`s after each event loop, adding
848 * them back into the pool. This allows a way to hold onto a reference that
849 * won't be added back into the pool.
850 */
851 persist: function () {
852 this.isPersistent = functionThatReturnsTrue;
853 },
854
855 /**
856 * Checks if this event should be released back into the pool.
857 *
858 * @return {boolean} True if this should not be released, false otherwise.
859 */
860 isPersistent: functionThatReturnsFalse,
861
862 /**
863 * `PooledClass` looks for `destructor` on each instance it releases.
864 */
865 destructor: function () {
866 var Interface = this.constructor.Interface;
867
868 for (var propName in Interface) {
869 {
870 Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
871 }
872 }
873
874 this.dispatchConfig = null;
875 this._targetInst = null;
876 this.nativeEvent = null;
877 this.isDefaultPrevented = functionThatReturnsFalse;
878 this.isPropagationStopped = functionThatReturnsFalse;
879 this._dispatchListeners = null;
880 this._dispatchInstances = null;
881
882 {
883 Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
884 Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
885 Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
886 Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
887 Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
888 }
889 }
890});
891
892SyntheticEvent.Interface = EventInterface;
893/**
894 * Helper to reduce boilerplate when creating subclasses.
895 */
896
897SyntheticEvent.extend = function (Interface) {
898 var Super = this;
899
900 var E = function () {};
901
902 E.prototype = Super.prototype;
903 var prototype = new E();
904
905 function Class() {
906 return Super.apply(this, arguments);
907 }
908
909 _assign(prototype, Class.prototype);
910
911 Class.prototype = prototype;
912 Class.prototype.constructor = Class;
913 Class.Interface = _assign({}, Super.Interface, Interface);
914 Class.extend = Super.extend;
915 addEventPoolingTo(Class);
916 return Class;
917};
918
919addEventPoolingTo(SyntheticEvent);
920/**
921 * Helper to nullify syntheticEvent instance properties when destructing
922 *
923 * @param {String} propName
924 * @param {?object} getVal
925 * @return {object} defineProperty object
926 */
927
928function getPooledWarningPropertyDefinition(propName, getVal) {
929 var isFunction = typeof getVal === 'function';
930 return {
931 configurable: true,
932 set: set,
933 get: get
934 };
935
936 function set(val) {
937 var action = isFunction ? 'setting the method' : 'setting the property';
938 warn(action, 'This is effectively a no-op');
939 return val;
940 }
941
942 function get() {
943 var action = isFunction ? 'accessing the method' : 'accessing the property';
944 var result = isFunction ? 'This is a no-op function' : 'This is set to null';
945 warn(action, result);
946 return getVal;
947 }
948
949 function warn(action, result) {
950 var warningCondition = false;
951 !warningCondition ? warningWithoutStack$1(false, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0;
952 }
953}
954
955function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
956 var EventConstructor = this;
957
958 if (EventConstructor.eventPool.length) {
959 var instance = EventConstructor.eventPool.pop();
960 EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
961 return instance;
962 }
963
964 return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
965}
966
967function releasePooledEvent(event) {
968 var EventConstructor = this;
969
970 if (!(event instanceof EventConstructor)) {
971 {
972 throw Error("Trying to release an event instance into a pool of a different type.");
973 }
974 }
975
976 event.destructor();
977
978 if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
979 EventConstructor.eventPool.push(event);
980 }
981}
982
983function addEventPoolingTo(EventConstructor) {
984 EventConstructor.eventPool = [];
985 EventConstructor.getPooled = getPooledEvent;
986 EventConstructor.release = releasePooledEvent;
987}
988
989/**
990 * `touchHistory` isn't actually on the native event, but putting it in the
991 * interface will ensure that it is cleaned up when pooled/destroyed. The
992 * `ResponderEventPlugin` will populate it appropriately.
993 */
994
995var ResponderSyntheticEvent = SyntheticEvent.extend({
996 touchHistory: function (nativeEvent) {
997 return null; // Actually doesn't even look at the native event.
998 }
999});
1000
1001// Note: ideally these would be imported from DOMTopLevelEventTypes,
1002// but our build system currently doesn't let us do that from a fork.
1003var TOP_TOUCH_START = 'touchstart';
1004var TOP_TOUCH_MOVE = 'touchmove';
1005var TOP_TOUCH_END = 'touchend';
1006var TOP_TOUCH_CANCEL = 'touchcancel';
1007var TOP_SCROLL = 'scroll';
1008var TOP_SELECTION_CHANGE = 'selectionchange';
1009var TOP_MOUSE_DOWN = 'mousedown';
1010var TOP_MOUSE_MOVE = 'mousemove';
1011var TOP_MOUSE_UP = 'mouseup';
1012function isStartish(topLevelType) {
1013 return topLevelType === TOP_TOUCH_START || topLevelType === TOP_MOUSE_DOWN;
1014}
1015function isMoveish(topLevelType) {
1016 return topLevelType === TOP_TOUCH_MOVE || topLevelType === TOP_MOUSE_MOVE;
1017}
1018function isEndish(topLevelType) {
1019 return topLevelType === TOP_TOUCH_END || topLevelType === TOP_TOUCH_CANCEL || topLevelType === TOP_MOUSE_UP;
1020}
1021var startDependencies = [TOP_TOUCH_START, TOP_MOUSE_DOWN];
1022var moveDependencies = [TOP_TOUCH_MOVE, TOP_MOUSE_MOVE];
1023var endDependencies = [TOP_TOUCH_CANCEL, TOP_TOUCH_END, TOP_MOUSE_UP];
1024
1025/**
1026 * Tracks the position and time of each active touch by `touch.identifier`. We
1027 * should typically only see IDs in the range of 1-20 because IDs get recycled
1028 * when touches end and start again.
1029 */
1030
1031var MAX_TOUCH_BANK = 20;
1032var touchBank = [];
1033var touchHistory = {
1034 touchBank: touchBank,
1035 numberActiveTouches: 0,
1036 // If there is only one active touch, we remember its location. This prevents
1037 // us having to loop through all of the touches all the time in the most
1038 // common case.
1039 indexOfSingleActiveTouch: -1,
1040 mostRecentTimeStamp: 0
1041};
1042
1043function timestampForTouch(touch) {
1044 // The legacy internal implementation provides "timeStamp", which has been
1045 // renamed to "timestamp". Let both work for now while we iron it out
1046 // TODO (evv): rename timeStamp to timestamp in internal code
1047 return touch.timeStamp || touch.timestamp;
1048}
1049/**
1050 * TODO: Instead of making gestures recompute filtered velocity, we could
1051 * include a built in velocity computation that can be reused globally.
1052 */
1053
1054
1055function createTouchRecord(touch) {
1056 return {
1057 touchActive: true,
1058 startPageX: touch.pageX,
1059 startPageY: touch.pageY,
1060 startTimeStamp: timestampForTouch(touch),
1061 currentPageX: touch.pageX,
1062 currentPageY: touch.pageY,
1063 currentTimeStamp: timestampForTouch(touch),
1064 previousPageX: touch.pageX,
1065 previousPageY: touch.pageY,
1066 previousTimeStamp: timestampForTouch(touch)
1067 };
1068}
1069
1070function resetTouchRecord(touchRecord, touch) {
1071 touchRecord.touchActive = true;
1072 touchRecord.startPageX = touch.pageX;
1073 touchRecord.startPageY = touch.pageY;
1074 touchRecord.startTimeStamp = timestampForTouch(touch);
1075 touchRecord.currentPageX = touch.pageX;
1076 touchRecord.currentPageY = touch.pageY;
1077 touchRecord.currentTimeStamp = timestampForTouch(touch);
1078 touchRecord.previousPageX = touch.pageX;
1079 touchRecord.previousPageY = touch.pageY;
1080 touchRecord.previousTimeStamp = timestampForTouch(touch);
1081}
1082
1083function getTouchIdentifier(_ref) {
1084 var identifier = _ref.identifier;
1085
1086 if (!(identifier != null)) {
1087 {
1088 throw Error("Touch object is missing identifier.");
1089 }
1090 }
1091
1092 {
1093 !(identifier <= MAX_TOUCH_BANK) ? warningWithoutStack$1(false, 'Touch identifier %s is greater than maximum supported %s which causes ' + 'performance issues backfilling array locations for all of the indices.', identifier, MAX_TOUCH_BANK) : void 0;
1094 }
1095
1096 return identifier;
1097}
1098
1099function recordTouchStart(touch) {
1100 var identifier = getTouchIdentifier(touch);
1101 var touchRecord = touchBank[identifier];
1102
1103 if (touchRecord) {
1104 resetTouchRecord(touchRecord, touch);
1105 } else {
1106 touchBank[identifier] = createTouchRecord(touch);
1107 }
1108
1109 touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
1110}
1111
1112function recordTouchMove(touch) {
1113 var touchRecord = touchBank[getTouchIdentifier(touch)];
1114
1115 if (touchRecord) {
1116 touchRecord.touchActive = true;
1117 touchRecord.previousPageX = touchRecord.currentPageX;
1118 touchRecord.previousPageY = touchRecord.currentPageY;
1119 touchRecord.previousTimeStamp = touchRecord.currentTimeStamp;
1120 touchRecord.currentPageX = touch.pageX;
1121 touchRecord.currentPageY = touch.pageY;
1122 touchRecord.currentTimeStamp = timestampForTouch(touch);
1123 touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
1124 } else {
1125 console.warn('Cannot record touch move without a touch start.\n' + 'Touch Move: %s\n', 'Touch Bank: %s', printTouch(touch), printTouchBank());
1126 }
1127}
1128
1129function recordTouchEnd(touch) {
1130 var touchRecord = touchBank[getTouchIdentifier(touch)];
1131
1132 if (touchRecord) {
1133 touchRecord.touchActive = false;
1134 touchRecord.previousPageX = touchRecord.currentPageX;
1135 touchRecord.previousPageY = touchRecord.currentPageY;
1136 touchRecord.previousTimeStamp = touchRecord.currentTimeStamp;
1137 touchRecord.currentPageX = touch.pageX;
1138 touchRecord.currentPageY = touch.pageY;
1139 touchRecord.currentTimeStamp = timestampForTouch(touch);
1140 touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
1141 } else {
1142 console.warn('Cannot record touch end without a touch start.\n' + 'Touch End: %s\n', 'Touch Bank: %s', printTouch(touch), printTouchBank());
1143 }
1144}
1145
1146function printTouch(touch) {
1147 return JSON.stringify({
1148 identifier: touch.identifier,
1149 pageX: touch.pageX,
1150 pageY: touch.pageY,
1151 timestamp: timestampForTouch(touch)
1152 });
1153}
1154
1155function printTouchBank() {
1156 var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK));
1157
1158 if (touchBank.length > MAX_TOUCH_BANK) {
1159 printed += ' (original size: ' + touchBank.length + ')';
1160 }
1161
1162 return printed;
1163}
1164
1165var ResponderTouchHistoryStore = {
1166 recordTouchTrack: function (topLevelType, nativeEvent) {
1167 if (isMoveish(topLevelType)) {
1168 nativeEvent.changedTouches.forEach(recordTouchMove);
1169 } else if (isStartish(topLevelType)) {
1170 nativeEvent.changedTouches.forEach(recordTouchStart);
1171 touchHistory.numberActiveTouches = nativeEvent.touches.length;
1172
1173 if (touchHistory.numberActiveTouches === 1) {
1174 touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier;
1175 }
1176 } else if (isEndish(topLevelType)) {
1177 nativeEvent.changedTouches.forEach(recordTouchEnd);
1178 touchHistory.numberActiveTouches = nativeEvent.touches.length;
1179
1180 if (touchHistory.numberActiveTouches === 1) {
1181 for (var i = 0; i < touchBank.length; i++) {
1182 var touchTrackToCheck = touchBank[i];
1183
1184 if (touchTrackToCheck != null && touchTrackToCheck.touchActive) {
1185 touchHistory.indexOfSingleActiveTouch = i;
1186 break;
1187 }
1188 }
1189
1190 {
1191 var activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch];
1192 !(activeRecord != null && activeRecord.touchActive) ? warningWithoutStack$1(false, 'Cannot find single active touch.') : void 0;
1193 }
1194 }
1195 }
1196 },
1197 touchHistory: touchHistory
1198};
1199
1200/**
1201 * Accumulates items that must not be null or undefined.
1202 *
1203 * This is used to conserve memory by avoiding array allocations.
1204 *
1205 * @return {*|array<*>} An accumulation of items.
1206 */
1207
1208function accumulate(current, next) {
1209 if (!(next != null)) {
1210 {
1211 throw Error("accumulate(...): Accumulated items must not be null or undefined.");
1212 }
1213 }
1214
1215 if (current == null) {
1216 return next;
1217 } // Both are not empty. Warning: Never call x.concat(y) when you are not
1218 // certain that x is an Array (x could be a string with concat method).
1219
1220
1221 if (Array.isArray(current)) {
1222 return current.concat(next);
1223 }
1224
1225 if (Array.isArray(next)) {
1226 return [current].concat(next);
1227 }
1228
1229 return [current, next];
1230}
1231
1232/**
1233 * Instance of element that should respond to touch/move types of interactions,
1234 * as indicated explicitly by relevant callbacks.
1235 */
1236
1237var responderInst = null;
1238/**
1239 * Count of current touches. A textInput should become responder iff the
1240 * selection changes while there is a touch on the screen.
1241 */
1242
1243var trackedTouchCount = 0;
1244
1245var changeResponder = function (nextResponderInst, blockHostResponder) {
1246 var oldResponderInst = responderInst;
1247 responderInst = nextResponderInst;
1248
1249 if (ResponderEventPlugin.GlobalResponderHandler !== null) {
1250 ResponderEventPlugin.GlobalResponderHandler.onChange(oldResponderInst, nextResponderInst, blockHostResponder);
1251 }
1252};
1253
1254var eventTypes = {
1255 /**
1256 * On a `touchStart`/`mouseDown`, is it desired that this element become the
1257 * responder?
1258 */
1259 startShouldSetResponder: {
1260 phasedRegistrationNames: {
1261 bubbled: 'onStartShouldSetResponder',
1262 captured: 'onStartShouldSetResponderCapture'
1263 },
1264 dependencies: startDependencies
1265 },
1266
1267 /**
1268 * On a `scroll`, is it desired that this element become the responder? This
1269 * is usually not needed, but should be used to retroactively infer that a
1270 * `touchStart` had occurred during momentum scroll. During a momentum scroll,
1271 * a touch start will be immediately followed by a scroll event if the view is
1272 * currently scrolling.
1273 *
1274 * TODO: This shouldn't bubble.
1275 */
1276 scrollShouldSetResponder: {
1277 phasedRegistrationNames: {
1278 bubbled: 'onScrollShouldSetResponder',
1279 captured: 'onScrollShouldSetResponderCapture'
1280 },
1281 dependencies: [TOP_SCROLL]
1282 },
1283
1284 /**
1285 * On text selection change, should this element become the responder? This
1286 * is needed for text inputs or other views with native selection, so the
1287 * JS view can claim the responder.
1288 *
1289 * TODO: This shouldn't bubble.
1290 */
1291 selectionChangeShouldSetResponder: {
1292 phasedRegistrationNames: {
1293 bubbled: 'onSelectionChangeShouldSetResponder',
1294 captured: 'onSelectionChangeShouldSetResponderCapture'
1295 },
1296 dependencies: [TOP_SELECTION_CHANGE]
1297 },
1298
1299 /**
1300 * On a `touchMove`/`mouseMove`, is it desired that this element become the
1301 * responder?
1302 */
1303 moveShouldSetResponder: {
1304 phasedRegistrationNames: {
1305 bubbled: 'onMoveShouldSetResponder',
1306 captured: 'onMoveShouldSetResponderCapture'
1307 },
1308 dependencies: moveDependencies
1309 },
1310
1311 /**
1312 * Direct responder events dispatched directly to responder. Do not bubble.
1313 */
1314 responderStart: {
1315 registrationName: 'onResponderStart',
1316 dependencies: startDependencies
1317 },
1318 responderMove: {
1319 registrationName: 'onResponderMove',
1320 dependencies: moveDependencies
1321 },
1322 responderEnd: {
1323 registrationName: 'onResponderEnd',
1324 dependencies: endDependencies
1325 },
1326 responderRelease: {
1327 registrationName: 'onResponderRelease',
1328 dependencies: endDependencies
1329 },
1330 responderTerminationRequest: {
1331 registrationName: 'onResponderTerminationRequest',
1332 dependencies: []
1333 },
1334 responderGrant: {
1335 registrationName: 'onResponderGrant',
1336 dependencies: []
1337 },
1338 responderReject: {
1339 registrationName: 'onResponderReject',
1340 dependencies: []
1341 },
1342 responderTerminate: {
1343 registrationName: 'onResponderTerminate',
1344 dependencies: []
1345 }
1346};
1347/**
1348 *
1349 * Responder System:
1350 * ----------------
1351 *
1352 * - A global, solitary "interaction lock" on a view.
1353 * - If a node becomes the responder, it should convey visual feedback
1354 * immediately to indicate so, either by highlighting or moving accordingly.
1355 * - To be the responder means, that touches are exclusively important to that
1356 * responder view, and no other view.
1357 * - While touches are still occurring, the responder lock can be transferred to
1358 * a new view, but only to increasingly "higher" views (meaning ancestors of
1359 * the current responder).
1360 *
1361 * Responder being granted:
1362 * ------------------------
1363 *
1364 * - Touch starts, moves, and scrolls can cause an ID to become the responder.
1365 * - We capture/bubble `startShouldSetResponder`/`moveShouldSetResponder` to
1366 * the "appropriate place".
1367 * - If nothing is currently the responder, the "appropriate place" is the
1368 * initiating event's `targetID`.
1369 * - If something *is* already the responder, the "appropriate place" is the
1370 * first common ancestor of the event target and the current `responderInst`.
1371 * - Some negotiation happens: See the timing diagram below.
1372 * - Scrolled views automatically become responder. The reasoning is that a
1373 * platform scroll view that isn't built on top of the responder system has
1374 * began scrolling, and the active responder must now be notified that the
1375 * interaction is no longer locked to it - the system has taken over.
1376 *
1377 * - Responder being released:
1378 * As soon as no more touches that *started* inside of descendants of the
1379 * *current* responderInst, an `onResponderRelease` event is dispatched to the
1380 * current responder, and the responder lock is released.
1381 *
1382 * TODO:
1383 * - on "end", a callback hook for `onResponderEndShouldRemainResponder` that
1384 * determines if the responder lock should remain.
1385 * - If a view shouldn't "remain" the responder, any active touches should by
1386 * default be considered "dead" and do not influence future negotiations or
1387 * bubble paths. It should be as if those touches do not exist.
1388 * -- For multitouch: Usually a translate-z will choose to "remain" responder
1389 * after one out of many touches ended. For translate-y, usually the view
1390 * doesn't wish to "remain" responder after one of many touches end.
1391 * - Consider building this on top of a `stopPropagation` model similar to
1392 * `W3C` events.
1393 * - Ensure that `onResponderTerminate` is called on touch cancels, whether or
1394 * not `onResponderTerminationRequest` returns `true` or `false`.
1395 *
1396 */
1397
1398/* Negotiation Performed
1399 +-----------------------+
1400 / \
1401Process low level events to + Current Responder + wantsResponderID
1402determine who to perform negot-| (if any exists at all) |
1403iation/transition | Otherwise just pass through|
1404-------------------------------+----------------------------+------------------+
1405Bubble to find first ID | |
1406to return true:wantsResponderID| |
1407 | |
1408 +-------------+ | |
1409 | onTouchStart| | |
1410 +------+------+ none | |
1411 | return| |
1412+-----------v-------------+true| +------------------------+ |
1413|onStartShouldSetResponder|----->|onResponderStart (cur) |<-----------+
1414+-----------+-------------+ | +------------------------+ | |
1415 | | | +--------+-------+
1416 | returned true for| false:REJECT +-------->|onResponderReject
1417 | wantsResponderID | | | +----------------+
1418 | (now attempt | +------------------+-----+ |
1419 | handoff) | | onResponder | |
1420 +------------------->| TerminationRequest| |
1421 | +------------------+-----+ |
1422 | | | +----------------+
1423 | true:GRANT +-------->|onResponderGrant|
1424 | | +--------+-------+
1425 | +------------------------+ | |
1426 | | onResponderTerminate |<-----------+
1427 | +------------------+-----+ |
1428 | | | +----------------+
1429 | +-------->|onResponderStart|
1430 | | +----------------+
1431Bubble to find first ID | |
1432to return true:wantsResponderID| |
1433 | |
1434 +-------------+ | |
1435 | onTouchMove | | |
1436 +------+------+ none | |
1437 | return| |
1438+-----------v-------------+true| +------------------------+ |
1439|onMoveShouldSetResponder |----->|onResponderMove (cur) |<-----------+
1440+-----------+-------------+ | +------------------------+ | |
1441 | | | +--------+-------+
1442 | returned true for| false:REJECT +-------->|onResponderRejec|
1443 | wantsResponderID | | | +----------------+
1444 | (now attempt | +------------------+-----+ |
1445 | handoff) | | onResponder | |
1446 +------------------->| TerminationRequest| |
1447 | +------------------+-----+ |
1448 | | | +----------------+
1449 | true:GRANT +-------->|onResponderGrant|
1450 | | +--------+-------+
1451 | +------------------------+ | |
1452 | | onResponderTerminate |<-----------+
1453 | +------------------+-----+ |
1454 | | | +----------------+
1455 | +-------->|onResponderMove |
1456 | | +----------------+
1457 | |
1458 | |
1459 Some active touch started| |
1460 inside current responder | +------------------------+ |
1461 +------------------------->| onResponderEnd | |
1462 | | +------------------------+ |
1463 +---+---------+ | |
1464 | onTouchEnd | | |
1465 +---+---------+ | |
1466 | | +------------------------+ |
1467 +------------------------->| onResponderEnd | |
1468 No active touches started| +-----------+------------+ |
1469 inside current responder | | |
1470 | v |
1471 | +------------------------+ |
1472 | | onResponderRelease | |
1473 | +------------------------+ |
1474 | |
1475 + + */
1476
1477/**
1478 * A note about event ordering in the `EventPluginHub`.
1479 *
1480 * Suppose plugins are injected in the following order:
1481 *
1482 * `[R, S, C]`
1483 *
1484 * To help illustrate the example, assume `S` is `SimpleEventPlugin` (for
1485 * `onClick` etc) and `R` is `ResponderEventPlugin`.
1486 *
1487 * "Deferred-Dispatched Events":
1488 *
1489 * - The current event plugin system will traverse the list of injected plugins,
1490 * in order, and extract events by collecting the plugin's return value of
1491 * `extractEvents()`.
1492 * - These events that are returned from `extractEvents` are "deferred
1493 * dispatched events".
1494 * - When returned from `extractEvents`, deferred-dispatched events contain an
1495 * "accumulation" of deferred dispatches.
1496 * - These deferred dispatches are accumulated/collected before they are
1497 * returned, but processed at a later time by the `EventPluginHub` (hence the
1498 * name deferred).
1499 *
1500 * In the process of returning their deferred-dispatched events, event plugins
1501 * themselves can dispatch events on-demand without returning them from
1502 * `extractEvents`. Plugins might want to do this, so that they can use event
1503 * dispatching as a tool that helps them decide which events should be extracted
1504 * in the first place.
1505 *
1506 * "On-Demand-Dispatched Events":
1507 *
1508 * - On-demand-dispatched events are not returned from `extractEvents`.
1509 * - On-demand-dispatched events are dispatched during the process of returning
1510 * the deferred-dispatched events.
1511 * - They should not have side effects.
1512 * - They should be avoided, and/or eventually be replaced with another
1513 * abstraction that allows event plugins to perform multiple "rounds" of event
1514 * extraction.
1515 *
1516 * Therefore, the sequence of event dispatches becomes:
1517 *
1518 * - `R`s on-demand events (if any) (dispatched by `R` on-demand)
1519 * - `S`s on-demand events (if any) (dispatched by `S` on-demand)
1520 * - `C`s on-demand events (if any) (dispatched by `C` on-demand)
1521 * - `R`s extracted events (if any) (dispatched by `EventPluginHub`)
1522 * - `S`s extracted events (if any) (dispatched by `EventPluginHub`)
1523 * - `C`s extracted events (if any) (dispatched by `EventPluginHub`)
1524 *
1525 * In the case of `ResponderEventPlugin`: If the `startShouldSetResponder`
1526 * on-demand dispatch returns `true` (and some other details are satisfied) the
1527 * `onResponderGrant` deferred dispatched event is returned from
1528 * `extractEvents`. The sequence of dispatch executions in this case
1529 * will appear as follows:
1530 *
1531 * - `startShouldSetResponder` (`ResponderEventPlugin` dispatches on-demand)
1532 * - `touchStartCapture` (`EventPluginHub` dispatches as usual)
1533 * - `touchStart` (`EventPluginHub` dispatches as usual)
1534 * - `responderGrant/Reject` (`EventPluginHub` dispatches as usual)
1535 */
1536
1537function setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
1538 var shouldSetEventType = isStartish(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder : topLevelType === TOP_SELECTION_CHANGE ? eventTypes.selectionChangeShouldSetResponder : eventTypes.scrollShouldSetResponder; // TODO: stop one short of the current responder.
1539
1540 var bubbleShouldSetFrom = !responderInst ? targetInst : getLowestCommonAncestor(responderInst, targetInst); // When capturing/bubbling the "shouldSet" event, we want to skip the target
1541 // (deepest ID) if it happens to be the current responder. The reasoning:
1542 // It's strange to get an `onMoveShouldSetResponder` when you're *already*
1543 // the responder.
1544
1545 var skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst;
1546 var shouldSetEvent = ResponderSyntheticEvent.getPooled(shouldSetEventType, bubbleShouldSetFrom, nativeEvent, nativeEventTarget);
1547 shouldSetEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
1548
1549 if (skipOverBubbleShouldSetFrom) {
1550 accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent);
1551 } else {
1552 accumulateTwoPhaseDispatches(shouldSetEvent);
1553 }
1554
1555 var wantsResponderInst = executeDispatchesInOrderStopAtTrue(shouldSetEvent);
1556
1557 if (!shouldSetEvent.isPersistent()) {
1558 shouldSetEvent.constructor.release(shouldSetEvent);
1559 }
1560
1561 if (!wantsResponderInst || wantsResponderInst === responderInst) {
1562 return null;
1563 }
1564
1565 var extracted;
1566 var grantEvent = ResponderSyntheticEvent.getPooled(eventTypes.responderGrant, wantsResponderInst, nativeEvent, nativeEventTarget);
1567 grantEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
1568 accumulateDirectDispatches(grantEvent);
1569 var blockHostResponder = executeDirectDispatch(grantEvent) === true;
1570
1571 if (responderInst) {
1572 var terminationRequestEvent = ResponderSyntheticEvent.getPooled(eventTypes.responderTerminationRequest, responderInst, nativeEvent, nativeEventTarget);
1573 terminationRequestEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
1574 accumulateDirectDispatches(terminationRequestEvent);
1575 var shouldSwitch = !hasDispatches(terminationRequestEvent) || executeDirectDispatch(terminationRequestEvent);
1576
1577 if (!terminationRequestEvent.isPersistent()) {
1578 terminationRequestEvent.constructor.release(terminationRequestEvent);
1579 }
1580
1581 if (shouldSwitch) {
1582 var terminateEvent = ResponderSyntheticEvent.getPooled(eventTypes.responderTerminate, responderInst, nativeEvent, nativeEventTarget);
1583 terminateEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
1584 accumulateDirectDispatches(terminateEvent);
1585 extracted = accumulate(extracted, [grantEvent, terminateEvent]);
1586 changeResponder(wantsResponderInst, blockHostResponder);
1587 } else {
1588 var rejectEvent = ResponderSyntheticEvent.getPooled(eventTypes.responderReject, wantsResponderInst, nativeEvent, nativeEventTarget);
1589 rejectEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
1590 accumulateDirectDispatches(rejectEvent);
1591 extracted = accumulate(extracted, rejectEvent);
1592 }
1593 } else {
1594 extracted = accumulate(extracted, grantEvent);
1595 changeResponder(wantsResponderInst, blockHostResponder);
1596 }
1597
1598 return extracted;
1599}
1600/**
1601 * A transfer is a negotiation between a currently set responder and the next
1602 * element to claim responder status. Any start event could trigger a transfer
1603 * of responderInst. Any move event could trigger a transfer.
1604 *
1605 * @param {string} topLevelType Record from `BrowserEventConstants`.
1606 * @return {boolean} True if a transfer of responder could possibly occur.
1607 */
1608
1609
1610function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) {
1611 return topLevelInst && ( // responderIgnoreScroll: We are trying to migrate away from specifically
1612 // tracking native scroll events here and responderIgnoreScroll indicates we
1613 // will send topTouchCancel to handle canceling touch events instead
1614 topLevelType === TOP_SCROLL && !nativeEvent.responderIgnoreScroll || trackedTouchCount > 0 && topLevelType === TOP_SELECTION_CHANGE || isStartish(topLevelType) || isMoveish(topLevelType));
1615}
1616/**
1617 * Returns whether or not this touch end event makes it such that there are no
1618 * longer any touches that started inside of the current `responderInst`.
1619 *
1620 * @param {NativeEvent} nativeEvent Native touch end event.
1621 * @return {boolean} Whether or not this touch end event ends the responder.
1622 */
1623
1624
1625function noResponderTouches(nativeEvent) {
1626 var touches = nativeEvent.touches;
1627
1628 if (!touches || touches.length === 0) {
1629 return true;
1630 }
1631
1632 for (var i = 0; i < touches.length; i++) {
1633 var activeTouch = touches[i];
1634 var target = activeTouch.target;
1635
1636 if (target !== null && target !== undefined && target !== 0) {
1637 // Is the original touch location inside of the current responder?
1638 var targetInst = getInstanceFromNode$1(target);
1639
1640 if (isAncestor(responderInst, targetInst)) {
1641 return false;
1642 }
1643 }
1644 }
1645
1646 return true;
1647}
1648
1649var ResponderEventPlugin = {
1650 /* For unit testing only */
1651 _getResponder: function () {
1652 return responderInst;
1653 },
1654 eventTypes: eventTypes,
1655
1656 /**
1657 * We must be resilient to `targetInst` being `null` on `touchMove` or
1658 * `touchEnd`. On certain platforms, this means that a native scroll has
1659 * assumed control and the original touch targets are destroyed.
1660 */
1661 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
1662 if (isStartish(topLevelType)) {
1663 trackedTouchCount += 1;
1664 } else if (isEndish(topLevelType)) {
1665 if (trackedTouchCount >= 0) {
1666 trackedTouchCount -= 1;
1667 } else {
1668 console.warn('Ended a touch event which was not counted in `trackedTouchCount`.');
1669 return null;
1670 }
1671 }
1672
1673 ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent);
1674 var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ? setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) : null; // Responder may or may not have transferred on a new touch start/move.
1675 // Regardless, whoever is the responder after any potential transfer, we
1676 // direct all touch start/move/ends to them in the form of
1677 // `onResponderMove/Start/End`. These will be called for *every* additional
1678 // finger that move/start/end, dispatched directly to whoever is the
1679 // current responder at that moment, until the responder is "released".
1680 //
1681 // These multiple individual change touch events are are always bookended
1682 // by `onResponderGrant`, and one of
1683 // (`onResponderRelease/onResponderTerminate`).
1684
1685 var isResponderTouchStart = responderInst && isStartish(topLevelType);
1686 var isResponderTouchMove = responderInst && isMoveish(topLevelType);
1687 var isResponderTouchEnd = responderInst && isEndish(topLevelType);
1688 var incrementalTouch = isResponderTouchStart ? eventTypes.responderStart : isResponderTouchMove ? eventTypes.responderMove : isResponderTouchEnd ? eventTypes.responderEnd : null;
1689
1690 if (incrementalTouch) {
1691 var gesture = ResponderSyntheticEvent.getPooled(incrementalTouch, responderInst, nativeEvent, nativeEventTarget);
1692 gesture.touchHistory = ResponderTouchHistoryStore.touchHistory;
1693 accumulateDirectDispatches(gesture);
1694 extracted = accumulate(extracted, gesture);
1695 }
1696
1697 var isResponderTerminate = responderInst && topLevelType === TOP_TOUCH_CANCEL;
1698 var isResponderRelease = responderInst && !isResponderTerminate && isEndish(topLevelType) && noResponderTouches(nativeEvent);
1699 var finalTouch = isResponderTerminate ? eventTypes.responderTerminate : isResponderRelease ? eventTypes.responderRelease : null;
1700
1701 if (finalTouch) {
1702 var finalEvent = ResponderSyntheticEvent.getPooled(finalTouch, responderInst, nativeEvent, nativeEventTarget);
1703 finalEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
1704 accumulateDirectDispatches(finalEvent);
1705 extracted = accumulate(extracted, finalEvent);
1706 changeResponder(null);
1707 }
1708
1709 return extracted;
1710 },
1711 GlobalResponderHandler: null,
1712 injection: {
1713 /**
1714 * @param {{onChange: (ReactID, ReactID) => void} GlobalResponderHandler
1715 * Object that handles any change in responder. Use this to inject
1716 * integration with an existing touch handling system etc.
1717 */
1718 injectGlobalResponderHandler: function (GlobalResponderHandler) {
1719 ResponderEventPlugin.GlobalResponderHandler = GlobalResponderHandler;
1720 }
1721 }
1722};
1723
1724// Keep in sync with ReactDOM.js, ReactTestUtils.js, and ReactTestUtilsAct.js:
1725
1726var _ReactDOM$__SECRET_IN = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events;
1727var getInstanceFromNode = _ReactDOM$__SECRET_IN[0];
1728var getNodeFromInstance = _ReactDOM$__SECRET_IN[1];
1729var getFiberCurrentPropsFromNode = _ReactDOM$__SECRET_IN[2];
1730var injectEventPluginsByName = _ReactDOM$__SECRET_IN[3];
1731setComponentTree(getFiberCurrentPropsFromNode, getInstanceFromNode, getNodeFromInstance);
1732
1733
1734var ReactDOMUnstableNativeDependencies = Object.freeze({
1735 ResponderEventPlugin: ResponderEventPlugin,
1736 ResponderTouchHistoryStore: ResponderTouchHistoryStore,
1737 injectEventPluginsByName: injectEventPluginsByName
1738});
1739
1740var unstableNativeDependencies = ReactDOMUnstableNativeDependencies;
1741
1742return unstableNativeDependencies;
1743
1744})));