Projekt

Obecné

Profil

Stáhnout (56 KB) Statistiky
| Větev: | Revize:
1
/** @license React v16.13.1
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

    
13

    
14
if (process.env.NODE_ENV !== "production") {
15
  (function() {
16
'use strict';
17

    
18
var ReactDOM = require('react-dom');
19
var React = require('react');
20
var _assign = require('object-assign');
21

    
22
var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions.
23
// Current owner and dispatcher used to share the same ref,
24
// but PR #14548 split them out to better support the react-debug-tools package.
25

    
26
if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
27
  ReactSharedInternals.ReactCurrentDispatcher = {
28
    current: null
29
  };
30
}
31

    
32
if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) {
33
  ReactSharedInternals.ReactCurrentBatchConfig = {
34
    suspense: null
35
  };
36
}
37

    
38
// by calls to these methods by a Babel plugin.
39
//
40
// In PROD (or in packages without access to React internals),
41
// they are left as they are instead.
42

    
43
function warn(format) {
44
  {
45
    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
46
      args[_key - 1] = arguments[_key];
47
    }
48

    
49
    printWarning('warn', format, args);
50
  }
51
}
52
function error(format) {
53
  {
54
    for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
55
      args[_key2 - 1] = arguments[_key2];
56
    }
57

    
58
    printWarning('error', format, args);
59
  }
60
}
61

    
62
function printWarning(level, format, args) {
63
  // When changing this logic, you might want to also
64
  // update consoleWithStackDev.www.js as well.
65
  {
66
    var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\n    in') === 0;
67

    
68
    if (!hasExistingStack) {
69
      var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
70
      var stack = ReactDebugCurrentFrame.getStackAddendum();
71

    
72
      if (stack !== '') {
73
        format += '%s';
74
        args = args.concat([stack]);
75
      }
76
    }
77

    
78
    var argsWithFormat = args.map(function (item) {
79
      return '' + item;
80
    }); // Careful: RN currently depends on this prefix
81

    
82
    argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
83
    // breaks IE9: https://github.com/facebook/react/issues/13610
84
    // eslint-disable-next-line react-internal/no-production-logging
85

    
86
    Function.prototype.apply.call(console[level], console, argsWithFormat);
87

    
88
    try {
89
      // --- Welcome to debugging React ---
90
      // This error was thrown as a convenience so that you can use this stack
91
      // to find the callsite that caused this warning to fire.
92
      var argIndex = 0;
93
      var message = 'Warning: ' + format.replace(/%s/g, function () {
94
        return args[argIndex++];
95
      });
96
      throw new Error(message);
97
    } catch (x) {}
98
  }
99
}
100

    
101
{
102
  // In DEV mode, we swap out invokeGuardedCallback for a special version
103
  // that plays more nicely with the browser's DevTools. The idea is to preserve
104
  // "Pause on exceptions" behavior. Because React wraps all user-provided
105
  // functions in invokeGuardedCallback, and the production version of
106
  // invokeGuardedCallback uses a try-catch, all user exceptions are treated
107
  // like caught exceptions, and the DevTools won't pause unless the developer
108
  // takes the extra step of enabling pause on caught exceptions. This is
109
  // unintuitive, though, because even though React has caught the error, from
110
  // the developer's perspective, the error is uncaught.
111
  //
112
  // To preserve the expected "Pause on exceptions" behavior, we don't use a
113
  // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
114
  // DOM node, and call the user-provided callback from inside an event handler
115
  // for that fake event. If the callback throws, the error is "captured" using
116
  // a global event handler. But because the error happens in a different
117
  // event loop context, it does not interrupt the normal program flow.
118
  // Effectively, this gives us try-catch behavior without actually using
119
  // try-catch. Neat!
120
  // Check that the browser supports the APIs we need to implement our special
121
  // DEV version of invokeGuardedCallback
122
  if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
123
    var fakeNode = document.createElement('react');
124
  }
125
}
126

    
127
var getFiberCurrentPropsFromNode = null;
128
var getInstanceFromNode = null;
129
var getNodeFromInstance = null;
130
function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) {
131
  getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;
132
  getInstanceFromNode = getInstanceFromNodeImpl;
133
  getNodeFromInstance = getNodeFromInstanceImpl;
134

    
135
  {
136
    if (!getNodeFromInstance || !getInstanceFromNode) {
137
      error('EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.');
138
    }
139
  }
140
}
141
var validateEventDispatches;
142

    
143
{
144
  validateEventDispatches = function (event) {
145
    var dispatchListeners = event._dispatchListeners;
146
    var dispatchInstances = event._dispatchInstances;
147
    var listenersIsArr = Array.isArray(dispatchListeners);
148
    var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
149
    var instancesIsArr = Array.isArray(dispatchInstances);
150
    var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
151

    
152
    if (instancesIsArr !== listenersIsArr || instancesLen !== listenersLen) {
153
      error('EventPluginUtils: Invalid `event`.');
154
    }
155
  };
156
}
157
/**
158
 * Standard/simple iteration through an event's collected dispatches, but stops
159
 * at the first dispatch execution returning true, and returns that id.
160
 *
161
 * @return {?string} id of the first dispatch execution who's listener returns
162
 * true, or null if no listener returned true.
163
 */
164

    
165
function executeDispatchesInOrderStopAtTrueImpl(event) {
166
  var dispatchListeners = event._dispatchListeners;
167
  var dispatchInstances = event._dispatchInstances;
168

    
169
  {
170
    validateEventDispatches(event);
171
  }
172

    
173
  if (Array.isArray(dispatchListeners)) {
174
    for (var i = 0; i < dispatchListeners.length; i++) {
175
      if (event.isPropagationStopped()) {
176
        break;
177
      } // Listeners and Instances are two parallel arrays that are always in sync.
178

    
179

    
180
      if (dispatchListeners[i](event, dispatchInstances[i])) {
181
        return dispatchInstances[i];
182
      }
183
    }
184
  } else if (dispatchListeners) {
185
    if (dispatchListeners(event, dispatchInstances)) {
186
      return dispatchInstances;
187
    }
188
  }
189

    
190
  return null;
191
}
192
/**
193
 * @see executeDispatchesInOrderStopAtTrueImpl
194
 */
195

    
196

    
197
function executeDispatchesInOrderStopAtTrue(event) {
198
  var ret = executeDispatchesInOrderStopAtTrueImpl(event);
199
  event._dispatchInstances = null;
200
  event._dispatchListeners = null;
201
  return ret;
202
}
203
/**
204
 * Execution of a "direct" dispatch - there must be at most one dispatch
205
 * accumulated on the event or it is considered an error. It doesn't really make
206
 * sense for an event with multiple dispatches (bubbled) to keep track of the
207
 * return values at each dispatch execution, but it does tend to make sense when
208
 * dealing with "direct" dispatches.
209
 *
210
 * @return {*} The return value of executing the single dispatch.
211
 */
212

    
213
function executeDirectDispatch(event) {
214
  {
215
    validateEventDispatches(event);
216
  }
217

    
218
  var dispatchListener = event._dispatchListeners;
219
  var dispatchInstance = event._dispatchInstances;
220

    
221
  if (!!Array.isArray(dispatchListener)) {
222
    {
223
      throw Error( "executeDirectDispatch(...): Invalid `event`." );
224
    }
225
  }
226

    
227
  event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null;
228
  var res = dispatchListener ? dispatchListener(event) : null;
229
  event.currentTarget = null;
230
  event._dispatchListeners = null;
231
  event._dispatchInstances = null;
232
  return res;
233
}
234
/**
235
 * @param {SyntheticEvent} event
236
 * @return {boolean} True iff number of dispatches accumulated is greater than 0.
237
 */
238

    
239
function hasDispatches(event) {
240
  return !!event._dispatchListeners;
241
}
242

    
243
var HostComponent = 5;
244

    
245
function getParent(inst) {
246
  do {
247
    inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
248
    // That is depending on if we want nested subtrees (layers) to bubble
249
    // events to their parent. We could also go through parentNode on the
250
    // host node but that wouldn't work for React Native and doesn't let us
251
    // do the portal feature.
252
  } while (inst && inst.tag !== HostComponent);
253

    
254
  if (inst) {
255
    return inst;
256
  }
257

    
258
  return null;
259
}
260
/**
261
 * Return the lowest common ancestor of A and B, or null if they are in
262
 * different trees.
263
 */
264

    
265

    
266
function getLowestCommonAncestor(instA, instB) {
267
  var depthA = 0;
268

    
269
  for (var tempA = instA; tempA; tempA = getParent(tempA)) {
270
    depthA++;
271
  }
272

    
273
  var depthB = 0;
274

    
275
  for (var tempB = instB; tempB; tempB = getParent(tempB)) {
276
    depthB++;
277
  } // If A is deeper, crawl up.
278

    
279

    
280
  while (depthA - depthB > 0) {
281
    instA = getParent(instA);
282
    depthA--;
283
  } // If B is deeper, crawl up.
284

    
285

    
286
  while (depthB - depthA > 0) {
287
    instB = getParent(instB);
288
    depthB--;
289
  } // Walk in lockstep until we find a match.
290

    
291

    
292
  var depth = depthA;
293

    
294
  while (depth--) {
295
    if (instA === instB || instA === instB.alternate) {
296
      return instA;
297
    }
298

    
299
    instA = getParent(instA);
300
    instB = getParent(instB);
301
  }
302

    
303
  return null;
304
}
305
/**
306
 * Return if A is an ancestor of B.
307
 */
308

    
309
function isAncestor(instA, instB) {
310
  while (instB) {
311
    if (instA === instB || instA === instB.alternate) {
312
      return true;
313
    }
314

    
315
    instB = getParent(instB);
316
  }
317

    
318
  return false;
319
}
320
/**
321
 * Return the parent instance of the passed-in instance.
322
 */
323

    
324
function getParentInstance(inst) {
325
  return getParent(inst);
326
}
327
/**
328
 * Simulates the traversal of a two-phase, capture/bubble event dispatch.
329
 */
330

    
331
function traverseTwoPhase(inst, fn, arg) {
332
  var path = [];
333

    
334
  while (inst) {
335
    path.push(inst);
336
    inst = getParent(inst);
337
  }
338

    
339
  var i;
340

    
341
  for (i = path.length; i-- > 0;) {
342
    fn(path[i], 'captured', arg);
343
  }
344

    
345
  for (i = 0; i < path.length; i++) {
346
    fn(path[i], 'bubbled', arg);
347
  }
348
}
349

    
350
function isInteractive(tag) {
351
  return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
352
}
353

    
354
function shouldPreventMouseEvent(name, type, props) {
355
  switch (name) {
356
    case 'onClick':
357
    case 'onClickCapture':
358
    case 'onDoubleClick':
359
    case 'onDoubleClickCapture':
360
    case 'onMouseDown':
361
    case 'onMouseDownCapture':
362
    case 'onMouseMove':
363
    case 'onMouseMoveCapture':
364
    case 'onMouseUp':
365
    case 'onMouseUpCapture':
366
    case 'onMouseEnter':
367
      return !!(props.disabled && isInteractive(type));
368

    
369
    default:
370
      return false;
371
  }
372
}
373
/**
374
 * @param {object} inst The instance, which is the source of events.
375
 * @param {string} registrationName Name of listener (e.g. `onClick`).
376
 * @return {?function} The stored callback.
377
 */
378

    
379

    
380
function getListener(inst, registrationName) {
381
  var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
382
  // live here; needs to be moved to a better place soon
383

    
384
  var stateNode = inst.stateNode;
385

    
386
  if (!stateNode) {
387
    // Work in progress (ex: onload events in incremental mode).
388
    return null;
389
  }
390

    
391
  var props = getFiberCurrentPropsFromNode(stateNode);
392

    
393
  if (!props) {
394
    // Work in progress.
395
    return null;
396
  }
397

    
398
  listener = props[registrationName];
399

    
400
  if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
401
    return null;
402
  }
403

    
404
  if (!(!listener || typeof listener === 'function')) {
405
    {
406
      throw Error( "Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type." );
407
    }
408
  }
409

    
410
  return listener;
411
}
412

    
413
/**
414
 * Accumulates items that must not be null or undefined into the first one. This
415
 * is used to conserve memory by avoiding array allocations, and thus sacrifices
416
 * API cleanness. Since `current` can be null before being passed in and not
417
 * null after this function, make sure to assign it back to `current`:
418
 *
419
 * `a = accumulateInto(a, b);`
420
 *
421
 * This API should be sparingly used. Try `accumulate` for something cleaner.
422
 *
423
 * @return {*|array<*>} An accumulation of items.
424
 */
425

    
426
function accumulateInto(current, next) {
427
  if (!(next != null)) {
428
    {
429
      throw Error( "accumulateInto(...): Accumulated items must not be null or undefined." );
430
    }
431
  }
432

    
433
  if (current == null) {
434
    return next;
435
  } // Both are not empty. Warning: Never call x.concat(y) when you are not
436
  // certain that x is an Array (x could be a string with concat method).
437

    
438

    
439
  if (Array.isArray(current)) {
440
    if (Array.isArray(next)) {
441
      current.push.apply(current, next);
442
      return current;
443
    }
444

    
445
    current.push(next);
446
    return current;
447
  }
448

    
449
  if (Array.isArray(next)) {
450
    // A bit too dangerous to mutate `next`.
451
    return [current].concat(next);
452
  }
453

    
454
  return [current, next];
455
}
456

    
457
/**
458
 * @param {array} arr an "accumulation" of items which is either an Array or
459
 * a single item. Useful when paired with the `accumulate` module. This is a
460
 * simple utility that allows us to reason about a collection of items, but
461
 * handling the case when there is exactly one item (and we do not need to
462
 * allocate an array).
463
 * @param {function} cb Callback invoked with each element or a collection.
464
 * @param {?} [scope] Scope used as `this` in a callback.
465
 */
466
function forEachAccumulated(arr, cb, scope) {
467
  if (Array.isArray(arr)) {
468
    arr.forEach(cb, scope);
469
  } else if (arr) {
470
    cb.call(scope, arr);
471
  }
472
}
473

    
474
/**
475
 * Some event types have a notion of different registration names for different
476
 * "phases" of propagation. This finds listeners by a given phase.
477
 */
478
function listenerAtPhase(inst, event, propagationPhase) {
479
  var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
480
  return getListener(inst, registrationName);
481
}
482
/**
483
 * A small set of propagation patterns, each of which will accept a small amount
484
 * of information, and generate a set of "dispatch ready event objects" - which
485
 * are sets of events that have already been annotated with a set of dispatched
486
 * listener functions/ids. The API is designed this way to discourage these
487
 * propagation strategies from actually executing the dispatches, since we
488
 * always want to collect the entire set of dispatches before executing even a
489
 * single one.
490
 */
491

    
492
/**
493
 * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
494
 * here, allows us to not have to bind or create functions for each event.
495
 * Mutating the event's members allows us to not have to create a wrapping
496
 * "dispatch" object that pairs the event with the listener.
497
 */
498

    
499

    
500
function accumulateDirectionalDispatches(inst, phase, event) {
501
  {
502
    if (!inst) {
503
      error('Dispatching inst must not be null');
504
    }
505
  }
506

    
507
  var listener = listenerAtPhase(inst, event, phase);
508

    
509
  if (listener) {
510
    event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
511
    event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
512
  }
513
}
514
/**
515
 * Collect dispatches (must be entirely collected before dispatching - see unit
516
 * tests). Lazily allocate the array to conserve memory.  We must loop through
517
 * each event and perform the traversal for each one. We cannot perform a
518
 * single traversal for the entire collection of events because each event may
519
 * have a different target.
520
 */
521

    
522

    
523
function accumulateTwoPhaseDispatchesSingle(event) {
524
  if (event && event.dispatchConfig.phasedRegistrationNames) {
525
    traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
526
  }
527
}
528
/**
529
 * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
530
 */
531

    
532

    
533
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
534
  if (event && event.dispatchConfig.phasedRegistrationNames) {
535
    var targetInst = event._targetInst;
536
    var parentInst = targetInst ? getParentInstance(targetInst) : null;
537
    traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event);
538
  }
539
}
540
/**
541
 * Accumulates without regard to direction, does not look for phased
542
 * registration names. Same as `accumulateDirectDispatchesSingle` but without
543
 * requiring that the `dispatchMarker` be the same as the dispatched ID.
544
 */
545

    
546

    
547
function accumulateDispatches(inst, ignoredDirection, event) {
548
  if (inst && event && event.dispatchConfig.registrationName) {
549
    var registrationName = event.dispatchConfig.registrationName;
550
    var listener = getListener(inst, registrationName);
551

    
552
    if (listener) {
553
      event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
554
      event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
555
    }
556
  }
557
}
558
/**
559
 * Accumulates dispatches on an `SyntheticEvent`, but only for the
560
 * `dispatchMarker`.
561
 * @param {SyntheticEvent} event
562
 */
563

    
564

    
565
function accumulateDirectDispatchesSingle(event) {
566
  if (event && event.dispatchConfig.registrationName) {
567
    accumulateDispatches(event._targetInst, null, event);
568
  }
569
}
570

    
571
function accumulateTwoPhaseDispatches(events) {
572
  forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
573
}
574
function accumulateTwoPhaseDispatchesSkipTarget(events) {
575
  forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
576
}
577
function accumulateDirectDispatches(events) {
578
  forEachAccumulated(events, accumulateDirectDispatchesSingle);
579
}
580

    
581
var EVENT_POOL_SIZE = 10;
582
/**
583
 * @interface Event
584
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
585
 */
586

    
587
var EventInterface = {
588
  type: null,
589
  target: null,
590
  // currentTarget is set when dispatching; no use in copying it here
591
  currentTarget: function () {
592
    return null;
593
  },
594
  eventPhase: null,
595
  bubbles: null,
596
  cancelable: null,
597
  timeStamp: function (event) {
598
    return event.timeStamp || Date.now();
599
  },
600
  defaultPrevented: null,
601
  isTrusted: null
602
};
603

    
604
function functionThatReturnsTrue() {
605
  return true;
606
}
607

    
608
function functionThatReturnsFalse() {
609
  return false;
610
}
611
/**
612
 * Synthetic events are dispatched by event plugins, typically in response to a
613
 * top-level event delegation handler.
614
 *
615
 * These systems should generally use pooling to reduce the frequency of garbage
616
 * collection. The system should check `isPersistent` to determine whether the
617
 * event should be released into the pool after being dispatched. Users that
618
 * need a persisted event should invoke `persist`.
619
 *
620
 * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
621
 * normalizing browser quirks. Subclasses do not necessarily have to implement a
622
 * DOM interface; custom application-specific events can also subclass this.
623
 *
624
 * @param {object} dispatchConfig Configuration used to dispatch this event.
625
 * @param {*} targetInst Marker identifying the event target.
626
 * @param {object} nativeEvent Native browser event.
627
 * @param {DOMEventTarget} nativeEventTarget Target node.
628
 */
629

    
630

    
631
function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
632
  {
633
    // these have a getter/setter for warnings
634
    delete this.nativeEvent;
635
    delete this.preventDefault;
636
    delete this.stopPropagation;
637
    delete this.isDefaultPrevented;
638
    delete this.isPropagationStopped;
639
  }
640

    
641
  this.dispatchConfig = dispatchConfig;
642
  this._targetInst = targetInst;
643
  this.nativeEvent = nativeEvent;
644
  var Interface = this.constructor.Interface;
645

    
646
  for (var propName in Interface) {
647
    if (!Interface.hasOwnProperty(propName)) {
648
      continue;
649
    }
650

    
651
    {
652
      delete this[propName]; // this has a getter/setter for warnings
653
    }
654

    
655
    var normalize = Interface[propName];
656

    
657
    if (normalize) {
658
      this[propName] = normalize(nativeEvent);
659
    } else {
660
      if (propName === 'target') {
661
        this.target = nativeEventTarget;
662
      } else {
663
        this[propName] = nativeEvent[propName];
664
      }
665
    }
666
  }
667

    
668
  var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
669

    
670
  if (defaultPrevented) {
671
    this.isDefaultPrevented = functionThatReturnsTrue;
672
  } else {
673
    this.isDefaultPrevented = functionThatReturnsFalse;
674
  }
675

    
676
  this.isPropagationStopped = functionThatReturnsFalse;
677
  return this;
678
}
679

    
680
_assign(SyntheticEvent.prototype, {
681
  preventDefault: function () {
682
    this.defaultPrevented = true;
683
    var event = this.nativeEvent;
684

    
685
    if (!event) {
686
      return;
687
    }
688

    
689
    if (event.preventDefault) {
690
      event.preventDefault();
691
    } else if (typeof event.returnValue !== 'unknown') {
692
      event.returnValue = false;
693
    }
694

    
695
    this.isDefaultPrevented = functionThatReturnsTrue;
696
  },
697
  stopPropagation: function () {
698
    var event = this.nativeEvent;
699

    
700
    if (!event) {
701
      return;
702
    }
703

    
704
    if (event.stopPropagation) {
705
      event.stopPropagation();
706
    } else if (typeof event.cancelBubble !== 'unknown') {
707
      // The ChangeEventPlugin registers a "propertychange" event for
708
      // IE. This event does not support bubbling or cancelling, and
709
      // any references to cancelBubble throw "Member not found".  A
710
      // typeof check of "unknown" circumvents this issue (and is also
711
      // IE specific).
712
      event.cancelBubble = true;
713
    }
714

    
715
    this.isPropagationStopped = functionThatReturnsTrue;
716
  },
717

    
718
  /**
719
   * We release all dispatched `SyntheticEvent`s after each event loop, adding
720
   * them back into the pool. This allows a way to hold onto a reference that
721
   * won't be added back into the pool.
722
   */
723
  persist: function () {
724
    this.isPersistent = functionThatReturnsTrue;
725
  },
726

    
727
  /**
728
   * Checks if this event should be released back into the pool.
729
   *
730
   * @return {boolean} True if this should not be released, false otherwise.
731
   */
732
  isPersistent: functionThatReturnsFalse,
733

    
734
  /**
735
   * `PooledClass` looks for `destructor` on each instance it releases.
736
   */
737
  destructor: function () {
738
    var Interface = this.constructor.Interface;
739

    
740
    for (var propName in Interface) {
741
      {
742
        Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
743
      }
744
    }
745

    
746
    this.dispatchConfig = null;
747
    this._targetInst = null;
748
    this.nativeEvent = null;
749
    this.isDefaultPrevented = functionThatReturnsFalse;
750
    this.isPropagationStopped = functionThatReturnsFalse;
751
    this._dispatchListeners = null;
752
    this._dispatchInstances = null;
753

    
754
    {
755
      Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
756
      Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
757
      Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
758
      Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
759
      Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
760
    }
761
  }
762
});
763

    
764
SyntheticEvent.Interface = EventInterface;
765
/**
766
 * Helper to reduce boilerplate when creating subclasses.
767
 */
768

    
769
SyntheticEvent.extend = function (Interface) {
770
  var Super = this;
771

    
772
  var E = function () {};
773

    
774
  E.prototype = Super.prototype;
775
  var prototype = new E();
776

    
777
  function Class() {
778
    return Super.apply(this, arguments);
779
  }
780

    
781
  _assign(prototype, Class.prototype);
782

    
783
  Class.prototype = prototype;
784
  Class.prototype.constructor = Class;
785
  Class.Interface = _assign({}, Super.Interface, Interface);
786
  Class.extend = Super.extend;
787
  addEventPoolingTo(Class);
788
  return Class;
789
};
790

    
791
addEventPoolingTo(SyntheticEvent);
792
/**
793
 * Helper to nullify syntheticEvent instance properties when destructing
794
 *
795
 * @param {String} propName
796
 * @param {?object} getVal
797
 * @return {object} defineProperty object
798
 */
799

    
800
function getPooledWarningPropertyDefinition(propName, getVal) {
801
  var isFunction = typeof getVal === 'function';
802
  return {
803
    configurable: true,
804
    set: set,
805
    get: get
806
  };
807

    
808
  function set(val) {
809
    var action = isFunction ? 'setting the method' : 'setting the property';
810
    warn(action, 'This is effectively a no-op');
811
    return val;
812
  }
813

    
814
  function get() {
815
    var action = isFunction ? 'accessing the method' : 'accessing the property';
816
    var result = isFunction ? 'This is a no-op function' : 'This is set to null';
817
    warn(action, result);
818
    return getVal;
819
  }
820

    
821
  function warn(action, result) {
822
    {
823
      error("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);
824
    }
825
  }
826
}
827

    
828
function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
829
  var EventConstructor = this;
830

    
831
  if (EventConstructor.eventPool.length) {
832
    var instance = EventConstructor.eventPool.pop();
833
    EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
834
    return instance;
835
  }
836

    
837
  return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
838
}
839

    
840
function releasePooledEvent(event) {
841
  var EventConstructor = this;
842

    
843
  if (!(event instanceof EventConstructor)) {
844
    {
845
      throw Error( "Trying to release an event instance into a pool of a different type." );
846
    }
847
  }
848

    
849
  event.destructor();
850

    
851
  if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
852
    EventConstructor.eventPool.push(event);
853
  }
854
}
855

    
856
function addEventPoolingTo(EventConstructor) {
857
  EventConstructor.eventPool = [];
858
  EventConstructor.getPooled = getPooledEvent;
859
  EventConstructor.release = releasePooledEvent;
860
}
861

    
862
/**
863
 * `touchHistory` isn't actually on the native event, but putting it in the
864
 * interface will ensure that it is cleaned up when pooled/destroyed. The
865
 * `ResponderEventPlugin` will populate it appropriately.
866
 */
867

    
868
var ResponderSyntheticEvent = SyntheticEvent.extend({
869
  touchHistory: function (nativeEvent) {
870
    return null; // Actually doesn't even look at the native event.
871
  }
872
});
873

    
874
// Note: ideally these would be imported from DOMTopLevelEventTypes,
875
// but our build system currently doesn't let us do that from a fork.
876
var TOP_TOUCH_START = 'touchstart';
877
var TOP_TOUCH_MOVE = 'touchmove';
878
var TOP_TOUCH_END = 'touchend';
879
var TOP_TOUCH_CANCEL = 'touchcancel';
880
var TOP_SCROLL = 'scroll';
881
var TOP_SELECTION_CHANGE = 'selectionchange';
882
var TOP_MOUSE_DOWN = 'mousedown';
883
var TOP_MOUSE_MOVE = 'mousemove';
884
var TOP_MOUSE_UP = 'mouseup';
885
function isStartish(topLevelType) {
886
  return topLevelType === TOP_TOUCH_START || topLevelType === TOP_MOUSE_DOWN;
887
}
888
function isMoveish(topLevelType) {
889
  return topLevelType === TOP_TOUCH_MOVE || topLevelType === TOP_MOUSE_MOVE;
890
}
891
function isEndish(topLevelType) {
892
  return topLevelType === TOP_TOUCH_END || topLevelType === TOP_TOUCH_CANCEL || topLevelType === TOP_MOUSE_UP;
893
}
894
var startDependencies = [TOP_TOUCH_START, TOP_MOUSE_DOWN];
895
var moveDependencies = [TOP_TOUCH_MOVE, TOP_MOUSE_MOVE];
896
var endDependencies = [TOP_TOUCH_CANCEL, TOP_TOUCH_END, TOP_MOUSE_UP];
897

    
898
/**
899
 * Tracks the position and time of each active touch by `touch.identifier`. We
900
 * should typically only see IDs in the range of 1-20 because IDs get recycled
901
 * when touches end and start again.
902
 */
903

    
904
var MAX_TOUCH_BANK = 20;
905
var touchBank = [];
906
var touchHistory = {
907
  touchBank: touchBank,
908
  numberActiveTouches: 0,
909
  // If there is only one active touch, we remember its location. This prevents
910
  // us having to loop through all of the touches all the time in the most
911
  // common case.
912
  indexOfSingleActiveTouch: -1,
913
  mostRecentTimeStamp: 0
914
};
915

    
916
function timestampForTouch(touch) {
917
  // The legacy internal implementation provides "timeStamp", which has been
918
  // renamed to "timestamp". Let both work for now while we iron it out
919
  // TODO (evv): rename timeStamp to timestamp in internal code
920
  return touch.timeStamp || touch.timestamp;
921
}
922
/**
923
 * TODO: Instead of making gestures recompute filtered velocity, we could
924
 * include a built in velocity computation that can be reused globally.
925
 */
926

    
927

    
928
function createTouchRecord(touch) {
929
  return {
930
    touchActive: true,
931
    startPageX: touch.pageX,
932
    startPageY: touch.pageY,
933
    startTimeStamp: timestampForTouch(touch),
934
    currentPageX: touch.pageX,
935
    currentPageY: touch.pageY,
936
    currentTimeStamp: timestampForTouch(touch),
937
    previousPageX: touch.pageX,
938
    previousPageY: touch.pageY,
939
    previousTimeStamp: timestampForTouch(touch)
940
  };
941
}
942

    
943
function resetTouchRecord(touchRecord, touch) {
944
  touchRecord.touchActive = true;
945
  touchRecord.startPageX = touch.pageX;
946
  touchRecord.startPageY = touch.pageY;
947
  touchRecord.startTimeStamp = timestampForTouch(touch);
948
  touchRecord.currentPageX = touch.pageX;
949
  touchRecord.currentPageY = touch.pageY;
950
  touchRecord.currentTimeStamp = timestampForTouch(touch);
951
  touchRecord.previousPageX = touch.pageX;
952
  touchRecord.previousPageY = touch.pageY;
953
  touchRecord.previousTimeStamp = timestampForTouch(touch);
954
}
955

    
956
function getTouchIdentifier(_ref) {
957
  var identifier = _ref.identifier;
958

    
959
  if (!(identifier != null)) {
960
    {
961
      throw Error( "Touch object is missing identifier." );
962
    }
963
  }
964

    
965
  {
966
    if (identifier > MAX_TOUCH_BANK) {
967
      error('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);
968
    }
969
  }
970

    
971
  return identifier;
972
}
973

    
974
function recordTouchStart(touch) {
975
  var identifier = getTouchIdentifier(touch);
976
  var touchRecord = touchBank[identifier];
977

    
978
  if (touchRecord) {
979
    resetTouchRecord(touchRecord, touch);
980
  } else {
981
    touchBank[identifier] = createTouchRecord(touch);
982
  }
983

    
984
  touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
985
}
986

    
987
function recordTouchMove(touch) {
988
  var touchRecord = touchBank[getTouchIdentifier(touch)];
989

    
990
  if (touchRecord) {
991
    touchRecord.touchActive = true;
992
    touchRecord.previousPageX = touchRecord.currentPageX;
993
    touchRecord.previousPageY = touchRecord.currentPageY;
994
    touchRecord.previousTimeStamp = touchRecord.currentTimeStamp;
995
    touchRecord.currentPageX = touch.pageX;
996
    touchRecord.currentPageY = touch.pageY;
997
    touchRecord.currentTimeStamp = timestampForTouch(touch);
998
    touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
999
  } else {
1000
    {
1001
      warn('Cannot record touch move without a touch start.\n' + 'Touch Move: %s\n' + 'Touch Bank: %s', printTouch(touch), printTouchBank());
1002
    }
1003
  }
1004
}
1005

    
1006
function recordTouchEnd(touch) {
1007
  var touchRecord = touchBank[getTouchIdentifier(touch)];
1008

    
1009
  if (touchRecord) {
1010
    touchRecord.touchActive = false;
1011
    touchRecord.previousPageX = touchRecord.currentPageX;
1012
    touchRecord.previousPageY = touchRecord.currentPageY;
1013
    touchRecord.previousTimeStamp = touchRecord.currentTimeStamp;
1014
    touchRecord.currentPageX = touch.pageX;
1015
    touchRecord.currentPageY = touch.pageY;
1016
    touchRecord.currentTimeStamp = timestampForTouch(touch);
1017
    touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
1018
  } else {
1019
    {
1020
      warn('Cannot record touch end without a touch start.\n' + 'Touch End: %s\n' + 'Touch Bank: %s', printTouch(touch), printTouchBank());
1021
    }
1022
  }
1023
}
1024

    
1025
function printTouch(touch) {
1026
  return JSON.stringify({
1027
    identifier: touch.identifier,
1028
    pageX: touch.pageX,
1029
    pageY: touch.pageY,
1030
    timestamp: timestampForTouch(touch)
1031
  });
1032
}
1033

    
1034
function printTouchBank() {
1035
  var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK));
1036

    
1037
  if (touchBank.length > MAX_TOUCH_BANK) {
1038
    printed += ' (original size: ' + touchBank.length + ')';
1039
  }
1040

    
1041
  return printed;
1042
}
1043

    
1044
var ResponderTouchHistoryStore = {
1045
  recordTouchTrack: function (topLevelType, nativeEvent) {
1046
    if (isMoveish(topLevelType)) {
1047
      nativeEvent.changedTouches.forEach(recordTouchMove);
1048
    } else if (isStartish(topLevelType)) {
1049
      nativeEvent.changedTouches.forEach(recordTouchStart);
1050
      touchHistory.numberActiveTouches = nativeEvent.touches.length;
1051

    
1052
      if (touchHistory.numberActiveTouches === 1) {
1053
        touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier;
1054
      }
1055
    } else if (isEndish(topLevelType)) {
1056
      nativeEvent.changedTouches.forEach(recordTouchEnd);
1057
      touchHistory.numberActiveTouches = nativeEvent.touches.length;
1058

    
1059
      if (touchHistory.numberActiveTouches === 1) {
1060
        for (var i = 0; i < touchBank.length; i++) {
1061
          var touchTrackToCheck = touchBank[i];
1062

    
1063
          if (touchTrackToCheck != null && touchTrackToCheck.touchActive) {
1064
            touchHistory.indexOfSingleActiveTouch = i;
1065
            break;
1066
          }
1067
        }
1068

    
1069
        {
1070
          var activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch];
1071

    
1072
          if (activeRecord == null || !activeRecord.touchActive) {
1073
            error('Cannot find single active touch.');
1074
          }
1075
        }
1076
      }
1077
    }
1078
  },
1079
  touchHistory: touchHistory
1080
};
1081

    
1082
/**
1083
 * Accumulates items that must not be null or undefined.
1084
 *
1085
 * This is used to conserve memory by avoiding array allocations.
1086
 *
1087
 * @return {*|array<*>} An accumulation of items.
1088
 */
1089

    
1090
function accumulate(current, next) {
1091
  if (!(next != null)) {
1092
    {
1093
      throw Error( "accumulate(...): Accumulated items must not be null or undefined." );
1094
    }
1095
  }
1096

    
1097
  if (current == null) {
1098
    return next;
1099
  } // Both are not empty. Warning: Never call x.concat(y) when you are not
1100
  // certain that x is an Array (x could be a string with concat method).
1101

    
1102

    
1103
  if (Array.isArray(current)) {
1104
    return current.concat(next);
1105
  }
1106

    
1107
  if (Array.isArray(next)) {
1108
    return [current].concat(next);
1109
  }
1110

    
1111
  return [current, next];
1112
}
1113

    
1114
/**
1115
 * Instance of element that should respond to touch/move types of interactions,
1116
 * as indicated explicitly by relevant callbacks.
1117
 */
1118

    
1119
var responderInst = null;
1120
/**
1121
 * Count of current touches. A textInput should become responder iff the
1122
 * selection changes while there is a touch on the screen.
1123
 */
1124

    
1125
var trackedTouchCount = 0;
1126

    
1127
var changeResponder = function (nextResponderInst, blockHostResponder) {
1128
  var oldResponderInst = responderInst;
1129
  responderInst = nextResponderInst;
1130

    
1131
  if (ResponderEventPlugin.GlobalResponderHandler !== null) {
1132
    ResponderEventPlugin.GlobalResponderHandler.onChange(oldResponderInst, nextResponderInst, blockHostResponder);
1133
  }
1134
};
1135

    
1136
var eventTypes = {
1137
  /**
1138
   * On a `touchStart`/`mouseDown`, is it desired that this element become the
1139
   * responder?
1140
   */
1141
  startShouldSetResponder: {
1142
    phasedRegistrationNames: {
1143
      bubbled: 'onStartShouldSetResponder',
1144
      captured: 'onStartShouldSetResponderCapture'
1145
    },
1146
    dependencies: startDependencies
1147
  },
1148

    
1149
  /**
1150
   * On a `scroll`, is it desired that this element become the responder? This
1151
   * is usually not needed, but should be used to retroactively infer that a
1152
   * `touchStart` had occurred during momentum scroll. During a momentum scroll,
1153
   * a touch start will be immediately followed by a scroll event if the view is
1154
   * currently scrolling.
1155
   *
1156
   * TODO: This shouldn't bubble.
1157
   */
1158
  scrollShouldSetResponder: {
1159
    phasedRegistrationNames: {
1160
      bubbled: 'onScrollShouldSetResponder',
1161
      captured: 'onScrollShouldSetResponderCapture'
1162
    },
1163
    dependencies: [TOP_SCROLL]
1164
  },
1165

    
1166
  /**
1167
   * On text selection change, should this element become the responder? This
1168
   * is needed for text inputs or other views with native selection, so the
1169
   * JS view can claim the responder.
1170
   *
1171
   * TODO: This shouldn't bubble.
1172
   */
1173
  selectionChangeShouldSetResponder: {
1174
    phasedRegistrationNames: {
1175
      bubbled: 'onSelectionChangeShouldSetResponder',
1176
      captured: 'onSelectionChangeShouldSetResponderCapture'
1177
    },
1178
    dependencies: [TOP_SELECTION_CHANGE]
1179
  },
1180

    
1181
  /**
1182
   * On a `touchMove`/`mouseMove`, is it desired that this element become the
1183
   * responder?
1184
   */
1185
  moveShouldSetResponder: {
1186
    phasedRegistrationNames: {
1187
      bubbled: 'onMoveShouldSetResponder',
1188
      captured: 'onMoveShouldSetResponderCapture'
1189
    },
1190
    dependencies: moveDependencies
1191
  },
1192

    
1193
  /**
1194
   * Direct responder events dispatched directly to responder. Do not bubble.
1195
   */
1196
  responderStart: {
1197
    registrationName: 'onResponderStart',
1198
    dependencies: startDependencies
1199
  },
1200
  responderMove: {
1201
    registrationName: 'onResponderMove',
1202
    dependencies: moveDependencies
1203
  },
1204
  responderEnd: {
1205
    registrationName: 'onResponderEnd',
1206
    dependencies: endDependencies
1207
  },
1208
  responderRelease: {
1209
    registrationName: 'onResponderRelease',
1210
    dependencies: endDependencies
1211
  },
1212
  responderTerminationRequest: {
1213
    registrationName: 'onResponderTerminationRequest',
1214
    dependencies: []
1215
  },
1216
  responderGrant: {
1217
    registrationName: 'onResponderGrant',
1218
    dependencies: []
1219
  },
1220
  responderReject: {
1221
    registrationName: 'onResponderReject',
1222
    dependencies: []
1223
  },
1224
  responderTerminate: {
1225
    registrationName: 'onResponderTerminate',
1226
    dependencies: []
1227
  }
1228
};
1229
/**
1230
 *
1231
 * Responder System:
1232
 * ----------------
1233
 *
1234
 * - A global, solitary "interaction lock" on a view.
1235
 * - If a node becomes the responder, it should convey visual feedback
1236
 *   immediately to indicate so, either by highlighting or moving accordingly.
1237
 * - To be the responder means, that touches are exclusively important to that
1238
 *   responder view, and no other view.
1239
 * - While touches are still occurring, the responder lock can be transferred to
1240
 *   a new view, but only to increasingly "higher" views (meaning ancestors of
1241
 *   the current responder).
1242
 *
1243
 * Responder being granted:
1244
 * ------------------------
1245
 *
1246
 * - Touch starts, moves, and scrolls can cause an ID to become the responder.
1247
 * - We capture/bubble `startShouldSetResponder`/`moveShouldSetResponder` to
1248
 *   the "appropriate place".
1249
 * - If nothing is currently the responder, the "appropriate place" is the
1250
 *   initiating event's `targetID`.
1251
 * - If something *is* already the responder, the "appropriate place" is the
1252
 *   first common ancestor of the event target and the current `responderInst`.
1253
 * - Some negotiation happens: See the timing diagram below.
1254
 * - Scrolled views automatically become responder. The reasoning is that a
1255
 *   platform scroll view that isn't built on top of the responder system has
1256
 *   began scrolling, and the active responder must now be notified that the
1257
 *   interaction is no longer locked to it - the system has taken over.
1258
 *
1259
 * - Responder being released:
1260
 *   As soon as no more touches that *started* inside of descendants of the
1261
 *   *current* responderInst, an `onResponderRelease` event is dispatched to the
1262
 *   current responder, and the responder lock is released.
1263
 *
1264
 * TODO:
1265
 * - on "end", a callback hook for `onResponderEndShouldRemainResponder` that
1266
 *   determines if the responder lock should remain.
1267
 * - If a view shouldn't "remain" the responder, any active touches should by
1268
 *   default be considered "dead" and do not influence future negotiations or
1269
 *   bubble paths. It should be as if those touches do not exist.
1270
 * -- For multitouch: Usually a translate-z will choose to "remain" responder
1271
 *  after one out of many touches ended. For translate-y, usually the view
1272
 *  doesn't wish to "remain" responder after one of many touches end.
1273
 * - Consider building this on top of a `stopPropagation` model similar to
1274
 *   `W3C` events.
1275
 * - Ensure that `onResponderTerminate` is called on touch cancels, whether or
1276
 *   not `onResponderTerminationRequest` returns `true` or `false`.
1277
 *
1278
 */
1279

    
1280
/*                                             Negotiation Performed
1281
                                             +-----------------------+
1282
                                            /                         \
1283
Process low level events to    +     Current Responder      +   wantsResponderID
1284
determine who to perform negot-|   (if any exists at all)   |
1285
iation/transition              | Otherwise just pass through|
1286
-------------------------------+----------------------------+------------------+
1287
Bubble to find first ID        |                            |
1288
to return true:wantsResponderID|                            |
1289
                               |                            |
1290
     +-------------+           |                            |
1291
     | onTouchStart|           |                            |
1292
     +------+------+     none  |                            |
1293
            |            return|                            |
1294
+-----------v-------------+true| +------------------------+ |
1295
|onStartShouldSetResponder|----->|onResponderStart (cur)  |<-----------+
1296
+-----------+-------------+    | +------------------------+ |          |
1297
            |                  |                            | +--------+-------+
1298
            | returned true for|       false:REJECT +-------->|onResponderReject
1299
            | wantsResponderID |                    |       | +----------------+
1300
            | (now attempt     | +------------------+-----+ |
1301
            |  handoff)        | |   onResponder          | |
1302
            +------------------->|      TerminationRequest| |
1303
                               | +------------------+-----+ |
1304
                               |                    |       | +----------------+
1305
                               |         true:GRANT +-------->|onResponderGrant|
1306
                               |                            | +--------+-------+
1307
                               | +------------------------+ |          |
1308
                               | |   onResponderTerminate |<-----------+
1309
                               | +------------------+-----+ |
1310
                               |                    |       | +----------------+
1311
                               |                    +-------->|onResponderStart|
1312
                               |                            | +----------------+
1313
Bubble to find first ID        |                            |
1314
to return true:wantsResponderID|                            |
1315
                               |                            |
1316
     +-------------+           |                            |
1317
     | onTouchMove |           |                            |
1318
     +------+------+     none  |                            |
1319
            |            return|                            |
1320
+-----------v-------------+true| +------------------------+ |
1321
|onMoveShouldSetResponder |----->|onResponderMove (cur)   |<-----------+
1322
+-----------+-------------+    | +------------------------+ |          |
1323
            |                  |                            | +--------+-------+
1324
            | returned true for|       false:REJECT +-------->|onResponderRejec|
1325
            | wantsResponderID |                    |       | +----------------+
1326
            | (now attempt     | +------------------+-----+ |
1327
            |  handoff)        | |   onResponder          | |
1328
            +------------------->|      TerminationRequest| |
1329
                               | +------------------+-----+ |
1330
                               |                    |       | +----------------+
1331
                               |         true:GRANT +-------->|onResponderGrant|
1332
                               |                            | +--------+-------+
1333
                               | +------------------------+ |          |
1334
                               | |   onResponderTerminate |<-----------+
1335
                               | +------------------+-----+ |
1336
                               |                    |       | +----------------+
1337
                               |                    +-------->|onResponderMove |
1338
                               |                            | +----------------+
1339
                               |                            |
1340
                               |                            |
1341
      Some active touch started|                            |
1342
      inside current responder | +------------------------+ |
1343
      +------------------------->|      onResponderEnd    | |
1344
      |                        | +------------------------+ |
1345
  +---+---------+              |                            |
1346
  | onTouchEnd  |              |                            |
1347
  +---+---------+              |                            |
1348
      |                        | +------------------------+ |
1349
      +------------------------->|     onResponderEnd     | |
1350
      No active touches started| +-----------+------------+ |
1351
      inside current responder |             |              |
1352
                               |             v              |
1353
                               | +------------------------+ |
1354
                               | |    onResponderRelease  | |
1355
                               | +------------------------+ |
1356
                               |                            |
1357
                               +                            + */
1358

    
1359
/**
1360
 * A note about event ordering in the `EventPluginRegistry`.
1361
 *
1362
 * Suppose plugins are injected in the following order:
1363
 *
1364
 * `[R, S, C]`
1365
 *
1366
 * To help illustrate the example, assume `S` is `SimpleEventPlugin` (for
1367
 * `onClick` etc) and `R` is `ResponderEventPlugin`.
1368
 *
1369
 * "Deferred-Dispatched Events":
1370
 *
1371
 * - The current event plugin system will traverse the list of injected plugins,
1372
 *   in order, and extract events by collecting the plugin's return value of
1373
 *   `extractEvents()`.
1374
 * - These events that are returned from `extractEvents` are "deferred
1375
 *   dispatched events".
1376
 * - When returned from `extractEvents`, deferred-dispatched events contain an
1377
 *   "accumulation" of deferred dispatches.
1378
 * - These deferred dispatches are accumulated/collected before they are
1379
 *   returned, but processed at a later time by the `EventPluginRegistry` (hence the
1380
 *   name deferred).
1381
 *
1382
 * In the process of returning their deferred-dispatched events, event plugins
1383
 * themselves can dispatch events on-demand without returning them from
1384
 * `extractEvents`. Plugins might want to do this, so that they can use event
1385
 * dispatching as a tool that helps them decide which events should be extracted
1386
 * in the first place.
1387
 *
1388
 * "On-Demand-Dispatched Events":
1389
 *
1390
 * - On-demand-dispatched events are not returned from `extractEvents`.
1391
 * - On-demand-dispatched events are dispatched during the process of returning
1392
 *   the deferred-dispatched events.
1393
 * - They should not have side effects.
1394
 * - They should be avoided, and/or eventually be replaced with another
1395
 *   abstraction that allows event plugins to perform multiple "rounds" of event
1396
 *   extraction.
1397
 *
1398
 * Therefore, the sequence of event dispatches becomes:
1399
 *
1400
 * - `R`s on-demand events (if any)   (dispatched by `R` on-demand)
1401
 * - `S`s on-demand events (if any)   (dispatched by `S` on-demand)
1402
 * - `C`s on-demand events (if any)   (dispatched by `C` on-demand)
1403
 * - `R`s extracted events (if any)   (dispatched by `EventPluginRegistry`)
1404
 * - `S`s extracted events (if any)   (dispatched by `EventPluginRegistry`)
1405
 * - `C`s extracted events (if any)   (dispatched by `EventPluginRegistry`)
1406
 *
1407
 * In the case of `ResponderEventPlugin`: If the `startShouldSetResponder`
1408
 * on-demand dispatch returns `true` (and some other details are satisfied) the
1409
 * `onResponderGrant` deferred dispatched event is returned from
1410
 * `extractEvents`. The sequence of dispatch executions in this case
1411
 * will appear as follows:
1412
 *
1413
 * - `startShouldSetResponder` (`ResponderEventPlugin` dispatches on-demand)
1414
 * - `touchStartCapture`       (`EventPluginRegistry` dispatches as usual)
1415
 * - `touchStart`              (`EventPluginRegistry` dispatches as usual)
1416
 * - `responderGrant/Reject`   (`EventPluginRegistry` dispatches as usual)
1417
 */
1418

    
1419
function setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
1420
  var shouldSetEventType = isStartish(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder : topLevelType === TOP_SELECTION_CHANGE ? eventTypes.selectionChangeShouldSetResponder : eventTypes.scrollShouldSetResponder; // TODO: stop one short of the current responder.
1421

    
1422
  var bubbleShouldSetFrom = !responderInst ? targetInst : getLowestCommonAncestor(responderInst, targetInst); // When capturing/bubbling the "shouldSet" event, we want to skip the target
1423
  // (deepest ID) if it happens to be the current responder. The reasoning:
1424
  // It's strange to get an `onMoveShouldSetResponder` when you're *already*
1425
  // the responder.
1426

    
1427
  var skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst;
1428
  var shouldSetEvent = ResponderSyntheticEvent.getPooled(shouldSetEventType, bubbleShouldSetFrom, nativeEvent, nativeEventTarget);
1429
  shouldSetEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
1430

    
1431
  if (skipOverBubbleShouldSetFrom) {
1432
    accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent);
1433
  } else {
1434
    accumulateTwoPhaseDispatches(shouldSetEvent);
1435
  }
1436

    
1437
  var wantsResponderInst = executeDispatchesInOrderStopAtTrue(shouldSetEvent);
1438

    
1439
  if (!shouldSetEvent.isPersistent()) {
1440
    shouldSetEvent.constructor.release(shouldSetEvent);
1441
  }
1442

    
1443
  if (!wantsResponderInst || wantsResponderInst === responderInst) {
1444
    return null;
1445
  }
1446

    
1447
  var extracted;
1448
  var grantEvent = ResponderSyntheticEvent.getPooled(eventTypes.responderGrant, wantsResponderInst, nativeEvent, nativeEventTarget);
1449
  grantEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
1450
  accumulateDirectDispatches(grantEvent);
1451
  var blockHostResponder = executeDirectDispatch(grantEvent) === true;
1452

    
1453
  if (responderInst) {
1454
    var terminationRequestEvent = ResponderSyntheticEvent.getPooled(eventTypes.responderTerminationRequest, responderInst, nativeEvent, nativeEventTarget);
1455
    terminationRequestEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
1456
    accumulateDirectDispatches(terminationRequestEvent);
1457
    var shouldSwitch = !hasDispatches(terminationRequestEvent) || executeDirectDispatch(terminationRequestEvent);
1458

    
1459
    if (!terminationRequestEvent.isPersistent()) {
1460
      terminationRequestEvent.constructor.release(terminationRequestEvent);
1461
    }
1462

    
1463
    if (shouldSwitch) {
1464
      var terminateEvent = ResponderSyntheticEvent.getPooled(eventTypes.responderTerminate, responderInst, nativeEvent, nativeEventTarget);
1465
      terminateEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
1466
      accumulateDirectDispatches(terminateEvent);
1467
      extracted = accumulate(extracted, [grantEvent, terminateEvent]);
1468
      changeResponder(wantsResponderInst, blockHostResponder);
1469
    } else {
1470
      var rejectEvent = ResponderSyntheticEvent.getPooled(eventTypes.responderReject, wantsResponderInst, nativeEvent, nativeEventTarget);
1471
      rejectEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
1472
      accumulateDirectDispatches(rejectEvent);
1473
      extracted = accumulate(extracted, rejectEvent);
1474
    }
1475
  } else {
1476
    extracted = accumulate(extracted, grantEvent);
1477
    changeResponder(wantsResponderInst, blockHostResponder);
1478
  }
1479

    
1480
  return extracted;
1481
}
1482
/**
1483
 * A transfer is a negotiation between a currently set responder and the next
1484
 * element to claim responder status. Any start event could trigger a transfer
1485
 * of responderInst. Any move event could trigger a transfer.
1486
 *
1487
 * @param {string} topLevelType Record from `BrowserEventConstants`.
1488
 * @return {boolean} True if a transfer of responder could possibly occur.
1489
 */
1490

    
1491

    
1492
function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) {
1493
  return topLevelInst && ( // responderIgnoreScroll: We are trying to migrate away from specifically
1494
  // tracking native scroll events here and responderIgnoreScroll indicates we
1495
  // will send topTouchCancel to handle canceling touch events instead
1496
  topLevelType === TOP_SCROLL && !nativeEvent.responderIgnoreScroll || trackedTouchCount > 0 && topLevelType === TOP_SELECTION_CHANGE || isStartish(topLevelType) || isMoveish(topLevelType));
1497
}
1498
/**
1499
 * Returns whether or not this touch end event makes it such that there are no
1500
 * longer any touches that started inside of the current `responderInst`.
1501
 *
1502
 * @param {NativeEvent} nativeEvent Native touch end event.
1503
 * @return {boolean} Whether or not this touch end event ends the responder.
1504
 */
1505

    
1506

    
1507
function noResponderTouches(nativeEvent) {
1508
  var touches = nativeEvent.touches;
1509

    
1510
  if (!touches || touches.length === 0) {
1511
    return true;
1512
  }
1513

    
1514
  for (var i = 0; i < touches.length; i++) {
1515
    var activeTouch = touches[i];
1516
    var target = activeTouch.target;
1517

    
1518
    if (target !== null && target !== undefined && target !== 0) {
1519
      // Is the original touch location inside of the current responder?
1520
      var targetInst = getInstanceFromNode(target);
1521

    
1522
      if (isAncestor(responderInst, targetInst)) {
1523
        return false;
1524
      }
1525
    }
1526
  }
1527

    
1528
  return true;
1529
}
1530

    
1531
var ResponderEventPlugin = {
1532
  /* For unit testing only */
1533
  _getResponder: function () {
1534
    return responderInst;
1535
  },
1536
  eventTypes: eventTypes,
1537

    
1538
  /**
1539
   * We must be resilient to `targetInst` being `null` on `touchMove` or
1540
   * `touchEnd`. On certain platforms, this means that a native scroll has
1541
   * assumed control and the original touch targets are destroyed.
1542
   */
1543
  extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
1544
    if (isStartish(topLevelType)) {
1545
      trackedTouchCount += 1;
1546
    } else if (isEndish(topLevelType)) {
1547
      if (trackedTouchCount >= 0) {
1548
        trackedTouchCount -= 1;
1549
      } else {
1550
        {
1551
          warn('Ended a touch event which was not counted in `trackedTouchCount`.');
1552
        }
1553

    
1554
        return null;
1555
      }
1556
    }
1557

    
1558
    ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent);
1559
    var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ? setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) : null; // Responder may or may not have transferred on a new touch start/move.
1560
    // Regardless, whoever is the responder after any potential transfer, we
1561
    // direct all touch start/move/ends to them in the form of
1562
    // `onResponderMove/Start/End`. These will be called for *every* additional
1563
    // finger that move/start/end, dispatched directly to whoever is the
1564
    // current responder at that moment, until the responder is "released".
1565
    //
1566
    // These multiple individual change touch events are are always bookended
1567
    // by `onResponderGrant`, and one of
1568
    // (`onResponderRelease/onResponderTerminate`).
1569

    
1570
    var isResponderTouchStart = responderInst && isStartish(topLevelType);
1571
    var isResponderTouchMove = responderInst && isMoveish(topLevelType);
1572
    var isResponderTouchEnd = responderInst && isEndish(topLevelType);
1573
    var incrementalTouch = isResponderTouchStart ? eventTypes.responderStart : isResponderTouchMove ? eventTypes.responderMove : isResponderTouchEnd ? eventTypes.responderEnd : null;
1574

    
1575
    if (incrementalTouch) {
1576
      var gesture = ResponderSyntheticEvent.getPooled(incrementalTouch, responderInst, nativeEvent, nativeEventTarget);
1577
      gesture.touchHistory = ResponderTouchHistoryStore.touchHistory;
1578
      accumulateDirectDispatches(gesture);
1579
      extracted = accumulate(extracted, gesture);
1580
    }
1581

    
1582
    var isResponderTerminate = responderInst && topLevelType === TOP_TOUCH_CANCEL;
1583
    var isResponderRelease = responderInst && !isResponderTerminate && isEndish(topLevelType) && noResponderTouches(nativeEvent);
1584
    var finalTouch = isResponderTerminate ? eventTypes.responderTerminate : isResponderRelease ? eventTypes.responderRelease : null;
1585

    
1586
    if (finalTouch) {
1587
      var finalEvent = ResponderSyntheticEvent.getPooled(finalTouch, responderInst, nativeEvent, nativeEventTarget);
1588
      finalEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
1589
      accumulateDirectDispatches(finalEvent);
1590
      extracted = accumulate(extracted, finalEvent);
1591
      changeResponder(null);
1592
    }
1593

    
1594
    return extracted;
1595
  },
1596
  GlobalResponderHandler: null,
1597
  injection: {
1598
    /**
1599
     * @param {{onChange: (ReactID, ReactID) => void} GlobalResponderHandler
1600
     * Object that handles any change in responder. Use this to inject
1601
     * integration with an existing touch handling system etc.
1602
     */
1603
    injectGlobalResponderHandler: function (GlobalResponderHandler) {
1604
      ResponderEventPlugin.GlobalResponderHandler = GlobalResponderHandler;
1605
    }
1606
  }
1607
};
1608

    
1609
// Keep in sync with ReactDOM.js, ReactTestUtils.js, and ReactTestUtilsAct.js:
1610

    
1611
var _ReactDOM$__SECRET_IN = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events,
1612
    getInstanceFromNode$1 = _ReactDOM$__SECRET_IN[0],
1613
    getNodeFromInstance$1 = _ReactDOM$__SECRET_IN[1],
1614
    getFiberCurrentPropsFromNode$1 = _ReactDOM$__SECRET_IN[2],
1615
    injectEventPluginsByName = _ReactDOM$__SECRET_IN[3];
1616
setComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);
1617

    
1618
var ReactDOMUnstableNativeDependencies = /*#__PURE__*/Object.freeze({
1619
  __proto__: null,
1620
  ResponderEventPlugin: ResponderEventPlugin,
1621
  ResponderTouchHistoryStore: ResponderTouchHistoryStore,
1622
  injectEventPluginsByName: injectEventPluginsByName
1623
});
1624

    
1625
var unstableNativeDependencies = ReactDOMUnstableNativeDependencies;
1626

    
1627
module.exports = unstableNativeDependencies;
1628
  })();
1629
}
(11-11/15)