UNPKG

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