UNPKG

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