Passed
Push — master ( 445067...6ce435 )
by Johan
02:18
created

node_modules/react-dom/cjs/react-dom.development.js   F

Complexity

Total Complexity 3617
Complexity/F 4.67

Size

Lines of Code 27927
Function Count 775

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 3617
eloc 19164
mnd 2842
bc 2842
fnc 775
dl 0
loc 27927
rs 0.8
bpm 3.667
cpm 4.667
noi 0
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like node_modules/react-dom/cjs/react-dom.development.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
/** @license React v16.10.1
2
 * react-dom.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 React = require('react');
19
var _assign = require('object-assign');
20
var Scheduler = require('scheduler');
21
var checkPropTypes = require('prop-types/checkPropTypes');
22
var tracing = require('scheduler/tracing');
23
24
// Do not require this module directly! Use normal `invariant` calls with
25
// template literal strings. The messages will be converted to ReactError during
26
// build, and in production they will be minified.
27
28
// Do not require this module directly! Use normal `invariant` calls with
29
// template literal strings. The messages will be converted to ReactError during
30
// build, and in production they will be minified.
31
function ReactError(error) {
32
  error.name = 'Invariant Violation';
33
  return error;
34
}
35
36
/**
37
 * Use invariant() to assert state which your program assumes to be true.
38
 *
39
 * Provide sprintf-style format (only %s is supported) and arguments
40
 * to provide information about what broke and what you were
41
 * expecting.
42
 *
43
 * The invariant message will be stripped in production, but the invariant
44
 * will remain to ensure logic does not differ in production.
45
 */
46
47
(function () {
48
  if (!React) {
49
    {
50
      throw ReactError(Error("ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM."));
51
    }
52
  }
53
})();
54
55
/**
56
 * Injectable ordering of event plugins.
57
 */
58
var eventPluginOrder = null;
59
/**
60
 * Injectable mapping from names to event plugin modules.
61
 */
62
63
var namesToPlugins = {};
64
/**
65
 * Recomputes the plugin list using the injected plugins and plugin ordering.
66
 *
67
 * @private
68
 */
69
70
function recomputePluginOrdering() {
71
  if (!eventPluginOrder) {
72
    // Wait until an `eventPluginOrder` is injected.
73
    return;
74
  }
75
76
  for (var pluginName in namesToPlugins) {
77
    var pluginModule = namesToPlugins[pluginName];
78
    var pluginIndex = eventPluginOrder.indexOf(pluginName);
79
80
    (function () {
81
      if (!(pluginIndex > -1)) {
82
        {
83
          throw ReactError(Error("EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + pluginName + "`."));
84
        }
85
      }
86
    })();
87
88
    if (plugins[pluginIndex]) {
89
      continue;
90
    }
91
92
    (function () {
93
      if (!pluginModule.extractEvents) {
94
        {
95
          throw ReactError(Error("EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + pluginName + "` does not."));
96
        }
97
      }
98
    })();
99
100
    plugins[pluginIndex] = pluginModule;
101
    var publishedEvents = pluginModule.eventTypes;
102
103
    for (var eventName in publishedEvents) {
104
      (function () {
105
        if (!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName)) {
106
          {
107
            throw ReactError(Error("EventPluginRegistry: Failed to publish event `" + eventName + "` for plugin `" + pluginName + "`."));
108
          }
109
        }
110
      })();
111
    }
112
  }
113
}
114
/**
115
 * Publishes an event so that it can be dispatched by the supplied plugin.
116
 *
117
 * @param {object} dispatchConfig Dispatch configuration for the event.
118
 * @param {object} PluginModule Plugin publishing the event.
119
 * @return {boolean} True if the event was successfully published.
120
 * @private
121
 */
122
123
124
function publishEventForPlugin(dispatchConfig, pluginModule, eventName) {
125
  (function () {
126
    if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) {
127
      {
128
        throw ReactError(Error("EventPluginHub: More than one plugin attempted to publish the same event name, `" + eventName + "`."));
129
      }
130
    }
131
  })();
132
133
  eventNameDispatchConfigs[eventName] = dispatchConfig;
134
  var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
135
136
  if (phasedRegistrationNames) {
137
    for (var phaseName in phasedRegistrationNames) {
138
      if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
139
        var phasedRegistrationName = phasedRegistrationNames[phaseName];
140
        publishRegistrationName(phasedRegistrationName, pluginModule, eventName);
141
      }
142
    }
143
144
    return true;
145
  } else if (dispatchConfig.registrationName) {
146
    publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);
147
    return true;
148
  }
149
150
  return false;
151
}
152
/**
153
 * Publishes a registration name that is used to identify dispatched events.
154
 *
155
 * @param {string} registrationName Registration name to add.
156
 * @param {object} PluginModule Plugin publishing the event.
157
 * @private
158
 */
159
160
161
function publishRegistrationName(registrationName, pluginModule, eventName) {
162
  (function () {
163
    if (!!registrationNameModules[registrationName]) {
164
      {
165
        throw ReactError(Error("EventPluginHub: More than one plugin attempted to publish the same registration name, `" + registrationName + "`."));
166
      }
167
    }
168
  })();
169
170
  registrationNameModules[registrationName] = pluginModule;
171
  registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;
172
173
  {
174
    var lowerCasedName = registrationName.toLowerCase();
175
    possibleRegistrationNames[lowerCasedName] = registrationName;
176
177
    if (registrationName === 'onDoubleClick') {
178
      possibleRegistrationNames.ondblclick = registrationName;
179
    }
180
  }
181
}
182
/**
183
 * Registers plugins so that they can extract and dispatch events.
184
 *
185
 * @see {EventPluginHub}
186
 */
187
188
/**
189
 * Ordered list of injected plugins.
190
 */
191
192
193
var plugins = [];
194
/**
195
 * Mapping from event name to dispatch config
196
 */
197
198
var eventNameDispatchConfigs = {};
199
/**
200
 * Mapping from registration name to plugin module
201
 */
202
203
var registrationNameModules = {};
204
/**
205
 * Mapping from registration name to event name
206
 */
207
208
var registrationNameDependencies = {};
209
/**
210
 * Mapping from lowercase registration names to the properly cased version,
211
 * used to warn in the case of missing event handlers. Available
212
 * only in true.
213
 * @type {Object}
214
 */
215
216
var possibleRegistrationNames = {}; // Trust the developer to only use possibleRegistrationNames in true
217
218
/**
219
 * Injects an ordering of plugins (by plugin name). This allows the ordering
220
 * to be decoupled from injection of the actual plugins so that ordering is
221
 * always deterministic regardless of packaging, on-the-fly injection, etc.
222
 *
223
 * @param {array} InjectedEventPluginOrder
224
 * @internal
225
 * @see {EventPluginHub.injection.injectEventPluginOrder}
226
 */
227
228
function injectEventPluginOrder(injectedEventPluginOrder) {
229
  (function () {
230
    if (!!eventPluginOrder) {
231
      {
232
        throw ReactError(Error("EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React."));
233
      }
234
    }
235
  })(); // Clone the ordering so it cannot be dynamically mutated.
236
237
238
  eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
239
  recomputePluginOrdering();
240
}
241
/**
242
 * Injects plugins to be used by `EventPluginHub`. The plugin names must be
243
 * in the ordering injected by `injectEventPluginOrder`.
244
 *
245
 * Plugins can be injected as part of page initialization or on-the-fly.
246
 *
247
 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
248
 * @internal
249
 * @see {EventPluginHub.injection.injectEventPluginsByName}
250
 */
251
252
function injectEventPluginsByName(injectedNamesToPlugins) {
253
  var isOrderingDirty = false;
254
255
  for (var pluginName in injectedNamesToPlugins) {
256
    if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
257
      continue;
258
    }
259
260
    var pluginModule = injectedNamesToPlugins[pluginName];
261
262
    if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {
263
      (function () {
264
        if (!!namesToPlugins[pluginName]) {
265
          {
266
            throw ReactError(Error("EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + pluginName + "`."));
267
          }
268
        }
269
      })();
270
271
      namesToPlugins[pluginName] = pluginModule;
272
      isOrderingDirty = true;
273
    }
274
  }
275
276
  if (isOrderingDirty) {
277
    recomputePluginOrdering();
278
  }
279
}
280
281
var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {
282
  var funcArgs = Array.prototype.slice.call(arguments, 3);
283
284
  try {
285
    func.apply(context, funcArgs);
286
  } catch (error) {
287
    this.onError(error);
288
  }
289
};
290
291
{
292
  // In DEV mode, we swap out invokeGuardedCallback for a special version
293
  // that plays more nicely with the browser's DevTools. The idea is to preserve
294
  // "Pause on exceptions" behavior. Because React wraps all user-provided
295
  // functions in invokeGuardedCallback, and the production version of
296
  // invokeGuardedCallback uses a try-catch, all user exceptions are treated
297
  // like caught exceptions, and the DevTools won't pause unless the developer
298
  // takes the extra step of enabling pause on caught exceptions. This is
299
  // unintuitive, though, because even though React has caught the error, from
300
  // the developer's perspective, the error is uncaught.
301
  //
302
  // To preserve the expected "Pause on exceptions" behavior, we don't use a
303
  // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
304
  // DOM node, and call the user-provided callback from inside an event handler
305
  // for that fake event. If the callback throws, the error is "captured" using
306
  // a global event handler. But because the error happens in a different
307
  // event loop context, it does not interrupt the normal program flow.
308
  // Effectively, this gives us try-catch behavior without actually using
309
  // try-catch. Neat!
310
  // Check that the browser supports the APIs we need to implement our special
311
  // DEV version of invokeGuardedCallback
312
  if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
313
    var fakeNode = document.createElement('react');
314
315
    var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {
316
      // If document doesn't exist we know for sure we will crash in this method
317
      // when we call document.createEvent(). However this can cause confusing
318
      // errors: https://github.com/facebookincubator/create-react-app/issues/3482
319
      // So we preemptively throw with a better message instead.
320
      (function () {
321
        if (!(typeof document !== 'undefined')) {
322
          {
323
            throw ReactError(Error("The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous."));
324
          }
325
        }
326
      })();
327
328
      var evt = document.createEvent('Event'); // Keeps track of whether the user-provided callback threw an error. We
329
      // set this to true at the beginning, then set it to false right after
330
      // calling the function. If the function errors, `didError` will never be
331
      // set to false. This strategy works even if the browser is flaky and
332
      // fails to call our global error handler, because it doesn't rely on
333
      // the error event at all.
334
335
      var didError = true; // Keeps track of the value of window.event so that we can reset it
336
      // during the callback to let user code access window.event in the
337
      // browsers that support it.
338
339
      var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
340
      // dispatching: https://github.com/facebook/react/issues/13688
341
342
      var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); // Create an event handler for our fake event. We will synchronously
343
      // dispatch our fake event using `dispatchEvent`. Inside the handler, we
344
      // call the user-provided callback.
345
346
      var funcArgs = Array.prototype.slice.call(arguments, 3);
347
348
      function callCallback() {
349
        // We immediately remove the callback from event listeners so that
350
        // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
351
        // nested call would trigger the fake event handlers of any call higher
352
        // in the stack.
353
        fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
354
        // window.event assignment in both IE <= 10 as they throw an error
355
        // "Member not found" in strict mode, and in Firefox which does not
356
        // support window.event.
357
358
        if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
359
          window.event = windowEvent;
360
        }
361
362
        func.apply(context, funcArgs);
363
        didError = false;
364
      } // Create a global error event handler. We use this to capture the value
365
      // that was thrown. It's possible that this error handler will fire more
366
      // than once; for example, if non-React code also calls `dispatchEvent`
367
      // and a handler for that event throws. We should be resilient to most of
368
      // those cases. Even if our error event handler fires more than once, the
369
      // last error event is always used. If the callback actually does error,
370
      // we know that the last error event is the correct one, because it's not
371
      // possible for anything else to have happened in between our callback
372
      // erroring and the code that follows the `dispatchEvent` call below. If
373
      // the callback doesn't error, but the error event was fired, we know to
374
      // ignore it because `didError` will be false, as described above.
375
376
377
      var error; // Use this to track whether the error event is ever called.
378
379
      var didSetError = false;
380
      var isCrossOriginError = false;
381
382
      function handleWindowError(event) {
383
        error = event.error;
384
        didSetError = true;
385
386
        if (error === null && event.colno === 0 && event.lineno === 0) {
387
          isCrossOriginError = true;
388
        }
389
390
        if (event.defaultPrevented) {
391
          // Some other error handler has prevented default.
392
          // Browsers silence the error report if this happens.
393
          // We'll remember this to later decide whether to log it or not.
394
          if (error != null && typeof error === 'object') {
395
            try {
396
              error._suppressLogging = true;
397
            } catch (inner) {// Ignore.
398
            }
399
          }
400
        }
401
      } // Create a fake event type.
402
403
404
      var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers
405
406
      window.addEventListener('error', handleWindowError);
407
      fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
408
      // errors, it will trigger our global error handler.
409
410
      evt.initEvent(evtType, false, false);
411
      fakeNode.dispatchEvent(evt);
412
413
      if (windowEventDescriptor) {
414
        Object.defineProperty(window, 'event', windowEventDescriptor);
415
      }
416
417
      if (didError) {
418
        if (!didSetError) {
419
          // The callback errored, but the error event never fired.
420
          error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');
421
        } else if (isCrossOriginError) {
422
          error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.');
423
        }
424
425
        this.onError(error);
426
      } // Remove our event listeners
427
428
429
      window.removeEventListener('error', handleWindowError);
430
    };
431
432
    invokeGuardedCallbackImpl = invokeGuardedCallbackDev;
433
  }
434
}
435
436
var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
437
438
var hasError = false;
439
var caughtError = null; // Used by event system to capture/rethrow the first error.
440
441
var hasRethrowError = false;
442
var rethrowError = null;
443
var reporter = {
444
  onError: function (error) {
445
    hasError = true;
446
    caughtError = error;
447
  }
448
};
449
/**
450
 * Call a function while guarding against errors that happens within it.
451
 * Returns an error if it throws, otherwise null.
452
 *
453
 * In production, this is implemented using a try-catch. The reason we don't
454
 * use a try-catch directly is so that we can swap out a different
455
 * implementation in DEV mode.
456
 *
457
 * @param {String} name of the guard to use for logging or debugging
458
 * @param {Function} func The function to invoke
459
 * @param {*} context The context to use when calling the function
460
 * @param {...*} args Arguments for function
461
 */
462
463
function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
464
  hasError = false;
465
  caughtError = null;
466
  invokeGuardedCallbackImpl$1.apply(reporter, arguments);
467
}
468
/**
469
 * Same as invokeGuardedCallback, but instead of returning an error, it stores
470
 * it in a global so it can be rethrown by `rethrowCaughtError` later.
471
 * TODO: See if caughtError and rethrowError can be unified.
472
 *
473
 * @param {String} name of the guard to use for logging or debugging
474
 * @param {Function} func The function to invoke
475
 * @param {*} context The context to use when calling the function
476
 * @param {...*} args Arguments for function
477
 */
478
479
function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
480
  invokeGuardedCallback.apply(this, arguments);
481
482
  if (hasError) {
483
    var error = clearCaughtError();
484
485
    if (!hasRethrowError) {
486
      hasRethrowError = true;
487
      rethrowError = error;
488
    }
489
  }
490
}
491
/**
492
 * During execution of guarded functions we will capture the first error which
493
 * we will rethrow to be handled by the top level error handler.
494
 */
495
496
function rethrowCaughtError() {
497
  if (hasRethrowError) {
498
    var error = rethrowError;
499
    hasRethrowError = false;
500
    rethrowError = null;
501
    throw error;
502
  }
503
}
504
function hasCaughtError() {
505
  return hasError;
506
}
507
function clearCaughtError() {
508
  if (hasError) {
509
    var error = caughtError;
510
    hasError = false;
511
    caughtError = null;
512
    return error;
513
  } else {
514
    (function () {
515
      {
516
        {
517
          throw ReactError(Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue."));
518
        }
519
      }
520
    })();
521
  }
522
}
523
524
/**
525
 * Similar to invariant but only logs a warning if the condition is not met.
526
 * This can be used to log issues in development environments in critical
527
 * paths. Removing the logging code for production environments will keep the
528
 * same logic and follow the same code paths.
529
 */
530
var warningWithoutStack = function () {};
531
532
{
533
  warningWithoutStack = function (condition, format) {
534
    for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
535
      args[_key - 2] = arguments[_key];
536
    }
537
538
    if (format === undefined) {
539
      throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
540
    }
541
542
    if (args.length > 8) {
543
      // Check before the condition to catch violations early.
544
      throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
545
    }
546
547
    if (condition) {
548
      return;
549
    }
550
551
    if (typeof console !== 'undefined') {
552
      var argsWithFormat = args.map(function (item) {
553
        return '' + item;
554
      });
555
      argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
556
      // breaks IE9: https://github.com/facebook/react/issues/13610
557
558
      Function.prototype.apply.call(console.error, console, argsWithFormat);
559
    }
560
561
    try {
562
      // --- Welcome to debugging React ---
563
      // This error was thrown as a convenience so that you can use this stack
564
      // to find the callsite that caused this warning to fire.
565
      var argIndex = 0;
566
      var message = 'Warning: ' + format.replace(/%s/g, function () {
567
        return args[argIndex++];
568
      });
569
      throw new Error(message);
570
    } catch (x) {}
571
  };
572
}
573
574
var warningWithoutStack$1 = warningWithoutStack;
575
576
var getFiberCurrentPropsFromNode = null;
577
var getInstanceFromNode = null;
578
var getNodeFromInstance = null;
579
function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) {
580
  getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;
581
  getInstanceFromNode = getInstanceFromNodeImpl;
582
  getNodeFromInstance = getNodeFromInstanceImpl;
583
584
  {
585
    !(getNodeFromInstance && getInstanceFromNode) ? warningWithoutStack$1(false, 'EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0;
586
  }
587
}
588
var validateEventDispatches;
589
590
{
591
  validateEventDispatches = function (event) {
592
    var dispatchListeners = event._dispatchListeners;
593
    var dispatchInstances = event._dispatchInstances;
594
    var listenersIsArr = Array.isArray(dispatchListeners);
595
    var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
596
    var instancesIsArr = Array.isArray(dispatchInstances);
597
    var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
598
    !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, 'EventPluginUtils: Invalid `event`.') : void 0;
599
  };
600
}
601
/**
602
 * Dispatch the event to the listener.
603
 * @param {SyntheticEvent} event SyntheticEvent to handle
604
 * @param {function} listener Application-level callback
605
 * @param {*} inst Internal component instance
606
 */
607
608
609
function executeDispatch(event, listener, inst) {
610
  var type = event.type || 'unknown-event';
611
  event.currentTarget = getNodeFromInstance(inst);
612
  invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
613
  event.currentTarget = null;
614
}
615
/**
616
 * Standard/simple iteration through an event's collected dispatches.
617
 */
618
619
function executeDispatchesInOrder(event) {
620
  var dispatchListeners = event._dispatchListeners;
621
  var dispatchInstances = event._dispatchInstances;
622
623
  {
624
    validateEventDispatches(event);
625
  }
626
627
  if (Array.isArray(dispatchListeners)) {
628
    for (var i = 0; i < dispatchListeners.length; i++) {
629
      if (event.isPropagationStopped()) {
630
        break;
631
      } // Listeners and Instances are two parallel arrays that are always in sync.
632
633
634
      executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
635
    }
636
  } else if (dispatchListeners) {
637
    executeDispatch(event, dispatchListeners, dispatchInstances);
638
  }
639
640
  event._dispatchListeners = null;
641
  event._dispatchInstances = null;
642
}
643
/**
644
 * @see executeDispatchesInOrderStopAtTrueImpl
645
 */
646
647
648
649
/**
650
 * Execution of a "direct" dispatch - there must be at most one dispatch
651
 * accumulated on the event or it is considered an error. It doesn't really make
652
 * sense for an event with multiple dispatches (bubbled) to keep track of the
653
 * return values at each dispatch execution, but it does tend to make sense when
654
 * dealing with "direct" dispatches.
655
 *
656
 * @return {*} The return value of executing the single dispatch.
657
 */
658
659
660
/**
661
 * @param {SyntheticEvent} event
662
 * @return {boolean} True iff number of dispatches accumulated is greater than 0.
663
 */
664
665
/**
666
 * Accumulates items that must not be null or undefined into the first one. This
667
 * is used to conserve memory by avoiding array allocations, and thus sacrifices
668
 * API cleanness. Since `current` can be null before being passed in and not
669
 * null after this function, make sure to assign it back to `current`:
670
 *
671
 * `a = accumulateInto(a, b);`
672
 *
673
 * This API should be sparingly used. Try `accumulate` for something cleaner.
674
 *
675
 * @return {*|array<*>} An accumulation of items.
676
 */
677
678
function accumulateInto(current, next) {
679
  (function () {
680
    if (!(next != null)) {
681
      {
682
        throw ReactError(Error("accumulateInto(...): Accumulated items must not be null or undefined."));
683
      }
684
    }
685
  })();
686
687
  if (current == null) {
688
    return next;
689
  } // Both are not empty. Warning: Never call x.concat(y) when you are not
690
  // certain that x is an Array (x could be a string with concat method).
691
692
693
  if (Array.isArray(current)) {
694
    if (Array.isArray(next)) {
695
      current.push.apply(current, next);
696
      return current;
697
    }
698
699
    current.push(next);
700
    return current;
701
  }
702
703
  if (Array.isArray(next)) {
704
    // A bit too dangerous to mutate `next`.
705
    return [current].concat(next);
706
  }
707
708
  return [current, next];
709
}
710
711
/**
712
 * @param {array} arr an "accumulation" of items which is either an Array or
713
 * a single item. Useful when paired with the `accumulate` module. This is a
714
 * simple utility that allows us to reason about a collection of items, but
715
 * handling the case when there is exactly one item (and we do not need to
716
 * allocate an array).
717
 * @param {function} cb Callback invoked with each element or a collection.
718
 * @param {?} [scope] Scope used as `this` in a callback.
719
 */
720
function forEachAccumulated(arr, cb, scope) {
721
  if (Array.isArray(arr)) {
722
    arr.forEach(cb, scope);
723
  } else if (arr) {
724
    cb.call(scope, arr);
725
  }
726
}
727
728
/**
729
 * Internal queue of events that have accumulated their dispatches and are
730
 * waiting to have their dispatches executed.
731
 */
732
733
var eventQueue = null;
734
/**
735
 * Dispatches an event and releases it back into the pool, unless persistent.
736
 *
737
 * @param {?object} event Synthetic event to be dispatched.
738
 * @private
739
 */
740
741
var executeDispatchesAndRelease = function (event) {
742
  if (event) {
743
    executeDispatchesInOrder(event);
744
745
    if (!event.isPersistent()) {
746
      event.constructor.release(event);
747
    }
748
  }
749
};
750
751
var executeDispatchesAndReleaseTopLevel = function (e) {
752
  return executeDispatchesAndRelease(e);
753
};
754
755
function runEventsInBatch(events) {
756
  if (events !== null) {
757
    eventQueue = accumulateInto(eventQueue, events);
758
  } // Set `eventQueue` to null before processing it so that we can tell if more
759
  // events get enqueued while processing.
760
761
762
  var processingEventQueue = eventQueue;
763
  eventQueue = null;
764
765
  if (!processingEventQueue) {
766
    return;
767
  }
768
769
  forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
770
771
  (function () {
772
    if (!!eventQueue) {
773
      {
774
        throw ReactError(Error("processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented."));
775
      }
776
    }
777
  })(); // This would be a good time to rethrow if any of the event handlers threw.
778
779
780
  rethrowCaughtError();
781
}
782
783
function isInteractive(tag) {
784
  return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
785
}
786
787
function shouldPreventMouseEvent(name, type, props) {
788
  switch (name) {
789
    case 'onClick':
790
    case 'onClickCapture':
791
    case 'onDoubleClick':
792
    case 'onDoubleClickCapture':
793
    case 'onMouseDown':
794
    case 'onMouseDownCapture':
795
    case 'onMouseMove':
796
    case 'onMouseMoveCapture':
797
    case 'onMouseUp':
798
    case 'onMouseUpCapture':
799
      return !!(props.disabled && isInteractive(type));
800
801
    default:
802
      return false;
803
  }
804
}
805
/**
806
 * This is a unified interface for event plugins to be installed and configured.
807
 *
808
 * Event plugins can implement the following properties:
809
 *
810
 *   `extractEvents` {function(string, DOMEventTarget, string, object): *}
811
 *     Required. When a top-level event is fired, this method is expected to
812
 *     extract synthetic events that will in turn be queued and dispatched.
813
 *
814
 *   `eventTypes` {object}
815
 *     Optional, plugins that fire events must publish a mapping of registration
816
 *     names that are used to register listeners. Values of this mapping must
817
 *     be objects that contain `registrationName` or `phasedRegistrationNames`.
818
 *
819
 *   `executeDispatch` {function(object, function, string)}
820
 *     Optional, allows plugins to override how an event gets dispatched. By
821
 *     default, the listener is simply invoked.
822
 *
823
 * Each plugin that is injected into `EventsPluginHub` is immediately operable.
824
 *
825
 * @public
826
 */
827
828
/**
829
 * Methods for injecting dependencies.
830
 */
831
832
833
var injection = {
834
  /**
835
   * @param {array} InjectedEventPluginOrder
836
   * @public
837
   */
838
  injectEventPluginOrder: injectEventPluginOrder,
839
840
  /**
841
   * @param {object} injectedNamesToPlugins Map from names to plugin modules.
842
   */
843
  injectEventPluginsByName: injectEventPluginsByName
844
};
845
/**
846
 * @param {object} inst The instance, which is the source of events.
847
 * @param {string} registrationName Name of listener (e.g. `onClick`).
848
 * @return {?function} The stored callback.
849
 */
850
851
function getListener(inst, registrationName) {
852
  var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
853
  // live here; needs to be moved to a better place soon
854
855
  var stateNode = inst.stateNode;
856
857
  if (!stateNode) {
858
    // Work in progress (ex: onload events in incremental mode).
859
    return null;
860
  }
861
862
  var props = getFiberCurrentPropsFromNode(stateNode);
863
864
  if (!props) {
865
    // Work in progress.
866
    return null;
867
  }
868
869
  listener = props[registrationName];
870
871
  if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
872
    return null;
873
  }
874
875
  (function () {
876
    if (!(!listener || typeof listener === 'function')) {
877
      {
878
        throw ReactError(Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type."));
879
      }
880
    }
881
  })();
882
883
  return listener;
884
}
885
/**
886
 * Allows registered plugins an opportunity to extract events from top-level
887
 * native browser events.
888
 *
889
 * @return {*} An accumulation of synthetic events.
890
 * @internal
891
 */
892
893
function extractPluginEvents(topLevelType, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
894
  var events = null;
895
896
  for (var i = 0; i < plugins.length; i++) {
897
    // Not every plugin in the ordering may be loaded at runtime.
898
    var possiblePlugin = plugins[i];
899
900
    if (possiblePlugin) {
901
      var extractedEvents = possiblePlugin.extractEvents(topLevelType, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget);
902
903
      if (extractedEvents) {
904
        events = accumulateInto(events, extractedEvents);
905
      }
906
    }
907
  }
908
909
  return events;
910
}
911
912
function runExtractedPluginEventsInBatch(topLevelType, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
913
  var events = extractPluginEvents(topLevelType, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget);
914
  runEventsInBatch(events);
915
}
916
917
var FunctionComponent = 0;
918
var ClassComponent = 1;
919
var IndeterminateComponent = 2; // Before we know whether it is function or class
920
921
var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
922
923
var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
924
925
var HostComponent = 5;
926
var HostText = 6;
927
var Fragment = 7;
928
var Mode = 8;
929
var ContextConsumer = 9;
930
var ContextProvider = 10;
931
var ForwardRef = 11;
932
var Profiler = 12;
933
var SuspenseComponent = 13;
934
var MemoComponent = 14;
935
var SimpleMemoComponent = 15;
936
var LazyComponent = 16;
937
var IncompleteClassComponent = 17;
938
var DehydratedFragment = 18;
939
var SuspenseListComponent = 19;
940
var FundamentalComponent = 20;
941
var ScopeComponent = 21;
942
943
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.
944
// Current owner and dispatcher used to share the same ref,
945
// but PR #14548 split them out to better support the react-debug-tools package.
946
947
if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
948
  ReactSharedInternals.ReactCurrentDispatcher = {
949
    current: null
950
  };
951
}
952
953
if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) {
954
  ReactSharedInternals.ReactCurrentBatchConfig = {
955
    suspense: null
956
  };
957
}
958
959
var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
960
var describeComponentFrame = function (name, source, ownerName) {
961
  var sourceInfo = '';
962
963
  if (source) {
964
    var path = source.fileName;
965
    var fileName = path.replace(BEFORE_SLASH_RE, '');
966
967
    {
968
      // In DEV, include code for a common special case:
969
      // prefer "folder/index.js" instead of just "index.js".
970
      if (/^index\./.test(fileName)) {
971
        var match = path.match(BEFORE_SLASH_RE);
972
973
        if (match) {
974
          var pathBeforeSlash = match[1];
975
976
          if (pathBeforeSlash) {
977
            var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
978
            fileName = folderName + '/' + fileName;
979
          }
980
        }
981
      }
982
    }
983
984
    sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
985
  } else if (ownerName) {
986
    sourceInfo = ' (created by ' + ownerName + ')';
987
  }
988
989
  return '\n    in ' + (name || 'Unknown') + sourceInfo;
990
};
991
992
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
993
// nor polyfill, then a plain number is used for performance.
994
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
995
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
996
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
997
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
998
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
999
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
1000
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
1001
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
1002
// (unstable) APIs that have been removed. Can we remove the symbols?
1003
1004
1005
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
1006
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
1007
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
1008
var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
1009
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
1010
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
1011
var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
1012
var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
1013
var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
1014
var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
1015
var FAUX_ITERATOR_SYMBOL = '@@iterator';
1016
function getIteratorFn(maybeIterable) {
1017
  if (maybeIterable === null || typeof maybeIterable !== 'object') {
1018
    return null;
1019
  }
1020
1021
  var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
1022
1023
  if (typeof maybeIterator === 'function') {
1024
    return maybeIterator;
1025
  }
1026
1027
  return null;
1028
}
1029
1030
/**
1031
 * Similar to invariant but only logs a warning if the condition is not met.
1032
 * This can be used to log issues in development environments in critical
1033
 * paths. Removing the logging code for production environments will keep the
1034
 * same logic and follow the same code paths.
1035
 */
1036
1037
var warning = warningWithoutStack$1;
1038
1039
{
1040
  warning = function (condition, format) {
1041
    if (condition) {
1042
      return;
1043
    }
1044
1045
    var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1046
    var stack = ReactDebugCurrentFrame.getStackAddendum(); // eslint-disable-next-line react-internal/warning-and-invariant-args
1047
1048
    for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
1049
      args[_key - 2] = arguments[_key];
1050
    }
1051
1052
    warningWithoutStack$1.apply(void 0, [false, format + '%s'].concat(args, [stack]));
1053
  };
1054
}
1055
1056
var warning$1 = warning;
1057
1058
var Uninitialized = -1;
1059
var Pending = 0;
1060
var Resolved = 1;
1061
var Rejected = 2;
1062
function refineResolvedLazyComponent(lazyComponent) {
1063
  return lazyComponent._status === Resolved ? lazyComponent._result : null;
1064
}
1065
function initializeLazyComponentType(lazyComponent) {
1066
  if (lazyComponent._status === Uninitialized) {
1067
    lazyComponent._status = Pending;
1068
    var ctor = lazyComponent._ctor;
1069
    var thenable = ctor();
1070
    lazyComponent._result = thenable;
1071
    thenable.then(function (moduleObject) {
1072
      if (lazyComponent._status === Pending) {
1073
        var defaultExport = moduleObject.default;
1074
1075
        {
1076
          if (defaultExport === undefined) {
1077
            warning$1(false, 'lazy: Expected the result of a dynamic import() call. ' + 'Instead received: %s\n\nYour code should look like: \n  ' + "const MyComponent = lazy(() => import('./MyComponent'))", moduleObject);
1078
          }
1079
        }
1080
1081
        lazyComponent._status = Resolved;
1082
        lazyComponent._result = defaultExport;
1083
      }
1084
    }, function (error) {
1085
      if (lazyComponent._status === Pending) {
1086
        lazyComponent._status = Rejected;
1087
        lazyComponent._result = error;
1088
      }
1089
    });
1090
  }
1091
}
1092
1093
function getWrappedName(outerType, innerType, wrapperName) {
1094
  var functionName = innerType.displayName || innerType.name || '';
1095
  return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
1096
}
1097
1098
function getComponentName(type) {
1099
  if (type == null) {
1100
    // Host root, text node or just invalid type.
1101
    return null;
1102
  }
1103
1104
  {
1105
    if (typeof type.tag === 'number') {
1106
      warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
1107
    }
1108
  }
1109
1110
  if (typeof type === 'function') {
1111
    return type.displayName || type.name || null;
1112
  }
1113
1114
  if (typeof type === 'string') {
1115
    return type;
1116
  }
1117
1118
  switch (type) {
1119
    case REACT_FRAGMENT_TYPE:
1120
      return 'Fragment';
1121
1122
    case REACT_PORTAL_TYPE:
1123
      return 'Portal';
1124
1125
    case REACT_PROFILER_TYPE:
1126
      return "Profiler";
1127
1128
    case REACT_STRICT_MODE_TYPE:
1129
      return 'StrictMode';
1130
1131
    case REACT_SUSPENSE_TYPE:
1132
      return 'Suspense';
1133
1134
    case REACT_SUSPENSE_LIST_TYPE:
1135
      return 'SuspenseList';
1136
  }
1137
1138
  if (typeof type === 'object') {
1139
    switch (type.$$typeof) {
1140
      case REACT_CONTEXT_TYPE:
1141
        return 'Context.Consumer';
1142
1143
      case REACT_PROVIDER_TYPE:
1144
        return 'Context.Provider';
1145
1146
      case REACT_FORWARD_REF_TYPE:
1147
        return getWrappedName(type, type.render, 'ForwardRef');
1148
1149
      case REACT_MEMO_TYPE:
1150
        return getComponentName(type.type);
1151
1152
      case REACT_LAZY_TYPE:
1153
        {
1154
          var thenable = type;
1155
          var resolvedThenable = refineResolvedLazyComponent(thenable);
1156
1157
          if (resolvedThenable) {
1158
            return getComponentName(resolvedThenable);
1159
          }
1160
1161
          break;
1162
        }
1163
    }
1164
  }
1165
1166
  return null;
1167
}
1168
1169
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1170
1171
function describeFiber(fiber) {
1172
  switch (fiber.tag) {
1173
    case HostRoot:
1174
    case HostPortal:
1175
    case HostText:
1176
    case Fragment:
1177
    case ContextProvider:
1178
    case ContextConsumer:
1179
      return '';
1180
1181
    default:
1182
      var owner = fiber._debugOwner;
1183
      var source = fiber._debugSource;
1184
      var name = getComponentName(fiber.type);
1185
      var ownerName = null;
1186
1187
      if (owner) {
1188
        ownerName = getComponentName(owner.type);
1189
      }
1190
1191
      return describeComponentFrame(name, source, ownerName);
1192
  }
1193
}
1194
1195
function getStackByFiberInDevAndProd(workInProgress) {
1196
  var info = '';
1197
  var node = workInProgress;
1198
1199
  do {
1200
    info += describeFiber(node);
1201
    node = node.return;
1202
  } while (node);
1203
1204
  return info;
1205
}
1206
var current = null;
1207
var phase = null;
1208
function getCurrentFiberOwnerNameInDevOrNull() {
1209
  {
1210
    if (current === null) {
1211
      return null;
1212
    }
1213
1214
    var owner = current._debugOwner;
1215
1216
    if (owner !== null && typeof owner !== 'undefined') {
1217
      return getComponentName(owner.type);
1218
    }
1219
  }
1220
1221
  return null;
1222
}
1223
function getCurrentFiberStackInDev() {
1224
  {
1225
    if (current === null) {
1226
      return '';
1227
    } // Safe because if current fiber exists, we are reconciling,
1228
    // and it is guaranteed to be the work-in-progress version.
1229
1230
1231
    return getStackByFiberInDevAndProd(current);
1232
  }
1233
1234
  return '';
1235
}
1236
function resetCurrentFiber() {
1237
  {
1238
    ReactDebugCurrentFrame.getCurrentStack = null;
1239
    current = null;
1240
    phase = null;
1241
  }
1242
}
1243
function setCurrentFiber(fiber) {
1244
  {
1245
    ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev;
1246
    current = fiber;
1247
    phase = null;
1248
  }
1249
}
1250
function setCurrentPhase(lifeCyclePhase) {
1251
  {
1252
    phase = lifeCyclePhase;
1253
  }
1254
}
1255
1256
var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
1257
1258
function endsWith(subject, search) {
1259
  var length = subject.length;
1260
  return subject.substring(length - search.length, length) === search;
1261
}
1262
1263
var PLUGIN_EVENT_SYSTEM = 1;
1264
var RESPONDER_EVENT_SYSTEM = 1 << 1;
1265
var IS_PASSIVE = 1 << 2;
1266
var IS_ACTIVE = 1 << 3;
1267
var PASSIVE_NOT_SUPPORTED = 1 << 4;
1268
var IS_REPLAYED = 1 << 5;
1269
1270
var restoreImpl = null;
1271
var restoreTarget = null;
1272
var restoreQueue = null;
1273
1274
function restoreStateOfTarget(target) {
1275
  // We perform this translation at the end of the event loop so that we
1276
  // always receive the correct fiber here
1277
  var internalInstance = getInstanceFromNode(target);
1278
1279
  if (!internalInstance) {
1280
    // Unmounted
1281
    return;
1282
  }
1283
1284
  (function () {
1285
    if (!(typeof restoreImpl === 'function')) {
1286
      {
1287
        throw ReactError(Error("setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue."));
1288
      }
1289
    }
1290
  })();
1291
1292
  var props = getFiberCurrentPropsFromNode(internalInstance.stateNode);
1293
  restoreImpl(internalInstance.stateNode, internalInstance.type, props);
1294
}
1295
1296
function setRestoreImplementation(impl) {
1297
  restoreImpl = impl;
1298
}
1299
function enqueueStateRestore(target) {
1300
  if (restoreTarget) {
1301
    if (restoreQueue) {
1302
      restoreQueue.push(target);
1303
    } else {
1304
      restoreQueue = [target];
1305
    }
1306
  } else {
1307
    restoreTarget = target;
1308
  }
1309
}
1310
function needsStateRestore() {
1311
  return restoreTarget !== null || restoreQueue !== null;
1312
}
1313
function restoreStateIfNeeded() {
1314
  if (!restoreTarget) {
1315
    return;
1316
  }
1317
1318
  var target = restoreTarget;
1319
  var queuedTargets = restoreQueue;
1320
  restoreTarget = null;
1321
  restoreQueue = null;
1322
  restoreStateOfTarget(target);
1323
1324
  if (queuedTargets) {
1325
    for (var i = 0; i < queuedTargets.length; i++) {
1326
      restoreStateOfTarget(queuedTargets[i]);
1327
    }
1328
  }
1329
}
1330
1331
var enableUserTimingAPI = true; // Helps identify side effects in begin-phase lifecycle hooks and setState reducers:
1332
1333
var debugRenderPhaseSideEffects = false; // In some cases, StrictMode should also double-render lifecycles.
1334
// This can be confusing for tests though,
1335
// And it can be bad for performance in production.
1336
// This feature flag can be used to control the behavior:
1337
1338
var debugRenderPhaseSideEffectsForStrictMode = true; // To preserve the "Pause on caught exceptions" behavior of the debugger, we
1339
// replay the begin phase of a failed component inside invokeGuardedCallback.
1340
1341
var replayFailedUnitOfWorkWithInvokeGuardedCallback = true; // Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:
1342
1343
var warnAboutDeprecatedLifecycles = true; // Gather advanced timing metrics for Profiler subtrees.
1344
1345
var enableProfilerTimer = true; // Trace which interactions trigger each commit.
1346
1347
var enableSchedulerTracing = true; // Only used in www builds.
1348
1349
var enableSuspenseServerRenderer = false; // TODO: true? Here it might just be false.
1350
1351
var enableSelectiveHydration = false; // Only used in www builds.
1352
1353
 // Only used in www builds.
1354
1355
 // Disable javascript: URL strings in href for XSS protection.
1356
1357
var disableJavaScriptURLs = false; // React Fire: prevent the value and checked attributes from syncing
1358
// with their related DOM properties
1359
1360
var disableInputAttributeSyncing = false; // These APIs will no longer be "unstable" in the upcoming 16.7 release,
1361
// Control this behavior with a flag to support 16.6 minor releases in the meanwhile.
1362
1363
var enableStableConcurrentModeAPIs = false;
1364
var warnAboutShorthandPropertyCollision = false; // See https://github.com/react-native-community/discussions-and-proposals/issues/72 for more information
1365
// This is a flag so we can fix warnings in RN core before turning it on
1366
1367
 // Experimental React Flare event system and event components support.
1368
1369
var enableFlareAPI = false; // Experimental Host Component support.
1370
1371
var enableFundamentalAPI = false; // Experimental Scope support.
1372
1373
var enableScopeAPI = false; // New API for JSX transforms to target - https://github.com/reactjs/rfcs/pull/107
1374
1375
 // We will enforce mocking scheduler with scheduler/unstable_mock at some point. (v17?)
1376
// Till then, we warn about the missing mock, but still fallback to a sync mode compatible version
1377
1378
var warnAboutUnmockedScheduler = false; // For tests, we flush suspense fallbacks in an act scope;
1379
// *except* in some of our own tests, where we test incremental loading states.
1380
1381
var flushSuspenseFallbacksInTests = true; // Changes priority of some events like mousemove to user-blocking priority,
1382
// but without making them discrete. The flag exists in case it causes
1383
// starvation problems.
1384
1385
var enableUserBlockingEvents = false; // Add a callback property to suspense to notify which promises are currently
1386
// in the update queue. This allows reporting and tracing of what is causing
1387
// the user to see a loading state.
1388
// Also allows hydration callbacks to fire when a dehydrated boundary gets
1389
// hydrated or deleted.
1390
1391
var enableSuspenseCallback = false; // Part of the simplification of React.createElement so we can eventually move
1392
// from React.createElement to React.jsx
1393
// https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md
1394
1395
var warnAboutDefaultPropsOnFunctionComponents = false;
1396
var warnAboutStringRefs = false;
1397
var disableLegacyContext = false;
1398
var disableSchedulerTimeoutBasedOnReactExpirationTime = false;
1399
var enableTrustedTypesIntegration = false;
1400
1401
// the renderer. Such as when we're dispatching events or if third party
1402
// libraries need to call batchedUpdates. Eventually, this API will go away when
1403
// everything is batched by default. We'll then have a similar API to opt-out of
1404
// scheduled work and instead do synchronous work.
1405
// Defaults
1406
1407
var batchedUpdatesImpl = function (fn, bookkeeping) {
1408
  return fn(bookkeeping);
1409
};
1410
1411
var discreteUpdatesImpl = function (fn, a, b, c) {
1412
  return fn(a, b, c);
1413
};
1414
1415
var flushDiscreteUpdatesImpl = function () {};
1416
1417
var batchedEventUpdatesImpl = batchedUpdatesImpl;
1418
var isInsideEventHandler = false;
1419
var isBatchingEventUpdates = false;
1420
1421
function finishEventHandler() {
1422
  // Here we wait until all updates have propagated, which is important
1423
  // when using controlled components within layers:
1424
  // https://github.com/facebook/react/issues/1698
1425
  // Then we restore state of any controlled component.
1426
  var controlledComponentsHavePendingUpdates = needsStateRestore();
1427
1428
  if (controlledComponentsHavePendingUpdates) {
1429
    // If a controlled event was fired, we may need to restore the state of
1430
    // the DOM node back to the controlled value. This is necessary when React
1431
    // bails out of the update without touching the DOM.
1432
    flushDiscreteUpdatesImpl();
1433
    restoreStateIfNeeded();
1434
  }
1435
}
1436
1437
function batchedUpdates(fn, bookkeeping) {
1438
  if (isInsideEventHandler) {
1439
    // If we are currently inside another batch, we need to wait until it
1440
    // fully completes before restoring state.
1441
    return fn(bookkeeping);
1442
  }
1443
1444
  isInsideEventHandler = true;
1445
1446
  try {
1447
    return batchedUpdatesImpl(fn, bookkeeping);
1448
  } finally {
1449
    isInsideEventHandler = false;
1450
    finishEventHandler();
1451
  }
1452
}
1453
function batchedEventUpdates(fn, a, b) {
1454
  if (isBatchingEventUpdates) {
1455
    // If we are currently inside another batch, we need to wait until it
1456
    // fully completes before restoring state.
1457
    return fn(a, b);
1458
  }
1459
1460
  isBatchingEventUpdates = true;
1461
1462
  try {
1463
    return batchedEventUpdatesImpl(fn, a, b);
1464
  } finally {
1465
    isBatchingEventUpdates = false;
1466
    finishEventHandler();
1467
  }
1468
} // This is for the React Flare event system
1469
1470
function executeUserEventHandler(fn, value) {
1471
  var previouslyInEventHandler = isInsideEventHandler;
1472
1473
  try {
1474
    isInsideEventHandler = true;
1475
    var type = typeof value === 'object' && value !== null ? value.type : '';
1476
    invokeGuardedCallbackAndCatchFirstError(type, fn, undefined, value);
1477
  } finally {
1478
    isInsideEventHandler = previouslyInEventHandler;
1479
  }
1480
}
1481
function discreteUpdates(fn, a, b, c) {
1482
  var prevIsInsideEventHandler = isInsideEventHandler;
1483
  isInsideEventHandler = true;
1484
1485
  try {
1486
    return discreteUpdatesImpl(fn, a, b, c);
1487
  } finally {
1488
    isInsideEventHandler = prevIsInsideEventHandler;
1489
1490
    if (!isInsideEventHandler) {
1491
      finishEventHandler();
1492
    }
1493
  }
1494
}
1495
var lastFlushedEventTimeStamp = 0;
1496
function flushDiscreteUpdatesIfNeeded(timeStamp) {
1497
  // event.timeStamp isn't overly reliable due to inconsistencies in
1498
  // how different browsers have historically provided the time stamp.
1499
  // Some browsers provide high-resolution time stamps for all events,
1500
  // some provide low-resolution time stamps for all events. FF < 52
1501
  // even mixes both time stamps together. Some browsers even report
1502
  // negative time stamps or time stamps that are 0 (iOS9) in some cases.
1503
  // Given we are only comparing two time stamps with equality (!==),
1504
  // we are safe from the resolution differences. If the time stamp is 0
1505
  // we bail-out of preventing the flush, which can affect semantics,
1506
  // such as if an earlier flush removes or adds event listeners that
1507
  // are fired in the subsequent flush. However, this is the same
1508
  // behaviour as we had before this change, so the risks are low.
1509
  if (!isInsideEventHandler && (!enableFlareAPI || timeStamp === 0 || lastFlushedEventTimeStamp !== timeStamp)) {
1510
    lastFlushedEventTimeStamp = timeStamp;
1511
    flushDiscreteUpdatesImpl();
1512
  }
1513
}
1514
function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushDiscreteUpdatesImpl, _batchedEventUpdatesImpl) {
1515
  batchedUpdatesImpl = _batchedUpdatesImpl;
1516
  discreteUpdatesImpl = _discreteUpdatesImpl;
1517
  flushDiscreteUpdatesImpl = _flushDiscreteUpdatesImpl;
1518
  batchedEventUpdatesImpl = _batchedEventUpdatesImpl;
1519
}
1520
1521
var DiscreteEvent = 0;
1522
var UserBlockingEvent = 1;
1523
var ContinuousEvent = 2;
1524
1525
// CommonJS interop named imports.
1526
1527
var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority;
1528
var runWithPriority = Scheduler.unstable_runWithPriority;
1529
var listenToResponderEventTypesImpl;
1530
function setListenToResponderEventTypes(_listenToResponderEventTypesImpl) {
1531
  listenToResponderEventTypesImpl = _listenToResponderEventTypesImpl;
1532
}
1533
var activeTimeouts = new Map();
1534
var rootEventTypesToEventResponderInstances = new Map();
1535
var DoNotPropagateToNextResponder = 0;
1536
var PropagateToNextResponder = 1;
1537
var currentTimeStamp = 0;
1538
var currentTimers = new Map();
1539
var currentInstance = null;
1540
var currentTimerIDCounter = 0;
1541
var currentDocument = null;
1542
var currentPropagationBehavior = DoNotPropagateToNextResponder;
1543
var eventResponderContext = {
1544
  dispatchEvent: function (eventValue, eventListener, eventPriority) {
1545
    validateResponderContext();
1546
    validateEventValue(eventValue);
1547
1548
    switch (eventPriority) {
1549
      case DiscreteEvent:
1550
        {
1551
          flushDiscreteUpdatesIfNeeded(currentTimeStamp);
1552
          discreteUpdates(function () {
1553
            return executeUserEventHandler(eventListener, eventValue);
1554
          });
1555
          break;
1556
        }
1557
1558
      case UserBlockingEvent:
1559
        {
1560
          if (enableUserBlockingEvents) {
1561
            runWithPriority(UserBlockingPriority, function () {
1562
              return executeUserEventHandler(eventListener, eventValue);
1563
            });
1564
          } else {
1565
            executeUserEventHandler(eventListener, eventValue);
1566
          }
1567
1568
          break;
1569
        }
1570
1571
      case ContinuousEvent:
1572
        {
1573
          executeUserEventHandler(eventListener, eventValue);
1574
          break;
1575
        }
1576
    }
1577
  },
1578
  isTargetWithinResponder: function (target) {
1579
    validateResponderContext();
1580
1581
    if (target != null) {
1582
      var fiber = getClosestInstanceFromNode(target);
1583
      var responderFiber = currentInstance.fiber;
1584
1585
      while (fiber !== null) {
1586
        if (fiber === responderFiber || fiber.alternate === responderFiber) {
1587
          return true;
1588
        }
1589
1590
        fiber = fiber.return;
1591
      }
1592
    }
1593
1594
    return false;
1595
  },
1596
  isTargetWithinResponderScope: function (target) {
1597
    validateResponderContext();
1598
    var componentInstance = currentInstance;
1599
    var responder = componentInstance.responder;
1600
1601
    if (target != null) {
1602
      var fiber = getClosestInstanceFromNode(target);
1603
      var responderFiber = currentInstance.fiber;
1604
1605
      while (fiber !== null) {
1606
        if (fiber === responderFiber || fiber.alternate === responderFiber) {
1607
          return true;
1608
        }
1609
1610
        if (doesFiberHaveResponder(fiber, responder)) {
1611
          return false;
1612
        }
1613
1614
        fiber = fiber.return;
1615
      }
1616
    }
1617
1618
    return false;
1619
  },
1620
  isTargetWithinNode: function (childTarget, parentTarget) {
1621
    validateResponderContext();
1622
    var childFiber = getClosestInstanceFromNode(childTarget);
1623
    var parentFiber = getClosestInstanceFromNode(parentTarget);
1624
1625
    if (childFiber != null && parentFiber != null) {
1626
      var parentAlternateFiber = parentFiber.alternate;
1627
      var node = childFiber;
1628
1629
      while (node !== null) {
1630
        if (node === parentFiber || node === parentAlternateFiber) {
1631
          return true;
1632
        }
1633
1634
        node = node.return;
1635
      }
1636
1637
      return false;
1638
    } // Fallback to DOM APIs
1639
1640
1641
    return parentTarget.contains(childTarget);
1642
  },
1643
  addRootEventTypes: function (rootEventTypes) {
1644
    validateResponderContext();
1645
    listenToResponderEventTypesImpl(rootEventTypes, currentDocument);
1646
1647
    for (var i = 0; i < rootEventTypes.length; i++) {
1648
      var rootEventType = rootEventTypes[i];
1649
      var eventResponderInstance = currentInstance;
1650
      registerRootEventType(rootEventType, eventResponderInstance);
1651
    }
1652
  },
1653
  removeRootEventTypes: function (rootEventTypes) {
1654
    validateResponderContext();
1655
1656
    for (var i = 0; i < rootEventTypes.length; i++) {
1657
      var rootEventType = rootEventTypes[i];
1658
      var rootEventResponders = rootEventTypesToEventResponderInstances.get(rootEventType);
1659
      var rootEventTypesSet = currentInstance.rootEventTypes;
1660
1661
      if (rootEventTypesSet !== null) {
1662
        rootEventTypesSet.delete(rootEventType);
1663
      }
1664
1665
      if (rootEventResponders !== undefined) {
1666
        rootEventResponders.delete(currentInstance);
1667
      }
1668
    }
1669
  },
1670
  setTimeout: function (func, delay) {
1671
    validateResponderContext();
1672
1673
    if (currentTimers === null) {
1674
      currentTimers = new Map();
1675
    }
1676
1677
    var timeout = currentTimers.get(delay);
1678
    var timerId = currentTimerIDCounter++;
1679
1680
    if (timeout === undefined) {
1681
      var timers = new Map();
1682
      var id = setTimeout(function () {
1683
        processTimers(timers, delay);
1684
      }, delay);
1685
      timeout = {
1686
        id: id,
1687
        timers: timers
1688
      };
1689
      currentTimers.set(delay, timeout);
1690
    }
1691
1692
    timeout.timers.set(timerId, {
1693
      instance: currentInstance,
1694
      func: func,
1695
      id: timerId,
1696
      timeStamp: currentTimeStamp
1697
    });
1698
    activeTimeouts.set(timerId, timeout);
1699
    return timerId;
1700
  },
1701
  clearTimeout: function (timerId) {
1702
    validateResponderContext();
1703
    var timeout = activeTimeouts.get(timerId);
1704
1705
    if (timeout !== undefined) {
1706
      var timers = timeout.timers;
1707
      timers.delete(timerId);
1708
1709
      if (timers.size === 0) {
1710
        clearTimeout(timeout.id);
1711
      }
1712
    }
1713
  },
1714
  getActiveDocument: getActiveDocument,
1715
  objectAssign: _assign,
1716
  getTimeStamp: function () {
1717
    validateResponderContext();
1718
    return currentTimeStamp;
1719
  },
1720
  isTargetWithinHostComponent: function (target, elementType) {
1721
    validateResponderContext();
1722
    var fiber = getClosestInstanceFromNode(target);
1723
1724
    while (fiber !== null) {
1725
      if (fiber.tag === HostComponent && fiber.type === elementType) {
1726
        return true;
1727
      }
1728
1729
      fiber = fiber.return;
1730
    }
1731
1732
    return false;
1733
  },
1734
  continuePropagation: function () {
1735
    currentPropagationBehavior = PropagateToNextResponder;
1736
  },
1737
  enqueueStateRestore: enqueueStateRestore,
1738
  getResponderNode: function () {
1739
    validateResponderContext();
1740
    var responderFiber = currentInstance.fiber;
1741
1742
    if (responderFiber.tag === ScopeComponent) {
1743
      return null;
1744
    }
1745
1746
    return responderFiber.stateNode;
1747
  }
1748
};
1749
1750
function validateEventValue(eventValue) {
1751
  if (typeof eventValue === 'object' && eventValue !== null) {
1752
    var target = eventValue.target,
1753
        type = eventValue.type,
1754
        timeStamp = eventValue.timeStamp;
1755
1756
    if (target == null || type == null || timeStamp == null) {
1757
      throw new Error('context.dispatchEvent: "target", "timeStamp", and "type" fields on event object are required.');
1758
    }
1759
1760
    var showWarning = function (name) {
1761
      {
1762
        warning$1(false, '%s is not available on event objects created from event responder modules (React Flare). ' + 'Try wrapping in a conditional, i.e. `if (event.type !== "press") { event.%s }`', name, name);
1763
      }
1764
    };
1765
1766
    eventValue.isDefaultPrevented = function () {
1767
      {
1768
        showWarning('isDefaultPrevented()');
1769
      }
1770
    };
1771
1772
    eventValue.isPropagationStopped = function () {
1773
      {
1774
        showWarning('isPropagationStopped()');
1775
      }
1776
    }; // $FlowFixMe: we don't need value, Flow thinks we do
1777
1778
1779
    Object.defineProperty(eventValue, 'nativeEvent', {
1780
      get: function () {
1781
        {
1782
          showWarning('nativeEvent');
1783
        }
1784
      }
1785
    });
1786
  }
1787
}
1788
1789
function doesFiberHaveResponder(fiber, responder) {
1790
  var tag = fiber.tag;
1791
1792
  if (tag === HostComponent || tag === ScopeComponent) {
1793
    var dependencies = fiber.dependencies;
1794
1795
    if (dependencies !== null) {
1796
      var respondersMap = dependencies.responders;
1797
1798
      if (respondersMap !== null && respondersMap.has(responder)) {
1799
        return true;
1800
      }
1801
    }
1802
  }
1803
1804
  return false;
1805
}
1806
1807
function getActiveDocument() {
1808
  return currentDocument;
1809
}
1810
1811
function processTimers(timers, delay) {
1812
  var timersArr = Array.from(timers.values());
1813
  var previousInstance = currentInstance;
1814
  var previousTimers = currentTimers;
1815
1816
  try {
1817
    batchedEventUpdates(function () {
1818
      for (var i = 0; i < timersArr.length; i++) {
1819
        var _timersArr$i = timersArr[i],
1820
            instance = _timersArr$i.instance,
1821
            func = _timersArr$i.func,
1822
            id = _timersArr$i.id,
1823
            timeStamp = _timersArr$i.timeStamp;
1824
        currentInstance = instance;
1825
        currentTimeStamp = timeStamp + delay;
1826
1827
        try {
1828
          func();
1829
        } finally {
1830
          activeTimeouts.delete(id);
1831
        }
1832
      }
1833
    });
1834
  } finally {
1835
    currentTimers = previousTimers;
1836
    currentInstance = previousInstance;
1837
    currentTimeStamp = 0;
1838
  }
1839
}
1840
1841
function createDOMResponderEvent(topLevelType, nativeEvent, nativeEventTarget, passive, passiveSupported) {
1842
  var _ref = nativeEvent,
1843
      buttons = _ref.buttons,
1844
      pointerType = _ref.pointerType;
1845
  var eventPointerType = '';
1846
1847
  if (pointerType !== undefined) {
1848
    eventPointerType = pointerType;
1849
  } else if (nativeEvent.key !== undefined) {
1850
    eventPointerType = 'keyboard';
1851
  } else if (buttons !== undefined) {
1852
    eventPointerType = 'mouse';
1853
  } else if (nativeEvent.changedTouches !== undefined) {
1854
    eventPointerType = 'touch';
1855
  }
1856
1857
  return {
1858
    nativeEvent: nativeEvent,
1859
    passive: passive,
1860
    passiveSupported: passiveSupported,
1861
    pointerType: eventPointerType,
1862
    target: nativeEventTarget,
1863
    type: topLevelType
1864
  };
1865
}
1866
1867
function responderEventTypesContainType(eventTypes, type) {
1868
  for (var i = 0, len = eventTypes.length; i < len; i++) {
1869
    if (eventTypes[i] === type) {
1870
      return true;
1871
    }
1872
  }
1873
1874
  return false;
1875
}
1876
1877
function validateResponderTargetEventTypes(eventType, responder) {
1878
  var targetEventTypes = responder.targetEventTypes; // Validate the target event type exists on the responder
1879
1880
  if (targetEventTypes !== null) {
1881
    return responderEventTypesContainType(targetEventTypes, eventType);
1882
  }
1883
1884
  return false;
1885
}
1886
1887
function traverseAndHandleEventResponderInstances(topLevelType, targetFiber, nativeEvent, nativeEventTarget, eventSystemFlags) {
1888
  var isPassiveEvent = (eventSystemFlags & IS_PASSIVE) !== 0;
1889
  var isPassiveSupported = (eventSystemFlags & PASSIVE_NOT_SUPPORTED) === 0;
1890
  var isPassive = isPassiveEvent || !isPassiveSupported;
1891
  var eventType = isPassive ? topLevelType : topLevelType + '_active'; // Trigger event responders in this order:
1892
  // - Bubble target responder phase
1893
  // - Root responder phase
1894
1895
  var visitedResponders = new Set();
1896
  var responderEvent = createDOMResponderEvent(topLevelType, nativeEvent, nativeEventTarget, isPassiveEvent, isPassiveSupported);
1897
  var node = targetFiber;
1898
  var insidePortal = false;
1899
1900
  while (node !== null) {
1901
    var _node = node,
1902
        dependencies = _node.dependencies,
1903
        tag = _node.tag;
1904
1905
    if (tag === HostPortal) {
1906
      insidePortal = true;
1907
    } else if ((tag === HostComponent || tag === ScopeComponent) && dependencies !== null) {
1908
      var respondersMap = dependencies.responders;
1909
1910
      if (respondersMap !== null) {
1911
        var responderInstances = Array.from(respondersMap.values());
1912
1913
        for (var i = 0, length = responderInstances.length; i < length; i++) {
1914
          var responderInstance = responderInstances[i];
1915
          var props = responderInstance.props,
1916
              responder = responderInstance.responder,
1917
              state = responderInstance.state;
1918
1919
          if (!visitedResponders.has(responder) && validateResponderTargetEventTypes(eventType, responder) && (!insidePortal || responder.targetPortalPropagation)) {
1920
            visitedResponders.add(responder);
1921
            var onEvent = responder.onEvent;
1922
1923
            if (onEvent !== null) {
1924
              currentInstance = responderInstance;
1925
              onEvent(responderEvent, eventResponderContext, props, state);
1926
1927
              if (currentPropagationBehavior === PropagateToNextResponder) {
1928
                visitedResponders.delete(responder);
1929
                currentPropagationBehavior = DoNotPropagateToNextResponder;
1930
              }
1931
            }
1932
          }
1933
        }
1934
      }
1935
    }
1936
1937
    node = node.return;
1938
  } // Root phase
1939
1940
1941
  var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get(eventType);
1942
1943
  if (rootEventResponderInstances !== undefined) {
1944
    var _responderInstances = Array.from(rootEventResponderInstances);
1945
1946
    for (var _i = 0; _i < _responderInstances.length; _i++) {
1947
      var _responderInstance = _responderInstances[_i];
1948
      var props = _responderInstance.props,
1949
          responder = _responderInstance.responder,
1950
          state = _responderInstance.state;
1951
      var onRootEvent = responder.onRootEvent;
1952
1953
      if (onRootEvent !== null) {
1954
        currentInstance = _responderInstance;
1955
        onRootEvent(responderEvent, eventResponderContext, props, state);
1956
      }
1957
    }
1958
  }
1959
}
1960
1961
function mountEventResponder(responder, responderInstance, props, state) {
1962
  var onMount = responder.onMount;
1963
1964
  if (onMount !== null) {
1965
    var previousInstance = currentInstance;
1966
    var previousTimers = currentTimers;
1967
    currentInstance = responderInstance;
1968
1969
    try {
1970
      batchedEventUpdates(function () {
1971
        onMount(eventResponderContext, props, state);
1972
      });
1973
    } finally {
1974
      currentInstance = previousInstance;
1975
      currentTimers = previousTimers;
1976
    }
1977
  }
1978
}
1979
function unmountEventResponder(responderInstance) {
1980
  var responder = responderInstance.responder;
1981
  var onUnmount = responder.onUnmount;
1982
1983
  if (onUnmount !== null) {
1984
    var props = responderInstance.props,
1985
        state = responderInstance.state;
1986
    var previousInstance = currentInstance;
1987
    var previousTimers = currentTimers;
1988
    currentInstance = responderInstance;
1989
1990
    try {
1991
      batchedEventUpdates(function () {
1992
        onUnmount(eventResponderContext, props, state);
1993
      });
1994
    } finally {
1995
      currentInstance = previousInstance;
1996
      currentTimers = previousTimers;
1997
    }
1998
  }
1999
2000
  var rootEventTypesSet = responderInstance.rootEventTypes;
2001
2002
  if (rootEventTypesSet !== null) {
2003
    var rootEventTypes = Array.from(rootEventTypesSet);
2004
2005
    for (var i = 0; i < rootEventTypes.length; i++) {
2006
      var topLevelEventType = rootEventTypes[i];
2007
      var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get(topLevelEventType);
2008
2009
      if (rootEventResponderInstances !== undefined) {
2010
        rootEventResponderInstances.delete(responderInstance);
2011
      }
2012
    }
2013
  }
2014
}
2015
2016
function validateResponderContext() {
2017
  (function () {
2018
    if (!(currentInstance !== null)) {
2019
      {
2020
        throw ReactError(Error("An event responder context was used outside of an event cycle. Use context.setTimeout() to use asynchronous responder context outside of event cycle ."));
2021
      }
2022
    }
2023
  })();
2024
}
2025
2026
function dispatchEventForResponderEventSystem(topLevelType, targetFiber, nativeEvent, nativeEventTarget, eventSystemFlags) {
2027
  if (enableFlareAPI) {
2028
    var previousInstance = currentInstance;
2029
    var previousTimers = currentTimers;
2030
    var previousTimeStamp = currentTimeStamp;
2031
    var previousDocument = currentDocument;
2032
    var previousPropagationBehavior = currentPropagationBehavior;
2033
    currentPropagationBehavior = DoNotPropagateToNextResponder;
2034
    currentTimers = null; // nodeType 9 is DOCUMENT_NODE
2035
2036
    currentDocument = nativeEventTarget.nodeType === 9 ? nativeEventTarget : nativeEventTarget.ownerDocument; // We might want to control timeStamp another way here
2037
2038
    currentTimeStamp = nativeEvent.timeStamp;
2039
2040
    try {
2041
      batchedEventUpdates(function () {
2042
        traverseAndHandleEventResponderInstances(topLevelType, targetFiber, nativeEvent, nativeEventTarget, eventSystemFlags);
2043
      });
2044
    } finally {
2045
      currentTimers = previousTimers;
2046
      currentInstance = previousInstance;
2047
      currentTimeStamp = previousTimeStamp;
2048
      currentDocument = previousDocument;
2049
      currentPropagationBehavior = previousPropagationBehavior;
2050
    }
2051
  }
2052
}
2053
function addRootEventTypesForResponderInstance(responderInstance, rootEventTypes) {
2054
  for (var i = 0; i < rootEventTypes.length; i++) {
2055
    var rootEventType = rootEventTypes[i];
2056
    registerRootEventType(rootEventType, responderInstance);
2057
  }
2058
}
2059
2060
function registerRootEventType(rootEventType, eventResponderInstance) {
2061
  var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get(rootEventType);
2062
2063
  if (rootEventResponderInstances === undefined) {
2064
    rootEventResponderInstances = new Set();
2065
    rootEventTypesToEventResponderInstances.set(rootEventType, rootEventResponderInstances);
2066
  }
2067
2068
  var rootEventTypesSet = eventResponderInstance.rootEventTypes;
2069
2070
  if (rootEventTypesSet === null) {
2071
    rootEventTypesSet = eventResponderInstance.rootEventTypes = new Set();
2072
  }
2073
2074
  (function () {
2075
    if (!!rootEventTypesSet.has(rootEventType)) {
2076
      {
2077
        throw ReactError(Error("addRootEventTypes() found a duplicate root event type of \"" + rootEventType + "\". This might be because the event type exists in the event responder \"rootEventTypes\" array or because of a previous addRootEventTypes() using this root event type."));
2078
      }
2079
    }
2080
  })();
2081
2082
  rootEventTypesSet.add(rootEventType);
2083
  rootEventResponderInstances.add(eventResponderInstance);
2084
}
2085
2086
// A reserved attribute.
2087
// It is handled by React separately and shouldn't be written to the DOM.
2088
var RESERVED = 0; // A simple string attribute.
2089
// Attributes that aren't in the whitelist are presumed to have this type.
2090
2091
var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
2092
// "enumerated" attributes with "true" and "false" as possible values.
2093
// When true, it should be set to a "true" string.
2094
// When false, it should be set to a "false" string.
2095
2096
var BOOLEANISH_STRING = 2; // A real boolean attribute.
2097
// When true, it should be present (set either to an empty string or its name).
2098
// When false, it should be omitted.
2099
2100
var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
2101
// When true, it should be present (set either to an empty string or its name).
2102
// When false, it should be omitted.
2103
// For any other value, should be present with that value.
2104
2105
var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
2106
// When falsy, it should be removed.
2107
2108
var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
2109
// When falsy, it should be removed.
2110
2111
var POSITIVE_NUMERIC = 6;
2112
2113
/* eslint-disable max-len */
2114
var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
2115
/* eslint-enable max-len */
2116
2117
var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
2118
2119
var ROOT_ATTRIBUTE_NAME = 'data-reactroot';
2120
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
2121
var hasOwnProperty = Object.prototype.hasOwnProperty;
2122
var illegalAttributeNameCache = {};
2123
var validatedAttributeNameCache = {};
2124
function isAttributeNameSafe(attributeName) {
2125
  if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
2126
    return true;
2127
  }
2128
2129
  if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
2130
    return false;
2131
  }
2132
2133
  if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
2134
    validatedAttributeNameCache[attributeName] = true;
2135
    return true;
2136
  }
2137
2138
  illegalAttributeNameCache[attributeName] = true;
2139
2140
  {
2141
    warning$1(false, 'Invalid attribute name: `%s`', attributeName);
2142
  }
2143
2144
  return false;
2145
}
2146
function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
2147
  if (propertyInfo !== null) {
2148
    return propertyInfo.type === RESERVED;
2149
  }
2150
2151
  if (isCustomComponentTag) {
2152
    return false;
2153
  }
2154
2155
  if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
2156
    return true;
2157
  }
2158
2159
  return false;
2160
}
2161
function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
2162
  if (propertyInfo !== null && propertyInfo.type === RESERVED) {
2163
    return false;
2164
  }
2165
2166
  switch (typeof value) {
2167
    case 'function': // $FlowIssue symbol is perfectly valid here
2168
2169
    case 'symbol':
2170
      // eslint-disable-line
2171
      return true;
2172
2173
    case 'boolean':
2174
      {
2175
        if (isCustomComponentTag) {
2176
          return false;
2177
        }
2178
2179
        if (propertyInfo !== null) {
2180
          return !propertyInfo.acceptsBooleans;
2181
        } else {
2182
          var prefix = name.toLowerCase().slice(0, 5);
2183
          return prefix !== 'data-' && prefix !== 'aria-';
2184
        }
2185
      }
2186
2187
    default:
2188
      return false;
2189
  }
2190
}
2191
function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
2192
  if (value === null || typeof value === 'undefined') {
2193
    return true;
2194
  }
2195
2196
  if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
2197
    return true;
2198
  }
2199
2200
  if (isCustomComponentTag) {
2201
    return false;
2202
  }
2203
2204
  if (propertyInfo !== null) {
2205
    switch (propertyInfo.type) {
2206
      case BOOLEAN:
2207
        return !value;
2208
2209
      case OVERLOADED_BOOLEAN:
2210
        return value === false;
2211
2212
      case NUMERIC:
2213
        return isNaN(value);
2214
2215
      case POSITIVE_NUMERIC:
2216
        return isNaN(value) || value < 1;
2217
    }
2218
  }
2219
2220
  return false;
2221
}
2222
function getPropertyInfo(name) {
2223
  return properties.hasOwnProperty(name) ? properties[name] : null;
2224
}
2225
2226
function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL) {
2227
  this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
2228
  this.attributeName = attributeName;
2229
  this.attributeNamespace = attributeNamespace;
2230
  this.mustUseProperty = mustUseProperty;
2231
  this.propertyName = name;
2232
  this.type = type;
2233
  this.sanitizeURL = sanitizeURL;
2234
} // When adding attributes to this list, be sure to also add them to
2235
// the `possibleStandardNames` module to ensure casing and incorrect
2236
// name warnings.
2237
2238
2239
var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.
2240
2241
['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
2242
// elements (not just inputs). Now that ReactDOMInput assigns to the
2243
// defaultValue property -- do we need this?
2244
'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'].forEach(function (name) {
2245
  properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
2246
  name, // attributeName
2247
  null, // attributeNamespace
2248
  false);
2249
}); // A few React string attributes have a different name.
2250
// This is a mapping from React prop names to the attribute names.
2251
2252
[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
2253
  var name = _ref[0],
2254
      attributeName = _ref[1];
2255
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2256
  attributeName, // attributeName
2257
  null, // attributeNamespace
2258
  false);
2259
}); // These are "enumerated" HTML attributes that accept "true" and "false".
2260
// In React, we let users pass `true` and `false` even though technically
2261
// these aren't boolean attributes (they are coerced to strings).
2262
2263
['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
2264
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2265
  name.toLowerCase(), // attributeName
2266
  null, // attributeNamespace
2267
  false);
2268
}); // These are "enumerated" SVG attributes that accept "true" and "false".
2269
// In React, we let users pass `true` and `false` even though technically
2270
// these aren't boolean attributes (they are coerced to strings).
2271
// Since these are SVG attributes, their attribute names are case-sensitive.
2272
2273
['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
2274
  properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2275
  name, // attributeName
2276
  null, // attributeNamespace
2277
  false);
2278
}); // These are HTML boolean attributes.
2279
2280
['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
2281
// on the client side because the browsers are inconsistent. Instead we call focus().
2282
'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
2283
'itemScope'].forEach(function (name) {
2284
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
2285
  name.toLowerCase(), // attributeName
2286
  null, // attributeNamespace
2287
  false);
2288
}); // These are the few React props that we set as DOM properties
2289
// rather than attributes. These are all booleans.
2290
2291
['checked', // Note: `option.selected` is not updated if `select.multiple` is
2292
// disabled with `removeAttribute`. We have special logic for handling this.
2293
'multiple', 'muted', 'selected'].forEach(function (name) {
2294
  properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
2295
  name, // attributeName
2296
  null, // attributeNamespace
2297
  false);
2298
}); // These are HTML attributes that are "overloaded booleans": they behave like
2299
// booleans, but can also accept a string value.
2300
2301
['capture', 'download'].forEach(function (name) {
2302
  properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
2303
  name, // attributeName
2304
  null, // attributeNamespace
2305
  false);
2306
}); // These are HTML attributes that must be positive numbers.
2307
2308
['cols', 'rows', 'size', 'span'].forEach(function (name) {
2309
  properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
2310
  name, // attributeName
2311
  null, // attributeNamespace
2312
  false);
2313
}); // These are HTML attributes that must be numbers.
2314
2315
['rowSpan', 'start'].forEach(function (name) {
2316
  properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
2317
  name.toLowerCase(), // attributeName
2318
  null, // attributeNamespace
2319
  false);
2320
});
2321
var CAMELIZE = /[\-\:]([a-z])/g;
2322
2323
var capitalize = function (token) {
2324
  return token[1].toUpperCase();
2325
}; // This is a list of all SVG attributes that need special casing, namespacing,
2326
// or boolean value assignment. Regular attributes that just accept strings
2327
// and have the same names are omitted, just like in the HTML whitelist.
2328
// Some of these attributes can be hard to find. This list was created by
2329
// scrapping the MDN documentation.
2330
2331
2332
['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height'].forEach(function (attributeName) {
2333
  var name = attributeName.replace(CAMELIZE, capitalize);
2334
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2335
  attributeName, null, // attributeNamespace
2336
  false);
2337
}); // String SVG attributes with the xlink namespace.
2338
2339
['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type'].forEach(function (attributeName) {
2340
  var name = attributeName.replace(CAMELIZE, capitalize);
2341
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2342
  attributeName, 'http://www.w3.org/1999/xlink', false);
2343
}); // String SVG attributes with the xml namespace.
2344
2345
['xml:base', 'xml:lang', 'xml:space'].forEach(function (attributeName) {
2346
  var name = attributeName.replace(CAMELIZE, capitalize);
2347
  properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2348
  attributeName, 'http://www.w3.org/XML/1998/namespace', false);
2349
}); // These attribute exists both in HTML and SVG.
2350
// The attribute name is case-sensitive in SVG so we can't just use
2351
// the React name like we do for attributes that exist only in HTML.
2352
2353
['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
2354
  properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
2355
  attributeName.toLowerCase(), // attributeName
2356
  null, // attributeNamespace
2357
  false);
2358
}); // These attributes accept URLs. These must not allow javascript: URLS.
2359
// These will also need to accept Trusted Types object in the future.
2360
2361
var xlinkHref = 'xlinkHref';
2362
properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
2363
'xlink:href', 'http://www.w3.org/1999/xlink', true);
2364
['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
2365
  properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
2366
  attributeName.toLowerCase(), // attributeName
2367
  null, // attributeNamespace
2368
  true);
2369
});
2370
2371
var ReactDebugCurrentFrame$1 = null;
2372
2373
{
2374
  ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
2375
} // A javascript: URL can contain leading C0 control or \u0020 SPACE,
2376
// and any newline or tab are filtered out as if they're not part of the URL.
2377
// https://url.spec.whatwg.org/#url-parsing
2378
// Tab or newline are defined as \r\n\t:
2379
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
2380
// A C0 control is a code point in the range \u0000 NULL to \u001F
2381
// INFORMATION SEPARATOR ONE, inclusive:
2382
// https://infra.spec.whatwg.org/#c0-control-or-space
2383
2384
/* eslint-disable max-len */
2385
2386
2387
var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
2388
var didWarn = false;
2389
2390
function sanitizeURL(url) {
2391
  if (disableJavaScriptURLs) {
2392
    (function () {
2393
      if (!!isJavaScriptProtocol.test(url)) {
2394
        {
2395
          throw ReactError(Error("React has blocked a javascript: URL as a security precaution." + (ReactDebugCurrentFrame$1.getStackAddendum())));
2396
        }
2397
      }
2398
    })();
2399
  } else if (true && !didWarn && isJavaScriptProtocol.test(url)) {
2400
    didWarn = true;
2401
    warning$1(false, 'A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
2402
  }
2403
}
2404
2405
// Flow does not allow string concatenation of most non-string types. To work
2406
// around this limitation, we use an opaque type that can only be obtained by
2407
// passing the value through getToStringValue first.
2408
function toString(value) {
2409
  return '' + value;
2410
}
2411
function getToStringValue(value) {
2412
  switch (typeof value) {
2413
    case 'boolean':
2414
    case 'number':
2415
    case 'object':
2416
    case 'string':
2417
    case 'undefined':
2418
      return value;
2419
2420
    default:
2421
      // function, symbol are assigned as empty strings
2422
      return '';
2423
  }
2424
}
2425
/** Trusted value is a wrapper for "safe" values which can be assigned to DOM execution sinks. */
2426
2427
/**
2428
 * We allow passing objects with toString method as element attributes or in dangerouslySetInnerHTML
2429
 * and we do validations that the value is safe. Once we do validation we want to use the validated
2430
 * value instead of the object (because object.toString may return something else on next call).
2431
 *
2432
 * If application uses Trusted Types we don't stringify trusted values, but preserve them as objects.
2433
 */
2434
var toStringOrTrustedType = toString;
2435
2436
if (enableTrustedTypesIntegration && typeof trustedTypes !== 'undefined') {
2437
  var isHTML = trustedTypes.isHTML;
2438
  var isScript = trustedTypes.isScript;
2439
  var isScriptURL = trustedTypes.isScriptURL; // TrustedURLs are deprecated and will be removed soon: https://github.com/WICG/trusted-types/pull/204
2440
2441
  var isURL = trustedTypes.isURL ? trustedTypes.isURL : function (value) {
2442
    return false;
2443
  };
2444
2445
  toStringOrTrustedType = function (value) {
2446
    if (typeof value === 'object' && (isHTML(value) || isScript(value) || isScriptURL(value) || isURL(value))) {
2447
      // Pass Trusted Types through.
2448
      return value;
2449
    }
2450
2451
    return toString(value);
2452
  };
2453
}
2454
2455
/**
2456
 * Set attribute for a node. The attribute value can be either string or
2457
 * Trusted value (if application uses Trusted Types).
2458
 */
2459
function setAttribute(node, attributeName, attributeValue) {
2460
  node.setAttribute(attributeName, attributeValue);
2461
}
2462
/**
2463
 * Set attribute with namespace for a node. The attribute value can be either string or
2464
 * Trusted value (if application uses Trusted Types).
2465
 */
2466
2467
function setAttributeNS(node, attributeNamespace, attributeName, attributeValue) {
2468
  node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
2469
}
2470
2471
/**
2472
 * Get the value for a property on a node. Only used in DEV for SSR validation.
2473
 * The "expected" argument is used as a hint of what the expected value is.
2474
 * Some properties have multiple equivalent values.
2475
 */
2476
function getValueForProperty(node, name, expected, propertyInfo) {
2477
  {
2478
    if (propertyInfo.mustUseProperty) {
2479
      var propertyName = propertyInfo.propertyName;
2480
      return node[propertyName];
2481
    } else {
2482
      if (!disableJavaScriptURLs && propertyInfo.sanitizeURL) {
2483
        // If we haven't fully disabled javascript: URLs, and if
2484
        // the hydration is successful of a javascript: URL, we
2485
        // still want to warn on the client.
2486
        sanitizeURL('' + expected);
2487
      }
2488
2489
      var attributeName = propertyInfo.attributeName;
2490
      var stringValue = null;
2491
2492
      if (propertyInfo.type === OVERLOADED_BOOLEAN) {
2493
        if (node.hasAttribute(attributeName)) {
2494
          var value = node.getAttribute(attributeName);
2495
2496
          if (value === '') {
2497
            return true;
2498
          }
2499
2500
          if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2501
            return value;
2502
          }
2503
2504
          if (value === '' + expected) {
2505
            return expected;
2506
          }
2507
2508
          return value;
2509
        }
2510
      } else if (node.hasAttribute(attributeName)) {
2511
        if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2512
          // We had an attribute but shouldn't have had one, so read it
2513
          // for the error message.
2514
          return node.getAttribute(attributeName);
2515
        }
2516
2517
        if (propertyInfo.type === BOOLEAN) {
2518
          // If this was a boolean, it doesn't matter what the value is
2519
          // the fact that we have it is the same as the expected.
2520
          return expected;
2521
        } // Even if this property uses a namespace we use getAttribute
2522
        // because we assume its namespaced name is the same as our config.
2523
        // To use getAttributeNS we need the local name which we don't have
2524
        // in our config atm.
2525
2526
2527
        stringValue = node.getAttribute(attributeName);
2528
      }
2529
2530
      if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2531
        return stringValue === null ? expected : stringValue;
2532
      } else if (stringValue === '' + expected) {
2533
        return expected;
2534
      } else {
2535
        return stringValue;
2536
      }
2537
    }
2538
  }
2539
}
2540
/**
2541
 * Get the value for a attribute on a node. Only used in DEV for SSR validation.
2542
 * The third argument is used as a hint of what the expected value is. Some
2543
 * attributes have multiple equivalent values.
2544
 */
2545
2546
function getValueForAttribute(node, name, expected) {
2547
  {
2548
    if (!isAttributeNameSafe(name)) {
2549
      return;
2550
    }
2551
2552
    if (!node.hasAttribute(name)) {
2553
      return expected === undefined ? undefined : null;
2554
    }
2555
2556
    var value = node.getAttribute(name);
2557
2558
    if (value === '' + expected) {
2559
      return expected;
2560
    }
2561
2562
    return value;
2563
  }
2564
}
2565
/**
2566
 * Sets the value for a property on a node.
2567
 *
2568
 * @param {DOMElement} node
2569
 * @param {string} name
2570
 * @param {*} value
2571
 */
2572
2573
function setValueForProperty(node, name, value, isCustomComponentTag) {
2574
  var propertyInfo = getPropertyInfo(name);
2575
2576
  if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
2577
    return;
2578
  }
2579
2580
  if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
2581
    value = null;
2582
  } // If the prop isn't in the special list, treat it as a simple attribute.
2583
2584
2585
  if (isCustomComponentTag || propertyInfo === null) {
2586
    if (isAttributeNameSafe(name)) {
2587
      var _attributeName = name;
2588
2589
      if (value === null) {
2590
        node.removeAttribute(_attributeName);
2591
      } else {
2592
        setAttribute(node, _attributeName, toStringOrTrustedType(value));
2593
      }
2594
    }
2595
2596
    return;
2597
  }
2598
2599
  var mustUseProperty = propertyInfo.mustUseProperty;
2600
2601
  if (mustUseProperty) {
2602
    var propertyName = propertyInfo.propertyName;
2603
2604
    if (value === null) {
2605
      var type = propertyInfo.type;
2606
      node[propertyName] = type === BOOLEAN ? false : '';
2607
    } else {
2608
      // Contrary to `setAttribute`, object properties are properly
2609
      // `toString`ed by IE8/9.
2610
      node[propertyName] = value;
2611
    }
2612
2613
    return;
2614
  } // The rest are treated as attributes with special cases.
2615
2616
2617
  var attributeName = propertyInfo.attributeName,
2618
      attributeNamespace = propertyInfo.attributeNamespace;
2619
2620
  if (value === null) {
2621
    node.removeAttribute(attributeName);
2622
  } else {
2623
    var _type = propertyInfo.type;
2624
    var attributeValue;
2625
2626
    if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
2627
      // If attribute type is boolean, we know for sure it won't be an execution sink
2628
      // and we won't require Trusted Type here.
2629
      attributeValue = '';
2630
    } else {
2631
      // `setAttribute` with objects becomes only `[object]` in IE8/9,
2632
      // ('' + value) makes it output the correct toString()-value.
2633
      attributeValue = toStringOrTrustedType(value);
2634
2635
      if (propertyInfo.sanitizeURL) {
2636
        sanitizeURL(attributeValue.toString());
2637
      }
2638
    }
2639
2640
    if (attributeNamespace) {
2641
      setAttributeNS(node, attributeNamespace, attributeName, attributeValue);
2642
    } else {
2643
      setAttribute(node, attributeName, attributeValue);
2644
    }
2645
  }
2646
}
2647
2648
var ReactDebugCurrentFrame$2 = null;
2649
var ReactControlledValuePropTypes = {
2650
  checkPropTypes: null
2651
};
2652
2653
{
2654
  ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame;
2655
  var hasReadOnlyValue = {
2656
    button: true,
2657
    checkbox: true,
2658
    image: true,
2659
    hidden: true,
2660
    radio: true,
2661
    reset: true,
2662
    submit: true
2663
  };
2664
  var propTypes = {
2665
    value: function (props, propName, componentName) {
2666
      if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null || enableFlareAPI && props.listeners) {
2667
        return null;
2668
      }
2669
2670
      return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
2671
    },
2672
    checked: function (props, propName, componentName) {
2673
      if (props.onChange || props.readOnly || props.disabled || props[propName] == null || enableFlareAPI && props.listeners) {
2674
        return null;
2675
      }
2676
2677
      return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
2678
    }
2679
  };
2680
  /**
2681
   * Provide a linked `value` attribute for controlled forms. You should not use
2682
   * this outside of the ReactDOM controlled form components.
2683
   */
2684
2685
  ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) {
2686
    checkPropTypes(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$2.getStackAddendum);
2687
  };
2688
}
2689
2690
function isCheckable(elem) {
2691
  var type = elem.type;
2692
  var nodeName = elem.nodeName;
2693
  return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
2694
}
2695
2696
function getTracker(node) {
2697
  return node._valueTracker;
2698
}
2699
2700
function detachTracker(node) {
2701
  node._valueTracker = null;
2702
}
2703
2704
function getValueFromNode(node) {
2705
  var value = '';
2706
2707
  if (!node) {
2708
    return value;
2709
  }
2710
2711
  if (isCheckable(node)) {
2712
    value = node.checked ? 'true' : 'false';
2713
  } else {
2714
    value = node.value;
2715
  }
2716
2717
  return value;
2718
}
2719
2720
function trackValueOnNode(node) {
2721
  var valueField = isCheckable(node) ? 'checked' : 'value';
2722
  var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
2723
  var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail
2724
  // and don't track value will cause over reporting of changes,
2725
  // but it's better then a hard failure
2726
  // (needed for certain tests that spyOn input values and Safari)
2727
2728
  if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
2729
    return;
2730
  }
2731
2732
  var get = descriptor.get,
2733
      set = descriptor.set;
2734
  Object.defineProperty(node, valueField, {
2735
    configurable: true,
2736
    get: function () {
2737
      return get.call(this);
2738
    },
2739
    set: function (value) {
2740
      currentValue = '' + value;
2741
      set.call(this, value);
2742
    }
2743
  }); // We could've passed this the first time
2744
  // but it triggers a bug in IE11 and Edge 14/15.
2745
  // Calling defineProperty() again should be equivalent.
2746
  // https://github.com/facebook/react/issues/11768
2747
2748
  Object.defineProperty(node, valueField, {
2749
    enumerable: descriptor.enumerable
2750
  });
2751
  var tracker = {
2752
    getValue: function () {
2753
      return currentValue;
2754
    },
2755
    setValue: function (value) {
2756
      currentValue = '' + value;
2757
    },
2758
    stopTracking: function () {
2759
      detachTracker(node);
2760
      delete node[valueField];
2761
    }
2762
  };
2763
  return tracker;
2764
}
2765
2766
function track(node) {
2767
  if (getTracker(node)) {
2768
    return;
2769
  } // TODO: Once it's just Fiber we can move this to node._wrapperState
2770
2771
2772
  node._valueTracker = trackValueOnNode(node);
2773
}
2774
function updateValueIfChanged(node) {
2775
  if (!node) {
2776
    return false;
2777
  }
2778
2779
  var tracker = getTracker(node); // if there is no tracker at this point it's unlikely
2780
  // that trying again will succeed
2781
2782
  if (!tracker) {
2783
    return true;
2784
  }
2785
2786
  var lastValue = tracker.getValue();
2787
  var nextValue = getValueFromNode(node);
2788
2789
  if (nextValue !== lastValue) {
2790
    tracker.setValue(nextValue);
2791
    return true;
2792
  }
2793
2794
  return false;
2795
}
2796
2797
// TODO: direct imports like some-package/src/* are bad. Fix me.
2798
var didWarnValueDefaultValue = false;
2799
var didWarnCheckedDefaultChecked = false;
2800
var didWarnControlledToUncontrolled = false;
2801
var didWarnUncontrolledToControlled = false;
2802
2803
function isControlled(props) {
2804
  var usesChecked = props.type === 'checkbox' || props.type === 'radio';
2805
  return usesChecked ? props.checked != null : props.value != null;
2806
}
2807
/**
2808
 * Implements an <input> host component that allows setting these optional
2809
 * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
2810
 *
2811
 * If `checked` or `value` are not supplied (or null/undefined), user actions
2812
 * that affect the checked state or value will trigger updates to the element.
2813
 *
2814
 * If they are supplied (and not null/undefined), the rendered element will not
2815
 * trigger updates to the element. Instead, the props must change in order for
2816
 * the rendered element to be updated.
2817
 *
2818
 * The rendered element will be initialized as unchecked (or `defaultChecked`)
2819
 * with an empty value (or `defaultValue`).
2820
 *
2821
 * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
2822
 */
2823
2824
2825
function getHostProps(element, props) {
2826
  var node = element;
2827
  var checked = props.checked;
2828
2829
  var hostProps = _assign({}, props, {
2830
    defaultChecked: undefined,
2831
    defaultValue: undefined,
2832
    value: undefined,
2833
    checked: checked != null ? checked : node._wrapperState.initialChecked
2834
  });
2835
2836
  return hostProps;
2837
}
2838
function initWrapperState(element, props) {
2839
  {
2840
    ReactControlledValuePropTypes.checkPropTypes('input', props);
2841
2842
    if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
2843
      warning$1(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);
2844
      didWarnCheckedDefaultChecked = true;
2845
    }
2846
2847
    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
2848
      warning$1(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);
2849
      didWarnValueDefaultValue = true;
2850
    }
2851
  }
2852
2853
  var node = element;
2854
  var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
2855
  node._wrapperState = {
2856
    initialChecked: props.checked != null ? props.checked : props.defaultChecked,
2857
    initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
2858
    controlled: isControlled(props)
2859
  };
2860
}
2861
function updateChecked(element, props) {
2862
  var node = element;
2863
  var checked = props.checked;
2864
2865
  if (checked != null) {
2866
    setValueForProperty(node, 'checked', checked, false);
2867
  }
2868
}
2869
function updateWrapper(element, props) {
2870
  var node = element;
2871
2872
  {
2873
    var controlled = isControlled(props);
2874
2875
    if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
2876
      warning$1(false, 'A component is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type);
2877
      didWarnUncontrolledToControlled = true;
2878
    }
2879
2880
    if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
2881
      warning$1(false, 'A component is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type);
2882
      didWarnControlledToUncontrolled = true;
2883
    }
2884
  }
2885
2886
  updateChecked(element, props);
2887
  var value = getToStringValue(props.value);
2888
  var type = props.type;
2889
2890
  if (value != null) {
2891
    if (type === 'number') {
2892
      if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible.
2893
      // eslint-disable-next-line
2894
      node.value != value) {
2895
        node.value = toString(value);
2896
      }
2897
    } else if (node.value !== toString(value)) {
2898
      node.value = toString(value);
2899
    }
2900
  } else if (type === 'submit' || type === 'reset') {
2901
    // Submit/reset inputs need the attribute removed completely to avoid
2902
    // blank-text buttons.
2903
    node.removeAttribute('value');
2904
    return;
2905
  }
2906
2907
  if (disableInputAttributeSyncing) {
2908
    // When not syncing the value attribute, React only assigns a new value
2909
    // whenever the defaultValue React prop has changed. When not present,
2910
    // React does nothing
2911
    if (props.hasOwnProperty('defaultValue')) {
2912
      setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
2913
    }
2914
  } else {
2915
    // When syncing the value attribute, the value comes from a cascade of
2916
    // properties:
2917
    //  1. The value React property
2918
    //  2. The defaultValue React property
2919
    //  3. Otherwise there should be no change
2920
    if (props.hasOwnProperty('value')) {
2921
      setDefaultValue(node, props.type, value);
2922
    } else if (props.hasOwnProperty('defaultValue')) {
2923
      setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
2924
    }
2925
  }
2926
2927
  if (disableInputAttributeSyncing) {
2928
    // When not syncing the checked attribute, the attribute is directly
2929
    // controllable from the defaultValue React property. It needs to be
2930
    // updated as new props come in.
2931
    if (props.defaultChecked == null) {
2932
      node.removeAttribute('checked');
2933
    } else {
2934
      node.defaultChecked = !!props.defaultChecked;
2935
    }
2936
  } else {
2937
    // When syncing the checked attribute, it only changes when it needs
2938
    // to be removed, such as transitioning from a checkbox into a text input
2939
    if (props.checked == null && props.defaultChecked != null) {
2940
      node.defaultChecked = !!props.defaultChecked;
2941
    }
2942
  }
2943
}
2944
function postMountWrapper(element, props, isHydrating) {
2945
  var node = element; // Do not assign value if it is already set. This prevents user text input
2946
  // from being lost during SSR hydration.
2947
2948
  if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
2949
    var type = props.type;
2950
    var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the
2951
    // default value provided by the browser. See: #12872
2952
2953
    if (isButton && (props.value === undefined || props.value === null)) {
2954
      return;
2955
    }
2956
2957
    var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input
2958
    // from being lost during SSR hydration.
2959
2960
    if (!isHydrating) {
2961
      if (disableInputAttributeSyncing) {
2962
        var value = getToStringValue(props.value); // When not syncing the value attribute, the value property points
2963
        // directly to the React prop. Only assign it if it exists.
2964
2965
        if (value != null) {
2966
          // Always assign on buttons so that it is possible to assign an
2967
          // empty string to clear button text.
2968
          //
2969
          // Otherwise, do not re-assign the value property if is empty. This
2970
          // potentially avoids a DOM write and prevents Firefox (~60.0.1) from
2971
          // prematurely marking required inputs as invalid. Equality is compared
2972
          // to the current value in case the browser provided value is not an
2973
          // empty string.
2974
          if (isButton || value !== node.value) {
2975
            node.value = toString(value);
2976
          }
2977
        }
2978
      } else {
2979
        // When syncing the value attribute, the value property should use
2980
        // the wrapperState._initialValue property. This uses:
2981
        //
2982
        //   1. The value React property when present
2983
        //   2. The defaultValue React property when present
2984
        //   3. An empty string
2985
        if (initialValue !== node.value) {
2986
          node.value = initialValue;
2987
        }
2988
      }
2989
    }
2990
2991
    if (disableInputAttributeSyncing) {
2992
      // When not syncing the value attribute, assign the value attribute
2993
      // directly from the defaultValue React property (when present)
2994
      var defaultValue = getToStringValue(props.defaultValue);
2995
2996
      if (defaultValue != null) {
2997
        node.defaultValue = toString(defaultValue);
2998
      }
2999
    } else {
3000
      // Otherwise, the value attribute is synchronized to the property,
3001
      // so we assign defaultValue to the same thing as the value property
3002
      // assignment step above.
3003
      node.defaultValue = initialValue;
3004
    }
3005
  } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
3006
  // this is needed to work around a chrome bug where setting defaultChecked
3007
  // will sometimes influence the value of checked (even after detachment).
3008
  // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
3009
  // We need to temporarily unset name to avoid disrupting radio button groups.
3010
3011
3012
  var name = node.name;
3013
3014
  if (name !== '') {
3015
    node.name = '';
3016
  }
3017
3018
  if (disableInputAttributeSyncing) {
3019
    // When not syncing the checked attribute, the checked property
3020
    // never gets assigned. It must be manually set. We don't want
3021
    // to do this when hydrating so that existing user input isn't
3022
    // modified
3023
    if (!isHydrating) {
3024
      updateChecked(element, props);
3025
    } // Only assign the checked attribute if it is defined. This saves
3026
    // a DOM write when controlling the checked attribute isn't needed
3027
    // (text inputs, submit/reset)
3028
3029
3030
    if (props.hasOwnProperty('defaultChecked')) {
3031
      node.defaultChecked = !node.defaultChecked;
3032
      node.defaultChecked = !!props.defaultChecked;
3033
    }
3034
  } else {
3035
    // When syncing the checked attribute, both the checked property and
3036
    // attribute are assigned at the same time using defaultChecked. This uses:
3037
    //
3038
    //   1. The checked React property when present
3039
    //   2. The defaultChecked React property when present
3040
    //   3. Otherwise, false
3041
    node.defaultChecked = !node.defaultChecked;
3042
    node.defaultChecked = !!node._wrapperState.initialChecked;
3043
  }
3044
3045
  if (name !== '') {
3046
    node.name = name;
3047
  }
3048
}
3049
function restoreControlledState$1(element, props) {
3050
  var node = element;
3051
  updateWrapper(node, props);
3052
  updateNamedCousins(node, props);
3053
}
3054
3055
function updateNamedCousins(rootNode, props) {
3056
  var name = props.name;
3057
3058
  if (props.type === 'radio' && name != null) {
3059
    var queryRoot = rootNode;
3060
3061
    while (queryRoot.parentNode) {
3062
      queryRoot = queryRoot.parentNode;
3063
    } // If `rootNode.form` was non-null, then we could try `form.elements`,
3064
    // but that sometimes behaves strangely in IE8. We could also try using
3065
    // `form.getElementsByName`, but that will only return direct children
3066
    // and won't include inputs that use the HTML5 `form=` attribute. Since
3067
    // the input might not even be in a form. It might not even be in the
3068
    // document. Let's just use the local `querySelectorAll` to ensure we don't
3069
    // miss anything.
3070
3071
3072
    var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
3073
3074
    for (var i = 0; i < group.length; i++) {
3075
      var otherNode = group[i];
3076
3077
      if (otherNode === rootNode || otherNode.form !== rootNode.form) {
3078
        continue;
3079
      } // This will throw if radio buttons rendered by different copies of React
3080
      // and the same name are rendered into the same form (same as #1939).
3081
      // That's probably okay; we don't support it just as we don't support
3082
      // mixing React radio buttons with non-React ones.
3083
3084
3085
      var otherProps = getFiberCurrentPropsFromNode$1(otherNode);
3086
3087
      (function () {
3088
        if (!otherProps) {
3089
          {
3090
            throw ReactError(Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."));
3091
          }
3092
        }
3093
      })(); // We need update the tracked value on the named cousin since the value
3094
      // was changed but the input saw no event or value set
3095
3096
3097
      updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that
3098
      // was previously checked to update will cause it to be come re-checked
3099
      // as appropriate.
3100
3101
      updateWrapper(otherNode, otherProps);
3102
    }
3103
  }
3104
} // In Chrome, assigning defaultValue to certain input types triggers input validation.
3105
// For number inputs, the display value loses trailing decimal points. For email inputs,
3106
// Chrome raises "The specified value <x> is not a valid email address".
3107
//
3108
// Here we check to see if the defaultValue has actually changed, avoiding these problems
3109
// when the user is inputting text
3110
//
3111
// https://github.com/facebook/react/issues/7253
3112
3113
3114
function setDefaultValue(node, type, value) {
3115
  if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
3116
  type !== 'number' || node.ownerDocument.activeElement !== node) {
3117
    if (value == null) {
3118
      node.defaultValue = toString(node._wrapperState.initialValue);
3119
    } else if (node.defaultValue !== toString(value)) {
3120
      node.defaultValue = toString(value);
3121
    }
3122
  }
3123
}
3124
3125
var didWarnSelectedSetOnOption = false;
3126
var didWarnInvalidChild = false;
3127
3128
function flattenChildren(children) {
3129
  var content = ''; // Flatten children. We'll warn if they are invalid
3130
  // during validateProps() which runs for hydration too.
3131
  // Note that this would throw on non-element objects.
3132
  // Elements are stringified (which is normally irrelevant
3133
  // but matters for <fbt>).
3134
3135
  React.Children.forEach(children, function (child) {
3136
    if (child == null) {
3137
      return;
3138
    }
3139
3140
    content += child; // Note: we don't warn about invalid children here.
3141
    // Instead, this is done separately below so that
3142
    // it happens during the hydration codepath too.
3143
  });
3144
  return content;
3145
}
3146
/**
3147
 * Implements an <option> host component that warns when `selected` is set.
3148
 */
3149
3150
3151
function validateProps(element, props) {
3152
  {
3153
    // This mirrors the codepath above, but runs for hydration too.
3154
    // Warn about invalid children here so that client and hydration are consistent.
3155
    // TODO: this seems like it could cause a DEV-only throw for hydration
3156
    // if children contains a non-element object. We should try to avoid that.
3157
    if (typeof props.children === 'object' && props.children !== null) {
3158
      React.Children.forEach(props.children, function (child) {
3159
        if (child == null) {
3160
          return;
3161
        }
3162
3163
        if (typeof child === 'string' || typeof child === 'number') {
3164
          return;
3165
        }
3166
3167
        if (typeof child.type !== 'string') {
3168
          return;
3169
        }
3170
3171
        if (!didWarnInvalidChild) {
3172
          didWarnInvalidChild = true;
3173
          warning$1(false, 'Only strings and numbers are supported as <option> children.');
3174
        }
3175
      });
3176
    } // TODO: Remove support for `selected` in <option>.
3177
3178
3179
    if (props.selected != null && !didWarnSelectedSetOnOption) {
3180
      warning$1(false, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
3181
      didWarnSelectedSetOnOption = true;
3182
    }
3183
  }
3184
}
3185
function postMountWrapper$1(element, props) {
3186
  // value="" should make a value attribute (#6219)
3187
  if (props.value != null) {
3188
    element.setAttribute('value', toString(getToStringValue(props.value)));
3189
  }
3190
}
3191
function getHostProps$1(element, props) {
3192
  var hostProps = _assign({
3193
    children: undefined
3194
  }, props);
3195
3196
  var content = flattenChildren(props.children);
3197
3198
  if (content) {
3199
    hostProps.children = content;
3200
  }
3201
3202
  return hostProps;
3203
}
3204
3205
// TODO: direct imports like some-package/src/* are bad. Fix me.
3206
var didWarnValueDefaultValue$1;
3207
3208
{
3209
  didWarnValueDefaultValue$1 = false;
3210
}
3211
3212
function getDeclarationErrorAddendum() {
3213
  var ownerName = getCurrentFiberOwnerNameInDevOrNull();
3214
3215
  if (ownerName) {
3216
    return '\n\nCheck the render method of `' + ownerName + '`.';
3217
  }
3218
3219
  return '';
3220
}
3221
3222
var valuePropNames = ['value', 'defaultValue'];
3223
/**
3224
 * Validation function for `value` and `defaultValue`.
3225
 */
3226
3227
function checkSelectPropTypes(props) {
3228
  ReactControlledValuePropTypes.checkPropTypes('select', props);
3229
3230
  for (var i = 0; i < valuePropNames.length; i++) {
3231
    var propName = valuePropNames[i];
3232
3233
    if (props[propName] == null) {
3234
      continue;
3235
    }
3236
3237
    var isArray = Array.isArray(props[propName]);
3238
3239
    if (props.multiple && !isArray) {
3240
      warning$1(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
3241
    } else if (!props.multiple && isArray) {
3242
      warning$1(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
3243
    }
3244
  }
3245
}
3246
3247
function updateOptions(node, multiple, propValue, setDefaultSelected) {
3248
  var options = node.options;
3249
3250
  if (multiple) {
3251
    var selectedValues = propValue;
3252
    var selectedValue = {};
3253
3254
    for (var i = 0; i < selectedValues.length; i++) {
3255
      // Prefix to avoid chaos with special keys.
3256
      selectedValue['$' + selectedValues[i]] = true;
3257
    }
3258
3259
    for (var _i = 0; _i < options.length; _i++) {
3260
      var selected = selectedValue.hasOwnProperty('$' + options[_i].value);
3261
3262
      if (options[_i].selected !== selected) {
3263
        options[_i].selected = selected;
3264
      }
3265
3266
      if (selected && setDefaultSelected) {
3267
        options[_i].defaultSelected = true;
3268
      }
3269
    }
3270
  } else {
3271
    // Do not set `select.value` as exact behavior isn't consistent across all
3272
    // browsers for all cases.
3273
    var _selectedValue = toString(getToStringValue(propValue));
3274
3275
    var defaultSelected = null;
3276
3277
    for (var _i2 = 0; _i2 < options.length; _i2++) {
3278
      if (options[_i2].value === _selectedValue) {
3279
        options[_i2].selected = true;
3280
3281
        if (setDefaultSelected) {
3282
          options[_i2].defaultSelected = true;
3283
        }
3284
3285
        return;
3286
      }
3287
3288
      if (defaultSelected === null && !options[_i2].disabled) {
3289
        defaultSelected = options[_i2];
3290
      }
3291
    }
3292
3293
    if (defaultSelected !== null) {
3294
      defaultSelected.selected = true;
3295
    }
3296
  }
3297
}
3298
/**
3299
 * Implements a <select> host component that allows optionally setting the
3300
 * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
3301
 * stringable. If `multiple` is true, the prop must be an array of stringables.
3302
 *
3303
 * If `value` is not supplied (or null/undefined), user actions that change the
3304
 * selected option will trigger updates to the rendered options.
3305
 *
3306
 * If it is supplied (and not null/undefined), the rendered options will not
3307
 * update in response to user actions. Instead, the `value` prop must change in
3308
 * order for the rendered options to update.
3309
 *
3310
 * If `defaultValue` is provided, any options with the supplied values will be
3311
 * selected.
3312
 */
3313
3314
3315
function getHostProps$2(element, props) {
3316
  return _assign({}, props, {
3317
    value: undefined
3318
  });
3319
}
3320
function initWrapperState$1(element, props) {
3321
  var node = element;
3322
3323
  {
3324
    checkSelectPropTypes(props);
3325
  }
3326
3327
  node._wrapperState = {
3328
    wasMultiple: !!props.multiple
3329
  };
3330
3331
  {
3332
    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
3333
      warning$1(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components');
3334
      didWarnValueDefaultValue$1 = true;
3335
    }
3336
  }
3337
}
3338
function postMountWrapper$2(element, props) {
3339
  var node = element;
3340
  node.multiple = !!props.multiple;
3341
  var value = props.value;
3342
3343
  if (value != null) {
3344
    updateOptions(node, !!props.multiple, value, false);
3345
  } else if (props.defaultValue != null) {
3346
    updateOptions(node, !!props.multiple, props.defaultValue, true);
3347
  }
3348
}
3349
function postUpdateWrapper(element, props) {
3350
  var node = element;
3351
  var wasMultiple = node._wrapperState.wasMultiple;
3352
  node._wrapperState.wasMultiple = !!props.multiple;
3353
  var value = props.value;
3354
3355
  if (value != null) {
3356
    updateOptions(node, !!props.multiple, value, false);
3357
  } else if (wasMultiple !== !!props.multiple) {
3358
    // For simplicity, reapply `defaultValue` if `multiple` is toggled.
3359
    if (props.defaultValue != null) {
3360
      updateOptions(node, !!props.multiple, props.defaultValue, true);
3361
    } else {
3362
      // Revert the select back to its default unselected state.
3363
      updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
3364
    }
3365
  }
3366
}
3367
function restoreControlledState$2(element, props) {
3368
  var node = element;
3369
  var value = props.value;
3370
3371
  if (value != null) {
3372
    updateOptions(node, !!props.multiple, value, false);
3373
  }
3374
}
3375
3376
var didWarnValDefaultVal = false;
3377
3378
/**
3379
 * Implements a <textarea> host component that allows setting `value`, and
3380
 * `defaultValue`. This differs from the traditional DOM API because value is
3381
 * usually set as PCDATA children.
3382
 *
3383
 * If `value` is not supplied (or null/undefined), user actions that affect the
3384
 * value will trigger updates to the element.
3385
 *
3386
 * If `value` is supplied (and not null/undefined), the rendered element will
3387
 * not trigger updates to the element. Instead, the `value` prop must change in
3388
 * order for the rendered element to be updated.
3389
 *
3390
 * The rendered element will be initialized with an empty value, the prop
3391
 * `defaultValue` if specified, or the children content (deprecated).
3392
 */
3393
function getHostProps$3(element, props) {
3394
  var node = element;
3395
3396
  (function () {
3397
    if (!(props.dangerouslySetInnerHTML == null)) {
3398
      {
3399
        throw ReactError(Error("`dangerouslySetInnerHTML` does not make sense on <textarea>."));
3400
      }
3401
    }
3402
  })(); // Always set children to the same thing. In IE9, the selection range will
3403
  // get reset if `textContent` is mutated.  We could add a check in setTextContent
3404
  // to only set the value if/when the value differs from the node value (which would
3405
  // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
3406
  // solution. The value can be a boolean or object so that's why it's forced
3407
  // to be a string.
3408
3409
3410
  var hostProps = _assign({}, props, {
3411
    value: undefined,
3412
    defaultValue: undefined,
3413
    children: toString(node._wrapperState.initialValue)
3414
  });
3415
3416
  return hostProps;
3417
}
3418
function initWrapperState$2(element, props) {
3419
  var node = element;
3420
3421
  {
3422
    ReactControlledValuePropTypes.checkPropTypes('textarea', props);
3423
3424
    if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
3425
      warning$1(false, '%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
3426
      didWarnValDefaultVal = true;
3427
    }
3428
  }
3429
3430
  var initialValue = props.value; // Only bother fetching default value if we're going to use it
3431
3432
  if (initialValue == null) {
3433
    var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>.
3434
3435
    var children = props.children;
3436
3437
    if (children != null) {
3438
      {
3439
        warning$1(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
3440
      }
3441
3442
      (function () {
3443
        if (!(defaultValue == null)) {
3444
          {
3445
            throw ReactError(Error("If you supply `defaultValue` on a <textarea>, do not pass children."));
3446
          }
3447
        }
3448
      })();
3449
3450
      if (Array.isArray(children)) {
3451
        (function () {
3452
          if (!(children.length <= 1)) {
3453
            {
3454
              throw ReactError(Error("<textarea> can only have at most one child."));
3455
            }
3456
          }
3457
        })();
3458
3459
        children = children[0];
3460
      }
3461
3462
      defaultValue = children;
3463
    }
3464
3465
    if (defaultValue == null) {
3466
      defaultValue = '';
3467
    }
3468
3469
    initialValue = defaultValue;
3470
  }
3471
3472
  node._wrapperState = {
3473
    initialValue: getToStringValue(initialValue)
3474
  };
3475
}
3476
function updateWrapper$1(element, props) {
3477
  var node = element;
3478
  var value = getToStringValue(props.value);
3479
  var defaultValue = getToStringValue(props.defaultValue);
3480
3481
  if (value != null) {
3482
    // Cast `value` to a string to ensure the value is set correctly. While
3483
    // browsers typically do this as necessary, jsdom doesn't.
3484
    var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed
3485
3486
    if (newValue !== node.value) {
3487
      node.value = newValue;
3488
    }
3489
3490
    if (props.defaultValue == null && node.defaultValue !== newValue) {
3491
      node.defaultValue = newValue;
3492
    }
3493
  }
3494
3495
  if (defaultValue != null) {
3496
    node.defaultValue = toString(defaultValue);
3497
  }
3498
}
3499
function postMountWrapper$3(element, props) {
3500
  var node = element; // This is in postMount because we need access to the DOM node, which is not
3501
  // available until after the component has mounted.
3502
3503
  var textContent = node.textContent; // Only set node.value if textContent is equal to the expected
3504
  // initial value. In IE10/IE11 there is a bug where the placeholder attribute
3505
  // will populate textContent as well.
3506
  // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
3507
3508
  if (textContent === node._wrapperState.initialValue) {
3509
    if (textContent !== '' && textContent !== null) {
3510
      node.value = textContent;
3511
    }
3512
  }
3513
}
3514
function restoreControlledState$3(element, props) {
3515
  // DOM component is still mounted; update
3516
  updateWrapper$1(element, props);
3517
}
3518
3519
var HTML_NAMESPACE$1 = 'http://www.w3.org/1999/xhtml';
3520
var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
3521
var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
3522
var Namespaces = {
3523
  html: HTML_NAMESPACE$1,
3524
  mathml: MATH_NAMESPACE,
3525
  svg: SVG_NAMESPACE
3526
}; // Assumes there is no parent namespace.
3527
3528
function getIntrinsicNamespace(type) {
3529
  switch (type) {
3530
    case 'svg':
3531
      return SVG_NAMESPACE;
3532
3533
    case 'math':
3534
      return MATH_NAMESPACE;
3535
3536
    default:
3537
      return HTML_NAMESPACE$1;
3538
  }
3539
}
3540
function getChildNamespace(parentNamespace, type) {
3541
  if (parentNamespace == null || parentNamespace === HTML_NAMESPACE$1) {
3542
    // No (or default) parent namespace: potential entry point.
3543
    return getIntrinsicNamespace(type);
3544
  }
3545
3546
  if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
3547
    // We're leaving SVG.
3548
    return HTML_NAMESPACE$1;
3549
  } // By default, pass namespace below.
3550
3551
3552
  return parentNamespace;
3553
}
3554
3555
/* globals MSApp */
3556
3557
/**
3558
 * Create a function which has 'unsafe' privileges (required by windows8 apps)
3559
 */
3560
var createMicrosoftUnsafeLocalFunction = function (func) {
3561
  if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
3562
    return function (arg0, arg1, arg2, arg3) {
3563
      MSApp.execUnsafeLocalFunction(function () {
3564
        return func(arg0, arg1, arg2, arg3);
3565
      });
3566
    };
3567
  } else {
3568
    return func;
3569
  }
3570
};
3571
3572
var reusableSVGContainer;
3573
/**
3574
 * Set the innerHTML property of a node
3575
 *
3576
 * @param {DOMElement} node
3577
 * @param {string} html
3578
 * @internal
3579
 */
3580
3581
var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
3582
  if (node.namespaceURI === Namespaces.svg) {
3583
    {
3584
      if (enableTrustedTypesIntegration) {
3585
        // TODO: reconsider the text of this warning and when it should show
3586
        // before enabling the feature flag.
3587
        !(typeof trustedTypes === 'undefined') ? warning$1(false, "Using 'dangerouslySetInnerHTML' in an svg element with " + 'Trusted Types enabled in an Internet Explorer will cause ' + 'the trusted value to be converted to string. Assigning string ' + "to 'innerHTML' will throw an error if Trusted Types are enforced. " + "You can try to wrap your svg element inside a div and use 'dangerouslySetInnerHTML' " + 'on the enclosing div instead.') : void 0;
3588
      }
3589
    }
3590
3591
    if (!('innerHTML' in node)) {
3592
      // IE does not have innerHTML for SVG nodes, so instead we inject the
3593
      // new markup in a temp node and then move the child nodes across into
3594
      // the target node
3595
      reusableSVGContainer = reusableSVGContainer || document.createElement('div');
3596
      reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>';
3597
      var svgNode = reusableSVGContainer.firstChild;
3598
3599
      while (node.firstChild) {
3600
        node.removeChild(node.firstChild);
3601
      }
3602
3603
      while (svgNode.firstChild) {
3604
        node.appendChild(svgNode.firstChild);
3605
      }
3606
3607
      return;
3608
    }
3609
  }
3610
3611
  node.innerHTML = html;
3612
});
3613
3614
/**
3615
 * HTML nodeType values that represent the type of the node
3616
 */
3617
var ELEMENT_NODE = 1;
3618
var TEXT_NODE = 3;
3619
var COMMENT_NODE = 8;
3620
var DOCUMENT_NODE = 9;
3621
var DOCUMENT_FRAGMENT_NODE = 11;
3622
3623
/**
3624
 * Set the textContent property of a node. For text updates, it's faster
3625
 * to set the `nodeValue` of the Text node directly instead of using
3626
 * `.textContent` which will remove the existing node and create a new one.
3627
 *
3628
 * @param {DOMElement} node
3629
 * @param {string} text
3630
 * @internal
3631
 */
3632
3633
var setTextContent = function (node, text) {
3634
  if (text) {
3635
    var firstChild = node.firstChild;
3636
3637
    if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
3638
      firstChild.nodeValue = text;
3639
      return;
3640
    }
3641
  }
3642
3643
  node.textContent = text;
3644
};
3645
3646
// Do not use the below two methods directly!
3647
// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.
3648
// (It is the only module that is allowed to access these methods.)
3649
function unsafeCastStringToDOMTopLevelType(topLevelType) {
3650
  return topLevelType;
3651
}
3652
function unsafeCastDOMTopLevelTypeToString(topLevelType) {
3653
  return topLevelType;
3654
}
3655
3656
/**
3657
 * Generate a mapping of standard vendor prefixes using the defined style property and event name.
3658
 *
3659
 * @param {string} styleProp
3660
 * @param {string} eventName
3661
 * @returns {object}
3662
 */
3663
3664
function makePrefixMap(styleProp, eventName) {
3665
  var prefixes = {};
3666
  prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
3667
  prefixes['Webkit' + styleProp] = 'webkit' + eventName;
3668
  prefixes['Moz' + styleProp] = 'moz' + eventName;
3669
  return prefixes;
3670
}
3671
/**
3672
 * A list of event names to a configurable list of vendor prefixes.
3673
 */
3674
3675
3676
var vendorPrefixes = {
3677
  animationend: makePrefixMap('Animation', 'AnimationEnd'),
3678
  animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
3679
  animationstart: makePrefixMap('Animation', 'AnimationStart'),
3680
  transitionend: makePrefixMap('Transition', 'TransitionEnd')
3681
};
3682
/**
3683
 * Event names that have already been detected and prefixed (if applicable).
3684
 */
3685
3686
var prefixedEventNames = {};
3687
/**
3688
 * Element to check for prefixes on.
3689
 */
3690
3691
var style = {};
3692
/**
3693
 * Bootstrap if a DOM exists.
3694
 */
3695
3696
if (canUseDOM) {
3697
  style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,
3698
  // the un-prefixed "animation" and "transition" properties are defined on the
3699
  // style object but the events that fire will still be prefixed, so we need
3700
  // to check if the un-prefixed events are usable, and if not remove them from the map.
3701
3702
  if (!('AnimationEvent' in window)) {
3703
    delete vendorPrefixes.animationend.animation;
3704
    delete vendorPrefixes.animationiteration.animation;
3705
    delete vendorPrefixes.animationstart.animation;
3706
  } // Same as above
3707
3708
3709
  if (!('TransitionEvent' in window)) {
3710
    delete vendorPrefixes.transitionend.transition;
3711
  }
3712
}
3713
/**
3714
 * Attempts to determine the correct vendor prefixed event name.
3715
 *
3716
 * @param {string} eventName
3717
 * @returns {string}
3718
 */
3719
3720
3721
function getVendorPrefixedEventName(eventName) {
3722
  if (prefixedEventNames[eventName]) {
3723
    return prefixedEventNames[eventName];
3724
  } else if (!vendorPrefixes[eventName]) {
3725
    return eventName;
3726
  }
3727
3728
  var prefixMap = vendorPrefixes[eventName];
3729
3730
  for (var styleProp in prefixMap) {
3731
    if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
3732
      return prefixedEventNames[eventName] = prefixMap[styleProp];
3733
    }
3734
  }
3735
3736
  return eventName;
3737
}
3738
3739
/**
3740
 * To identify top level events in ReactDOM, we use constants defined by this
3741
 * module. This is the only module that uses the unsafe* methods to express
3742
 * that the constants actually correspond to the browser event names. This lets
3743
 * us save some bundle size by avoiding a top level type -> event name map.
3744
 * The rest of ReactDOM code should import top level types from this file.
3745
 */
3746
3747
var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
3748
var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
3749
var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));
3750
var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
3751
var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
3752
var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
3753
var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
3754
var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
3755
var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
3756
var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
3757
var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
3758
var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
3759
var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');
3760
var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');
3761
var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
3762
var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
3763
var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
3764
var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
3765
var TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick');
3766
var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
3767
var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
3768
var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
3769
var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
3770
var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
3771
var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
3772
var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
3773
var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
3774
var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
3775
var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
3776
var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
3777
var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
3778
var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
3779
var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
3780
var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture');
3781
var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
3782
var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid');
3783
var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
3784
var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
3785
var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
3786
var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
3787
var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
3788
var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
3789
var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
3790
var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture');
3791
var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
3792
var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
3793
var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
3794
var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
3795
var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
3796
var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
3797
var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
3798
var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
3799
var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
3800
var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel');
3801
var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown');
3802
3803
3804
var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove');
3805
var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout');
3806
var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover');
3807
var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup');
3808
var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
3809
var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
3810
var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset');
3811
var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
3812
var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
3813
var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
3814
var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
3815
var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
3816
var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit');
3817
var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
3818
var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
3819
var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
3820
var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
3821
var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
3822
var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
3823
var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
3824
var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
3825
var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
3826
var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
3827
var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
3828
var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); // List of events that need to be individually attached to media elements.
3829
// Note that events in this list will *not* be listened to at the top level
3830
// unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.
3831
3832
var mediaEventTypes = [TOP_ABORT, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_VOLUME_CHANGE, TOP_WAITING];
3833
function getRawEventName(topLevelType) {
3834
  return unsafeCastDOMTopLevelTypeToString(topLevelType);
3835
}
3836
3837
var attemptSynchronousHydration;
3838
function setAttemptSynchronousHydration(fn) {
3839
  attemptSynchronousHydration = fn;
3840
} // TODO: Upgrade this definition once we're on a newer version of Flow that
3841
// has this definition built-in.
3842
3843
var hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed.
3844
3845
var queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout.
3846
3847
// if the last target was dehydrated.
3848
3849
var queuedFocus = null;
3850
var queuedDrag = null;
3851
var queuedMouse = null; // For pointer events there can be one latest event per pointerId.
3852
3853
var queuedPointers = new Map();
3854
var queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too.
3855
3856
function hasQueuedDiscreteEvents() {
3857
  return queuedDiscreteEvents.length > 0;
3858
}
3859
3860
var discreteReplayableEvents = [TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_TOUCH_CANCEL, TOP_TOUCH_END, TOP_TOUCH_START, TOP_AUX_CLICK, TOP_DOUBLE_CLICK, TOP_POINTER_CANCEL, TOP_POINTER_DOWN, TOP_POINTER_UP, TOP_DRAG_END, TOP_DRAG_START, TOP_DROP, TOP_COMPOSITION_END, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_INPUT, TOP_TEXT_INPUT, TOP_CLOSE, TOP_CANCEL, TOP_COPY, TOP_CUT, TOP_PASTE, TOP_CLICK, TOP_CHANGE, TOP_CONTEXT_MENU, TOP_RESET, TOP_SUBMIT];
3861
var continuousReplayableEvents = [TOP_FOCUS, TOP_BLUR, TOP_DRAG_ENTER, TOP_DRAG_LEAVE, TOP_MOUSE_OVER, TOP_MOUSE_OUT, TOP_POINTER_OVER, TOP_POINTER_OUT, TOP_GOT_POINTER_CAPTURE, TOP_LOST_POINTER_CAPTURE];
3862
function isReplayableDiscreteEvent(eventType) {
3863
  return discreteReplayableEvents.indexOf(eventType) > -1;
3864
}
3865
3866
function trapReplayableEvent(topLevelType, document, listeningSet) {
3867
  listenToTopLevel(topLevelType, document, listeningSet);
3868
3869
  if (enableFlareAPI) {
3870
    // Trap events for the responder system.
3871
    var passiveEventKey = unsafeCastDOMTopLevelTypeToString(topLevelType) + '_passive';
3872
3873
    if (!listeningSet.has(passiveEventKey)) {
3874
      trapEventForResponderEventSystem(document, topLevelType, true);
3875
      listeningSet.add(passiveEventKey);
3876
    } // TODO: This listens to all events as active which might have
3877
    // undesirable effects. It's also unnecessary to have both
3878
    // passive and active listeners. Instead, we could start with
3879
    // a passive and upgrade it to an active one if needed.
3880
    // For replaying purposes the active is never needed since we
3881
    // currently don't preventDefault.
3882
3883
3884
    var activeEventKey = unsafeCastDOMTopLevelTypeToString(topLevelType) + '_active';
3885
3886
    if (!listeningSet.has(activeEventKey)) {
3887
      trapEventForResponderEventSystem(document, topLevelType, false);
3888
      listeningSet.add(activeEventKey);
3889
    }
3890
  }
3891
}
3892
3893
function eagerlyTrapReplayableEvents(document) {
3894
  var listeningSet = getListeningSetForElement(document); // Discrete
3895
3896
  discreteReplayableEvents.forEach(function (topLevelType) {
3897
    trapReplayableEvent(topLevelType, document, listeningSet);
3898
  }); // Continuous
3899
3900
  continuousReplayableEvents.forEach(function (topLevelType) {
3901
    trapReplayableEvent(topLevelType, document, listeningSet);
3902
  });
3903
}
3904
3905
function createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
3906
  return {
3907
    blockedOn: blockedOn,
3908
    topLevelType: topLevelType,
3909
    eventSystemFlags: eventSystemFlags | IS_REPLAYED,
3910
    nativeEvent: nativeEvent
3911
  };
3912
}
3913
3914
function queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
3915
  var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent);
3916
  queuedDiscreteEvents.push(queuedEvent);
3917
3918
  if (enableSelectiveHydration) {
3919
    if (queuedDiscreteEvents.length === 1) {
3920
      // If this was the first discrete event, we might be able to
3921
      // synchronously unblock it so that preventDefault still works.
3922
      while (queuedEvent.blockedOn !== null) {
3923
        var _fiber = getInstanceFromNode$1(queuedEvent.blockedOn);
3924
3925
        if (_fiber === null) {
3926
          break;
3927
        }
3928
3929
        attemptSynchronousHydration(_fiber);
3930
3931
        if (queuedEvent.blockedOn === null) {
3932
          // We got unblocked by hydration. Let's try again.
3933
          replayUnblockedEvents(); // If we're reblocked, on an inner boundary, we might need
3934
          // to attempt hydrating that one.
3935
3936
          continue;
3937
        } else {
3938
          // We're still blocked from hydation, we have to give up
3939
          // and replay later.
3940
          break;
3941
        }
3942
      }
3943
    }
3944
  }
3945
} // Resets the replaying for this type of continuous event to no event.
3946
3947
function clearIfContinuousEvent(topLevelType, nativeEvent) {
3948
  switch (topLevelType) {
3949
    case TOP_FOCUS:
3950
    case TOP_BLUR:
3951
      queuedFocus = null;
3952
      break;
3953
3954
    case TOP_DRAG_ENTER:
3955
    case TOP_DRAG_LEAVE:
3956
      queuedDrag = null;
3957
      break;
3958
3959
    case TOP_MOUSE_OVER:
3960
    case TOP_MOUSE_OUT:
3961
      queuedMouse = null;
3962
      break;
3963
3964
    case TOP_POINTER_OVER:
3965
    case TOP_POINTER_OUT:
3966
      {
3967
        var pointerId = nativeEvent.pointerId;
3968
        queuedPointers.delete(pointerId);
3969
        break;
3970
      }
3971
3972
    case TOP_GOT_POINTER_CAPTURE:
3973
    case TOP_LOST_POINTER_CAPTURE:
3974
      {
3975
        var _pointerId = nativeEvent.pointerId;
3976
        queuedPointerCaptures.delete(_pointerId);
3977
        break;
3978
      }
3979
  }
3980
}
3981
3982
function accumulateOrCreateQueuedReplayableEvent(existingQueuedEvent, blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
3983
  if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {
3984
    return createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent);
3985
  } // If we have already queued this exact event, then it's because
3986
  // the different event systems have different DOM event listeners.
3987
  // We can accumulate the flags and store a single event to be
3988
  // replayed.
3989
3990
3991
  existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
3992
  return existingQueuedEvent;
3993
}
3994
3995
function queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
3996
  // These set relatedTarget to null because the replayed event will be treated as if we
3997
  // moved from outside the window (no target) onto the target once it hydrates.
3998
  // Instead of mutating we could clone the event.
3999
  switch (topLevelType) {
4000
    case TOP_FOCUS:
4001
      {
4002
        var focusEvent = nativeEvent;
4003
        queuedFocus = accumulateOrCreateQueuedReplayableEvent(queuedFocus, blockedOn, topLevelType, eventSystemFlags, focusEvent);
4004
        return true;
4005
      }
4006
4007
    case TOP_DRAG_ENTER:
4008
      {
4009
        var dragEvent = nativeEvent;
4010
        queuedDrag = accumulateOrCreateQueuedReplayableEvent(queuedDrag, blockedOn, topLevelType, eventSystemFlags, dragEvent);
4011
        return true;
4012
      }
4013
4014
    case TOP_MOUSE_OVER:
4015
      {
4016
        var mouseEvent = nativeEvent;
4017
        queuedMouse = accumulateOrCreateQueuedReplayableEvent(queuedMouse, blockedOn, topLevelType, eventSystemFlags, mouseEvent);
4018
        return true;
4019
      }
4020
4021
    case TOP_POINTER_OVER:
4022
      {
4023
        var pointerEvent = nativeEvent;
4024
        var pointerId = pointerEvent.pointerId;
4025
        queuedPointers.set(pointerId, accumulateOrCreateQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, topLevelType, eventSystemFlags, pointerEvent));
4026
        return true;
4027
      }
4028
4029
    case TOP_GOT_POINTER_CAPTURE:
4030
      {
4031
        var _pointerEvent = nativeEvent;
4032
        var _pointerId2 = _pointerEvent.pointerId;
4033
        queuedPointerCaptures.set(_pointerId2, accumulateOrCreateQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, topLevelType, eventSystemFlags, _pointerEvent));
4034
        return true;
4035
      }
4036
  }
4037
4038
  return false;
4039
}
4040
4041
function attemptReplayQueuedEvent(queuedEvent) {
4042
  if (queuedEvent.blockedOn !== null) {
4043
    return false;
4044
  }
4045
4046
  var nextBlockedOn = attemptToDispatchEvent(queuedEvent.topLevelType, queuedEvent.eventSystemFlags, queuedEvent.nativeEvent);
4047
4048
  if (nextBlockedOn !== null) {
4049
    // We're still blocked. Try again later.
4050
    queuedEvent.blockedOn = nextBlockedOn;
4051
    return false;
4052
  }
4053
4054
  return true;
4055
}
4056
4057
function attemptReplayQueuedEventInMap(queuedEvent, key, map) {
4058
  if (attemptReplayQueuedEvent(queuedEvent)) {
4059
    map.delete(key);
4060
  }
4061
}
4062
4063
function replayUnblockedEvents() {
4064
  hasScheduledReplayAttempt = false; // First replay discrete events.
4065
4066
  while (queuedDiscreteEvents.length > 0) {
4067
    var nextDiscreteEvent = queuedDiscreteEvents[0];
4068
4069
    if (nextDiscreteEvent.blockedOn !== null) {
4070
      // We're still blocked.
4071
      break;
4072
    }
4073
4074
    var nextBlockedOn = attemptToDispatchEvent(nextDiscreteEvent.topLevelType, nextDiscreteEvent.eventSystemFlags, nextDiscreteEvent.nativeEvent);
4075
4076
    if (nextBlockedOn !== null) {
4077
      // We're still blocked. Try again later.
4078
      nextDiscreteEvent.blockedOn = nextBlockedOn;
4079
    } else {
4080
      // We've successfully replayed the first event. Let's try the next one.
4081
      queuedDiscreteEvents.shift();
4082
    }
4083
  } // Next replay any continuous events.
4084
4085
4086
  if (queuedFocus !== null && attemptReplayQueuedEvent(queuedFocus)) {
4087
    queuedFocus = null;
4088
  }
4089
4090
  if (queuedDrag !== null && attemptReplayQueuedEvent(queuedDrag)) {
4091
    queuedDrag = null;
4092
  }
4093
4094
  if (queuedMouse !== null && attemptReplayQueuedEvent(queuedMouse)) {
4095
    queuedMouse = null;
4096
  }
4097
4098
  queuedPointers.forEach(attemptReplayQueuedEventInMap);
4099
  queuedPointerCaptures.forEach(attemptReplayQueuedEventInMap);
4100
}
4101
4102
function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
4103
  if (queuedEvent.blockedOn === unblocked) {
4104
    queuedEvent.blockedOn = null;
4105
4106
    if (!hasScheduledReplayAttempt) {
4107
      hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are
4108
      // now unblocked. This first might not actually be unblocked yet.
4109
      // We could check it early to avoid scheduling an unnecessary callback.
4110
4111
      Scheduler.unstable_scheduleCallback(Scheduler.unstable_NormalPriority, replayUnblockedEvents);
4112
    }
4113
  }
4114
}
4115
4116
function retryIfBlockedOn(unblocked) {
4117
  // Mark anything that was blocked on this as no longer blocked
4118
  // and eligible for a replay.
4119
  if (queuedDiscreteEvents.length > 0) {
4120
    scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's
4121
    // worth it because we expect very few discrete events to queue up and once
4122
    // we are actually fully unblocked it will be fast to replay them.
4123
4124
    for (var i = 1; i < queuedDiscreteEvents.length; i++) {
4125
      var queuedEvent = queuedDiscreteEvents[i];
4126
4127
      if (queuedEvent.blockedOn === unblocked) {
4128
        queuedEvent.blockedOn = null;
4129
      }
4130
    }
4131
  }
4132
4133
  if (queuedFocus !== null) {
4134
    scheduleCallbackIfUnblocked(queuedFocus, unblocked);
4135
  }
4136
4137
  if (queuedDrag !== null) {
4138
    scheduleCallbackIfUnblocked(queuedDrag, unblocked);
4139
  }
4140
4141
  if (queuedMouse !== null) {
4142
    scheduleCallbackIfUnblocked(queuedMouse, unblocked);
4143
  }
4144
4145
  var unblock = function (queuedEvent) {
4146
    return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
4147
  };
4148
4149
  queuedPointers.forEach(unblock);
4150
  queuedPointerCaptures.forEach(unblock);
4151
}
4152
4153
/**
4154
 * `ReactInstanceMap` maintains a mapping from a public facing stateful
4155
 * instance (key) and the internal representation (value). This allows public
4156
 * methods to accept the user facing instance as an argument and map them back
4157
 * to internal methods.
4158
 *
4159
 * Note that this module is currently shared and assumed to be stateless.
4160
 * If this becomes an actual Map, that will break.
4161
 */
4162
4163
/**
4164
 * This API should be called `delete` but we'd have to make sure to always
4165
 * transform these to strings for IE support. When this transform is fully
4166
 * supported we can rename it.
4167
 */
4168
4169
function get(key) {
4170
  return key._reactInternalFiber;
4171
}
4172
function has(key) {
4173
  return key._reactInternalFiber !== undefined;
4174
}
4175
function set(key, value) {
4176
  key._reactInternalFiber = value;
4177
}
4178
4179
// Don't change these two values. They're used by React Dev Tools.
4180
var NoEffect =
4181
/*              */
4182
0;
4183
var PerformedWork =
4184
/*         */
4185
1; // You can change the rest (and add more).
4186
4187
var Placement =
4188
/*             */
4189
2;
4190
var Update =
4191
/*                */
4192
4;
4193
var PlacementAndUpdate =
4194
/*    */
4195
6;
4196
var Deletion =
4197
/*              */
4198
8;
4199
var ContentReset =
4200
/*          */
4201
16;
4202
var Callback =
4203
/*              */
4204
32;
4205
var DidCapture =
4206
/*            */
4207
64;
4208
var Ref =
4209
/*                   */
4210
128;
4211
var Snapshot =
4212
/*              */
4213
256;
4214
var Passive =
4215
/*               */
4216
512;
4217
var Hydrating =
4218
/*             */
4219
1024;
4220
var HydratingAndUpdate =
4221
/*    */
4222
1028; // Passive & Update & Callback & Ref & Snapshot
4223
4224
var LifecycleEffectMask =
4225
/*   */
4226
932; // Union of all host effects
4227
4228
var HostEffectMask =
4229
/*        */
4230
2047;
4231
var Incomplete =
4232
/*            */
4233
2048;
4234
var ShouldCapture =
4235
/*         */
4236
4096;
4237
4238
var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
4239
function getNearestMountedFiber(fiber) {
4240
  var node = fiber;
4241
  var nearestMounted = fiber;
4242
4243
  if (!fiber.alternate) {
4244
    // If there is no alternate, this might be a new tree that isn't inserted
4245
    // yet. If it is, then it will have a pending insertion effect on it.
4246
    var nextNode = node;
4247
4248
    do {
4249
      node = nextNode;
4250
4251
      if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) {
4252
        // This is an insertion or in-progress hydration. The nearest possible
4253
        // mounted fiber is the parent but we need to continue to figure out
4254
        // if that one is still mounted.
4255
        nearestMounted = node.return;
4256
      }
4257
4258
      nextNode = node.return;
4259
    } while (nextNode);
4260
  } else {
4261
    while (node.return) {
4262
      node = node.return;
4263
    }
4264
  }
4265
4266
  if (node.tag === HostRoot) {
4267
    // TODO: Check if this was a nested HostRoot when used with
4268
    // renderContainerIntoSubtree.
4269
    return nearestMounted;
4270
  } // If we didn't hit the root, that means that we're in an disconnected tree
4271
  // that has been unmounted.
4272
4273
4274
  return null;
4275
}
4276
function getSuspenseInstanceFromFiber(fiber) {
4277
  if (fiber.tag === SuspenseComponent) {
4278
    var suspenseState = fiber.memoizedState;
4279
4280
    if (suspenseState === null) {
4281
      var current = fiber.alternate;
4282
4283
      if (current !== null) {
4284
        suspenseState = current.memoizedState;
4285
      }
4286
    }
4287
4288
    if (suspenseState !== null) {
4289
      return suspenseState.dehydrated;
4290
    }
4291
  }
4292
4293
  return null;
4294
}
4295
function getContainerFromFiber(fiber) {
4296
  return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;
4297
}
4298
function isFiberMounted(fiber) {
4299
  return getNearestMountedFiber(fiber) === fiber;
4300
}
4301
function isMounted(component) {
4302
  {
4303
    var owner = ReactCurrentOwner$1.current;
4304
4305
    if (owner !== null && owner.tag === ClassComponent) {
4306
      var ownerFiber = owner;
4307
      var instance = ownerFiber.stateNode;
4308
      !instance._warnedAboutRefsInRender ? warningWithoutStack$1(false, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(ownerFiber.type) || 'A component') : void 0;
4309
      instance._warnedAboutRefsInRender = true;
4310
    }
4311
  }
4312
4313
  var fiber = get(component);
4314
4315
  if (!fiber) {
4316
    return false;
4317
  }
4318
4319
  return getNearestMountedFiber(fiber) === fiber;
4320
}
4321
4322
function assertIsMounted(fiber) {
4323
  (function () {
4324
    if (!(getNearestMountedFiber(fiber) === fiber)) {
4325
      {
4326
        throw ReactError(Error("Unable to find node on an unmounted component."));
4327
      }
4328
    }
4329
  })();
4330
}
4331
4332
function findCurrentFiberUsingSlowPath(fiber) {
4333
  var alternate = fiber.alternate;
4334
4335
  if (!alternate) {
4336
    // If there is no alternate, then we only need to check if it is mounted.
4337
    var nearestMounted = getNearestMountedFiber(fiber);
4338
4339
    (function () {
4340
      if (!(nearestMounted !== null)) {
4341
        {
4342
          throw ReactError(Error("Unable to find node on an unmounted component."));
4343
        }
4344
      }
4345
    })();
4346
4347
    if (nearestMounted !== fiber) {
4348
      return null;
4349
    }
4350
4351
    return fiber;
4352
  } // If we have two possible branches, we'll walk backwards up to the root
4353
  // to see what path the root points to. On the way we may hit one of the
4354
  // special cases and we'll deal with them.
4355
4356
4357
  var a = fiber;
4358
  var b = alternate;
4359
4360
  while (true) {
4361
    var parentA = a.return;
4362
4363
    if (parentA === null) {
4364
      // We're at the root.
4365
      break;
4366
    }
4367
4368
    var parentB = parentA.alternate;
4369
4370
    if (parentB === null) {
4371
      // There is no alternate. This is an unusual case. Currently, it only
4372
      // happens when a Suspense component is hidden. An extra fragment fiber
4373
      // is inserted in between the Suspense fiber and its children. Skip
4374
      // over this extra fragment fiber and proceed to the next parent.
4375
      var nextParent = parentA.return;
4376
4377
      if (nextParent !== null) {
4378
        a = b = nextParent;
4379
        continue;
4380
      } // If there's no parent, we're at the root.
4381
4382
4383
      break;
4384
    } // If both copies of the parent fiber point to the same child, we can
4385
    // assume that the child is current. This happens when we bailout on low
4386
    // priority: the bailed out fiber's child reuses the current child.
4387
4388
4389
    if (parentA.child === parentB.child) {
4390
      var child = parentA.child;
4391
4392
      while (child) {
4393
        if (child === a) {
4394
          // We've determined that A is the current branch.
4395
          assertIsMounted(parentA);
4396
          return fiber;
4397
        }
4398
4399
        if (child === b) {
4400
          // We've determined that B is the current branch.
4401
          assertIsMounted(parentA);
4402
          return alternate;
4403
        }
4404
4405
        child = child.sibling;
4406
      } // We should never have an alternate for any mounting node. So the only
4407
      // way this could possibly happen is if this was unmounted, if at all.
4408
4409
4410
      (function () {
4411
        {
4412
          {
4413
            throw ReactError(Error("Unable to find node on an unmounted component."));
4414
          }
4415
        }
4416
      })();
4417
    }
4418
4419
    if (a.return !== b.return) {
4420
      // The return pointer of A and the return pointer of B point to different
4421
      // fibers. We assume that return pointers never criss-cross, so A must
4422
      // belong to the child set of A.return, and B must belong to the child
4423
      // set of B.return.
4424
      a = parentA;
4425
      b = parentB;
4426
    } else {
4427
      // The return pointers point to the same fiber. We'll have to use the
4428
      // default, slow path: scan the child sets of each parent alternate to see
4429
      // which child belongs to which set.
4430
      //
4431
      // Search parent A's child set
4432
      var didFindChild = false;
4433
      var _child = parentA.child;
4434
4435
      while (_child) {
4436
        if (_child === a) {
4437
          didFindChild = true;
4438
          a = parentA;
4439
          b = parentB;
4440
          break;
4441
        }
4442
4443
        if (_child === b) {
4444
          didFindChild = true;
4445
          b = parentA;
4446
          a = parentB;
4447
          break;
4448
        }
4449
4450
        _child = _child.sibling;
4451
      }
4452
4453
      if (!didFindChild) {
4454
        // Search parent B's child set
4455
        _child = parentB.child;
4456
4457
        while (_child) {
4458
          if (_child === a) {
4459
            didFindChild = true;
4460
            a = parentB;
4461
            b = parentA;
4462
            break;
4463
          }
4464
4465
          if (_child === b) {
4466
            didFindChild = true;
4467
            b = parentB;
4468
            a = parentA;
4469
            break;
4470
          }
4471
4472
          _child = _child.sibling;
4473
        }
4474
4475
        (function () {
4476
          if (!didFindChild) {
4477
            {
4478
              throw ReactError(Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue."));
4479
            }
4480
          }
4481
        })();
4482
      }
4483
    }
4484
4485
    (function () {
4486
      if (!(a.alternate === b)) {
4487
        {
4488
          throw ReactError(Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue."));
4489
        }
4490
      }
4491
    })();
4492
  } // If the root is not a host container, we're in a disconnected tree. I.e.
4493
  // unmounted.
4494
4495
4496
  (function () {
4497
    if (!(a.tag === HostRoot)) {
4498
      {
4499
        throw ReactError(Error("Unable to find node on an unmounted component."));
4500
      }
4501
    }
4502
  })();
4503
4504
  if (a.stateNode.current === a) {
4505
    // We've determined that A is the current branch.
4506
    return fiber;
4507
  } // Otherwise B has to be current branch.
4508
4509
4510
  return alternate;
4511
}
4512
function findCurrentHostFiber(parent) {
4513
  var currentParent = findCurrentFiberUsingSlowPath(parent);
4514
4515
  if (!currentParent) {
4516
    return null;
4517
  } // Next we'll drill down this component to find the first HostComponent/Text.
4518
4519
4520
  var node = currentParent;
4521
4522
  while (true) {
4523
    if (node.tag === HostComponent || node.tag === HostText) {
4524
      return node;
4525
    } else if (node.child) {
4526
      node.child.return = node;
4527
      node = node.child;
4528
      continue;
4529
    }
4530
4531
    if (node === currentParent) {
4532
      return null;
4533
    }
4534
4535
    while (!node.sibling) {
4536
      if (!node.return || node.return === currentParent) {
4537
        return null;
4538
      }
4539
4540
      node = node.return;
4541
    }
4542
4543
    node.sibling.return = node.return;
4544
    node = node.sibling;
4545
  } // Flow needs the return null here, but ESLint complains about it.
4546
  // eslint-disable-next-line no-unreachable
4547
4548
4549
  return null;
4550
}
4551
function findCurrentHostFiberWithNoPortals(parent) {
4552
  var currentParent = findCurrentFiberUsingSlowPath(parent);
4553
4554
  if (!currentParent) {
4555
    return null;
4556
  } // Next we'll drill down this component to find the first HostComponent/Text.
4557
4558
4559
  var node = currentParent;
4560
4561
  while (true) {
4562
    if (node.tag === HostComponent || node.tag === HostText || enableFundamentalAPI && node.tag === FundamentalComponent) {
4563
      return node;
4564
    } else if (node.child && node.tag !== HostPortal) {
4565
      node.child.return = node;
4566
      node = node.child;
4567
      continue;
4568
    }
4569
4570
    if (node === currentParent) {
4571
      return null;
4572
    }
4573
4574
    while (!node.sibling) {
4575
      if (!node.return || node.return === currentParent) {
4576
        return null;
4577
      }
4578
4579
      node = node.return;
4580
    }
4581
4582
    node.sibling.return = node.return;
4583
    node = node.sibling;
4584
  } // Flow needs the return null here, but ESLint complains about it.
4585
  // eslint-disable-next-line no-unreachable
4586
4587
4588
  return null;
4589
}
4590
4591
function addEventBubbleListener(element, eventType, listener) {
4592
  element.addEventListener(eventType, listener, false);
4593
}
4594
function addEventCaptureListener(element, eventType, listener) {
4595
  element.addEventListener(eventType, listener, true);
4596
}
4597
function addEventCaptureListenerWithPassiveFlag(element, eventType, listener, passive) {
4598
  element.addEventListener(eventType, listener, {
4599
    capture: true,
4600
    passive: passive
4601
  });
4602
}
4603
4604
/**
4605
 * Gets the target node from a native browser event by accounting for
4606
 * inconsistencies in browser DOM APIs.
4607
 *
4608
 * @param {object} nativeEvent Native browser event.
4609
 * @return {DOMEventTarget} Target node.
4610
 */
4611
4612
function getEventTarget(nativeEvent) {
4613
  // Fallback to nativeEvent.srcElement for IE9
4614
  // https://github.com/facebook/react/issues/12506
4615
  var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963
4616
4617
  if (target.correspondingUseElement) {
4618
    target = target.correspondingUseElement;
4619
  } // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
4620
  // @see http://www.quirksmode.org/js/events_properties.html
4621
4622
4623
  return target.nodeType === TEXT_NODE ? target.parentNode : target;
4624
}
4625
4626
function getParent(inst) {
4627
  do {
4628
    inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
4629
    // That is depending on if we want nested subtrees (layers) to bubble
4630
    // events to their parent. We could also go through parentNode on the
4631
    // host node but that wouldn't work for React Native and doesn't let us
4632
    // do the portal feature.
4633
  } while (inst && inst.tag !== HostComponent);
4634
4635
  if (inst) {
4636
    return inst;
4637
  }
4638
4639
  return null;
4640
}
4641
/**
4642
 * Return the lowest common ancestor of A and B, or null if they are in
4643
 * different trees.
4644
 */
4645
4646
4647
function getLowestCommonAncestor(instA, instB) {
4648
  var depthA = 0;
4649
4650
  for (var tempA = instA; tempA; tempA = getParent(tempA)) {
4651
    depthA++;
4652
  }
4653
4654
  var depthB = 0;
4655
4656
  for (var tempB = instB; tempB; tempB = getParent(tempB)) {
4657
    depthB++;
4658
  } // If A is deeper, crawl up.
4659
4660
4661
  while (depthA - depthB > 0) {
4662
    instA = getParent(instA);
4663
    depthA--;
4664
  } // If B is deeper, crawl up.
4665
4666
4667
  while (depthB - depthA > 0) {
4668
    instB = getParent(instB);
4669
    depthB--;
4670
  } // Walk in lockstep until we find a match.
4671
4672
4673
  var depth = depthA;
4674
4675
  while (depth--) {
4676
    if (instA === instB || instA === instB.alternate) {
4677
      return instA;
4678
    }
4679
4680
    instA = getParent(instA);
4681
    instB = getParent(instB);
4682
  }
4683
4684
  return null;
4685
}
4686
/**
4687
 * Return if A is an ancestor of B.
4688
 */
4689
4690
4691
/**
4692
 * Return the parent instance of the passed-in instance.
4693
 */
4694
4695
4696
/**
4697
 * Simulates the traversal of a two-phase, capture/bubble event dispatch.
4698
 */
4699
4700
function traverseTwoPhase(inst, fn, arg) {
4701
  var path = [];
4702
4703
  while (inst) {
4704
    path.push(inst);
4705
    inst = getParent(inst);
4706
  }
4707
4708
  var i;
4709
4710
  for (i = path.length; i-- > 0;) {
4711
    fn(path[i], 'captured', arg);
4712
  }
4713
4714
  for (i = 0; i < path.length; i++) {
4715
    fn(path[i], 'bubbled', arg);
4716
  }
4717
}
4718
/**
4719
 * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
4720
 * should would receive a `mouseEnter` or `mouseLeave` event.
4721
 *
4722
 * Does not invoke the callback on the nearest common ancestor because nothing
4723
 * "entered" or "left" that element.
4724
 */
4725
4726
function traverseEnterLeave(from, to, fn, argFrom, argTo) {
4727
  var common = from && to ? getLowestCommonAncestor(from, to) : null;
4728
  var pathFrom = [];
4729
4730
  while (true) {
4731
    if (!from) {
4732
      break;
4733
    }
4734
4735
    if (from === common) {
4736
      break;
4737
    }
4738
4739
    var alternate = from.alternate;
4740
4741
    if (alternate !== null && alternate === common) {
4742
      break;
4743
    }
4744
4745
    pathFrom.push(from);
4746
    from = getParent(from);
4747
  }
4748
4749
  var pathTo = [];
4750
4751
  while (true) {
4752
    if (!to) {
4753
      break;
4754
    }
4755
4756
    if (to === common) {
4757
      break;
4758
    }
4759
4760
    var _alternate = to.alternate;
4761
4762
    if (_alternate !== null && _alternate === common) {
4763
      break;
4764
    }
4765
4766
    pathTo.push(to);
4767
    to = getParent(to);
4768
  }
4769
4770
  for (var i = 0; i < pathFrom.length; i++) {
4771
    fn(pathFrom[i], 'bubbled', argFrom);
4772
  }
4773
4774
  for (var _i = pathTo.length; _i-- > 0;) {
4775
    fn(pathTo[_i], 'captured', argTo);
4776
  }
4777
}
4778
4779
/**
4780
 * Some event types have a notion of different registration names for different
4781
 * "phases" of propagation. This finds listeners by a given phase.
4782
 */
4783
function listenerAtPhase(inst, event, propagationPhase) {
4784
  var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
4785
  return getListener(inst, registrationName);
4786
}
4787
/**
4788
 * A small set of propagation patterns, each of which will accept a small amount
4789
 * of information, and generate a set of "dispatch ready event objects" - which
4790
 * are sets of events that have already been annotated with a set of dispatched
4791
 * listener functions/ids. The API is designed this way to discourage these
4792
 * propagation strategies from actually executing the dispatches, since we
4793
 * always want to collect the entire set of dispatches before executing even a
4794
 * single one.
4795
 */
4796
4797
/**
4798
 * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
4799
 * here, allows us to not have to bind or create functions for each event.
4800
 * Mutating the event's members allows us to not have to create a wrapping
4801
 * "dispatch" object that pairs the event with the listener.
4802
 */
4803
4804
4805
function accumulateDirectionalDispatches(inst, phase, event) {
4806
  {
4807
    !inst ? warningWithoutStack$1(false, 'Dispatching inst must not be null') : void 0;
4808
  }
4809
4810
  var listener = listenerAtPhase(inst, event, phase);
4811
4812
  if (listener) {
4813
    event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
4814
    event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
4815
  }
4816
}
4817
/**
4818
 * Collect dispatches (must be entirely collected before dispatching - see unit
4819
 * tests). Lazily allocate the array to conserve memory.  We must loop through
4820
 * each event and perform the traversal for each one. We cannot perform a
4821
 * single traversal for the entire collection of events because each event may
4822
 * have a different target.
4823
 */
4824
4825
4826
function accumulateTwoPhaseDispatchesSingle(event) {
4827
  if (event && event.dispatchConfig.phasedRegistrationNames) {
4828
    traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
4829
  }
4830
}
4831
/**
4832
 * Accumulates without regard to direction, does not look for phased
4833
 * registration names. Same as `accumulateDirectDispatchesSingle` but without
4834
 * requiring that the `dispatchMarker` be the same as the dispatched ID.
4835
 */
4836
4837
4838
function accumulateDispatches(inst, ignoredDirection, event) {
4839
  if (inst && event && event.dispatchConfig.registrationName) {
4840
    var registrationName = event.dispatchConfig.registrationName;
4841
    var listener = getListener(inst, registrationName);
4842
4843
    if (listener) {
4844
      event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
4845
      event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
4846
    }
4847
  }
4848
}
4849
/**
4850
 * Accumulates dispatches on an `SyntheticEvent`, but only for the
4851
 * `dispatchMarker`.
4852
 * @param {SyntheticEvent} event
4853
 */
4854
4855
4856
function accumulateDirectDispatchesSingle(event) {
4857
  if (event && event.dispatchConfig.registrationName) {
4858
    accumulateDispatches(event._targetInst, null, event);
4859
  }
4860
}
4861
4862
function accumulateTwoPhaseDispatches(events) {
4863
  forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
4864
}
4865
4866
function accumulateEnterLeaveDispatches(leave, enter, from, to) {
4867
  traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
4868
}
4869
function accumulateDirectDispatches(events) {
4870
  forEachAccumulated(events, accumulateDirectDispatchesSingle);
4871
}
4872
4873
/* eslint valid-typeof: 0 */
4874
var EVENT_POOL_SIZE = 10;
4875
/**
4876
 * @interface Event
4877
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4878
 */
4879
4880
var EventInterface = {
4881
  type: null,
4882
  target: null,
4883
  // currentTarget is set when dispatching; no use in copying it here
4884
  currentTarget: function () {
4885
    return null;
4886
  },
4887
  eventPhase: null,
4888
  bubbles: null,
4889
  cancelable: null,
4890
  timeStamp: function (event) {
4891
    return event.timeStamp || Date.now();
4892
  },
4893
  defaultPrevented: null,
4894
  isTrusted: null
4895
};
4896
4897
function functionThatReturnsTrue() {
4898
  return true;
4899
}
4900
4901
function functionThatReturnsFalse() {
4902
  return false;
4903
}
4904
/**
4905
 * Synthetic events are dispatched by event plugins, typically in response to a
4906
 * top-level event delegation handler.
4907
 *
4908
 * These systems should generally use pooling to reduce the frequency of garbage
4909
 * collection. The system should check `isPersistent` to determine whether the
4910
 * event should be released into the pool after being dispatched. Users that
4911
 * need a persisted event should invoke `persist`.
4912
 *
4913
 * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
4914
 * normalizing browser quirks. Subclasses do not necessarily have to implement a
4915
 * DOM interface; custom application-specific events can also subclass this.
4916
 *
4917
 * @param {object} dispatchConfig Configuration used to dispatch this event.
4918
 * @param {*} targetInst Marker identifying the event target.
4919
 * @param {object} nativeEvent Native browser event.
4920
 * @param {DOMEventTarget} nativeEventTarget Target node.
4921
 */
4922
4923
4924
function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
4925
  {
4926
    // these have a getter/setter for warnings
4927
    delete this.nativeEvent;
4928
    delete this.preventDefault;
4929
    delete this.stopPropagation;
4930
    delete this.isDefaultPrevented;
4931
    delete this.isPropagationStopped;
4932
  }
4933
4934
  this.dispatchConfig = dispatchConfig;
4935
  this._targetInst = targetInst;
4936
  this.nativeEvent = nativeEvent;
4937
  var Interface = this.constructor.Interface;
4938
4939
  for (var propName in Interface) {
4940
    if (!Interface.hasOwnProperty(propName)) {
4941
      continue;
4942
    }
4943
4944
    {
4945
      delete this[propName]; // this has a getter/setter for warnings
4946
    }
4947
4948
    var normalize = Interface[propName];
4949
4950
    if (normalize) {
4951
      this[propName] = normalize(nativeEvent);
4952
    } else {
4953
      if (propName === 'target') {
4954
        this.target = nativeEventTarget;
4955
      } else {
4956
        this[propName] = nativeEvent[propName];
4957
      }
4958
    }
4959
  }
4960
4961
  var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
4962
4963
  if (defaultPrevented) {
4964
    this.isDefaultPrevented = functionThatReturnsTrue;
4965
  } else {
4966
    this.isDefaultPrevented = functionThatReturnsFalse;
4967
  }
4968
4969
  this.isPropagationStopped = functionThatReturnsFalse;
4970
  return this;
4971
}
4972
4973
_assign(SyntheticEvent.prototype, {
4974
  preventDefault: function () {
4975
    this.defaultPrevented = true;
4976
    var event = this.nativeEvent;
4977
4978
    if (!event) {
4979
      return;
4980
    }
4981
4982
    if (event.preventDefault) {
4983
      event.preventDefault();
4984
    } else if (typeof event.returnValue !== 'unknown') {
4985
      event.returnValue = false;
4986
    }
4987
4988
    this.isDefaultPrevented = functionThatReturnsTrue;
4989
  },
4990
  stopPropagation: function () {
4991
    var event = this.nativeEvent;
4992
4993
    if (!event) {
4994
      return;
4995
    }
4996
4997
    if (event.stopPropagation) {
4998
      event.stopPropagation();
4999
    } else if (typeof event.cancelBubble !== 'unknown') {
5000
      // The ChangeEventPlugin registers a "propertychange" event for
5001
      // IE. This event does not support bubbling or cancelling, and
5002
      // any references to cancelBubble throw "Member not found".  A
5003
      // typeof check of "unknown" circumvents this issue (and is also
5004
      // IE specific).
5005
      event.cancelBubble = true;
5006
    }
5007
5008
    this.isPropagationStopped = functionThatReturnsTrue;
5009
  },
5010
5011
  /**
5012
   * We release all dispatched `SyntheticEvent`s after each event loop, adding
5013
   * them back into the pool. This allows a way to hold onto a reference that
5014
   * won't be added back into the pool.
5015
   */
5016
  persist: function () {
5017
    this.isPersistent = functionThatReturnsTrue;
5018
  },
5019
5020
  /**
5021
   * Checks if this event should be released back into the pool.
5022
   *
5023
   * @return {boolean} True if this should not be released, false otherwise.
5024
   */
5025
  isPersistent: functionThatReturnsFalse,
5026
5027
  /**
5028
   * `PooledClass` looks for `destructor` on each instance it releases.
5029
   */
5030
  destructor: function () {
5031
    var Interface = this.constructor.Interface;
5032
5033
    for (var propName in Interface) {
5034
      {
5035
        Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
5036
      }
5037
    }
5038
5039
    this.dispatchConfig = null;
5040
    this._targetInst = null;
5041
    this.nativeEvent = null;
5042
    this.isDefaultPrevented = functionThatReturnsFalse;
5043
    this.isPropagationStopped = functionThatReturnsFalse;
5044
    this._dispatchListeners = null;
5045
    this._dispatchInstances = null;
5046
5047
    {
5048
      Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
5049
      Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
5050
      Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
5051
      Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
5052
      Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
5053
    }
5054
  }
5055
});
5056
5057
SyntheticEvent.Interface = EventInterface;
5058
/**
5059
 * Helper to reduce boilerplate when creating subclasses.
5060
 */
5061
5062
SyntheticEvent.extend = function (Interface) {
5063
  var Super = this;
5064
5065
  var E = function () {};
5066
5067
  E.prototype = Super.prototype;
5068
  var prototype = new E();
5069
5070
  function Class() {
5071
    return Super.apply(this, arguments);
5072
  }
5073
5074
  _assign(prototype, Class.prototype);
5075
5076
  Class.prototype = prototype;
5077
  Class.prototype.constructor = Class;
5078
  Class.Interface = _assign({}, Super.Interface, Interface);
5079
  Class.extend = Super.extend;
5080
  addEventPoolingTo(Class);
5081
  return Class;
5082
};
5083
5084
addEventPoolingTo(SyntheticEvent);
5085
/**
5086
 * Helper to nullify syntheticEvent instance properties when destructing
5087
 *
5088
 * @param {String} propName
5089
 * @param {?object} getVal
5090
 * @return {object} defineProperty object
5091
 */
5092
5093
function getPooledWarningPropertyDefinition(propName, getVal) {
5094
  var isFunction = typeof getVal === 'function';
5095
  return {
5096
    configurable: true,
5097
    set: set,
5098
    get: get
5099
  };
5100
5101
  function set(val) {
5102
    var action = isFunction ? 'setting the method' : 'setting the property';
5103
    warn(action, 'This is effectively a no-op');
5104
    return val;
5105
  }
5106
5107
  function get() {
5108
    var action = isFunction ? 'accessing the method' : 'accessing the property';
5109
    var result = isFunction ? 'This is a no-op function' : 'This is set to null';
5110
    warn(action, result);
5111
    return getVal;
5112
  }
5113
5114
  function warn(action, result) {
5115
    var warningCondition = false;
5116
    !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;
5117
  }
5118
}
5119
5120
function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
5121
  var EventConstructor = this;
5122
5123
  if (EventConstructor.eventPool.length) {
5124
    var instance = EventConstructor.eventPool.pop();
5125
    EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
5126
    return instance;
5127
  }
5128
5129
  return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
5130
}
5131
5132
function releasePooledEvent(event) {
5133
  var EventConstructor = this;
5134
5135
  (function () {
5136
    if (!(event instanceof EventConstructor)) {
5137
      {
5138
        throw ReactError(Error("Trying to release an event instance into a pool of a different type."));
5139
      }
5140
    }
5141
  })();
5142
5143
  event.destructor();
5144
5145
  if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
5146
    EventConstructor.eventPool.push(event);
5147
  }
5148
}
5149
5150
function addEventPoolingTo(EventConstructor) {
5151
  EventConstructor.eventPool = [];
5152
  EventConstructor.getPooled = getPooledEvent;
5153
  EventConstructor.release = releasePooledEvent;
5154
}
5155
5156
/**
5157
 * @interface Event
5158
 * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
5159
 * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
5160
 */
5161
5162
var SyntheticAnimationEvent = SyntheticEvent.extend({
5163
  animationName: null,
5164
  elapsedTime: null,
5165
  pseudoElement: null
5166
});
5167
5168
/**
5169
 * @interface Event
5170
 * @see http://www.w3.org/TR/clipboard-apis/
5171
 */
5172
5173
var SyntheticClipboardEvent = SyntheticEvent.extend({
5174
  clipboardData: function (event) {
5175
    return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
5176
  }
5177
});
5178
5179
var SyntheticUIEvent = SyntheticEvent.extend({
5180
  view: null,
5181
  detail: null
5182
});
5183
5184
/**
5185
 * @interface FocusEvent
5186
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5187
 */
5188
5189
var SyntheticFocusEvent = SyntheticUIEvent.extend({
5190
  relatedTarget: null
5191
});
5192
5193
/**
5194
 * `charCode` represents the actual "character code" and is safe to use with
5195
 * `String.fromCharCode`. As such, only keys that correspond to printable
5196
 * characters produce a valid `charCode`, the only exception to this is Enter.
5197
 * The Tab-key is considered non-printable and does not have a `charCode`,
5198
 * presumably because it does not produce a tab-character in browsers.
5199
 *
5200
 * @param {object} nativeEvent Native browser event.
5201
 * @return {number} Normalized `charCode` property.
5202
 */
5203
function getEventCharCode(nativeEvent) {
5204
  var charCode;
5205
  var keyCode = nativeEvent.keyCode;
5206
5207
  if ('charCode' in nativeEvent) {
5208
    charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.
5209
5210
    if (charCode === 0 && keyCode === 13) {
5211
      charCode = 13;
5212
    }
5213
  } else {
5214
    // IE8 does not implement `charCode`, but `keyCode` has the correct value.
5215
    charCode = keyCode;
5216
  } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
5217
  // report Enter as charCode 10 when ctrl is pressed.
5218
5219
5220
  if (charCode === 10) {
5221
    charCode = 13;
5222
  } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
5223
  // Must not discard the (non-)printable Enter-key.
5224
5225
5226
  if (charCode >= 32 || charCode === 13) {
5227
    return charCode;
5228
  }
5229
5230
  return 0;
5231
}
5232
5233
/**
5234
 * Normalization of deprecated HTML5 `key` values
5235
 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
5236
 */
5237
5238
var normalizeKey = {
5239
  Esc: 'Escape',
5240
  Spacebar: ' ',
5241
  Left: 'ArrowLeft',
5242
  Up: 'ArrowUp',
5243
  Right: 'ArrowRight',
5244
  Down: 'ArrowDown',
5245
  Del: 'Delete',
5246
  Win: 'OS',
5247
  Menu: 'ContextMenu',
5248
  Apps: 'ContextMenu',
5249
  Scroll: 'ScrollLock',
5250
  MozPrintableKey: 'Unidentified'
5251
};
5252
/**
5253
 * Translation from legacy `keyCode` to HTML5 `key`
5254
 * Only special keys supported, all others depend on keyboard layout or browser
5255
 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
5256
 */
5257
5258
var translateToKey = {
5259
  '8': 'Backspace',
5260
  '9': 'Tab',
5261
  '12': 'Clear',
5262
  '13': 'Enter',
5263
  '16': 'Shift',
5264
  '17': 'Control',
5265
  '18': 'Alt',
5266
  '19': 'Pause',
5267
  '20': 'CapsLock',
5268
  '27': 'Escape',
5269
  '32': ' ',
5270
  '33': 'PageUp',
5271
  '34': 'PageDown',
5272
  '35': 'End',
5273
  '36': 'Home',
5274
  '37': 'ArrowLeft',
5275
  '38': 'ArrowUp',
5276
  '39': 'ArrowRight',
5277
  '40': 'ArrowDown',
5278
  '45': 'Insert',
5279
  '46': 'Delete',
5280
  '112': 'F1',
5281
  '113': 'F2',
5282
  '114': 'F3',
5283
  '115': 'F4',
5284
  '116': 'F5',
5285
  '117': 'F6',
5286
  '118': 'F7',
5287
  '119': 'F8',
5288
  '120': 'F9',
5289
  '121': 'F10',
5290
  '122': 'F11',
5291
  '123': 'F12',
5292
  '144': 'NumLock',
5293
  '145': 'ScrollLock',
5294
  '224': 'Meta'
5295
};
5296
/**
5297
 * @param {object} nativeEvent Native browser event.
5298
 * @return {string} Normalized `key` property.
5299
 */
5300
5301
function getEventKey(nativeEvent) {
5302
  if (nativeEvent.key) {
5303
    // Normalize inconsistent values reported by browsers due to
5304
    // implementations of a working draft specification.
5305
    // FireFox implements `key` but returns `MozPrintableKey` for all
5306
    // printable characters (normalized to `Unidentified`), ignore it.
5307
    var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
5308
5309
    if (key !== 'Unidentified') {
5310
      return key;
5311
    }
5312
  } // Browser does not implement `key`, polyfill as much of it as we can.
5313
5314
5315
  if (nativeEvent.type === 'keypress') {
5316
    var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
5317
    // thus be captured by `keypress`, no other non-printable key should.
5318
5319
    return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
5320
  }
5321
5322
  if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
5323
    // While user keyboard layout determines the actual meaning of each
5324
    // `keyCode` value, almost all function keys have a universal value.
5325
    return translateToKey[nativeEvent.keyCode] || 'Unidentified';
5326
  }
5327
5328
  return '';
5329
}
5330
5331
/**
5332
 * Translation from modifier key to the associated property in the event.
5333
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
5334
 */
5335
var modifierKeyToProp = {
5336
  Alt: 'altKey',
5337
  Control: 'ctrlKey',
5338
  Meta: 'metaKey',
5339
  Shift: 'shiftKey'
5340
}; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
5341
// getModifierState. If getModifierState is not supported, we map it to a set of
5342
// modifier keys exposed by the event. In this case, Lock-keys are not supported.
5343
5344
function modifierStateGetter(keyArg) {
5345
  var syntheticEvent = this;
5346
  var nativeEvent = syntheticEvent.nativeEvent;
5347
5348
  if (nativeEvent.getModifierState) {
5349
    return nativeEvent.getModifierState(keyArg);
5350
  }
5351
5352
  var keyProp = modifierKeyToProp[keyArg];
5353
  return keyProp ? !!nativeEvent[keyProp] : false;
5354
}
5355
5356
function getEventModifierState(nativeEvent) {
5357
  return modifierStateGetter;
5358
}
5359
5360
/**
5361
 * @interface KeyboardEvent
5362
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5363
 */
5364
5365
var SyntheticKeyboardEvent = SyntheticUIEvent.extend({
5366
  key: getEventKey,
5367
  location: null,
5368
  ctrlKey: null,
5369
  shiftKey: null,
5370
  altKey: null,
5371
  metaKey: null,
5372
  repeat: null,
5373
  locale: null,
5374
  getModifierState: getEventModifierState,
5375
  // Legacy Interface
5376
  charCode: function (event) {
5377
    // `charCode` is the result of a KeyPress event and represents the value of
5378
    // the actual printable character.
5379
    // KeyPress is deprecated, but its replacement is not yet final and not
5380
    // implemented in any major browser. Only KeyPress has charCode.
5381
    if (event.type === 'keypress') {
5382
      return getEventCharCode(event);
5383
    }
5384
5385
    return 0;
5386
  },
5387
  keyCode: function (event) {
5388
    // `keyCode` is the result of a KeyDown/Up event and represents the value of
5389
    // physical keyboard key.
5390
    // The actual meaning of the value depends on the users' keyboard layout
5391
    // which cannot be detected. Assuming that it is a US keyboard layout
5392
    // provides a surprisingly accurate mapping for US and European users.
5393
    // Due to this, it is left to the user to implement at this time.
5394
    if (event.type === 'keydown' || event.type === 'keyup') {
5395
      return event.keyCode;
5396
    }
5397
5398
    return 0;
5399
  },
5400
  which: function (event) {
5401
    // `which` is an alias for either `keyCode` or `charCode` depending on the
5402
    // type of the event.
5403
    if (event.type === 'keypress') {
5404
      return getEventCharCode(event);
5405
    }
5406
5407
    if (event.type === 'keydown' || event.type === 'keyup') {
5408
      return event.keyCode;
5409
    }
5410
5411
    return 0;
5412
  }
5413
});
5414
5415
var previousScreenX = 0;
5416
var previousScreenY = 0; // Use flags to signal movementX/Y has already been set
5417
5418
var isMovementXSet = false;
5419
var isMovementYSet = false;
5420
/**
5421
 * @interface MouseEvent
5422
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5423
 */
5424
5425
var SyntheticMouseEvent = SyntheticUIEvent.extend({
5426
  screenX: null,
5427
  screenY: null,
5428
  clientX: null,
5429
  clientY: null,
5430
  pageX: null,
5431
  pageY: null,
5432
  ctrlKey: null,
5433
  shiftKey: null,
5434
  altKey: null,
5435
  metaKey: null,
5436
  getModifierState: getEventModifierState,
5437
  button: null,
5438
  buttons: null,
5439
  relatedTarget: function (event) {
5440
    return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
5441
  },
5442
  movementX: function (event) {
5443
    if ('movementX' in event) {
5444
      return event.movementX;
5445
    }
5446
5447
    var screenX = previousScreenX;
5448
    previousScreenX = event.screenX;
5449
5450
    if (!isMovementXSet) {
5451
      isMovementXSet = true;
5452
      return 0;
5453
    }
5454
5455
    return event.type === 'mousemove' ? event.screenX - screenX : 0;
5456
  },
5457
  movementY: function (event) {
5458
    if ('movementY' in event) {
5459
      return event.movementY;
5460
    }
5461
5462
    var screenY = previousScreenY;
5463
    previousScreenY = event.screenY;
5464
5465
    if (!isMovementYSet) {
5466
      isMovementYSet = true;
5467
      return 0;
5468
    }
5469
5470
    return event.type === 'mousemove' ? event.screenY - screenY : 0;
5471
  }
5472
});
5473
5474
/**
5475
 * @interface PointerEvent
5476
 * @see http://www.w3.org/TR/pointerevents/
5477
 */
5478
5479
var SyntheticPointerEvent = SyntheticMouseEvent.extend({
5480
  pointerId: null,
5481
  width: null,
5482
  height: null,
5483
  pressure: null,
5484
  tangentialPressure: null,
5485
  tiltX: null,
5486
  tiltY: null,
5487
  twist: null,
5488
  pointerType: null,
5489
  isPrimary: null
5490
});
5491
5492
/**
5493
 * @interface DragEvent
5494
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5495
 */
5496
5497
var SyntheticDragEvent = SyntheticMouseEvent.extend({
5498
  dataTransfer: null
5499
});
5500
5501
/**
5502
 * @interface TouchEvent
5503
 * @see http://www.w3.org/TR/touch-events/
5504
 */
5505
5506
var SyntheticTouchEvent = SyntheticUIEvent.extend({
5507
  touches: null,
5508
  targetTouches: null,
5509
  changedTouches: null,
5510
  altKey: null,
5511
  metaKey: null,
5512
  ctrlKey: null,
5513
  shiftKey: null,
5514
  getModifierState: getEventModifierState
5515
});
5516
5517
/**
5518
 * @interface Event
5519
 * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
5520
 * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
5521
 */
5522
5523
var SyntheticTransitionEvent = SyntheticEvent.extend({
5524
  propertyName: null,
5525
  elapsedTime: null,
5526
  pseudoElement: null
5527
});
5528
5529
/**
5530
 * @interface WheelEvent
5531
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5532
 */
5533
5534
var SyntheticWheelEvent = SyntheticMouseEvent.extend({
5535
  deltaX: function (event) {
5536
    return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
5537
    'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
5538
  },
5539
  deltaY: function (event) {
5540
    return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
5541
    'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
5542
    'wheelDelta' in event ? -event.wheelDelta : 0;
5543
  },
5544
  deltaZ: null,
5545
  // Browsers without "deltaMode" is reporting in raw wheel delta where one
5546
  // notch on the scroll is always +/- 120, roughly equivalent to pixels.
5547
  // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
5548
  // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
5549
  deltaMode: null
5550
});
5551
5552
/**
5553
 * Turns
5554
 * ['abort', ...]
5555
 * into
5556
 * eventTypes = {
5557
 *   'abort': {
5558
 *     phasedRegistrationNames: {
5559
 *       bubbled: 'onAbort',
5560
 *       captured: 'onAbortCapture',
5561
 *     },
5562
 *     dependencies: [TOP_ABORT],
5563
 *   },
5564
 *   ...
5565
 * };
5566
 * topLevelEventsToDispatchConfig = new Map([
5567
 *   [TOP_ABORT, { sameConfig }],
5568
 * ]);
5569
 */
5570
5571
var eventTuples = [// Discrete events
5572
[TOP_BLUR, 'blur', DiscreteEvent], [TOP_CANCEL, 'cancel', DiscreteEvent], [TOP_CLICK, 'click', DiscreteEvent], [TOP_CLOSE, 'close', DiscreteEvent], [TOP_CONTEXT_MENU, 'contextMenu', DiscreteEvent], [TOP_COPY, 'copy', DiscreteEvent], [TOP_CUT, 'cut', DiscreteEvent], [TOP_AUX_CLICK, 'auxClick', DiscreteEvent], [TOP_DOUBLE_CLICK, 'doubleClick', DiscreteEvent], [TOP_DRAG_END, 'dragEnd', DiscreteEvent], [TOP_DRAG_START, 'dragStart', DiscreteEvent], [TOP_DROP, 'drop', DiscreteEvent], [TOP_FOCUS, 'focus', DiscreteEvent], [TOP_INPUT, 'input', DiscreteEvent], [TOP_INVALID, 'invalid', DiscreteEvent], [TOP_KEY_DOWN, 'keyDown', DiscreteEvent], [TOP_KEY_PRESS, 'keyPress', DiscreteEvent], [TOP_KEY_UP, 'keyUp', DiscreteEvent], [TOP_MOUSE_DOWN, 'mouseDown', DiscreteEvent], [TOP_MOUSE_UP, 'mouseUp', DiscreteEvent], [TOP_PASTE, 'paste', DiscreteEvent], [TOP_PAUSE, 'pause', DiscreteEvent], [TOP_PLAY, 'play', DiscreteEvent], [TOP_POINTER_CANCEL, 'pointerCancel', DiscreteEvent], [TOP_POINTER_DOWN, 'pointerDown', DiscreteEvent], [TOP_POINTER_UP, 'pointerUp', DiscreteEvent], [TOP_RATE_CHANGE, 'rateChange', DiscreteEvent], [TOP_RESET, 'reset', DiscreteEvent], [TOP_SEEKED, 'seeked', DiscreteEvent], [TOP_SUBMIT, 'submit', DiscreteEvent], [TOP_TOUCH_CANCEL, 'touchCancel', DiscreteEvent], [TOP_TOUCH_END, 'touchEnd', DiscreteEvent], [TOP_TOUCH_START, 'touchStart', DiscreteEvent], [TOP_VOLUME_CHANGE, 'volumeChange', DiscreteEvent], // User-blocking events
5573
[TOP_DRAG, 'drag', UserBlockingEvent], [TOP_DRAG_ENTER, 'dragEnter', UserBlockingEvent], [TOP_DRAG_EXIT, 'dragExit', UserBlockingEvent], [TOP_DRAG_LEAVE, 'dragLeave', UserBlockingEvent], [TOP_DRAG_OVER, 'dragOver', UserBlockingEvent], [TOP_MOUSE_MOVE, 'mouseMove', UserBlockingEvent], [TOP_MOUSE_OUT, 'mouseOut', UserBlockingEvent], [TOP_MOUSE_OVER, 'mouseOver', UserBlockingEvent], [TOP_POINTER_MOVE, 'pointerMove', UserBlockingEvent], [TOP_POINTER_OUT, 'pointerOut', UserBlockingEvent], [TOP_POINTER_OVER, 'pointerOver', UserBlockingEvent], [TOP_SCROLL, 'scroll', UserBlockingEvent], [TOP_TOGGLE, 'toggle', UserBlockingEvent], [TOP_TOUCH_MOVE, 'touchMove', UserBlockingEvent], [TOP_WHEEL, 'wheel', UserBlockingEvent], // Continuous events
5574
[TOP_ABORT, 'abort', ContinuousEvent], [TOP_ANIMATION_END, 'animationEnd', ContinuousEvent], [TOP_ANIMATION_ITERATION, 'animationIteration', ContinuousEvent], [TOP_ANIMATION_START, 'animationStart', ContinuousEvent], [TOP_CAN_PLAY, 'canPlay', ContinuousEvent], [TOP_CAN_PLAY_THROUGH, 'canPlayThrough', ContinuousEvent], [TOP_DURATION_CHANGE, 'durationChange', ContinuousEvent], [TOP_EMPTIED, 'emptied', ContinuousEvent], [TOP_ENCRYPTED, 'encrypted', ContinuousEvent], [TOP_ENDED, 'ended', ContinuousEvent], [TOP_ERROR, 'error', ContinuousEvent], [TOP_GOT_POINTER_CAPTURE, 'gotPointerCapture', ContinuousEvent], [TOP_LOAD, 'load', ContinuousEvent], [TOP_LOADED_DATA, 'loadedData', ContinuousEvent], [TOP_LOADED_METADATA, 'loadedMetadata', ContinuousEvent], [TOP_LOAD_START, 'loadStart', ContinuousEvent], [TOP_LOST_POINTER_CAPTURE, 'lostPointerCapture', ContinuousEvent], [TOP_PLAYING, 'playing', ContinuousEvent], [TOP_PROGRESS, 'progress', ContinuousEvent], [TOP_SEEKING, 'seeking', ContinuousEvent], [TOP_STALLED, 'stalled', ContinuousEvent], [TOP_SUSPEND, 'suspend', ContinuousEvent], [TOP_TIME_UPDATE, 'timeUpdate', ContinuousEvent], [TOP_TRANSITION_END, 'transitionEnd', ContinuousEvent], [TOP_WAITING, 'waiting', ContinuousEvent]];
5575
var eventTypes = {};
5576
var topLevelEventsToDispatchConfig = {};
5577
5578
for (var i = 0; i < eventTuples.length; i++) {
5579
  var eventTuple = eventTuples[i];
5580
  var topEvent = eventTuple[0];
5581
  var event = eventTuple[1];
5582
  var eventPriority = eventTuple[2];
5583
  var capitalizedEvent = event[0].toUpperCase() + event.slice(1);
5584
  var onEvent = 'on' + capitalizedEvent;
5585
  var config = {
5586
    phasedRegistrationNames: {
5587
      bubbled: onEvent,
5588
      captured: onEvent + 'Capture'
5589
    },
5590
    dependencies: [topEvent],
5591
    eventPriority: eventPriority
5592
  };
5593
  eventTypes[event] = config;
5594
  topLevelEventsToDispatchConfig[topEvent] = config;
5595
} // Only used in DEV for exhaustiveness validation.
5596
5597
5598
var knownHTMLTopLevelTypes = [TOP_ABORT, TOP_CANCEL, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_CLOSE, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_INPUT, TOP_INVALID, TOP_LOAD, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_RESET, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUBMIT, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_TOGGLE, TOP_VOLUME_CHANGE, TOP_WAITING];
5599
var SimpleEventPlugin = {
5600
  eventTypes: eventTypes,
5601
  getEventPriority: function (topLevelType) {
5602
    var config = topLevelEventsToDispatchConfig[topLevelType];
5603
    return config !== undefined ? config.eventPriority : ContinuousEvent;
5604
  },
5605
  extractEvents: function (topLevelType, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
5606
    var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
5607
5608
    if (!dispatchConfig) {
5609
      return null;
5610
    }
5611
5612
    var EventConstructor;
5613
5614
    switch (topLevelType) {
5615
      case TOP_KEY_PRESS:
5616
        // Firefox creates a keypress event for function keys too. This removes
5617
        // the unwanted keypress events. Enter is however both printable and
5618
        // non-printable. One would expect Tab to be as well (but it isn't).
5619
        if (getEventCharCode(nativeEvent) === 0) {
5620
          return null;
5621
        }
5622
5623
      /* falls through */
5624
5625
      case TOP_KEY_DOWN:
5626
      case TOP_KEY_UP:
5627
        EventConstructor = SyntheticKeyboardEvent;
5628
        break;
5629
5630
      case TOP_BLUR:
5631
      case TOP_FOCUS:
5632
        EventConstructor = SyntheticFocusEvent;
5633
        break;
5634
5635
      case TOP_CLICK:
5636
        // Firefox creates a click event on right mouse clicks. This removes the
5637
        // unwanted click events.
5638
        if (nativeEvent.button === 2) {
5639
          return null;
5640
        }
5641
5642
      /* falls through */
5643
5644
      case TOP_AUX_CLICK:
5645
      case TOP_DOUBLE_CLICK:
5646
      case TOP_MOUSE_DOWN:
5647
      case TOP_MOUSE_MOVE:
5648
      case TOP_MOUSE_UP: // TODO: Disabled elements should not respond to mouse events
5649
5650
      /* falls through */
5651
5652
      case TOP_MOUSE_OUT:
5653
      case TOP_MOUSE_OVER:
5654
      case TOP_CONTEXT_MENU:
5655
        EventConstructor = SyntheticMouseEvent;
5656
        break;
5657
5658
      case TOP_DRAG:
5659
      case TOP_DRAG_END:
5660
      case TOP_DRAG_ENTER:
5661
      case TOP_DRAG_EXIT:
5662
      case TOP_DRAG_LEAVE:
5663
      case TOP_DRAG_OVER:
5664
      case TOP_DRAG_START:
5665
      case TOP_DROP:
5666
        EventConstructor = SyntheticDragEvent;
5667
        break;
5668
5669
      case TOP_TOUCH_CANCEL:
5670
      case TOP_TOUCH_END:
5671
      case TOP_TOUCH_MOVE:
5672
      case TOP_TOUCH_START:
5673
        EventConstructor = SyntheticTouchEvent;
5674
        break;
5675
5676
      case TOP_ANIMATION_END:
5677
      case TOP_ANIMATION_ITERATION:
5678
      case TOP_ANIMATION_START:
5679
        EventConstructor = SyntheticAnimationEvent;
5680
        break;
5681
5682
      case TOP_TRANSITION_END:
5683
        EventConstructor = SyntheticTransitionEvent;
5684
        break;
5685
5686
      case TOP_SCROLL:
5687
        EventConstructor = SyntheticUIEvent;
5688
        break;
5689
5690
      case TOP_WHEEL:
5691
        EventConstructor = SyntheticWheelEvent;
5692
        break;
5693
5694
      case TOP_COPY:
5695
      case TOP_CUT:
5696
      case TOP_PASTE:
5697
        EventConstructor = SyntheticClipboardEvent;
5698
        break;
5699
5700
      case TOP_GOT_POINTER_CAPTURE:
5701
      case TOP_LOST_POINTER_CAPTURE:
5702
      case TOP_POINTER_CANCEL:
5703
      case TOP_POINTER_DOWN:
5704
      case TOP_POINTER_MOVE:
5705
      case TOP_POINTER_OUT:
5706
      case TOP_POINTER_OVER:
5707
      case TOP_POINTER_UP:
5708
        EventConstructor = SyntheticPointerEvent;
5709
        break;
5710
5711
      default:
5712
        {
5713
          if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {
5714
            warningWithoutStack$1(false, 'SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType);
5715
          }
5716
        } // HTML Events
5717
        // @see http://www.w3.org/TR/html5/index.html#events-0
5718
5719
5720
        EventConstructor = SyntheticEvent;
5721
        break;
5722
    }
5723
5724
    var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
5725
    accumulateTwoPhaseDispatches(event);
5726
    return event;
5727
  }
5728
};
5729
5730
var passiveBrowserEventsSupported = false; // Check if browser support events with passive listeners
5731
// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
5732
5733
if (enableFlareAPI && canUseDOM) {
5734
  try {
5735
    var options = {}; // $FlowFixMe: Ignore Flow complaining about needing a value
5736
5737
    Object.defineProperty(options, 'passive', {
5738
      get: function () {
5739
        passiveBrowserEventsSupported = true;
5740
      }
5741
    });
5742
    window.addEventListener('test', options, options);
5743
    window.removeEventListener('test', options, options);
5744
  } catch (e) {
5745
    passiveBrowserEventsSupported = false;
5746
  }
5747
}
5748
5749
// Intentionally not named imports because Rollup would use dynamic dispatch for
5750
// CommonJS interop named imports.
5751
var UserBlockingPriority$1 = Scheduler.unstable_UserBlockingPriority;
5752
var runWithPriority$1 = Scheduler.unstable_runWithPriority;
5753
var getEventPriority = SimpleEventPlugin.getEventPriority;
5754
var CALLBACK_BOOKKEEPING_POOL_SIZE = 10;
5755
var callbackBookkeepingPool = [];
5756
5757
/**
5758
 * Find the deepest React component completely containing the root of the
5759
 * passed-in instance (for use when entire React trees are nested within each
5760
 * other). If React trees are not nested, returns null.
5761
 */
5762
function findRootContainerNode(inst) {
5763
  if (inst.tag === HostRoot) {
5764
    return inst.stateNode.containerInfo;
5765
  } // TODO: It may be a good idea to cache this to prevent unnecessary DOM
5766
  // traversal, but caching is difficult to do correctly without using a
5767
  // mutation observer to listen for all DOM changes.
5768
5769
5770
  while (inst.return) {
5771
    inst = inst.return;
5772
  }
5773
5774
  if (inst.tag !== HostRoot) {
5775
    // This can happen if we're in a detached tree.
5776
    return null;
5777
  }
5778
5779
  return inst.stateNode.containerInfo;
5780
} // Used to store ancestor hierarchy in top level callback
5781
5782
5783
function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags) {
5784
  if (callbackBookkeepingPool.length) {
5785
    var instance = callbackBookkeepingPool.pop();
5786
    instance.topLevelType = topLevelType;
5787
    instance.eventSystemFlags = eventSystemFlags;
5788
    instance.nativeEvent = nativeEvent;
5789
    instance.targetInst = targetInst;
5790
    return instance;
5791
  }
5792
5793
  return {
5794
    topLevelType: topLevelType,
5795
    eventSystemFlags: eventSystemFlags,
5796
    nativeEvent: nativeEvent,
5797
    targetInst: targetInst,
5798
    ancestors: []
5799
  };
5800
}
5801
5802
function releaseTopLevelCallbackBookKeeping(instance) {
5803
  instance.topLevelType = null;
5804
  instance.nativeEvent = null;
5805
  instance.targetInst = null;
5806
  instance.ancestors.length = 0;
5807
5808
  if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) {
5809
    callbackBookkeepingPool.push(instance);
5810
  }
5811
}
5812
5813
function handleTopLevel(bookKeeping) {
5814
  var targetInst = bookKeeping.targetInst; // Loop through the hierarchy, in case there's any nested components.
5815
  // It's important that we build the array of ancestors before calling any
5816
  // event handlers, because event handlers can modify the DOM, leading to
5817
  // inconsistencies with ReactMount's node cache. See #1105.
5818
5819
  var ancestor = targetInst;
5820
5821
  do {
5822
    if (!ancestor) {
5823
      var ancestors = bookKeeping.ancestors;
5824
      ancestors.push(ancestor);
5825
      break;
5826
    }
5827
5828
    var root = findRootContainerNode(ancestor);
5829
5830
    if (!root) {
5831
      break;
5832
    }
5833
5834
    var tag = ancestor.tag;
5835
5836
    if (tag === HostComponent || tag === HostText) {
5837
      bookKeeping.ancestors.push(ancestor);
5838
    }
5839
5840
    ancestor = getClosestInstanceFromNode(root);
5841
  } while (ancestor);
5842
5843
  for (var i = 0; i < bookKeeping.ancestors.length; i++) {
5844
    targetInst = bookKeeping.ancestors[i];
5845
    var eventTarget = getEventTarget(bookKeeping.nativeEvent);
5846
    var topLevelType = bookKeeping.topLevelType;
5847
    var nativeEvent = bookKeeping.nativeEvent;
5848
    runExtractedPluginEventsInBatch(topLevelType, bookKeeping.eventSystemFlags, targetInst, nativeEvent, eventTarget);
5849
  }
5850
} // TODO: can we stop exporting these?
5851
5852
5853
var _enabled = true;
5854
function setEnabled(enabled) {
5855
  _enabled = !!enabled;
5856
}
5857
function isEnabled() {
5858
  return _enabled;
5859
}
5860
function trapBubbledEvent(topLevelType, element) {
5861
  trapEventForPluginEventSystem(element, topLevelType, false);
5862
}
5863
function trapCapturedEvent(topLevelType, element) {
5864
  trapEventForPluginEventSystem(element, topLevelType, true);
5865
}
5866
function trapEventForResponderEventSystem(element, topLevelType, passive) {
5867
  if (enableFlareAPI) {
5868
    var rawEventName = getRawEventName(topLevelType);
5869
    var eventFlags = RESPONDER_EVENT_SYSTEM; // If passive option is not supported, then the event will be
5870
    // active and not passive, but we flag it as using not being
5871
    // supported too. This way the responder event plugins know,
5872
    // and can provide polyfills if needed.
5873
5874
    if (passive) {
5875
      if (passiveBrowserEventsSupported) {
5876
        eventFlags |= IS_PASSIVE;
5877
      } else {
5878
        eventFlags |= IS_ACTIVE;
5879
        eventFlags |= PASSIVE_NOT_SUPPORTED;
5880
        passive = false;
5881
      }
5882
    } else {
5883
      eventFlags |= IS_ACTIVE;
5884
    } // Check if interactive and wrap in discreteUpdates
5885
5886
5887
    var listener = dispatchEvent.bind(null, topLevelType, eventFlags);
5888
5889
    if (passiveBrowserEventsSupported) {
5890
      addEventCaptureListenerWithPassiveFlag(element, rawEventName, listener, passive);
5891
    } else {
5892
      addEventCaptureListener(element, rawEventName, listener);
5893
    }
5894
  }
5895
}
5896
5897
function trapEventForPluginEventSystem(element, topLevelType, capture) {
5898
  var listener;
5899
5900
  switch (getEventPriority(topLevelType)) {
5901
    case DiscreteEvent:
5902
      listener = dispatchDiscreteEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
5903
      break;
5904
5905
    case UserBlockingEvent:
5906
      listener = dispatchUserBlockingUpdate.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
5907
      break;
5908
5909
    case ContinuousEvent:
5910
    default:
5911
      listener = dispatchEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
5912
      break;
5913
  }
5914
5915
  var rawEventName = getRawEventName(topLevelType);
5916
5917
  if (capture) {
5918
    addEventCaptureListener(element, rawEventName, listener);
5919
  } else {
5920
    addEventBubbleListener(element, rawEventName, listener);
5921
  }
5922
}
5923
5924
function dispatchDiscreteEvent(topLevelType, eventSystemFlags, nativeEvent) {
5925
  flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp);
5926
  discreteUpdates(dispatchEvent, topLevelType, eventSystemFlags, nativeEvent);
5927
}
5928
5929
function dispatchUserBlockingUpdate(topLevelType, eventSystemFlags, nativeEvent) {
5930
  if (enableUserBlockingEvents) {
5931
    runWithPriority$1(UserBlockingPriority$1, dispatchEvent.bind(null, topLevelType, eventSystemFlags, nativeEvent));
5932
  } else {
5933
    dispatchEvent(topLevelType, eventSystemFlags, nativeEvent);
5934
  }
5935
}
5936
5937
function dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst) {
5938
  var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags);
5939
5940
  try {
5941
    // Event queue being processed in the same cycle allows
5942
    // `preventDefault`.
5943
    batchedEventUpdates(handleTopLevel, bookKeeping);
5944
  } finally {
5945
    releaseTopLevelCallbackBookKeeping(bookKeeping);
5946
  }
5947
}
5948
5949
function dispatchEvent(topLevelType, eventSystemFlags, nativeEvent) {
5950
  if (!_enabled) {
5951
    return;
5952
  }
5953
5954
  if (hasQueuedDiscreteEvents() && isReplayableDiscreteEvent(topLevelType)) {
5955
    // If we already have a queue of discrete events, and this is another discrete
5956
    // event, then we can't dispatch it regardless of its target, since they
5957
    // need to dispatch in order.
5958
    queueDiscreteEvent(null, // Flags that we're not actually blocked on anything as far as we know.
5959
    topLevelType, eventSystemFlags, nativeEvent);
5960
    return;
5961
  }
5962
5963
  var blockedOn = attemptToDispatchEvent(topLevelType, eventSystemFlags, nativeEvent);
5964
5965
  if (blockedOn === null) {
5966
    // We successfully dispatched this event.
5967
    clearIfContinuousEvent(topLevelType, nativeEvent);
5968
    return;
5969
  }
5970
5971
  if (isReplayableDiscreteEvent(topLevelType)) {
5972
    // This this to be replayed later once the target is available.
5973
    queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent);
5974
    return;
5975
  }
5976
5977
  if (queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent)) {
5978
    return;
5979
  } // We need to clear only if we didn't queue because
5980
  // queueing is accummulative.
5981
5982
5983
  clearIfContinuousEvent(topLevelType, nativeEvent); // This is not replayable so we'll invoke it but without a target,
5984
  // in case the event system needs to trace it.
5985
5986
  if (enableFlareAPI) {
5987
    if (eventSystemFlags & PLUGIN_EVENT_SYSTEM) {
5988
      dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, null);
5989
    }
5990
5991
    if (eventSystemFlags & RESPONDER_EVENT_SYSTEM) {
5992
      // React Flare event system
5993
      dispatchEventForResponderEventSystem(topLevelType, null, nativeEvent, getEventTarget(nativeEvent), eventSystemFlags);
5994
    }
5995
  } else {
5996
    dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, null);
5997
  }
5998
} // Attempt dispatching an event. Returns a SuspenseInstance or Container if it's blocked.
5999
6000
function attemptToDispatchEvent(topLevelType, eventSystemFlags, nativeEvent) {
6001
  // TODO: Warn if _enabled is false.
6002
  var nativeEventTarget = getEventTarget(nativeEvent);
6003
  var targetInst = getClosestInstanceFromNode(nativeEventTarget);
6004
6005
  if (targetInst !== null) {
6006
    var nearestMounted = getNearestMountedFiber(targetInst);
6007
6008
    if (nearestMounted === null) {
6009
      // This tree has been unmounted already. Dispatch without a target.
6010
      targetInst = null;
6011
    } else {
6012
      var tag = nearestMounted.tag;
6013
6014
      if (tag === SuspenseComponent) {
6015
        var instance = getSuspenseInstanceFromFiber(nearestMounted);
6016
6017
        if (instance !== null) {
6018
          // Queue the event to be replayed later. Abort dispatching since we
6019
          // don't want this event dispatched twice through the event system.
6020
          // TODO: If this is the first discrete event in the queue. Schedule an increased
6021
          // priority for this boundary.
6022
          return instance;
6023
        } // This shouldn't happen, something went wrong but to avoid blocking
6024
        // the whole system, dispatch the event without a target.
6025
        // TODO: Warn.
6026
6027
6028
        targetInst = null;
6029
      } else if (tag === HostRoot) {
6030
        var root = nearestMounted.stateNode;
6031
6032
        if (root.hydrate) {
6033
          // If this happens during a replay something went wrong and it might block
6034
          // the whole system.
6035
          return getContainerFromFiber(nearestMounted);
6036
        }
6037
6038
        targetInst = null;
6039
      } else if (nearestMounted !== targetInst) {
6040
        // If we get an event (ex: img onload) before committing that
6041
        // component's mount, ignore it for now (that is, treat it as if it was an
6042
        // event on a non-React tree). We might also consider queueing events and
6043
        // dispatching them after the mount.
6044
        targetInst = null;
6045
      }
6046
    }
6047
  }
6048
6049
  if (enableFlareAPI) {
6050
    if (eventSystemFlags & PLUGIN_EVENT_SYSTEM) {
6051
      dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst);
6052
    }
6053
6054
    if (eventSystemFlags & RESPONDER_EVENT_SYSTEM) {
6055
      // React Flare event system
6056
      dispatchEventForResponderEventSystem(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
6057
    }
6058
  } else {
6059
    dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst);
6060
  } // We're not blocked on anything.
6061
6062
6063
  return null;
6064
}
6065
6066
/**
6067
 * Checks if an event is supported in the current execution environment.
6068
 *
6069
 * NOTE: This will not work correctly for non-generic events such as `change`,
6070
 * `reset`, `load`, `error`, and `select`.
6071
 *
6072
 * Borrows from Modernizr.
6073
 *
6074
 * @param {string} eventNameSuffix Event name, e.g. "click".
6075
 * @return {boolean} True if the event is supported.
6076
 * @internal
6077
 * @license Modernizr 3.0.0pre (Custom Build) | MIT
6078
 */
6079
6080
function isEventSupported(eventNameSuffix) {
6081
  if (!canUseDOM) {
6082
    return false;
6083
  }
6084
6085
  var eventName = 'on' + eventNameSuffix;
6086
  var isSupported = eventName in document;
6087
6088
  if (!isSupported) {
6089
    var element = document.createElement('div');
6090
    element.setAttribute(eventName, 'return;');
6091
    isSupported = typeof element[eventName] === 'function';
6092
  }
6093
6094
  return isSupported;
6095
}
6096
6097
/**
6098
 * Summary of `ReactBrowserEventEmitter` event handling:
6099
 *
6100
 *  - Top-level delegation is used to trap most native browser events. This
6101
 *    may only occur in the main thread and is the responsibility of
6102
 *    ReactDOMEventListener, which is injected and can therefore support
6103
 *    pluggable event sources. This is the only work that occurs in the main
6104
 *    thread.
6105
 *
6106
 *  - We normalize and de-duplicate events to account for browser quirks. This
6107
 *    may be done in the worker thread.
6108
 *
6109
 *  - Forward these native events (with the associated top-level type used to
6110
 *    trap it) to `EventPluginHub`, which in turn will ask plugins if they want
6111
 *    to extract any synthetic events.
6112
 *
6113
 *  - The `EventPluginHub` will then process each event by annotating them with
6114
 *    "dispatches", a sequence of listeners and IDs that care about that event.
6115
 *
6116
 *  - The `EventPluginHub` then dispatches the events.
6117
 *
6118
 * Overview of React and the event system:
6119
 *
6120
 * +------------+    .
6121
 * |    DOM     |    .
6122
 * +------------+    .
6123
 *       |           .
6124
 *       v           .
6125
 * +------------+    .
6126
 * | ReactEvent |    .
6127
 * |  Listener  |    .
6128
 * +------------+    .                         +-----------+
6129
 *       |           .               +--------+|SimpleEvent|
6130
 *       |           .               |         |Plugin     |
6131
 * +-----|------+    .               v         +-----------+
6132
 * |     |      |    .    +--------------+                    +------------+
6133
 * |     +-----------.--->|EventPluginHub|                    |    Event   |
6134
 * |            |    .    |              |     +-----------+  | Propagators|
6135
 * | ReactEvent |    .    |              |     |TapEvent   |  |------------|
6136
 * |  Emitter   |    .    |              |<---+|Plugin     |  |other plugin|
6137
 * |            |    .    |              |     +-----------+  |  utilities |
6138
 * |     +-----------.--->|              |                    +------------+
6139
 * |     |      |    .    +--------------+
6140
 * +-----|------+    .                ^        +-----------+
6141
 *       |           .                |        |Enter/Leave|
6142
 *       +           .                +-------+|Plugin     |
6143
 * +-------------+   .                         +-----------+
6144
 * | application |   .
6145
 * |-------------|   .
6146
 * |             |   .
6147
 * |             |   .
6148
 * +-------------+   .
6149
 *                   .
6150
 *    React Core     .  General Purpose Event Plugin System
6151
 */
6152
6153
var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
6154
var elementListeningSets = new PossiblyWeakMap();
6155
function getListeningSetForElement(element) {
6156
  var listeningSet = elementListeningSets.get(element);
6157
6158
  if (listeningSet === undefined) {
6159
    listeningSet = new Set();
6160
    elementListeningSets.set(element, listeningSet);
6161
  }
6162
6163
  return listeningSet;
6164
}
6165
/**
6166
 * We listen for bubbled touch events on the document object.
6167
 *
6168
 * Firefox v8.01 (and possibly others) exhibited strange behavior when
6169
 * mounting `onmousemove` events at some node that was not the document
6170
 * element. The symptoms were that if your mouse is not moving over something
6171
 * contained within that mount point (for example on the background) the
6172
 * top-level listeners for `onmousemove` won't be called. However, if you
6173
 * register the `mousemove` on the document object, then it will of course
6174
 * catch all `mousemove`s. This along with iOS quirks, justifies restricting
6175
 * top-level listeners to the document object only, at least for these
6176
 * movement types of events and possibly all events.
6177
 *
6178
 * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
6179
 *
6180
 * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
6181
 * they bubble to document.
6182
 *
6183
 * @param {string} registrationName Name of listener (e.g. `onClick`).
6184
 * @param {object} mountAt Container where to mount the listener
6185
 */
6186
6187
function listenTo(registrationName, mountAt) {
6188
  var listeningSet = getListeningSetForElement(mountAt);
6189
  var dependencies = registrationNameDependencies[registrationName];
6190
6191
  for (var i = 0; i < dependencies.length; i++) {
6192
    var dependency = dependencies[i];
6193
    listenToTopLevel(dependency, mountAt, listeningSet);
6194
  }
6195
}
6196
function listenToTopLevel(topLevelType, mountAt, listeningSet) {
6197
  if (!listeningSet.has(topLevelType)) {
6198
    switch (topLevelType) {
6199
      case TOP_SCROLL:
6200
        trapCapturedEvent(TOP_SCROLL, mountAt);
6201
        break;
6202
6203
      case TOP_FOCUS:
6204
      case TOP_BLUR:
6205
        trapCapturedEvent(TOP_FOCUS, mountAt);
6206
        trapCapturedEvent(TOP_BLUR, mountAt); // We set the flag for a single dependency later in this function,
6207
        // but this ensures we mark both as attached rather than just one.
6208
6209
        listeningSet.add(TOP_BLUR);
6210
        listeningSet.add(TOP_FOCUS);
6211
        break;
6212
6213
      case TOP_CANCEL:
6214
      case TOP_CLOSE:
6215
        if (isEventSupported(getRawEventName(topLevelType))) {
6216
          trapCapturedEvent(topLevelType, mountAt);
6217
        }
6218
6219
        break;
6220
6221
      case TOP_INVALID:
6222
      case TOP_SUBMIT:
6223
      case TOP_RESET:
6224
        // We listen to them on the target DOM elements.
6225
        // Some of them bubble so we don't want them to fire twice.
6226
        break;
6227
6228
      default:
6229
        // By default, listen on the top level to all non-media events.
6230
        // Media events don't bubble so adding the listener wouldn't do anything.
6231
        var isMediaEvent = mediaEventTypes.indexOf(topLevelType) !== -1;
6232
6233
        if (!isMediaEvent) {
6234
          trapBubbledEvent(topLevelType, mountAt);
6235
        }
6236
6237
        break;
6238
    }
6239
6240
    listeningSet.add(topLevelType);
6241
  }
6242
}
6243
function isListeningToAllDependencies(registrationName, mountAt) {
6244
  var listeningSet = getListeningSetForElement(mountAt);
6245
  var dependencies = registrationNameDependencies[registrationName];
6246
6247
  for (var i = 0; i < dependencies.length; i++) {
6248
    var dependency = dependencies[i];
6249
6250
    if (!listeningSet.has(dependency)) {
6251
      return false;
6252
    }
6253
  }
6254
6255
  return true;
6256
}
6257
6258
// List derived from Gecko source code:
6259
// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
6260
var shorthandToLonghand = {
6261
  animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
6262
  background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
6263
  backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
6264
  border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6265
  borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
6266
  borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
6267
  borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
6268
  borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
6269
  borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
6270
  borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
6271
  borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
6272
  borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
6273
  borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
6274
  borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
6275
  borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
6276
  borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6277
  borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
6278
  columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
6279
  columns: ['columnCount', 'columnWidth'],
6280
  flex: ['flexBasis', 'flexGrow', 'flexShrink'],
6281
  flexFlow: ['flexDirection', 'flexWrap'],
6282
  font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
6283
  fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
6284
  gap: ['columnGap', 'rowGap'],
6285
  grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6286
  gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
6287
  gridColumn: ['gridColumnEnd', 'gridColumnStart'],
6288
  gridColumnGap: ['columnGap'],
6289
  gridGap: ['columnGap', 'rowGap'],
6290
  gridRow: ['gridRowEnd', 'gridRowStart'],
6291
  gridRowGap: ['rowGap'],
6292
  gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6293
  listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
6294
  margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
6295
  marker: ['markerEnd', 'markerMid', 'markerStart'],
6296
  mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
6297
  maskPosition: ['maskPositionX', 'maskPositionY'],
6298
  outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
6299
  overflow: ['overflowX', 'overflowY'],
6300
  padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
6301
  placeContent: ['alignContent', 'justifyContent'],
6302
  placeItems: ['alignItems', 'justifyItems'],
6303
  placeSelf: ['alignSelf', 'justifySelf'],
6304
  textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
6305
  textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
6306
  transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
6307
  wordWrap: ['overflowWrap']
6308
};
6309
6310
/**
6311
 * CSS properties which accept numbers but are not in units of "px".
6312
 */
6313
var isUnitlessNumber = {
6314
  animationIterationCount: true,
6315
  borderImageOutset: true,
6316
  borderImageSlice: true,
6317
  borderImageWidth: true,
6318
  boxFlex: true,
6319
  boxFlexGroup: true,
6320
  boxOrdinalGroup: true,
6321
  columnCount: true,
6322
  columns: true,
6323
  flex: true,
6324
  flexGrow: true,
6325
  flexPositive: true,
6326
  flexShrink: true,
6327
  flexNegative: true,
6328
  flexOrder: true,
6329
  gridArea: true,
6330
  gridRow: true,
6331
  gridRowEnd: true,
6332
  gridRowSpan: true,
6333
  gridRowStart: true,
6334
  gridColumn: true,
6335
  gridColumnEnd: true,
6336
  gridColumnSpan: true,
6337
  gridColumnStart: true,
6338
  fontWeight: true,
6339
  lineClamp: true,
6340
  lineHeight: true,
6341
  opacity: true,
6342
  order: true,
6343
  orphans: true,
6344
  tabSize: true,
6345
  widows: true,
6346
  zIndex: true,
6347
  zoom: true,
6348
  // SVG-related properties
6349
  fillOpacity: true,
6350
  floodOpacity: true,
6351
  stopOpacity: true,
6352
  strokeDasharray: true,
6353
  strokeDashoffset: true,
6354
  strokeMiterlimit: true,
6355
  strokeOpacity: true,
6356
  strokeWidth: true
6357
};
6358
/**
6359
 * @param {string} prefix vendor-specific prefix, eg: Webkit
6360
 * @param {string} key style name, eg: transitionDuration
6361
 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
6362
 * WebkitTransitionDuration
6363
 */
6364
6365
function prefixKey(prefix, key) {
6366
  return prefix + key.charAt(0).toUpperCase() + key.substring(1);
6367
}
6368
/**
6369
 * Support style names that may come passed in prefixed by adding permutations
6370
 * of vendor prefixes.
6371
 */
6372
6373
6374
var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
6375
// infinite loop, because it iterates over the newly added props too.
6376
6377
Object.keys(isUnitlessNumber).forEach(function (prop) {
6378
  prefixes.forEach(function (prefix) {
6379
    isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
6380
  });
6381
});
6382
6383
/**
6384
 * Convert a value into the proper css writable value. The style name `name`
6385
 * should be logical (no hyphens), as specified
6386
 * in `CSSProperty.isUnitlessNumber`.
6387
 *
6388
 * @param {string} name CSS property name such as `topMargin`.
6389
 * @param {*} value CSS property value such as `10px`.
6390
 * @return {string} Normalized style value with dimensions applied.
6391
 */
6392
6393
function dangerousStyleValue(name, value, isCustomProperty) {
6394
  // Note that we've removed escapeTextForBrowser() calls here since the
6395
  // whole string will be escaped when the attribute is injected into
6396
  // the markup. If you provide unsafe user data here they can inject
6397
  // arbitrary CSS which may be problematic (I couldn't repro this):
6398
  // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
6399
  // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
6400
  // This is not an XSS hole but instead a potential CSS injection issue
6401
  // which has lead to a greater discussion about how we're going to
6402
  // trust URLs moving forward. See #2115901
6403
  var isEmpty = value == null || typeof value === 'boolean' || value === '';
6404
6405
  if (isEmpty) {
6406
    return '';
6407
  }
6408
6409
  if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
6410
    return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
6411
  }
6412
6413
  return ('' + value).trim();
6414
}
6415
6416
var uppercasePattern = /([A-Z])/g;
6417
var msPattern = /^ms-/;
6418
/**
6419
 * Hyphenates a camelcased CSS property name, for example:
6420
 *
6421
 *   > hyphenateStyleName('backgroundColor')
6422
 *   < "background-color"
6423
 *   > hyphenateStyleName('MozTransition')
6424
 *   < "-moz-transition"
6425
 *   > hyphenateStyleName('msTransition')
6426
 *   < "-ms-transition"
6427
 *
6428
 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
6429
 * is converted to `-ms-`.
6430
 */
6431
6432
function hyphenateStyleName(name) {
6433
  return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
6434
}
6435
6436
var warnValidStyle = function () {};
6437
6438
{
6439
  // 'msTransform' is correct, but the other prefixes should be capitalized
6440
  var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
6441
  var msPattern$1 = /^-ms-/;
6442
  var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon
6443
6444
  var badStyleValueWithSemicolonPattern = /;\s*$/;
6445
  var warnedStyleNames = {};
6446
  var warnedStyleValues = {};
6447
  var warnedForNaNValue = false;
6448
  var warnedForInfinityValue = false;
6449
6450
  var camelize = function (string) {
6451
    return string.replace(hyphenPattern, function (_, character) {
6452
      return character.toUpperCase();
6453
    });
6454
  };
6455
6456
  var warnHyphenatedStyleName = function (name) {
6457
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6458
      return;
6459
    }
6460
6461
    warnedStyleNames[name] = true;
6462
    warning$1(false, 'Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
6463
    // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
6464
    // is converted to lowercase `ms`.
6465
    camelize(name.replace(msPattern$1, 'ms-')));
6466
  };
6467
6468
  var warnBadVendoredStyleName = function (name) {
6469
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6470
      return;
6471
    }
6472
6473
    warnedStyleNames[name] = true;
6474
    warning$1(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
6475
  };
6476
6477
  var warnStyleValueWithSemicolon = function (name, value) {
6478
    if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
6479
      return;
6480
    }
6481
6482
    warnedStyleValues[value] = true;
6483
    warning$1(false, "Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
6484
  };
6485
6486
  var warnStyleValueIsNaN = function (name, value) {
6487
    if (warnedForNaNValue) {
6488
      return;
6489
    }
6490
6491
    warnedForNaNValue = true;
6492
    warning$1(false, '`NaN` is an invalid value for the `%s` css style property.', name);
6493
  };
6494
6495
  var warnStyleValueIsInfinity = function (name, value) {
6496
    if (warnedForInfinityValue) {
6497
      return;
6498
    }
6499
6500
    warnedForInfinityValue = true;
6501
    warning$1(false, '`Infinity` is an invalid value for the `%s` css style property.', name);
6502
  };
6503
6504
  warnValidStyle = function (name, value) {
6505
    if (name.indexOf('-') > -1) {
6506
      warnHyphenatedStyleName(name);
6507
    } else if (badVendoredStyleNamePattern.test(name)) {
6508
      warnBadVendoredStyleName(name);
6509
    } else if (badStyleValueWithSemicolonPattern.test(value)) {
6510
      warnStyleValueWithSemicolon(name, value);
6511
    }
6512
6513
    if (typeof value === 'number') {
6514
      if (isNaN(value)) {
6515
        warnStyleValueIsNaN(name, value);
6516
      } else if (!isFinite(value)) {
6517
        warnStyleValueIsInfinity(name, value);
6518
      }
6519
    }
6520
  };
6521
}
6522
6523
var warnValidStyle$1 = warnValidStyle;
6524
6525
/**
6526
 * Operations for dealing with CSS properties.
6527
 */
6528
6529
/**
6530
 * This creates a string that is expected to be equivalent to the style
6531
 * attribute generated by server-side rendering. It by-passes warnings and
6532
 * security checks so it's not safe to use this value for anything other than
6533
 * comparison. It is only used in DEV for SSR validation.
6534
 */
6535
6536
function createDangerousStringForStyles(styles) {
6537
  {
6538
    var serialized = '';
6539
    var delimiter = '';
6540
6541
    for (var styleName in styles) {
6542
      if (!styles.hasOwnProperty(styleName)) {
6543
        continue;
6544
      }
6545
6546
      var styleValue = styles[styleName];
6547
6548
      if (styleValue != null) {
6549
        var isCustomProperty = styleName.indexOf('--') === 0;
6550
        serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':';
6551
        serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
6552
        delimiter = ';';
6553
      }
6554
    }
6555
6556
    return serialized || null;
6557
  }
6558
}
6559
/**
6560
 * Sets the value for multiple styles on a node.  If a value is specified as
6561
 * '' (empty string), the corresponding style property will be unset.
6562
 *
6563
 * @param {DOMElement} node
6564
 * @param {object} styles
6565
 */
6566
6567
function setValueForStyles(node, styles) {
6568
  var style = node.style;
6569
6570
  for (var styleName in styles) {
6571
    if (!styles.hasOwnProperty(styleName)) {
6572
      continue;
6573
    }
6574
6575
    var isCustomProperty = styleName.indexOf('--') === 0;
6576
6577
    {
6578
      if (!isCustomProperty) {
6579
        warnValidStyle$1(styleName, styles[styleName]);
6580
      }
6581
    }
6582
6583
    var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
6584
6585
    if (styleName === 'float') {
6586
      styleName = 'cssFloat';
6587
    }
6588
6589
    if (isCustomProperty) {
6590
      style.setProperty(styleName, styleValue);
6591
    } else {
6592
      style[styleName] = styleValue;
6593
    }
6594
  }
6595
}
6596
6597
function isValueEmpty(value) {
6598
  return value == null || typeof value === 'boolean' || value === '';
6599
}
6600
/**
6601
 * Given {color: 'red', overflow: 'hidden'} returns {
6602
 *   color: 'color',
6603
 *   overflowX: 'overflow',
6604
 *   overflowY: 'overflow',
6605
 * }. This can be read as "the overflowY property was set by the overflow
6606
 * shorthand". That is, the values are the property that each was derived from.
6607
 */
6608
6609
6610
function expandShorthandMap(styles) {
6611
  var expanded = {};
6612
6613
  for (var key in styles) {
6614
    var longhands = shorthandToLonghand[key] || [key];
6615
6616
    for (var i = 0; i < longhands.length; i++) {
6617
      expanded[longhands[i]] = key;
6618
    }
6619
  }
6620
6621
  return expanded;
6622
}
6623
/**
6624
 * When mixing shorthand and longhand property names, we warn during updates if
6625
 * we expect an incorrect result to occur. In particular, we warn for:
6626
 *
6627
 * Updating a shorthand property (longhand gets overwritten):
6628
 *   {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
6629
 *   becomes .style.font = 'baz'
6630
 * Removing a shorthand property (longhand gets lost too):
6631
 *   {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
6632
 *   becomes .style.font = ''
6633
 * Removing a longhand property (should revert to shorthand; doesn't):
6634
 *   {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
6635
 *   becomes .style.fontVariant = ''
6636
 */
6637
6638
6639
function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
6640
  if (!warnAboutShorthandPropertyCollision) {
6641
    return;
6642
  }
6643
6644
  if (!nextStyles) {
6645
    return;
6646
  }
6647
6648
  var expandedUpdates = expandShorthandMap(styleUpdates);
6649
  var expandedStyles = expandShorthandMap(nextStyles);
6650
  var warnedAbout = {};
6651
6652
  for (var key in expandedUpdates) {
6653
    var originalKey = expandedUpdates[key];
6654
    var correctOriginalKey = expandedStyles[key];
6655
6656
    if (correctOriginalKey && originalKey !== correctOriginalKey) {
6657
      var warningKey = originalKey + ',' + correctOriginalKey;
6658
6659
      if (warnedAbout[warningKey]) {
6660
        continue;
6661
      }
6662
6663
      warnedAbout[warningKey] = true;
6664
      warning$1(false, '%s a style property during rerender (%s) when a ' + 'conflicting property is set (%s) can lead to styling bugs. To ' + "avoid this, don't mix shorthand and non-shorthand properties " + 'for the same value; instead, replace the shorthand with ' + 'separate values.', isValueEmpty(styleUpdates[originalKey]) ? 'Removing' : 'Updating', originalKey, correctOriginalKey);
6665
    }
6666
  }
6667
}
6668
6669
// For HTML, certain tags should omit their close tag. We keep a whitelist for
6670
// those special-case tags.
6671
var omittedCloseTags = {
6672
  area: true,
6673
  base: true,
6674
  br: true,
6675
  col: true,
6676
  embed: true,
6677
  hr: true,
6678
  img: true,
6679
  input: true,
6680
  keygen: true,
6681
  link: true,
6682
  meta: true,
6683
  param: true,
6684
  source: true,
6685
  track: true,
6686
  wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems.
6687
6688
};
6689
6690
// `omittedCloseTags` except that `menuitem` should still have its closing tag.
6691
6692
var voidElementTags = _assign({
6693
  menuitem: true
6694
}, omittedCloseTags);
6695
6696
// or add stack by default to invariants where possible.
6697
6698
var HTML$1 = '__html';
6699
var ReactDebugCurrentFrame$3 = null;
6700
6701
{
6702
  ReactDebugCurrentFrame$3 = ReactSharedInternals.ReactDebugCurrentFrame;
6703
}
6704
6705
function assertValidProps(tag, props) {
6706
  if (!props) {
6707
    return;
6708
  } // Note the use of `==` which checks for null or undefined.
6709
6710
6711
  if (voidElementTags[tag]) {
6712
    (function () {
6713
      if (!(props.children == null && props.dangerouslySetInnerHTML == null)) {
6714
        {
6715
          throw ReactError(Error(tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`." + (ReactDebugCurrentFrame$3.getStackAddendum())));
6716
        }
6717
      }
6718
    })();
6719
  }
6720
6721
  if (props.dangerouslySetInnerHTML != null) {
6722
    (function () {
6723
      if (!(props.children == null)) {
6724
        {
6725
          throw ReactError(Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`."));
6726
        }
6727
      }
6728
    })();
6729
6730
    (function () {
6731
      if (!(typeof props.dangerouslySetInnerHTML === 'object' && HTML$1 in props.dangerouslySetInnerHTML)) {
6732
        {
6733
          throw ReactError(Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information."));
6734
        }
6735
      }
6736
    })();
6737
  }
6738
6739
  {
6740
    !(props.suppressContentEditableWarning || !props.contentEditable || props.children == null) ? warning$1(false, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : void 0;
6741
  }
6742
6743
  (function () {
6744
    if (!(props.style == null || typeof props.style === 'object')) {
6745
      {
6746
        throw ReactError(Error("The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX." + (ReactDebugCurrentFrame$3.getStackAddendum())));
6747
      }
6748
    }
6749
  })();
6750
}
6751
6752
function isCustomComponent(tagName, props) {
6753
  if (tagName.indexOf('-') === -1) {
6754
    return typeof props.is === 'string';
6755
  }
6756
6757
  switch (tagName) {
6758
    // These are reserved SVG and MathML elements.
6759
    // We don't mind this whitelist too much because we expect it to never grow.
6760
    // The alternative is to track the namespace in a few places which is convoluted.
6761
    // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
6762
    case 'annotation-xml':
6763
    case 'color-profile':
6764
    case 'font-face':
6765
    case 'font-face-src':
6766
    case 'font-face-uri':
6767
    case 'font-face-format':
6768
    case 'font-face-name':
6769
    case 'missing-glyph':
6770
      return false;
6771
6772
    default:
6773
      return true;
6774
  }
6775
}
6776
6777
// When adding attributes to the HTML or SVG whitelist, be sure to
6778
// also add them to this module to ensure casing and incorrect name
6779
// warnings.
6780
var possibleStandardNames = {
6781
  // HTML
6782
  accept: 'accept',
6783
  acceptcharset: 'acceptCharset',
6784
  'accept-charset': 'acceptCharset',
6785
  accesskey: 'accessKey',
6786
  action: 'action',
6787
  allowfullscreen: 'allowFullScreen',
6788
  alt: 'alt',
6789
  as: 'as',
6790
  async: 'async',
6791
  autocapitalize: 'autoCapitalize',
6792
  autocomplete: 'autoComplete',
6793
  autocorrect: 'autoCorrect',
6794
  autofocus: 'autoFocus',
6795
  autoplay: 'autoPlay',
6796
  autosave: 'autoSave',
6797
  capture: 'capture',
6798
  cellpadding: 'cellPadding',
6799
  cellspacing: 'cellSpacing',
6800
  challenge: 'challenge',
6801
  charset: 'charSet',
6802
  checked: 'checked',
6803
  children: 'children',
6804
  cite: 'cite',
6805
  class: 'className',
6806
  classid: 'classID',
6807
  classname: 'className',
6808
  cols: 'cols',
6809
  colspan: 'colSpan',
6810
  content: 'content',
6811
  contenteditable: 'contentEditable',
6812
  contextmenu: 'contextMenu',
6813
  controls: 'controls',
6814
  controlslist: 'controlsList',
6815
  coords: 'coords',
6816
  crossorigin: 'crossOrigin',
6817
  dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
6818
  data: 'data',
6819
  datetime: 'dateTime',
6820
  default: 'default',
6821
  defaultchecked: 'defaultChecked',
6822
  defaultvalue: 'defaultValue',
6823
  defer: 'defer',
6824
  dir: 'dir',
6825
  disabled: 'disabled',
6826
  disablepictureinpicture: 'disablePictureInPicture',
6827
  download: 'download',
6828
  draggable: 'draggable',
6829
  enctype: 'encType',
6830
  for: 'htmlFor',
6831
  form: 'form',
6832
  formmethod: 'formMethod',
6833
  formaction: 'formAction',
6834
  formenctype: 'formEncType',
6835
  formnovalidate: 'formNoValidate',
6836
  formtarget: 'formTarget',
6837
  frameborder: 'frameBorder',
6838
  headers: 'headers',
6839
  height: 'height',
6840
  hidden: 'hidden',
6841
  high: 'high',
6842
  href: 'href',
6843
  hreflang: 'hrefLang',
6844
  htmlfor: 'htmlFor',
6845
  httpequiv: 'httpEquiv',
6846
  'http-equiv': 'httpEquiv',
6847
  icon: 'icon',
6848
  id: 'id',
6849
  innerhtml: 'innerHTML',
6850
  inputmode: 'inputMode',
6851
  integrity: 'integrity',
6852
  is: 'is',
6853
  itemid: 'itemID',
6854
  itemprop: 'itemProp',
6855
  itemref: 'itemRef',
6856
  itemscope: 'itemScope',
6857
  itemtype: 'itemType',
6858
  keyparams: 'keyParams',
6859
  keytype: 'keyType',
6860
  kind: 'kind',
6861
  label: 'label',
6862
  lang: 'lang',
6863
  list: 'list',
6864
  loop: 'loop',
6865
  low: 'low',
6866
  manifest: 'manifest',
6867
  marginwidth: 'marginWidth',
6868
  marginheight: 'marginHeight',
6869
  max: 'max',
6870
  maxlength: 'maxLength',
6871
  media: 'media',
6872
  mediagroup: 'mediaGroup',
6873
  method: 'method',
6874
  min: 'min',
6875
  minlength: 'minLength',
6876
  multiple: 'multiple',
6877
  muted: 'muted',
6878
  name: 'name',
6879
  nomodule: 'noModule',
6880
  nonce: 'nonce',
6881
  novalidate: 'noValidate',
6882
  open: 'open',
6883
  optimum: 'optimum',
6884
  pattern: 'pattern',
6885
  placeholder: 'placeholder',
6886
  playsinline: 'playsInline',
6887
  poster: 'poster',
6888
  preload: 'preload',
6889
  profile: 'profile',
6890
  radiogroup: 'radioGroup',
6891
  readonly: 'readOnly',
6892
  referrerpolicy: 'referrerPolicy',
6893
  rel: 'rel',
6894
  required: 'required',
6895
  reversed: 'reversed',
6896
  role: 'role',
6897
  rows: 'rows',
6898
  rowspan: 'rowSpan',
6899
  sandbox: 'sandbox',
6900
  scope: 'scope',
6901
  scoped: 'scoped',
6902
  scrolling: 'scrolling',
6903
  seamless: 'seamless',
6904
  selected: 'selected',
6905
  shape: 'shape',
6906
  size: 'size',
6907
  sizes: 'sizes',
6908
  span: 'span',
6909
  spellcheck: 'spellCheck',
6910
  src: 'src',
6911
  srcdoc: 'srcDoc',
6912
  srclang: 'srcLang',
6913
  srcset: 'srcSet',
6914
  start: 'start',
6915
  step: 'step',
6916
  style: 'style',
6917
  summary: 'summary',
6918
  tabindex: 'tabIndex',
6919
  target: 'target',
6920
  title: 'title',
6921
  type: 'type',
6922
  usemap: 'useMap',
6923
  value: 'value',
6924
  width: 'width',
6925
  wmode: 'wmode',
6926
  wrap: 'wrap',
6927
  // SVG
6928
  about: 'about',
6929
  accentheight: 'accentHeight',
6930
  'accent-height': 'accentHeight',
6931
  accumulate: 'accumulate',
6932
  additive: 'additive',
6933
  alignmentbaseline: 'alignmentBaseline',
6934
  'alignment-baseline': 'alignmentBaseline',
6935
  allowreorder: 'allowReorder',
6936
  alphabetic: 'alphabetic',
6937
  amplitude: 'amplitude',
6938
  arabicform: 'arabicForm',
6939
  'arabic-form': 'arabicForm',
6940
  ascent: 'ascent',
6941
  attributename: 'attributeName',
6942
  attributetype: 'attributeType',
6943
  autoreverse: 'autoReverse',
6944
  azimuth: 'azimuth',
6945
  basefrequency: 'baseFrequency',
6946
  baselineshift: 'baselineShift',
6947
  'baseline-shift': 'baselineShift',
6948
  baseprofile: 'baseProfile',
6949
  bbox: 'bbox',
6950
  begin: 'begin',
6951
  bias: 'bias',
6952
  by: 'by',
6953
  calcmode: 'calcMode',
6954
  capheight: 'capHeight',
6955
  'cap-height': 'capHeight',
6956
  clip: 'clip',
6957
  clippath: 'clipPath',
6958
  'clip-path': 'clipPath',
6959
  clippathunits: 'clipPathUnits',
6960
  cliprule: 'clipRule',
6961
  'clip-rule': 'clipRule',
6962
  color: 'color',
6963
  colorinterpolation: 'colorInterpolation',
6964
  'color-interpolation': 'colorInterpolation',
6965
  colorinterpolationfilters: 'colorInterpolationFilters',
6966
  'color-interpolation-filters': 'colorInterpolationFilters',
6967
  colorprofile: 'colorProfile',
6968
  'color-profile': 'colorProfile',
6969
  colorrendering: 'colorRendering',
6970
  'color-rendering': 'colorRendering',
6971
  contentscripttype: 'contentScriptType',
6972
  contentstyletype: 'contentStyleType',
6973
  cursor: 'cursor',
6974
  cx: 'cx',
6975
  cy: 'cy',
6976
  d: 'd',
6977
  datatype: 'datatype',
6978
  decelerate: 'decelerate',
6979
  descent: 'descent',
6980
  diffuseconstant: 'diffuseConstant',
6981
  direction: 'direction',
6982
  display: 'display',
6983
  divisor: 'divisor',
6984
  dominantbaseline: 'dominantBaseline',
6985
  'dominant-baseline': 'dominantBaseline',
6986
  dur: 'dur',
6987
  dx: 'dx',
6988
  dy: 'dy',
6989
  edgemode: 'edgeMode',
6990
  elevation: 'elevation',
6991
  enablebackground: 'enableBackground',
6992
  'enable-background': 'enableBackground',
6993
  end: 'end',
6994
  exponent: 'exponent',
6995
  externalresourcesrequired: 'externalResourcesRequired',
6996
  fill: 'fill',
6997
  fillopacity: 'fillOpacity',
6998
  'fill-opacity': 'fillOpacity',
6999
  fillrule: 'fillRule',
7000
  'fill-rule': 'fillRule',
7001
  filter: 'filter',
7002
  filterres: 'filterRes',
7003
  filterunits: 'filterUnits',
7004
  floodopacity: 'floodOpacity',
7005
  'flood-opacity': 'floodOpacity',
7006
  floodcolor: 'floodColor',
7007
  'flood-color': 'floodColor',
7008
  focusable: 'focusable',
7009
  fontfamily: 'fontFamily',
7010
  'font-family': 'fontFamily',
7011
  fontsize: 'fontSize',
7012
  'font-size': 'fontSize',
7013
  fontsizeadjust: 'fontSizeAdjust',
7014
  'font-size-adjust': 'fontSizeAdjust',
7015
  fontstretch: 'fontStretch',
7016
  'font-stretch': 'fontStretch',
7017
  fontstyle: 'fontStyle',
7018
  'font-style': 'fontStyle',
7019
  fontvariant: 'fontVariant',
7020
  'font-variant': 'fontVariant',
7021
  fontweight: 'fontWeight',
7022
  'font-weight': 'fontWeight',
7023
  format: 'format',
7024
  from: 'from',
7025
  fx: 'fx',
7026
  fy: 'fy',
7027
  g1: 'g1',
7028
  g2: 'g2',
7029
  glyphname: 'glyphName',
7030
  'glyph-name': 'glyphName',
7031
  glyphorientationhorizontal: 'glyphOrientationHorizontal',
7032
  'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
7033
  glyphorientationvertical: 'glyphOrientationVertical',
7034
  'glyph-orientation-vertical': 'glyphOrientationVertical',
7035
  glyphref: 'glyphRef',
7036
  gradienttransform: 'gradientTransform',
7037
  gradientunits: 'gradientUnits',
7038
  hanging: 'hanging',
7039
  horizadvx: 'horizAdvX',
7040
  'horiz-adv-x': 'horizAdvX',
7041
  horizoriginx: 'horizOriginX',
7042
  'horiz-origin-x': 'horizOriginX',
7043
  ideographic: 'ideographic',
7044
  imagerendering: 'imageRendering',
7045
  'image-rendering': 'imageRendering',
7046
  in2: 'in2',
7047
  in: 'in',
7048
  inlist: 'inlist',
7049
  intercept: 'intercept',
7050
  k1: 'k1',
7051
  k2: 'k2',
7052
  k3: 'k3',
7053
  k4: 'k4',
7054
  k: 'k',
7055
  kernelmatrix: 'kernelMatrix',
7056
  kernelunitlength: 'kernelUnitLength',
7057
  kerning: 'kerning',
7058
  keypoints: 'keyPoints',
7059
  keysplines: 'keySplines',
7060
  keytimes: 'keyTimes',
7061
  lengthadjust: 'lengthAdjust',
7062
  letterspacing: 'letterSpacing',
7063
  'letter-spacing': 'letterSpacing',
7064
  lightingcolor: 'lightingColor',
7065
  'lighting-color': 'lightingColor',
7066
  limitingconeangle: 'limitingConeAngle',
7067
  local: 'local',
7068
  markerend: 'markerEnd',
7069
  'marker-end': 'markerEnd',
7070
  markerheight: 'markerHeight',
7071
  markermid: 'markerMid',
7072
  'marker-mid': 'markerMid',
7073
  markerstart: 'markerStart',
7074
  'marker-start': 'markerStart',
7075
  markerunits: 'markerUnits',
7076
  markerwidth: 'markerWidth',
7077
  mask: 'mask',
7078
  maskcontentunits: 'maskContentUnits',
7079
  maskunits: 'maskUnits',
7080
  mathematical: 'mathematical',
7081
  mode: 'mode',
7082
  numoctaves: 'numOctaves',
7083
  offset: 'offset',
7084
  opacity: 'opacity',
7085
  operator: 'operator',
7086
  order: 'order',
7087
  orient: 'orient',
7088
  orientation: 'orientation',
7089
  origin: 'origin',
7090
  overflow: 'overflow',
7091
  overlineposition: 'overlinePosition',
7092
  'overline-position': 'overlinePosition',
7093
  overlinethickness: 'overlineThickness',
7094
  'overline-thickness': 'overlineThickness',
7095
  paintorder: 'paintOrder',
7096
  'paint-order': 'paintOrder',
7097
  panose1: 'panose1',
7098
  'panose-1': 'panose1',
7099
  pathlength: 'pathLength',
7100
  patterncontentunits: 'patternContentUnits',
7101
  patterntransform: 'patternTransform',
7102
  patternunits: 'patternUnits',
7103
  pointerevents: 'pointerEvents',
7104
  'pointer-events': 'pointerEvents',
7105
  points: 'points',
7106
  pointsatx: 'pointsAtX',
7107
  pointsaty: 'pointsAtY',
7108
  pointsatz: 'pointsAtZ',
7109
  prefix: 'prefix',
7110
  preservealpha: 'preserveAlpha',
7111
  preserveaspectratio: 'preserveAspectRatio',
7112
  primitiveunits: 'primitiveUnits',
7113
  property: 'property',
7114
  r: 'r',
7115
  radius: 'radius',
7116
  refx: 'refX',
7117
  refy: 'refY',
7118
  renderingintent: 'renderingIntent',
7119
  'rendering-intent': 'renderingIntent',
7120
  repeatcount: 'repeatCount',
7121
  repeatdur: 'repeatDur',
7122
  requiredextensions: 'requiredExtensions',
7123
  requiredfeatures: 'requiredFeatures',
7124
  resource: 'resource',
7125
  restart: 'restart',
7126
  result: 'result',
7127
  results: 'results',
7128
  rotate: 'rotate',
7129
  rx: 'rx',
7130
  ry: 'ry',
7131
  scale: 'scale',
7132
  security: 'security',
7133
  seed: 'seed',
7134
  shaperendering: 'shapeRendering',
7135
  'shape-rendering': 'shapeRendering',
7136
  slope: 'slope',
7137
  spacing: 'spacing',
7138
  specularconstant: 'specularConstant',
7139
  specularexponent: 'specularExponent',
7140
  speed: 'speed',
7141
  spreadmethod: 'spreadMethod',
7142
  startoffset: 'startOffset',
7143
  stddeviation: 'stdDeviation',
7144
  stemh: 'stemh',
7145
  stemv: 'stemv',
7146
  stitchtiles: 'stitchTiles',
7147
  stopcolor: 'stopColor',
7148
  'stop-color': 'stopColor',
7149
  stopopacity: 'stopOpacity',
7150
  'stop-opacity': 'stopOpacity',
7151
  strikethroughposition: 'strikethroughPosition',
7152
  'strikethrough-position': 'strikethroughPosition',
7153
  strikethroughthickness: 'strikethroughThickness',
7154
  'strikethrough-thickness': 'strikethroughThickness',
7155
  string: 'string',
7156
  stroke: 'stroke',
7157
  strokedasharray: 'strokeDasharray',
7158
  'stroke-dasharray': 'strokeDasharray',
7159
  strokedashoffset: 'strokeDashoffset',
7160
  'stroke-dashoffset': 'strokeDashoffset',
7161
  strokelinecap: 'strokeLinecap',
7162
  'stroke-linecap': 'strokeLinecap',
7163
  strokelinejoin: 'strokeLinejoin',
7164
  'stroke-linejoin': 'strokeLinejoin',
7165
  strokemiterlimit: 'strokeMiterlimit',
7166
  'stroke-miterlimit': 'strokeMiterlimit',
7167
  strokewidth: 'strokeWidth',
7168
  'stroke-width': 'strokeWidth',
7169
  strokeopacity: 'strokeOpacity',
7170
  'stroke-opacity': 'strokeOpacity',
7171
  suppresscontenteditablewarning: 'suppressContentEditableWarning',
7172
  suppresshydrationwarning: 'suppressHydrationWarning',
7173
  surfacescale: 'surfaceScale',
7174
  systemlanguage: 'systemLanguage',
7175
  tablevalues: 'tableValues',
7176
  targetx: 'targetX',
7177
  targety: 'targetY',
7178
  textanchor: 'textAnchor',
7179
  'text-anchor': 'textAnchor',
7180
  textdecoration: 'textDecoration',
7181
  'text-decoration': 'textDecoration',
7182
  textlength: 'textLength',
7183
  textrendering: 'textRendering',
7184
  'text-rendering': 'textRendering',
7185
  to: 'to',
7186
  transform: 'transform',
7187
  typeof: 'typeof',
7188
  u1: 'u1',
7189
  u2: 'u2',
7190
  underlineposition: 'underlinePosition',
7191
  'underline-position': 'underlinePosition',
7192
  underlinethickness: 'underlineThickness',
7193
  'underline-thickness': 'underlineThickness',
7194
  unicode: 'unicode',
7195
  unicodebidi: 'unicodeBidi',
7196
  'unicode-bidi': 'unicodeBidi',
7197
  unicoderange: 'unicodeRange',
7198
  'unicode-range': 'unicodeRange',
7199
  unitsperem: 'unitsPerEm',
7200
  'units-per-em': 'unitsPerEm',
7201
  unselectable: 'unselectable',
7202
  valphabetic: 'vAlphabetic',
7203
  'v-alphabetic': 'vAlphabetic',
7204
  values: 'values',
7205
  vectoreffect: 'vectorEffect',
7206
  'vector-effect': 'vectorEffect',
7207
  version: 'version',
7208
  vertadvy: 'vertAdvY',
7209
  'vert-adv-y': 'vertAdvY',
7210
  vertoriginx: 'vertOriginX',
7211
  'vert-origin-x': 'vertOriginX',
7212
  vertoriginy: 'vertOriginY',
7213
  'vert-origin-y': 'vertOriginY',
7214
  vhanging: 'vHanging',
7215
  'v-hanging': 'vHanging',
7216
  videographic: 'vIdeographic',
7217
  'v-ideographic': 'vIdeographic',
7218
  viewbox: 'viewBox',
7219
  viewtarget: 'viewTarget',
7220
  visibility: 'visibility',
7221
  vmathematical: 'vMathematical',
7222
  'v-mathematical': 'vMathematical',
7223
  vocab: 'vocab',
7224
  widths: 'widths',
7225
  wordspacing: 'wordSpacing',
7226
  'word-spacing': 'wordSpacing',
7227
  writingmode: 'writingMode',
7228
  'writing-mode': 'writingMode',
7229
  x1: 'x1',
7230
  x2: 'x2',
7231
  x: 'x',
7232
  xchannelselector: 'xChannelSelector',
7233
  xheight: 'xHeight',
7234
  'x-height': 'xHeight',
7235
  xlinkactuate: 'xlinkActuate',
7236
  'xlink:actuate': 'xlinkActuate',
7237
  xlinkarcrole: 'xlinkArcrole',
7238
  'xlink:arcrole': 'xlinkArcrole',
7239
  xlinkhref: 'xlinkHref',
7240
  'xlink:href': 'xlinkHref',
7241
  xlinkrole: 'xlinkRole',
7242
  'xlink:role': 'xlinkRole',
7243
  xlinkshow: 'xlinkShow',
7244
  'xlink:show': 'xlinkShow',
7245
  xlinktitle: 'xlinkTitle',
7246
  'xlink:title': 'xlinkTitle',
7247
  xlinktype: 'xlinkType',
7248
  'xlink:type': 'xlinkType',
7249
  xmlbase: 'xmlBase',
7250
  'xml:base': 'xmlBase',
7251
  xmllang: 'xmlLang',
7252
  'xml:lang': 'xmlLang',
7253
  xmlns: 'xmlns',
7254
  'xml:space': 'xmlSpace',
7255
  xmlnsxlink: 'xmlnsXlink',
7256
  'xmlns:xlink': 'xmlnsXlink',
7257
  xmlspace: 'xmlSpace',
7258
  y1: 'y1',
7259
  y2: 'y2',
7260
  y: 'y',
7261
  ychannelselector: 'yChannelSelector',
7262
  z: 'z',
7263
  zoomandpan: 'zoomAndPan'
7264
};
7265
7266
var ariaProperties = {
7267
  'aria-current': 0,
7268
  // state
7269
  'aria-details': 0,
7270
  'aria-disabled': 0,
7271
  // state
7272
  'aria-hidden': 0,
7273
  // state
7274
  'aria-invalid': 0,
7275
  // state
7276
  'aria-keyshortcuts': 0,
7277
  'aria-label': 0,
7278
  'aria-roledescription': 0,
7279
  // Widget Attributes
7280
  'aria-autocomplete': 0,
7281
  'aria-checked': 0,
7282
  'aria-expanded': 0,
7283
  'aria-haspopup': 0,
7284
  'aria-level': 0,
7285
  'aria-modal': 0,
7286
  'aria-multiline': 0,
7287
  'aria-multiselectable': 0,
7288
  'aria-orientation': 0,
7289
  'aria-placeholder': 0,
7290
  'aria-pressed': 0,
7291
  'aria-readonly': 0,
7292
  'aria-required': 0,
7293
  'aria-selected': 0,
7294
  'aria-sort': 0,
7295
  'aria-valuemax': 0,
7296
  'aria-valuemin': 0,
7297
  'aria-valuenow': 0,
7298
  'aria-valuetext': 0,
7299
  // Live Region Attributes
7300
  'aria-atomic': 0,
7301
  'aria-busy': 0,
7302
  'aria-live': 0,
7303
  'aria-relevant': 0,
7304
  // Drag-and-Drop Attributes
7305
  'aria-dropeffect': 0,
7306
  'aria-grabbed': 0,
7307
  // Relationship Attributes
7308
  'aria-activedescendant': 0,
7309
  'aria-colcount': 0,
7310
  'aria-colindex': 0,
7311
  'aria-colspan': 0,
7312
  'aria-controls': 0,
7313
  'aria-describedby': 0,
7314
  'aria-errormessage': 0,
7315
  'aria-flowto': 0,
7316
  'aria-labelledby': 0,
7317
  'aria-owns': 0,
7318
  'aria-posinset': 0,
7319
  'aria-rowcount': 0,
7320
  'aria-rowindex': 0,
7321
  'aria-rowspan': 0,
7322
  'aria-setsize': 0
7323
};
7324
7325
var warnedProperties = {};
7326
var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7327
var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7328
var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
7329
7330
function validateProperty(tagName, name) {
7331
  if (hasOwnProperty$1.call(warnedProperties, name) && warnedProperties[name]) {
7332
    return true;
7333
  }
7334
7335
  if (rARIACamel.test(name)) {
7336
    var ariaName = 'aria-' + name.slice(4).toLowerCase();
7337
    var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
7338
    // DOM properties, then it is an invalid aria-* attribute.
7339
7340
    if (correctName == null) {
7341
      warning$1(false, 'Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
7342
      warnedProperties[name] = true;
7343
      return true;
7344
    } // aria-* attributes should be lowercase; suggest the lowercase version.
7345
7346
7347
    if (name !== correctName) {
7348
      warning$1(false, 'Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
7349
      warnedProperties[name] = true;
7350
      return true;
7351
    }
7352
  }
7353
7354
  if (rARIA.test(name)) {
7355
    var lowerCasedName = name.toLowerCase();
7356
    var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
7357
    // DOM properties, then it is an invalid aria-* attribute.
7358
7359
    if (standardName == null) {
7360
      warnedProperties[name] = true;
7361
      return false;
7362
    } // aria-* attributes should be lowercase; suggest the lowercase version.
7363
7364
7365
    if (name !== standardName) {
7366
      warning$1(false, 'Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
7367
      warnedProperties[name] = true;
7368
      return true;
7369
    }
7370
  }
7371
7372
  return true;
7373
}
7374
7375
function warnInvalidARIAProps(type, props) {
7376
  var invalidProps = [];
7377
7378
  for (var key in props) {
7379
    var isValid = validateProperty(type, key);
7380
7381
    if (!isValid) {
7382
      invalidProps.push(key);
7383
    }
7384
  }
7385
7386
  var unknownPropString = invalidProps.map(function (prop) {
7387
    return '`' + prop + '`';
7388
  }).join(', ');
7389
7390
  if (invalidProps.length === 1) {
7391
    warning$1(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7392
  } else if (invalidProps.length > 1) {
7393
    warning$1(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7394
  }
7395
}
7396
7397
function validateProperties(type, props) {
7398
  if (isCustomComponent(type, props)) {
7399
    return;
7400
  }
7401
7402
  warnInvalidARIAProps(type, props);
7403
}
7404
7405
var didWarnValueNull = false;
7406
function validateProperties$1(type, props) {
7407
  if (type !== 'input' && type !== 'textarea' && type !== 'select') {
7408
    return;
7409
  }
7410
7411
  if (props != null && props.value === null && !didWarnValueNull) {
7412
    didWarnValueNull = true;
7413
7414
    if (type === 'select' && props.multiple) {
7415
      warning$1(false, '`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
7416
    } else {
7417
      warning$1(false, '`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
7418
    }
7419
  }
7420
}
7421
7422
var validateProperty$1 = function () {};
7423
7424
{
7425
  var warnedProperties$1 = {};
7426
  var _hasOwnProperty = Object.prototype.hasOwnProperty;
7427
  var EVENT_NAME_REGEX = /^on./;
7428
  var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
7429
  var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7430
  var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7431
7432
  validateProperty$1 = function (tagName, name, value, canUseEventSystem) {
7433
    if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
7434
      return true;
7435
    }
7436
7437
    var lowerCasedName = name.toLowerCase();
7438
7439
    if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
7440
      warning$1(false, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');
7441
      warnedProperties$1[name] = true;
7442
      return true;
7443
    } // We can't rely on the event system being injected on the server.
7444
7445
7446
    if (canUseEventSystem) {
7447
      if (registrationNameModules.hasOwnProperty(name)) {
7448
        return true;
7449
      }
7450
7451
      var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
7452
7453
      if (registrationName != null) {
7454
        warning$1(false, 'Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
7455
        warnedProperties$1[name] = true;
7456
        return true;
7457
      }
7458
7459
      if (EVENT_NAME_REGEX.test(name)) {
7460
        warning$1(false, 'Unknown event handler property `%s`. It will be ignored.', name);
7461
        warnedProperties$1[name] = true;
7462
        return true;
7463
      }
7464
    } else if (EVENT_NAME_REGEX.test(name)) {
7465
      // If no event plugins have been injected, we are in a server environment.
7466
      // So we can't tell if the event name is correct for sure, but we can filter
7467
      // out known bad ones like `onclick`. We can't suggest a specific replacement though.
7468
      if (INVALID_EVENT_NAME_REGEX.test(name)) {
7469
        warning$1(false, 'Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
7470
      }
7471
7472
      warnedProperties$1[name] = true;
7473
      return true;
7474
    } // Let the ARIA attribute hook validate ARIA attributes
7475
7476
7477
    if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
7478
      return true;
7479
    }
7480
7481
    if (lowerCasedName === 'innerhtml') {
7482
      warning$1(false, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
7483
      warnedProperties$1[name] = true;
7484
      return true;
7485
    }
7486
7487
    if (lowerCasedName === 'aria') {
7488
      warning$1(false, 'The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
7489
      warnedProperties$1[name] = true;
7490
      return true;
7491
    }
7492
7493
    if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
7494
      warning$1(false, 'Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
7495
      warnedProperties$1[name] = true;
7496
      return true;
7497
    }
7498
7499
    if (typeof value === 'number' && isNaN(value)) {
7500
      warning$1(false, 'Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
7501
      warnedProperties$1[name] = true;
7502
      return true;
7503
    }
7504
7505
    var propertyInfo = getPropertyInfo(name);
7506
    var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.
7507
7508
    if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
7509
      var standardName = possibleStandardNames[lowerCasedName];
7510
7511
      if (standardName !== name) {
7512
        warning$1(false, 'Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
7513
        warnedProperties$1[name] = true;
7514
        return true;
7515
      }
7516
    } else if (!isReserved && name !== lowerCasedName) {
7517
      // Unknown attributes should have lowercase casing since that's how they
7518
      // will be cased anyway with server rendering.
7519
      warning$1(false, 'React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);
7520
      warnedProperties$1[name] = true;
7521
      return true;
7522
    }
7523
7524
    if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7525
      if (value) {
7526
        warning$1(false, 'Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
7527
      } else {
7528
        warning$1(false, 'Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
7529
      }
7530
7531
      warnedProperties$1[name] = true;
7532
      return true;
7533
    } // Now that we've validated casing, do not validate
7534
    // data types for reserved props
7535
7536
7537
    if (isReserved) {
7538
      return true;
7539
    } // Warn when a known attribute is a bad type
7540
7541
7542
    if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7543
      warnedProperties$1[name] = true;
7544
      return false;
7545
    } // Warn when passing the strings 'false' or 'true' into a boolean prop
7546
7547
7548
    if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
7549
      warning$1(false, 'Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);
7550
      warnedProperties$1[name] = true;
7551
      return true;
7552
    }
7553
7554
    return true;
7555
  };
7556
}
7557
7558
var warnUnknownProperties = function (type, props, canUseEventSystem) {
7559
  var unknownProps = [];
7560
7561
  for (var key in props) {
7562
    var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);
7563
7564
    if (!isValid) {
7565
      unknownProps.push(key);
7566
    }
7567
  }
7568
7569
  var unknownPropString = unknownProps.map(function (prop) {
7570
    return '`' + prop + '`';
7571
  }).join(', ');
7572
7573
  if (unknownProps.length === 1) {
7574
    warning$1(false, 'Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior', unknownPropString, type);
7575
  } else if (unknownProps.length > 1) {
7576
    warning$1(false, 'Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior', unknownPropString, type);
7577
  }
7578
};
7579
7580
function validateProperties$2(type, props, canUseEventSystem) {
7581
  if (isCustomComponent(type, props)) {
7582
    return;
7583
  }
7584
7585
  warnUnknownProperties(type, props, canUseEventSystem);
7586
}
7587
7588
// TODO: direct imports like some-package/src/* are bad. Fix me.
7589
var didWarnInvalidHydration = false;
7590
var didWarnShadyDOM = false;
7591
var didWarnScriptTags = false;
7592
var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
7593
var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
7594
var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
7595
var AUTOFOCUS = 'autoFocus';
7596
var CHILDREN = 'children';
7597
var STYLE$1 = 'style';
7598
var HTML = '__html';
7599
var LISTENERS = 'listeners';
7600
var HTML_NAMESPACE = Namespaces.html;
7601
var warnedUnknownTags;
7602
var suppressHydrationWarning;
7603
var validatePropertiesInDevelopment;
7604
var warnForTextDifference;
7605
var warnForPropDifference;
7606
var warnForExtraAttributes;
7607
var warnForInvalidEventListener;
7608
var canDiffStyleForHydrationWarning;
7609
var normalizeMarkupForTextOrAttribute;
7610
var normalizeHTML;
7611
7612
{
7613
  warnedUnknownTags = {
7614
    // Chrome is the only major browser not shipping <time>. But as of July
7615
    // 2017 it intends to ship it due to widespread usage. We intentionally
7616
    // *don't* warn for <time> even if it's unrecognized by Chrome because
7617
    // it soon will be, and many apps have been using it anyway.
7618
    time: true,
7619
    // There are working polyfills for <dialog>. Let people use it.
7620
    dialog: true,
7621
    // Electron ships a custom <webview> tag to display external web content in
7622
    // an isolated frame and process.
7623
    // This tag is not present in non Electron environments such as JSDom which
7624
    // is often used for testing purposes.
7625
    // @see https://electronjs.org/docs/api/webview-tag
7626
    webview: true
7627
  };
7628
7629
  validatePropertiesInDevelopment = function (type, props) {
7630
    validateProperties(type, props);
7631
    validateProperties$1(type, props);
7632
    validateProperties$2(type, props,
7633
    /* canUseEventSystem */
7634
    true);
7635
  }; // IE 11 parses & normalizes the style attribute as opposed to other
7636
  // browsers. It adds spaces and sorts the properties in some
7637
  // non-alphabetical order. Handling that would require sorting CSS
7638
  // properties in the client & server versions or applying
7639
  // `expectedStyle` to a temporary DOM node to read its `style` attribute
7640
  // normalized. Since it only affects IE, we're skipping style warnings
7641
  // in that browser completely in favor of doing all that work.
7642
  // See https://github.com/facebook/react/issues/11807
7643
7644
7645
  canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode; // HTML parsing normalizes CR and CRLF to LF.
7646
  // It also can turn \u0000 into \uFFFD inside attributes.
7647
  // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
7648
  // If we have a mismatch, it might be caused by that.
7649
  // We will still patch up in this case but not fire the warning.
7650
7651
  var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
7652
  var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
7653
7654
  normalizeMarkupForTextOrAttribute = function (markup) {
7655
    var markupString = typeof markup === 'string' ? markup : '' + markup;
7656
    return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
7657
  };
7658
7659
  warnForTextDifference = function (serverText, clientText) {
7660
    if (didWarnInvalidHydration) {
7661
      return;
7662
    }
7663
7664
    var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
7665
    var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
7666
7667
    if (normalizedServerText === normalizedClientText) {
7668
      return;
7669
    }
7670
7671
    didWarnInvalidHydration = true;
7672
    warningWithoutStack$1(false, 'Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
7673
  };
7674
7675
  warnForPropDifference = function (propName, serverValue, clientValue) {
7676
    if (didWarnInvalidHydration) {
7677
      return;
7678
    }
7679
7680
    var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
7681
    var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
7682
7683
    if (normalizedServerValue === normalizedClientValue) {
7684
      return;
7685
    }
7686
7687
    didWarnInvalidHydration = true;
7688
    warningWithoutStack$1(false, 'Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
7689
  };
7690
7691
  warnForExtraAttributes = function (attributeNames) {
7692
    if (didWarnInvalidHydration) {
7693
      return;
7694
    }
7695
7696
    didWarnInvalidHydration = true;
7697
    var names = [];
7698
    attributeNames.forEach(function (name) {
7699
      names.push(name);
7700
    });
7701
    warningWithoutStack$1(false, 'Extra attributes from the server: %s', names);
7702
  };
7703
7704
  warnForInvalidEventListener = function (registrationName, listener) {
7705
    if (listener === false) {
7706
      warning$1(false, 'Expected `%s` listener to be a function, instead got `false`.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', registrationName, registrationName, registrationName);
7707
    } else {
7708
      warning$1(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
7709
    }
7710
  }; // Parse the HTML and read it back to normalize the HTML string so that it
7711
  // can be used for comparison.
7712
7713
7714
  normalizeHTML = function (parent, html) {
7715
    // We could have created a separate document here to avoid
7716
    // re-initializing custom elements if they exist. But this breaks
7717
    // how <noscript> is being handled. So we use the same document.
7718
    // See the discussion in https://github.com/facebook/react/pull/11157.
7719
    var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
7720
    testElement.innerHTML = html;
7721
    return testElement.innerHTML;
7722
  };
7723
}
7724
7725
function ensureListeningTo(rootContainerElement, registrationName) {
7726
  var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;
7727
  var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;
7728
  listenTo(registrationName, doc);
7729
}
7730
7731
function getOwnerDocumentFromRootContainer(rootContainerElement) {
7732
  return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
7733
}
7734
7735
function noop() {}
7736
7737
function trapClickOnNonInteractiveElement(node) {
7738
  // Mobile Safari does not fire properly bubble click events on
7739
  // non-interactive elements, which means delegated click listeners do not
7740
  // fire. The workaround for this bug involves attaching an empty click
7741
  // listener on the target node.
7742
  // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
7743
  // Just set it using the onclick property so that we don't have to manage any
7744
  // bookkeeping for it. Not sure if we need to clear it when the listener is
7745
  // removed.
7746
  // TODO: Only do this for the relevant Safaris maybe?
7747
  node.onclick = noop;
7748
}
7749
7750
function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
7751
  for (var propKey in nextProps) {
7752
    if (!nextProps.hasOwnProperty(propKey)) {
7753
      continue;
7754
    }
7755
7756
    var nextProp = nextProps[propKey];
7757
7758
    if (propKey === STYLE$1) {
7759
      {
7760
        if (nextProp) {
7761
          // Freeze the next style object so that we can assume it won't be
7762
          // mutated. We have already warned for this in the past.
7763
          Object.freeze(nextProp);
7764
        }
7765
      } // Relies on `updateStylesByID` not mutating `styleUpdates`.
7766
7767
7768
      setValueForStyles(domElement, nextProp);
7769
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7770
      var nextHtml = nextProp ? nextProp[HTML] : undefined;
7771
7772
      if (nextHtml != null) {
7773
        setInnerHTML(domElement, nextHtml);
7774
      }
7775
    } else if (propKey === CHILDREN) {
7776
      if (typeof nextProp === 'string') {
7777
        // Avoid setting initial textContent when the text is empty. In IE11 setting
7778
        // textContent on a <textarea> will cause the placeholder to not
7779
        // show within the <textarea> until it has been focused and blurred again.
7780
        // https://github.com/facebook/react/issues/6731#issuecomment-254874553
7781
        var canSetTextContent = tag !== 'textarea' || nextProp !== '';
7782
7783
        if (canSetTextContent) {
7784
          setTextContent(domElement, nextProp);
7785
        }
7786
      } else if (typeof nextProp === 'number') {
7787
        setTextContent(domElement, '' + nextProp);
7788
      }
7789
    } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {// Noop
7790
    } else if (propKey === AUTOFOCUS) {// We polyfill it separately on the client during commit.
7791
      // We could have excluded it in the property list instead of
7792
      // adding a special case here, but then it wouldn't be emitted
7793
      // on server rendering (but we *do* want to emit it in SSR).
7794
    } else if (registrationNameModules.hasOwnProperty(propKey)) {
7795
      if (nextProp != null) {
7796
        if (true && typeof nextProp !== 'function') {
7797
          warnForInvalidEventListener(propKey, nextProp);
7798
        }
7799
7800
        ensureListeningTo(rootContainerElement, propKey);
7801
      }
7802
    } else if (nextProp != null) {
7803
      setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
7804
    }
7805
  }
7806
}
7807
7808
function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
7809
  // TODO: Handle wasCustomComponentTag
7810
  for (var i = 0; i < updatePayload.length; i += 2) {
7811
    var propKey = updatePayload[i];
7812
    var propValue = updatePayload[i + 1];
7813
7814
    if (propKey === STYLE$1) {
7815
      setValueForStyles(domElement, propValue);
7816
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7817
      setInnerHTML(domElement, propValue);
7818
    } else if (propKey === CHILDREN) {
7819
      setTextContent(domElement, propValue);
7820
    } else {
7821
      setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
7822
    }
7823
  }
7824
}
7825
7826
function createElement(type, props, rootContainerElement, parentNamespace) {
7827
  var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML
7828
  // tags get no namespace.
7829
7830
  var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
7831
  var domElement;
7832
  var namespaceURI = parentNamespace;
7833
7834
  if (namespaceURI === HTML_NAMESPACE) {
7835
    namespaceURI = getIntrinsicNamespace(type);
7836
  }
7837
7838
  if (namespaceURI === HTML_NAMESPACE) {
7839
    {
7840
      isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to
7841
      // allow <SVG> or <mATH>.
7842
7843
      !(isCustomComponentTag || type === type.toLowerCase()) ? warning$1(false, '<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type) : void 0;
7844
    }
7845
7846
    if (type === 'script') {
7847
      // Create the script via .innerHTML so its "parser-inserted" flag is
7848
      // set to true and it does not execute
7849
      var div = ownerDocument.createElement('div');
7850
7851
      {
7852
        if (enableTrustedTypesIntegration && !didWarnScriptTags) {
7853
          warning$1(false, 'Encountered a script tag while rendering React component. ' + 'Scripts inside React components are never executed when rendering ' + 'on the client. Consider using template tag instead ' + '(https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template).');
7854
          didWarnScriptTags = true;
7855
        }
7856
      }
7857
7858
      div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
7859
      // This is guaranteed to yield a script element.
7860
7861
      var firstChild = div.firstChild;
7862
      domElement = div.removeChild(firstChild);
7863
    } else if (typeof props.is === 'string') {
7864
      // $FlowIssue `createElement` should be updated for Web Components
7865
      domElement = ownerDocument.createElement(type, {
7866
        is: props.is
7867
      });
7868
    } else {
7869
      // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
7870
      // See discussion in https://github.com/facebook/react/pull/6896
7871
      // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
7872
      domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
7873
      // attributes on `select`s needs to be added before `option`s are inserted.
7874
      // This prevents:
7875
      // - a bug where the `select` does not scroll to the correct option because singular
7876
      //  `select` elements automatically pick the first item #13222
7877
      // - a bug where the `select` set the first item as selected despite the `size` attribute #14239
7878
      // See https://github.com/facebook/react/issues/13222
7879
      // and https://github.com/facebook/react/issues/14239
7880
7881
      if (type === 'select') {
7882
        var node = domElement;
7883
7884
        if (props.multiple) {
7885
          node.multiple = true;
7886
        } else if (props.size) {
7887
          // Setting a size greater than 1 causes a select to behave like `multiple=true`, where
7888
          // it is possible that no option is selected.
7889
          //
7890
          // This is only necessary when a select in "single selection mode".
7891
          node.size = props.size;
7892
        }
7893
      }
7894
    }
7895
  } else {
7896
    domElement = ownerDocument.createElementNS(namespaceURI, type);
7897
  }
7898
7899
  {
7900
    if (namespaceURI === HTML_NAMESPACE) {
7901
      if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {
7902
        warnedUnknownTags[type] = true;
7903
        warning$1(false, 'The tag <%s> is unrecognized in this browser. ' + 'If you meant to render a React component, start its name with ' + 'an uppercase letter.', type);
7904
      }
7905
    }
7906
  }
7907
7908
  return domElement;
7909
}
7910
function createTextNode(text, rootContainerElement) {
7911
  return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
7912
}
7913
function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
7914
  var isCustomComponentTag = isCustomComponent(tag, rawProps);
7915
7916
  {
7917
    validatePropertiesInDevelopment(tag, rawProps);
7918
7919
    if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
7920
      warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
7921
      didWarnShadyDOM = true;
7922
    }
7923
  } // TODO: Make sure that we check isMounted before firing any of these events.
7924
7925
7926
  var props;
7927
7928
  switch (tag) {
7929
    case 'iframe':
7930
    case 'object':
7931
    case 'embed':
7932
      trapBubbledEvent(TOP_LOAD, domElement);
7933
      props = rawProps;
7934
      break;
7935
7936
    case 'video':
7937
    case 'audio':
7938
      // Create listener for each media event
7939
      for (var i = 0; i < mediaEventTypes.length; i++) {
7940
        trapBubbledEvent(mediaEventTypes[i], domElement);
7941
      }
7942
7943
      props = rawProps;
7944
      break;
7945
7946
    case 'source':
7947
      trapBubbledEvent(TOP_ERROR, domElement);
7948
      props = rawProps;
7949
      break;
7950
7951
    case 'img':
7952
    case 'image':
7953
    case 'link':
7954
      trapBubbledEvent(TOP_ERROR, domElement);
7955
      trapBubbledEvent(TOP_LOAD, domElement);
7956
      props = rawProps;
7957
      break;
7958
7959
    case 'form':
7960
      trapBubbledEvent(TOP_RESET, domElement);
7961
      trapBubbledEvent(TOP_SUBMIT, domElement);
7962
      props = rawProps;
7963
      break;
7964
7965
    case 'details':
7966
      trapBubbledEvent(TOP_TOGGLE, domElement);
7967
      props = rawProps;
7968
      break;
7969
7970
    case 'input':
7971
      initWrapperState(domElement, rawProps);
7972
      props = getHostProps(domElement, rawProps);
7973
      trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
7974
      // to onChange. Even if there is no listener.
7975
7976
      ensureListeningTo(rootContainerElement, 'onChange');
7977
      break;
7978
7979
    case 'option':
7980
      validateProps(domElement, rawProps);
7981
      props = getHostProps$1(domElement, rawProps);
7982
      break;
7983
7984
    case 'select':
7985
      initWrapperState$1(domElement, rawProps);
7986
      props = getHostProps$2(domElement, rawProps);
7987
      trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
7988
      // to onChange. Even if there is no listener.
7989
7990
      ensureListeningTo(rootContainerElement, 'onChange');
7991
      break;
7992
7993
    case 'textarea':
7994
      initWrapperState$2(domElement, rawProps);
7995
      props = getHostProps$3(domElement, rawProps);
7996
      trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
7997
      // to onChange. Even if there is no listener.
7998
7999
      ensureListeningTo(rootContainerElement, 'onChange');
8000
      break;
8001
8002
    default:
8003
      props = rawProps;
8004
  }
8005
8006
  assertValidProps(tag, props);
8007
  setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
8008
8009
  switch (tag) {
8010
    case 'input':
8011
      // TODO: Make sure we check if this is still unmounted or do any clean
8012
      // up necessary since we never stop tracking anymore.
8013
      track(domElement);
8014
      postMountWrapper(domElement, rawProps, false);
8015
      break;
8016
8017
    case 'textarea':
8018
      // TODO: Make sure we check if this is still unmounted or do any clean
8019
      // up necessary since we never stop tracking anymore.
8020
      track(domElement);
8021
      postMountWrapper$3(domElement, rawProps);
8022
      break;
8023
8024
    case 'option':
8025
      postMountWrapper$1(domElement, rawProps);
8026
      break;
8027
8028
    case 'select':
8029
      postMountWrapper$2(domElement, rawProps);
8030
      break;
8031
8032
    default:
8033
      if (typeof props.onClick === 'function') {
8034
        // TODO: This cast may not be sound for SVG, MathML or custom elements.
8035
        trapClickOnNonInteractiveElement(domElement);
8036
      }
8037
8038
      break;
8039
  }
8040
} // Calculate the diff between the two objects.
8041
8042
function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
8043
  {
8044
    validatePropertiesInDevelopment(tag, nextRawProps);
8045
  }
8046
8047
  var updatePayload = null;
8048
  var lastProps;
8049
  var nextProps;
8050
8051
  switch (tag) {
8052
    case 'input':
8053
      lastProps = getHostProps(domElement, lastRawProps);
8054
      nextProps = getHostProps(domElement, nextRawProps);
8055
      updatePayload = [];
8056
      break;
8057
8058
    case 'option':
8059
      lastProps = getHostProps$1(domElement, lastRawProps);
8060
      nextProps = getHostProps$1(domElement, nextRawProps);
8061
      updatePayload = [];
8062
      break;
8063
8064
    case 'select':
8065
      lastProps = getHostProps$2(domElement, lastRawProps);
8066
      nextProps = getHostProps$2(domElement, nextRawProps);
8067
      updatePayload = [];
8068
      break;
8069
8070
    case 'textarea':
8071
      lastProps = getHostProps$3(domElement, lastRawProps);
8072
      nextProps = getHostProps$3(domElement, nextRawProps);
8073
      updatePayload = [];
8074
      break;
8075
8076
    default:
8077
      lastProps = lastRawProps;
8078
      nextProps = nextRawProps;
8079
8080
      if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
8081
        // TODO: This cast may not be sound for SVG, MathML or custom elements.
8082
        trapClickOnNonInteractiveElement(domElement);
8083
      }
8084
8085
      break;
8086
  }
8087
8088
  assertValidProps(tag, nextProps);
8089
  var propKey;
8090
  var styleName;
8091
  var styleUpdates = null;
8092
8093
  for (propKey in lastProps) {
8094
    if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
8095
      continue;
8096
    }
8097
8098
    if (propKey === STYLE$1) {
8099
      var lastStyle = lastProps[propKey];
8100
8101
      for (styleName in lastStyle) {
8102
        if (lastStyle.hasOwnProperty(styleName)) {
8103
          if (!styleUpdates) {
8104
            styleUpdates = {};
8105
          }
8106
8107
          styleUpdates[styleName] = '';
8108
        }
8109
      }
8110
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) {// Noop. This is handled by the clear text mechanism.
8111
    } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {// Noop
8112
    } else if (propKey === AUTOFOCUS) {// Noop. It doesn't work on updates anyway.
8113
    } else if (registrationNameModules.hasOwnProperty(propKey)) {
8114
      // This is a special case. If any listener updates we need to ensure
8115
      // that the "current" fiber pointer gets updated so we need a commit
8116
      // to update this element.
8117
      if (!updatePayload) {
8118
        updatePayload = [];
8119
      }
8120
    } else {
8121
      // For all other deleted properties we add it to the queue. We use
8122
      // the whitelist in the commit phase instead.
8123
      (updatePayload = updatePayload || []).push(propKey, null);
8124
    }
8125
  }
8126
8127
  for (propKey in nextProps) {
8128
    var nextProp = nextProps[propKey];
8129
    var lastProp = lastProps != null ? lastProps[propKey] : undefined;
8130
8131
    if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
8132
      continue;
8133
    }
8134
8135
    if (propKey === STYLE$1) {
8136
      {
8137
        if (nextProp) {
8138
          // Freeze the next style object so that we can assume it won't be
8139
          // mutated. We have already warned for this in the past.
8140
          Object.freeze(nextProp);
8141
        }
8142
      }
8143
8144
      if (lastProp) {
8145
        // Unset styles on `lastProp` but not on `nextProp`.
8146
        for (styleName in lastProp) {
8147
          if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
8148
            if (!styleUpdates) {
8149
              styleUpdates = {};
8150
            }
8151
8152
            styleUpdates[styleName] = '';
8153
          }
8154
        } // Update styles that changed since `lastProp`.
8155
8156
8157
        for (styleName in nextProp) {
8158
          if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
8159
            if (!styleUpdates) {
8160
              styleUpdates = {};
8161
            }
8162
8163
            styleUpdates[styleName] = nextProp[styleName];
8164
          }
8165
        }
8166
      } else {
8167
        // Relies on `updateStylesByID` not mutating `styleUpdates`.
8168
        if (!styleUpdates) {
8169
          if (!updatePayload) {
8170
            updatePayload = [];
8171
          }
8172
8173
          updatePayload.push(propKey, styleUpdates);
8174
        }
8175
8176
        styleUpdates = nextProp;
8177
      }
8178
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8179
      var nextHtml = nextProp ? nextProp[HTML] : undefined;
8180
      var lastHtml = lastProp ? lastProp[HTML] : undefined;
8181
8182
      if (nextHtml != null) {
8183
        if (lastHtml !== nextHtml) {
8184
          (updatePayload = updatePayload || []).push(propKey, toStringOrTrustedType(nextHtml));
8185
        }
8186
      } else {// TODO: It might be too late to clear this if we have children
8187
        // inserted already.
8188
      }
8189
    } else if (propKey === CHILDREN) {
8190
      if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {
8191
        (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
8192
      }
8193
    } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {// Noop
8194
    } else if (registrationNameModules.hasOwnProperty(propKey)) {
8195
      if (nextProp != null) {
8196
        // We eagerly listen to this even though we haven't committed yet.
8197
        if (true && typeof nextProp !== 'function') {
8198
          warnForInvalidEventListener(propKey, nextProp);
8199
        }
8200
8201
        ensureListeningTo(rootContainerElement, propKey);
8202
      }
8203
8204
      if (!updatePayload && lastProp !== nextProp) {
8205
        // This is a special case. If any listener updates we need to ensure
8206
        // that the "current" props pointer gets updated so we need a commit
8207
        // to update this element.
8208
        updatePayload = [];
8209
      }
8210
    } else {
8211
      // For any other property we always add it to the queue and then we
8212
      // filter it out using the whitelist during the commit.
8213
      (updatePayload = updatePayload || []).push(propKey, nextProp);
8214
    }
8215
  }
8216
8217
  if (styleUpdates) {
8218
    {
8219
      validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE$1]);
8220
    }
8221
8222
    (updatePayload = updatePayload || []).push(STYLE$1, styleUpdates);
8223
  }
8224
8225
  return updatePayload;
8226
} // Apply the diff.
8227
8228
function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
8229
  // Update checked *before* name.
8230
  // In the middle of an update, it is possible to have multiple checked.
8231
  // When a checked radio tries to change name, browser makes another radio's checked false.
8232
  if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
8233
    updateChecked(domElement, nextRawProps);
8234
  }
8235
8236
  var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
8237
  var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff.
8238
8239
  updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props
8240
  // changed.
8241
8242
  switch (tag) {
8243
    case 'input':
8244
      // Update the wrapper around inputs *after* updating props. This has to
8245
      // happen after `updateDOMProperties`. Otherwise HTML5 input validations
8246
      // raise warnings and prevent the new value from being assigned.
8247
      updateWrapper(domElement, nextRawProps);
8248
      break;
8249
8250
    case 'textarea':
8251
      updateWrapper$1(domElement, nextRawProps);
8252
      break;
8253
8254
    case 'select':
8255
      // <select> value update needs to occur after <option> children
8256
      // reconciliation
8257
      postUpdateWrapper(domElement, nextRawProps);
8258
      break;
8259
  }
8260
}
8261
8262
function getPossibleStandardName(propName) {
8263
  {
8264
    var lowerCasedName = propName.toLowerCase();
8265
8266
    if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
8267
      return null;
8268
    }
8269
8270
    return possibleStandardNames[lowerCasedName] || null;
8271
  }
8272
8273
  return null;
8274
}
8275
8276
function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {
8277
  var isCustomComponentTag;
8278
  var extraAttributeNames;
8279
8280
  {
8281
    suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING$1] === true;
8282
    isCustomComponentTag = isCustomComponent(tag, rawProps);
8283
    validatePropertiesInDevelopment(tag, rawProps);
8284
8285
    if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
8286
      warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
8287
      didWarnShadyDOM = true;
8288
    }
8289
  } // TODO: Make sure that we check isMounted before firing any of these events.
8290
8291
8292
  switch (tag) {
8293
    case 'iframe':
8294
    case 'object':
8295
    case 'embed':
8296
      trapBubbledEvent(TOP_LOAD, domElement);
8297
      break;
8298
8299
    case 'video':
8300
    case 'audio':
8301
      // Create listener for each media event
8302
      for (var i = 0; i < mediaEventTypes.length; i++) {
8303
        trapBubbledEvent(mediaEventTypes[i], domElement);
8304
      }
8305
8306
      break;
8307
8308
    case 'source':
8309
      trapBubbledEvent(TOP_ERROR, domElement);
8310
      break;
8311
8312
    case 'img':
8313
    case 'image':
8314
    case 'link':
8315
      trapBubbledEvent(TOP_ERROR, domElement);
8316
      trapBubbledEvent(TOP_LOAD, domElement);
8317
      break;
8318
8319
    case 'form':
8320
      trapBubbledEvent(TOP_RESET, domElement);
8321
      trapBubbledEvent(TOP_SUBMIT, domElement);
8322
      break;
8323
8324
    case 'details':
8325
      trapBubbledEvent(TOP_TOGGLE, domElement);
8326
      break;
8327
8328
    case 'input':
8329
      initWrapperState(domElement, rawProps);
8330
      trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8331
      // to onChange. Even if there is no listener.
8332
8333
      ensureListeningTo(rootContainerElement, 'onChange');
8334
      break;
8335
8336
    case 'option':
8337
      validateProps(domElement, rawProps);
8338
      break;
8339
8340
    case 'select':
8341
      initWrapperState$1(domElement, rawProps);
8342
      trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8343
      // to onChange. Even if there is no listener.
8344
8345
      ensureListeningTo(rootContainerElement, 'onChange');
8346
      break;
8347
8348
    case 'textarea':
8349
      initWrapperState$2(domElement, rawProps);
8350
      trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8351
      // to onChange. Even if there is no listener.
8352
8353
      ensureListeningTo(rootContainerElement, 'onChange');
8354
      break;
8355
  }
8356
8357
  assertValidProps(tag, rawProps);
8358
8359
  {
8360
    extraAttributeNames = new Set();
8361
    var attributes = domElement.attributes;
8362
8363
    for (var _i = 0; _i < attributes.length; _i++) {
8364
      var name = attributes[_i].name.toLowerCase();
8365
8366
      switch (name) {
8367
        // Built-in SSR attribute is whitelisted
8368
        case 'data-reactroot':
8369
          break;
8370
        // Controlled attributes are not validated
8371
        // TODO: Only ignore them on controlled tags.
8372
8373
        case 'value':
8374
          break;
8375
8376
        case 'checked':
8377
          break;
8378
8379
        case 'selected':
8380
          break;
8381
8382
        default:
8383
          // Intentionally use the original name.
8384
          // See discussion in https://github.com/facebook/react/pull/10676.
8385
          extraAttributeNames.add(attributes[_i].name);
8386
      }
8387
    }
8388
  }
8389
8390
  var updatePayload = null;
8391
8392
  for (var propKey in rawProps) {
8393
    if (!rawProps.hasOwnProperty(propKey)) {
8394
      continue;
8395
    }
8396
8397
    var nextProp = rawProps[propKey];
8398
8399
    if (propKey === CHILDREN) {
8400
      // For text content children we compare against textContent. This
8401
      // might match additional HTML that is hidden when we read it using
8402
      // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
8403
      // satisfies our requirement. Our requirement is not to produce perfect
8404
      // HTML and attributes. Ideally we should preserve structure but it's
8405
      // ok not to if the visible content is still enough to indicate what
8406
      // even listeners these nodes might be wired up to.
8407
      // TODO: Warn if there is more than a single textNode as a child.
8408
      // TODO: Should we use domElement.firstChild.nodeValue to compare?
8409
      if (typeof nextProp === 'string') {
8410
        if (domElement.textContent !== nextProp) {
8411
          if (true && !suppressHydrationWarning) {
8412
            warnForTextDifference(domElement.textContent, nextProp);
8413
          }
8414
8415
          updatePayload = [CHILDREN, nextProp];
8416
        }
8417
      } else if (typeof nextProp === 'number') {
8418
        if (domElement.textContent !== '' + nextProp) {
8419
          if (true && !suppressHydrationWarning) {
8420
            warnForTextDifference(domElement.textContent, nextProp);
8421
          }
8422
8423
          updatePayload = [CHILDREN, '' + nextProp];
8424
        }
8425
      }
8426
    } else if (registrationNameModules.hasOwnProperty(propKey)) {
8427
      if (nextProp != null) {
8428
        if (true && typeof nextProp !== 'function') {
8429
          warnForInvalidEventListener(propKey, nextProp);
8430
        }
8431
8432
        ensureListeningTo(rootContainerElement, propKey);
8433
      }
8434
    } else if (true && // Convince Flow we've calculated it (it's DEV-only in this method.)
8435
    typeof isCustomComponentTag === 'boolean') {
8436
      // Validate that the properties correspond to their expected values.
8437
      var serverValue = void 0;
8438
      var propertyInfo = getPropertyInfo(propKey);
8439
8440
      if (suppressHydrationWarning) {// Don't bother comparing. We're ignoring all these warnings.
8441
      } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1 || // Controlled attributes are not validated
8442
      // TODO: Only ignore them on controlled tags.
8443
      propKey === 'value' || propKey === 'checked' || propKey === 'selected') {// Noop
8444
      } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8445
        var serverHTML = domElement.innerHTML;
8446
        var nextHtml = nextProp ? nextProp[HTML] : undefined;
8447
        var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : '');
8448
8449
        if (expectedHTML !== serverHTML) {
8450
          warnForPropDifference(propKey, serverHTML, expectedHTML);
8451
        }
8452
      } else if (propKey === STYLE$1) {
8453
        // $FlowFixMe - Should be inferred as not undefined.
8454
        extraAttributeNames.delete(propKey);
8455
8456
        if (canDiffStyleForHydrationWarning) {
8457
          var expectedStyle = createDangerousStringForStyles(nextProp);
8458
          serverValue = domElement.getAttribute('style');
8459
8460
          if (expectedStyle !== serverValue) {
8461
            warnForPropDifference(propKey, serverValue, expectedStyle);
8462
          }
8463
        }
8464
      } else if (isCustomComponentTag) {
8465
        // $FlowFixMe - Should be inferred as not undefined.
8466
        extraAttributeNames.delete(propKey.toLowerCase());
8467
        serverValue = getValueForAttribute(domElement, propKey, nextProp);
8468
8469
        if (nextProp !== serverValue) {
8470
          warnForPropDifference(propKey, serverValue, nextProp);
8471
        }
8472
      } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
8473
        var isMismatchDueToBadCasing = false;
8474
8475
        if (propertyInfo !== null) {
8476
          // $FlowFixMe - Should be inferred as not undefined.
8477
          extraAttributeNames.delete(propertyInfo.attributeName);
8478
          serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
8479
        } else {
8480
          var ownNamespace = parentNamespace;
8481
8482
          if (ownNamespace === HTML_NAMESPACE) {
8483
            ownNamespace = getIntrinsicNamespace(tag);
8484
          }
8485
8486
          if (ownNamespace === HTML_NAMESPACE) {
8487
            // $FlowFixMe - Should be inferred as not undefined.
8488
            extraAttributeNames.delete(propKey.toLowerCase());
8489
          } else {
8490
            var standardName = getPossibleStandardName(propKey);
8491
8492
            if (standardName !== null && standardName !== propKey) {
8493
              // If an SVG prop is supplied with bad casing, it will
8494
              // be successfully parsed from HTML, but will produce a mismatch
8495
              // (and would be incorrectly rendered on the client).
8496
              // However, we already warn about bad casing elsewhere.
8497
              // So we'll skip the misleading extra mismatch warning in this case.
8498
              isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined.
8499
8500
              extraAttributeNames.delete(standardName);
8501
            } // $FlowFixMe - Should be inferred as not undefined.
8502
8503
8504
            extraAttributeNames.delete(propKey);
8505
          }
8506
8507
          serverValue = getValueForAttribute(domElement, propKey, nextProp);
8508
        }
8509
8510
        if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
8511
          warnForPropDifference(propKey, serverValue, nextProp);
8512
        }
8513
      }
8514
    }
8515
  }
8516
8517
  {
8518
    // $FlowFixMe - Should be inferred as not undefined.
8519
    if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
8520
      // $FlowFixMe - Should be inferred as not undefined.
8521
      warnForExtraAttributes(extraAttributeNames);
8522
    }
8523
  }
8524
8525
  switch (tag) {
8526
    case 'input':
8527
      // TODO: Make sure we check if this is still unmounted or do any clean
8528
      // up necessary since we never stop tracking anymore.
8529
      track(domElement);
8530
      postMountWrapper(domElement, rawProps, true);
8531
      break;
8532
8533
    case 'textarea':
8534
      // TODO: Make sure we check if this is still unmounted or do any clean
8535
      // up necessary since we never stop tracking anymore.
8536
      track(domElement);
8537
      postMountWrapper$3(domElement, rawProps);
8538
      break;
8539
8540
    case 'select':
8541
    case 'option':
8542
      // For input and textarea we current always set the value property at
8543
      // post mount to force it to diverge from attributes. However, for
8544
      // option and select we don't quite do the same thing and select
8545
      // is not resilient to the DOM state changing so we don't do that here.
8546
      // TODO: Consider not doing this for input and textarea.
8547
      break;
8548
8549
    default:
8550
      if (typeof rawProps.onClick === 'function') {
8551
        // TODO: This cast may not be sound for SVG, MathML or custom elements.
8552
        trapClickOnNonInteractiveElement(domElement);
8553
      }
8554
8555
      break;
8556
  }
8557
8558
  return updatePayload;
8559
}
8560
function diffHydratedText(textNode, text) {
8561
  var isDifferent = textNode.nodeValue !== text;
8562
  return isDifferent;
8563
}
8564
function warnForUnmatchedText(textNode, text) {
8565
  {
8566
    warnForTextDifference(textNode.nodeValue, text);
8567
  }
8568
}
8569
function warnForDeletedHydratableElement(parentNode, child) {
8570
  {
8571
    if (didWarnInvalidHydration) {
8572
      return;
8573
    }
8574
8575
    didWarnInvalidHydration = true;
8576
    warningWithoutStack$1(false, 'Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
8577
  }
8578
}
8579
function warnForDeletedHydratableText(parentNode, child) {
8580
  {
8581
    if (didWarnInvalidHydration) {
8582
      return;
8583
    }
8584
8585
    didWarnInvalidHydration = true;
8586
    warningWithoutStack$1(false, 'Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
8587
  }
8588
}
8589
function warnForInsertedHydratedElement(parentNode, tag, props) {
8590
  {
8591
    if (didWarnInvalidHydration) {
8592
      return;
8593
    }
8594
8595
    didWarnInvalidHydration = true;
8596
    warningWithoutStack$1(false, 'Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
8597
  }
8598
}
8599
function warnForInsertedHydratedText(parentNode, text) {
8600
  {
8601
    if (text === '') {
8602
      // We expect to insert empty text nodes since they're not represented in
8603
      // the HTML.
8604
      // TODO: Remove this special case if we can just avoid inserting empty
8605
      // text nodes.
8606
      return;
8607
    }
8608
8609
    if (didWarnInvalidHydration) {
8610
      return;
8611
    }
8612
8613
    didWarnInvalidHydration = true;
8614
    warningWithoutStack$1(false, 'Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
8615
  }
8616
}
8617
function restoreControlledState$$1(domElement, tag, props) {
8618
  switch (tag) {
8619
    case 'input':
8620
      restoreControlledState$1(domElement, props);
8621
      return;
8622
8623
    case 'textarea':
8624
      restoreControlledState$3(domElement, props);
8625
      return;
8626
8627
    case 'select':
8628
      restoreControlledState$2(domElement, props);
8629
      return;
8630
  }
8631
}
8632
function listenToEventResponderEventTypes(eventTypes, element) {
8633
  if (enableFlareAPI) {
8634
    // Get the listening Set for this element. We use this to track
8635
    // what events we're listening to.
8636
    var listeningSet = getListeningSetForElement(element); // Go through each target event type of the event responder
8637
8638
    for (var i = 0, length = eventTypes.length; i < length; ++i) {
8639
      var eventType = eventTypes[i];
8640
      var isPassive = !endsWith(eventType, '_active');
8641
      var eventKey = isPassive ? eventType + '_passive' : eventType;
8642
      var targetEventType = isPassive ? eventType : eventType.substring(0, eventType.length - 7);
8643
8644
      if (!listeningSet.has(eventKey)) {
8645
        trapEventForResponderEventSystem(element, targetEventType, isPassive);
8646
        listeningSet.add(eventKey);
8647
      }
8648
    }
8649
  }
8650
} // We can remove this once the event API is stable and out of a flag
8651
8652
if (enableFlareAPI) {
8653
  setListenToResponderEventTypes(listenToEventResponderEventTypes);
8654
}
8655
8656
function getActiveElement(doc) {
8657
  doc = doc || (typeof document !== 'undefined' ? document : undefined);
8658
8659
  if (typeof doc === 'undefined') {
8660
    return null;
8661
  }
8662
8663
  try {
8664
    return doc.activeElement || doc.body;
8665
  } catch (e) {
8666
    return doc.body;
8667
  }
8668
}
8669
8670
/**
8671
 * Given any node return the first leaf node without children.
8672
 *
8673
 * @param {DOMElement|DOMTextNode} node
8674
 * @return {DOMElement|DOMTextNode}
8675
 */
8676
8677
function getLeafNode(node) {
8678
  while (node && node.firstChild) {
8679
    node = node.firstChild;
8680
  }
8681
8682
  return node;
8683
}
8684
/**
8685
 * Get the next sibling within a container. This will walk up the
8686
 * DOM if a node's siblings have been exhausted.
8687
 *
8688
 * @param {DOMElement|DOMTextNode} node
8689
 * @return {?DOMElement|DOMTextNode}
8690
 */
8691
8692
8693
function getSiblingNode(node) {
8694
  while (node) {
8695
    if (node.nextSibling) {
8696
      return node.nextSibling;
8697
    }
8698
8699
    node = node.parentNode;
8700
  }
8701
}
8702
/**
8703
 * Get object describing the nodes which contain characters at offset.
8704
 *
8705
 * @param {DOMElement|DOMTextNode} root
8706
 * @param {number} offset
8707
 * @return {?object}
8708
 */
8709
8710
8711
function getNodeForCharacterOffset(root, offset) {
8712
  var node = getLeafNode(root);
8713
  var nodeStart = 0;
8714
  var nodeEnd = 0;
8715
8716
  while (node) {
8717
    if (node.nodeType === TEXT_NODE) {
8718
      nodeEnd = nodeStart + node.textContent.length;
8719
8720
      if (nodeStart <= offset && nodeEnd >= offset) {
8721
        return {
8722
          node: node,
8723
          offset: offset - nodeStart
8724
        };
8725
      }
8726
8727
      nodeStart = nodeEnd;
8728
    }
8729
8730
    node = getLeafNode(getSiblingNode(node));
8731
  }
8732
}
8733
8734
/**
8735
 * @param {DOMElement} outerNode
8736
 * @return {?object}
8737
 */
8738
8739
function getOffsets(outerNode) {
8740
  var ownerDocument = outerNode.ownerDocument;
8741
  var win = ownerDocument && ownerDocument.defaultView || window;
8742
  var selection = win.getSelection && win.getSelection();
8743
8744
  if (!selection || selection.rangeCount === 0) {
8745
    return null;
8746
  }
8747
8748
  var anchorNode = selection.anchorNode,
8749
      anchorOffset = selection.anchorOffset,
8750
      focusNode = selection.focusNode,
8751
      focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
8752
  // up/down buttons on an <input type="number">. Anonymous divs do not seem to
8753
  // expose properties, triggering a "Permission denied error" if any of its
8754
  // properties are accessed. The only seemingly possible way to avoid erroring
8755
  // is to access a property that typically works for non-anonymous divs and
8756
  // catch any error that may otherwise arise. See
8757
  // https://bugzilla.mozilla.org/show_bug.cgi?id=208427
8758
8759
  try {
8760
    /* eslint-disable no-unused-expressions */
8761
    anchorNode.nodeType;
8762
    focusNode.nodeType;
8763
    /* eslint-enable no-unused-expressions */
8764
  } catch (e) {
8765
    return null;
8766
  }
8767
8768
  return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
8769
}
8770
/**
8771
 * Returns {start, end} where `start` is the character/codepoint index of
8772
 * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
8773
 * `end` is the index of (focusNode, focusOffset).
8774
 *
8775
 * Returns null if you pass in garbage input but we should probably just crash.
8776
 *
8777
 * Exported only for testing.
8778
 */
8779
8780
function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
8781
  var length = 0;
8782
  var start = -1;
8783
  var end = -1;
8784
  var indexWithinAnchor = 0;
8785
  var indexWithinFocus = 0;
8786
  var node = outerNode;
8787
  var parentNode = null;
8788
8789
  outer: while (true) {
8790
    var next = null;
8791
8792
    while (true) {
8793
      if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
8794
        start = length + anchorOffset;
8795
      }
8796
8797
      if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
8798
        end = length + focusOffset;
8799
      }
8800
8801
      if (node.nodeType === TEXT_NODE) {
8802
        length += node.nodeValue.length;
8803
      }
8804
8805
      if ((next = node.firstChild) === null) {
8806
        break;
8807
      } // Moving from `node` to its first child `next`.
8808
8809
8810
      parentNode = node;
8811
      node = next;
8812
    }
8813
8814
    while (true) {
8815
      if (node === outerNode) {
8816
        // If `outerNode` has children, this is always the second time visiting
8817
        // it. If it has no children, this is still the first loop, and the only
8818
        // valid selection is anchorNode and focusNode both equal to this node
8819
        // and both offsets 0, in which case we will have handled above.
8820
        break outer;
8821
      }
8822
8823
      if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
8824
        start = length;
8825
      }
8826
8827
      if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
8828
        end = length;
8829
      }
8830
8831
      if ((next = node.nextSibling) !== null) {
8832
        break;
8833
      }
8834
8835
      node = parentNode;
8836
      parentNode = node.parentNode;
8837
    } // Moving from `node` to its next sibling `next`.
8838
8839
8840
    node = next;
8841
  }
8842
8843
  if (start === -1 || end === -1) {
8844
    // This should never happen. (Would happen if the anchor/focus nodes aren't
8845
    // actually inside the passed-in node.)
8846
    return null;
8847
  }
8848
8849
  return {
8850
    start: start,
8851
    end: end
8852
  };
8853
}
8854
/**
8855
 * In modern non-IE browsers, we can support both forward and backward
8856
 * selections.
8857
 *
8858
 * Note: IE10+ supports the Selection object, but it does not support
8859
 * the `extend` method, which means that even in modern IE, it's not possible
8860
 * to programmatically create a backward selection. Thus, for all IE
8861
 * versions, we use the old IE API to create our selections.
8862
 *
8863
 * @param {DOMElement|DOMTextNode} node
8864
 * @param {object} offsets
8865
 */
8866
8867
function setOffsets(node, offsets) {
8868
  var doc = node.ownerDocument || document;
8869
  var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios.
8870
  // (For instance: TinyMCE editor used in a list component that supports pasting to add more,
8871
  // fails when pasting 100+ items)
8872
8873
  if (!win.getSelection) {
8874
    return;
8875
  }
8876
8877
  var selection = win.getSelection();
8878
  var length = node.textContent.length;
8879
  var start = Math.min(offsets.start, length);
8880
  var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method.
8881
  // Flip backward selections, so we can set with a single range.
8882
8883
  if (!selection.extend && start > end) {
8884
    var temp = end;
8885
    end = start;
8886
    start = temp;
8887
  }
8888
8889
  var startMarker = getNodeForCharacterOffset(node, start);
8890
  var endMarker = getNodeForCharacterOffset(node, end);
8891
8892
  if (startMarker && endMarker) {
8893
    if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
8894
      return;
8895
    }
8896
8897
    var range = doc.createRange();
8898
    range.setStart(startMarker.node, startMarker.offset);
8899
    selection.removeAllRanges();
8900
8901
    if (start > end) {
8902
      selection.addRange(range);
8903
      selection.extend(endMarker.node, endMarker.offset);
8904
    } else {
8905
      range.setEnd(endMarker.node, endMarker.offset);
8906
      selection.addRange(range);
8907
    }
8908
  }
8909
}
8910
8911
function isTextNode(node) {
8912
  return node && node.nodeType === TEXT_NODE;
8913
}
8914
8915
function containsNode(outerNode, innerNode) {
8916
  if (!outerNode || !innerNode) {
8917
    return false;
8918
  } else if (outerNode === innerNode) {
8919
    return true;
8920
  } else if (isTextNode(outerNode)) {
8921
    return false;
8922
  } else if (isTextNode(innerNode)) {
8923
    return containsNode(outerNode, innerNode.parentNode);
8924
  } else if ('contains' in outerNode) {
8925
    return outerNode.contains(innerNode);
8926
  } else if (outerNode.compareDocumentPosition) {
8927
    return !!(outerNode.compareDocumentPosition(innerNode) & 16);
8928
  } else {
8929
    return false;
8930
  }
8931
}
8932
8933
function isInDocument(node) {
8934
  return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
8935
}
8936
8937
function isSameOriginFrame(iframe) {
8938
  try {
8939
    // Accessing the contentDocument of a HTMLIframeElement can cause the browser
8940
    // to throw, e.g. if it has a cross-origin src attribute.
8941
    // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
8942
    // iframe.contentDocument.defaultView;
8943
    // A safety way is to access one of the cross origin properties: Window or Location
8944
    // Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
8945
    // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
8946
    return typeof iframe.contentWindow.location.href === 'string';
8947
  } catch (err) {
8948
    return false;
8949
  }
8950
}
8951
8952
function getActiveElementDeep() {
8953
  var win = window;
8954
  var element = getActiveElement();
8955
8956
  while (element instanceof win.HTMLIFrameElement) {
8957
    if (isSameOriginFrame(element)) {
8958
      win = element.contentWindow;
8959
    } else {
8960
      return element;
8961
    }
8962
8963
    element = getActiveElement(win.document);
8964
  }
8965
8966
  return element;
8967
}
8968
/**
8969
 * @ReactInputSelection: React input selection module. Based on Selection.js,
8970
 * but modified to be suitable for react and has a couple of bug fixes (doesn't
8971
 * assume buttons have range selections allowed).
8972
 * Input selection module for React.
8973
 */
8974
8975
/**
8976
 * @hasSelectionCapabilities: we get the element types that support selection
8977
 * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
8978
 * and `selectionEnd` rows.
8979
 */
8980
8981
8982
function hasSelectionCapabilities(elem) {
8983
  var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
8984
  return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
8985
}
8986
function getSelectionInformation() {
8987
  var focusedElem = getActiveElementDeep();
8988
  return {
8989
    focusedElem: focusedElem,
8990
    selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null
8991
  };
8992
}
8993
/**
8994
 * @restoreSelection: If any selection information was potentially lost,
8995
 * restore it. This is useful when performing operations that could remove dom
8996
 * nodes and place them back in, resulting in focus being lost.
8997
 */
8998
8999
function restoreSelection(priorSelectionInformation) {
9000
  var curFocusedElem = getActiveElementDeep();
9001
  var priorFocusedElem = priorSelectionInformation.focusedElem;
9002
  var priorSelectionRange = priorSelectionInformation.selectionRange;
9003
9004
  if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
9005
    if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
9006
      setSelection(priorFocusedElem, priorSelectionRange);
9007
    } // Focusing a node can change the scroll position, which is undesirable
9008
9009
9010
    var ancestors = [];
9011
    var ancestor = priorFocusedElem;
9012
9013
    while (ancestor = ancestor.parentNode) {
9014
      if (ancestor.nodeType === ELEMENT_NODE) {
9015
        ancestors.push({
9016
          element: ancestor,
9017
          left: ancestor.scrollLeft,
9018
          top: ancestor.scrollTop
9019
        });
9020
      }
9021
    }
9022
9023
    if (typeof priorFocusedElem.focus === 'function') {
9024
      priorFocusedElem.focus();
9025
    }
9026
9027
    for (var i = 0; i < ancestors.length; i++) {
9028
      var info = ancestors[i];
9029
      info.element.scrollLeft = info.left;
9030
      info.element.scrollTop = info.top;
9031
    }
9032
  }
9033
}
9034
/**
9035
 * @getSelection: Gets the selection bounds of a focused textarea, input or
9036
 * contentEditable node.
9037
 * -@input: Look up selection bounds of this input
9038
 * -@return {start: selectionStart, end: selectionEnd}
9039
 */
9040
9041
function getSelection(input) {
9042
  var selection;
9043
9044
  if ('selectionStart' in input) {
9045
    // Modern browser with input or textarea.
9046
    selection = {
9047
      start: input.selectionStart,
9048
      end: input.selectionEnd
9049
    };
9050
  } else {
9051
    // Content editable or old IE textarea.
9052
    selection = getOffsets(input);
9053
  }
9054
9055
  return selection || {
9056
    start: 0,
9057
    end: 0
9058
  };
9059
}
9060
/**
9061
 * @setSelection: Sets the selection bounds of a textarea or input and focuses
9062
 * the input.
9063
 * -@input     Set selection bounds of this input or textarea
9064
 * -@offsets   Object of same form that is returned from get*
9065
 */
9066
9067
function setSelection(input, offsets) {
9068
  var start = offsets.start,
9069
      end = offsets.end;
9070
9071
  if (end === undefined) {
9072
    end = start;
9073
  }
9074
9075
  if ('selectionStart' in input) {
9076
    input.selectionStart = start;
9077
    input.selectionEnd = Math.min(end, input.value.length);
9078
  } else {
9079
    setOffsets(input, offsets);
9080
  }
9081
}
9082
9083
var validateDOMNesting = function () {};
9084
9085
var updatedAncestorInfo = function () {};
9086
9087
{
9088
  // This validation code was written based on the HTML5 parsing spec:
9089
  // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
9090
  //
9091
  // Note: this does not catch all invalid nesting, nor does it try to (as it's
9092
  // not clear what practical benefit doing so provides); instead, we warn only
9093
  // for cases where the parser will give a parse tree differing from what React
9094
  // intended. For example, <b><div></div></b> is invalid but we don't warn
9095
  // because it still parses correctly; we do warn for other cases like nested
9096
  // <p> tags where the beginning of the second element implicitly closes the
9097
  // first, causing a confusing mess.
9098
  // https://html.spec.whatwg.org/multipage/syntax.html#special
9099
  var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
9100
9101
  var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
9102
  // TODO: Distinguish by namespace here -- for <title>, including it here
9103
  // errs on the side of fewer warnings
9104
  'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
9105
9106
  var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
9107
9108
  var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
9109
  var emptyAncestorInfo = {
9110
    current: null,
9111
    formTag: null,
9112
    aTagInScope: null,
9113
    buttonTagInScope: null,
9114
    nobrTagInScope: null,
9115
    pTagInButtonScope: null,
9116
    listItemTagAutoclosing: null,
9117
    dlItemTagAutoclosing: null
9118
  };
9119
9120
  updatedAncestorInfo = function (oldInfo, tag) {
9121
    var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
9122
9123
    var info = {
9124
      tag: tag
9125
    };
9126
9127
    if (inScopeTags.indexOf(tag) !== -1) {
9128
      ancestorInfo.aTagInScope = null;
9129
      ancestorInfo.buttonTagInScope = null;
9130
      ancestorInfo.nobrTagInScope = null;
9131
    }
9132
9133
    if (buttonScopeTags.indexOf(tag) !== -1) {
9134
      ancestorInfo.pTagInButtonScope = null;
9135
    } // See rules for 'li', 'dd', 'dt' start tags in
9136
    // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
9137
9138
9139
    if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
9140
      ancestorInfo.listItemTagAutoclosing = null;
9141
      ancestorInfo.dlItemTagAutoclosing = null;
9142
    }
9143
9144
    ancestorInfo.current = info;
9145
9146
    if (tag === 'form') {
9147
      ancestorInfo.formTag = info;
9148
    }
9149
9150
    if (tag === 'a') {
9151
      ancestorInfo.aTagInScope = info;
9152
    }
9153
9154
    if (tag === 'button') {
9155
      ancestorInfo.buttonTagInScope = info;
9156
    }
9157
9158
    if (tag === 'nobr') {
9159
      ancestorInfo.nobrTagInScope = info;
9160
    }
9161
9162
    if (tag === 'p') {
9163
      ancestorInfo.pTagInButtonScope = info;
9164
    }
9165
9166
    if (tag === 'li') {
9167
      ancestorInfo.listItemTagAutoclosing = info;
9168
    }
9169
9170
    if (tag === 'dd' || tag === 'dt') {
9171
      ancestorInfo.dlItemTagAutoclosing = info;
9172
    }
9173
9174
    return ancestorInfo;
9175
  };
9176
  /**
9177
   * Returns whether
9178
   */
9179
9180
9181
  var isTagValidWithParent = function (tag, parentTag) {
9182
    // First, let's check if we're in an unusual parsing mode...
9183
    switch (parentTag) {
9184
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
9185
      case 'select':
9186
        return tag === 'option' || tag === 'optgroup' || tag === '#text';
9187
9188
      case 'optgroup':
9189
        return tag === 'option' || tag === '#text';
9190
      // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
9191
      // but
9192
9193
      case 'option':
9194
        return tag === '#text';
9195
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
9196
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
9197
      // No special behavior since these rules fall back to "in body" mode for
9198
      // all except special table nodes which cause bad parsing behavior anyway.
9199
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
9200
9201
      case 'tr':
9202
        return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
9203
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
9204
9205
      case 'tbody':
9206
      case 'thead':
9207
      case 'tfoot':
9208
        return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
9209
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
9210
9211
      case 'colgroup':
9212
        return tag === 'col' || tag === 'template';
9213
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
9214
9215
      case 'table':
9216
        return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
9217
      // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
9218
9219
      case 'head':
9220
        return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
9221
      // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
9222
9223
      case 'html':
9224
        return tag === 'head' || tag === 'body' || tag === 'frameset';
9225
9226
      case 'frameset':
9227
        return tag === 'frame';
9228
9229
      case '#document':
9230
        return tag === 'html';
9231
    } // Probably in the "in body" parsing mode, so we outlaw only tag combos
9232
    // where the parsing rules cause implicit opens or closes to be added.
9233
    // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
9234
9235
9236
    switch (tag) {
9237
      case 'h1':
9238
      case 'h2':
9239
      case 'h3':
9240
      case 'h4':
9241
      case 'h5':
9242
      case 'h6':
9243
        return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
9244
9245
      case 'rp':
9246
      case 'rt':
9247
        return impliedEndTags.indexOf(parentTag) === -1;
9248
9249
      case 'body':
9250
      case 'caption':
9251
      case 'col':
9252
      case 'colgroup':
9253
      case 'frameset':
9254
      case 'frame':
9255
      case 'head':
9256
      case 'html':
9257
      case 'tbody':
9258
      case 'td':
9259
      case 'tfoot':
9260
      case 'th':
9261
      case 'thead':
9262
      case 'tr':
9263
        // These tags are only valid with a few parents that have special child
9264
        // parsing rules -- if we're down here, then none of those matched and
9265
        // so we allow it only if we don't know what the parent is, as all other
9266
        // cases are invalid.
9267
        return parentTag == null;
9268
    }
9269
9270
    return true;
9271
  };
9272
  /**
9273
   * Returns whether
9274
   */
9275
9276
9277
  var findInvalidAncestorForTag = function (tag, ancestorInfo) {
9278
    switch (tag) {
9279
      case 'address':
9280
      case 'article':
9281
      case 'aside':
9282
      case 'blockquote':
9283
      case 'center':
9284
      case 'details':
9285
      case 'dialog':
9286
      case 'dir':
9287
      case 'div':
9288
      case 'dl':
9289
      case 'fieldset':
9290
      case 'figcaption':
9291
      case 'figure':
9292
      case 'footer':
9293
      case 'header':
9294
      case 'hgroup':
9295
      case 'main':
9296
      case 'menu':
9297
      case 'nav':
9298
      case 'ol':
9299
      case 'p':
9300
      case 'section':
9301
      case 'summary':
9302
      case 'ul':
9303
      case 'pre':
9304
      case 'listing':
9305
      case 'table':
9306
      case 'hr':
9307
      case 'xmp':
9308
      case 'h1':
9309
      case 'h2':
9310
      case 'h3':
9311
      case 'h4':
9312
      case 'h5':
9313
      case 'h6':
9314
        return ancestorInfo.pTagInButtonScope;
9315
9316
      case 'form':
9317
        return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
9318
9319
      case 'li':
9320
        return ancestorInfo.listItemTagAutoclosing;
9321
9322
      case 'dd':
9323
      case 'dt':
9324
        return ancestorInfo.dlItemTagAutoclosing;
9325
9326
      case 'button':
9327
        return ancestorInfo.buttonTagInScope;
9328
9329
      case 'a':
9330
        // Spec says something about storing a list of markers, but it sounds
9331
        // equivalent to this check.
9332
        return ancestorInfo.aTagInScope;
9333
9334
      case 'nobr':
9335
        return ancestorInfo.nobrTagInScope;
9336
    }
9337
9338
    return null;
9339
  };
9340
9341
  var didWarn$1 = {};
9342
9343
  validateDOMNesting = function (childTag, childText, ancestorInfo) {
9344
    ancestorInfo = ancestorInfo || emptyAncestorInfo;
9345
    var parentInfo = ancestorInfo.current;
9346
    var parentTag = parentInfo && parentInfo.tag;
9347
9348
    if (childText != null) {
9349
      !(childTag == null) ? warningWithoutStack$1(false, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0;
9350
      childTag = '#text';
9351
    }
9352
9353
    var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
9354
    var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
9355
    var invalidParentOrAncestor = invalidParent || invalidAncestor;
9356
9357
    if (!invalidParentOrAncestor) {
9358
      return;
9359
    }
9360
9361
    var ancestorTag = invalidParentOrAncestor.tag;
9362
    var addendum = getCurrentFiberStackInDev();
9363
    var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;
9364
9365
    if (didWarn$1[warnKey]) {
9366
      return;
9367
    }
9368
9369
    didWarn$1[warnKey] = true;
9370
    var tagDisplayName = childTag;
9371
    var whitespaceInfo = '';
9372
9373
    if (childTag === '#text') {
9374
      if (/\S/.test(childText)) {
9375
        tagDisplayName = 'Text nodes';
9376
      } else {
9377
        tagDisplayName = 'Whitespace text nodes';
9378
        whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
9379
      }
9380
    } else {
9381
      tagDisplayName = '<' + childTag + '>';
9382
    }
9383
9384
    if (invalidParent) {
9385
      var info = '';
9386
9387
      if (ancestorTag === 'table' && childTag === 'tr') {
9388
        info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.';
9389
      }
9390
9391
      warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info, addendum);
9392
    } else {
9393
      warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.%s', tagDisplayName, ancestorTag, addendum);
9394
    }
9395
  };
9396
}
9397
9398
// can re-export everything from this module.
9399
9400
function shim() {
9401
  (function () {
9402
    {
9403
      {
9404
        throw ReactError(Error("The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue."));
9405
      }
9406
    }
9407
  })();
9408
} // Persistence (when unsupported)
9409
9410
9411
var supportsPersistence = false;
9412
var cloneInstance = shim;
9413
var cloneFundamentalInstance = shim;
9414
var createContainerChildSet = shim;
9415
var appendChildToContainerChildSet = shim;
9416
var finalizeContainerChildren = shim;
9417
var replaceContainerChildren = shim;
9418
var cloneHiddenInstance = shim;
9419
var cloneHiddenTextInstance = shim;
9420
9421
var SUPPRESS_HYDRATION_WARNING;
9422
9423
{
9424
  SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
9425
}
9426
9427
var SUSPENSE_START_DATA = '$';
9428
var SUSPENSE_END_DATA = '/$';
9429
var SUSPENSE_PENDING_START_DATA = '$?';
9430
var SUSPENSE_FALLBACK_START_DATA = '$!';
9431
var STYLE = 'style';
9432
var eventsEnabled = null;
9433
var selectionInformation = null;
9434
9435
function shouldAutoFocusHostComponent(type, props) {
9436
  switch (type) {
9437
    case 'button':
9438
    case 'input':
9439
    case 'select':
9440
    case 'textarea':
9441
      return !!props.autoFocus;
9442
  }
9443
9444
  return false;
9445
}
9446
9447
function getRootHostContext(rootContainerInstance) {
9448
  var type;
9449
  var namespace;
9450
  var nodeType = rootContainerInstance.nodeType;
9451
9452
  switch (nodeType) {
9453
    case DOCUMENT_NODE:
9454
    case DOCUMENT_FRAGMENT_NODE:
9455
      {
9456
        type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
9457
        var root = rootContainerInstance.documentElement;
9458
        namespace = root ? root.namespaceURI : getChildNamespace(null, '');
9459
        break;
9460
      }
9461
9462
    default:
9463
      {
9464
        var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
9465
        var ownNamespace = container.namespaceURI || null;
9466
        type = container.tagName;
9467
        namespace = getChildNamespace(ownNamespace, type);
9468
        break;
9469
      }
9470
  }
9471
9472
  {
9473
    var validatedTag = type.toLowerCase();
9474
    var ancestorInfo = updatedAncestorInfo(null, validatedTag);
9475
    return {
9476
      namespace: namespace,
9477
      ancestorInfo: ancestorInfo
9478
    };
9479
  }
9480
9481
  return namespace;
9482
}
9483
function getChildHostContext(parentHostContext, type, rootContainerInstance) {
9484
  {
9485
    var parentHostContextDev = parentHostContext;
9486
    var namespace = getChildNamespace(parentHostContextDev.namespace, type);
9487
    var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
9488
    return {
9489
      namespace: namespace,
9490
      ancestorInfo: ancestorInfo
9491
    };
9492
  }
9493
9494
  var parentNamespace = parentHostContext;
9495
  return getChildNamespace(parentNamespace, type);
9496
}
9497
function getPublicInstance(instance) {
9498
  return instance;
9499
}
9500
function prepareForCommit(containerInfo) {
9501
  eventsEnabled = isEnabled();
9502
  selectionInformation = getSelectionInformation();
9503
  setEnabled(false);
9504
}
9505
function resetAfterCommit(containerInfo) {
9506
  restoreSelection(selectionInformation);
9507
  selectionInformation = null;
9508
  setEnabled(eventsEnabled);
9509
  eventsEnabled = null;
9510
}
9511
function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
9512
  var parentNamespace;
9513
9514
  {
9515
    // TODO: take namespace into account when validating.
9516
    var hostContextDev = hostContext;
9517
    validateDOMNesting(type, null, hostContextDev.ancestorInfo);
9518
9519
    if (typeof props.children === 'string' || typeof props.children === 'number') {
9520
      var string = '' + props.children;
9521
      var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
9522
      validateDOMNesting(null, string, ownAncestorInfo);
9523
    }
9524
9525
    parentNamespace = hostContextDev.namespace;
9526
  }
9527
9528
  var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
9529
  precacheFiberNode(internalInstanceHandle, domElement);
9530
  updateFiberProps(domElement, props);
9531
  return domElement;
9532
}
9533
function appendInitialChild(parentInstance, child) {
9534
  parentInstance.appendChild(child);
9535
}
9536
function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
9537
  setInitialProperties(domElement, type, props, rootContainerInstance);
9538
  return shouldAutoFocusHostComponent(type, props);
9539
}
9540
function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
9541
  {
9542
    var hostContextDev = hostContext;
9543
9544
    if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
9545
      var string = '' + newProps.children;
9546
      var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
9547
      validateDOMNesting(null, string, ownAncestorInfo);
9548
    }
9549
  }
9550
9551
  return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);
9552
}
9553
function shouldSetTextContent(type, props) {
9554
  return type === 'textarea' || type === 'option' || type === 'noscript' || typeof props.children === 'string' || typeof props.children === 'number' || typeof props.dangerouslySetInnerHTML === 'object' && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null;
9555
}
9556
function shouldDeprioritizeSubtree(type, props) {
9557
  return !!props.hidden;
9558
}
9559
function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
9560
  {
9561
    var hostContextDev = hostContext;
9562
    validateDOMNesting(null, text, hostContextDev.ancestorInfo);
9563
  }
9564
9565
  var textNode = createTextNode(text, rootContainerInstance);
9566
  precacheFiberNode(internalInstanceHandle, textNode);
9567
  return textNode;
9568
}
9569
var isPrimaryRenderer = true;
9570
var warnsIfNotActing = true; // This initialization code may run even on server environments
9571
// if a component just imports ReactDOM (e.g. for findDOMNode).
9572
// Some environments might not have setTimeout or clearTimeout.
9573
9574
var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
9575
var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
9576
var noTimeout = -1; // -------------------
9577
//     Mutation
9578
// -------------------
9579
9580
var supportsMutation = true;
9581
function commitMount(domElement, type, newProps, internalInstanceHandle) {
9582
  // Despite the naming that might imply otherwise, this method only
9583
  // fires if there is an `Update` effect scheduled during mounting.
9584
  // This happens if `finalizeInitialChildren` returns `true` (which it
9585
  // does to implement the `autoFocus` attribute on the client). But
9586
  // there are also other cases when this might happen (such as patching
9587
  // up text content during hydration mismatch). So we'll check this again.
9588
  if (shouldAutoFocusHostComponent(type, newProps)) {
9589
    domElement.focus();
9590
  }
9591
}
9592
function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
9593
  // Update the props handle so that we know which props are the ones with
9594
  // with current event handlers.
9595
  updateFiberProps(domElement, newProps); // Apply the diff to the DOM node.
9596
9597
  updateProperties(domElement, updatePayload, type, oldProps, newProps);
9598
}
9599
function resetTextContent(domElement) {
9600
  setTextContent(domElement, '');
9601
}
9602
function commitTextUpdate(textInstance, oldText, newText) {
9603
  textInstance.nodeValue = newText;
9604
}
9605
function appendChild(parentInstance, child) {
9606
  parentInstance.appendChild(child);
9607
}
9608
function appendChildToContainer(container, child) {
9609
  var parentNode;
9610
9611
  if (container.nodeType === COMMENT_NODE) {
9612
    parentNode = container.parentNode;
9613
    parentNode.insertBefore(child, container);
9614
  } else {
9615
    parentNode = container;
9616
    parentNode.appendChild(child);
9617
  } // This container might be used for a portal.
9618
  // If something inside a portal is clicked, that click should bubble
9619
  // through the React tree. However, on Mobile Safari the click would
9620
  // never bubble through the *DOM* tree unless an ancestor with onclick
9621
  // event exists. So we wouldn't see it and dispatch it.
9622
  // This is why we ensure that non React root containers have inline onclick
9623
  // defined.
9624
  // https://github.com/facebook/react/issues/11918
9625
9626
9627
  var reactRootContainer = container._reactRootContainer;
9628
9629
  if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
9630
    // TODO: This cast may not be sound for SVG, MathML or custom elements.
9631
    trapClickOnNonInteractiveElement(parentNode);
9632
  }
9633
}
9634
function insertBefore(parentInstance, child, beforeChild) {
9635
  parentInstance.insertBefore(child, beforeChild);
9636
}
9637
function insertInContainerBefore(container, child, beforeChild) {
9638
  if (container.nodeType === COMMENT_NODE) {
9639
    container.parentNode.insertBefore(child, beforeChild);
9640
  } else {
9641
    container.insertBefore(child, beforeChild);
9642
  }
9643
}
9644
function removeChild(parentInstance, child) {
9645
  parentInstance.removeChild(child);
9646
}
9647
function removeChildFromContainer(container, child) {
9648
  if (container.nodeType === COMMENT_NODE) {
9649
    container.parentNode.removeChild(child);
9650
  } else {
9651
    container.removeChild(child);
9652
  }
9653
}
9654
function clearSuspenseBoundary(parentInstance, suspenseInstance) {
9655
  var node = suspenseInstance; // Delete all nodes within this suspense boundary.
9656
  // There might be nested nodes so we need to keep track of how
9657
  // deep we are and only break out when we're back on top.
9658
9659
  var depth = 0;
9660
9661
  do {
9662
    var nextNode = node.nextSibling;
9663
    parentInstance.removeChild(node);
9664
9665
    if (nextNode && nextNode.nodeType === COMMENT_NODE) {
9666
      var data = nextNode.data;
9667
9668
      if (data === SUSPENSE_END_DATA) {
9669
        if (depth === 0) {
9670
          parentInstance.removeChild(nextNode); // Retry if any event replaying was blocked on this.
9671
9672
          retryIfBlockedOn(suspenseInstance);
9673
          return;
9674
        } else {
9675
          depth--;
9676
        }
9677
      } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_FALLBACK_START_DATA) {
9678
        depth++;
9679
      }
9680
    }
9681
9682
    node = nextNode;
9683
  } while (node); // TODO: Warn, we didn't find the end comment boundary.
9684
  // Retry if any event replaying was blocked on this.
9685
9686
9687
  retryIfBlockedOn(suspenseInstance);
9688
}
9689
function clearSuspenseBoundaryFromContainer(container, suspenseInstance) {
9690
  if (container.nodeType === COMMENT_NODE) {
9691
    clearSuspenseBoundary(container.parentNode, suspenseInstance);
9692
  } else if (container.nodeType === ELEMENT_NODE) {
9693
    clearSuspenseBoundary(container, suspenseInstance);
9694
  } else {} // Document nodes should never contain suspense boundaries.
9695
  // Retry if any event replaying was blocked on this.
9696
9697
9698
  retryIfBlockedOn(container);
9699
}
9700
function hideInstance(instance) {
9701
  // TODO: Does this work for all element types? What about MathML? Should we
9702
  // pass host context to this method?
9703
  instance = instance;
9704
  var style = instance.style;
9705
9706
  if (typeof style.setProperty === 'function') {
9707
    style.setProperty('display', 'none', 'important');
9708
  } else {
9709
    style.display = 'none';
9710
  }
9711
}
9712
function hideTextInstance(textInstance) {
9713
  textInstance.nodeValue = '';
9714
}
9715
function unhideInstance(instance, props) {
9716
  instance = instance;
9717
  var styleProp = props[STYLE];
9718
  var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
9719
  instance.style.display = dangerousStyleValue('display', display);
9720
}
9721
function unhideTextInstance(textInstance, text) {
9722
  textInstance.nodeValue = text;
9723
} // -------------------
9724
//     Hydration
9725
// -------------------
9726
9727
var supportsHydration = true;
9728
function canHydrateInstance(instance, type, props) {
9729
  if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
9730
    return null;
9731
  } // This has now been refined to an element node.
9732
9733
9734
  return instance;
9735
}
9736
function canHydrateTextInstance(instance, text) {
9737
  if (text === '' || instance.nodeType !== TEXT_NODE) {
9738
    // Empty strings are not parsed by HTML so there won't be a correct match here.
9739
    return null;
9740
  } // This has now been refined to a text node.
9741
9742
9743
  return instance;
9744
}
9745
function canHydrateSuspenseInstance(instance) {
9746
  if (instance.nodeType !== COMMENT_NODE) {
9747
    // Empty strings are not parsed by HTML so there won't be a correct match here.
9748
    return null;
9749
  } // This has now been refined to a suspense node.
9750
9751
9752
  return instance;
9753
}
9754
function isSuspenseInstancePending(instance) {
9755
  return instance.data === SUSPENSE_PENDING_START_DATA;
9756
}
9757
function isSuspenseInstanceFallback(instance) {
9758
  return instance.data === SUSPENSE_FALLBACK_START_DATA;
9759
}
9760
function registerSuspenseInstanceRetry(instance, callback) {
9761
  instance._reactRetry = callback;
9762
}
9763
9764
function getNextHydratable(node) {
9765
  // Skip non-hydratable nodes.
9766
  for (; node != null; node = node.nextSibling) {
9767
    var nodeType = node.nodeType;
9768
9769
    if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {
9770
      break;
9771
    }
9772
9773
    if (enableSuspenseServerRenderer) {
9774
      if (nodeType === COMMENT_NODE) {
9775
        var nodeData = node.data;
9776
9777
        if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) {
9778
          break;
9779
        }
9780
      }
9781
    }
9782
  }
9783
9784
  return node;
9785
}
9786
9787
function getNextHydratableSibling(instance) {
9788
  return getNextHydratable(instance.nextSibling);
9789
}
9790
function getFirstHydratableChild(parentInstance) {
9791
  return getNextHydratable(parentInstance.firstChild);
9792
}
9793
function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
9794
  precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events
9795
  // get attached.
9796
9797
  updateFiberProps(instance, props);
9798
  var parentNamespace;
9799
9800
  {
9801
    var hostContextDev = hostContext;
9802
    parentNamespace = hostContextDev.namespace;
9803
  }
9804
9805
  return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);
9806
}
9807
function hydrateTextInstance(textInstance, text, internalInstanceHandle) {
9808
  precacheFiberNode(internalInstanceHandle, textInstance);
9809
  return diffHydratedText(textInstance, text);
9810
}
9811
function hydrateSuspenseInstance(suspenseInstance, internalInstanceHandle) {
9812
  precacheFiberNode(internalInstanceHandle, suspenseInstance);
9813
}
9814
function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
9815
  var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary.
9816
  // There might be nested nodes so we need to keep track of how
9817
  // deep we are and only break out when we're back on top.
9818
9819
  var depth = 0;
9820
9821
  while (node) {
9822
    if (node.nodeType === COMMENT_NODE) {
9823
      var data = node.data;
9824
9825
      if (data === SUSPENSE_END_DATA) {
9826
        if (depth === 0) {
9827
          return getNextHydratableSibling(node);
9828
        } else {
9829
          depth--;
9830
        }
9831
      } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
9832
        depth++;
9833
      }
9834
    }
9835
9836
    node = node.nextSibling;
9837
  } // TODO: Warn, we didn't find the end comment boundary.
9838
9839
9840
  return null;
9841
} // Returns the SuspenseInstance if this node is a direct child of a
9842
// SuspenseInstance. I.e. if its previous sibling is a Comment with
9843
// SUSPENSE_x_START_DATA. Otherwise, null.
9844
9845
function getParentSuspenseInstance(targetInstance) {
9846
  var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary.
9847
  // There might be nested nodes so we need to keep track of how
9848
  // deep we are and only break out when we're back on top.
9849
9850
  var depth = 0;
9851
9852
  while (node) {
9853
    if (node.nodeType === COMMENT_NODE) {
9854
      var data = node.data;
9855
9856
      if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
9857
        if (depth === 0) {
9858
          return node;
9859
        } else {
9860
          depth--;
9861
        }
9862
      } else if (data === SUSPENSE_END_DATA) {
9863
        depth++;
9864
      }
9865
    }
9866
9867
    node = node.previousSibling;
9868
  }
9869
9870
  return null;
9871
}
9872
function commitHydratedContainer(container) {
9873
  // Retry if any event replaying was blocked on this.
9874
  retryIfBlockedOn(container);
9875
}
9876
function commitHydratedSuspenseInstance(suspenseInstance) {
9877
  // Retry if any event replaying was blocked on this.
9878
  retryIfBlockedOn(suspenseInstance);
9879
}
9880
function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {
9881
  {
9882
    warnForUnmatchedText(textInstance, text);
9883
  }
9884
}
9885
function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {
9886
  if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9887
    warnForUnmatchedText(textInstance, text);
9888
  }
9889
}
9890
function didNotHydrateContainerInstance(parentContainer, instance) {
9891
  {
9892
    if (instance.nodeType === ELEMENT_NODE) {
9893
      warnForDeletedHydratableElement(parentContainer, instance);
9894
    } else if (instance.nodeType === COMMENT_NODE) {// TODO: warnForDeletedHydratableSuspenseBoundary
9895
    } else {
9896
      warnForDeletedHydratableText(parentContainer, instance);
9897
    }
9898
  }
9899
}
9900
function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {
9901
  if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9902
    if (instance.nodeType === ELEMENT_NODE) {
9903
      warnForDeletedHydratableElement(parentInstance, instance);
9904
    } else if (instance.nodeType === COMMENT_NODE) {// TODO: warnForDeletedHydratableSuspenseBoundary
9905
    } else {
9906
      warnForDeletedHydratableText(parentInstance, instance);
9907
    }
9908
  }
9909
}
9910
function didNotFindHydratableContainerInstance(parentContainer, type, props) {
9911
  {
9912
    warnForInsertedHydratedElement(parentContainer, type, props);
9913
  }
9914
}
9915
function didNotFindHydratableContainerTextInstance(parentContainer, text) {
9916
  {
9917
    warnForInsertedHydratedText(parentContainer, text);
9918
  }
9919
}
9920
9921
function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {
9922
  if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9923
    warnForInsertedHydratedElement(parentInstance, type, props);
9924
  }
9925
}
9926
function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {
9927
  if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9928
    warnForInsertedHydratedText(parentInstance, text);
9929
  }
9930
}
9931
function didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance) {
9932
  if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {// TODO: warnForInsertedHydratedSuspense(parentInstance);
9933
  }
9934
}
9935
function mountResponderInstance(responder, responderInstance, responderProps, responderState, instance) {
9936
  // Listen to events
9937
  var doc = instance.ownerDocument;
9938
  var _ref = responder,
9939
      rootEventTypes = _ref.rootEventTypes,
9940
      targetEventTypes = _ref.targetEventTypes;
9941
9942
  if (targetEventTypes !== null) {
9943
    listenToEventResponderEventTypes(targetEventTypes, doc);
9944
  }
9945
9946
  if (rootEventTypes !== null) {
9947
    addRootEventTypesForResponderInstance(responderInstance, rootEventTypes);
9948
    listenToEventResponderEventTypes(rootEventTypes, doc);
9949
  }
9950
9951
  mountEventResponder(responder, responderInstance, responderProps, responderState);
9952
  return responderInstance;
9953
}
9954
function unmountResponderInstance(responderInstance) {
9955
  if (enableFlareAPI) {
9956
    // TODO stop listening to targetEventTypes
9957
    unmountEventResponder(responderInstance);
9958
  }
9959
}
9960
function getFundamentalComponentInstance(fundamentalInstance) {
9961
  if (enableFundamentalAPI) {
9962
    var currentFiber = fundamentalInstance.currentFiber,
9963
        impl = fundamentalInstance.impl,
9964
        props = fundamentalInstance.props,
9965
        state = fundamentalInstance.state;
9966
    var instance = impl.getInstance(null, props, state);
9967
    precacheFiberNode(currentFiber, instance);
9968
    return instance;
9969
  } // Because of the flag above, this gets around the Flow error;
9970
9971
9972
  return null;
9973
}
9974
function mountFundamentalComponent(fundamentalInstance) {
9975
  if (enableFundamentalAPI) {
9976
    var impl = fundamentalInstance.impl,
9977
        instance = fundamentalInstance.instance,
9978
        props = fundamentalInstance.props,
9979
        state = fundamentalInstance.state;
9980
    var onMount = impl.onMount;
9981
9982
    if (onMount !== undefined) {
9983
      onMount(null, instance, props, state);
9984
    }
9985
  }
9986
}
9987
function shouldUpdateFundamentalComponent(fundamentalInstance) {
9988
  if (enableFundamentalAPI) {
9989
    var impl = fundamentalInstance.impl,
9990
        prevProps = fundamentalInstance.prevProps,
9991
        props = fundamentalInstance.props,
9992
        state = fundamentalInstance.state;
9993
    var shouldUpdate = impl.shouldUpdate;
9994
9995
    if (shouldUpdate !== undefined) {
9996
      return shouldUpdate(null, prevProps, props, state);
9997
    }
9998
  }
9999
10000
  return true;
10001
}
10002
function updateFundamentalComponent(fundamentalInstance) {
10003
  if (enableFundamentalAPI) {
10004
    var impl = fundamentalInstance.impl,
10005
        instance = fundamentalInstance.instance,
10006
        prevProps = fundamentalInstance.prevProps,
10007
        props = fundamentalInstance.props,
10008
        state = fundamentalInstance.state;
10009
    var onUpdate = impl.onUpdate;
10010
10011
    if (onUpdate !== undefined) {
10012
      onUpdate(null, instance, prevProps, props, state);
10013
    }
10014
  }
10015
}
10016
function unmountFundamentalComponent(fundamentalInstance) {
10017
  if (enableFundamentalAPI) {
10018
    var impl = fundamentalInstance.impl,
10019
        instance = fundamentalInstance.instance,
10020
        props = fundamentalInstance.props,
10021
        state = fundamentalInstance.state;
10022
    var onUnmount = impl.onUnmount;
10023
10024
    if (onUnmount !== undefined) {
10025
      onUnmount(null, instance, props, state);
10026
    }
10027
  }
10028
}
10029
10030
var randomKey = Math.random().toString(36).slice(2);
10031
var internalInstanceKey = '__reactInternalInstance$' + randomKey;
10032
var internalEventHandlersKey = '__reactEventHandlers$' + randomKey;
10033
var internalContainerInstanceKey = '__reactContainere$' + randomKey;
10034
function precacheFiberNode(hostInst, node) {
10035
  node[internalInstanceKey] = hostInst;
10036
}
10037
function markContainerAsRoot(hostRoot, node) {
10038
  node[internalContainerInstanceKey] = hostRoot;
10039
} // Given a DOM node, return the closest HostComponent or HostText fiber ancestor.
10040
// If the target node is part of a hydrated or not yet rendered subtree, then
10041
// this may also return a SuspenseComponent or HostRoot to indicate that.
10042
// Conceptually the HostRoot fiber is a child of the Container node. So if you
10043
// pass the Container node as the targetNode, you wiill not actually get the
10044
// HostRoot back. To get to the HostRoot, you need to pass a child of it.
10045
// The same thing applies to Suspense boundaries.
10046
10047
function getClosestInstanceFromNode(targetNode) {
10048
  var targetInst = targetNode[internalInstanceKey];
10049
10050
  if (targetInst) {
10051
    // Don't return HostRoot or SuspenseComponent here.
10052
    return targetInst;
10053
  } // If the direct event target isn't a React owned DOM node, we need to look
10054
  // to see if one of its parents is a React owned DOM node.
10055
10056
10057
  var parentNode = targetNode.parentNode;
10058
10059
  while (parentNode) {
10060
    // We'll check if this is a container root that could include
10061
    // React nodes in the future. We need to check this first because
10062
    // if we're a child of a dehydrated container, we need to first
10063
    // find that inner container before moving on to finding the parent
10064
    // instance. Note that we don't check this field on  the targetNode
10065
    // itself because the fibers are conceptually between the container
10066
    // node and the first child. It isn't surrounding the container node.
10067
    // If it's not a container, we check if it's an instance.
10068
    targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];
10069
10070
    if (targetInst) {
10071
      // Since this wasn't the direct target of the event, we might have
10072
      // stepped past dehydrated DOM nodes to get here. However they could
10073
      // also have been non-React nodes. We need to answer which one.
10074
      // If we the instance doesn't have any children, then there can't be
10075
      // a nested suspense boundary within it. So we can use this as a fast
10076
      // bailout. Most of the time, when people add non-React children to
10077
      // the tree, it is using a ref to a child-less DOM node.
10078
      // Normally we'd only need to check one of the fibers because if it
10079
      // has ever gone from having children to deleting them or vice versa
10080
      // it would have deleted the dehydrated boundary nested inside already.
10081
      // However, since the HostRoot starts out with an alternate it might
10082
      // have one on the alternate so we need to check in case this was a
10083
      // root.
10084
      var alternate = targetInst.alternate;
10085
10086
      if (targetInst.child !== null || alternate !== null && alternate.child !== null) {
10087
        // Next we need to figure out if the node that skipped past is
10088
        // nested within a dehydrated boundary and if so, which one.
10089
        var suspenseInstance = getParentSuspenseInstance(targetNode);
10090
10091
        while (suspenseInstance !== null) {
10092
          // We found a suspense instance. That means that we haven't
10093
          // hydrated it yet. Even though we leave the comments in the
10094
          // DOM after hydrating, and there are boundaries in the DOM
10095
          // that could already be hydrated, we wouldn't have found them
10096
          // through this pass since if the target is hydrated it would
10097
          // have had an internalInstanceKey on it.
10098
          // Let's get the fiber associated with the SuspenseComponent
10099
          // as the deepest instance.
10100
          var targetSuspenseInst = suspenseInstance[internalInstanceKey];
10101
10102
          if (targetSuspenseInst) {
10103
            return targetSuspenseInst;
10104
          } // If we don't find a Fiber on the comment, it might be because
10105
          // we haven't gotten to hydrate it yet. There might still be a
10106
          // parent boundary that hasn't above this one so we need to find
10107
          // the outer most that is known.
10108
10109
10110
          suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent
10111
          // host component also hasn't hydrated yet. We can return it
10112
          // below since it will bail out on the isMounted check later.
10113
        }
10114
      }
10115
10116
      return targetInst;
10117
    }
10118
10119
    targetNode = parentNode;
10120
    parentNode = targetNode.parentNode;
10121
  }
10122
10123
  return null;
10124
}
10125
/**
10126
 * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
10127
 * instance, or null if the node was not rendered by this React.
10128
 */
10129
10130
function getInstanceFromNode$1(node) {
10131
  var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];
10132
10133
  if (inst) {
10134
    if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {
10135
      return inst;
10136
    } else {
10137
      return null;
10138
    }
10139
  }
10140
10141
  return null;
10142
}
10143
/**
10144
 * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
10145
 * DOM node.
10146
 */
10147
10148
function getNodeFromInstance$1(inst) {
10149
  if (inst.tag === HostComponent || inst.tag === HostText) {
10150
    // In Fiber this, is just the state node right now. We assume it will be
10151
    // a host component or host text.
10152
    return inst.stateNode;
10153
  } // Without this first invariant, passing a non-DOM-component triggers the next
10154
  // invariant for a missing parent, which is super confusing.
10155
10156
10157
  (function () {
10158
    {
10159
      {
10160
        throw ReactError(Error("getNodeFromInstance: Invalid argument."));
10161
      }
10162
    }
10163
  })();
10164
}
10165
function getFiberCurrentPropsFromNode$1(node) {
10166
  return node[internalEventHandlersKey] || null;
10167
}
10168
function updateFiberProps(node, props) {
10169
  node[internalEventHandlersKey] = props;
10170
}
10171
10172
/**
10173
 * These variables store information about text content of a target node,
10174
 * allowing comparison of content before and after a given event.
10175
 *
10176
 * Identify the node where selection currently begins, then observe
10177
 * both its text content and its current position in the DOM. Since the
10178
 * browser may natively replace the target node during composition, we can
10179
 * use its position to find its replacement.
10180
 *
10181
 *
10182
 */
10183
var root = null;
10184
var startText = null;
10185
var fallbackText = null;
10186
function initialize(nativeEventTarget) {
10187
  root = nativeEventTarget;
10188
  startText = getText();
10189
  return true;
10190
}
10191
function reset() {
10192
  root = null;
10193
  startText = null;
10194
  fallbackText = null;
10195
}
10196
function getData() {
10197
  if (fallbackText) {
10198
    return fallbackText;
10199
  }
10200
10201
  var start;
10202
  var startValue = startText;
10203
  var startLength = startValue.length;
10204
  var end;
10205
  var endValue = getText();
10206
  var endLength = endValue.length;
10207
10208
  for (start = 0; start < startLength; start++) {
10209
    if (startValue[start] !== endValue[start]) {
10210
      break;
10211
    }
10212
  }
10213
10214
  var minEnd = startLength - start;
10215
10216
  for (end = 1; end <= minEnd; end++) {
10217
    if (startValue[startLength - end] !== endValue[endLength - end]) {
10218
      break;
10219
    }
10220
  }
10221
10222
  var sliceTail = end > 1 ? 1 - end : undefined;
10223
  fallbackText = endValue.slice(start, sliceTail);
10224
  return fallbackText;
10225
}
10226
function getText() {
10227
  if ('value' in root) {
10228
    return root.value;
10229
  }
10230
10231
  return root.textContent;
10232
}
10233
10234
/**
10235
 * @interface Event
10236
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
10237
 */
10238
10239
var SyntheticCompositionEvent = SyntheticEvent.extend({
10240
  data: null
10241
});
10242
10243
/**
10244
 * @interface Event
10245
 * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
10246
 *      /#events-inputevents
10247
 */
10248
10249
var SyntheticInputEvent = SyntheticEvent.extend({
10250
  data: null
10251
});
10252
10253
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
10254
10255
var START_KEYCODE = 229;
10256
var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
10257
var documentMode = null;
10258
10259
if (canUseDOM && 'documentMode' in document) {
10260
  documentMode = document.documentMode;
10261
} // Webkit offers a very useful `textInput` event that can be used to
10262
// directly represent `beforeInput`. The IE `textinput` event is not as
10263
// useful, so we don't use it.
10264
10265
10266
var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied
10267
// by the native compositionend event may be incorrect. Japanese ideographic
10268
// spaces, for instance (\u3000) are not recorded correctly.
10269
10270
var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
10271
var SPACEBAR_CODE = 32;
10272
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); // Events and their corresponding property names.
10273
10274
var eventTypes$1 = {
10275
  beforeInput: {
10276
    phasedRegistrationNames: {
10277
      bubbled: 'onBeforeInput',
10278
      captured: 'onBeforeInputCapture'
10279
    },
10280
    dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]
10281
  },
10282
  compositionEnd: {
10283
    phasedRegistrationNames: {
10284
      bubbled: 'onCompositionEnd',
10285
      captured: 'onCompositionEndCapture'
10286
    },
10287
    dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
10288
  },
10289
  compositionStart: {
10290
    phasedRegistrationNames: {
10291
      bubbled: 'onCompositionStart',
10292
      captured: 'onCompositionStartCapture'
10293
    },
10294
    dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
10295
  },
10296
  compositionUpdate: {
10297
    phasedRegistrationNames: {
10298
      bubbled: 'onCompositionUpdate',
10299
      captured: 'onCompositionUpdateCapture'
10300
    },
10301
    dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
10302
  }
10303
}; // Track whether we've ever handled a keypress on the space key.
10304
10305
var hasSpaceKeypress = false;
10306
/**
10307
 * Return whether a native keypress event is assumed to be a command.
10308
 * This is required because Firefox fires `keypress` events for key commands
10309
 * (cut, copy, select-all, etc.) even though no character is inserted.
10310
 */
10311
10312
function isKeypressCommand(nativeEvent) {
10313
  return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.
10314
  !(nativeEvent.ctrlKey && nativeEvent.altKey);
10315
}
10316
/**
10317
 * Translate native top level events into event types.
10318
 *
10319
 * @param {string} topLevelType
10320
 * @return {object}
10321
 */
10322
10323
10324
function getCompositionEventType(topLevelType) {
10325
  switch (topLevelType) {
10326
    case TOP_COMPOSITION_START:
10327
      return eventTypes$1.compositionStart;
10328
10329
    case TOP_COMPOSITION_END:
10330
      return eventTypes$1.compositionEnd;
10331
10332
    case TOP_COMPOSITION_UPDATE:
10333
      return eventTypes$1.compositionUpdate;
10334
  }
10335
}
10336
/**
10337
 * Does our fallback best-guess model think this event signifies that
10338
 * composition has begun?
10339
 *
10340
 * @param {string} topLevelType
10341
 * @param {object} nativeEvent
10342
 * @return {boolean}
10343
 */
10344
10345
10346
function isFallbackCompositionStart(topLevelType, nativeEvent) {
10347
  return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;
10348
}
10349
/**
10350
 * Does our fallback mode think that this event is the end of composition?
10351
 *
10352
 * @param {string} topLevelType
10353
 * @param {object} nativeEvent
10354
 * @return {boolean}
10355
 */
10356
10357
10358
function isFallbackCompositionEnd(topLevelType, nativeEvent) {
10359
  switch (topLevelType) {
10360
    case TOP_KEY_UP:
10361
      // Command keys insert or clear IME input.
10362
      return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
10363
10364
    case TOP_KEY_DOWN:
10365
      // Expect IME keyCode on each keydown. If we get any other
10366
      // code we must have exited earlier.
10367
      return nativeEvent.keyCode !== START_KEYCODE;
10368
10369
    case TOP_KEY_PRESS:
10370
    case TOP_MOUSE_DOWN:
10371
    case TOP_BLUR:
10372
      // Events are not possible without cancelling IME.
10373
      return true;
10374
10375
    default:
10376
      return false;
10377
  }
10378
}
10379
/**
10380
 * Google Input Tools provides composition data via a CustomEvent,
10381
 * with the `data` property populated in the `detail` object. If this
10382
 * is available on the event object, use it. If not, this is a plain
10383
 * composition event and we have nothing special to extract.
10384
 *
10385
 * @param {object} nativeEvent
10386
 * @return {?string}
10387
 */
10388
10389
10390
function getDataFromCustomEvent(nativeEvent) {
10391
  var detail = nativeEvent.detail;
10392
10393
  if (typeof detail === 'object' && 'data' in detail) {
10394
    return detail.data;
10395
  }
10396
10397
  return null;
10398
}
10399
/**
10400
 * Check if a composition event was triggered by Korean IME.
10401
 * Our fallback mode does not work well with IE's Korean IME,
10402
 * so just use native composition events when Korean IME is used.
10403
 * Although CompositionEvent.locale property is deprecated,
10404
 * it is available in IE, where our fallback mode is enabled.
10405
 *
10406
 * @param {object} nativeEvent
10407
 * @return {boolean}
10408
 */
10409
10410
10411
function isUsingKoreanIME(nativeEvent) {
10412
  return nativeEvent.locale === 'ko';
10413
} // Track the current IME composition status, if any.
10414
10415
10416
var isComposing = false;
10417
/**
10418
 * @return {?object} A SyntheticCompositionEvent.
10419
 */
10420
10421
function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
10422
  var eventType;
10423
  var fallbackData;
10424
10425
  if (canUseCompositionEvent) {
10426
    eventType = getCompositionEventType(topLevelType);
10427
  } else if (!isComposing) {
10428
    if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
10429
      eventType = eventTypes$1.compositionStart;
10430
    }
10431
  } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
10432
    eventType = eventTypes$1.compositionEnd;
10433
  }
10434
10435
  if (!eventType) {
10436
    return null;
10437
  }
10438
10439
  if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
10440
    // The current composition is stored statically and must not be
10441
    // overwritten while composition continues.
10442
    if (!isComposing && eventType === eventTypes$1.compositionStart) {
10443
      isComposing = initialize(nativeEventTarget);
10444
    } else if (eventType === eventTypes$1.compositionEnd) {
10445
      if (isComposing) {
10446
        fallbackData = getData();
10447
      }
10448
    }
10449
  }
10450
10451
  var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
10452
10453
  if (fallbackData) {
10454
    // Inject data generated from fallback path into the synthetic event.
10455
    // This matches the property of native CompositionEventInterface.
10456
    event.data = fallbackData;
10457
  } else {
10458
    var customData = getDataFromCustomEvent(nativeEvent);
10459
10460
    if (customData !== null) {
10461
      event.data = customData;
10462
    }
10463
  }
10464
10465
  accumulateTwoPhaseDispatches(event);
10466
  return event;
10467
}
10468
/**
10469
 * @param {TopLevelType} topLevelType Number from `TopLevelType`.
10470
 * @param {object} nativeEvent Native browser event.
10471
 * @return {?string} The string corresponding to this `beforeInput` event.
10472
 */
10473
10474
10475
function getNativeBeforeInputChars(topLevelType, nativeEvent) {
10476
  switch (topLevelType) {
10477
    case TOP_COMPOSITION_END:
10478
      return getDataFromCustomEvent(nativeEvent);
10479
10480
    case TOP_KEY_PRESS:
10481
      /**
10482
       * If native `textInput` events are available, our goal is to make
10483
       * use of them. However, there is a special case: the spacebar key.
10484
       * In Webkit, preventing default on a spacebar `textInput` event
10485
       * cancels character insertion, but it *also* causes the browser
10486
       * to fall back to its default spacebar behavior of scrolling the
10487
       * page.
10488
       *
10489
       * Tracking at:
10490
       * https://code.google.com/p/chromium/issues/detail?id=355103
10491
       *
10492
       * To avoid this issue, use the keypress event as if no `textInput`
10493
       * event is available.
10494
       */
10495
      var which = nativeEvent.which;
10496
10497
      if (which !== SPACEBAR_CODE) {
10498
        return null;
10499
      }
10500
10501
      hasSpaceKeypress = true;
10502
      return SPACEBAR_CHAR;
10503
10504
    case TOP_TEXT_INPUT:
10505
      // Record the characters to be added to the DOM.
10506
      var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled
10507
      // it at the keypress level and bail immediately. Android Chrome
10508
      // doesn't give us keycodes, so we need to ignore it.
10509
10510
      if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
10511
        return null;
10512
      }
10513
10514
      return chars;
10515
10516
    default:
10517
      // For other native event types, do nothing.
10518
      return null;
10519
  }
10520
}
10521
/**
10522
 * For browsers that do not provide the `textInput` event, extract the
10523
 * appropriate string to use for SyntheticInputEvent.
10524
 *
10525
 * @param {number} topLevelType Number from `TopLevelEventTypes`.
10526
 * @param {object} nativeEvent Native browser event.
10527
 * @return {?string} The fallback string for this `beforeInput` event.
10528
 */
10529
10530
10531
function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
10532
  // If we are currently composing (IME) and using a fallback to do so,
10533
  // try to extract the composed characters from the fallback object.
10534
  // If composition event is available, we extract a string only at
10535
  // compositionevent, otherwise extract it at fallback events.
10536
  if (isComposing) {
10537
    if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {
10538
      var chars = getData();
10539
      reset();
10540
      isComposing = false;
10541
      return chars;
10542
    }
10543
10544
    return null;
10545
  }
10546
10547
  switch (topLevelType) {
10548
    case TOP_PASTE:
10549
      // If a paste event occurs after a keypress, throw out the input
10550
      // chars. Paste events should not lead to BeforeInput events.
10551
      return null;
10552
10553
    case TOP_KEY_PRESS:
10554
      /**
10555
       * As of v27, Firefox may fire keypress events even when no character
10556
       * will be inserted. A few possibilities:
10557
       *
10558
       * - `which` is `0`. Arrow keys, Esc key, etc.
10559
       *
10560
       * - `which` is the pressed key code, but no char is available.
10561
       *   Ex: 'AltGr + d` in Polish. There is no modified character for
10562
       *   this key combination and no character is inserted into the
10563
       *   document, but FF fires the keypress for char code `100` anyway.
10564
       *   No `input` event will occur.
10565
       *
10566
       * - `which` is the pressed key code, but a command combination is
10567
       *   being used. Ex: `Cmd+C`. No character is inserted, and no
10568
       *   `input` event will occur.
10569
       */
10570
      if (!isKeypressCommand(nativeEvent)) {
10571
        // IE fires the `keypress` event when a user types an emoji via
10572
        // Touch keyboard of Windows.  In such a case, the `char` property
10573
        // holds an emoji character like `\uD83D\uDE0A`.  Because its length
10574
        // is 2, the property `which` does not represent an emoji correctly.
10575
        // In such a case, we directly return the `char` property instead of
10576
        // using `which`.
10577
        if (nativeEvent.char && nativeEvent.char.length > 1) {
10578
          return nativeEvent.char;
10579
        } else if (nativeEvent.which) {
10580
          return String.fromCharCode(nativeEvent.which);
10581
        }
10582
      }
10583
10584
      return null;
10585
10586
    case TOP_COMPOSITION_END:
10587
      return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
10588
10589
    default:
10590
      return null;
10591
  }
10592
}
10593
/**
10594
 * Extract a SyntheticInputEvent for `beforeInput`, based on either native
10595
 * `textInput` or fallback behavior.
10596
 *
10597
 * @return {?object} A SyntheticInputEvent.
10598
 */
10599
10600
10601
function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
10602
  var chars;
10603
10604
  if (canUseTextInputEvent) {
10605
    chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
10606
  } else {
10607
    chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
10608
  } // If no characters are being inserted, no BeforeInput event should
10609
  // be fired.
10610
10611
10612
  if (!chars) {
10613
    return null;
10614
  }
10615
10616
  var event = SyntheticInputEvent.getPooled(eventTypes$1.beforeInput, targetInst, nativeEvent, nativeEventTarget);
10617
  event.data = chars;
10618
  accumulateTwoPhaseDispatches(event);
10619
  return event;
10620
}
10621
/**
10622
 * Create an `onBeforeInput` event to match
10623
 * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
10624
 *
10625
 * This event plugin is based on the native `textInput` event
10626
 * available in Chrome, Safari, Opera, and IE. This event fires after
10627
 * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
10628
 *
10629
 * `beforeInput` is spec'd but not implemented in any browsers, and
10630
 * the `input` event does not provide any useful information about what has
10631
 * actually been added, contrary to the spec. Thus, `textInput` is the best
10632
 * available event to identify the characters that have actually been inserted
10633
 * into the target node.
10634
 *
10635
 * This plugin is also responsible for emitting `composition` events, thus
10636
 * allowing us to share composition fallback code for both `beforeInput` and
10637
 * `composition` event types.
10638
 */
10639
10640
10641
var BeforeInputEventPlugin = {
10642
  eventTypes: eventTypes$1,
10643
  extractEvents: function (topLevelType, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
10644
    var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
10645
    var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
10646
10647
    if (composition === null) {
10648
      return beforeInput;
10649
    }
10650
10651
    if (beforeInput === null) {
10652
      return composition;
10653
    }
10654
10655
    return [composition, beforeInput];
10656
  }
10657
};
10658
10659
/**
10660
 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
10661
 */
10662
var supportedInputTypes = {
10663
  color: true,
10664
  date: true,
10665
  datetime: true,
10666
  'datetime-local': true,
10667
  email: true,
10668
  month: true,
10669
  number: true,
10670
  password: true,
10671
  range: true,
10672
  search: true,
10673
  tel: true,
10674
  text: true,
10675
  time: true,
10676
  url: true,
10677
  week: true
10678
};
10679
10680
function isTextInputElement(elem) {
10681
  var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
10682
10683
  if (nodeName === 'input') {
10684
    return !!supportedInputTypes[elem.type];
10685
  }
10686
10687
  if (nodeName === 'textarea') {
10688
    return true;
10689
  }
10690
10691
  return false;
10692
}
10693
10694
var eventTypes$2 = {
10695
  change: {
10696
    phasedRegistrationNames: {
10697
      bubbled: 'onChange',
10698
      captured: 'onChangeCapture'
10699
    },
10700
    dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE]
10701
  }
10702
};
10703
10704
function createAndAccumulateChangeEvent(inst, nativeEvent, target) {
10705
  var event = SyntheticEvent.getPooled(eventTypes$2.change, inst, nativeEvent, target);
10706
  event.type = 'change'; // Flag this event loop as needing state restore.
10707
10708
  enqueueStateRestore(target);
10709
  accumulateTwoPhaseDispatches(event);
10710
  return event;
10711
}
10712
/**
10713
 * For IE shims
10714
 */
10715
10716
10717
var activeElement = null;
10718
var activeElementInst = null;
10719
/**
10720
 * SECTION: handle `change` event
10721
 */
10722
10723
function shouldUseChangeEvent(elem) {
10724
  var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
10725
  return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
10726
}
10727
10728
function manualDispatchChangeEvent(nativeEvent) {
10729
  var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the
10730
  // other events and have it go through ReactBrowserEventEmitter. Since it
10731
  // doesn't, we manually listen for the events and so we have to enqueue and
10732
  // process the abstract event manually.
10733
  //
10734
  // Batching is necessary here in order to ensure that all event handlers run
10735
  // before the next rerender (including event handlers attached to ancestor
10736
  // elements instead of directly on the input). Without this, controlled
10737
  // components don't work properly in conjunction with event bubbling because
10738
  // the component is rerendered and the value reverted before all the event
10739
  // handlers can run. See https://github.com/facebook/react/issues/708.
10740
10741
  batchedUpdates(runEventInBatch, event);
10742
}
10743
10744
function runEventInBatch(event) {
10745
  runEventsInBatch(event);
10746
}
10747
10748
function getInstIfValueChanged(targetInst) {
10749
  var targetNode = getNodeFromInstance$1(targetInst);
10750
10751
  if (updateValueIfChanged(targetNode)) {
10752
    return targetInst;
10753
  }
10754
}
10755
10756
function getTargetInstForChangeEvent(topLevelType, targetInst) {
10757
  if (topLevelType === TOP_CHANGE) {
10758
    return targetInst;
10759
  }
10760
}
10761
/**
10762
 * SECTION: handle `input` event
10763
 */
10764
10765
10766
var isInputEventSupported = false;
10767
10768
if (canUseDOM) {
10769
  // IE9 claims to support the input event but fails to trigger it when
10770
  // deleting text, so we ignore its input events.
10771
  isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
10772
}
10773
/**
10774
 * (For IE <=9) Starts tracking propertychange events on the passed-in element
10775
 * and override the value property so that we can distinguish user events from
10776
 * value changes in JS.
10777
 */
10778
10779
10780
function startWatchingForValueChange(target, targetInst) {
10781
  activeElement = target;
10782
  activeElementInst = targetInst;
10783
  activeElement.attachEvent('onpropertychange', handlePropertyChange);
10784
}
10785
/**
10786
 * (For IE <=9) Removes the event listeners from the currently-tracked element,
10787
 * if any exists.
10788
 */
10789
10790
10791
function stopWatchingForValueChange() {
10792
  if (!activeElement) {
10793
    return;
10794
  }
10795
10796
  activeElement.detachEvent('onpropertychange', handlePropertyChange);
10797
  activeElement = null;
10798
  activeElementInst = null;
10799
}
10800
/**
10801
 * (For IE <=9) Handles a propertychange event, sending a `change` event if
10802
 * the value of the active element has changed.
10803
 */
10804
10805
10806
function handlePropertyChange(nativeEvent) {
10807
  if (nativeEvent.propertyName !== 'value') {
10808
    return;
10809
  }
10810
10811
  if (getInstIfValueChanged(activeElementInst)) {
10812
    manualDispatchChangeEvent(nativeEvent);
10813
  }
10814
}
10815
10816
function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
10817
  if (topLevelType === TOP_FOCUS) {
10818
    // In IE9, propertychange fires for most input events but is buggy and
10819
    // doesn't fire when text is deleted, but conveniently, selectionchange
10820
    // appears to fire in all of the remaining cases so we catch those and
10821
    // forward the event if the value has changed
10822
    // In either case, we don't want to call the event handler if the value
10823
    // is changed from JS so we redefine a setter for `.value` that updates
10824
    // our activeElementValue variable, allowing us to ignore those changes
10825
    //
10826
    // stopWatching() should be a noop here but we call it just in case we
10827
    // missed a blur event somehow.
10828
    stopWatchingForValueChange();
10829
    startWatchingForValueChange(target, targetInst);
10830
  } else if (topLevelType === TOP_BLUR) {
10831
    stopWatchingForValueChange();
10832
  }
10833
} // For IE8 and IE9.
10834
10835
10836
function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {
10837
  if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {
10838
    // On the selectionchange event, the target is just document which isn't
10839
    // helpful for us so just check activeElement instead.
10840
    //
10841
    // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
10842
    // propertychange on the first input event after setting `value` from a
10843
    // script and fires only keydown, keypress, keyup. Catching keyup usually
10844
    // gets it and catching keydown lets us fire an event for the first
10845
    // keystroke if user does a key repeat (it'll be a little delayed: right
10846
    // before the second keystroke). Other input methods (e.g., paste) seem to
10847
    // fire selectionchange normally.
10848
    return getInstIfValueChanged(activeElementInst);
10849
  }
10850
}
10851
/**
10852
 * SECTION: handle `click` event
10853
 */
10854
10855
10856
function shouldUseClickEvent(elem) {
10857
  // Use the `click` event to detect changes to checkbox and radio inputs.
10858
  // This approach works across all browsers, whereas `change` does not fire
10859
  // until `blur` in IE8.
10860
  var nodeName = elem.nodeName;
10861
  return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
10862
}
10863
10864
function getTargetInstForClickEvent(topLevelType, targetInst) {
10865
  if (topLevelType === TOP_CLICK) {
10866
    return getInstIfValueChanged(targetInst);
10867
  }
10868
}
10869
10870
function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {
10871
  if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) {
10872
    return getInstIfValueChanged(targetInst);
10873
  }
10874
}
10875
10876
function handleControlledInputBlur(node) {
10877
  var state = node._wrapperState;
10878
10879
  if (!state || !state.controlled || node.type !== 'number') {
10880
    return;
10881
  }
10882
10883
  if (!disableInputAttributeSyncing) {
10884
    // If controlled, assign the value attribute to the current value on blur
10885
    setDefaultValue(node, 'number', node.value);
10886
  }
10887
}
10888
/**
10889
 * This plugin creates an `onChange` event that normalizes change events
10890
 * across form elements. This event fires at a time when it's possible to
10891
 * change the element's value without seeing a flicker.
10892
 *
10893
 * Supported elements are:
10894
 * - input (see `isTextInputElement`)
10895
 * - textarea
10896
 * - select
10897
 */
10898
10899
10900
var ChangeEventPlugin = {
10901
  eventTypes: eventTypes$2,
10902
  _isInputEventSupported: isInputEventSupported,
10903
  extractEvents: function (topLevelType, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
10904
    var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
10905
    var getTargetInstFunc, handleEventFunc;
10906
10907
    if (shouldUseChangeEvent(targetNode)) {
10908
      getTargetInstFunc = getTargetInstForChangeEvent;
10909
    } else if (isTextInputElement(targetNode)) {
10910
      if (isInputEventSupported) {
10911
        getTargetInstFunc = getTargetInstForInputOrChangeEvent;
10912
      } else {
10913
        getTargetInstFunc = getTargetInstForInputEventPolyfill;
10914
        handleEventFunc = handleEventsForInputEventPolyfill;
10915
      }
10916
    } else if (shouldUseClickEvent(targetNode)) {
10917
      getTargetInstFunc = getTargetInstForClickEvent;
10918
    }
10919
10920
    if (getTargetInstFunc) {
10921
      var inst = getTargetInstFunc(topLevelType, targetInst);
10922
10923
      if (inst) {
10924
        var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget);
10925
        return event;
10926
      }
10927
    }
10928
10929
    if (handleEventFunc) {
10930
      handleEventFunc(topLevelType, targetNode, targetInst);
10931
    } // When blurring, set the value attribute for number inputs
10932
10933
10934
    if (topLevelType === TOP_BLUR) {
10935
      handleControlledInputBlur(targetNode);
10936
    }
10937
  }
10938
};
10939
10940
/**
10941
 * Module that is injectable into `EventPluginHub`, that specifies a
10942
 * deterministic ordering of `EventPlugin`s. A convenient way to reason about
10943
 * plugins, without having to package every one of them. This is better than
10944
 * having plugins be ordered in the same order that they are injected because
10945
 * that ordering would be influenced by the packaging order.
10946
 * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
10947
 * preventing default on events is convenient in `SimpleEventPlugin` handlers.
10948
 */
10949
var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];
10950
10951
var eventTypes$3 = {
10952
  mouseEnter: {
10953
    registrationName: 'onMouseEnter',
10954
    dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
10955
  },
10956
  mouseLeave: {
10957
    registrationName: 'onMouseLeave',
10958
    dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
10959
  },
10960
  pointerEnter: {
10961
    registrationName: 'onPointerEnter',
10962
    dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
10963
  },
10964
  pointerLeave: {
10965
    registrationName: 'onPointerLeave',
10966
    dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
10967
  }
10968
};
10969
var EnterLeaveEventPlugin = {
10970
  eventTypes: eventTypes$3,
10971
10972
  /**
10973
   * For almost every interaction we care about, there will be both a top-level
10974
   * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
10975
   * we do not extract duplicate events. However, moving the mouse into the
10976
   * browser from outside will not fire a `mouseout` event. In this case, we use
10977
   * the `mouseover` top-level event.
10978
   */
10979
  extractEvents: function (topLevelType, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
10980
    var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
10981
    var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;
10982
10983
    if (isOverEvent && (eventSystemFlags & IS_REPLAYED) === 0 && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
10984
      // If this is an over event with a target, then we've already dispatched
10985
      // the event in the out event of the other target. If this is replayed,
10986
      // then it's because we couldn't dispatch against this target previously
10987
      // so we have to do it now instead.
10988
      return null;
10989
    }
10990
10991
    if (!isOutEvent && !isOverEvent) {
10992
      // Must not be a mouse or pointer in or out - ignoring.
10993
      return null;
10994
    }
10995
10996
    var win;
10997
10998
    if (nativeEventTarget.window === nativeEventTarget) {
10999
      // `nativeEventTarget` is probably a window object.
11000
      win = nativeEventTarget;
11001
    } else {
11002
      // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
11003
      var doc = nativeEventTarget.ownerDocument;
11004
11005
      if (doc) {
11006
        win = doc.defaultView || doc.parentWindow;
11007
      } else {
11008
        win = window;
11009
      }
11010
    }
11011
11012
    var from;
11013
    var to;
11014
11015
    if (isOutEvent) {
11016
      from = targetInst;
11017
      var related = nativeEvent.relatedTarget || nativeEvent.toElement;
11018
      to = related ? getClosestInstanceFromNode(related) : null;
11019
11020
      if (to !== null) {
11021
        var nearestMounted = getNearestMountedFiber(to);
11022
11023
        if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {
11024
          to = null;
11025
        }
11026
      }
11027
    } else {
11028
      // Moving to a node from outside the window.
11029
      from = null;
11030
      to = targetInst;
11031
    }
11032
11033
    if (from === to) {
11034
      // Nothing pertains to our managed components.
11035
      return null;
11036
    }
11037
11038
    var eventInterface, leaveEventType, enterEventType, eventTypePrefix;
11039
11040
    if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
11041
      eventInterface = SyntheticMouseEvent;
11042
      leaveEventType = eventTypes$3.mouseLeave;
11043
      enterEventType = eventTypes$3.mouseEnter;
11044
      eventTypePrefix = 'mouse';
11045
    } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {
11046
      eventInterface = SyntheticPointerEvent;
11047
      leaveEventType = eventTypes$3.pointerLeave;
11048
      enterEventType = eventTypes$3.pointerEnter;
11049
      eventTypePrefix = 'pointer';
11050
    }
11051
11052
    var fromNode = from == null ? win : getNodeFromInstance$1(from);
11053
    var toNode = to == null ? win : getNodeFromInstance$1(to);
11054
    var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);
11055
    leave.type = eventTypePrefix + 'leave';
11056
    leave.target = fromNode;
11057
    leave.relatedTarget = toNode;
11058
    var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);
11059
    enter.type = eventTypePrefix + 'enter';
11060
    enter.target = toNode;
11061
    enter.relatedTarget = fromNode;
11062
    accumulateEnterLeaveDispatches(leave, enter, from, to);
11063
    return [leave, enter];
11064
  }
11065
};
11066
11067
/**
11068
 * inlined Object.is polyfill to avoid requiring consumers ship their own
11069
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
11070
 */
11071
function is(x, y) {
11072
  return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
11073
  ;
11074
}
11075
11076
var is$1 = typeof Object.is === 'function' ? Object.is : is;
11077
11078
var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
11079
/**
11080
 * Performs equality by iterating through keys on an object and returning false
11081
 * when any key has values which are not strictly equal between the arguments.
11082
 * Returns true when the values of all keys are strictly equal.
11083
 */
11084
11085
function shallowEqual(objA, objB) {
11086
  if (is$1(objA, objB)) {
11087
    return true;
11088
  }
11089
11090
  if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
11091
    return false;
11092
  }
11093
11094
  var keysA = Object.keys(objA);
11095
  var keysB = Object.keys(objB);
11096
11097
  if (keysA.length !== keysB.length) {
11098
    return false;
11099
  } // Test for A's keys different from B.
11100
11101
11102
  for (var i = 0; i < keysA.length; i++) {
11103
    if (!hasOwnProperty$2.call(objB, keysA[i]) || !is$1(objA[keysA[i]], objB[keysA[i]])) {
11104
      return false;
11105
    }
11106
  }
11107
11108
  return true;
11109
}
11110
11111
var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;
11112
var eventTypes$4 = {
11113
  select: {
11114
    phasedRegistrationNames: {
11115
      bubbled: 'onSelect',
11116
      captured: 'onSelectCapture'
11117
    },
11118
    dependencies: [TOP_BLUR, TOP_CONTEXT_MENU, TOP_DRAG_END, TOP_FOCUS, TOP_KEY_DOWN, TOP_KEY_UP, TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_SELECTION_CHANGE]
11119
  }
11120
};
11121
var activeElement$1 = null;
11122
var activeElementInst$1 = null;
11123
var lastSelection = null;
11124
var mouseDown = false;
11125
/**
11126
 * Get an object which is a unique representation of the current selection.
11127
 *
11128
 * The return value will not be consistent across nodes or browsers, but
11129
 * two identical selections on the same node will return identical objects.
11130
 *
11131
 * @param {DOMElement} node
11132
 * @return {object}
11133
 */
11134
11135
function getSelection$1(node) {
11136
  if ('selectionStart' in node && hasSelectionCapabilities(node)) {
11137
    return {
11138
      start: node.selectionStart,
11139
      end: node.selectionEnd
11140
    };
11141
  } else {
11142
    var win = node.ownerDocument && node.ownerDocument.defaultView || window;
11143
    var selection = win.getSelection();
11144
    return {
11145
      anchorNode: selection.anchorNode,
11146
      anchorOffset: selection.anchorOffset,
11147
      focusNode: selection.focusNode,
11148
      focusOffset: selection.focusOffset
11149
    };
11150
  }
11151
}
11152
/**
11153
 * Get document associated with the event target.
11154
 *
11155
 * @param {object} nativeEventTarget
11156
 * @return {Document}
11157
 */
11158
11159
11160
function getEventTargetDocument(eventTarget) {
11161
  return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
11162
}
11163
/**
11164
 * Poll selection to see whether it's changed.
11165
 *
11166
 * @param {object} nativeEvent
11167
 * @param {object} nativeEventTarget
11168
 * @return {?SyntheticEvent}
11169
 */
11170
11171
11172
function constructSelectEvent(nativeEvent, nativeEventTarget) {
11173
  // Ensure we have the right element, and that the user is not dragging a
11174
  // selection (this matches native `select` event behavior). In HTML5, select
11175
  // fires only on input and textarea thus if there's no focused element we
11176
  // won't dispatch.
11177
  var doc = getEventTargetDocument(nativeEventTarget);
11178
11179
  if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
11180
    return null;
11181
  } // Only fire when selection has actually changed.
11182
11183
11184
  var currentSelection = getSelection$1(activeElement$1);
11185
11186
  if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
11187
    lastSelection = currentSelection;
11188
    var syntheticEvent = SyntheticEvent.getPooled(eventTypes$4.select, activeElementInst$1, nativeEvent, nativeEventTarget);
11189
    syntheticEvent.type = 'select';
11190
    syntheticEvent.target = activeElement$1;
11191
    accumulateTwoPhaseDispatches(syntheticEvent);
11192
    return syntheticEvent;
11193
  }
11194
11195
  return null;
11196
}
11197
/**
11198
 * This plugin creates an `onSelect` event that normalizes select events
11199
 * across form elements.
11200
 *
11201
 * Supported elements are:
11202
 * - input (see `isTextInputElement`)
11203
 * - textarea
11204
 * - contentEditable
11205
 *
11206
 * This differs from native browser implementations in the following ways:
11207
 * - Fires on contentEditable fields as well as inputs.
11208
 * - Fires for collapsed selection.
11209
 * - Fires after user input.
11210
 */
11211
11212
11213
var SelectEventPlugin = {
11214
  eventTypes: eventTypes$4,
11215
  extractEvents: function (topLevelType, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
11216
    var doc = getEventTargetDocument(nativeEventTarget); // Track whether all listeners exists for this plugin. If none exist, we do
11217
    // not extract events. See #3639.
11218
11219
    if (!doc || !isListeningToAllDependencies('onSelect', doc)) {
11220
      return null;
11221
    }
11222
11223
    var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
11224
11225
    switch (topLevelType) {
11226
      // Track the input node that has focus.
11227
      case TOP_FOCUS:
11228
        if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
11229
          activeElement$1 = targetNode;
11230
          activeElementInst$1 = targetInst;
11231
          lastSelection = null;
11232
        }
11233
11234
        break;
11235
11236
      case TOP_BLUR:
11237
        activeElement$1 = null;
11238
        activeElementInst$1 = null;
11239
        lastSelection = null;
11240
        break;
11241
      // Don't fire the event while the user is dragging. This matches the
11242
      // semantics of the native select event.
11243
11244
      case TOP_MOUSE_DOWN:
11245
        mouseDown = true;
11246
        break;
11247
11248
      case TOP_CONTEXT_MENU:
11249
      case TOP_MOUSE_UP:
11250
      case TOP_DRAG_END:
11251
        mouseDown = false;
11252
        return constructSelectEvent(nativeEvent, nativeEventTarget);
11253
      // Chrome and IE fire non-standard event when selection is changed (and
11254
      // sometimes when it hasn't). IE's event fires out of order with respect
11255
      // to key and input events on deletion, so we discard it.
11256
      //
11257
      // Firefox doesn't support selectionchange, so check selection status
11258
      // after each key entry. The selection changes after keydown and before
11259
      // keyup, but we check on keydown as well in the case of holding down a
11260
      // key, when multiple keydown events are fired but only one keyup is.
11261
      // This is also our approach for IE handling, for the reason above.
11262
11263
      case TOP_SELECTION_CHANGE:
11264
        if (skipSelectionChangeEvent) {
11265
          break;
11266
        }
11267
11268
      // falls through
11269
11270
      case TOP_KEY_DOWN:
11271
      case TOP_KEY_UP:
11272
        return constructSelectEvent(nativeEvent, nativeEventTarget);
11273
    }
11274
11275
    return null;
11276
  }
11277
};
11278
11279
/**
11280
 * Inject modules for resolving DOM hierarchy and plugin ordering.
11281
 */
11282
11283
injection.injectEventPluginOrder(DOMEventPluginOrder);
11284
setComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);
11285
/**
11286
 * Some important event plugins included by default (without having to require
11287
 * them).
11288
 */
11289
11290
injection.injectEventPluginsByName({
11291
  SimpleEventPlugin: SimpleEventPlugin,
11292
  EnterLeaveEventPlugin: EnterLeaveEventPlugin,
11293
  ChangeEventPlugin: ChangeEventPlugin,
11294
  SelectEventPlugin: SelectEventPlugin,
11295
  BeforeInputEventPlugin: BeforeInputEventPlugin
11296
});
11297
11298
// Prefix measurements so that it's possible to filter them.
11299
// Longer prefixes are hard to read in DevTools.
11300
var reactEmoji = "\u269B";
11301
var warningEmoji = "\u26D4";
11302
var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; // Keep track of current fiber so that we know the path to unwind on pause.
11303
// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
11304
11305
var currentFiber = null; // If we're in the middle of user code, which fiber and method is it?
11306
// Reusing `currentFiber` would be confusing for this because user code fiber
11307
// can change during commit phase too, but we don't need to unwind it (since
11308
// lifecycles in the commit phase don't resemble a tree).
11309
11310
var currentPhase = null;
11311
var currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem,
11312
// so we will keep track of it, and include it in the report.
11313
// Track commits caused by cascading updates.
11314
11315
var isCommitting = false;
11316
var hasScheduledUpdateInCurrentCommit = false;
11317
var hasScheduledUpdateInCurrentPhase = false;
11318
var commitCountInCurrentWorkLoop = 0;
11319
var effectCountInCurrentCommit = 0;
11320
// to avoid stretch the commit phase with measurement overhead.
11321
11322
var labelsInCurrentCommit = new Set();
11323
11324
var formatMarkName = function (markName) {
11325
  return reactEmoji + " " + markName;
11326
};
11327
11328
var formatLabel = function (label, warning) {
11329
  var prefix = warning ? warningEmoji + " " : reactEmoji + " ";
11330
  var suffix = warning ? " Warning: " + warning : '';
11331
  return "" + prefix + label + suffix;
11332
};
11333
11334
var beginMark = function (markName) {
11335
  performance.mark(formatMarkName(markName));
11336
};
11337
11338
var clearMark = function (markName) {
11339
  performance.clearMarks(formatMarkName(markName));
11340
};
11341
11342
var endMark = function (label, markName, warning) {
11343
  var formattedMarkName = formatMarkName(markName);
11344
  var formattedLabel = formatLabel(label, warning);
11345
11346
  try {
11347
    performance.measure(formattedLabel, formattedMarkName);
11348
  } catch (err) {} // If previous mark was missing for some reason, this will throw.
11349
  // This could only happen if React crashed in an unexpected place earlier.
11350
  // Don't pile on with more errors.
11351
  // Clear marks immediately to avoid growing buffer.
11352
11353
11354
  performance.clearMarks(formattedMarkName);
11355
  performance.clearMeasures(formattedLabel);
11356
};
11357
11358
var getFiberMarkName = function (label, debugID) {
11359
  return label + " (#" + debugID + ")";
11360
};
11361
11362
var getFiberLabel = function (componentName, isMounted, phase) {
11363
  if (phase === null) {
11364
    // These are composite component total time measurements.
11365
    return componentName + " [" + (isMounted ? 'update' : 'mount') + "]";
11366
  } else {
11367
    // Composite component methods.
11368
    return componentName + "." + phase;
11369
  }
11370
};
11371
11372
var beginFiberMark = function (fiber, phase) {
11373
  var componentName = getComponentName(fiber.type) || 'Unknown';
11374
  var debugID = fiber._debugID;
11375
  var isMounted = fiber.alternate !== null;
11376
  var label = getFiberLabel(componentName, isMounted, phase);
11377
11378
  if (isCommitting && labelsInCurrentCommit.has(label)) {
11379
    // During the commit phase, we don't show duplicate labels because
11380
    // there is a fixed overhead for every measurement, and we don't
11381
    // want to stretch the commit phase beyond necessary.
11382
    return false;
11383
  }
11384
11385
  labelsInCurrentCommit.add(label);
11386
  var markName = getFiberMarkName(label, debugID);
11387
  beginMark(markName);
11388
  return true;
11389
};
11390
11391
var clearFiberMark = function (fiber, phase) {
11392
  var componentName = getComponentName(fiber.type) || 'Unknown';
11393
  var debugID = fiber._debugID;
11394
  var isMounted = fiber.alternate !== null;
11395
  var label = getFiberLabel(componentName, isMounted, phase);
11396
  var markName = getFiberMarkName(label, debugID);
11397
  clearMark(markName);
11398
};
11399
11400
var endFiberMark = function (fiber, phase, warning) {
11401
  var componentName = getComponentName(fiber.type) || 'Unknown';
11402
  var debugID = fiber._debugID;
11403
  var isMounted = fiber.alternate !== null;
11404
  var label = getFiberLabel(componentName, isMounted, phase);
11405
  var markName = getFiberMarkName(label, debugID);
11406
  endMark(label, markName, warning);
11407
};
11408
11409
var shouldIgnoreFiber = function (fiber) {
11410
  // Host components should be skipped in the timeline.
11411
  // We could check typeof fiber.type, but does this work with RN?
11412
  switch (fiber.tag) {
11413
    case HostRoot:
11414
    case HostComponent:
11415
    case HostText:
11416
    case HostPortal:
11417
    case Fragment:
11418
    case ContextProvider:
11419
    case ContextConsumer:
11420
    case Mode:
11421
      return true;
11422
11423
    default:
11424
      return false;
11425
  }
11426
};
11427
11428
var clearPendingPhaseMeasurement = function () {
11429
  if (currentPhase !== null && currentPhaseFiber !== null) {
11430
    clearFiberMark(currentPhaseFiber, currentPhase);
11431
  }
11432
11433
  currentPhaseFiber = null;
11434
  currentPhase = null;
11435
  hasScheduledUpdateInCurrentPhase = false;
11436
};
11437
11438
var pauseTimers = function () {
11439
  // Stops all currently active measurements so that they can be resumed
11440
  // if we continue in a later deferred loop from the same unit of work.
11441
  var fiber = currentFiber;
11442
11443
  while (fiber) {
11444
    if (fiber._debugIsCurrentlyTiming) {
11445
      endFiberMark(fiber, null, null);
11446
    }
11447
11448
    fiber = fiber.return;
11449
  }
11450
};
11451
11452
var resumeTimersRecursively = function (fiber) {
11453
  if (fiber.return !== null) {
11454
    resumeTimersRecursively(fiber.return);
11455
  }
11456
11457
  if (fiber._debugIsCurrentlyTiming) {
11458
    beginFiberMark(fiber, null);
11459
  }
11460
};
11461
11462
var resumeTimers = function () {
11463
  // Resumes all measurements that were active during the last deferred loop.
11464
  if (currentFiber !== null) {
11465
    resumeTimersRecursively(currentFiber);
11466
  }
11467
};
11468
11469
function recordEffect() {
11470
  if (enableUserTimingAPI) {
11471
    effectCountInCurrentCommit++;
11472
  }
11473
}
11474
function recordScheduleUpdate() {
11475
  if (enableUserTimingAPI) {
11476
    if (isCommitting) {
11477
      hasScheduledUpdateInCurrentCommit = true;
11478
    }
11479
11480
    if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
11481
      hasScheduledUpdateInCurrentPhase = true;
11482
    }
11483
  }
11484
}
11485
11486
11487
function startWorkTimer(fiber) {
11488
  if (enableUserTimingAPI) {
11489
    if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11490
      return;
11491
    } // If we pause, this is the fiber to unwind from.
11492
11493
11494
    currentFiber = fiber;
11495
11496
    if (!beginFiberMark(fiber, null)) {
11497
      return;
11498
    }
11499
11500
    fiber._debugIsCurrentlyTiming = true;
11501
  }
11502
}
11503
function cancelWorkTimer(fiber) {
11504
  if (enableUserTimingAPI) {
11505
    if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11506
      return;
11507
    } // Remember we shouldn't complete measurement for this fiber.
11508
    // Otherwise flamechart will be deep even for small updates.
11509
11510
11511
    fiber._debugIsCurrentlyTiming = false;
11512
    clearFiberMark(fiber, null);
11513
  }
11514
}
11515
function stopWorkTimer(fiber) {
11516
  if (enableUserTimingAPI) {
11517
    if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11518
      return;
11519
    } // If we pause, its parent is the fiber to unwind from.
11520
11521
11522
    currentFiber = fiber.return;
11523
11524
    if (!fiber._debugIsCurrentlyTiming) {
11525
      return;
11526
    }
11527
11528
    fiber._debugIsCurrentlyTiming = false;
11529
    endFiberMark(fiber, null, null);
11530
  }
11531
}
11532
function stopFailedWorkTimer(fiber) {
11533
  if (enableUserTimingAPI) {
11534
    if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11535
      return;
11536
    } // If we pause, its parent is the fiber to unwind from.
11537
11538
11539
    currentFiber = fiber.return;
11540
11541
    if (!fiber._debugIsCurrentlyTiming) {
11542
      return;
11543
    }
11544
11545
    fiber._debugIsCurrentlyTiming = false;
11546
    var warning = fiber.tag === SuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
11547
    endFiberMark(fiber, null, warning);
11548
  }
11549
}
11550
function startPhaseTimer(fiber, phase) {
11551
  if (enableUserTimingAPI) {
11552
    if (!supportsUserTiming) {
11553
      return;
11554
    }
11555
11556
    clearPendingPhaseMeasurement();
11557
11558
    if (!beginFiberMark(fiber, phase)) {
11559
      return;
11560
    }
11561
11562
    currentPhaseFiber = fiber;
11563
    currentPhase = phase;
11564
  }
11565
}
11566
function stopPhaseTimer() {
11567
  if (enableUserTimingAPI) {
11568
    if (!supportsUserTiming) {
11569
      return;
11570
    }
11571
11572
    if (currentPhase !== null && currentPhaseFiber !== null) {
11573
      var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
11574
      endFiberMark(currentPhaseFiber, currentPhase, warning);
11575
    }
11576
11577
    currentPhase = null;
11578
    currentPhaseFiber = null;
11579
  }
11580
}
11581
function startWorkLoopTimer(nextUnitOfWork) {
11582
  if (enableUserTimingAPI) {
11583
    currentFiber = nextUnitOfWork;
11584
11585
    if (!supportsUserTiming) {
11586
      return;
11587
    }
11588
11589
    commitCountInCurrentWorkLoop = 0; // This is top level call.
11590
    // Any other measurements are performed within.
11591
11592
    beginMark('(React Tree Reconciliation)'); // Resume any measurements that were in progress during the last loop.
11593
11594
    resumeTimers();
11595
  }
11596
}
11597
function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
11598
  if (enableUserTimingAPI) {
11599
    if (!supportsUserTiming) {
11600
      return;
11601
    }
11602
11603
    var warning = null;
11604
11605
    if (interruptedBy !== null) {
11606
      if (interruptedBy.tag === HostRoot) {
11607
        warning = 'A top-level update interrupted the previous render';
11608
      } else {
11609
        var componentName = getComponentName(interruptedBy.type) || 'Unknown';
11610
        warning = "An update to " + componentName + " interrupted the previous render";
11611
      }
11612
    } else if (commitCountInCurrentWorkLoop > 1) {
11613
      warning = 'There were cascading updates';
11614
    }
11615
11616
    commitCountInCurrentWorkLoop = 0;
11617
    var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)'; // Pause any measurements until the next loop.
11618
11619
    pauseTimers();
11620
    endMark(label, '(React Tree Reconciliation)', warning);
11621
  }
11622
}
11623
function startCommitTimer() {
11624
  if (enableUserTimingAPI) {
11625
    if (!supportsUserTiming) {
11626
      return;
11627
    }
11628
11629
    isCommitting = true;
11630
    hasScheduledUpdateInCurrentCommit = false;
11631
    labelsInCurrentCommit.clear();
11632
    beginMark('(Committing Changes)');
11633
  }
11634
}
11635
function stopCommitTimer() {
11636
  if (enableUserTimingAPI) {
11637
    if (!supportsUserTiming) {
11638
      return;
11639
    }
11640
11641
    var warning = null;
11642
11643
    if (hasScheduledUpdateInCurrentCommit) {
11644
      warning = 'Lifecycle hook scheduled a cascading update';
11645
    } else if (commitCountInCurrentWorkLoop > 0) {
11646
      warning = 'Caused by a cascading update in earlier commit';
11647
    }
11648
11649
    hasScheduledUpdateInCurrentCommit = false;
11650
    commitCountInCurrentWorkLoop++;
11651
    isCommitting = false;
11652
    labelsInCurrentCommit.clear();
11653
    endMark('(Committing Changes)', '(Committing Changes)', warning);
11654
  }
11655
}
11656
function startCommitSnapshotEffectsTimer() {
11657
  if (enableUserTimingAPI) {
11658
    if (!supportsUserTiming) {
11659
      return;
11660
    }
11661
11662
    effectCountInCurrentCommit = 0;
11663
    beginMark('(Committing Snapshot Effects)');
11664
  }
11665
}
11666
function stopCommitSnapshotEffectsTimer() {
11667
  if (enableUserTimingAPI) {
11668
    if (!supportsUserTiming) {
11669
      return;
11670
    }
11671
11672
    var count = effectCountInCurrentCommit;
11673
    effectCountInCurrentCommit = 0;
11674
    endMark("(Committing Snapshot Effects: " + count + " Total)", '(Committing Snapshot Effects)', null);
11675
  }
11676
}
11677
function startCommitHostEffectsTimer() {
11678
  if (enableUserTimingAPI) {
11679
    if (!supportsUserTiming) {
11680
      return;
11681
    }
11682
11683
    effectCountInCurrentCommit = 0;
11684
    beginMark('(Committing Host Effects)');
11685
  }
11686
}
11687
function stopCommitHostEffectsTimer() {
11688
  if (enableUserTimingAPI) {
11689
    if (!supportsUserTiming) {
11690
      return;
11691
    }
11692
11693
    var count = effectCountInCurrentCommit;
11694
    effectCountInCurrentCommit = 0;
11695
    endMark("(Committing Host Effects: " + count + " Total)", '(Committing Host Effects)', null);
11696
  }
11697
}
11698
function startCommitLifeCyclesTimer() {
11699
  if (enableUserTimingAPI) {
11700
    if (!supportsUserTiming) {
11701
      return;
11702
    }
11703
11704
    effectCountInCurrentCommit = 0;
11705
    beginMark('(Calling Lifecycle Methods)');
11706
  }
11707
}
11708
function stopCommitLifeCyclesTimer() {
11709
  if (enableUserTimingAPI) {
11710
    if (!supportsUserTiming) {
11711
      return;
11712
    }
11713
11714
    var count = effectCountInCurrentCommit;
11715
    effectCountInCurrentCommit = 0;
11716
    endMark("(Calling Lifecycle Methods: " + count + " Total)", '(Calling Lifecycle Methods)', null);
11717
  }
11718
}
11719
11720
var valueStack = [];
11721
var fiberStack;
11722
11723
{
11724
  fiberStack = [];
11725
}
11726
11727
var index = -1;
11728
11729
function createCursor(defaultValue) {
11730
  return {
11731
    current: defaultValue
11732
  };
11733
}
11734
11735
function pop(cursor, fiber) {
11736
  if (index < 0) {
11737
    {
11738
      warningWithoutStack$1(false, 'Unexpected pop.');
11739
    }
11740
11741
    return;
11742
  }
11743
11744
  {
11745
    if (fiber !== fiberStack[index]) {
11746
      warningWithoutStack$1(false, 'Unexpected Fiber popped.');
11747
    }
11748
  }
11749
11750
  cursor.current = valueStack[index];
11751
  valueStack[index] = null;
11752
11753
  {
11754
    fiberStack[index] = null;
11755
  }
11756
11757
  index--;
11758
}
11759
11760
function push(cursor, value, fiber) {
11761
  index++;
11762
  valueStack[index] = cursor.current;
11763
11764
  {
11765
    fiberStack[index] = fiber;
11766
  }
11767
11768
  cursor.current = value;
11769
}
11770
11771
var warnedAboutMissingGetChildContext;
11772
11773
{
11774
  warnedAboutMissingGetChildContext = {};
11775
}
11776
11777
var emptyContextObject = {};
11778
11779
{
11780
  Object.freeze(emptyContextObject);
11781
} // A cursor to the current merged context object on the stack.
11782
11783
11784
var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.
11785
11786
var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.
11787
// We use this to get access to the parent context after we have already
11788
// pushed the next context provider, and now need to merge their contexts.
11789
11790
var previousContext = emptyContextObject;
11791
11792
function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
11793
  if (disableLegacyContext) {
11794
    return emptyContextObject;
11795
  } else {
11796
    if (didPushOwnContextIfProvider && isContextProvider(Component)) {
11797
      // If the fiber is a context provider itself, when we read its context
11798
      // we may have already pushed its own child context on the stack. A context
11799
      // provider should not "see" its own child context. Therefore we read the
11800
      // previous (parent) context instead for a context provider.
11801
      return previousContext;
11802
    }
11803
11804
    return contextStackCursor.current;
11805
  }
11806
}
11807
11808
function cacheContext(workInProgress, unmaskedContext, maskedContext) {
11809
  if (disableLegacyContext) {
11810
    return;
11811
  } else {
11812
    var instance = workInProgress.stateNode;
11813
    instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
11814
    instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
11815
  }
11816
}
11817
11818
function getMaskedContext(workInProgress, unmaskedContext) {
11819
  if (disableLegacyContext) {
11820
    return emptyContextObject;
11821
  } else {
11822
    var type = workInProgress.type;
11823
    var contextTypes = type.contextTypes;
11824
11825
    if (!contextTypes) {
11826
      return emptyContextObject;
11827
    } // Avoid recreating masked context unless unmasked context has changed.
11828
    // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
11829
    // This may trigger infinite loops if componentWillReceiveProps calls setState.
11830
11831
11832
    var instance = workInProgress.stateNode;
11833
11834
    if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
11835
      return instance.__reactInternalMemoizedMaskedChildContext;
11836
    }
11837
11838
    var context = {};
11839
11840
    for (var key in contextTypes) {
11841
      context[key] = unmaskedContext[key];
11842
    }
11843
11844
    {
11845
      var name = getComponentName(type) || 'Unknown';
11846
      checkPropTypes(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
11847
    } // Cache unmasked context so we can avoid recreating masked context unless necessary.
11848
    // Context is created before the class component is instantiated so check for instance.
11849
11850
11851
    if (instance) {
11852
      cacheContext(workInProgress, unmaskedContext, context);
11853
    }
11854
11855
    return context;
11856
  }
11857
}
11858
11859
function hasContextChanged() {
11860
  if (disableLegacyContext) {
11861
    return false;
11862
  } else {
11863
    return didPerformWorkStackCursor.current;
11864
  }
11865
}
11866
11867
function isContextProvider(type) {
11868
  if (disableLegacyContext) {
11869
    return false;
11870
  } else {
11871
    var childContextTypes = type.childContextTypes;
11872
    return childContextTypes !== null && childContextTypes !== undefined;
11873
  }
11874
}
11875
11876
function popContext(fiber) {
11877
  if (disableLegacyContext) {
11878
    return;
11879
  } else {
11880
    pop(didPerformWorkStackCursor, fiber);
11881
    pop(contextStackCursor, fiber);
11882
  }
11883
}
11884
11885
function popTopLevelContextObject(fiber) {
11886
  if (disableLegacyContext) {
11887
    return;
11888
  } else {
11889
    pop(didPerformWorkStackCursor, fiber);
11890
    pop(contextStackCursor, fiber);
11891
  }
11892
}
11893
11894
function pushTopLevelContextObject(fiber, context, didChange) {
11895
  if (disableLegacyContext) {
11896
    return;
11897
  } else {
11898
    (function () {
11899
      if (!(contextStackCursor.current === emptyContextObject)) {
11900
        {
11901
          throw ReactError(Error("Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue."));
11902
        }
11903
      }
11904
    })();
11905
11906
    push(contextStackCursor, context, fiber);
11907
    push(didPerformWorkStackCursor, didChange, fiber);
11908
  }
11909
}
11910
11911
function processChildContext(fiber, type, parentContext) {
11912
  if (disableLegacyContext) {
11913
    return parentContext;
11914
  } else {
11915
    var instance = fiber.stateNode;
11916
    var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.
11917
    // It has only been added in Fiber to match the (unintentional) behavior in Stack.
11918
11919
    if (typeof instance.getChildContext !== 'function') {
11920
      {
11921
        var componentName = getComponentName(type) || 'Unknown';
11922
11923
        if (!warnedAboutMissingGetChildContext[componentName]) {
11924
          warnedAboutMissingGetChildContext[componentName] = true;
11925
          warningWithoutStack$1(false, '%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
11926
        }
11927
      }
11928
11929
      return parentContext;
11930
    }
11931
11932
    var childContext;
11933
11934
    {
11935
      setCurrentPhase('getChildContext');
11936
    }
11937
11938
    startPhaseTimer(fiber, 'getChildContext');
11939
    childContext = instance.getChildContext();
11940
    stopPhaseTimer();
11941
11942
    {
11943
      setCurrentPhase(null);
11944
    }
11945
11946
    for (var contextKey in childContext) {
11947
      (function () {
11948
        if (!(contextKey in childContextTypes)) {
11949
          {
11950
            throw ReactError(Error((getComponentName(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes."));
11951
          }
11952
        }
11953
      })();
11954
    }
11955
11956
    {
11957
      var name = getComponentName(type) || 'Unknown';
11958
      checkPropTypes(childContextTypes, childContext, 'child context', name, // In practice, there is one case in which we won't get a stack. It's when
11959
      // somebody calls unstable_renderSubtreeIntoContainer() and we process
11960
      // context from the parent component instance. The stack will be missing
11961
      // because it's outside of the reconciliation, and so the pointer has not
11962
      // been set. This is rare and doesn't matter. We'll also remove that API.
11963
      getCurrentFiberStackInDev);
11964
    }
11965
11966
    return _assign({}, parentContext, {}, childContext);
11967
  }
11968
}
11969
11970
function pushContextProvider(workInProgress) {
11971
  if (disableLegacyContext) {
11972
    return false;
11973
  } else {
11974
    var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.
11975
    // If the instance does not exist yet, we will push null at first,
11976
    // and replace it on the stack later when invalidating the context.
11977
11978
    var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.
11979
    // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
11980
11981
    previousContext = contextStackCursor.current;
11982
    push(contextStackCursor, memoizedMergedChildContext, workInProgress);
11983
    push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
11984
    return true;
11985
  }
11986
}
11987
11988
function invalidateContextProvider(workInProgress, type, didChange) {
11989
  if (disableLegacyContext) {
11990
    return;
11991
  } else {
11992
    var instance = workInProgress.stateNode;
11993
11994
    (function () {
11995
      if (!instance) {
11996
        {
11997
          throw ReactError(Error("Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue."));
11998
        }
11999
      }
12000
    })();
12001
12002
    if (didChange) {
12003
      // Merge parent and own context.
12004
      // Skip this if we're not updating due to sCU.
12005
      // This avoids unnecessarily recomputing memoized values.
12006
      var mergedContext = processChildContext(workInProgress, type, previousContext);
12007
      instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.
12008
      // It is important to unwind the context in the reverse order.
12009
12010
      pop(didPerformWorkStackCursor, workInProgress);
12011
      pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.
12012
12013
      push(contextStackCursor, mergedContext, workInProgress);
12014
      push(didPerformWorkStackCursor, didChange, workInProgress);
12015
    } else {
12016
      pop(didPerformWorkStackCursor, workInProgress);
12017
      push(didPerformWorkStackCursor, didChange, workInProgress);
12018
    }
12019
  }
12020
}
12021
12022
function findCurrentUnmaskedContext(fiber) {
12023
  if (disableLegacyContext) {
12024
    return emptyContextObject;
12025
  } else {
12026
    // Currently this is only used with renderSubtreeIntoContainer; not sure if it
12027
    // makes sense elsewhere
12028
    (function () {
12029
      if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {
12030
        {
12031
          throw ReactError(Error("Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue."));
12032
        }
12033
      }
12034
    })();
12035
12036
    var node = fiber;
12037
12038
    do {
12039
      switch (node.tag) {
12040
        case HostRoot:
12041
          return node.stateNode.context;
12042
12043
        case ClassComponent:
12044
          {
12045
            var Component = node.type;
12046
12047
            if (isContextProvider(Component)) {
12048
              return node.stateNode.__reactInternalMemoizedMergedChildContext;
12049
            }
12050
12051
            break;
12052
          }
12053
      }
12054
12055
      node = node.return;
12056
    } while (node !== null);
12057
12058
    (function () {
12059
      {
12060
        {
12061
          throw ReactError(Error("Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue."));
12062
        }
12063
      }
12064
    })();
12065
  }
12066
}
12067
12068
var LegacyRoot = 0;
12069
var BatchedRoot = 1;
12070
var ConcurrentRoot = 2;
12071
12072
// Intentionally not named imports because Rollup would use dynamic dispatch for
12073
// CommonJS interop named imports.
12074
var Scheduler_runWithPriority = Scheduler.unstable_runWithPriority;
12075
var Scheduler_scheduleCallback = Scheduler.unstable_scheduleCallback;
12076
var Scheduler_cancelCallback = Scheduler.unstable_cancelCallback;
12077
var Scheduler_shouldYield = Scheduler.unstable_shouldYield;
12078
var Scheduler_requestPaint = Scheduler.unstable_requestPaint;
12079
var Scheduler_now = Scheduler.unstable_now;
12080
var Scheduler_getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel;
12081
var Scheduler_ImmediatePriority = Scheduler.unstable_ImmediatePriority;
12082
var Scheduler_UserBlockingPriority = Scheduler.unstable_UserBlockingPriority;
12083
var Scheduler_NormalPriority = Scheduler.unstable_NormalPriority;
12084
var Scheduler_LowPriority = Scheduler.unstable_LowPriority;
12085
var Scheduler_IdlePriority = Scheduler.unstable_IdlePriority;
12086
12087
if (enableSchedulerTracing) {
12088
  // Provide explicit error message when production+profiling bundle of e.g.
12089
  // react-dom is used with production (non-profiling) bundle of
12090
  // scheduler/tracing
12091
  (function () {
12092
    if (!(tracing.__interactionsRef != null && tracing.__interactionsRef.current != null)) {
12093
      {
12094
        throw ReactError(Error("It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling"));
12095
      }
12096
    }
12097
  })();
12098
}
12099
12100
var fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use
12101
// ascending numbers so we can compare them like numbers. They start at 90 to
12102
// avoid clashing with Scheduler's priorities.
12103
12104
var ImmediatePriority = 99;
12105
var UserBlockingPriority$2 = 98;
12106
var NormalPriority = 97;
12107
var LowPriority = 96;
12108
var IdlePriority = 95; // NoPriority is the absence of priority. Also React-only.
12109
12110
var NoPriority = 90;
12111
var shouldYield = Scheduler_shouldYield;
12112
var requestPaint = // Fall back gracefully if we're running an older version of Scheduler.
12113
Scheduler_requestPaint !== undefined ? Scheduler_requestPaint : function () {};
12114
var syncQueue = null;
12115
var immediateQueueCallbackNode = null;
12116
var isFlushingSyncQueue = false;
12117
var initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly.
12118
// This will be the case for modern browsers that support `performance.now`. In
12119
// older browsers, Scheduler falls back to `Date.now`, which returns a Unix
12120
// timestamp. In that case, subtract the module initialization time to simulate
12121
// the behavior of performance.now and keep our times small enough to fit
12122
// within 32 bits.
12123
// TODO: Consider lifting this into Scheduler.
12124
12125
var now = initialTimeMs < 10000 ? Scheduler_now : function () {
12126
  return Scheduler_now() - initialTimeMs;
12127
};
12128
function getCurrentPriorityLevel() {
12129
  switch (Scheduler_getCurrentPriorityLevel()) {
12130
    case Scheduler_ImmediatePriority:
12131
      return ImmediatePriority;
12132
12133
    case Scheduler_UserBlockingPriority:
12134
      return UserBlockingPriority$2;
12135
12136
    case Scheduler_NormalPriority:
12137
      return NormalPriority;
12138
12139
    case Scheduler_LowPriority:
12140
      return LowPriority;
12141
12142
    case Scheduler_IdlePriority:
12143
      return IdlePriority;
12144
12145
    default:
12146
      (function () {
12147
        {
12148
          {
12149
            throw ReactError(Error("Unknown priority level."));
12150
          }
12151
        }
12152
      })();
12153
12154
  }
12155
}
12156
12157
function reactPriorityToSchedulerPriority(reactPriorityLevel) {
12158
  switch (reactPriorityLevel) {
12159
    case ImmediatePriority:
12160
      return Scheduler_ImmediatePriority;
12161
12162
    case UserBlockingPriority$2:
12163
      return Scheduler_UserBlockingPriority;
12164
12165
    case NormalPriority:
12166
      return Scheduler_NormalPriority;
12167
12168
    case LowPriority:
12169
      return Scheduler_LowPriority;
12170
12171
    case IdlePriority:
12172
      return Scheduler_IdlePriority;
12173
12174
    default:
12175
      (function () {
12176
        {
12177
          {
12178
            throw ReactError(Error("Unknown priority level."));
12179
          }
12180
        }
12181
      })();
12182
12183
  }
12184
}
12185
12186
function runWithPriority$2(reactPriorityLevel, fn) {
12187
  var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
12188
  return Scheduler_runWithPriority(priorityLevel, fn);
12189
}
12190
function scheduleCallback(reactPriorityLevel, callback, options) {
12191
  var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
12192
  return Scheduler_scheduleCallback(priorityLevel, callback, options);
12193
}
12194
function scheduleSyncCallback(callback) {
12195
  // Push this callback into an internal queue. We'll flush these either in
12196
  // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
12197
  if (syncQueue === null) {
12198
    syncQueue = [callback]; // Flush the queue in the next tick, at the earliest.
12199
12200
    immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl);
12201
  } else {
12202
    // Push onto existing queue. Don't need to schedule a callback because
12203
    // we already scheduled one when we created the queue.
12204
    syncQueue.push(callback);
12205
  }
12206
12207
  return fakeCallbackNode;
12208
}
12209
function cancelCallback(callbackNode) {
12210
  if (callbackNode !== fakeCallbackNode) {
12211
    Scheduler_cancelCallback(callbackNode);
12212
  }
12213
}
12214
function flushSyncCallbackQueue() {
12215
  if (immediateQueueCallbackNode !== null) {
12216
    var node = immediateQueueCallbackNode;
12217
    immediateQueueCallbackNode = null;
12218
    Scheduler_cancelCallback(node);
12219
  }
12220
12221
  flushSyncCallbackQueueImpl();
12222
}
12223
12224
function flushSyncCallbackQueueImpl() {
12225
  if (!isFlushingSyncQueue && syncQueue !== null) {
12226
    // Prevent re-entrancy.
12227
    isFlushingSyncQueue = true;
12228
    var i = 0;
12229
12230
    try {
12231
      var _isSync = true;
12232
      var queue = syncQueue;
12233
      runWithPriority$2(ImmediatePriority, function () {
12234
        for (; i < queue.length; i++) {
12235
          var callback = queue[i];
12236
12237
          do {
12238
            callback = callback(_isSync);
12239
          } while (callback !== null);
12240
        }
12241
      });
12242
      syncQueue = null;
12243
    } catch (error) {
12244
      // If something throws, leave the remaining callbacks on the queue.
12245
      if (syncQueue !== null) {
12246
        syncQueue = syncQueue.slice(i + 1);
12247
      } // Resume flushing in the next tick
12248
12249
12250
      Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueue);
12251
      throw error;
12252
    } finally {
12253
      isFlushingSyncQueue = false;
12254
    }
12255
  }
12256
}
12257
12258
var NoMode = 0;
12259
var StrictMode = 1; // TODO: Remove BatchedMode and ConcurrentMode by reading from the root
12260
// tag instead
12261
12262
var BatchedMode = 2;
12263
var ConcurrentMode = 4;
12264
var ProfileMode = 8;
12265
12266
// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
12267
// Math.pow(2, 30) - 1
12268
// 0b111111111111111111111111111111
12269
var MAX_SIGNED_31_BIT_INT = 1073741823;
12270
12271
var NoWork = 0; // TODO: Think of a better name for Never. The key difference with Idle is that
12272
// Never work can be committed in an inconsistent state without tearing the UI.
12273
// The main example is offscreen content, like a hidden subtree. So one possible
12274
// name is Offscreen. However, it also includes dehydrated Suspense boundaries,
12275
// which are inconsistent in the sense that they haven't finished yet, but
12276
// aren't visibly inconsistent because the server rendered HTML matches what the
12277
// hydrated tree would look like.
12278
12279
var Never = 1; // Idle is slightly higher priority than Never. It must completely finish in
12280
// order to be consistent.
12281
12282
var Idle = 2;
12283
var Sync = MAX_SIGNED_31_BIT_INT;
12284
var Batched = Sync - 1;
12285
var UNIT_SIZE = 10;
12286
var MAGIC_NUMBER_OFFSET = Batched - 1; // 1 unit of expiration time represents 10ms.
12287
12288
function msToExpirationTime(ms) {
12289
  // Always add an offset so that we don't clash with the magic number for NoWork.
12290
  return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
12291
}
12292
function expirationTimeToMs(expirationTime) {
12293
  return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
12294
}
12295
12296
function ceiling(num, precision) {
12297
  return ((num / precision | 0) + 1) * precision;
12298
}
12299
12300
function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
12301
  return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
12302
} // TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update
12303
// the names to reflect.
12304
12305
12306
var LOW_PRIORITY_EXPIRATION = 5000;
12307
var LOW_PRIORITY_BATCH_SIZE = 250;
12308
function computeAsyncExpiration(currentTime) {
12309
  return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
12310
}
12311
function computeSuspenseExpiration(currentTime, timeoutMs) {
12312
  // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time?
12313
  return computeExpirationBucket(currentTime, timeoutMs, LOW_PRIORITY_BATCH_SIZE);
12314
} // We intentionally set a higher expiration time for interactive updates in
12315
// dev than in production.
12316
//
12317
// If the main thread is being blocked so long that you hit the expiration,
12318
// it's a problem that could be solved with better scheduling.
12319
//
12320
// People will be more likely to notice this and fix it with the long
12321
// expiration time in development.
12322
//
12323
// In production we opt for better UX at the risk of masking scheduling
12324
// problems, by expiring fast.
12325
12326
var HIGH_PRIORITY_EXPIRATION = 500;
12327
var HIGH_PRIORITY_BATCH_SIZE = 100;
12328
function computeInteractiveExpiration(currentTime) {
12329
  return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
12330
}
12331
function inferPriorityFromExpirationTime(currentTime, expirationTime) {
12332
  if (expirationTime === Sync) {
12333
    return ImmediatePriority;
12334
  }
12335
12336
  if (expirationTime === Never || expirationTime === Idle) {
12337
    return IdlePriority;
12338
  }
12339
12340
  var msUntil = expirationTimeToMs(expirationTime) - expirationTimeToMs(currentTime);
12341
12342
  if (msUntil <= 0) {
12343
    return ImmediatePriority;
12344
  }
12345
12346
  if (msUntil <= HIGH_PRIORITY_EXPIRATION + HIGH_PRIORITY_BATCH_SIZE) {
12347
    return UserBlockingPriority$2;
12348
  }
12349
12350
  if (msUntil <= LOW_PRIORITY_EXPIRATION + LOW_PRIORITY_BATCH_SIZE) {
12351
    return NormalPriority;
12352
  } // TODO: Handle LowPriority
12353
  // Assume anything lower has idle priority
12354
12355
12356
  return IdlePriority;
12357
}
12358
12359
/**
12360
 * Forked from fbjs/warning:
12361
 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
12362
 *
12363
 * Only change is we use console.warn instead of console.error,
12364
 * and do nothing when 'console' is not supported.
12365
 * This really simplifies the code.
12366
 * ---
12367
 * Similar to invariant but only logs a warning if the condition is not met.
12368
 * This can be used to log issues in development environments in critical
12369
 * paths. Removing the logging code for production environments will keep the
12370
 * same logic and follow the same code paths.
12371
 */
12372
var lowPriorityWarningWithoutStack = function () {};
12373
12374
{
12375
  var printWarning = function (format) {
12376
    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
12377
      args[_key - 1] = arguments[_key];
12378
    }
12379
12380
    var argIndex = 0;
12381
    var message = 'Warning: ' + format.replace(/%s/g, function () {
12382
      return args[argIndex++];
12383
    });
12384
12385
    if (typeof console !== 'undefined') {
12386
      console.warn(message);
12387
    }
12388
12389
    try {
12390
      // --- Welcome to debugging React ---
12391
      // This error was thrown as a convenience so that you can use this stack
12392
      // to find the callsite that caused this warning to fire.
12393
      throw new Error(message);
12394
    } catch (x) {}
12395
  };
12396
12397
  lowPriorityWarningWithoutStack = function (condition, format) {
12398
    if (format === undefined) {
12399
      throw new Error('`lowPriorityWarningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
12400
    }
12401
12402
    if (!condition) {
12403
      for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
12404
        args[_key2 - 2] = arguments[_key2];
12405
      }
12406
12407
      printWarning.apply(void 0, [format].concat(args));
12408
    }
12409
  };
12410
}
12411
12412
var lowPriorityWarningWithoutStack$1 = lowPriorityWarningWithoutStack;
12413
12414
var ReactStrictModeWarnings = {
12415
  recordUnsafeLifecycleWarnings: function (fiber, instance) {},
12416
  flushPendingUnsafeLifecycleWarnings: function () {},
12417
  recordLegacyContextWarning: function (fiber, instance) {},
12418
  flushLegacyContextWarning: function () {},
12419
  discardPendingWarnings: function () {}
12420
};
12421
12422
{
12423
  var findStrictRoot = function (fiber) {
12424
    var maybeStrictRoot = null;
12425
    var node = fiber;
12426
12427
    while (node !== null) {
12428
      if (node.mode & StrictMode) {
12429
        maybeStrictRoot = node;
12430
      }
12431
12432
      node = node.return;
12433
    }
12434
12435
    return maybeStrictRoot;
12436
  };
12437
12438
  var setToSortedString = function (set) {
12439
    var array = [];
12440
    set.forEach(function (value) {
12441
      array.push(value);
12442
    });
12443
    return array.sort().join(', ');
12444
  };
12445
12446
  var pendingComponentWillMountWarnings = [];
12447
  var pendingUNSAFE_ComponentWillMountWarnings = [];
12448
  var pendingComponentWillReceivePropsWarnings = [];
12449
  var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12450
  var pendingComponentWillUpdateWarnings = [];
12451
  var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.
12452
12453
  var didWarnAboutUnsafeLifecycles = new Set();
12454
12455
  ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
12456
    // Dedup strategy: Warn once per component.
12457
    if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
12458
      return;
12459
    }
12460
12461
    if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.
12462
    instance.componentWillMount.__suppressDeprecationWarning !== true) {
12463
      pendingComponentWillMountWarnings.push(fiber);
12464
    }
12465
12466
    if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillMount === 'function') {
12467
      pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
12468
    }
12469
12470
    if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
12471
      pendingComponentWillReceivePropsWarnings.push(fiber);
12472
    }
12473
12474
    if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
12475
      pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
12476
    }
12477
12478
    if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
12479
      pendingComponentWillUpdateWarnings.push(fiber);
12480
    }
12481
12482
    if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {
12483
      pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
12484
    }
12485
  };
12486
12487
  ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
12488
    // We do an initial pass to gather component names
12489
    var componentWillMountUniqueNames = new Set();
12490
12491
    if (pendingComponentWillMountWarnings.length > 0) {
12492
      pendingComponentWillMountWarnings.forEach(function (fiber) {
12493
        componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
12494
        didWarnAboutUnsafeLifecycles.add(fiber.type);
12495
      });
12496
      pendingComponentWillMountWarnings = [];
12497
    }
12498
12499
    var UNSAFE_componentWillMountUniqueNames = new Set();
12500
12501
    if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
12502
      pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {
12503
        UNSAFE_componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
12504
        didWarnAboutUnsafeLifecycles.add(fiber.type);
12505
      });
12506
      pendingUNSAFE_ComponentWillMountWarnings = [];
12507
    }
12508
12509
    var componentWillReceivePropsUniqueNames = new Set();
12510
12511
    if (pendingComponentWillReceivePropsWarnings.length > 0) {
12512
      pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
12513
        componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
12514
        didWarnAboutUnsafeLifecycles.add(fiber.type);
12515
      });
12516
      pendingComponentWillReceivePropsWarnings = [];
12517
    }
12518
12519
    var UNSAFE_componentWillReceivePropsUniqueNames = new Set();
12520
12521
    if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
12522
      pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {
12523
        UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
12524
        didWarnAboutUnsafeLifecycles.add(fiber.type);
12525
      });
12526
      pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12527
    }
12528
12529
    var componentWillUpdateUniqueNames = new Set();
12530
12531
    if (pendingComponentWillUpdateWarnings.length > 0) {
12532
      pendingComponentWillUpdateWarnings.forEach(function (fiber) {
12533
        componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
12534
        didWarnAboutUnsafeLifecycles.add(fiber.type);
12535
      });
12536
      pendingComponentWillUpdateWarnings = [];
12537
    }
12538
12539
    var UNSAFE_componentWillUpdateUniqueNames = new Set();
12540
12541
    if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
12542
      pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {
12543
        UNSAFE_componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
12544
        didWarnAboutUnsafeLifecycles.add(fiber.type);
12545
      });
12546
      pendingUNSAFE_ComponentWillUpdateWarnings = [];
12547
    } // Finally, we flush all the warnings
12548
    // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'
12549
12550
12551
    if (UNSAFE_componentWillMountUniqueNames.size > 0) {
12552
      var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
12553
      warningWithoutStack$1(false, 'Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames);
12554
    }
12555
12556
    if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
12557
      var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);
12558
12559
      warningWithoutStack$1(false, 'Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state\n' + '\nPlease update the following components: %s', _sortedNames);
12560
    }
12561
12562
    if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
12563
      var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);
12564
12565
      warningWithoutStack$1(false, 'Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2);
12566
    }
12567
12568
    if (componentWillMountUniqueNames.size > 0) {
12569
      var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);
12570
12571
      lowPriorityWarningWithoutStack$1(false, 'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3);
12572
    }
12573
12574
    if (componentWillReceivePropsUniqueNames.size > 0) {
12575
      var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);
12576
12577
      lowPriorityWarningWithoutStack$1(false, 'componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4);
12578
    }
12579
12580
    if (componentWillUpdateUniqueNames.size > 0) {
12581
      var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);
12582
12583
      lowPriorityWarningWithoutStack$1(false, 'componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5);
12584
    }
12585
  };
12586
12587
  var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.
12588
12589
  var didWarnAboutLegacyContext = new Set();
12590
12591
  ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
12592
    var strictRoot = findStrictRoot(fiber);
12593
12594
    if (strictRoot === null) {
12595
      warningWithoutStack$1(false, 'Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');
12596
      return;
12597
    } // Dedup strategy: Warn once per component.
12598
12599
12600
    if (didWarnAboutLegacyContext.has(fiber.type)) {
12601
      return;
12602
    }
12603
12604
    var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
12605
12606
    if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
12607
      if (warningsForRoot === undefined) {
12608
        warningsForRoot = [];
12609
        pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
12610
      }
12611
12612
      warningsForRoot.push(fiber);
12613
    }
12614
  };
12615
12616
  ReactStrictModeWarnings.flushLegacyContextWarning = function () {
12617
    pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
12618
      var uniqueNames = new Set();
12619
      fiberArray.forEach(function (fiber) {
12620
        uniqueNames.add(getComponentName(fiber.type) || 'Component');
12621
        didWarnAboutLegacyContext.add(fiber.type);
12622
      });
12623
      var sortedNames = setToSortedString(uniqueNames);
12624
      var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
12625
      warningWithoutStack$1(false, 'Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://fb.me/react-legacy-context' + '%s', sortedNames, strictRootComponentStack);
12626
    });
12627
  };
12628
12629
  ReactStrictModeWarnings.discardPendingWarnings = function () {
12630
    pendingComponentWillMountWarnings = [];
12631
    pendingUNSAFE_ComponentWillMountWarnings = [];
12632
    pendingComponentWillReceivePropsWarnings = [];
12633
    pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12634
    pendingComponentWillUpdateWarnings = [];
12635
    pendingUNSAFE_ComponentWillUpdateWarnings = [];
12636
    pendingLegacyContextWarning = new Map();
12637
  };
12638
}
12639
12640
var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.
12641
12642
var failedBoundaries = null;
12643
var setRefreshHandler = function (handler) {
12644
  {
12645
    resolveFamily = handler;
12646
  }
12647
};
12648
function resolveFunctionForHotReloading(type) {
12649
  {
12650
    if (resolveFamily === null) {
12651
      // Hot reloading is disabled.
12652
      return type;
12653
    }
12654
12655
    var family = resolveFamily(type);
12656
12657
    if (family === undefined) {
12658
      return type;
12659
    } // Use the latest known implementation.
12660
12661
12662
    return family.current;
12663
  }
12664
}
12665
function resolveClassForHotReloading(type) {
12666
  // No implementation differences.
12667
  return resolveFunctionForHotReloading(type);
12668
}
12669
function resolveForwardRefForHotReloading(type) {
12670
  {
12671
    if (resolveFamily === null) {
12672
      // Hot reloading is disabled.
12673
      return type;
12674
    }
12675
12676
    var family = resolveFamily(type);
12677
12678
    if (family === undefined) {
12679
      // Check if we're dealing with a real forwardRef. Don't want to crash early.
12680
      if (type !== null && type !== undefined && typeof type.render === 'function') {
12681
        // ForwardRef is special because its resolved .type is an object,
12682
        // but it's possible that we only have its inner render function in the map.
12683
        // If that inner render function is different, we'll build a new forwardRef type.
12684
        var currentRender = resolveFunctionForHotReloading(type.render);
12685
12686
        if (type.render !== currentRender) {
12687
          var syntheticType = {
12688
            $$typeof: REACT_FORWARD_REF_TYPE,
12689
            render: currentRender
12690
          };
12691
12692
          if (type.displayName !== undefined) {
12693
            syntheticType.displayName = type.displayName;
12694
          }
12695
12696
          return syntheticType;
12697
        }
12698
      }
12699
12700
      return type;
12701
    } // Use the latest known implementation.
12702
12703
12704
    return family.current;
12705
  }
12706
}
12707
function isCompatibleFamilyForHotReloading(fiber, element) {
12708
  {
12709
    if (resolveFamily === null) {
12710
      // Hot reloading is disabled.
12711
      return false;
12712
    }
12713
12714
    var prevType = fiber.elementType;
12715
    var nextType = element.type; // If we got here, we know types aren't === equal.
12716
12717
    var needsCompareFamilies = false;
12718
    var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;
12719
12720
    switch (fiber.tag) {
12721
      case ClassComponent:
12722
        {
12723
          if (typeof nextType === 'function') {
12724
            needsCompareFamilies = true;
12725
          }
12726
12727
          break;
12728
        }
12729
12730
      case FunctionComponent:
12731
        {
12732
          if (typeof nextType === 'function') {
12733
            needsCompareFamilies = true;
12734
          } else if ($$typeofNextType === REACT_LAZY_TYPE) {
12735
            // We don't know the inner type yet.
12736
            // We're going to assume that the lazy inner type is stable,
12737
            // and so it is sufficient to avoid reconciling it away.
12738
            // We're not going to unwrap or actually use the new lazy type.
12739
            needsCompareFamilies = true;
12740
          }
12741
12742
          break;
12743
        }
12744
12745
      case ForwardRef:
12746
        {
12747
          if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
12748
            needsCompareFamilies = true;
12749
          } else if ($$typeofNextType === REACT_LAZY_TYPE) {
12750
            needsCompareFamilies = true;
12751
          }
12752
12753
          break;
12754
        }
12755
12756
      case MemoComponent:
12757
      case SimpleMemoComponent:
12758
        {
12759
          if ($$typeofNextType === REACT_MEMO_TYPE) {
12760
            // TODO: if it was but can no longer be simple,
12761
            // we shouldn't set this.
12762
            needsCompareFamilies = true;
12763
          } else if ($$typeofNextType === REACT_LAZY_TYPE) {
12764
            needsCompareFamilies = true;
12765
          }
12766
12767
          break;
12768
        }
12769
12770
      default:
12771
        return false;
12772
    } // Check if both types have a family and it's the same one.
12773
12774
12775
    if (needsCompareFamilies) {
12776
      // Note: memo() and forwardRef() we'll compare outer rather than inner type.
12777
      // This means both of them need to be registered to preserve state.
12778
      // If we unwrapped and compared the inner types for wrappers instead,
12779
      // then we would risk falsely saying two separate memo(Foo)
12780
      // calls are equivalent because they wrap the same Foo function.
12781
      var prevFamily = resolveFamily(prevType);
12782
12783
      if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {
12784
        return true;
12785
      }
12786
    }
12787
12788
    return false;
12789
  }
12790
}
12791
function markFailedErrorBoundaryForHotReloading(fiber) {
12792
  {
12793
    if (resolveFamily === null) {
12794
      // Hot reloading is disabled.
12795
      return;
12796
    }
12797
12798
    if (typeof WeakSet !== 'function') {
12799
      return;
12800
    }
12801
12802
    if (failedBoundaries === null) {
12803
      failedBoundaries = new WeakSet();
12804
    }
12805
12806
    failedBoundaries.add(fiber);
12807
  }
12808
}
12809
var scheduleRefresh = function (root, update) {
12810
  {
12811
    if (resolveFamily === null) {
12812
      // Hot reloading is disabled.
12813
      return;
12814
    }
12815
12816
    var staleFamilies = update.staleFamilies,
12817
        updatedFamilies = update.updatedFamilies;
12818
    flushPassiveEffects();
12819
    flushSync(function () {
12820
      scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);
12821
    });
12822
  }
12823
};
12824
var scheduleRoot = function (root, element) {
12825
  {
12826
    if (root.context !== emptyContextObject) {
12827
      // Super edge case: root has a legacy _renderSubtree context
12828
      // but we don't know the parentComponent so we can't pass it.
12829
      // Just ignore. We'll delete this with _renderSubtree code path later.
12830
      return;
12831
    }
12832
12833
    flushPassiveEffects();
12834
    updateContainerAtExpirationTime(element, root, null, Sync, null);
12835
  }
12836
};
12837
12838
function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
12839
  {
12840
    var alternate = fiber.alternate,
12841
        child = fiber.child,
12842
        sibling = fiber.sibling,
12843
        tag = fiber.tag,
12844
        type = fiber.type;
12845
    var candidateType = null;
12846
12847
    switch (tag) {
12848
      case FunctionComponent:
12849
      case SimpleMemoComponent:
12850
      case ClassComponent:
12851
        candidateType = type;
12852
        break;
12853
12854
      case ForwardRef:
12855
        candidateType = type.render;
12856
        break;
12857
12858
      default:
12859
        break;
12860
    }
12861
12862
    if (resolveFamily === null) {
12863
      throw new Error('Expected resolveFamily to be set during hot reload.');
12864
    }
12865
12866
    var needsRender = false;
12867
    var needsRemount = false;
12868
12869
    if (candidateType !== null) {
12870
      var family = resolveFamily(candidateType);
12871
12872
      if (family !== undefined) {
12873
        if (staleFamilies.has(family)) {
12874
          needsRemount = true;
12875
        } else if (updatedFamilies.has(family)) {
12876
          if (tag === ClassComponent) {
12877
            needsRemount = true;
12878
          } else {
12879
            needsRender = true;
12880
          }
12881
        }
12882
      }
12883
    }
12884
12885
    if (failedBoundaries !== null) {
12886
      if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
12887
        needsRemount = true;
12888
      }
12889
    }
12890
12891
    if (needsRemount) {
12892
      fiber._debugNeedsRemount = true;
12893
    }
12894
12895
    if (needsRemount || needsRender) {
12896
      scheduleWork(fiber, Sync);
12897
    }
12898
12899
    if (child !== null && !needsRemount) {
12900
      scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
12901
    }
12902
12903
    if (sibling !== null) {
12904
      scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
12905
    }
12906
  }
12907
}
12908
12909
var findHostInstancesForRefresh = function (root, families) {
12910
  {
12911
    var hostInstances = new Set();
12912
    var types = new Set(families.map(function (family) {
12913
      return family.current;
12914
    }));
12915
    findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);
12916
    return hostInstances;
12917
  }
12918
};
12919
12920
function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
12921
  {
12922
    var child = fiber.child,
12923
        sibling = fiber.sibling,
12924
        tag = fiber.tag,
12925
        type = fiber.type;
12926
    var candidateType = null;
12927
12928
    switch (tag) {
12929
      case FunctionComponent:
12930
      case SimpleMemoComponent:
12931
      case ClassComponent:
12932
        candidateType = type;
12933
        break;
12934
12935
      case ForwardRef:
12936
        candidateType = type.render;
12937
        break;
12938
12939
      default:
12940
        break;
12941
    }
12942
12943
    var didMatch = false;
12944
12945
    if (candidateType !== null) {
12946
      if (types.has(candidateType)) {
12947
        didMatch = true;
12948
      }
12949
    }
12950
12951
    if (didMatch) {
12952
      // We have a match. This only drills down to the closest host components.
12953
      // There's no need to search deeper because for the purpose of giving
12954
      // visual feedback, "flashing" outermost parent rectangles is sufficient.
12955
      findHostInstancesForFiberShallowly(fiber, hostInstances);
12956
    } else {
12957
      // If there's no match, maybe there will be one further down in the child tree.
12958
      if (child !== null) {
12959
        findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
12960
      }
12961
    }
12962
12963
    if (sibling !== null) {
12964
      findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
12965
    }
12966
  }
12967
}
12968
12969
function findHostInstancesForFiberShallowly(fiber, hostInstances) {
12970
  {
12971
    var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);
12972
12973
    if (foundHostInstances) {
12974
      return;
12975
    } // If we didn't find any host children, fallback to closest host parent.
12976
12977
12978
    var node = fiber;
12979
12980
    while (true) {
12981
      switch (node.tag) {
12982
        case HostComponent:
12983
          hostInstances.add(node.stateNode);
12984
          return;
12985
12986
        case HostPortal:
12987
          hostInstances.add(node.stateNode.containerInfo);
12988
          return;
12989
12990
        case HostRoot:
12991
          hostInstances.add(node.stateNode.containerInfo);
12992
          return;
12993
      }
12994
12995
      if (node.return === null) {
12996
        throw new Error('Expected to reach root first.');
12997
      }
12998
12999
      node = node.return;
13000
    }
13001
  }
13002
}
13003
13004
function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
13005
  {
13006
    var node = fiber;
13007
    var foundHostInstances = false;
13008
13009
    while (true) {
13010
      if (node.tag === HostComponent) {
13011
        // We got a match.
13012
        foundHostInstances = true;
13013
        hostInstances.add(node.stateNode); // There may still be more, so keep searching.
13014
      } else if (node.child !== null) {
13015
        node.child.return = node;
13016
        node = node.child;
13017
        continue;
13018
      }
13019
13020
      if (node === fiber) {
13021
        return foundHostInstances;
13022
      }
13023
13024
      while (node.sibling === null) {
13025
        if (node.return === null || node.return === fiber) {
13026
          return foundHostInstances;
13027
        }
13028
13029
        node = node.return;
13030
      }
13031
13032
      node.sibling.return = node.return;
13033
      node = node.sibling;
13034
    }
13035
  }
13036
13037
  return false;
13038
}
13039
13040
function resolveDefaultProps(Component, baseProps) {
13041
  if (Component && Component.defaultProps) {
13042
    // Resolve default props. Taken from ReactElement
13043
    var props = _assign({}, baseProps);
13044
13045
    var defaultProps = Component.defaultProps;
13046
13047
    for (var propName in defaultProps) {
13048
      if (props[propName] === undefined) {
13049
        props[propName] = defaultProps[propName];
13050
      }
13051
    }
13052
13053
    return props;
13054
  }
13055
13056
  return baseProps;
13057
}
13058
function readLazyComponentType(lazyComponent) {
13059
  initializeLazyComponentType(lazyComponent);
13060
13061
  if (lazyComponent._status !== Resolved) {
13062
    throw lazyComponent._result;
13063
  }
13064
13065
  return lazyComponent._result;
13066
}
13067
13068
var valueCursor = createCursor(null);
13069
var rendererSigil;
13070
13071
{
13072
  // Use this to detect multiple renderers using the same context
13073
  rendererSigil = {};
13074
}
13075
13076
var currentlyRenderingFiber = null;
13077
var lastContextDependency = null;
13078
var lastContextWithAllBitsObserved = null;
13079
var isDisallowedContextReadInDEV = false;
13080
function resetContextDependencies() {
13081
  // This is called right before React yields execution, to ensure `readContext`
13082
  // cannot be called outside the render phase.
13083
  currentlyRenderingFiber = null;
13084
  lastContextDependency = null;
13085
  lastContextWithAllBitsObserved = null;
13086
13087
  {
13088
    isDisallowedContextReadInDEV = false;
13089
  }
13090
}
13091
function enterDisallowedContextReadInDEV() {
13092
  {
13093
    isDisallowedContextReadInDEV = true;
13094
  }
13095
}
13096
function exitDisallowedContextReadInDEV() {
13097
  {
13098
    isDisallowedContextReadInDEV = false;
13099
  }
13100
}
13101
function pushProvider(providerFiber, nextValue) {
13102
  var context = providerFiber.type._context;
13103
13104
  if (isPrimaryRenderer) {
13105
    push(valueCursor, context._currentValue, providerFiber);
13106
    context._currentValue = nextValue;
13107
13108
    {
13109
      !(context._currentRenderer === undefined || context._currentRenderer === null || context._currentRenderer === rendererSigil) ? warningWithoutStack$1(false, 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.') : void 0;
13110
      context._currentRenderer = rendererSigil;
13111
    }
13112
  } else {
13113
    push(valueCursor, context._currentValue2, providerFiber);
13114
    context._currentValue2 = nextValue;
13115
13116
    {
13117
      !(context._currentRenderer2 === undefined || context._currentRenderer2 === null || context._currentRenderer2 === rendererSigil) ? warningWithoutStack$1(false, 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.') : void 0;
13118
      context._currentRenderer2 = rendererSigil;
13119
    }
13120
  }
13121
}
13122
function popProvider(providerFiber) {
13123
  var currentValue = valueCursor.current;
13124
  pop(valueCursor, providerFiber);
13125
  var context = providerFiber.type._context;
13126
13127
  if (isPrimaryRenderer) {
13128
    context._currentValue = currentValue;
13129
  } else {
13130
    context._currentValue2 = currentValue;
13131
  }
13132
}
13133
function calculateChangedBits(context, newValue, oldValue) {
13134
  if (is$1(oldValue, newValue)) {
13135
    // No change
13136
    return 0;
13137
  } else {
13138
    var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
13139
13140
    {
13141
      !((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits) ? warning$1(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0;
13142
    }
13143
13144
    return changedBits | 0;
13145
  }
13146
}
13147
function scheduleWorkOnParentPath(parent, renderExpirationTime) {
13148
  // Update the child expiration time of all the ancestors, including
13149
  // the alternates.
13150
  var node = parent;
13151
13152
  while (node !== null) {
13153
    var alternate = node.alternate;
13154
13155
    if (node.childExpirationTime < renderExpirationTime) {
13156
      node.childExpirationTime = renderExpirationTime;
13157
13158
      if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
13159
        alternate.childExpirationTime = renderExpirationTime;
13160
      }
13161
    } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
13162
      alternate.childExpirationTime = renderExpirationTime;
13163
    } else {
13164
      // Neither alternate was updated, which means the rest of the
13165
      // ancestor path already has sufficient priority.
13166
      break;
13167
    }
13168
13169
    node = node.return;
13170
  }
13171
}
13172
function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
13173
  var fiber = workInProgress.child;
13174
13175
  if (fiber !== null) {
13176
    // Set the return pointer of the child to the work-in-progress fiber.
13177
    fiber.return = workInProgress;
13178
  }
13179
13180
  while (fiber !== null) {
13181
    var nextFiber = void 0; // Visit this fiber.
13182
13183
    var list = fiber.dependencies;
13184
13185
    if (list !== null) {
13186
      nextFiber = fiber.child;
13187
      var dependency = list.firstContext;
13188
13189
      while (dependency !== null) {
13190
        // Check if the context matches.
13191
        if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
13192
          // Match! Schedule an update on this fiber.
13193
          if (fiber.tag === ClassComponent) {
13194
            // Schedule a force update on the work-in-progress.
13195
            var update = createUpdate(renderExpirationTime, null);
13196
            update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the
13197
            // update to the current fiber, too, which means it will persist even if
13198
            // this render is thrown away. Since it's a race condition, not sure it's
13199
            // worth fixing.
13200
13201
            enqueueUpdate(fiber, update);
13202
          }
13203
13204
          if (fiber.expirationTime < renderExpirationTime) {
13205
            fiber.expirationTime = renderExpirationTime;
13206
          }
13207
13208
          var alternate = fiber.alternate;
13209
13210
          if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
13211
            alternate.expirationTime = renderExpirationTime;
13212
          }
13213
13214
          scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too.
13215
13216
          if (list.expirationTime < renderExpirationTime) {
13217
            list.expirationTime = renderExpirationTime;
13218
          } // Since we already found a match, we can stop traversing the
13219
          // dependency list.
13220
13221
13222
          break;
13223
        }
13224
13225
        dependency = dependency.next;
13226
      }
13227
    } else if (fiber.tag === ContextProvider) {
13228
      // Don't scan deeper if this is a matching provider
13229
      nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
13230
    } else if (enableSuspenseServerRenderer && fiber.tag === DehydratedFragment) {
13231
      // If a dehydrated suspense bounudary is in this subtree, we don't know
13232
      // if it will have any context consumers in it. The best we can do is
13233
      // mark it as having updates.
13234
      var parentSuspense = fiber.return;
13235
13236
      (function () {
13237
        if (!(parentSuspense !== null)) {
13238
          {
13239
            throw ReactError(Error("We just came from a parent so we must have had a parent. This is a bug in React."));
13240
          }
13241
        }
13242
      })();
13243
13244
      if (parentSuspense.expirationTime < renderExpirationTime) {
13245
        parentSuspense.expirationTime = renderExpirationTime;
13246
      }
13247
13248
      var _alternate = parentSuspense.alternate;
13249
13250
      if (_alternate !== null && _alternate.expirationTime < renderExpirationTime) {
13251
        _alternate.expirationTime = renderExpirationTime;
13252
      } // This is intentionally passing this fiber as the parent
13253
      // because we want to schedule this fiber as having work
13254
      // on its children. We'll use the childExpirationTime on
13255
      // this fiber to indicate that a context has changed.
13256
13257
13258
      scheduleWorkOnParentPath(parentSuspense, renderExpirationTime);
13259
      nextFiber = fiber.sibling;
13260
    } else {
13261
      // Traverse down.
13262
      nextFiber = fiber.child;
13263
    }
13264
13265
    if (nextFiber !== null) {
13266
      // Set the return pointer of the child to the work-in-progress fiber.
13267
      nextFiber.return = fiber;
13268
    } else {
13269
      // No child. Traverse to next sibling.
13270
      nextFiber = fiber;
13271
13272
      while (nextFiber !== null) {
13273
        if (nextFiber === workInProgress) {
13274
          // We're back to the root of this subtree. Exit.
13275
          nextFiber = null;
13276
          break;
13277
        }
13278
13279
        var sibling = nextFiber.sibling;
13280
13281
        if (sibling !== null) {
13282
          // Set the return pointer of the sibling to the work-in-progress fiber.
13283
          sibling.return = nextFiber.return;
13284
          nextFiber = sibling;
13285
          break;
13286
        } // No more siblings. Traverse up.
13287
13288
13289
        nextFiber = nextFiber.return;
13290
      }
13291
    }
13292
13293
    fiber = nextFiber;
13294
  }
13295
}
13296
function prepareToReadContext(workInProgress, renderExpirationTime) {
13297
  currentlyRenderingFiber = workInProgress;
13298
  lastContextDependency = null;
13299
  lastContextWithAllBitsObserved = null;
13300
  var dependencies = workInProgress.dependencies;
13301
13302
  if (dependencies !== null) {
13303
    var firstContext = dependencies.firstContext;
13304
13305
    if (firstContext !== null) {
13306
      if (dependencies.expirationTime >= renderExpirationTime) {
13307
        // Context list has a pending update. Mark that this fiber performed work.
13308
        markWorkInProgressReceivedUpdate();
13309
      } // Reset the work-in-progress list
13310
13311
13312
      dependencies.firstContext = null;
13313
    }
13314
  }
13315
}
13316
function readContext(context, observedBits) {
13317
  {
13318
    // This warning would fire if you read context inside a Hook like useMemo.
13319
    // Unlike the class check below, it's not enforced in production for perf.
13320
    !!isDisallowedContextReadInDEV ? warning$1(false, 'Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().') : void 0;
13321
  }
13322
13323
  if (lastContextWithAllBitsObserved === context) {// Nothing to do. We already observe everything in this context.
13324
  } else if (observedBits === false || observedBits === 0) {// Do not observe any updates.
13325
  } else {
13326
    var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types.
13327
13328
    if (typeof observedBits !== 'number' || observedBits === MAX_SIGNED_31_BIT_INT) {
13329
      // Observe all updates.
13330
      lastContextWithAllBitsObserved = context;
13331
      resolvedObservedBits = MAX_SIGNED_31_BIT_INT;
13332
    } else {
13333
      resolvedObservedBits = observedBits;
13334
    }
13335
13336
    var contextItem = {
13337
      context: context,
13338
      observedBits: resolvedObservedBits,
13339
      next: null
13340
    };
13341
13342
    if (lastContextDependency === null) {
13343
      (function () {
13344
        if (!(currentlyRenderingFiber !== null)) {
13345
          {
13346
            throw ReactError(Error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."));
13347
          }
13348
        }
13349
      })(); // This is the first dependency for this component. Create a new list.
13350
13351
13352
      lastContextDependency = contextItem;
13353
      currentlyRenderingFiber.dependencies = {
13354
        expirationTime: NoWork,
13355
        firstContext: contextItem,
13356
        responders: null
13357
      };
13358
    } else {
13359
      // Append a new context item.
13360
      lastContextDependency = lastContextDependency.next = contextItem;
13361
    }
13362
  }
13363
13364
  return isPrimaryRenderer ? context._currentValue : context._currentValue2;
13365
}
13366
13367
// UpdateQueue is a linked list of prioritized updates.
13368
//
13369
// Like fibers, update queues come in pairs: a current queue, which represents
13370
// the visible state of the screen, and a work-in-progress queue, which can be
13371
// mutated and processed asynchronously before it is committed — a form of
13372
// double buffering. If a work-in-progress render is discarded before finishing,
13373
// we create a new work-in-progress by cloning the current queue.
13374
//
13375
// Both queues share a persistent, singly-linked list structure. To schedule an
13376
// update, we append it to the end of both queues. Each queue maintains a
13377
// pointer to first update in the persistent list that hasn't been processed.
13378
// The work-in-progress pointer always has a position equal to or greater than
13379
// the current queue, since we always work on that one. The current queue's
13380
// pointer is only updated during the commit phase, when we swap in the
13381
// work-in-progress.
13382
//
13383
// For example:
13384
//
13385
//   Current pointer:           A - B - C - D - E - F
13386
//   Work-in-progress pointer:              D - E - F
13387
//                                          ^
13388
//                                          The work-in-progress queue has
13389
//                                          processed more updates than current.
13390
//
13391
// The reason we append to both queues is because otherwise we might drop
13392
// updates without ever processing them. For example, if we only add updates to
13393
// the work-in-progress queue, some updates could be lost whenever a work-in
13394
// -progress render restarts by cloning from current. Similarly, if we only add
13395
// updates to the current queue, the updates will be lost whenever an already
13396
// in-progress queue commits and swaps with the current queue. However, by
13397
// adding to both queues, we guarantee that the update will be part of the next
13398
// work-in-progress. (And because the work-in-progress queue becomes the
13399
// current queue once it commits, there's no danger of applying the same
13400
// update twice.)
13401
//
13402
// Prioritization
13403
// --------------
13404
//
13405
// Updates are not sorted by priority, but by insertion; new updates are always
13406
// appended to the end of the list.
13407
//
13408
// The priority is still important, though. When processing the update queue
13409
// during the render phase, only the updates with sufficient priority are
13410
// included in the result. If we skip an update because it has insufficient
13411
// priority, it remains in the queue to be processed later, during a lower
13412
// priority render. Crucially, all updates subsequent to a skipped update also
13413
// remain in the queue *regardless of their priority*. That means high priority
13414
// updates are sometimes processed twice, at two separate priorities. We also
13415
// keep track of a base state, that represents the state before the first
13416
// update in the queue is applied.
13417
//
13418
// For example:
13419
//
13420
//   Given a base state of '', and the following queue of updates
13421
//
13422
//     A1 - B2 - C1 - D2
13423
//
13424
//   where the number indicates the priority, and the update is applied to the
13425
//   previous state by appending a letter, React will process these updates as
13426
//   two separate renders, one per distinct priority level:
13427
//
13428
//   First render, at priority 1:
13429
//     Base state: ''
13430
//     Updates: [A1, C1]
13431
//     Result state: 'AC'
13432
//
13433
//   Second render, at priority 2:
13434
//     Base state: 'A'            <-  The base state does not include C1,
13435
//                                    because B2 was skipped.
13436
//     Updates: [B2, C1, D2]      <-  C1 was rebased on top of B2
13437
//     Result state: 'ABCD'
13438
//
13439
// Because we process updates in insertion order, and rebase high priority
13440
// updates when preceding updates are skipped, the final result is deterministic
13441
// regardless of priority. Intermediate state may vary according to system
13442
// resources, but the final state is always the same.
13443
var UpdateState = 0;
13444
var ReplaceState = 1;
13445
var ForceUpdate = 2;
13446
var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.
13447
// It should only be read right after calling `processUpdateQueue`, via
13448
// `checkHasForceUpdateAfterProcessing`.
13449
13450
var hasForceUpdate = false;
13451
var didWarnUpdateInsideUpdate;
13452
var currentlyProcessingQueue;
13453
13454
13455
{
13456
  didWarnUpdateInsideUpdate = false;
13457
  currentlyProcessingQueue = null;
13458
13459
  
13460
}
13461
13462
function createUpdateQueue(baseState) {
13463
  var queue = {
13464
    baseState: baseState,
13465
    firstUpdate: null,
13466
    lastUpdate: null,
13467
    firstCapturedUpdate: null,
13468
    lastCapturedUpdate: null,
13469
    firstEffect: null,
13470
    lastEffect: null,
13471
    firstCapturedEffect: null,
13472
    lastCapturedEffect: null
13473
  };
13474
  return queue;
13475
}
13476
13477
function cloneUpdateQueue(currentQueue) {
13478
  var queue = {
13479
    baseState: currentQueue.baseState,
13480
    firstUpdate: currentQueue.firstUpdate,
13481
    lastUpdate: currentQueue.lastUpdate,
13482
    // TODO: With resuming, if we bail out and resuse the child tree, we should
13483
    // keep these effects.
13484
    firstCapturedUpdate: null,
13485
    lastCapturedUpdate: null,
13486
    firstEffect: null,
13487
    lastEffect: null,
13488
    firstCapturedEffect: null,
13489
    lastCapturedEffect: null
13490
  };
13491
  return queue;
13492
}
13493
13494
function createUpdate(expirationTime, suspenseConfig) {
13495
  var update = {
13496
    expirationTime: expirationTime,
13497
    suspenseConfig: suspenseConfig,
13498
    tag: UpdateState,
13499
    payload: null,
13500
    callback: null,
13501
    next: null,
13502
    nextEffect: null
13503
  };
13504
13505
  {
13506
    update.priority = getCurrentPriorityLevel();
13507
  }
13508
13509
  return update;
13510
}
13511
13512
function appendUpdateToQueue(queue, update) {
13513
  // Append the update to the end of the list.
13514
  if (queue.lastUpdate === null) {
13515
    // Queue is empty
13516
    queue.firstUpdate = queue.lastUpdate = update;
13517
  } else {
13518
    queue.lastUpdate.next = update;
13519
    queue.lastUpdate = update;
13520
  }
13521
}
13522
13523
function enqueueUpdate(fiber, update) {
13524
  // Update queues are created lazily.
13525
  var alternate = fiber.alternate;
13526
  var queue1;
13527
  var queue2;
13528
13529
  if (alternate === null) {
13530
    // There's only one fiber.
13531
    queue1 = fiber.updateQueue;
13532
    queue2 = null;
13533
13534
    if (queue1 === null) {
13535
      queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
13536
    }
13537
  } else {
13538
    // There are two owners.
13539
    queue1 = fiber.updateQueue;
13540
    queue2 = alternate.updateQueue;
13541
13542
    if (queue1 === null) {
13543
      if (queue2 === null) {
13544
        // Neither fiber has an update queue. Create new ones.
13545
        queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
13546
        queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
13547
      } else {
13548
        // Only one fiber has an update queue. Clone to create a new one.
13549
        queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
13550
      }
13551
    } else {
13552
      if (queue2 === null) {
13553
        // Only one fiber has an update queue. Clone to create a new one.
13554
        queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
13555
      } else {// Both owners have an update queue.
13556
      }
13557
    }
13558
  }
13559
13560
  if (queue2 === null || queue1 === queue2) {
13561
    // There's only a single queue.
13562
    appendUpdateToQueue(queue1, update);
13563
  } else {
13564
    // There are two queues. We need to append the update to both queues,
13565
    // while accounting for the persistent structure of the list — we don't
13566
    // want the same update to be added multiple times.
13567
    if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
13568
      // One of the queues is not empty. We must add the update to both queues.
13569
      appendUpdateToQueue(queue1, update);
13570
      appendUpdateToQueue(queue2, update);
13571
    } else {
13572
      // Both queues are non-empty. The last update is the same in both lists,
13573
      // because of structural sharing. So, only append to one of the lists.
13574
      appendUpdateToQueue(queue1, update); // But we still need to update the `lastUpdate` pointer of queue2.
13575
13576
      queue2.lastUpdate = update;
13577
    }
13578
  }
13579
13580
  {
13581
    if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
13582
      warningWithoutStack$1(false, 'An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.');
13583
      didWarnUpdateInsideUpdate = true;
13584
    }
13585
  }
13586
}
13587
function enqueueCapturedUpdate(workInProgress, update) {
13588
  // Captured updates go into a separate list, and only on the work-in-
13589
  // progress queue.
13590
  var workInProgressQueue = workInProgress.updateQueue;
13591
13592
  if (workInProgressQueue === null) {
13593
    workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
13594
  } else {
13595
    // TODO: I put this here rather than createWorkInProgress so that we don't
13596
    // clone the queue unnecessarily. There's probably a better way to
13597
    // structure this.
13598
    workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
13599
  } // Append the update to the end of the list.
13600
13601
13602
  if (workInProgressQueue.lastCapturedUpdate === null) {
13603
    // This is the first render phase update
13604
    workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
13605
  } else {
13606
    workInProgressQueue.lastCapturedUpdate.next = update;
13607
    workInProgressQueue.lastCapturedUpdate = update;
13608
  }
13609
}
13610
13611
function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
13612
  var current = workInProgress.alternate;
13613
13614
  if (current !== null) {
13615
    // If the work-in-progress queue is equal to the current queue,
13616
    // we need to clone it first.
13617
    if (queue === current.updateQueue) {
13618
      queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
13619
    }
13620
  }
13621
13622
  return queue;
13623
}
13624
13625
function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
13626
  switch (update.tag) {
13627
    case ReplaceState:
13628
      {
13629
        var payload = update.payload;
13630
13631
        if (typeof payload === 'function') {
13632
          // Updater function
13633
          {
13634
            enterDisallowedContextReadInDEV();
13635
13636
            if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
13637
              payload.call(instance, prevState, nextProps);
13638
            }
13639
          }
13640
13641
          var nextState = payload.call(instance, prevState, nextProps);
13642
13643
          {
13644
            exitDisallowedContextReadInDEV();
13645
          }
13646
13647
          return nextState;
13648
        } // State object
13649
13650
13651
        return payload;
13652
      }
13653
13654
    case CaptureUpdate:
13655
      {
13656
        workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
13657
      }
13658
    // Intentional fallthrough
13659
13660
    case UpdateState:
13661
      {
13662
        var _payload = update.payload;
13663
        var partialState;
13664
13665
        if (typeof _payload === 'function') {
13666
          // Updater function
13667
          {
13668
            enterDisallowedContextReadInDEV();
13669
13670
            if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
13671
              _payload.call(instance, prevState, nextProps);
13672
            }
13673
          }
13674
13675
          partialState = _payload.call(instance, prevState, nextProps);
13676
13677
          {
13678
            exitDisallowedContextReadInDEV();
13679
          }
13680
        } else {
13681
          // Partial state object
13682
          partialState = _payload;
13683
        }
13684
13685
        if (partialState === null || partialState === undefined) {
13686
          // Null and undefined are treated as no-ops.
13687
          return prevState;
13688
        } // Merge the partial state and the previous state.
13689
13690
13691
        return _assign({}, prevState, partialState);
13692
      }
13693
13694
    case ForceUpdate:
13695
      {
13696
        hasForceUpdate = true;
13697
        return prevState;
13698
      }
13699
  }
13700
13701
  return prevState;
13702
}
13703
13704
function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
13705
  hasForceUpdate = false;
13706
  queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
13707
13708
  {
13709
    currentlyProcessingQueue = queue;
13710
  } // These values may change as we process the queue.
13711
13712
13713
  var newBaseState = queue.baseState;
13714
  var newFirstUpdate = null;
13715
  var newExpirationTime = NoWork; // Iterate through the list of updates to compute the result.
13716
13717
  var update = queue.firstUpdate;
13718
  var resultState = newBaseState;
13719
13720
  while (update !== null) {
13721
    var updateExpirationTime = update.expirationTime;
13722
13723
    if (updateExpirationTime < renderExpirationTime) {
13724
      // This update does not have sufficient priority. Skip it.
13725
      if (newFirstUpdate === null) {
13726
        // This is the first skipped update. It will be the first update in
13727
        // the new list.
13728
        newFirstUpdate = update; // Since this is the first update that was skipped, the current result
13729
        // is the new base state.
13730
13731
        newBaseState = resultState;
13732
      } // Since this update will remain in the list, update the remaining
13733
      // expiration time.
13734
13735
13736
      if (newExpirationTime < updateExpirationTime) {
13737
        newExpirationTime = updateExpirationTime;
13738
      }
13739
    } else {
13740
      // This update does have sufficient priority.
13741
      // Mark the event time of this update as relevant to this render pass.
13742
      // TODO: This should ideally use the true event time of this update rather than
13743
      // its priority which is a derived and not reverseable value.
13744
      // TODO: We should skip this update if it was already committed but currently
13745
      // we have no way of detecting the difference between a committed and suspended
13746
      // update here.
13747
      markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process it and compute a new result.
13748
13749
      resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
13750
      var callback = update.callback;
13751
13752
      if (callback !== null) {
13753
        workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render.
13754
13755
        update.nextEffect = null;
13756
13757
        if (queue.lastEffect === null) {
13758
          queue.firstEffect = queue.lastEffect = update;
13759
        } else {
13760
          queue.lastEffect.nextEffect = update;
13761
          queue.lastEffect = update;
13762
        }
13763
      }
13764
    } // Continue to the next update.
13765
13766
13767
    update = update.next;
13768
  } // Separately, iterate though the list of captured updates.
13769
13770
13771
  var newFirstCapturedUpdate = null;
13772
  update = queue.firstCapturedUpdate;
13773
13774
  while (update !== null) {
13775
    var _updateExpirationTime = update.expirationTime;
13776
13777
    if (_updateExpirationTime < renderExpirationTime) {
13778
      // This update does not have sufficient priority. Skip it.
13779
      if (newFirstCapturedUpdate === null) {
13780
        // This is the first skipped captured update. It will be the first
13781
        // update in the new list.
13782
        newFirstCapturedUpdate = update; // If this is the first update that was skipped, the current result is
13783
        // the new base state.
13784
13785
        if (newFirstUpdate === null) {
13786
          newBaseState = resultState;
13787
        }
13788
      } // Since this update will remain in the list, update the remaining
13789
      // expiration time.
13790
13791
13792
      if (newExpirationTime < _updateExpirationTime) {
13793
        newExpirationTime = _updateExpirationTime;
13794
      }
13795
    } else {
13796
      // This update does have sufficient priority. Process it and compute
13797
      // a new result.
13798
      resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
13799
      var _callback = update.callback;
13800
13801
      if (_callback !== null) {
13802
        workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render.
13803
13804
        update.nextEffect = null;
13805
13806
        if (queue.lastCapturedEffect === null) {
13807
          queue.firstCapturedEffect = queue.lastCapturedEffect = update;
13808
        } else {
13809
          queue.lastCapturedEffect.nextEffect = update;
13810
          queue.lastCapturedEffect = update;
13811
        }
13812
      }
13813
    }
13814
13815
    update = update.next;
13816
  }
13817
13818
  if (newFirstUpdate === null) {
13819
    queue.lastUpdate = null;
13820
  }
13821
13822
  if (newFirstCapturedUpdate === null) {
13823
    queue.lastCapturedUpdate = null;
13824
  } else {
13825
    workInProgress.effectTag |= Callback;
13826
  }
13827
13828
  if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
13829
    // We processed every update, without skipping. That means the new base
13830
    // state is the same as the result state.
13831
    newBaseState = resultState;
13832
  }
13833
13834
  queue.baseState = newBaseState;
13835
  queue.firstUpdate = newFirstUpdate;
13836
  queue.firstCapturedUpdate = newFirstCapturedUpdate; // Set the remaining expiration time to be whatever is remaining in the queue.
13837
  // This should be fine because the only two other things that contribute to
13838
  // expiration time are props and context. We're already in the middle of the
13839
  // begin phase by the time we start processing the queue, so we've already
13840
  // dealt with the props. Context in components that specify
13841
  // shouldComponentUpdate is tricky; but we'll have to account for
13842
  // that regardless.
13843
13844
  markUnprocessedUpdateTime(newExpirationTime);
13845
  workInProgress.expirationTime = newExpirationTime;
13846
  workInProgress.memoizedState = resultState;
13847
13848
  {
13849
    currentlyProcessingQueue = null;
13850
  }
13851
}
13852
13853
function callCallback(callback, context) {
13854
  (function () {
13855
    if (!(typeof callback === 'function')) {
13856
      {
13857
        throw ReactError(Error("Invalid argument passed as callback. Expected a function. Instead received: " + callback));
13858
      }
13859
    }
13860
  })();
13861
13862
  callback.call(context);
13863
}
13864
13865
function resetHasForceUpdateBeforeProcessing() {
13866
  hasForceUpdate = false;
13867
}
13868
function checkHasForceUpdateAfterProcessing() {
13869
  return hasForceUpdate;
13870
}
13871
function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
13872
  // If the finished render included captured updates, and there are still
13873
  // lower priority updates left over, we need to keep the captured updates
13874
  // in the queue so that they are rebased and not dropped once we process the
13875
  // queue again at the lower priority.
13876
  if (finishedQueue.firstCapturedUpdate !== null) {
13877
    // Join the captured update list to the end of the normal list.
13878
    if (finishedQueue.lastUpdate !== null) {
13879
      finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
13880
      finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
13881
    } // Clear the list of captured updates.
13882
13883
13884
    finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
13885
  } // Commit the effects
13886
13887
13888
  commitUpdateEffects(finishedQueue.firstEffect, instance);
13889
  finishedQueue.firstEffect = finishedQueue.lastEffect = null;
13890
  commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
13891
  finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
13892
}
13893
13894
function commitUpdateEffects(effect, instance) {
13895
  while (effect !== null) {
13896
    var callback = effect.callback;
13897
13898
    if (callback !== null) {
13899
      effect.callback = null;
13900
      callCallback(callback, instance);
13901
    }
13902
13903
    effect = effect.nextEffect;
13904
  }
13905
}
13906
13907
var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig;
13908
function requestCurrentSuspenseConfig() {
13909
  return ReactCurrentBatchConfig.suspense;
13910
}
13911
13912
var fakeInternalInstance = {};
13913
var isArray$1 = Array.isArray; // React.Component uses a shared frozen object by default.
13914
// We'll use it to determine whether we need to initialize legacy refs.
13915
13916
var emptyRefsObject = new React.Component().refs;
13917
var didWarnAboutStateAssignmentForComponent;
13918
var didWarnAboutUninitializedState;
13919
var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
13920
var didWarnAboutLegacyLifecyclesAndDerivedState;
13921
var didWarnAboutUndefinedDerivedState;
13922
var warnOnUndefinedDerivedState;
13923
var warnOnInvalidCallback$1;
13924
var didWarnAboutDirectlyAssigningPropsToState;
13925
var didWarnAboutContextTypeAndContextTypes;
13926
var didWarnAboutInvalidateContextType;
13927
13928
{
13929
  didWarnAboutStateAssignmentForComponent = new Set();
13930
  didWarnAboutUninitializedState = new Set();
13931
  didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
13932
  didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
13933
  didWarnAboutDirectlyAssigningPropsToState = new Set();
13934
  didWarnAboutUndefinedDerivedState = new Set();
13935
  didWarnAboutContextTypeAndContextTypes = new Set();
13936
  didWarnAboutInvalidateContextType = new Set();
13937
  var didWarnOnInvalidCallback = new Set();
13938
13939
  warnOnInvalidCallback$1 = function (callback, callerName) {
13940
    if (callback === null || typeof callback === 'function') {
13941
      return;
13942
    }
13943
13944
    var key = callerName + "_" + callback;
13945
13946
    if (!didWarnOnInvalidCallback.has(key)) {
13947
      didWarnOnInvalidCallback.add(key);
13948
      warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
13949
    }
13950
  };
13951
13952
  warnOnUndefinedDerivedState = function (type, partialState) {
13953
    if (partialState === undefined) {
13954
      var componentName = getComponentName(type) || 'Component';
13955
13956
      if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
13957
        didWarnAboutUndefinedDerivedState.add(componentName);
13958
        warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
13959
      }
13960
    }
13961
  }; // This is so gross but it's at least non-critical and can be removed if
13962
  // it causes problems. This is meant to give a nicer error message for
13963
  // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
13964
  // ...)) which otherwise throws a "_processChildContext is not a function"
13965
  // exception.
13966
13967
13968
  Object.defineProperty(fakeInternalInstance, '_processChildContext', {
13969
    enumerable: false,
13970
    value: function () {
13971
      (function () {
13972
        {
13973
          {
13974
            throw ReactError(Error("_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal)."));
13975
          }
13976
        }
13977
      })();
13978
    }
13979
  });
13980
  Object.freeze(fakeInternalInstance);
13981
}
13982
13983
function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
13984
  var prevState = workInProgress.memoizedState;
13985
13986
  {
13987
    if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
13988
      // Invoke the function an extra time to help detect side-effects.
13989
      getDerivedStateFromProps(nextProps, prevState);
13990
    }
13991
  }
13992
13993
  var partialState = getDerivedStateFromProps(nextProps, prevState);
13994
13995
  {
13996
    warnOnUndefinedDerivedState(ctor, partialState);
13997
  } // Merge the partial state and the previous state.
13998
13999
14000
  var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
14001
  workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the
14002
  // base state.
14003
14004
  var updateQueue = workInProgress.updateQueue;
14005
14006
  if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
14007
    updateQueue.baseState = memoizedState;
14008
  }
14009
}
14010
var classComponentUpdater = {
14011
  isMounted: isMounted,
14012
  enqueueSetState: function (inst, payload, callback) {
14013
    var fiber = get(inst);
14014
    var currentTime = requestCurrentTime();
14015
    var suspenseConfig = requestCurrentSuspenseConfig();
14016
    var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
14017
    var update = createUpdate(expirationTime, suspenseConfig);
14018
    update.payload = payload;
14019
14020
    if (callback !== undefined && callback !== null) {
14021
      {
14022
        warnOnInvalidCallback$1(callback, 'setState');
14023
      }
14024
14025
      update.callback = callback;
14026
    }
14027
14028
    enqueueUpdate(fiber, update);
14029
    scheduleWork(fiber, expirationTime);
14030
  },
14031
  enqueueReplaceState: function (inst, payload, callback) {
14032
    var fiber = get(inst);
14033
    var currentTime = requestCurrentTime();
14034
    var suspenseConfig = requestCurrentSuspenseConfig();
14035
    var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
14036
    var update = createUpdate(expirationTime, suspenseConfig);
14037
    update.tag = ReplaceState;
14038
    update.payload = payload;
14039
14040
    if (callback !== undefined && callback !== null) {
14041
      {
14042
        warnOnInvalidCallback$1(callback, 'replaceState');
14043
      }
14044
14045
      update.callback = callback;
14046
    }
14047
14048
    enqueueUpdate(fiber, update);
14049
    scheduleWork(fiber, expirationTime);
14050
  },
14051
  enqueueForceUpdate: function (inst, callback) {
14052
    var fiber = get(inst);
14053
    var currentTime = requestCurrentTime();
14054
    var suspenseConfig = requestCurrentSuspenseConfig();
14055
    var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
14056
    var update = createUpdate(expirationTime, suspenseConfig);
14057
    update.tag = ForceUpdate;
14058
14059
    if (callback !== undefined && callback !== null) {
14060
      {
14061
        warnOnInvalidCallback$1(callback, 'forceUpdate');
14062
      }
14063
14064
      update.callback = callback;
14065
    }
14066
14067
    enqueueUpdate(fiber, update);
14068
    scheduleWork(fiber, expirationTime);
14069
  }
14070
};
14071
14072
function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
14073
  var instance = workInProgress.stateNode;
14074
14075
  if (typeof instance.shouldComponentUpdate === 'function') {
14076
    startPhaseTimer(workInProgress, 'shouldComponentUpdate');
14077
    var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
14078
    stopPhaseTimer();
14079
14080
    {
14081
      !(shouldUpdate !== undefined) ? warningWithoutStack$1(false, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentName(ctor) || 'Component') : void 0;
14082
    }
14083
14084
    return shouldUpdate;
14085
  }
14086
14087
  if (ctor.prototype && ctor.prototype.isPureReactComponent) {
14088
    return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
14089
  }
14090
14091
  return true;
14092
}
14093
14094
function checkClassInstance(workInProgress, ctor, newProps) {
14095
  var instance = workInProgress.stateNode;
14096
14097
  {
14098
    var name = getComponentName(ctor) || 'Component';
14099
    var renderPresent = instance.render;
14100
14101
    if (!renderPresent) {
14102
      if (ctor.prototype && typeof ctor.prototype.render === 'function') {
14103
        warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
14104
      } else {
14105
        warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
14106
      }
14107
    }
14108
14109
    var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
14110
    !noGetInitialStateOnES6 ? warningWithoutStack$1(false, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name) : void 0;
14111
    var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
14112
    !noGetDefaultPropsOnES6 ? warningWithoutStack$1(false, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name) : void 0;
14113
    var noInstancePropTypes = !instance.propTypes;
14114
    !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
14115
    var noInstanceContextType = !instance.contextType;
14116
    !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0;
14117
14118
    if (disableLegacyContext) {
14119
      if (ctor.childContextTypes) {
14120
        warningWithoutStack$1(false, '%s uses the legacy childContextTypes API which is no longer supported. ' + 'Use React.createContext() instead.', name);
14121
      }
14122
14123
      if (ctor.contextTypes) {
14124
        warningWithoutStack$1(false, '%s uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with static contextType instead.', name);
14125
      }
14126
    } else {
14127
      var noInstanceContextTypes = !instance.contextTypes;
14128
      !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
14129
14130
      if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
14131
        didWarnAboutContextTypeAndContextTypes.add(ctor);
14132
        warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
14133
      }
14134
    }
14135
14136
    var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
14137
    !noComponentShouldUpdate ? warningWithoutStack$1(false, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name) : void 0;
14138
14139
    if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
14140
      warningWithoutStack$1(false, '%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentName(ctor) || 'A pure component');
14141
    }
14142
14143
    var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
14144
    !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
14145
    var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
14146
    !noComponentDidReceiveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name) : void 0;
14147
    var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
14148
    !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
14149
    var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
14150
    !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
14151
    var hasMutatedProps = instance.props !== newProps;
14152
    !(instance.props === undefined || !hasMutatedProps) ? warningWithoutStack$1(false, '%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name) : void 0;
14153
    var noInstanceDefaultProps = !instance.defaultProps;
14154
    !noInstanceDefaultProps ? warningWithoutStack$1(false, 'Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name) : void 0;
14155
14156
    if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
14157
      didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
14158
      warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
14159
    }
14160
14161
    var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
14162
    !noInstanceGetDerivedStateFromProps ? warningWithoutStack$1(false, '%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name) : void 0;
14163
    var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function';
14164
    !noInstanceGetDerivedStateFromCatch ? warningWithoutStack$1(false, '%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name) : void 0;
14165
    var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function';
14166
    !noStaticGetSnapshotBeforeUpdate ? warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name) : void 0;
14167
    var _state = instance.state;
14168
14169
    if (_state && (typeof _state !== 'object' || isArray$1(_state))) {
14170
      warningWithoutStack$1(false, '%s.state: must be set to an object or null', name);
14171
    }
14172
14173
    if (typeof instance.getChildContext === 'function') {
14174
      !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
14175
    }
14176
  }
14177
}
14178
14179
function adoptClassInstance(workInProgress, instance) {
14180
  instance.updater = classComponentUpdater;
14181
  workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates
14182
14183
  set(instance, workInProgress);
14184
14185
  {
14186
    instance._reactInternalInstance = fakeInternalInstance;
14187
  }
14188
}
14189
14190
function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) {
14191
  var isLegacyContextConsumer = false;
14192
  var unmaskedContext = emptyContextObject;
14193
  var context = emptyContextObject;
14194
  var contextType = ctor.contextType;
14195
14196
  {
14197
    if ('contextType' in ctor) {
14198
      var isValid = // Allow null for conditional declaration
14199
      contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
14200
14201
      if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
14202
        didWarnAboutInvalidateContextType.add(ctor);
14203
        var addendum = '';
14204
14205
        if (contextType === undefined) {
14206
          addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
14207
        } else if (typeof contextType !== 'object') {
14208
          addendum = ' However, it is set to a ' + typeof contextType + '.';
14209
        } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
14210
          addendum = ' Did you accidentally pass the Context.Provider instead?';
14211
        } else if (contextType._context !== undefined) {
14212
          // <Context.Consumer>
14213
          addendum = ' Did you accidentally pass the Context.Consumer instead?';
14214
        } else {
14215
          addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
14216
        }
14217
14218
        warningWithoutStack$1(false, '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);
14219
      }
14220
    }
14221
  }
14222
14223
  if (typeof contextType === 'object' && contextType !== null) {
14224
    context = readContext(contextType);
14225
  } else if (!disableLegacyContext) {
14226
    unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14227
    var contextTypes = ctor.contextTypes;
14228
    isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
14229
    context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
14230
  } // Instantiate twice to help detect side-effects.
14231
14232
14233
  {
14234
    if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14235
      new ctor(props, context); // eslint-disable-line no-new
14236
    }
14237
  }
14238
14239
  var instance = new ctor(props, context);
14240
  var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
14241
  adoptClassInstance(workInProgress, instance);
14242
14243
  {
14244
    if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
14245
      var componentName = getComponentName(ctor) || 'Component';
14246
14247
      if (!didWarnAboutUninitializedState.has(componentName)) {
14248
        didWarnAboutUninitializedState.add(componentName);
14249
        warningWithoutStack$1(false, '`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
14250
      }
14251
    } // If new component APIs are defined, "unsafe" lifecycles won't be called.
14252
    // Warn about these lifecycles if they are present.
14253
    // Don't warn about react-lifecycles-compat polyfilled methods though.
14254
14255
14256
    if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
14257
      var foundWillMountName = null;
14258
      var foundWillReceivePropsName = null;
14259
      var foundWillUpdateName = null;
14260
14261
      if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
14262
        foundWillMountName = 'componentWillMount';
14263
      } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
14264
        foundWillMountName = 'UNSAFE_componentWillMount';
14265
      }
14266
14267
      if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
14268
        foundWillReceivePropsName = 'componentWillReceiveProps';
14269
      } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
14270
        foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
14271
      }
14272
14273
      if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
14274
        foundWillUpdateName = 'componentWillUpdate';
14275
      } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
14276
        foundWillUpdateName = 'UNSAFE_componentWillUpdate';
14277
      }
14278
14279
      if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
14280
        var _componentName = getComponentName(ctor) || 'Component';
14281
14282
        var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
14283
14284
        if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
14285
          didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
14286
          warningWithoutStack$1(false, 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://fb.me/react-unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n  " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n  " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n  " + foundWillUpdateName : '');
14287
        }
14288
      }
14289
    }
14290
  } // Cache unmasked context so we can avoid recreating masked context unless necessary.
14291
  // ReactFiberContext usually updates this cache but can't for newly-created instances.
14292
14293
14294
  if (isLegacyContextConsumer) {
14295
    cacheContext(workInProgress, unmaskedContext, context);
14296
  }
14297
14298
  return instance;
14299
}
14300
14301
function callComponentWillMount(workInProgress, instance) {
14302
  startPhaseTimer(workInProgress, 'componentWillMount');
14303
  var oldState = instance.state;
14304
14305
  if (typeof instance.componentWillMount === 'function') {
14306
    instance.componentWillMount();
14307
  }
14308
14309
  if (typeof instance.UNSAFE_componentWillMount === 'function') {
14310
    instance.UNSAFE_componentWillMount();
14311
  }
14312
14313
  stopPhaseTimer();
14314
14315
  if (oldState !== instance.state) {
14316
    {
14317
      warningWithoutStack$1(false, '%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentName(workInProgress.type) || 'Component');
14318
    }
14319
14320
    classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
14321
  }
14322
}
14323
14324
function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
14325
  var oldState = instance.state;
14326
  startPhaseTimer(workInProgress, 'componentWillReceiveProps');
14327
14328
  if (typeof instance.componentWillReceiveProps === 'function') {
14329
    instance.componentWillReceiveProps(newProps, nextContext);
14330
  }
14331
14332
  if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
14333
    instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
14334
  }
14335
14336
  stopPhaseTimer();
14337
14338
  if (instance.state !== oldState) {
14339
    {
14340
      var componentName = getComponentName(workInProgress.type) || 'Component';
14341
14342
      if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
14343
        didWarnAboutStateAssignmentForComponent.add(componentName);
14344
        warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
14345
      }
14346
    }
14347
14348
    classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
14349
  }
14350
} // Invokes the mount life-cycles on a previously never rendered instance.
14351
14352
14353
function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
14354
  {
14355
    checkClassInstance(workInProgress, ctor, newProps);
14356
  }
14357
14358
  var instance = workInProgress.stateNode;
14359
  instance.props = newProps;
14360
  instance.state = workInProgress.memoizedState;
14361
  instance.refs = emptyRefsObject;
14362
  var contextType = ctor.contextType;
14363
14364
  if (typeof contextType === 'object' && contextType !== null) {
14365
    instance.context = readContext(contextType);
14366
  } else if (disableLegacyContext) {
14367
    instance.context = emptyContextObject;
14368
  } else {
14369
    var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14370
    instance.context = getMaskedContext(workInProgress, unmaskedContext);
14371
  }
14372
14373
  {
14374
    if (instance.state === newProps) {
14375
      var componentName = getComponentName(ctor) || 'Component';
14376
14377
      if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
14378
        didWarnAboutDirectlyAssigningPropsToState.add(componentName);
14379
        warningWithoutStack$1(false, '%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
14380
      }
14381
    }
14382
14383
    if (workInProgress.mode & StrictMode) {
14384
      ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
14385
    }
14386
14387
    if (warnAboutDeprecatedLifecycles) {
14388
      ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
14389
    }
14390
  }
14391
14392
  var updateQueue = workInProgress.updateQueue;
14393
14394
  if (updateQueue !== null) {
14395
    processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14396
    instance.state = workInProgress.memoizedState;
14397
  }
14398
14399
  var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
14400
14401
  if (typeof getDerivedStateFromProps === 'function') {
14402
    applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
14403
    instance.state = workInProgress.memoizedState;
14404
  } // In order to support react-lifecycles-compat polyfilled components,
14405
  // Unsafe lifecycles should not be invoked for components using the new APIs.
14406
14407
14408
  if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
14409
    callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's
14410
    // process them now.
14411
14412
    updateQueue = workInProgress.updateQueue;
14413
14414
    if (updateQueue !== null) {
14415
      processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14416
      instance.state = workInProgress.memoizedState;
14417
    }
14418
  }
14419
14420
  if (typeof instance.componentDidMount === 'function') {
14421
    workInProgress.effectTag |= Update;
14422
  }
14423
}
14424
14425
function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
14426
  var instance = workInProgress.stateNode;
14427
  var oldProps = workInProgress.memoizedProps;
14428
  instance.props = oldProps;
14429
  var oldContext = instance.context;
14430
  var contextType = ctor.contextType;
14431
  var nextContext = emptyContextObject;
14432
14433
  if (typeof contextType === 'object' && contextType !== null) {
14434
    nextContext = readContext(contextType);
14435
  } else if (!disableLegacyContext) {
14436
    var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14437
    nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
14438
  }
14439
14440
  var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
14441
  var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
14442
  // ever the previously attempted to render - not the "current". However,
14443
  // during componentDidUpdate we pass the "current" props.
14444
  // In order to support react-lifecycles-compat polyfilled components,
14445
  // Unsafe lifecycles should not be invoked for components using the new APIs.
14446
14447
  if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
14448
    if (oldProps !== newProps || oldContext !== nextContext) {
14449
      callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
14450
    }
14451
  }
14452
14453
  resetHasForceUpdateBeforeProcessing();
14454
  var oldState = workInProgress.memoizedState;
14455
  var newState = instance.state = oldState;
14456
  var updateQueue = workInProgress.updateQueue;
14457
14458
  if (updateQueue !== null) {
14459
    processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14460
    newState = workInProgress.memoizedState;
14461
  }
14462
14463
  if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
14464
    // If an update was already in progress, we should schedule an Update
14465
    // effect even though we're bailing out, so that cWU/cDU are called.
14466
    if (typeof instance.componentDidMount === 'function') {
14467
      workInProgress.effectTag |= Update;
14468
    }
14469
14470
    return false;
14471
  }
14472
14473
  if (typeof getDerivedStateFromProps === 'function') {
14474
    applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
14475
    newState = workInProgress.memoizedState;
14476
  }
14477
14478
  var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
14479
14480
  if (shouldUpdate) {
14481
    // In order to support react-lifecycles-compat polyfilled components,
14482
    // Unsafe lifecycles should not be invoked for components using the new APIs.
14483
    if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
14484
      startPhaseTimer(workInProgress, 'componentWillMount');
14485
14486
      if (typeof instance.componentWillMount === 'function') {
14487
        instance.componentWillMount();
14488
      }
14489
14490
      if (typeof instance.UNSAFE_componentWillMount === 'function') {
14491
        instance.UNSAFE_componentWillMount();
14492
      }
14493
14494
      stopPhaseTimer();
14495
    }
14496
14497
    if (typeof instance.componentDidMount === 'function') {
14498
      workInProgress.effectTag |= Update;
14499
    }
14500
  } else {
14501
    // If an update was already in progress, we should schedule an Update
14502
    // effect even though we're bailing out, so that cWU/cDU are called.
14503
    if (typeof instance.componentDidMount === 'function') {
14504
      workInProgress.effectTag |= Update;
14505
    } // If shouldComponentUpdate returned false, we should still update the
14506
    // memoized state to indicate that this work can be reused.
14507
14508
14509
    workInProgress.memoizedProps = newProps;
14510
    workInProgress.memoizedState = newState;
14511
  } // Update the existing instance's state, props, and context pointers even
14512
  // if shouldComponentUpdate returns false.
14513
14514
14515
  instance.props = newProps;
14516
  instance.state = newState;
14517
  instance.context = nextContext;
14518
  return shouldUpdate;
14519
} // Invokes the update life-cycles and returns false if it shouldn't rerender.
14520
14521
14522
function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
14523
  var instance = workInProgress.stateNode;
14524
  var oldProps = workInProgress.memoizedProps;
14525
  instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
14526
  var oldContext = instance.context;
14527
  var contextType = ctor.contextType;
14528
  var nextContext = emptyContextObject;
14529
14530
  if (typeof contextType === 'object' && contextType !== null) {
14531
    nextContext = readContext(contextType);
14532
  } else if (!disableLegacyContext) {
14533
    var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14534
    nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
14535
  }
14536
14537
  var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
14538
  var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
14539
  // ever the previously attempted to render - not the "current". However,
14540
  // during componentDidUpdate we pass the "current" props.
14541
  // In order to support react-lifecycles-compat polyfilled components,
14542
  // Unsafe lifecycles should not be invoked for components using the new APIs.
14543
14544
  if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
14545
    if (oldProps !== newProps || oldContext !== nextContext) {
14546
      callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
14547
    }
14548
  }
14549
14550
  resetHasForceUpdateBeforeProcessing();
14551
  var oldState = workInProgress.memoizedState;
14552
  var newState = instance.state = oldState;
14553
  var updateQueue = workInProgress.updateQueue;
14554
14555
  if (updateQueue !== null) {
14556
    processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14557
    newState = workInProgress.memoizedState;
14558
  }
14559
14560
  if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
14561
    // If an update was already in progress, we should schedule an Update
14562
    // effect even though we're bailing out, so that cWU/cDU are called.
14563
    if (typeof instance.componentDidUpdate === 'function') {
14564
      if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14565
        workInProgress.effectTag |= Update;
14566
      }
14567
    }
14568
14569
    if (typeof instance.getSnapshotBeforeUpdate === 'function') {
14570
      if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14571
        workInProgress.effectTag |= Snapshot;
14572
      }
14573
    }
14574
14575
    return false;
14576
  }
14577
14578
  if (typeof getDerivedStateFromProps === 'function') {
14579
    applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
14580
    newState = workInProgress.memoizedState;
14581
  }
14582
14583
  var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
14584
14585
  if (shouldUpdate) {
14586
    // In order to support react-lifecycles-compat polyfilled components,
14587
    // Unsafe lifecycles should not be invoked for components using the new APIs.
14588
    if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
14589
      startPhaseTimer(workInProgress, 'componentWillUpdate');
14590
14591
      if (typeof instance.componentWillUpdate === 'function') {
14592
        instance.componentWillUpdate(newProps, newState, nextContext);
14593
      }
14594
14595
      if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
14596
        instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
14597
      }
14598
14599
      stopPhaseTimer();
14600
    }
14601
14602
    if (typeof instance.componentDidUpdate === 'function') {
14603
      workInProgress.effectTag |= Update;
14604
    }
14605
14606
    if (typeof instance.getSnapshotBeforeUpdate === 'function') {
14607
      workInProgress.effectTag |= Snapshot;
14608
    }
14609
  } else {
14610
    // If an update was already in progress, we should schedule an Update
14611
    // effect even though we're bailing out, so that cWU/cDU are called.
14612
    if (typeof instance.componentDidUpdate === 'function') {
14613
      if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14614
        workInProgress.effectTag |= Update;
14615
      }
14616
    }
14617
14618
    if (typeof instance.getSnapshotBeforeUpdate === 'function') {
14619
      if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14620
        workInProgress.effectTag |= Snapshot;
14621
      }
14622
    } // If shouldComponentUpdate returned false, we should still update the
14623
    // memoized props/state to indicate that this work can be reused.
14624
14625
14626
    workInProgress.memoizedProps = newProps;
14627
    workInProgress.memoizedState = newState;
14628
  } // Update the existing instance's state, props, and context pointers even
14629
  // if shouldComponentUpdate returns false.
14630
14631
14632
  instance.props = newProps;
14633
  instance.state = newState;
14634
  instance.context = nextContext;
14635
  return shouldUpdate;
14636
}
14637
14638
var didWarnAboutMaps;
14639
var didWarnAboutGenerators;
14640
var didWarnAboutStringRefs;
14641
var ownerHasKeyUseWarning;
14642
var ownerHasFunctionTypeWarning;
14643
14644
var warnForMissingKey = function (child) {};
14645
14646
{
14647
  didWarnAboutMaps = false;
14648
  didWarnAboutGenerators = false;
14649
  didWarnAboutStringRefs = {};
14650
  /**
14651
   * Warn if there's no key explicitly set on dynamic arrays of children or
14652
   * object keys are not valid. This allows us to keep track of children between
14653
   * updates.
14654
   */
14655
14656
  ownerHasKeyUseWarning = {};
14657
  ownerHasFunctionTypeWarning = {};
14658
14659
  warnForMissingKey = function (child) {
14660
    if (child === null || typeof child !== 'object') {
14661
      return;
14662
    }
14663
14664
    if (!child._store || child._store.validated || child.key != null) {
14665
      return;
14666
    }
14667
14668
    (function () {
14669
      if (!(typeof child._store === 'object')) {
14670
        {
14671
          throw ReactError(Error("React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue."));
14672
        }
14673
      }
14674
    })();
14675
14676
    child._store.validated = true;
14677
    var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
14678
14679
    if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
14680
      return;
14681
    }
14682
14683
    ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
14684
    warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
14685
  };
14686
}
14687
14688
var isArray = Array.isArray;
14689
14690
function coerceRef(returnFiber, current$$1, element) {
14691
  var mixedRef = element.ref;
14692
14693
  if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
14694
    {
14695
      // TODO: Clean this up once we turn on the string ref warning for
14696
      // everyone, because the strict mode case will no longer be relevant
14697
      if (returnFiber.mode & StrictMode || warnAboutStringRefs) {
14698
        var componentName = getComponentName(returnFiber.type) || 'Component';
14699
14700
        if (!didWarnAboutStringRefs[componentName]) {
14701
          if (warnAboutStringRefs) {
14702
            warningWithoutStack$1(false, 'Component "%s" contains the string ref "%s". Support for string refs ' + 'will be removed in a future major release. We recommend using ' + 'useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref%s', componentName, mixedRef, getStackByFiberInDevAndProd(returnFiber));
14703
          } else {
14704
            warningWithoutStack$1(false, 'A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref%s', mixedRef, getStackByFiberInDevAndProd(returnFiber));
14705
          }
14706
14707
          didWarnAboutStringRefs[componentName] = true;
14708
        }
14709
      }
14710
    }
14711
14712
    if (element._owner) {
14713
      var owner = element._owner;
14714
      var inst;
14715
14716
      if (owner) {
14717
        var ownerFiber = owner;
14718
14719
        (function () {
14720
          if (!(ownerFiber.tag === ClassComponent)) {
14721
            {
14722
              throw ReactError(Error("Function components cannot have refs. Did you mean to use React.forwardRef()?"));
14723
            }
14724
          }
14725
        })();
14726
14727
        inst = ownerFiber.stateNode;
14728
      }
14729
14730
      (function () {
14731
        if (!inst) {
14732
          {
14733
            throw ReactError(Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a bug in React. Please file an issue."));
14734
          }
14735
        }
14736
      })();
14737
14738
      var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref
14739
14740
      if (current$$1 !== null && current$$1.ref !== null && typeof current$$1.ref === 'function' && current$$1.ref._stringRef === stringRef) {
14741
        return current$$1.ref;
14742
      }
14743
14744
      var ref = function (value) {
14745
        var refs = inst.refs;
14746
14747
        if (refs === emptyRefsObject) {
14748
          // This is a lazy pooled frozen object, so we need to initialize.
14749
          refs = inst.refs = {};
14750
        }
14751
14752
        if (value === null) {
14753
          delete refs[stringRef];
14754
        } else {
14755
          refs[stringRef] = value;
14756
        }
14757
      };
14758
14759
      ref._stringRef = stringRef;
14760
      return ref;
14761
    } else {
14762
      (function () {
14763
        if (!(typeof mixedRef === 'string')) {
14764
          {
14765
            throw ReactError(Error("Expected ref to be a function, a string, an object returned by React.createRef(), or null."));
14766
          }
14767
        }
14768
      })();
14769
14770
      (function () {
14771
        if (!element._owner) {
14772
          {
14773
            throw ReactError(Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information."));
14774
          }
14775
        }
14776
      })();
14777
    }
14778
  }
14779
14780
  return mixedRef;
14781
}
14782
14783
function throwOnInvalidObjectType(returnFiber, newChild) {
14784
  if (returnFiber.type !== 'textarea') {
14785
    var addendum = '';
14786
14787
    {
14788
      addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
14789
    }
14790
14791
    (function () {
14792
      {
14793
        {
14794
          throw ReactError(Error("Objects are not valid as a React child (found: " + (Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild) + ")." + addendum));
14795
        }
14796
      }
14797
    })();
14798
  }
14799
}
14800
14801
function warnOnFunctionType() {
14802
  var currentComponentErrorInfo = 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.' + getCurrentFiberStackInDev();
14803
14804
  if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
14805
    return;
14806
  }
14807
14808
  ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
14809
  warning$1(false, 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
14810
} // This wrapper function exists because I expect to clone the code in each path
14811
// to be able to optimize each path individually by branching early. This needs
14812
// a compiler or we can do it manually. Helpers that don't need this branching
14813
// live outside of this function.
14814
14815
14816
function ChildReconciler(shouldTrackSideEffects) {
14817
  function deleteChild(returnFiber, childToDelete) {
14818
    if (!shouldTrackSideEffects) {
14819
      // Noop.
14820
      return;
14821
    } // Deletions are added in reversed order so we add it to the front.
14822
    // At this point, the return fiber's effect list is empty except for
14823
    // deletions, so we can just append the deletion to the list. The remaining
14824
    // effects aren't added until the complete phase. Once we implement
14825
    // resuming, this may not be true.
14826
14827
14828
    var last = returnFiber.lastEffect;
14829
14830
    if (last !== null) {
14831
      last.nextEffect = childToDelete;
14832
      returnFiber.lastEffect = childToDelete;
14833
    } else {
14834
      returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
14835
    }
14836
14837
    childToDelete.nextEffect = null;
14838
    childToDelete.effectTag = Deletion;
14839
  }
14840
14841
  function deleteRemainingChildren(returnFiber, currentFirstChild) {
14842
    if (!shouldTrackSideEffects) {
14843
      // Noop.
14844
      return null;
14845
    } // TODO: For the shouldClone case, this could be micro-optimized a bit by
14846
    // assuming that after the first child we've already added everything.
14847
14848
14849
    var childToDelete = currentFirstChild;
14850
14851
    while (childToDelete !== null) {
14852
      deleteChild(returnFiber, childToDelete);
14853
      childToDelete = childToDelete.sibling;
14854
    }
14855
14856
    return null;
14857
  }
14858
14859
  function mapRemainingChildren(returnFiber, currentFirstChild) {
14860
    // Add the remaining children to a temporary map so that we can find them by
14861
    // keys quickly. Implicit (null) keys get added to this set with their index
14862
    // instead.
14863
    var existingChildren = new Map();
14864
    var existingChild = currentFirstChild;
14865
14866
    while (existingChild !== null) {
14867
      if (existingChild.key !== null) {
14868
        existingChildren.set(existingChild.key, existingChild);
14869
      } else {
14870
        existingChildren.set(existingChild.index, existingChild);
14871
      }
14872
14873
      existingChild = existingChild.sibling;
14874
    }
14875
14876
    return existingChildren;
14877
  }
14878
14879
  function useFiber(fiber, pendingProps, expirationTime) {
14880
    // We currently set sibling to null and index to 0 here because it is easy
14881
    // to forget to do before returning it. E.g. for the single child case.
14882
    var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
14883
    clone.index = 0;
14884
    clone.sibling = null;
14885
    return clone;
14886
  }
14887
14888
  function placeChild(newFiber, lastPlacedIndex, newIndex) {
14889
    newFiber.index = newIndex;
14890
14891
    if (!shouldTrackSideEffects) {
14892
      // Noop.
14893
      return lastPlacedIndex;
14894
    }
14895
14896
    var current$$1 = newFiber.alternate;
14897
14898
    if (current$$1 !== null) {
14899
      var oldIndex = current$$1.index;
14900
14901
      if (oldIndex < lastPlacedIndex) {
14902
        // This is a move.
14903
        newFiber.effectTag = Placement;
14904
        return lastPlacedIndex;
14905
      } else {
14906
        // This item can stay in place.
14907
        return oldIndex;
14908
      }
14909
    } else {
14910
      // This is an insertion.
14911
      newFiber.effectTag = Placement;
14912
      return lastPlacedIndex;
14913
    }
14914
  }
14915
14916
  function placeSingleChild(newFiber) {
14917
    // This is simpler for the single child case. We only need to do a
14918
    // placement for inserting new children.
14919
    if (shouldTrackSideEffects && newFiber.alternate === null) {
14920
      newFiber.effectTag = Placement;
14921
    }
14922
14923
    return newFiber;
14924
  }
14925
14926
  function updateTextNode(returnFiber, current$$1, textContent, expirationTime) {
14927
    if (current$$1 === null || current$$1.tag !== HostText) {
14928
      // Insert
14929
      var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
14930
      created.return = returnFiber;
14931
      return created;
14932
    } else {
14933
      // Update
14934
      var existing = useFiber(current$$1, textContent, expirationTime);
14935
      existing.return = returnFiber;
14936
      return existing;
14937
    }
14938
  }
14939
14940
  function updateElement(returnFiber, current$$1, element, expirationTime) {
14941
    if (current$$1 !== null && (current$$1.elementType === element.type || ( // Keep this check inline so it only runs on the false path:
14942
    isCompatibleFamilyForHotReloading(current$$1, element)))) {
14943
      // Move based on index
14944
      var existing = useFiber(current$$1, element.props, expirationTime);
14945
      existing.ref = coerceRef(returnFiber, current$$1, element);
14946
      existing.return = returnFiber;
14947
14948
      {
14949
        existing._debugSource = element._source;
14950
        existing._debugOwner = element._owner;
14951
      }
14952
14953
      return existing;
14954
    } else {
14955
      // Insert
14956
      var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
14957
      created.ref = coerceRef(returnFiber, current$$1, element);
14958
      created.return = returnFiber;
14959
      return created;
14960
    }
14961
  }
14962
14963
  function updatePortal(returnFiber, current$$1, portal, expirationTime) {
14964
    if (current$$1 === null || current$$1.tag !== HostPortal || current$$1.stateNode.containerInfo !== portal.containerInfo || current$$1.stateNode.implementation !== portal.implementation) {
14965
      // Insert
14966
      var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
14967
      created.return = returnFiber;
14968
      return created;
14969
    } else {
14970
      // Update
14971
      var existing = useFiber(current$$1, portal.children || [], expirationTime);
14972
      existing.return = returnFiber;
14973
      return existing;
14974
    }
14975
  }
14976
14977
  function updateFragment(returnFiber, current$$1, fragment, expirationTime, key) {
14978
    if (current$$1 === null || current$$1.tag !== Fragment) {
14979
      // Insert
14980
      var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
14981
      created.return = returnFiber;
14982
      return created;
14983
    } else {
14984
      // Update
14985
      var existing = useFiber(current$$1, fragment, expirationTime);
14986
      existing.return = returnFiber;
14987
      return existing;
14988
    }
14989
  }
14990
14991
  function createChild(returnFiber, newChild, expirationTime) {
14992
    if (typeof newChild === 'string' || typeof newChild === 'number') {
14993
      // Text nodes don't have keys. If the previous node is implicitly keyed
14994
      // we can continue to replace it without aborting even if it is not a text
14995
      // node.
14996
      var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
14997
      created.return = returnFiber;
14998
      return created;
14999
    }
15000
15001
    if (typeof newChild === 'object' && newChild !== null) {
15002
      switch (newChild.$$typeof) {
15003
        case REACT_ELEMENT_TYPE:
15004
          {
15005
            var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
15006
15007
            _created.ref = coerceRef(returnFiber, null, newChild);
15008
            _created.return = returnFiber;
15009
            return _created;
15010
          }
15011
15012
        case REACT_PORTAL_TYPE:
15013
          {
15014
            var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
15015
15016
            _created2.return = returnFiber;
15017
            return _created2;
15018
          }
15019
      }
15020
15021
      if (isArray(newChild) || getIteratorFn(newChild)) {
15022
        var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
15023
15024
        _created3.return = returnFiber;
15025
        return _created3;
15026
      }
15027
15028
      throwOnInvalidObjectType(returnFiber, newChild);
15029
    }
15030
15031
    {
15032
      if (typeof newChild === 'function') {
15033
        warnOnFunctionType();
15034
      }
15035
    }
15036
15037
    return null;
15038
  }
15039
15040
  function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
15041
    // Update the fiber if the keys match, otherwise return null.
15042
    var key = oldFiber !== null ? oldFiber.key : null;
15043
15044
    if (typeof newChild === 'string' || typeof newChild === 'number') {
15045
      // Text nodes don't have keys. If the previous node is implicitly keyed
15046
      // we can continue to replace it without aborting even if it is not a text
15047
      // node.
15048
      if (key !== null) {
15049
        return null;
15050
      }
15051
15052
      return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
15053
    }
15054
15055
    if (typeof newChild === 'object' && newChild !== null) {
15056
      switch (newChild.$$typeof) {
15057
        case REACT_ELEMENT_TYPE:
15058
          {
15059
            if (newChild.key === key) {
15060
              if (newChild.type === REACT_FRAGMENT_TYPE) {
15061
                return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
15062
              }
15063
15064
              return updateElement(returnFiber, oldFiber, newChild, expirationTime);
15065
            } else {
15066
              return null;
15067
            }
15068
          }
15069
15070
        case REACT_PORTAL_TYPE:
15071
          {
15072
            if (newChild.key === key) {
15073
              return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
15074
            } else {
15075
              return null;
15076
            }
15077
          }
15078
      }
15079
15080
      if (isArray(newChild) || getIteratorFn(newChild)) {
15081
        if (key !== null) {
15082
          return null;
15083
        }
15084
15085
        return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
15086
      }
15087
15088
      throwOnInvalidObjectType(returnFiber, newChild);
15089
    }
15090
15091
    {
15092
      if (typeof newChild === 'function') {
15093
        warnOnFunctionType();
15094
      }
15095
    }
15096
15097
    return null;
15098
  }
15099
15100
  function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
15101
    if (typeof newChild === 'string' || typeof newChild === 'number') {
15102
      // Text nodes don't have keys, so we neither have to check the old nor
15103
      // new node for the key. If both are text nodes, they match.
15104
      var matchedFiber = existingChildren.get(newIdx) || null;
15105
      return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
15106
    }
15107
15108
    if (typeof newChild === 'object' && newChild !== null) {
15109
      switch (newChild.$$typeof) {
15110
        case REACT_ELEMENT_TYPE:
15111
          {
15112
            var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
15113
15114
            if (newChild.type === REACT_FRAGMENT_TYPE) {
15115
              return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
15116
            }
15117
15118
            return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
15119
          }
15120
15121
        case REACT_PORTAL_TYPE:
15122
          {
15123
            var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
15124
15125
            return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
15126
          }
15127
      }
15128
15129
      if (isArray(newChild) || getIteratorFn(newChild)) {
15130
        var _matchedFiber3 = existingChildren.get(newIdx) || null;
15131
15132
        return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
15133
      }
15134
15135
      throwOnInvalidObjectType(returnFiber, newChild);
15136
    }
15137
15138
    {
15139
      if (typeof newChild === 'function') {
15140
        warnOnFunctionType();
15141
      }
15142
    }
15143
15144
    return null;
15145
  }
15146
  /**
15147
   * Warns if there is a duplicate or missing key
15148
   */
15149
15150
15151
  function warnOnInvalidKey(child, knownKeys) {
15152
    {
15153
      if (typeof child !== 'object' || child === null) {
15154
        return knownKeys;
15155
      }
15156
15157
      switch (child.$$typeof) {
15158
        case REACT_ELEMENT_TYPE:
15159
        case REACT_PORTAL_TYPE:
15160
          warnForMissingKey(child);
15161
          var key = child.key;
15162
15163
          if (typeof key !== 'string') {
15164
            break;
15165
          }
15166
15167
          if (knownKeys === null) {
15168
            knownKeys = new Set();
15169
            knownKeys.add(key);
15170
            break;
15171
          }
15172
15173
          if (!knownKeys.has(key)) {
15174
            knownKeys.add(key);
15175
            break;
15176
          }
15177
15178
          warning$1(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key);
15179
          break;
15180
15181
        default:
15182
          break;
15183
      }
15184
    }
15185
15186
    return knownKeys;
15187
  }
15188
15189
  function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
15190
    // This algorithm can't optimize by searching from both ends since we
15191
    // don't have backpointers on fibers. I'm trying to see how far we can get
15192
    // with that model. If it ends up not being worth the tradeoffs, we can
15193
    // add it later.
15194
    // Even with a two ended optimization, we'd want to optimize for the case
15195
    // where there are few changes and brute force the comparison instead of
15196
    // going for the Map. It'd like to explore hitting that path first in
15197
    // forward-only mode and only go for the Map once we notice that we need
15198
    // lots of look ahead. This doesn't handle reversal as well as two ended
15199
    // search but that's unusual. Besides, for the two ended optimization to
15200
    // work on Iterables, we'd need to copy the whole set.
15201
    // In this first iteration, we'll just live with hitting the bad case
15202
    // (adding everything to a Map) in for every insert/move.
15203
    // If you change this code, also update reconcileChildrenIterator() which
15204
    // uses the same algorithm.
15205
    {
15206
      // First, validate keys.
15207
      var knownKeys = null;
15208
15209
      for (var i = 0; i < newChildren.length; i++) {
15210
        var child = newChildren[i];
15211
        knownKeys = warnOnInvalidKey(child, knownKeys);
15212
      }
15213
    }
15214
15215
    var resultingFirstChild = null;
15216
    var previousNewFiber = null;
15217
    var oldFiber = currentFirstChild;
15218
    var lastPlacedIndex = 0;
15219
    var newIdx = 0;
15220
    var nextOldFiber = null;
15221
15222
    for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
15223
      if (oldFiber.index > newIdx) {
15224
        nextOldFiber = oldFiber;
15225
        oldFiber = null;
15226
      } else {
15227
        nextOldFiber = oldFiber.sibling;
15228
      }
15229
15230
      var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
15231
15232
      if (newFiber === null) {
15233
        // TODO: This breaks on empty slots like null children. That's
15234
        // unfortunate because it triggers the slow path all the time. We need
15235
        // a better way to communicate whether this was a miss or null,
15236
        // boolean, undefined, etc.
15237
        if (oldFiber === null) {
15238
          oldFiber = nextOldFiber;
15239
        }
15240
15241
        break;
15242
      }
15243
15244
      if (shouldTrackSideEffects) {
15245
        if (oldFiber && newFiber.alternate === null) {
15246
          // We matched the slot, but we didn't reuse the existing fiber, so we
15247
          // need to delete the existing child.
15248
          deleteChild(returnFiber, oldFiber);
15249
        }
15250
      }
15251
15252
      lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
15253
15254
      if (previousNewFiber === null) {
15255
        // TODO: Move out of the loop. This only happens for the first run.
15256
        resultingFirstChild = newFiber;
15257
      } else {
15258
        // TODO: Defer siblings if we're not at the right index for this slot.
15259
        // I.e. if we had null values before, then we want to defer this
15260
        // for each null value. However, we also don't want to call updateSlot
15261
        // with the previous one.
15262
        previousNewFiber.sibling = newFiber;
15263
      }
15264
15265
      previousNewFiber = newFiber;
15266
      oldFiber = nextOldFiber;
15267
    }
15268
15269
    if (newIdx === newChildren.length) {
15270
      // We've reached the end of the new children. We can delete the rest.
15271
      deleteRemainingChildren(returnFiber, oldFiber);
15272
      return resultingFirstChild;
15273
    }
15274
15275
    if (oldFiber === null) {
15276
      // If we don't have any more existing children we can choose a fast path
15277
      // since the rest will all be insertions.
15278
      for (; newIdx < newChildren.length; newIdx++) {
15279
        var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
15280
15281
        if (_newFiber === null) {
15282
          continue;
15283
        }
15284
15285
        lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
15286
15287
        if (previousNewFiber === null) {
15288
          // TODO: Move out of the loop. This only happens for the first run.
15289
          resultingFirstChild = _newFiber;
15290
        } else {
15291
          previousNewFiber.sibling = _newFiber;
15292
        }
15293
15294
        previousNewFiber = _newFiber;
15295
      }
15296
15297
      return resultingFirstChild;
15298
    } // Add all children to a key map for quick lookups.
15299
15300
15301
    var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
15302
15303
    for (; newIdx < newChildren.length; newIdx++) {
15304
      var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
15305
15306
      if (_newFiber2 !== null) {
15307
        if (shouldTrackSideEffects) {
15308
          if (_newFiber2.alternate !== null) {
15309
            // The new fiber is a work in progress, but if there exists a
15310
            // current, that means that we reused the fiber. We need to delete
15311
            // it from the child list so that we don't add it to the deletion
15312
            // list.
15313
            existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
15314
          }
15315
        }
15316
15317
        lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
15318
15319
        if (previousNewFiber === null) {
15320
          resultingFirstChild = _newFiber2;
15321
        } else {
15322
          previousNewFiber.sibling = _newFiber2;
15323
        }
15324
15325
        previousNewFiber = _newFiber2;
15326
      }
15327
    }
15328
15329
    if (shouldTrackSideEffects) {
15330
      // Any existing children that weren't consumed above were deleted. We need
15331
      // to add them to the deletion list.
15332
      existingChildren.forEach(function (child) {
15333
        return deleteChild(returnFiber, child);
15334
      });
15335
    }
15336
15337
    return resultingFirstChild;
15338
  }
15339
15340
  function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
15341
    // This is the same implementation as reconcileChildrenArray(),
15342
    // but using the iterator instead.
15343
    var iteratorFn = getIteratorFn(newChildrenIterable);
15344
15345
    (function () {
15346
      if (!(typeof iteratorFn === 'function')) {
15347
        {
15348
          throw ReactError(Error("An object is not an iterable. This error is likely caused by a bug in React. Please file an issue."));
15349
        }
15350
      }
15351
    })();
15352
15353
    {
15354
      // We don't support rendering Generators because it's a mutation.
15355
      // See https://github.com/facebook/react/issues/12995
15356
      if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
15357
      newChildrenIterable[Symbol.toStringTag] === 'Generator') {
15358
        !didWarnAboutGenerators ? warning$1(false, 'Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.') : void 0;
15359
        didWarnAboutGenerators = true;
15360
      } // Warn about using Maps as children
15361
15362
15363
      if (newChildrenIterable.entries === iteratorFn) {
15364
        !didWarnAboutMaps ? warning$1(false, 'Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.') : void 0;
15365
        didWarnAboutMaps = true;
15366
      } // First, validate keys.
15367
      // We'll get a different iterator later for the main pass.
15368
15369
15370
      var _newChildren = iteratorFn.call(newChildrenIterable);
15371
15372
      if (_newChildren) {
15373
        var knownKeys = null;
15374
15375
        var _step = _newChildren.next();
15376
15377
        for (; !_step.done; _step = _newChildren.next()) {
15378
          var child = _step.value;
15379
          knownKeys = warnOnInvalidKey(child, knownKeys);
15380
        }
15381
      }
15382
    }
15383
15384
    var newChildren = iteratorFn.call(newChildrenIterable);
15385
15386
    (function () {
15387
      if (!(newChildren != null)) {
15388
        {
15389
          throw ReactError(Error("An iterable object provided no iterator."));
15390
        }
15391
      }
15392
    })();
15393
15394
    var resultingFirstChild = null;
15395
    var previousNewFiber = null;
15396
    var oldFiber = currentFirstChild;
15397
    var lastPlacedIndex = 0;
15398
    var newIdx = 0;
15399
    var nextOldFiber = null;
15400
    var step = newChildren.next();
15401
15402
    for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
15403
      if (oldFiber.index > newIdx) {
15404
        nextOldFiber = oldFiber;
15405
        oldFiber = null;
15406
      } else {
15407
        nextOldFiber = oldFiber.sibling;
15408
      }
15409
15410
      var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
15411
15412
      if (newFiber === null) {
15413
        // TODO: This breaks on empty slots like null children. That's
15414
        // unfortunate because it triggers the slow path all the time. We need
15415
        // a better way to communicate whether this was a miss or null,
15416
        // boolean, undefined, etc.
15417
        if (oldFiber === null) {
15418
          oldFiber = nextOldFiber;
15419
        }
15420
15421
        break;
15422
      }
15423
15424
      if (shouldTrackSideEffects) {
15425
        if (oldFiber && newFiber.alternate === null) {
15426
          // We matched the slot, but we didn't reuse the existing fiber, so we
15427
          // need to delete the existing child.
15428
          deleteChild(returnFiber, oldFiber);
15429
        }
15430
      }
15431
15432
      lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
15433
15434
      if (previousNewFiber === null) {
15435
        // TODO: Move out of the loop. This only happens for the first run.
15436
        resultingFirstChild = newFiber;
15437
      } else {
15438
        // TODO: Defer siblings if we're not at the right index for this slot.
15439
        // I.e. if we had null values before, then we want to defer this
15440
        // for each null value. However, we also don't want to call updateSlot
15441
        // with the previous one.
15442
        previousNewFiber.sibling = newFiber;
15443
      }
15444
15445
      previousNewFiber = newFiber;
15446
      oldFiber = nextOldFiber;
15447
    }
15448
15449
    if (step.done) {
15450
      // We've reached the end of the new children. We can delete the rest.
15451
      deleteRemainingChildren(returnFiber, oldFiber);
15452
      return resultingFirstChild;
15453
    }
15454
15455
    if (oldFiber === null) {
15456
      // If we don't have any more existing children we can choose a fast path
15457
      // since the rest will all be insertions.
15458
      for (; !step.done; newIdx++, step = newChildren.next()) {
15459
        var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
15460
15461
        if (_newFiber3 === null) {
15462
          continue;
15463
        }
15464
15465
        lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
15466
15467
        if (previousNewFiber === null) {
15468
          // TODO: Move out of the loop. This only happens for the first run.
15469
          resultingFirstChild = _newFiber3;
15470
        } else {
15471
          previousNewFiber.sibling = _newFiber3;
15472
        }
15473
15474
        previousNewFiber = _newFiber3;
15475
      }
15476
15477
      return resultingFirstChild;
15478
    } // Add all children to a key map for quick lookups.
15479
15480
15481
    var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
15482
15483
    for (; !step.done; newIdx++, step = newChildren.next()) {
15484
      var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
15485
15486
      if (_newFiber4 !== null) {
15487
        if (shouldTrackSideEffects) {
15488
          if (_newFiber4.alternate !== null) {
15489
            // The new fiber is a work in progress, but if there exists a
15490
            // current, that means that we reused the fiber. We need to delete
15491
            // it from the child list so that we don't add it to the deletion
15492
            // list.
15493
            existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
15494
          }
15495
        }
15496
15497
        lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
15498
15499
        if (previousNewFiber === null) {
15500
          resultingFirstChild = _newFiber4;
15501
        } else {
15502
          previousNewFiber.sibling = _newFiber4;
15503
        }
15504
15505
        previousNewFiber = _newFiber4;
15506
      }
15507
    }
15508
15509
    if (shouldTrackSideEffects) {
15510
      // Any existing children that weren't consumed above were deleted. We need
15511
      // to add them to the deletion list.
15512
      existingChildren.forEach(function (child) {
15513
        return deleteChild(returnFiber, child);
15514
      });
15515
    }
15516
15517
    return resultingFirstChild;
15518
  }
15519
15520
  function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
15521
    // There's no need to check for keys on text nodes since we don't have a
15522
    // way to define them.
15523
    if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
15524
      // We already have an existing node so let's just update it and delete
15525
      // the rest.
15526
      deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
15527
      var existing = useFiber(currentFirstChild, textContent, expirationTime);
15528
      existing.return = returnFiber;
15529
      return existing;
15530
    } // The existing first child is not a text node so we need to create one
15531
    // and delete the existing ones.
15532
15533
15534
    deleteRemainingChildren(returnFiber, currentFirstChild);
15535
    var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
15536
    created.return = returnFiber;
15537
    return created;
15538
  }
15539
15540
  function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
15541
    var key = element.key;
15542
    var child = currentFirstChild;
15543
15544
    while (child !== null) {
15545
      // TODO: If key === null and child.key === null, then this only applies to
15546
      // the first item in the list.
15547
      if (child.key === key) {
15548
        if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.elementType === element.type || ( // Keep this check inline so it only runs on the false path:
15549
        isCompatibleFamilyForHotReloading(child, element))) {
15550
          deleteRemainingChildren(returnFiber, child.sibling);
15551
          var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
15552
          existing.ref = coerceRef(returnFiber, child, element);
15553
          existing.return = returnFiber;
15554
15555
          {
15556
            existing._debugSource = element._source;
15557
            existing._debugOwner = element._owner;
15558
          }
15559
15560
          return existing;
15561
        } else {
15562
          deleteRemainingChildren(returnFiber, child);
15563
          break;
15564
        }
15565
      } else {
15566
        deleteChild(returnFiber, child);
15567
      }
15568
15569
      child = child.sibling;
15570
    }
15571
15572
    if (element.type === REACT_FRAGMENT_TYPE) {
15573
      var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
15574
      created.return = returnFiber;
15575
      return created;
15576
    } else {
15577
      var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
15578
15579
      _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
15580
      _created4.return = returnFiber;
15581
      return _created4;
15582
    }
15583
  }
15584
15585
  function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
15586
    var key = portal.key;
15587
    var child = currentFirstChild;
15588
15589
    while (child !== null) {
15590
      // TODO: If key === null and child.key === null, then this only applies to
15591
      // the first item in the list.
15592
      if (child.key === key) {
15593
        if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
15594
          deleteRemainingChildren(returnFiber, child.sibling);
15595
          var existing = useFiber(child, portal.children || [], expirationTime);
15596
          existing.return = returnFiber;
15597
          return existing;
15598
        } else {
15599
          deleteRemainingChildren(returnFiber, child);
15600
          break;
15601
        }
15602
      } else {
15603
        deleteChild(returnFiber, child);
15604
      }
15605
15606
      child = child.sibling;
15607
    }
15608
15609
    var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
15610
    created.return = returnFiber;
15611
    return created;
15612
  } // This API will tag the children with the side-effect of the reconciliation
15613
  // itself. They will be added to the side-effect list as we pass through the
15614
  // children and the parent.
15615
15616
15617
  function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
15618
    // This function is not recursive.
15619
    // If the top level item is an array, we treat it as a set of children,
15620
    // not as a fragment. Nested arrays on the other hand will be treated as
15621
    // fragment nodes. Recursion happens at the normal flow.
15622
    // Handle top level unkeyed fragments as if they were arrays.
15623
    // This leads to an ambiguity between <>{[...]}</> and <>...</>.
15624
    // We treat the ambiguous cases above the same.
15625
    var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
15626
15627
    if (isUnkeyedTopLevelFragment) {
15628
      newChild = newChild.props.children;
15629
    } // Handle object types
15630
15631
15632
    var isObject = typeof newChild === 'object' && newChild !== null;
15633
15634
    if (isObject) {
15635
      switch (newChild.$$typeof) {
15636
        case REACT_ELEMENT_TYPE:
15637
          return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
15638
15639
        case REACT_PORTAL_TYPE:
15640
          return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
15641
      }
15642
    }
15643
15644
    if (typeof newChild === 'string' || typeof newChild === 'number') {
15645
      return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
15646
    }
15647
15648
    if (isArray(newChild)) {
15649
      return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
15650
    }
15651
15652
    if (getIteratorFn(newChild)) {
15653
      return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
15654
    }
15655
15656
    if (isObject) {
15657
      throwOnInvalidObjectType(returnFiber, newChild);
15658
    }
15659
15660
    {
15661
      if (typeof newChild === 'function') {
15662
        warnOnFunctionType();
15663
      }
15664
    }
15665
15666
    if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
15667
      // If the new child is undefined, and the return fiber is a composite
15668
      // component, throw an error. If Fiber return types are disabled,
15669
      // we already threw above.
15670
      switch (returnFiber.tag) {
15671
        case ClassComponent:
15672
          {
15673
            {
15674
              var instance = returnFiber.stateNode;
15675
15676
              if (instance.render._isMockFunction) {
15677
                // We allow auto-mocks to proceed as if they're returning null.
15678
                break;
15679
              }
15680
            }
15681
          }
15682
        // Intentionally fall through to the next case, which handles both
15683
        // functions and classes
15684
        // eslint-disable-next-lined no-fallthrough
15685
15686
        case FunctionComponent:
15687
          {
15688
            var Component = returnFiber.type;
15689
15690
            (function () {
15691
              {
15692
                {
15693
                  throw ReactError(Error((Component.displayName || Component.name || 'Component') + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null."));
15694
                }
15695
              }
15696
            })();
15697
          }
15698
      }
15699
    } // Remaining cases are all treated as empty.
15700
15701
15702
    return deleteRemainingChildren(returnFiber, currentFirstChild);
15703
  }
15704
15705
  return reconcileChildFibers;
15706
}
15707
15708
var reconcileChildFibers = ChildReconciler(true);
15709
var mountChildFibers = ChildReconciler(false);
15710
function cloneChildFibers(current$$1, workInProgress) {
15711
  (function () {
15712
    if (!(current$$1 === null || workInProgress.child === current$$1.child)) {
15713
      {
15714
        throw ReactError(Error("Resuming work not yet implemented."));
15715
      }
15716
    }
15717
  })();
15718
15719
  if (workInProgress.child === null) {
15720
    return;
15721
  }
15722
15723
  var currentChild = workInProgress.child;
15724
  var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
15725
  workInProgress.child = newChild;
15726
  newChild.return = workInProgress;
15727
15728
  while (currentChild.sibling !== null) {
15729
    currentChild = currentChild.sibling;
15730
    newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
15731
    newChild.return = workInProgress;
15732
  }
15733
15734
  newChild.sibling = null;
15735
} // Reset a workInProgress child set to prepare it for a second pass.
15736
15737
function resetChildFibers(workInProgress, renderExpirationTime) {
15738
  var child = workInProgress.child;
15739
15740
  while (child !== null) {
15741
    resetWorkInProgress(child, renderExpirationTime);
15742
    child = child.sibling;
15743
  }
15744
}
15745
15746
var NO_CONTEXT = {};
15747
var contextStackCursor$1 = createCursor(NO_CONTEXT);
15748
var contextFiberStackCursor = createCursor(NO_CONTEXT);
15749
var rootInstanceStackCursor = createCursor(NO_CONTEXT);
15750
15751
function requiredContext(c) {
15752
  (function () {
15753
    if (!(c !== NO_CONTEXT)) {
15754
      {
15755
        throw ReactError(Error("Expected host context to exist. This error is likely caused by a bug in React. Please file an issue."));
15756
      }
15757
    }
15758
  })();
15759
15760
  return c;
15761
}
15762
15763
function getRootHostContainer() {
15764
  var rootInstance = requiredContext(rootInstanceStackCursor.current);
15765
  return rootInstance;
15766
}
15767
15768
function pushHostContainer(fiber, nextRootInstance) {
15769
  // Push current root instance onto the stack;
15770
  // This allows us to reset root when portals are popped.
15771
  push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.
15772
  // This enables us to pop only Fibers that provide unique contexts.
15773
15774
  push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.
15775
  // However, we can't just call getRootHostContext() and push it because
15776
  // we'd have a different number of entries on the stack depending on
15777
  // whether getRootHostContext() throws somewhere in renderer code or not.
15778
  // So we push an empty value first. This lets us safely unwind on errors.
15779
15780
  push(contextStackCursor$1, NO_CONTEXT, fiber);
15781
  var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it.
15782
15783
  pop(contextStackCursor$1, fiber);
15784
  push(contextStackCursor$1, nextRootContext, fiber);
15785
}
15786
15787
function popHostContainer(fiber) {
15788
  pop(contextStackCursor$1, fiber);
15789
  pop(contextFiberStackCursor, fiber);
15790
  pop(rootInstanceStackCursor, fiber);
15791
}
15792
15793
function getHostContext() {
15794
  var context = requiredContext(contextStackCursor$1.current);
15795
  return context;
15796
}
15797
15798
function pushHostContext(fiber) {
15799
  var rootInstance = requiredContext(rootInstanceStackCursor.current);
15800
  var context = requiredContext(contextStackCursor$1.current);
15801
  var nextContext = getChildHostContext(context, fiber.type, rootInstance); // Don't push this Fiber's context unless it's unique.
15802
15803
  if (context === nextContext) {
15804
    return;
15805
  } // Track the context and the Fiber that provided it.
15806
  // This enables us to pop only Fibers that provide unique contexts.
15807
15808
15809
  push(contextFiberStackCursor, fiber, fiber);
15810
  push(contextStackCursor$1, nextContext, fiber);
15811
}
15812
15813
function popHostContext(fiber) {
15814
  // Do not pop unless this Fiber provided the current context.
15815
  // pushHostContext() only pushes Fibers that provide unique contexts.
15816
  if (contextFiberStackCursor.current !== fiber) {
15817
    return;
15818
  }
15819
15820
  pop(contextStackCursor$1, fiber);
15821
  pop(contextFiberStackCursor, fiber);
15822
}
15823
15824
var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is
15825
// inherited deeply down the subtree. The upper bits only affect
15826
// this immediate suspense boundary and gets reset each new
15827
// boundary or suspense list.
15828
15829
var SubtreeSuspenseContextMask = 1; // Subtree Flags:
15830
// InvisibleParentSuspenseContext indicates that one of our parent Suspense
15831
// boundaries is not currently showing visible main content.
15832
// Either because it is already showing a fallback or is not mounted at all.
15833
// We can use this to determine if it is desirable to trigger a fallback at
15834
// the parent. If not, then we might need to trigger undesirable boundaries
15835
// and/or suspend the commit to avoid hiding the parent content.
15836
15837
var InvisibleParentSuspenseContext = 1; // Shallow Flags:
15838
// ForceSuspenseFallback can be used by SuspenseList to force newly added
15839
// items into their fallback state during one of the render passes.
15840
15841
var ForceSuspenseFallback = 2;
15842
var suspenseStackCursor = createCursor(DefaultSuspenseContext);
15843
function hasSuspenseContext(parentContext, flag) {
15844
  return (parentContext & flag) !== 0;
15845
}
15846
function setDefaultShallowSuspenseContext(parentContext) {
15847
  return parentContext & SubtreeSuspenseContextMask;
15848
}
15849
function setShallowSuspenseContext(parentContext, shallowContext) {
15850
  return parentContext & SubtreeSuspenseContextMask | shallowContext;
15851
}
15852
function addSubtreeSuspenseContext(parentContext, subtreeContext) {
15853
  return parentContext | subtreeContext;
15854
}
15855
function pushSuspenseContext(fiber, newContext) {
15856
  push(suspenseStackCursor, newContext, fiber);
15857
}
15858
function popSuspenseContext(fiber) {
15859
  pop(suspenseStackCursor, fiber);
15860
}
15861
15862
function shouldCaptureSuspense(workInProgress, hasInvisibleParent) {
15863
  // If it was the primary children that just suspended, capture and render the
15864
  // fallback. Otherwise, don't capture and bubble to the next boundary.
15865
  var nextState = workInProgress.memoizedState;
15866
15867
  if (nextState !== null) {
15868
    if (nextState.dehydrated !== null) {
15869
      // A dehydrated boundary always captures.
15870
      return true;
15871
    }
15872
15873
    return false;
15874
  }
15875
15876
  var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop.
15877
15878
  if (props.fallback === undefined) {
15879
    return false;
15880
  } // Regular boundaries always capture.
15881
15882
15883
  if (props.unstable_avoidThisFallback !== true) {
15884
    return true;
15885
  } // If it's a boundary we should avoid, then we prefer to bubble up to the
15886
  // parent boundary if it is currently invisible.
15887
15888
15889
  if (hasInvisibleParent) {
15890
    return false;
15891
  } // If the parent is not able to handle it, we must handle it.
15892
15893
15894
  return true;
15895
}
15896
function findFirstSuspended(row) {
15897
  var node = row;
15898
15899
  while (node !== null) {
15900
    if (node.tag === SuspenseComponent) {
15901
      var state = node.memoizedState;
15902
15903
      if (state !== null) {
15904
        var dehydrated = state.dehydrated;
15905
15906
        if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {
15907
          return node;
15908
        }
15909
      }
15910
    } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
15911
    // keep track of whether it suspended or not.
15912
    node.memoizedProps.revealOrder !== undefined) {
15913
      var didSuspend = (node.effectTag & DidCapture) !== NoEffect;
15914
15915
      if (didSuspend) {
15916
        return node;
15917
      }
15918
    } else if (node.child !== null) {
15919
      node.child.return = node;
15920
      node = node.child;
15921
      continue;
15922
    }
15923
15924
    if (node === row) {
15925
      return null;
15926
    }
15927
15928
    while (node.sibling === null) {
15929
      if (node.return === null || node.return === row) {
15930
        return null;
15931
      }
15932
15933
      node = node.return;
15934
    }
15935
15936
    node.sibling.return = node.return;
15937
    node = node.sibling;
15938
  }
15939
15940
  return null;
15941
}
15942
15943
var emptyObject = {};
15944
var isArray$2 = Array.isArray;
15945
function createResponderInstance(responder, responderProps, responderState, fiber) {
15946
  return {
15947
    fiber: fiber,
15948
    props: responderProps,
15949
    responder: responder,
15950
    rootEventTypes: null,
15951
    state: responderState
15952
  };
15953
}
15954
15955
function mountEventResponder$1(responder, responderProps, fiber, respondersMap, rootContainerInstance) {
15956
  var responderState = emptyObject;
15957
  var getInitialState = responder.getInitialState;
15958
15959
  if (getInitialState !== null) {
15960
    responderState = getInitialState(responderProps);
15961
  }
15962
15963
  var responderInstance = createResponderInstance(responder, responderProps, responderState, fiber);
15964
15965
  if (!rootContainerInstance) {
15966
    var node = fiber;
15967
15968
    while (node !== null) {
15969
      var tag = node.tag;
15970
15971
      if (tag === HostComponent) {
15972
        rootContainerInstance = node.stateNode;
15973
        break;
15974
      } else if (tag === HostRoot) {
15975
        rootContainerInstance = node.stateNode.containerInfo;
15976
        break;
15977
      }
15978
15979
      node = node.return;
15980
    }
15981
  }
15982
15983
  mountResponderInstance(responder, responderInstance, responderProps, responderState, rootContainerInstance);
15984
  respondersMap.set(responder, responderInstance);
15985
}
15986
15987
function updateEventListener(listener, fiber, visistedResponders, respondersMap, rootContainerInstance) {
15988
  var responder;
15989
  var props;
15990
15991
  if (listener) {
15992
    responder = listener.responder;
15993
    props = listener.props;
15994
  }
15995
15996
  (function () {
15997
    if (!(responder && responder.$$typeof === REACT_RESPONDER_TYPE)) {
15998
      {
15999
        throw ReactError(Error("An invalid value was used as an event listener. Expect one or many event listeners created via React.unstable_useResponder()."));
16000
      }
16001
    }
16002
  })();
16003
16004
  var listenerProps = props;
16005
16006
  if (visistedResponders.has(responder)) {
16007
    // show warning
16008
    {
16009
      warning$1(false, 'Duplicate event responder "%s" found in event listeners. ' + 'Event listeners passed to elements cannot use the same event responder more than once.', responder.displayName);
16010
    }
16011
16012
    return;
16013
  }
16014
16015
  visistedResponders.add(responder);
16016
  var responderInstance = respondersMap.get(responder);
16017
16018
  if (responderInstance === undefined) {
16019
    // Mount (happens in either complete or commit phase)
16020
    mountEventResponder$1(responder, listenerProps, fiber, respondersMap, rootContainerInstance);
16021
  } else {
16022
    // Update (happens during commit phase only)
16023
    responderInstance.props = listenerProps;
16024
    responderInstance.fiber = fiber;
16025
  }
16026
}
16027
16028
function updateEventListeners(listeners, fiber, rootContainerInstance) {
16029
  var visistedResponders = new Set();
16030
  var dependencies = fiber.dependencies;
16031
16032
  if (listeners != null) {
16033
    if (dependencies === null) {
16034
      dependencies = fiber.dependencies = {
16035
        expirationTime: NoWork,
16036
        firstContext: null,
16037
        responders: new Map()
16038
      };
16039
    }
16040
16041
    var respondersMap = dependencies.responders;
16042
16043
    if (respondersMap === null) {
16044
      respondersMap = new Map();
16045
    }
16046
16047
    if (isArray$2(listeners)) {
16048
      for (var i = 0, length = listeners.length; i < length; i++) {
16049
        var listener = listeners[i];
16050
        updateEventListener(listener, fiber, visistedResponders, respondersMap, rootContainerInstance);
16051
      }
16052
    } else {
16053
      updateEventListener(listeners, fiber, visistedResponders, respondersMap, rootContainerInstance);
16054
    }
16055
  }
16056
16057
  if (dependencies !== null) {
16058
    var _respondersMap = dependencies.responders;
16059
16060
    if (_respondersMap !== null) {
16061
      // Unmount
16062
      var mountedResponders = Array.from(_respondersMap.keys());
16063
16064
      for (var _i = 0, _length = mountedResponders.length; _i < _length; _i++) {
16065
        var mountedResponder = mountedResponders[_i];
16066
16067
        if (!visistedResponders.has(mountedResponder)) {
16068
          var responderInstance = _respondersMap.get(mountedResponder);
16069
16070
          unmountResponderInstance(responderInstance);
16071
16072
          _respondersMap.delete(mountedResponder);
16073
        }
16074
      }
16075
    }
16076
  }
16077
}
16078
function createResponderListener(responder, props) {
16079
  var eventResponderListener = {
16080
    responder: responder,
16081
    props: props
16082
  };
16083
16084
  {
16085
    Object.freeze(eventResponderListener);
16086
  }
16087
16088
  return eventResponderListener;
16089
}
16090
16091
var NoEffect$1 =
16092
/*             */
16093
0;
16094
var UnmountSnapshot =
16095
/*      */
16096
2;
16097
var UnmountMutation =
16098
/*      */
16099
4;
16100
var MountMutation =
16101
/*        */
16102
8;
16103
var UnmountLayout =
16104
/*        */
16105
16;
16106
var MountLayout =
16107
/*          */
16108
32;
16109
var MountPassive =
16110
/*         */
16111
64;
16112
var UnmountPassive =
16113
/*       */
16114
128;
16115
16116
var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
16117
var didWarnAboutMismatchedHooksForComponent;
16118
16119
{
16120
  didWarnAboutMismatchedHooksForComponent = new Set();
16121
}
16122
16123
// These are set right before calling the component.
16124
var renderExpirationTime$1 = NoWork; // The work-in-progress fiber. I've named it differently to distinguish it from
16125
// the work-in-progress hook.
16126
16127
var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The
16128
// current hook list is the list that belongs to the current fiber. The
16129
// work-in-progress hook list is a new list that will be added to the
16130
// work-in-progress fiber.
16131
16132
var currentHook = null;
16133
var nextCurrentHook = null;
16134
var firstWorkInProgressHook = null;
16135
var workInProgressHook = null;
16136
var nextWorkInProgressHook = null;
16137
var remainingExpirationTime = NoWork;
16138
var componentUpdateQueue = null;
16139
var sideEffectTag = 0; // Updates scheduled during render will trigger an immediate re-render at the
16140
// end of the current pass. We can't store these updates on the normal queue,
16141
// because if the work is aborted, they should be discarded. Because this is
16142
// a relatively rare case, we also don't want to add an additional field to
16143
// either the hook or queue object types. So we store them in a lazily create
16144
// map of queue -> render-phase updates, which are discarded once the component
16145
// completes without re-rendering.
16146
// Whether an update was scheduled during the currently executing render pass.
16147
16148
var didScheduleRenderPhaseUpdate = false; // Lazily created map of render-phase updates
16149
16150
var renderPhaseUpdates = null; // Counter to prevent infinite loops.
16151
16152
var numberOfReRenders = 0;
16153
var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook
16154
16155
var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.
16156
// The list stores the order of hooks used during the initial render (mount).
16157
// Subsequent renders (updates) reference this list.
16158
16159
var hookTypesDev = null;
16160
var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore
16161
// the dependencies for Hooks that need them (e.g. useEffect or useMemo).
16162
// When true, such Hooks will always be "remounted". Only used during hot reload.
16163
16164
var ignorePreviousDependencies = false;
16165
16166
function mountHookTypesDev() {
16167
  {
16168
    var hookName = currentHookNameInDev;
16169
16170
    if (hookTypesDev === null) {
16171
      hookTypesDev = [hookName];
16172
    } else {
16173
      hookTypesDev.push(hookName);
16174
    }
16175
  }
16176
}
16177
16178
function updateHookTypesDev() {
16179
  {
16180
    var hookName = currentHookNameInDev;
16181
16182
    if (hookTypesDev !== null) {
16183
      hookTypesUpdateIndexDev++;
16184
16185
      if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
16186
        warnOnHookMismatchInDev(hookName);
16187
      }
16188
    }
16189
  }
16190
}
16191
16192
function checkDepsAreArrayDev(deps) {
16193
  {
16194
    if (deps !== undefined && deps !== null && !Array.isArray(deps)) {
16195
      // Verify deps, but only on mount to avoid extra checks.
16196
      // It's unlikely their type would change as usually you define them inline.
16197
      warning$1(false, '%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps);
16198
    }
16199
  }
16200
}
16201
16202
function warnOnHookMismatchInDev(currentHookName) {
16203
  {
16204
    var componentName = getComponentName(currentlyRenderingFiber$1.type);
16205
16206
    if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
16207
      didWarnAboutMismatchedHooksForComponent.add(componentName);
16208
16209
      if (hookTypesDev !== null) {
16210
        var table = '';
16211
        var secondColumnStart = 30;
16212
16213
        for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
16214
          var oldHookName = hookTypesDev[i];
16215
          var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
16216
          var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up
16217
          // lol @ IE not supporting String#repeat
16218
16219
          while (row.length < secondColumnStart) {
16220
            row += ' ';
16221
          }
16222
16223
          row += newHookName + '\n';
16224
          table += row;
16225
        }
16226
16227
        warning$1(false, 'React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks\n\n' + '   Previous render            Next render\n' + '   ------------------------------------------------------\n' + '%s' + '   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table);
16228
      }
16229
    }
16230
  }
16231
}
16232
16233
function throwInvalidHookError() {
16234
  (function () {
16235
    {
16236
      {
16237
        throw ReactError(Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem."));
16238
      }
16239
    }
16240
  })();
16241
}
16242
16243
function areHookInputsEqual(nextDeps, prevDeps) {
16244
  {
16245
    if (ignorePreviousDependencies) {
16246
      // Only true when this component is being hot reloaded.
16247
      return false;
16248
    }
16249
  }
16250
16251
  if (prevDeps === null) {
16252
    {
16253
      warning$1(false, '%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
16254
    }
16255
16256
    return false;
16257
  }
16258
16259
  {
16260
    // Don't bother comparing lengths in prod because these arrays should be
16261
    // passed inline.
16262
    if (nextDeps.length !== prevDeps.length) {
16263
      warning$1(false, 'The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]");
16264
    }
16265
  }
16266
16267
  for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
16268
    if (is$1(nextDeps[i], prevDeps[i])) {
16269
      continue;
16270
    }
16271
16272
    return false;
16273
  }
16274
16275
  return true;
16276
}
16277
16278
function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) {
16279
  renderExpirationTime$1 = nextRenderExpirationTime;
16280
  currentlyRenderingFiber$1 = workInProgress;
16281
  nextCurrentHook = current !== null ? current.memoizedState : null;
16282
16283
  {
16284
    hookTypesDev = current !== null ? current._debugHookTypes : null;
16285
    hookTypesUpdateIndexDev = -1; // Used for hot reloading:
16286
16287
    ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;
16288
  } // The following should have already been reset
16289
  // currentHook = null;
16290
  // workInProgressHook = null;
16291
  // remainingExpirationTime = NoWork;
16292
  // componentUpdateQueue = null;
16293
  // didScheduleRenderPhaseUpdate = false;
16294
  // renderPhaseUpdates = null;
16295
  // numberOfReRenders = 0;
16296
  // sideEffectTag = 0;
16297
  // TODO Warn if no hooks are used at all during mount, then some are used during update.
16298
  // Currently we will identify the update render as a mount because nextCurrentHook === null.
16299
  // This is tricky because it's valid for certain types of components (e.g. React.lazy)
16300
  // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used.
16301
  // Non-stateful hooks (e.g. context) don't get added to memoizedState,
16302
  // so nextCurrentHook would be null during updates and mounts.
16303
16304
16305
  {
16306
    if (nextCurrentHook !== null) {
16307
      ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
16308
    } else if (hookTypesDev !== null) {
16309
      // This dispatcher handles an edge case where a component is updating,
16310
      // but no stateful hooks have been used.
16311
      // We want to match the production code behavior (which will use HooksDispatcherOnMount),
16312
      // but with the extra DEV validation to ensure hooks ordering hasn't changed.
16313
      // This dispatcher does that.
16314
      ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
16315
    } else {
16316
      ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
16317
    }
16318
  }
16319
16320
  var children = Component(props, refOrContext);
16321
16322
  if (didScheduleRenderPhaseUpdate) {
16323
    do {
16324
      didScheduleRenderPhaseUpdate = false;
16325
      numberOfReRenders += 1;
16326
16327
      {
16328
        // Even when hot reloading, allow dependencies to stabilize
16329
        // after first render to prevent infinite render phase updates.
16330
        ignorePreviousDependencies = false;
16331
      } // Start over from the beginning of the list
16332
16333
16334
      nextCurrentHook = current !== null ? current.memoizedState : null;
16335
      nextWorkInProgressHook = firstWorkInProgressHook;
16336
      currentHook = null;
16337
      workInProgressHook = null;
16338
      componentUpdateQueue = null;
16339
16340
      {
16341
        // Also validate hook order for cascading updates.
16342
        hookTypesUpdateIndexDev = -1;
16343
      }
16344
16345
      ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
16346
      children = Component(props, refOrContext);
16347
    } while (didScheduleRenderPhaseUpdate);
16348
16349
    renderPhaseUpdates = null;
16350
    numberOfReRenders = 0;
16351
  } // We can assume the previous dispatcher is always this one, since we set it
16352
  // at the beginning of the render phase and there's no re-entrancy.
16353
16354
16355
  ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
16356
  var renderedWork = currentlyRenderingFiber$1;
16357
  renderedWork.memoizedState = firstWorkInProgressHook;
16358
  renderedWork.expirationTime = remainingExpirationTime;
16359
  renderedWork.updateQueue = componentUpdateQueue;
16360
  renderedWork.effectTag |= sideEffectTag;
16361
16362
  {
16363
    renderedWork._debugHookTypes = hookTypesDev;
16364
  } // This check uses currentHook so that it works the same in DEV and prod bundles.
16365
  // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
16366
16367
16368
  var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
16369
  renderExpirationTime$1 = NoWork;
16370
  currentlyRenderingFiber$1 = null;
16371
  currentHook = null;
16372
  nextCurrentHook = null;
16373
  firstWorkInProgressHook = null;
16374
  workInProgressHook = null;
16375
  nextWorkInProgressHook = null;
16376
16377
  {
16378
    currentHookNameInDev = null;
16379
    hookTypesDev = null;
16380
    hookTypesUpdateIndexDev = -1;
16381
  }
16382
16383
  remainingExpirationTime = NoWork;
16384
  componentUpdateQueue = null;
16385
  sideEffectTag = 0; // These were reset above
16386
  // didScheduleRenderPhaseUpdate = false;
16387
  // renderPhaseUpdates = null;
16388
  // numberOfReRenders = 0;
16389
16390
  (function () {
16391
    if (!!didRenderTooFewHooks) {
16392
      {
16393
        throw ReactError(Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement."));
16394
      }
16395
    }
16396
  })();
16397
16398
  return children;
16399
}
16400
function bailoutHooks(current, workInProgress, expirationTime) {
16401
  workInProgress.updateQueue = current.updateQueue;
16402
  workInProgress.effectTag &= ~(Passive | Update);
16403
16404
  if (current.expirationTime <= expirationTime) {
16405
    current.expirationTime = NoWork;
16406
  }
16407
}
16408
function resetHooks() {
16409
  // We can assume the previous dispatcher is always this one, since we set it
16410
  // at the beginning of the render phase and there's no re-entrancy.
16411
  ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; // This is used to reset the state of this module when a component throws.
16412
  // It's also called inside mountIndeterminateComponent if we determine the
16413
  // component is a module-style component.
16414
16415
  renderExpirationTime$1 = NoWork;
16416
  currentlyRenderingFiber$1 = null;
16417
  currentHook = null;
16418
  nextCurrentHook = null;
16419
  firstWorkInProgressHook = null;
16420
  workInProgressHook = null;
16421
  nextWorkInProgressHook = null;
16422
16423
  {
16424
    hookTypesDev = null;
16425
    hookTypesUpdateIndexDev = -1;
16426
    currentHookNameInDev = null;
16427
  }
16428
16429
  remainingExpirationTime = NoWork;
16430
  componentUpdateQueue = null;
16431
  sideEffectTag = 0;
16432
  didScheduleRenderPhaseUpdate = false;
16433
  renderPhaseUpdates = null;
16434
  numberOfReRenders = 0;
16435
}
16436
16437
function mountWorkInProgressHook() {
16438
  var hook = {
16439
    memoizedState: null,
16440
    baseState: null,
16441
    queue: null,
16442
    baseUpdate: null,
16443
    next: null
16444
  };
16445
16446
  if (workInProgressHook === null) {
16447
    // This is the first hook in the list
16448
    firstWorkInProgressHook = workInProgressHook = hook;
16449
  } else {
16450
    // Append to the end of the list
16451
    workInProgressHook = workInProgressHook.next = hook;
16452
  }
16453
16454
  return workInProgressHook;
16455
}
16456
16457
function updateWorkInProgressHook() {
16458
  // This function is used both for updates and for re-renders triggered by a
16459
  // render phase update. It assumes there is either a current hook we can
16460
  // clone, or a work-in-progress hook from a previous render pass that we can
16461
  // use as a base. When we reach the end of the base list, we must switch to
16462
  // the dispatcher used for mounts.
16463
  if (nextWorkInProgressHook !== null) {
16464
    // There's already a work-in-progress. Reuse it.
16465
    workInProgressHook = nextWorkInProgressHook;
16466
    nextWorkInProgressHook = workInProgressHook.next;
16467
    currentHook = nextCurrentHook;
16468
    nextCurrentHook = currentHook !== null ? currentHook.next : null;
16469
  } else {
16470
    // Clone from the current hook.
16471
    (function () {
16472
      if (!(nextCurrentHook !== null)) {
16473
        {
16474
          throw ReactError(Error("Rendered more hooks than during the previous render."));
16475
        }
16476
      }
16477
    })();
16478
16479
    currentHook = nextCurrentHook;
16480
    var newHook = {
16481
      memoizedState: currentHook.memoizedState,
16482
      baseState: currentHook.baseState,
16483
      queue: currentHook.queue,
16484
      baseUpdate: currentHook.baseUpdate,
16485
      next: null
16486
    };
16487
16488
    if (workInProgressHook === null) {
16489
      // This is the first hook in the list.
16490
      workInProgressHook = firstWorkInProgressHook = newHook;
16491
    } else {
16492
      // Append to the end of the list.
16493
      workInProgressHook = workInProgressHook.next = newHook;
16494
    }
16495
16496
    nextCurrentHook = currentHook.next;
16497
  }
16498
16499
  return workInProgressHook;
16500
}
16501
16502
function createFunctionComponentUpdateQueue() {
16503
  return {
16504
    lastEffect: null
16505
  };
16506
}
16507
16508
function basicStateReducer(state, action) {
16509
  return typeof action === 'function' ? action(state) : action;
16510
}
16511
16512
function mountReducer(reducer, initialArg, init) {
16513
  var hook = mountWorkInProgressHook();
16514
  var initialState;
16515
16516
  if (init !== undefined) {
16517
    initialState = init(initialArg);
16518
  } else {
16519
    initialState = initialArg;
16520
  }
16521
16522
  hook.memoizedState = hook.baseState = initialState;
16523
  var queue = hook.queue = {
16524
    last: null,
16525
    dispatch: null,
16526
    lastRenderedReducer: reducer,
16527
    lastRenderedState: initialState
16528
  };
16529
  var dispatch = queue.dispatch = dispatchAction.bind(null, // Flow doesn't know this is non-null, but we do.
16530
  currentlyRenderingFiber$1, queue);
16531
  return [hook.memoizedState, dispatch];
16532
}
16533
16534
function updateReducer(reducer, initialArg, init) {
16535
  var hook = updateWorkInProgressHook();
16536
  var queue = hook.queue;
16537
16538
  (function () {
16539
    if (!(queue !== null)) {
16540
      {
16541
        throw ReactError(Error("Should have a queue. This is likely a bug in React. Please file an issue."));
16542
      }
16543
    }
16544
  })();
16545
16546
  queue.lastRenderedReducer = reducer;
16547
16548
  if (numberOfReRenders > 0) {
16549
    // This is a re-render. Apply the new render phase updates to the previous
16550
    // work-in-progress hook.
16551
    var _dispatch = queue.dispatch;
16552
16553
    if (renderPhaseUpdates !== null) {
16554
      // Render phase updates are stored in a map of queue -> linked list
16555
      var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
16556
16557
      if (firstRenderPhaseUpdate !== undefined) {
16558
        renderPhaseUpdates.delete(queue);
16559
        var newState = hook.memoizedState;
16560
        var update = firstRenderPhaseUpdate;
16561
16562
        do {
16563
          // Process this render phase update. We don't have to check the
16564
          // priority because it will always be the same as the current
16565
          // render's.
16566
          var action = update.action;
16567
          newState = reducer(newState, action);
16568
          update = update.next;
16569
        } while (update !== null); // Mark that the fiber performed work, but only if the new state is
16570
        // different from the current state.
16571
16572
16573
        if (!is$1(newState, hook.memoizedState)) {
16574
          markWorkInProgressReceivedUpdate();
16575
        }
16576
16577
        hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to
16578
        // the base state unless the queue is empty.
16579
        // TODO: Not sure if this is the desired semantics, but it's what we
16580
        // do for gDSFP. I can't remember why.
16581
16582
        if (hook.baseUpdate === queue.last) {
16583
          hook.baseState = newState;
16584
        }
16585
16586
        queue.lastRenderedState = newState;
16587
        return [newState, _dispatch];
16588
      }
16589
    }
16590
16591
    return [hook.memoizedState, _dispatch];
16592
  } // The last update in the entire queue
16593
16594
16595
  var last = queue.last; // The last update that is part of the base state.
16596
16597
  var baseUpdate = hook.baseUpdate;
16598
  var baseState = hook.baseState; // Find the first unprocessed update.
16599
16600
  var first;
16601
16602
  if (baseUpdate !== null) {
16603
    if (last !== null) {
16604
      // For the first update, the queue is a circular linked list where
16605
      // `queue.last.next = queue.first`. Once the first update commits, and
16606
      // the `baseUpdate` is no longer empty, we can unravel the list.
16607
      last.next = null;
16608
    }
16609
16610
    first = baseUpdate.next;
16611
  } else {
16612
    first = last !== null ? last.next : null;
16613
  }
16614
16615
  if (first !== null) {
16616
    var _newState = baseState;
16617
    var newBaseState = null;
16618
    var newBaseUpdate = null;
16619
    var prevUpdate = baseUpdate;
16620
    var _update = first;
16621
    var didSkip = false;
16622
16623
    do {
16624
      var updateExpirationTime = _update.expirationTime;
16625
16626
      if (updateExpirationTime < renderExpirationTime$1) {
16627
        // Priority is insufficient. Skip this update. If this is the first
16628
        // skipped update, the previous update/state is the new base
16629
        // update/state.
16630
        if (!didSkip) {
16631
          didSkip = true;
16632
          newBaseUpdate = prevUpdate;
16633
          newBaseState = _newState;
16634
        } // Update the remaining priority in the queue.
16635
16636
16637
        if (updateExpirationTime > remainingExpirationTime) {
16638
          remainingExpirationTime = updateExpirationTime;
16639
          markUnprocessedUpdateTime(remainingExpirationTime);
16640
        }
16641
      } else {
16642
        // This update does have sufficient priority.
16643
        // Mark the event time of this update as relevant to this render pass.
16644
        // TODO: This should ideally use the true event time of this update rather than
16645
        // its priority which is a derived and not reverseable value.
16646
        // TODO: We should skip this update if it was already committed but currently
16647
        // we have no way of detecting the difference between a committed and suspended
16648
        // update here.
16649
        markRenderEventTimeAndConfig(updateExpirationTime, _update.suspenseConfig); // Process this update.
16650
16651
        if (_update.eagerReducer === reducer) {
16652
          // If this update was processed eagerly, and its reducer matches the
16653
          // current reducer, we can use the eagerly computed state.
16654
          _newState = _update.eagerState;
16655
        } else {
16656
          var _action = _update.action;
16657
          _newState = reducer(_newState, _action);
16658
        }
16659
      }
16660
16661
      prevUpdate = _update;
16662
      _update = _update.next;
16663
    } while (_update !== null && _update !== first);
16664
16665
    if (!didSkip) {
16666
      newBaseUpdate = prevUpdate;
16667
      newBaseState = _newState;
16668
    } // Mark that the fiber performed work, but only if the new state is
16669
    // different from the current state.
16670
16671
16672
    if (!is$1(_newState, hook.memoizedState)) {
16673
      markWorkInProgressReceivedUpdate();
16674
    }
16675
16676
    hook.memoizedState = _newState;
16677
    hook.baseUpdate = newBaseUpdate;
16678
    hook.baseState = newBaseState;
16679
    queue.lastRenderedState = _newState;
16680
  }
16681
16682
  var dispatch = queue.dispatch;
16683
  return [hook.memoizedState, dispatch];
16684
}
16685
16686
function mountState(initialState) {
16687
  var hook = mountWorkInProgressHook();
16688
16689
  if (typeof initialState === 'function') {
16690
    initialState = initialState();
16691
  }
16692
16693
  hook.memoizedState = hook.baseState = initialState;
16694
  var queue = hook.queue = {
16695
    last: null,
16696
    dispatch: null,
16697
    lastRenderedReducer: basicStateReducer,
16698
    lastRenderedState: initialState
16699
  };
16700
  var dispatch = queue.dispatch = dispatchAction.bind(null, // Flow doesn't know this is non-null, but we do.
16701
  currentlyRenderingFiber$1, queue);
16702
  return [hook.memoizedState, dispatch];
16703
}
16704
16705
function updateState(initialState) {
16706
  return updateReducer(basicStateReducer, initialState);
16707
}
16708
16709
function pushEffect(tag, create, destroy, deps) {
16710
  var effect = {
16711
    tag: tag,
16712
    create: create,
16713
    destroy: destroy,
16714
    deps: deps,
16715
    // Circular
16716
    next: null
16717
  };
16718
16719
  if (componentUpdateQueue === null) {
16720
    componentUpdateQueue = createFunctionComponentUpdateQueue();
16721
    componentUpdateQueue.lastEffect = effect.next = effect;
16722
  } else {
16723
    var lastEffect = componentUpdateQueue.lastEffect;
16724
16725
    if (lastEffect === null) {
16726
      componentUpdateQueue.lastEffect = effect.next = effect;
16727
    } else {
16728
      var firstEffect = lastEffect.next;
16729
      lastEffect.next = effect;
16730
      effect.next = firstEffect;
16731
      componentUpdateQueue.lastEffect = effect;
16732
    }
16733
  }
16734
16735
  return effect;
16736
}
16737
16738
function mountRef(initialValue) {
16739
  var hook = mountWorkInProgressHook();
16740
  var ref = {
16741
    current: initialValue
16742
  };
16743
16744
  {
16745
    Object.seal(ref);
16746
  }
16747
16748
  hook.memoizedState = ref;
16749
  return ref;
16750
}
16751
16752
function updateRef(initialValue) {
16753
  var hook = updateWorkInProgressHook();
16754
  return hook.memoizedState;
16755
}
16756
16757
function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
16758
  var hook = mountWorkInProgressHook();
16759
  var nextDeps = deps === undefined ? null : deps;
16760
  sideEffectTag |= fiberEffectTag;
16761
  hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps);
16762
}
16763
16764
function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
16765
  var hook = updateWorkInProgressHook();
16766
  var nextDeps = deps === undefined ? null : deps;
16767
  var destroy = undefined;
16768
16769
  if (currentHook !== null) {
16770
    var prevEffect = currentHook.memoizedState;
16771
    destroy = prevEffect.destroy;
16772
16773
    if (nextDeps !== null) {
16774
      var prevDeps = prevEffect.deps;
16775
16776
      if (areHookInputsEqual(nextDeps, prevDeps)) {
16777
        pushEffect(NoEffect$1, create, destroy, nextDeps);
16778
        return;
16779
      }
16780
    }
16781
  }
16782
16783
  sideEffectTag |= fiberEffectTag;
16784
  hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps);
16785
}
16786
16787
function mountEffect(create, deps) {
16788
  {
16789
    // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
16790
    if ('undefined' !== typeof jest) {
16791
      warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
16792
    }
16793
  }
16794
16795
  return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
16796
}
16797
16798
function updateEffect(create, deps) {
16799
  {
16800
    // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
16801
    if ('undefined' !== typeof jest) {
16802
      warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
16803
    }
16804
  }
16805
16806
  return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
16807
}
16808
16809
function mountLayoutEffect(create, deps) {
16810
  return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
16811
}
16812
16813
function updateLayoutEffect(create, deps) {
16814
  return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
16815
}
16816
16817
function imperativeHandleEffect(create, ref) {
16818
  if (typeof ref === 'function') {
16819
    var refCallback = ref;
16820
16821
    var _inst = create();
16822
16823
    refCallback(_inst);
16824
    return function () {
16825
      refCallback(null);
16826
    };
16827
  } else if (ref !== null && ref !== undefined) {
16828
    var refObject = ref;
16829
16830
    {
16831
      !refObject.hasOwnProperty('current') ? warning$1(false, 'Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}') : void 0;
16832
    }
16833
16834
    var _inst2 = create();
16835
16836
    refObject.current = _inst2;
16837
    return function () {
16838
      refObject.current = null;
16839
    };
16840
  }
16841
}
16842
16843
function mountImperativeHandle(ref, create, deps) {
16844
  {
16845
    !(typeof create === 'function') ? warning$1(false, 'Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null') : void 0;
16846
  } // TODO: If deps are provided, should we skip comparing the ref itself?
16847
16848
16849
  var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
16850
  return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
16851
}
16852
16853
function updateImperativeHandle(ref, create, deps) {
16854
  {
16855
    !(typeof create === 'function') ? warning$1(false, 'Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null') : void 0;
16856
  } // TODO: If deps are provided, should we skip comparing the ref itself?
16857
16858
16859
  var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
16860
  return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
16861
}
16862
16863
function mountDebugValue(value, formatterFn) {// This hook is normally a no-op.
16864
  // The react-debug-hooks package injects its own implementation
16865
  // so that e.g. DevTools can display custom hook values.
16866
}
16867
16868
var updateDebugValue = mountDebugValue;
16869
16870
function mountCallback(callback, deps) {
16871
  var hook = mountWorkInProgressHook();
16872
  var nextDeps = deps === undefined ? null : deps;
16873
  hook.memoizedState = [callback, nextDeps];
16874
  return callback;
16875
}
16876
16877
function updateCallback(callback, deps) {
16878
  var hook = updateWorkInProgressHook();
16879
  var nextDeps = deps === undefined ? null : deps;
16880
  var prevState = hook.memoizedState;
16881
16882
  if (prevState !== null) {
16883
    if (nextDeps !== null) {
16884
      var prevDeps = prevState[1];
16885
16886
      if (areHookInputsEqual(nextDeps, prevDeps)) {
16887
        return prevState[0];
16888
      }
16889
    }
16890
  }
16891
16892
  hook.memoizedState = [callback, nextDeps];
16893
  return callback;
16894
}
16895
16896
function mountMemo(nextCreate, deps) {
16897
  var hook = mountWorkInProgressHook();
16898
  var nextDeps = deps === undefined ? null : deps;
16899
  var nextValue = nextCreate();
16900
  hook.memoizedState = [nextValue, nextDeps];
16901
  return nextValue;
16902
}
16903
16904
function updateMemo(nextCreate, deps) {
16905
  var hook = updateWorkInProgressHook();
16906
  var nextDeps = deps === undefined ? null : deps;
16907
  var prevState = hook.memoizedState;
16908
16909
  if (prevState !== null) {
16910
    // Assume these are defined. If they're not, areHookInputsEqual will warn.
16911
    if (nextDeps !== null) {
16912
      var prevDeps = prevState[1];
16913
16914
      if (areHookInputsEqual(nextDeps, prevDeps)) {
16915
        return prevState[0];
16916
      }
16917
    }
16918
  }
16919
16920
  var nextValue = nextCreate();
16921
  hook.memoizedState = [nextValue, nextDeps];
16922
  return nextValue;
16923
}
16924
16925
function dispatchAction(fiber, queue, action) {
16926
  (function () {
16927
    if (!(numberOfReRenders < RE_RENDER_LIMIT)) {
16928
      {
16929
        throw ReactError(Error("Too many re-renders. React limits the number of renders to prevent an infinite loop."));
16930
      }
16931
    }
16932
  })();
16933
16934
  {
16935
    !(typeof arguments[3] !== 'function') ? warning$1(false, "State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().') : void 0;
16936
  }
16937
16938
  var alternate = fiber.alternate;
16939
16940
  if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
16941
    // This is a render phase update. Stash it in a lazily-created map of
16942
    // queue -> linked list of updates. After this render pass, we'll restart
16943
    // and apply the stashed updates on top of the work-in-progress hook.
16944
    didScheduleRenderPhaseUpdate = true;
16945
    var update = {
16946
      expirationTime: renderExpirationTime$1,
16947
      suspenseConfig: null,
16948
      action: action,
16949
      eagerReducer: null,
16950
      eagerState: null,
16951
      next: null
16952
    };
16953
16954
    {
16955
      update.priority = getCurrentPriorityLevel();
16956
    }
16957
16958
    if (renderPhaseUpdates === null) {
16959
      renderPhaseUpdates = new Map();
16960
    }
16961
16962
    var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
16963
16964
    if (firstRenderPhaseUpdate === undefined) {
16965
      renderPhaseUpdates.set(queue, update);
16966
    } else {
16967
      // Append the update to the end of the list.
16968
      var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
16969
16970
      while (lastRenderPhaseUpdate.next !== null) {
16971
        lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
16972
      }
16973
16974
      lastRenderPhaseUpdate.next = update;
16975
    }
16976
  } else {
16977
    var currentTime = requestCurrentTime();
16978
    var suspenseConfig = requestCurrentSuspenseConfig();
16979
    var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
16980
    var _update2 = {
16981
      expirationTime: expirationTime,
16982
      suspenseConfig: suspenseConfig,
16983
      action: action,
16984
      eagerReducer: null,
16985
      eagerState: null,
16986
      next: null
16987
    };
16988
16989
    {
16990
      _update2.priority = getCurrentPriorityLevel();
16991
    } // Append the update to the end of the list.
16992
16993
16994
    var last = queue.last;
16995
16996
    if (last === null) {
16997
      // This is the first update. Create a circular list.
16998
      _update2.next = _update2;
16999
    } else {
17000
      var first = last.next;
17001
17002
      if (first !== null) {
17003
        // Still circular.
17004
        _update2.next = first;
17005
      }
17006
17007
      last.next = _update2;
17008
    }
17009
17010
    queue.last = _update2;
17011
17012
    if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
17013
      // The queue is currently empty, which means we can eagerly compute the
17014
      // next state before entering the render phase. If the new state is the
17015
      // same as the current state, we may be able to bail out entirely.
17016
      var lastRenderedReducer = queue.lastRenderedReducer;
17017
17018
      if (lastRenderedReducer !== null) {
17019
        var prevDispatcher;
17020
17021
        {
17022
          prevDispatcher = ReactCurrentDispatcher$1.current;
17023
          ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17024
        }
17025
17026
        try {
17027
          var currentState = queue.lastRenderedState;
17028
          var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute
17029
          // it, on the update object. If the reducer hasn't changed by the
17030
          // time we enter the render phase, then the eager state can be used
17031
          // without calling the reducer again.
17032
17033
          _update2.eagerReducer = lastRenderedReducer;
17034
          _update2.eagerState = eagerState;
17035
17036
          if (is$1(eagerState, currentState)) {
17037
            // Fast path. We can bail out without scheduling React to re-render.
17038
            // It's still possible that we'll need to rebase this update later,
17039
            // if the component re-renders for a different reason and by that
17040
            // time the reducer has changed.
17041
            return;
17042
          }
17043
        } catch (error) {// Suppress the error. It will throw again in the render phase.
17044
        } finally {
17045
          {
17046
            ReactCurrentDispatcher$1.current = prevDispatcher;
17047
          }
17048
        }
17049
      }
17050
    }
17051
17052
    {
17053
      // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
17054
      if ('undefined' !== typeof jest) {
17055
        warnIfNotScopedWithMatchingAct(fiber);
17056
        warnIfNotCurrentlyActingUpdatesInDev(fiber);
17057
      }
17058
    }
17059
17060
    scheduleWork(fiber, expirationTime);
17061
  }
17062
}
17063
17064
var ContextOnlyDispatcher = {
17065
  readContext: readContext,
17066
  useCallback: throwInvalidHookError,
17067
  useContext: throwInvalidHookError,
17068
  useEffect: throwInvalidHookError,
17069
  useImperativeHandle: throwInvalidHookError,
17070
  useLayoutEffect: throwInvalidHookError,
17071
  useMemo: throwInvalidHookError,
17072
  useReducer: throwInvalidHookError,
17073
  useRef: throwInvalidHookError,
17074
  useState: throwInvalidHookError,
17075
  useDebugValue: throwInvalidHookError,
17076
  useResponder: throwInvalidHookError
17077
};
17078
var HooksDispatcherOnMountInDEV = null;
17079
var HooksDispatcherOnMountWithHookTypesInDEV = null;
17080
var HooksDispatcherOnUpdateInDEV = null;
17081
var InvalidNestedHooksDispatcherOnMountInDEV = null;
17082
var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
17083
17084
{
17085
  var warnInvalidContextAccess = function () {
17086
    warning$1(false, 'Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
17087
  };
17088
17089
  var warnInvalidHookAccess = function () {
17090
    warning$1(false, 'Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://fb.me/rules-of-hooks');
17091
  };
17092
17093
  HooksDispatcherOnMountInDEV = {
17094
    readContext: function (context, observedBits) {
17095
      return readContext(context, observedBits);
17096
    },
17097
    useCallback: function (callback, deps) {
17098
      currentHookNameInDev = 'useCallback';
17099
      mountHookTypesDev();
17100
      checkDepsAreArrayDev(deps);
17101
      return mountCallback(callback, deps);
17102
    },
17103
    useContext: function (context, observedBits) {
17104
      currentHookNameInDev = 'useContext';
17105
      mountHookTypesDev();
17106
      return readContext(context, observedBits);
17107
    },
17108
    useEffect: function (create, deps) {
17109
      currentHookNameInDev = 'useEffect';
17110
      mountHookTypesDev();
17111
      checkDepsAreArrayDev(deps);
17112
      return mountEffect(create, deps);
17113
    },
17114
    useImperativeHandle: function (ref, create, deps) {
17115
      currentHookNameInDev = 'useImperativeHandle';
17116
      mountHookTypesDev();
17117
      checkDepsAreArrayDev(deps);
17118
      return mountImperativeHandle(ref, create, deps);
17119
    },
17120
    useLayoutEffect: function (create, deps) {
17121
      currentHookNameInDev = 'useLayoutEffect';
17122
      mountHookTypesDev();
17123
      checkDepsAreArrayDev(deps);
17124
      return mountLayoutEffect(create, deps);
17125
    },
17126
    useMemo: function (create, deps) {
17127
      currentHookNameInDev = 'useMemo';
17128
      mountHookTypesDev();
17129
      checkDepsAreArrayDev(deps);
17130
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17131
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17132
17133
      try {
17134
        return mountMemo(create, deps);
17135
      } finally {
17136
        ReactCurrentDispatcher$1.current = prevDispatcher;
17137
      }
17138
    },
17139
    useReducer: function (reducer, initialArg, init) {
17140
      currentHookNameInDev = 'useReducer';
17141
      mountHookTypesDev();
17142
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17143
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17144
17145
      try {
17146
        return mountReducer(reducer, initialArg, init);
17147
      } finally {
17148
        ReactCurrentDispatcher$1.current = prevDispatcher;
17149
      }
17150
    },
17151
    useRef: function (initialValue) {
17152
      currentHookNameInDev = 'useRef';
17153
      mountHookTypesDev();
17154
      return mountRef(initialValue);
17155
    },
17156
    useState: function (initialState) {
17157
      currentHookNameInDev = 'useState';
17158
      mountHookTypesDev();
17159
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17160
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17161
17162
      try {
17163
        return mountState(initialState);
17164
      } finally {
17165
        ReactCurrentDispatcher$1.current = prevDispatcher;
17166
      }
17167
    },
17168
    useDebugValue: function (value, formatterFn) {
17169
      currentHookNameInDev = 'useDebugValue';
17170
      mountHookTypesDev();
17171
      return mountDebugValue(value, formatterFn);
17172
    },
17173
    useResponder: function (responder, props) {
17174
      currentHookNameInDev = 'useResponder';
17175
      mountHookTypesDev();
17176
      return createResponderListener(responder, props);
17177
    }
17178
  };
17179
  HooksDispatcherOnMountWithHookTypesInDEV = {
17180
    readContext: function (context, observedBits) {
17181
      return readContext(context, observedBits);
17182
    },
17183
    useCallback: function (callback, deps) {
17184
      currentHookNameInDev = 'useCallback';
17185
      updateHookTypesDev();
17186
      return mountCallback(callback, deps);
17187
    },
17188
    useContext: function (context, observedBits) {
17189
      currentHookNameInDev = 'useContext';
17190
      updateHookTypesDev();
17191
      return readContext(context, observedBits);
17192
    },
17193
    useEffect: function (create, deps) {
17194
      currentHookNameInDev = 'useEffect';
17195
      updateHookTypesDev();
17196
      return mountEffect(create, deps);
17197
    },
17198
    useImperativeHandle: function (ref, create, deps) {
17199
      currentHookNameInDev = 'useImperativeHandle';
17200
      updateHookTypesDev();
17201
      return mountImperativeHandle(ref, create, deps);
17202
    },
17203
    useLayoutEffect: function (create, deps) {
17204
      currentHookNameInDev = 'useLayoutEffect';
17205
      updateHookTypesDev();
17206
      return mountLayoutEffect(create, deps);
17207
    },
17208
    useMemo: function (create, deps) {
17209
      currentHookNameInDev = 'useMemo';
17210
      updateHookTypesDev();
17211
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17212
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17213
17214
      try {
17215
        return mountMemo(create, deps);
17216
      } finally {
17217
        ReactCurrentDispatcher$1.current = prevDispatcher;
17218
      }
17219
    },
17220
    useReducer: function (reducer, initialArg, init) {
17221
      currentHookNameInDev = 'useReducer';
17222
      updateHookTypesDev();
17223
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17224
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17225
17226
      try {
17227
        return mountReducer(reducer, initialArg, init);
17228
      } finally {
17229
        ReactCurrentDispatcher$1.current = prevDispatcher;
17230
      }
17231
    },
17232
    useRef: function (initialValue) {
17233
      currentHookNameInDev = 'useRef';
17234
      updateHookTypesDev();
17235
      return mountRef(initialValue);
17236
    },
17237
    useState: function (initialState) {
17238
      currentHookNameInDev = 'useState';
17239
      updateHookTypesDev();
17240
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17241
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17242
17243
      try {
17244
        return mountState(initialState);
17245
      } finally {
17246
        ReactCurrentDispatcher$1.current = prevDispatcher;
17247
      }
17248
    },
17249
    useDebugValue: function (value, formatterFn) {
17250
      currentHookNameInDev = 'useDebugValue';
17251
      updateHookTypesDev();
17252
      return mountDebugValue(value, formatterFn);
17253
    },
17254
    useResponder: function (responder, props) {
17255
      currentHookNameInDev = 'useResponder';
17256
      updateHookTypesDev();
17257
      return createResponderListener(responder, props);
17258
    }
17259
  };
17260
  HooksDispatcherOnUpdateInDEV = {
17261
    readContext: function (context, observedBits) {
17262
      return readContext(context, observedBits);
17263
    },
17264
    useCallback: function (callback, deps) {
17265
      currentHookNameInDev = 'useCallback';
17266
      updateHookTypesDev();
17267
      return updateCallback(callback, deps);
17268
    },
17269
    useContext: function (context, observedBits) {
17270
      currentHookNameInDev = 'useContext';
17271
      updateHookTypesDev();
17272
      return readContext(context, observedBits);
17273
    },
17274
    useEffect: function (create, deps) {
17275
      currentHookNameInDev = 'useEffect';
17276
      updateHookTypesDev();
17277
      return updateEffect(create, deps);
17278
    },
17279
    useImperativeHandle: function (ref, create, deps) {
17280
      currentHookNameInDev = 'useImperativeHandle';
17281
      updateHookTypesDev();
17282
      return updateImperativeHandle(ref, create, deps);
17283
    },
17284
    useLayoutEffect: function (create, deps) {
17285
      currentHookNameInDev = 'useLayoutEffect';
17286
      updateHookTypesDev();
17287
      return updateLayoutEffect(create, deps);
17288
    },
17289
    useMemo: function (create, deps) {
17290
      currentHookNameInDev = 'useMemo';
17291
      updateHookTypesDev();
17292
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17293
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17294
17295
      try {
17296
        return updateMemo(create, deps);
17297
      } finally {
17298
        ReactCurrentDispatcher$1.current = prevDispatcher;
17299
      }
17300
    },
17301
    useReducer: function (reducer, initialArg, init) {
17302
      currentHookNameInDev = 'useReducer';
17303
      updateHookTypesDev();
17304
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17305
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17306
17307
      try {
17308
        return updateReducer(reducer, initialArg, init);
17309
      } finally {
17310
        ReactCurrentDispatcher$1.current = prevDispatcher;
17311
      }
17312
    },
17313
    useRef: function (initialValue) {
17314
      currentHookNameInDev = 'useRef';
17315
      updateHookTypesDev();
17316
      return updateRef(initialValue);
17317
    },
17318
    useState: function (initialState) {
17319
      currentHookNameInDev = 'useState';
17320
      updateHookTypesDev();
17321
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17322
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17323
17324
      try {
17325
        return updateState(initialState);
17326
      } finally {
17327
        ReactCurrentDispatcher$1.current = prevDispatcher;
17328
      }
17329
    },
17330
    useDebugValue: function (value, formatterFn) {
17331
      currentHookNameInDev = 'useDebugValue';
17332
      updateHookTypesDev();
17333
      return updateDebugValue(value, formatterFn);
17334
    },
17335
    useResponder: function (responder, props) {
17336
      currentHookNameInDev = 'useResponder';
17337
      updateHookTypesDev();
17338
      return createResponderListener(responder, props);
17339
    }
17340
  };
17341
  InvalidNestedHooksDispatcherOnMountInDEV = {
17342
    readContext: function (context, observedBits) {
17343
      warnInvalidContextAccess();
17344
      return readContext(context, observedBits);
17345
    },
17346
    useCallback: function (callback, deps) {
17347
      currentHookNameInDev = 'useCallback';
17348
      warnInvalidHookAccess();
17349
      mountHookTypesDev();
17350
      return mountCallback(callback, deps);
17351
    },
17352
    useContext: function (context, observedBits) {
17353
      currentHookNameInDev = 'useContext';
17354
      warnInvalidHookAccess();
17355
      mountHookTypesDev();
17356
      return readContext(context, observedBits);
17357
    },
17358
    useEffect: function (create, deps) {
17359
      currentHookNameInDev = 'useEffect';
17360
      warnInvalidHookAccess();
17361
      mountHookTypesDev();
17362
      return mountEffect(create, deps);
17363
    },
17364
    useImperativeHandle: function (ref, create, deps) {
17365
      currentHookNameInDev = 'useImperativeHandle';
17366
      warnInvalidHookAccess();
17367
      mountHookTypesDev();
17368
      return mountImperativeHandle(ref, create, deps);
17369
    },
17370
    useLayoutEffect: function (create, deps) {
17371
      currentHookNameInDev = 'useLayoutEffect';
17372
      warnInvalidHookAccess();
17373
      mountHookTypesDev();
17374
      return mountLayoutEffect(create, deps);
17375
    },
17376
    useMemo: function (create, deps) {
17377
      currentHookNameInDev = 'useMemo';
17378
      warnInvalidHookAccess();
17379
      mountHookTypesDev();
17380
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17381
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17382
17383
      try {
17384
        return mountMemo(create, deps);
17385
      } finally {
17386
        ReactCurrentDispatcher$1.current = prevDispatcher;
17387
      }
17388
    },
17389
    useReducer: function (reducer, initialArg, init) {
17390
      currentHookNameInDev = 'useReducer';
17391
      warnInvalidHookAccess();
17392
      mountHookTypesDev();
17393
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17394
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17395
17396
      try {
17397
        return mountReducer(reducer, initialArg, init);
17398
      } finally {
17399
        ReactCurrentDispatcher$1.current = prevDispatcher;
17400
      }
17401
    },
17402
    useRef: function (initialValue) {
17403
      currentHookNameInDev = 'useRef';
17404
      warnInvalidHookAccess();
17405
      mountHookTypesDev();
17406
      return mountRef(initialValue);
17407
    },
17408
    useState: function (initialState) {
17409
      currentHookNameInDev = 'useState';
17410
      warnInvalidHookAccess();
17411
      mountHookTypesDev();
17412
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17413
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17414
17415
      try {
17416
        return mountState(initialState);
17417
      } finally {
17418
        ReactCurrentDispatcher$1.current = prevDispatcher;
17419
      }
17420
    },
17421
    useDebugValue: function (value, formatterFn) {
17422
      currentHookNameInDev = 'useDebugValue';
17423
      warnInvalidHookAccess();
17424
      mountHookTypesDev();
17425
      return mountDebugValue(value, formatterFn);
17426
    },
17427
    useResponder: function (responder, props) {
17428
      currentHookNameInDev = 'useResponder';
17429
      warnInvalidHookAccess();
17430
      mountHookTypesDev();
17431
      return createResponderListener(responder, props);
17432
    }
17433
  };
17434
  InvalidNestedHooksDispatcherOnUpdateInDEV = {
17435
    readContext: function (context, observedBits) {
17436
      warnInvalidContextAccess();
17437
      return readContext(context, observedBits);
17438
    },
17439
    useCallback: function (callback, deps) {
17440
      currentHookNameInDev = 'useCallback';
17441
      warnInvalidHookAccess();
17442
      updateHookTypesDev();
17443
      return updateCallback(callback, deps);
17444
    },
17445
    useContext: function (context, observedBits) {
17446
      currentHookNameInDev = 'useContext';
17447
      warnInvalidHookAccess();
17448
      updateHookTypesDev();
17449
      return readContext(context, observedBits);
17450
    },
17451
    useEffect: function (create, deps) {
17452
      currentHookNameInDev = 'useEffect';
17453
      warnInvalidHookAccess();
17454
      updateHookTypesDev();
17455
      return updateEffect(create, deps);
17456
    },
17457
    useImperativeHandle: function (ref, create, deps) {
17458
      currentHookNameInDev = 'useImperativeHandle';
17459
      warnInvalidHookAccess();
17460
      updateHookTypesDev();
17461
      return updateImperativeHandle(ref, create, deps);
17462
    },
17463
    useLayoutEffect: function (create, deps) {
17464
      currentHookNameInDev = 'useLayoutEffect';
17465
      warnInvalidHookAccess();
17466
      updateHookTypesDev();
17467
      return updateLayoutEffect(create, deps);
17468
    },
17469
    useMemo: function (create, deps) {
17470
      currentHookNameInDev = 'useMemo';
17471
      warnInvalidHookAccess();
17472
      updateHookTypesDev();
17473
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17474
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17475
17476
      try {
17477
        return updateMemo(create, deps);
17478
      } finally {
17479
        ReactCurrentDispatcher$1.current = prevDispatcher;
17480
      }
17481
    },
17482
    useReducer: function (reducer, initialArg, init) {
17483
      currentHookNameInDev = 'useReducer';
17484
      warnInvalidHookAccess();
17485
      updateHookTypesDev();
17486
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17487
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17488
17489
      try {
17490
        return updateReducer(reducer, initialArg, init);
17491
      } finally {
17492
        ReactCurrentDispatcher$1.current = prevDispatcher;
17493
      }
17494
    },
17495
    useRef: function (initialValue) {
17496
      currentHookNameInDev = 'useRef';
17497
      warnInvalidHookAccess();
17498
      updateHookTypesDev();
17499
      return updateRef(initialValue);
17500
    },
17501
    useState: function (initialState) {
17502
      currentHookNameInDev = 'useState';
17503
      warnInvalidHookAccess();
17504
      updateHookTypesDev();
17505
      var prevDispatcher = ReactCurrentDispatcher$1.current;
17506
      ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17507
17508
      try {
17509
        return updateState(initialState);
17510
      } finally {
17511
        ReactCurrentDispatcher$1.current = prevDispatcher;
17512
      }
17513
    },
17514
    useDebugValue: function (value, formatterFn) {
17515
      currentHookNameInDev = 'useDebugValue';
17516
      warnInvalidHookAccess();
17517
      updateHookTypesDev();
17518
      return updateDebugValue(value, formatterFn);
17519
    },
17520
    useResponder: function (responder, props) {
17521
      currentHookNameInDev = 'useResponder';
17522
      warnInvalidHookAccess();
17523
      updateHookTypesDev();
17524
      return createResponderListener(responder, props);
17525
    }
17526
  };
17527
}
17528
17529
// CommonJS interop named imports.
17530
17531
var now$1 = Scheduler.unstable_now;
17532
var commitTime = 0;
17533
var profilerStartTime = -1;
17534
17535
function getCommitTime() {
17536
  return commitTime;
17537
}
17538
17539
function recordCommitTime() {
17540
  if (!enableProfilerTimer) {
17541
    return;
17542
  }
17543
17544
  commitTime = now$1();
17545
}
17546
17547
function startProfilerTimer(fiber) {
17548
  if (!enableProfilerTimer) {
17549
    return;
17550
  }
17551
17552
  profilerStartTime = now$1();
17553
17554
  if (fiber.actualStartTime < 0) {
17555
    fiber.actualStartTime = now$1();
17556
  }
17557
}
17558
17559
function stopProfilerTimerIfRunning(fiber) {
17560
  if (!enableProfilerTimer) {
17561
    return;
17562
  }
17563
17564
  profilerStartTime = -1;
17565
}
17566
17567
function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
17568
  if (!enableProfilerTimer) {
17569
    return;
17570
  }
17571
17572
  if (profilerStartTime >= 0) {
17573
    var elapsedTime = now$1() - profilerStartTime;
17574
    fiber.actualDuration += elapsedTime;
17575
17576
    if (overrideBaseTime) {
17577
      fiber.selfBaseDuration = elapsedTime;
17578
    }
17579
17580
    profilerStartTime = -1;
17581
  }
17582
}
17583
17584
// This may have been an insertion or a hydration.
17585
17586
var hydrationParentFiber = null;
17587
var nextHydratableInstance = null;
17588
var isHydrating = false;
17589
17590
function warnIfHydrating() {
17591
  {
17592
    !!isHydrating ? warning$1(false, 'We should not be hydrating here. This is a bug in React. Please file a bug.') : void 0;
17593
  }
17594
}
17595
17596
function enterHydrationState(fiber) {
17597
  if (!supportsHydration) {
17598
    return false;
17599
  }
17600
17601
  var parentInstance = fiber.stateNode.containerInfo;
17602
  nextHydratableInstance = getFirstHydratableChild(parentInstance);
17603
  hydrationParentFiber = fiber;
17604
  isHydrating = true;
17605
  return true;
17606
}
17607
17608
function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance) {
17609
  if (!supportsHydration) {
17610
    return false;
17611
  }
17612
17613
  nextHydratableInstance = getNextHydratableSibling(suspenseInstance);
17614
  popToNextHostParent(fiber);
17615
  isHydrating = true;
17616
  return true;
17617
}
17618
17619
function deleteHydratableInstance(returnFiber, instance) {
17620
  {
17621
    switch (returnFiber.tag) {
17622
      case HostRoot:
17623
        didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
17624
        break;
17625
17626
      case HostComponent:
17627
        didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
17628
        break;
17629
    }
17630
  }
17631
17632
  var childToDelete = createFiberFromHostInstanceForDeletion();
17633
  childToDelete.stateNode = instance;
17634
  childToDelete.return = returnFiber;
17635
  childToDelete.effectTag = Deletion; // This might seem like it belongs on progressedFirstDeletion. However,
17636
  // these children are not part of the reconciliation list of children.
17637
  // Even if we abort and rereconcile the children, that will try to hydrate
17638
  // again and the nodes are still in the host tree so these will be
17639
  // recreated.
17640
17641
  if (returnFiber.lastEffect !== null) {
17642
    returnFiber.lastEffect.nextEffect = childToDelete;
17643
    returnFiber.lastEffect = childToDelete;
17644
  } else {
17645
    returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
17646
  }
17647
}
17648
17649
function insertNonHydratedInstance(returnFiber, fiber) {
17650
  fiber.effectTag = fiber.effectTag & ~Hydrating | Placement;
17651
17652
  {
17653
    switch (returnFiber.tag) {
17654
      case HostRoot:
17655
        {
17656
          var parentContainer = returnFiber.stateNode.containerInfo;
17657
17658
          switch (fiber.tag) {
17659
            case HostComponent:
17660
              var type = fiber.type;
17661
              var props = fiber.pendingProps;
17662
              didNotFindHydratableContainerInstance(parentContainer, type, props);
17663
              break;
17664
17665
            case HostText:
17666
              var text = fiber.pendingProps;
17667
              didNotFindHydratableContainerTextInstance(parentContainer, text);
17668
              break;
17669
17670
            case SuspenseComponent:
17671
              
17672
              break;
17673
          }
17674
17675
          break;
17676
        }
17677
17678
      case HostComponent:
17679
        {
17680
          var parentType = returnFiber.type;
17681
          var parentProps = returnFiber.memoizedProps;
17682
          var parentInstance = returnFiber.stateNode;
17683
17684
          switch (fiber.tag) {
17685
            case HostComponent:
17686
              var _type = fiber.type;
17687
              var _props = fiber.pendingProps;
17688
              didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
17689
              break;
17690
17691
            case HostText:
17692
              var _text = fiber.pendingProps;
17693
              didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
17694
              break;
17695
17696
            case SuspenseComponent:
17697
              didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance);
17698
              break;
17699
          }
17700
17701
          break;
17702
        }
17703
17704
      default:
17705
        return;
17706
    }
17707
  }
17708
}
17709
17710
function tryHydrate(fiber, nextInstance) {
17711
  switch (fiber.tag) {
17712
    case HostComponent:
17713
      {
17714
        var type = fiber.type;
17715
        var props = fiber.pendingProps;
17716
        var instance = canHydrateInstance(nextInstance, type, props);
17717
17718
        if (instance !== null) {
17719
          fiber.stateNode = instance;
17720
          return true;
17721
        }
17722
17723
        return false;
17724
      }
17725
17726
    case HostText:
17727
      {
17728
        var text = fiber.pendingProps;
17729
        var textInstance = canHydrateTextInstance(nextInstance, text);
17730
17731
        if (textInstance !== null) {
17732
          fiber.stateNode = textInstance;
17733
          return true;
17734
        }
17735
17736
        return false;
17737
      }
17738
17739
    case SuspenseComponent:
17740
      {
17741
        if (enableSuspenseServerRenderer) {
17742
          var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
17743
17744
          if (suspenseInstance !== null) {
17745
            var suspenseState = {
17746
              dehydrated: suspenseInstance,
17747
              retryTime: Never
17748
            };
17749
            fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber.
17750
            // This simplifies the code for getHostSibling and deleting nodes,
17751
            // since it doesn't have to consider all Suspense boundaries and
17752
            // check if they're dehydrated ones or not.
17753
17754
            var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance);
17755
            dehydratedFragment.return = fiber;
17756
            fiber.child = dehydratedFragment;
17757
            return true;
17758
          }
17759
        }
17760
17761
        return false;
17762
      }
17763
17764
    default:
17765
      return false;
17766
  }
17767
}
17768
17769
function tryToClaimNextHydratableInstance(fiber) {
17770
  if (!isHydrating) {
17771
    return;
17772
  }
17773
17774
  var nextInstance = nextHydratableInstance;
17775
17776
  if (!nextInstance) {
17777
    // Nothing to hydrate. Make it an insertion.
17778
    insertNonHydratedInstance(hydrationParentFiber, fiber);
17779
    isHydrating = false;
17780
    hydrationParentFiber = fiber;
17781
    return;
17782
  }
17783
17784
  var firstAttemptedInstance = nextInstance;
17785
17786
  if (!tryHydrate(fiber, nextInstance)) {
17787
    // If we can't hydrate this instance let's try the next one.
17788
    // We use this as a heuristic. It's based on intuition and not data so it
17789
    // might be flawed or unnecessary.
17790
    nextInstance = getNextHydratableSibling(firstAttemptedInstance);
17791
17792
    if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
17793
      // Nothing to hydrate. Make it an insertion.
17794
      insertNonHydratedInstance(hydrationParentFiber, fiber);
17795
      isHydrating = false;
17796
      hydrationParentFiber = fiber;
17797
      return;
17798
    } // We matched the next one, we'll now assume that the first one was
17799
    // superfluous and we'll delete it. Since we can't eagerly delete it
17800
    // we'll have to schedule a deletion. To do that, this node needs a dummy
17801
    // fiber associated with it.
17802
17803
17804
    deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
17805
  }
17806
17807
  hydrationParentFiber = fiber;
17808
  nextHydratableInstance = getFirstHydratableChild(nextInstance);
17809
}
17810
17811
function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
17812
  if (!supportsHydration) {
17813
    (function () {
17814
      {
17815
        {
17816
          throw ReactError(Error("Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."));
17817
        }
17818
      }
17819
    })();
17820
  }
17821
17822
  var instance = fiber.stateNode;
17823
  var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber); // TODO: Type this specific to this type of component.
17824
17825
  fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
17826
  // is a new ref we mark this as an update.
17827
17828
  if (updatePayload !== null) {
17829
    return true;
17830
  }
17831
17832
  return false;
17833
}
17834
17835
function prepareToHydrateHostTextInstance(fiber) {
17836
  if (!supportsHydration) {
17837
    (function () {
17838
      {
17839
        {
17840
          throw ReactError(Error("Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."));
17841
        }
17842
      }
17843
    })();
17844
  }
17845
17846
  var textInstance = fiber.stateNode;
17847
  var textContent = fiber.memoizedProps;
17848
  var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
17849
17850
  {
17851
    if (shouldUpdate) {
17852
      // We assume that prepareToHydrateHostTextInstance is called in a context where the
17853
      // hydration parent is the parent host component of this host text.
17854
      var returnFiber = hydrationParentFiber;
17855
17856
      if (returnFiber !== null) {
17857
        switch (returnFiber.tag) {
17858
          case HostRoot:
17859
            {
17860
              var parentContainer = returnFiber.stateNode.containerInfo;
17861
              didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
17862
              break;
17863
            }
17864
17865
          case HostComponent:
17866
            {
17867
              var parentType = returnFiber.type;
17868
              var parentProps = returnFiber.memoizedProps;
17869
              var parentInstance = returnFiber.stateNode;
17870
              didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
17871
              break;
17872
            }
17873
        }
17874
      }
17875
    }
17876
  }
17877
17878
  return shouldUpdate;
17879
}
17880
17881
function prepareToHydrateHostSuspenseInstance(fiber) {
17882
  if (!supportsHydration) {
17883
    (function () {
17884
      {
17885
        {
17886
          throw ReactError(Error("Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."));
17887
        }
17888
      }
17889
    })();
17890
  }
17891
17892
  var suspenseState = fiber.memoizedState;
17893
  var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
17894
17895
  (function () {
17896
    if (!suspenseInstance) {
17897
      {
17898
        throw ReactError(Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."));
17899
      }
17900
    }
17901
  })();
17902
17903
  hydrateSuspenseInstance(suspenseInstance, fiber);
17904
}
17905
17906
function skipPastDehydratedSuspenseInstance(fiber) {
17907
  if (!supportsHydration) {
17908
    (function () {
17909
      {
17910
        {
17911
          throw ReactError(Error("Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."));
17912
        }
17913
      }
17914
    })();
17915
  }
17916
17917
  var suspenseState = fiber.memoizedState;
17918
  var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
17919
17920
  if (suspenseInstance === null) {
17921
    // This Suspense boundary was hydrated without a match.
17922
    return nextHydratableInstance;
17923
  }
17924
17925
  return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
17926
}
17927
17928
function popToNextHostParent(fiber) {
17929
  var parent = fiber.return;
17930
17931
  while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
17932
    parent = parent.return;
17933
  }
17934
17935
  hydrationParentFiber = parent;
17936
}
17937
17938
function popHydrationState(fiber) {
17939
  if (!supportsHydration) {
17940
    return false;
17941
  }
17942
17943
  if (fiber !== hydrationParentFiber) {
17944
    // We're deeper than the current hydration context, inside an inserted
17945
    // tree.
17946
    return false;
17947
  }
17948
17949
  if (!isHydrating) {
17950
    // If we're not currently hydrating but we're in a hydration context, then
17951
    // we were an insertion and now need to pop up reenter hydration of our
17952
    // siblings.
17953
    popToNextHostParent(fiber);
17954
    isHydrating = true;
17955
    return false;
17956
  }
17957
17958
  var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now.
17959
  // We only do this deeper than head and body since they tend to have random
17960
  // other nodes in them. We also ignore components with pure text content in
17961
  // side of them.
17962
  // TODO: Better heuristic.
17963
17964
  if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
17965
    var nextInstance = nextHydratableInstance;
17966
17967
    while (nextInstance) {
17968
      deleteHydratableInstance(fiber, nextInstance);
17969
      nextInstance = getNextHydratableSibling(nextInstance);
17970
    }
17971
  }
17972
17973
  popToNextHostParent(fiber);
17974
17975
  if (fiber.tag === SuspenseComponent) {
17976
    nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
17977
  } else {
17978
    nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
17979
  }
17980
17981
  return true;
17982
}
17983
17984
function resetHydrationState() {
17985
  if (!supportsHydration) {
17986
    return;
17987
  }
17988
17989
  hydrationParentFiber = null;
17990
  nextHydratableInstance = null;
17991
  isHydrating = false;
17992
}
17993
17994
var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
17995
var didReceiveUpdate = false;
17996
var didWarnAboutBadClass;
17997
var didWarnAboutModulePatternComponent;
17998
var didWarnAboutContextTypeOnFunctionComponent;
17999
var didWarnAboutGetDerivedStateOnFunctionComponent;
18000
var didWarnAboutFunctionRefs;
18001
var didWarnAboutReassigningProps;
18002
var didWarnAboutMaxDuration;
18003
var didWarnAboutRevealOrder;
18004
var didWarnAboutTailOptions;
18005
var didWarnAboutDefaultPropsOnFunctionComponent;
18006
18007
{
18008
  didWarnAboutBadClass = {};
18009
  didWarnAboutModulePatternComponent = {};
18010
  didWarnAboutContextTypeOnFunctionComponent = {};
18011
  didWarnAboutGetDerivedStateOnFunctionComponent = {};
18012
  didWarnAboutFunctionRefs = {};
18013
  didWarnAboutReassigningProps = false;
18014
  didWarnAboutMaxDuration = false;
18015
  didWarnAboutRevealOrder = {};
18016
  didWarnAboutTailOptions = {};
18017
  didWarnAboutDefaultPropsOnFunctionComponent = {};
18018
}
18019
18020
function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) {
18021
  if (current$$1 === null) {
18022
    // If this is a fresh new component that hasn't been rendered yet, we
18023
    // won't update its child set by applying minimal side-effects. Instead,
18024
    // we will add them all to the child before it gets rendered. That means
18025
    // we can optimize this reconciliation pass by not tracking side-effects.
18026
    workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18027
  } else {
18028
    // If the current child is the same as the work in progress, it means that
18029
    // we haven't yet started any work on these children. Therefore, we use
18030
    // the clone algorithm to create a copy of all the current children.
18031
    // If we had any progressed work already, that is invalid at this point so
18032
    // let's throw it out.
18033
    workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime);
18034
  }
18035
}
18036
18037
function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) {
18038
  // This function is fork of reconcileChildren. It's used in cases where we
18039
  // want to reconcile without matching against the existing set. This has the
18040
  // effect of all current children being unmounted; even if the type and key
18041
  // are the same, the old child is unmounted and a new child is created.
18042
  //
18043
  // To do this, we're going to go through the reconcile algorithm twice. In
18044
  // the first pass, we schedule a deletion for all the current children by
18045
  // passing null.
18046
  workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime); // In the second pass, we mount the new children. The trick here is that we
18047
  // pass null in place of where we usually pass the current child set. This has
18048
  // the effect of remounting all children regardless of whether their their
18049
  // identity matches.
18050
18051
  workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18052
}
18053
18054
function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18055
  // TODO: current can be non-null here even if the component
18056
  // hasn't yet mounted. This happens after the first render suspends.
18057
  // We'll need to figure out if this is fine or can cause issues.
18058
  {
18059
    if (workInProgress.type !== workInProgress.elementType) {
18060
      // Lazy component props can't be validated in createElement
18061
      // because they're only guaranteed to be resolved here.
18062
      var innerPropTypes = Component.propTypes;
18063
18064
      if (innerPropTypes) {
18065
        checkPropTypes(innerPropTypes, nextProps, // Resolved props
18066
        'prop', getComponentName(Component), getCurrentFiberStackInDev);
18067
      }
18068
    }
18069
  }
18070
18071
  var render = Component.render;
18072
  var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent
18073
18074
  var nextChildren;
18075
  prepareToReadContext(workInProgress, renderExpirationTime);
18076
18077
  {
18078
    ReactCurrentOwner$3.current = workInProgress;
18079
    setCurrentPhase('render');
18080
    nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
18081
18082
    if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18083
      // Only double-render components with Hooks
18084
      if (workInProgress.memoizedState !== null) {
18085
        nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
18086
      }
18087
    }
18088
18089
    setCurrentPhase(null);
18090
  }
18091
18092
  if (current$$1 !== null && !didReceiveUpdate) {
18093
    bailoutHooks(current$$1, workInProgress, renderExpirationTime);
18094
    return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18095
  } // React DevTools reads this flag.
18096
18097
18098
  workInProgress.effectTag |= PerformedWork;
18099
  reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18100
  return workInProgress.child;
18101
}
18102
18103
function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
18104
  if (current$$1 === null) {
18105
    var type = Component.type;
18106
18107
    if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
18108
    Component.defaultProps === undefined) {
18109
      var resolvedType = type;
18110
18111
      {
18112
        resolvedType = resolveFunctionForHotReloading(type);
18113
      } // If this is a plain function component without default props,
18114
      // and with only the default shallow comparison, we upgrade it
18115
      // to a SimpleMemoComponent to allow fast path updates.
18116
18117
18118
      workInProgress.tag = SimpleMemoComponent;
18119
      workInProgress.type = resolvedType;
18120
18121
      {
18122
        validateFunctionComponentInDev(workInProgress, type);
18123
      }
18124
18125
      return updateSimpleMemoComponent(current$$1, workInProgress, resolvedType, nextProps, updateExpirationTime, renderExpirationTime);
18126
    }
18127
18128
    {
18129
      var innerPropTypes = type.propTypes;
18130
18131
      if (innerPropTypes) {
18132
        // Inner memo component props aren't currently validated in createElement.
18133
        // We could move it there, but we'd still need this for lazy code path.
18134
        checkPropTypes(innerPropTypes, nextProps, // Resolved props
18135
        'prop', getComponentName(type), getCurrentFiberStackInDev);
18136
      }
18137
    }
18138
18139
    var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
18140
    child.ref = workInProgress.ref;
18141
    child.return = workInProgress;
18142
    workInProgress.child = child;
18143
    return child;
18144
  }
18145
18146
  {
18147
    var _type = Component.type;
18148
    var _innerPropTypes = _type.propTypes;
18149
18150
    if (_innerPropTypes) {
18151
      // Inner memo component props aren't currently validated in createElement.
18152
      // We could move it there, but we'd still need this for lazy code path.
18153
      checkPropTypes(_innerPropTypes, nextProps, // Resolved props
18154
      'prop', getComponentName(_type), getCurrentFiberStackInDev);
18155
    }
18156
  }
18157
18158
  var currentChild = current$$1.child; // This is always exactly one child
18159
18160
  if (updateExpirationTime < renderExpirationTime) {
18161
    // This will be the props with resolved defaultProps,
18162
    // unlike current.memoizedProps which will be the unresolved ones.
18163
    var prevProps = currentChild.memoizedProps; // Default to shallow comparison
18164
18165
    var compare = Component.compare;
18166
    compare = compare !== null ? compare : shallowEqual;
18167
18168
    if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
18169
      return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18170
    }
18171
  } // React DevTools reads this flag.
18172
18173
18174
  workInProgress.effectTag |= PerformedWork;
18175
  var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
18176
  newChild.ref = workInProgress.ref;
18177
  newChild.return = workInProgress;
18178
  workInProgress.child = newChild;
18179
  return newChild;
18180
}
18181
18182
function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
18183
  // TODO: current can be non-null here even if the component
18184
  // hasn't yet mounted. This happens when the inner render suspends.
18185
  // We'll need to figure out if this is fine or can cause issues.
18186
  {
18187
    if (workInProgress.type !== workInProgress.elementType) {
18188
      // Lazy component props can't be validated in createElement
18189
      // because they're only guaranteed to be resolved here.
18190
      var outerMemoType = workInProgress.elementType;
18191
18192
      if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
18193
        // We warn when you define propTypes on lazy()
18194
        // so let's just skip over it to find memo() outer wrapper.
18195
        // Inner props for memo are validated later.
18196
        outerMemoType = refineResolvedLazyComponent(outerMemoType);
18197
      }
18198
18199
      var outerPropTypes = outerMemoType && outerMemoType.propTypes;
18200
18201
      if (outerPropTypes) {
18202
        checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
18203
        'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
18204
      } // Inner propTypes will be validated in the function component path.
18205
18206
    }
18207
  }
18208
18209
  if (current$$1 !== null) {
18210
    var prevProps = current$$1.memoizedProps;
18211
18212
    if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload:
18213
    workInProgress.type === current$$1.type)) {
18214
      didReceiveUpdate = false;
18215
18216
      if (updateExpirationTime < renderExpirationTime) {
18217
        return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18218
      }
18219
    }
18220
  }
18221
18222
  return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
18223
}
18224
18225
function updateFragment(current$$1, workInProgress, renderExpirationTime) {
18226
  var nextChildren = workInProgress.pendingProps;
18227
  reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18228
  return workInProgress.child;
18229
}
18230
18231
function updateMode(current$$1, workInProgress, renderExpirationTime) {
18232
  var nextChildren = workInProgress.pendingProps.children;
18233
  reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18234
  return workInProgress.child;
18235
}
18236
18237
function updateProfiler(current$$1, workInProgress, renderExpirationTime) {
18238
  if (enableProfilerTimer) {
18239
    workInProgress.effectTag |= Update;
18240
  }
18241
18242
  var nextProps = workInProgress.pendingProps;
18243
  var nextChildren = nextProps.children;
18244
  reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18245
  return workInProgress.child;
18246
}
18247
18248
function markRef(current$$1, workInProgress) {
18249
  var ref = workInProgress.ref;
18250
18251
  if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) {
18252
    // Schedule a Ref effect
18253
    workInProgress.effectTag |= Ref;
18254
  }
18255
}
18256
18257
function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18258
  {
18259
    if (workInProgress.type !== workInProgress.elementType) {
18260
      // Lazy component props can't be validated in createElement
18261
      // because they're only guaranteed to be resolved here.
18262
      var innerPropTypes = Component.propTypes;
18263
18264
      if (innerPropTypes) {
18265
        checkPropTypes(innerPropTypes, nextProps, // Resolved props
18266
        'prop', getComponentName(Component), getCurrentFiberStackInDev);
18267
      }
18268
    }
18269
  }
18270
18271
  var context;
18272
18273
  if (!disableLegacyContext) {
18274
    var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
18275
    context = getMaskedContext(workInProgress, unmaskedContext);
18276
  }
18277
18278
  var nextChildren;
18279
  prepareToReadContext(workInProgress, renderExpirationTime);
18280
18281
  {
18282
    ReactCurrentOwner$3.current = workInProgress;
18283
    setCurrentPhase('render');
18284
    nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
18285
18286
    if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18287
      // Only double-render components with Hooks
18288
      if (workInProgress.memoizedState !== null) {
18289
        nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
18290
      }
18291
    }
18292
18293
    setCurrentPhase(null);
18294
  }
18295
18296
  if (current$$1 !== null && !didReceiveUpdate) {
18297
    bailoutHooks(current$$1, workInProgress, renderExpirationTime);
18298
    return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18299
  } // React DevTools reads this flag.
18300
18301
18302
  workInProgress.effectTag |= PerformedWork;
18303
  reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18304
  return workInProgress.child;
18305
}
18306
18307
function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18308
  {
18309
    if (workInProgress.type !== workInProgress.elementType) {
18310
      // Lazy component props can't be validated in createElement
18311
      // because they're only guaranteed to be resolved here.
18312
      var innerPropTypes = Component.propTypes;
18313
18314
      if (innerPropTypes) {
18315
        checkPropTypes(innerPropTypes, nextProps, // Resolved props
18316
        'prop', getComponentName(Component), getCurrentFiberStackInDev);
18317
      }
18318
    }
18319
  } // Push context providers early to prevent context stack mismatches.
18320
  // During mounting we don't know the child context yet as the instance doesn't exist.
18321
  // We will invalidate the child context in finishClassComponent() right after rendering.
18322
18323
18324
  var hasContext;
18325
18326
  if (isContextProvider(Component)) {
18327
    hasContext = true;
18328
    pushContextProvider(workInProgress);
18329
  } else {
18330
    hasContext = false;
18331
  }
18332
18333
  prepareToReadContext(workInProgress, renderExpirationTime);
18334
  var instance = workInProgress.stateNode;
18335
  var shouldUpdate;
18336
18337
  if (instance === null) {
18338
    if (current$$1 !== null) {
18339
      // An class component without an instance only mounts if it suspended
18340
      // inside a non- concurrent tree, in an inconsistent state. We want to
18341
      // tree it like a new mount, even though an empty version of it already
18342
      // committed. Disconnect the alternate pointers.
18343
      current$$1.alternate = null;
18344
      workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18345
18346
      workInProgress.effectTag |= Placement;
18347
    } // In the initial pass we might need to construct the instance.
18348
18349
18350
    constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18351
    mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18352
    shouldUpdate = true;
18353
  } else if (current$$1 === null) {
18354
    // In a resume, we'll already have an instance we can reuse.
18355
    shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18356
  } else {
18357
    shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
18358
  }
18359
18360
  var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
18361
18362
  {
18363
    var inst = workInProgress.stateNode;
18364
18365
    if (inst.props !== nextProps) {
18366
      !didWarnAboutReassigningProps ? warning$1(false, 'It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentName(workInProgress.type) || 'a component') : void 0;
18367
      didWarnAboutReassigningProps = true;
18368
    }
18369
  }
18370
18371
  return nextUnitOfWork;
18372
}
18373
18374
function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
18375
  // Refs should update even if shouldComponentUpdate returns false
18376
  markRef(current$$1, workInProgress);
18377
  var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
18378
18379
  if (!shouldUpdate && !didCaptureError) {
18380
    // Context providers should defer to sCU for rendering
18381
    if (hasContext) {
18382
      invalidateContextProvider(workInProgress, Component, false);
18383
    }
18384
18385
    return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18386
  }
18387
18388
  var instance = workInProgress.stateNode; // Rerender
18389
18390
  ReactCurrentOwner$3.current = workInProgress;
18391
  var nextChildren;
18392
18393
  if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
18394
    // If we captured an error, but getDerivedStateFrom catch is not defined,
18395
    // unmount all the children. componentDidCatch will schedule an update to
18396
    // re-render a fallback. This is temporary until we migrate everyone to
18397
    // the new API.
18398
    // TODO: Warn in a future release.
18399
    nextChildren = null;
18400
18401
    if (enableProfilerTimer) {
18402
      stopProfilerTimerIfRunning(workInProgress);
18403
    }
18404
  } else {
18405
    {
18406
      setCurrentPhase('render');
18407
      nextChildren = instance.render();
18408
18409
      if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18410
        instance.render();
18411
      }
18412
18413
      setCurrentPhase(null);
18414
    }
18415
  } // React DevTools reads this flag.
18416
18417
18418
  workInProgress.effectTag |= PerformedWork;
18419
18420
  if (current$$1 !== null && didCaptureError) {
18421
    // If we're recovering from an error, reconcile without reusing any of
18422
    // the existing children. Conceptually, the normal children and the children
18423
    // that are shown on error are two different sets, so we shouldn't reuse
18424
    // normal children even if their identities match.
18425
    forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime);
18426
  } else {
18427
    reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18428
  } // Memoize state using the values we just used to render.
18429
  // TODO: Restructure so we never read values from the instance.
18430
18431
18432
  workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.
18433
18434
  if (hasContext) {
18435
    invalidateContextProvider(workInProgress, Component, true);
18436
  }
18437
18438
  return workInProgress.child;
18439
}
18440
18441
function pushHostRootContext(workInProgress) {
18442
  var root = workInProgress.stateNode;
18443
18444
  if (root.pendingContext) {
18445
    pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
18446
  } else if (root.context) {
18447
    // Should always be set
18448
    pushTopLevelContextObject(workInProgress, root.context, false);
18449
  }
18450
18451
  pushHostContainer(workInProgress, root.containerInfo);
18452
}
18453
18454
function updateHostRoot(current$$1, workInProgress, renderExpirationTime) {
18455
  pushHostRootContext(workInProgress);
18456
  var updateQueue = workInProgress.updateQueue;
18457
18458
  (function () {
18459
    if (!(updateQueue !== null)) {
18460
      {
18461
        throw ReactError(Error("If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue."));
18462
      }
18463
    }
18464
  })();
18465
18466
  var nextProps = workInProgress.pendingProps;
18467
  var prevState = workInProgress.memoizedState;
18468
  var prevChildren = prevState !== null ? prevState.element : null;
18469
  processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
18470
  var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property
18471
  // being called "element".
18472
18473
  var nextChildren = nextState.element;
18474
18475
  if (nextChildren === prevChildren) {
18476
    // If the state is the same as before, that's a bailout because we had
18477
    // no work that expires at this time.
18478
    resetHydrationState();
18479
    return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18480
  }
18481
18482
  var root = workInProgress.stateNode;
18483
18484
  if (root.hydrate && enterHydrationState(workInProgress)) {
18485
    // If we don't have any current children this might be the first pass.
18486
    // We always try to hydrate. If this isn't a hydration pass there won't
18487
    // be any children to hydrate which is effectively the same thing as
18488
    // not hydrating.
18489
    var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18490
    workInProgress.child = child;
18491
    var node = child;
18492
18493
    while (node) {
18494
      // Mark each child as hydrating. This is a fast path to know whether this
18495
      // tree is part of a hydrating tree. This is used to determine if a child
18496
      // node has fully mounted yet, and for scheduling event replaying.
18497
      // Conceptually this is similar to Placement in that a new subtree is
18498
      // inserted into the React tree here. It just happens to not need DOM
18499
      // mutations because it already exists.
18500
      node.effectTag = node.effectTag & ~Placement | Hydrating;
18501
      node = node.sibling;
18502
    }
18503
  } else {
18504
    // Otherwise reset hydration state in case we aborted and resumed another
18505
    // root.
18506
    reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18507
    resetHydrationState();
18508
  }
18509
18510
  return workInProgress.child;
18511
}
18512
18513
function updateHostComponent(current$$1, workInProgress, renderExpirationTime) {
18514
  pushHostContext(workInProgress);
18515
18516
  if (current$$1 === null) {
18517
    tryToClaimNextHydratableInstance(workInProgress);
18518
  }
18519
18520
  var type = workInProgress.type;
18521
  var nextProps = workInProgress.pendingProps;
18522
  var prevProps = current$$1 !== null ? current$$1.memoizedProps : null;
18523
  var nextChildren = nextProps.children;
18524
  var isDirectTextChild = shouldSetTextContent(type, nextProps);
18525
18526
  if (isDirectTextChild) {
18527
    // We special case a direct text child of a host node. This is a common
18528
    // case. We won't handle it as a reified child. We will instead handle
18529
    // this in the host environment that also have access to this prop. That
18530
    // avoids allocating another HostText fiber and traversing it.
18531
    nextChildren = null;
18532
  } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
18533
    // If we're switching from a direct text child to a normal child, or to
18534
    // empty, we need to schedule the text content to be reset.
18535
    workInProgress.effectTag |= ContentReset;
18536
  }
18537
18538
  markRef(current$$1, workInProgress); // Check the host config to see if the children are offscreen/hidden.
18539
18540
  if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(type, nextProps)) {
18541
    if (enableSchedulerTracing) {
18542
      markSpawnedWork(Never);
18543
    } // Schedule this fiber to re-render at offscreen priority. Then bailout.
18544
18545
18546
    workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
18547
    return null;
18548
  }
18549
18550
  reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18551
  return workInProgress.child;
18552
}
18553
18554
function updateHostText(current$$1, workInProgress) {
18555
  if (current$$1 === null) {
18556
    tryToClaimNextHydratableInstance(workInProgress);
18557
  } // Nothing to do here. This is terminal. We'll do the completion step
18558
  // immediately after.
18559
18560
18561
  return null;
18562
}
18563
18564
function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
18565
  if (_current !== null) {
18566
    // An lazy component only mounts if it suspended inside a non-
18567
    // concurrent tree, in an inconsistent state. We want to treat it like
18568
    // a new mount, even though an empty version of it already committed.
18569
    // Disconnect the alternate pointers.
18570
    _current.alternate = null;
18571
    workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18572
18573
    workInProgress.effectTag |= Placement;
18574
  }
18575
18576
  var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet.
18577
  // Cancel and resume right after we know the tag.
18578
18579
  cancelWorkTimer(workInProgress);
18580
  var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type.
18581
18582
  workInProgress.type = Component;
18583
  var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
18584
  startWorkTimer(workInProgress);
18585
  var resolvedProps = resolveDefaultProps(Component, props);
18586
  var child;
18587
18588
  switch (resolvedTag) {
18589
    case FunctionComponent:
18590
      {
18591
        {
18592
          validateFunctionComponentInDev(workInProgress, Component);
18593
          workInProgress.type = Component = resolveFunctionForHotReloading(Component);
18594
        }
18595
18596
        child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18597
        break;
18598
      }
18599
18600
    case ClassComponent:
18601
      {
18602
        {
18603
          workInProgress.type = Component = resolveClassForHotReloading(Component);
18604
        }
18605
18606
        child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18607
        break;
18608
      }
18609
18610
    case ForwardRef:
18611
      {
18612
        {
18613
          workInProgress.type = Component = resolveForwardRefForHotReloading(Component);
18614
        }
18615
18616
        child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18617
        break;
18618
      }
18619
18620
    case MemoComponent:
18621
      {
18622
        {
18623
          if (workInProgress.type !== workInProgress.elementType) {
18624
            var outerPropTypes = Component.propTypes;
18625
18626
            if (outerPropTypes) {
18627
              checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only
18628
              'prop', getComponentName(Component), getCurrentFiberStackInDev);
18629
            }
18630
          }
18631
        }
18632
18633
        child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
18634
        updateExpirationTime, renderExpirationTime);
18635
        break;
18636
      }
18637
18638
    default:
18639
      {
18640
        var hint = '';
18641
18642
        {
18643
          if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
18644
            hint = ' Did you wrap a component in React.lazy() more than once?';
18645
          }
18646
        } // This message intentionally doesn't mention ForwardRef or MemoComponent
18647
        // because the fact that it's a separate type of work is an
18648
        // implementation detail.
18649
18650
18651
        (function () {
18652
          {
18653
            {
18654
              throw ReactError(Error("Element type is invalid. Received a promise that resolves to: " + Component + ". Lazy element type must resolve to a class or function." + hint));
18655
            }
18656
          }
18657
        })();
18658
      }
18659
  }
18660
18661
  return child;
18662
}
18663
18664
function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
18665
  if (_current !== null) {
18666
    // An incomplete component only mounts if it suspended inside a non-
18667
    // concurrent tree, in an inconsistent state. We want to treat it like
18668
    // a new mount, even though an empty version of it already committed.
18669
    // Disconnect the alternate pointers.
18670
    _current.alternate = null;
18671
    workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18672
18673
    workInProgress.effectTag |= Placement;
18674
  } // Promote the fiber to a class and try rendering again.
18675
18676
18677
  workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`
18678
  // Push context providers early to prevent context stack mismatches.
18679
  // During mounting we don't know the child context yet as the instance doesn't exist.
18680
  // We will invalidate the child context in finishClassComponent() right after rendering.
18681
18682
  var hasContext;
18683
18684
  if (isContextProvider(Component)) {
18685
    hasContext = true;
18686
    pushContextProvider(workInProgress);
18687
  } else {
18688
    hasContext = false;
18689
  }
18690
18691
  prepareToReadContext(workInProgress, renderExpirationTime);
18692
  constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18693
  mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18694
  return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
18695
}
18696
18697
function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
18698
  if (_current !== null) {
18699
    // An indeterminate component only mounts if it suspended inside a non-
18700
    // concurrent tree, in an inconsistent state. We want to treat it like
18701
    // a new mount, even though an empty version of it already committed.
18702
    // Disconnect the alternate pointers.
18703
    _current.alternate = null;
18704
    workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18705
18706
    workInProgress.effectTag |= Placement;
18707
  }
18708
18709
  var props = workInProgress.pendingProps;
18710
  var context;
18711
18712
  if (!disableLegacyContext) {
18713
    var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
18714
    context = getMaskedContext(workInProgress, unmaskedContext);
18715
  }
18716
18717
  prepareToReadContext(workInProgress, renderExpirationTime);
18718
  var value;
18719
18720
  {
18721
    if (Component.prototype && typeof Component.prototype.render === 'function') {
18722
      var componentName = getComponentName(Component) || 'Unknown';
18723
18724
      if (!didWarnAboutBadClass[componentName]) {
18725
        warningWithoutStack$1(false, "The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);
18726
        didWarnAboutBadClass[componentName] = true;
18727
      }
18728
    }
18729
18730
    if (workInProgress.mode & StrictMode) {
18731
      ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
18732
    }
18733
18734
    ReactCurrentOwner$3.current = workInProgress;
18735
    value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
18736
  } // React DevTools reads this flag.
18737
18738
18739
  workInProgress.effectTag |= PerformedWork;
18740
18741
  if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
18742
    {
18743
      var _componentName = getComponentName(Component) || 'Unknown';
18744
18745
      if (!didWarnAboutModulePatternComponent[_componentName]) {
18746
        warningWithoutStack$1(false, 'The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);
18747
        didWarnAboutModulePatternComponent[_componentName] = true;
18748
      }
18749
    } // Proceed under the assumption that this is a class instance
18750
18751
18752
    workInProgress.tag = ClassComponent; // Throw out any hooks that were used.
18753
18754
    resetHooks(); // Push context providers early to prevent context stack mismatches.
18755
    // During mounting we don't know the child context yet as the instance doesn't exist.
18756
    // We will invalidate the child context in finishClassComponent() right after rendering.
18757
18758
    var hasContext = false;
18759
18760
    if (isContextProvider(Component)) {
18761
      hasContext = true;
18762
      pushContextProvider(workInProgress);
18763
    } else {
18764
      hasContext = false;
18765
    }
18766
18767
    workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
18768
    var getDerivedStateFromProps = Component.getDerivedStateFromProps;
18769
18770
    if (typeof getDerivedStateFromProps === 'function') {
18771
      applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
18772
    }
18773
18774
    adoptClassInstance(workInProgress, value);
18775
    mountClassInstance(workInProgress, Component, props, renderExpirationTime);
18776
    return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
18777
  } else {
18778
    // Proceed under the assumption that this is a function component
18779
    workInProgress.tag = FunctionComponent;
18780
18781
    {
18782
      if (disableLegacyContext && Component.contextTypes) {
18783
        warningWithoutStack$1(false, '%s uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with React.useContext() instead.', getComponentName(Component) || 'Unknown');
18784
      }
18785
18786
      if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18787
        // Only double-render components with Hooks
18788
        if (workInProgress.memoizedState !== null) {
18789
          value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
18790
        }
18791
      }
18792
    }
18793
18794
    reconcileChildren(null, workInProgress, value, renderExpirationTime);
18795
18796
    {
18797
      validateFunctionComponentInDev(workInProgress, Component);
18798
    }
18799
18800
    return workInProgress.child;
18801
  }
18802
}
18803
18804
function validateFunctionComponentInDev(workInProgress, Component) {
18805
  if (Component) {
18806
    !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
18807
  }
18808
18809
  if (workInProgress.ref !== null) {
18810
    var info = '';
18811
    var ownerName = getCurrentFiberOwnerNameInDevOrNull();
18812
18813
    if (ownerName) {
18814
      info += '\n\nCheck the render method of `' + ownerName + '`.';
18815
    }
18816
18817
    var warningKey = ownerName || workInProgress._debugID || '';
18818
    var debugSource = workInProgress._debugSource;
18819
18820
    if (debugSource) {
18821
      warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
18822
    }
18823
18824
    if (!didWarnAboutFunctionRefs[warningKey]) {
18825
      didWarnAboutFunctionRefs[warningKey] = true;
18826
      warning$1(false, 'Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info);
18827
    }
18828
  }
18829
18830
  if (warnAboutDefaultPropsOnFunctionComponents && Component.defaultProps !== undefined) {
18831
    var componentName = getComponentName(Component) || 'Unknown';
18832
18833
    if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
18834
      warningWithoutStack$1(false, '%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);
18835
      didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
18836
    }
18837
  }
18838
18839
  if (typeof Component.getDerivedStateFromProps === 'function') {
18840
    var _componentName2 = getComponentName(Component) || 'Unknown';
18841
18842
    if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2]) {
18843
      warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', _componentName2);
18844
      didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2] = true;
18845
    }
18846
  }
18847
18848
  if (typeof Component.contextType === 'object' && Component.contextType !== null) {
18849
    var _componentName3 = getComponentName(Component) || 'Unknown';
18850
18851
    if (!didWarnAboutContextTypeOnFunctionComponent[_componentName3]) {
18852
      warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName3);
18853
      didWarnAboutContextTypeOnFunctionComponent[_componentName3] = true;
18854
    }
18855
  }
18856
}
18857
18858
var SUSPENDED_MARKER = {
18859
  dehydrated: null,
18860
  retryTime: Never
18861
};
18862
18863
function shouldRemainOnFallback(suspenseContext, current$$1, workInProgress) {
18864
  // If the context is telling us that we should show a fallback, and we're not
18865
  // already showing content, then we should show the fallback instead.
18866
  return hasSuspenseContext(suspenseContext, ForceSuspenseFallback) && (current$$1 === null || current$$1.memoizedState !== null);
18867
}
18868
18869
function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
18870
  var mode = workInProgress.mode;
18871
  var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.
18872
18873
  {
18874
    if (shouldSuspend(workInProgress)) {
18875
      workInProgress.effectTag |= DidCapture;
18876
    }
18877
  }
18878
18879
  var suspenseContext = suspenseStackCursor.current;
18880
  var nextDidTimeout = false;
18881
  var didSuspend = (workInProgress.effectTag & DidCapture) !== NoEffect;
18882
18883
  if (didSuspend || shouldRemainOnFallback(suspenseContext, current$$1, workInProgress)) {
18884
    // Something in this boundary's subtree already suspended. Switch to
18885
    // rendering the fallback children.
18886
    nextDidTimeout = true;
18887
    workInProgress.effectTag &= ~DidCapture;
18888
  } else {
18889
    // Attempting the main content
18890
    if (current$$1 === null || current$$1.memoizedState !== null) {
18891
      // This is a new mount or this boundary is already showing a fallback state.
18892
      // Mark this subtree context as having at least one invisible parent that could
18893
      // handle the fallback state.
18894
      // Boundaries without fallbacks or should be avoided are not considered since
18895
      // they cannot handle preferred fallback states.
18896
      if (nextProps.fallback !== undefined && nextProps.unstable_avoidThisFallback !== true) {
18897
        suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
18898
      }
18899
    }
18900
  }
18901
18902
  suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
18903
  pushSuspenseContext(workInProgress, suspenseContext);
18904
18905
  {
18906
    if ('maxDuration' in nextProps) {
18907
      if (!didWarnAboutMaxDuration) {
18908
        didWarnAboutMaxDuration = true;
18909
        warning$1(false, 'maxDuration has been removed from React. ' + 'Remove the maxDuration prop.');
18910
      }
18911
    }
18912
  } // This next part is a bit confusing. If the children timeout, we switch to
18913
  // showing the fallback children in place of the "primary" children.
18914
  // However, we don't want to delete the primary children because then their
18915
  // state will be lost (both the React state and the host state, e.g.
18916
  // uncontrolled form inputs). Instead we keep them mounted and hide them.
18917
  // Both the fallback children AND the primary children are rendered at the
18918
  // same time. Once the primary children are un-suspended, we can delete
18919
  // the fallback children — don't need to preserve their state.
18920
  //
18921
  // The two sets of children are siblings in the host environment, but
18922
  // semantically, for purposes of reconciliation, they are two separate sets.
18923
  // So we store them using two fragment fibers.
18924
  //
18925
  // However, we want to avoid allocating extra fibers for every placeholder.
18926
  // They're only necessary when the children time out, because that's the
18927
  // only time when both sets are mounted.
18928
  //
18929
  // So, the extra fragment fibers are only used if the children time out.
18930
  // Otherwise, we render the primary children directly. This requires some
18931
  // custom reconciliation logic to preserve the state of the primary
18932
  // children. It's essentially a very basic form of re-parenting.
18933
18934
18935
  if (current$$1 === null) {
18936
    if (enableSuspenseServerRenderer) {
18937
      // If we're currently hydrating, try to hydrate this boundary.
18938
      // But only if this has a fallback.
18939
      if (nextProps.fallback !== undefined) {
18940
        tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component.
18941
18942
        var suspenseState = workInProgress.memoizedState;
18943
18944
        if (suspenseState !== null) {
18945
          var dehydrated = suspenseState.dehydrated;
18946
18947
          if (dehydrated !== null) {
18948
            return mountDehydratedSuspenseComponent(workInProgress, dehydrated, renderExpirationTime);
18949
          }
18950
        }
18951
      }
18952
    } // This is the initial mount. This branch is pretty simple because there's
18953
    // no previous state that needs to be preserved.
18954
18955
18956
    if (nextDidTimeout) {
18957
      // Mount separate fragments for primary and fallback children.
18958
      var nextFallbackChildren = nextProps.fallback;
18959
      var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
18960
      primaryChildFragment.return = workInProgress;
18961
18962
      if ((workInProgress.mode & BatchedMode) === NoMode) {
18963
        // Outside of batched mode, we commit the effects from the
18964
        // partially completed, timed-out tree, too.
18965
        var progressedState = workInProgress.memoizedState;
18966
        var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
18967
        primaryChildFragment.child = progressedPrimaryChild;
18968
        var progressedChild = progressedPrimaryChild;
18969
18970
        while (progressedChild !== null) {
18971
          progressedChild.return = primaryChildFragment;
18972
          progressedChild = progressedChild.sibling;
18973
        }
18974
      }
18975
18976
      var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
18977
      fallbackChildFragment.return = workInProgress;
18978
      primaryChildFragment.sibling = fallbackChildFragment; // Skip the primary children, and continue working on the
18979
      // fallback children.
18980
18981
      workInProgress.memoizedState = SUSPENDED_MARKER;
18982
      workInProgress.child = primaryChildFragment;
18983
      return fallbackChildFragment;
18984
    } else {
18985
      // Mount the primary children without an intermediate fragment fiber.
18986
      var nextPrimaryChildren = nextProps.children;
18987
      workInProgress.memoizedState = null;
18988
      return workInProgress.child = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
18989
    }
18990
  } else {
18991
    // This is an update. This branch is more complicated because we need to
18992
    // ensure the state of the primary children is preserved.
18993
    var prevState = current$$1.memoizedState;
18994
18995
    if (prevState !== null) {
18996
      if (enableSuspenseServerRenderer) {
18997
        var _dehydrated = prevState.dehydrated;
18998
18999
        if (_dehydrated !== null) {
19000
          if (!didSuspend) {
19001
            return updateDehydratedSuspenseComponent(current$$1, workInProgress, _dehydrated, prevState, renderExpirationTime);
19002
          } else if (workInProgress.memoizedState !== null) {
19003
            // Something suspended and we should still be in dehydrated mode.
19004
            // Leave the existing child in place.
19005
            workInProgress.child = current$$1.child; // The dehydrated completion pass expects this flag to be there
19006
            // but the normal suspense pass doesn't.
19007
19008
            workInProgress.effectTag |= DidCapture;
19009
            return null;
19010
          } else {
19011
            // Suspended but we should no longer be in dehydrated mode.
19012
            // Therefore we now have to render the fallback. Wrap the children
19013
            // in a fragment fiber to keep them separate from the fallback
19014
            // children.
19015
            var _nextFallbackChildren = nextProps.fallback;
19016
19017
            var _primaryChildFragment = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't
19018
            // going to render this fragment.
19019
            null, mode, NoWork, null);
19020
19021
            _primaryChildFragment.return = workInProgress; // This is always null since we never want the previous child
19022
            // that we're not going to hydrate.
19023
19024
            _primaryChildFragment.child = null;
19025
19026
            if ((workInProgress.mode & BatchedMode) === NoMode) {
19027
              // Outside of batched mode, we commit the effects from the
19028
              // partially completed, timed-out tree, too.
19029
              var _progressedChild = _primaryChildFragment.child = workInProgress.child;
19030
19031
              while (_progressedChild !== null) {
19032
                _progressedChild.return = _primaryChildFragment;
19033
                _progressedChild = _progressedChild.sibling;
19034
              }
19035
            } else {
19036
              // We will have dropped the effect list which contains the deletion.
19037
              // We need to reconcile to delete the current child.
19038
              reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime);
19039
            } // Because primaryChildFragment is a new fiber that we're inserting as the
19040
            // parent of a new tree, we need to set its treeBaseDuration.
19041
19042
19043
            if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19044
              // treeBaseDuration is the sum of all the child tree base durations.
19045
              var treeBaseDuration = 0;
19046
              var hiddenChild = _primaryChildFragment.child;
19047
19048
              while (hiddenChild !== null) {
19049
                treeBaseDuration += hiddenChild.treeBaseDuration;
19050
                hiddenChild = hiddenChild.sibling;
19051
              }
19052
19053
              _primaryChildFragment.treeBaseDuration = treeBaseDuration;
19054
            } // Create a fragment from the fallback children, too.
19055
19056
19057
            var _fallbackChildFragment = createFiberFromFragment(_nextFallbackChildren, mode, renderExpirationTime, null);
19058
19059
            _fallbackChildFragment.return = workInProgress;
19060
            _primaryChildFragment.sibling = _fallbackChildFragment;
19061
            _fallbackChildFragment.effectTag |= Placement;
19062
            _primaryChildFragment.childExpirationTime = NoWork;
19063
            workInProgress.memoizedState = SUSPENDED_MARKER;
19064
            workInProgress.child = _primaryChildFragment; // Skip the primary children, and continue working on the
19065
            // fallback children.
19066
19067
            return _fallbackChildFragment;
19068
          }
19069
        }
19070
      } // The current tree already timed out. That means each child set is
19071
      // wrapped in a fragment fiber.
19072
19073
19074
      var currentPrimaryChildFragment = current$$1.child;
19075
      var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
19076
19077
      if (nextDidTimeout) {
19078
        // Still timed out. Reuse the current primary children by cloning
19079
        // its fragment. We're going to skip over these entirely.
19080
        var _nextFallbackChildren2 = nextProps.fallback;
19081
19082
        var _primaryChildFragment2 = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
19083
19084
        _primaryChildFragment2.return = workInProgress;
19085
19086
        if ((workInProgress.mode & BatchedMode) === NoMode) {
19087
          // Outside of batched mode, we commit the effects from the
19088
          // partially completed, timed-out tree, too.
19089
          var _progressedState = workInProgress.memoizedState;
19090
19091
          var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
19092
19093
          if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
19094
            _primaryChildFragment2.child = _progressedPrimaryChild;
19095
            var _progressedChild2 = _progressedPrimaryChild;
19096
19097
            while (_progressedChild2 !== null) {
19098
              _progressedChild2.return = _primaryChildFragment2;
19099
              _progressedChild2 = _progressedChild2.sibling;
19100
            }
19101
          }
19102
        } // Because primaryChildFragment is a new fiber that we're inserting as the
19103
        // parent of a new tree, we need to set its treeBaseDuration.
19104
19105
19106
        if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19107
          // treeBaseDuration is the sum of all the child tree base durations.
19108
          var _treeBaseDuration = 0;
19109
          var _hiddenChild = _primaryChildFragment2.child;
19110
19111
          while (_hiddenChild !== null) {
19112
            _treeBaseDuration += _hiddenChild.treeBaseDuration;
19113
            _hiddenChild = _hiddenChild.sibling;
19114
          }
19115
19116
          _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
19117
        } // Clone the fallback child fragment, too. These we'll continue
19118
        // working on.
19119
19120
19121
        var _fallbackChildFragment2 = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren2, currentFallbackChildFragment.expirationTime);
19122
19123
        _fallbackChildFragment2.return = workInProgress;
19124
        _primaryChildFragment2.sibling = _fallbackChildFragment2;
19125
        _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
19126
        // fallback children.
19127
19128
        workInProgress.memoizedState = SUSPENDED_MARKER;
19129
        workInProgress.child = _primaryChildFragment2;
19130
        return _fallbackChildFragment2;
19131
      } else {
19132
        // No longer suspended. Switch back to showing the primary children,
19133
        // and remove the intermediate fragment fiber.
19134
        var _nextPrimaryChildren = nextProps.children;
19135
        var currentPrimaryChild = currentPrimaryChildFragment.child;
19136
        var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime); // If this render doesn't suspend, we need to delete the fallback
19137
        // children. Wait until the complete phase, after we've confirmed the
19138
        // fallback is no longer needed.
19139
        // TODO: Would it be better to store the fallback fragment on
19140
        // the stateNode?
19141
        // Continue rendering the children, like we normally do.
19142
19143
        workInProgress.memoizedState = null;
19144
        return workInProgress.child = primaryChild;
19145
      }
19146
    } else {
19147
      // The current tree has not already timed out. That means the primary
19148
      // children are not wrapped in a fragment fiber.
19149
      var _currentPrimaryChild = current$$1.child;
19150
19151
      if (nextDidTimeout) {
19152
        // Timed out. Wrap the children in a fragment fiber to keep them
19153
        // separate from the fallback children.
19154
        var _nextFallbackChildren3 = nextProps.fallback;
19155
19156
        var _primaryChildFragment3 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't
19157
        // going to render this fragment.
19158
        null, mode, NoWork, null);
19159
19160
        _primaryChildFragment3.return = workInProgress;
19161
        _primaryChildFragment3.child = _currentPrimaryChild;
19162
19163
        if (_currentPrimaryChild !== null) {
19164
          _currentPrimaryChild.return = _primaryChildFragment3;
19165
        } // Even though we're creating a new fiber, there are no new children,
19166
        // because we're reusing an already mounted tree. So we don't need to
19167
        // schedule a placement.
19168
        // primaryChildFragment.effectTag |= Placement;
19169
19170
19171
        if ((workInProgress.mode & BatchedMode) === NoMode) {
19172
          // Outside of batched mode, we commit the effects from the
19173
          // partially completed, timed-out tree, too.
19174
          var _progressedState2 = workInProgress.memoizedState;
19175
19176
          var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
19177
19178
          _primaryChildFragment3.child = _progressedPrimaryChild2;
19179
          var _progressedChild3 = _progressedPrimaryChild2;
19180
19181
          while (_progressedChild3 !== null) {
19182
            _progressedChild3.return = _primaryChildFragment3;
19183
            _progressedChild3 = _progressedChild3.sibling;
19184
          }
19185
        } // Because primaryChildFragment is a new fiber that we're inserting as the
19186
        // parent of a new tree, we need to set its treeBaseDuration.
19187
19188
19189
        if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19190
          // treeBaseDuration is the sum of all the child tree base durations.
19191
          var _treeBaseDuration2 = 0;
19192
          var _hiddenChild2 = _primaryChildFragment3.child;
19193
19194
          while (_hiddenChild2 !== null) {
19195
            _treeBaseDuration2 += _hiddenChild2.treeBaseDuration;
19196
            _hiddenChild2 = _hiddenChild2.sibling;
19197
          }
19198
19199
          _primaryChildFragment3.treeBaseDuration = _treeBaseDuration2;
19200
        } // Create a fragment from the fallback children, too.
19201
19202
19203
        var _fallbackChildFragment3 = createFiberFromFragment(_nextFallbackChildren3, mode, renderExpirationTime, null);
19204
19205
        _fallbackChildFragment3.return = workInProgress;
19206
        _primaryChildFragment3.sibling = _fallbackChildFragment3;
19207
        _fallbackChildFragment3.effectTag |= Placement;
19208
        _primaryChildFragment3.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
19209
        // fallback children.
19210
19211
        workInProgress.memoizedState = SUSPENDED_MARKER;
19212
        workInProgress.child = _primaryChildFragment3;
19213
        return _fallbackChildFragment3;
19214
      } else {
19215
        // Still haven't timed out.  Continue rendering the children, like we
19216
        // normally do.
19217
        workInProgress.memoizedState = null;
19218
        var _nextPrimaryChildren2 = nextProps.children;
19219
        return workInProgress.child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
19220
      }
19221
    }
19222
  }
19223
}
19224
19225
function retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime) {
19226
  // We're now not suspended nor dehydrated.
19227
  workInProgress.memoizedState = null; // Retry with the full children.
19228
19229
  var nextProps = workInProgress.pendingProps;
19230
  var nextChildren = nextProps.children; // This will ensure that the children get Placement effects and
19231
  // that the old child gets a Deletion effect.
19232
  // We could also call forceUnmountCurrentAndReconcile.
19233
19234
  reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19235
  return workInProgress.child;
19236
}
19237
19238
function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderExpirationTime) {
19239
  // During the first pass, we'll bail out and not drill into the children.
19240
  // Instead, we'll leave the content in place and try to hydrate it later.
19241
  if ((workInProgress.mode & BatchedMode) === NoMode) {
19242
    {
19243
      warning$1(false, 'Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOM.unstable_createSyncRoot(container, { hydrate: true })' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.');
19244
    }
19245
19246
    workInProgress.expirationTime = Sync;
19247
  } else if (isSuspenseInstanceFallback(suspenseInstance)) {
19248
    // This is a client-only boundary. Since we won't get any content from the server
19249
    // for this, we need to schedule that at a higher priority based on when it would
19250
    // have timed out. In theory we could render it in this pass but it would have the
19251
    // wrong priority associated with it and will prevent hydration of parent path.
19252
    // Instead, we'll leave work left on it to render it in a separate commit.
19253
    // TODO This time should be the time at which the server rendered response that is
19254
    // a parent to this boundary was displayed. However, since we currently don't have
19255
    // a protocol to transfer that time, we'll just estimate it by using the current
19256
    // time. This will mean that Suspense timeouts are slightly shifted to later than
19257
    // they should be.
19258
    var serverDisplayTime = requestCurrentTime(); // Schedule a normal pri update to render this content.
19259
19260
    var newExpirationTime = computeAsyncExpiration(serverDisplayTime);
19261
19262
    if (enableSchedulerTracing) {
19263
      markSpawnedWork(newExpirationTime);
19264
    }
19265
19266
    workInProgress.expirationTime = newExpirationTime;
19267
  } else {
19268
    // We'll continue hydrating the rest at offscreen priority since we'll already
19269
    // be showing the right content coming from the server, it is no rush.
19270
    workInProgress.expirationTime = Never;
19271
19272
    if (enableSchedulerTracing) {
19273
      markSpawnedWork(Never);
19274
    }
19275
  }
19276
19277
  return null;
19278
}
19279
19280
function updateDehydratedSuspenseComponent(current$$1, workInProgress, suspenseInstance, suspenseState, renderExpirationTime) {
19281
  // We should never be hydrating at this point because it is the first pass,
19282
  // but after we've already committed once.
19283
  warnIfHydrating();
19284
19285
  if ((workInProgress.mode & BatchedMode) === NoMode) {
19286
    return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19287
  }
19288
19289
  if (isSuspenseInstanceFallback(suspenseInstance)) {
19290
    // This boundary is in a permanent fallback state. In this case, we'll never
19291
    // get an update and we'll never be able to hydrate the final content. Let's just try the
19292
    // client side render instead.
19293
    return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19294
  } // We use childExpirationTime to indicate that a child might depend on context, so if
19295
  // any context has changed, we need to treat is as if the input might have changed.
19296
19297
19298
  var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime;
19299
19300
  if (didReceiveUpdate || hasContextChanged$$1) {
19301
    // This boundary has changed since the first render. This means that we are now unable to
19302
    // hydrate it. We might still be able to hydrate it using an earlier expiration time, if
19303
    // we are rendering at lower expiration than sync.
19304
    if (renderExpirationTime < Sync) {
19305
      if (suspenseState.retryTime <= renderExpirationTime) {
19306
        // This render is even higher pri than we've seen before, let's try again
19307
        // at even higher pri.
19308
        var attemptHydrationAtExpirationTime = renderExpirationTime + 1;
19309
        suspenseState.retryTime = attemptHydrationAtExpirationTime;
19310
        scheduleWork(current$$1, attemptHydrationAtExpirationTime); // TODO: Early abort this render.
19311
      } else {// We have already tried to ping at a higher priority than we're rendering with
19312
          // so if we got here, we must have failed to hydrate at those levels. We must
19313
          // now give up. Instead, we're going to delete the whole subtree and instead inject
19314
          // a new real Suspense boundary to take its place, which may render content
19315
          // or fallback. This might suspend for a while and if it does we might still have
19316
          // an opportunity to hydrate before this pass commits.
19317
        }
19318
    } // If we have scheduled higher pri work above, this will probably just abort the render
19319
    // since we now have higher priority work, but in case it doesn't, we need to prepare to
19320
    // render something, if we time out. Even if that requires us to delete everything and
19321
    // skip hydration.
19322
    // Delay having to do this as long as the suspense timeout allows us.
19323
19324
19325
    renderDidSuspendDelayIfPossible();
19326
    return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19327
  } else if (isSuspenseInstancePending(suspenseInstance)) {
19328
    // This component is still pending more data from the server, so we can't hydrate its
19329
    // content. We treat it as if this component suspended itself. It might seem as if
19330
    // we could just try to render it client-side instead. However, this will perform a
19331
    // lot of unnecessary work and is unlikely to complete since it often will suspend
19332
    // on missing data anyway. Additionally, the server might be able to render more
19333
    // than we can on the client yet. In that case we'd end up with more fallback states
19334
    // on the client than if we just leave it alone. If the server times out or errors
19335
    // these should update this boundary to the permanent Fallback state instead.
19336
    // Mark it as having captured (i.e. suspended).
19337
    workInProgress.effectTag |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment.
19338
19339
    workInProgress.child = current$$1.child; // Register a callback to retry this boundary once the server has sent the result.
19340
19341
    registerSuspenseInstanceRetry(suspenseInstance, retryDehydratedSuspenseBoundary.bind(null, current$$1));
19342
    return null;
19343
  } else {
19344
    // This is the first attempt.
19345
    reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance);
19346
    var nextProps = workInProgress.pendingProps;
19347
    var nextChildren = nextProps.children;
19348
    var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
19349
    var node = child;
19350
19351
    while (node) {
19352
      // Mark each child as hydrating. This is a fast path to know whether this
19353
      // tree is part of a hydrating tree. This is used to determine if a child
19354
      // node has fully mounted yet, and for scheduling event replaying.
19355
      // Conceptually this is similar to Placement in that a new subtree is
19356
      // inserted into the React tree here. It just happens to not need DOM
19357
      // mutations because it already exists.
19358
      node.effectTag |= Hydrating;
19359
      node = node.sibling;
19360
    }
19361
19362
    workInProgress.child = child;
19363
    return workInProgress.child;
19364
  }
19365
}
19366
19367
function propagateSuspenseContextChange(workInProgress, firstChild, renderExpirationTime) {
19368
  // Mark any Suspense boundaries with fallbacks as having work to do.
19369
  // If they were previously forced into fallbacks, they may now be able
19370
  // to unblock.
19371
  var node = firstChild;
19372
19373
  while (node !== null) {
19374
    if (node.tag === SuspenseComponent) {
19375
      var state = node.memoizedState;
19376
19377
      if (state !== null) {
19378
        if (node.expirationTime < renderExpirationTime) {
19379
          node.expirationTime = renderExpirationTime;
19380
        }
19381
19382
        var alternate = node.alternate;
19383
19384
        if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
19385
          alternate.expirationTime = renderExpirationTime;
19386
        }
19387
19388
        scheduleWorkOnParentPath(node.return, renderExpirationTime);
19389
      }
19390
    } else if (node.child !== null) {
19391
      node.child.return = node;
19392
      node = node.child;
19393
      continue;
19394
    }
19395
19396
    if (node === workInProgress) {
19397
      return;
19398
    }
19399
19400
    while (node.sibling === null) {
19401
      if (node.return === null || node.return === workInProgress) {
19402
        return;
19403
      }
19404
19405
      node = node.return;
19406
    }
19407
19408
    node.sibling.return = node.return;
19409
    node = node.sibling;
19410
  }
19411
}
19412
19413
function findLastContentRow(firstChild) {
19414
  // This is going to find the last row among these children that is already
19415
  // showing content on the screen, as opposed to being in fallback state or
19416
  // new. If a row has multiple Suspense boundaries, any of them being in the
19417
  // fallback state, counts as the whole row being in a fallback state.
19418
  // Note that the "rows" will be workInProgress, but any nested children
19419
  // will still be current since we haven't rendered them yet. The mounted
19420
  // order may not be the same as the new order. We use the new order.
19421
  var row = firstChild;
19422
  var lastContentRow = null;
19423
19424
  while (row !== null) {
19425
    var currentRow = row.alternate; // New rows can't be content rows.
19426
19427
    if (currentRow !== null && findFirstSuspended(currentRow) === null) {
19428
      lastContentRow = row;
19429
    }
19430
19431
    row = row.sibling;
19432
  }
19433
19434
  return lastContentRow;
19435
}
19436
19437
function validateRevealOrder(revealOrder) {
19438
  {
19439
    if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {
19440
      didWarnAboutRevealOrder[revealOrder] = true;
19441
19442
      if (typeof revealOrder === 'string') {
19443
        switch (revealOrder.toLowerCase()) {
19444
          case 'together':
19445
          case 'forwards':
19446
          case 'backwards':
19447
            {
19448
              warning$1(false, '"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
19449
              break;
19450
            }
19451
19452
          case 'forward':
19453
          case 'backward':
19454
            {
19455
              warning$1(false, '"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase());
19456
              break;
19457
            }
19458
19459
          default:
19460
            warning$1(false, '"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
19461
            break;
19462
        }
19463
      } else {
19464
        warning$1(false, '%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
19465
      }
19466
    }
19467
  }
19468
}
19469
19470
function validateTailOptions(tailMode, revealOrder) {
19471
  {
19472
    if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
19473
      if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
19474
        didWarnAboutTailOptions[tailMode] = true;
19475
        warning$1(false, '"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode);
19476
      } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
19477
        didWarnAboutTailOptions[tailMode] = true;
19478
        warning$1(false, '<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode);
19479
      }
19480
    }
19481
  }
19482
}
19483
19484
function validateSuspenseListNestedChild(childSlot, index) {
19485
  {
19486
    var isArray = Array.isArray(childSlot);
19487
    var isIterable = !isArray && typeof getIteratorFn(childSlot) === 'function';
19488
19489
    if (isArray || isIterable) {
19490
      var type = isArray ? 'array' : 'iterable';
19491
      warning$1(false, 'A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type);
19492
      return false;
19493
    }
19494
  }
19495
19496
  return true;
19497
}
19498
19499
function validateSuspenseListChildren(children, revealOrder) {
19500
  {
19501
    if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {
19502
      if (Array.isArray(children)) {
19503
        for (var i = 0; i < children.length; i++) {
19504
          if (!validateSuspenseListNestedChild(children[i], i)) {
19505
            return;
19506
          }
19507
        }
19508
      } else {
19509
        var iteratorFn = getIteratorFn(children);
19510
19511
        if (typeof iteratorFn === 'function') {
19512
          var childrenIterator = iteratorFn.call(children);
19513
19514
          if (childrenIterator) {
19515
            var step = childrenIterator.next();
19516
            var _i = 0;
19517
19518
            for (; !step.done; step = childrenIterator.next()) {
19519
              if (!validateSuspenseListNestedChild(step.value, _i)) {
19520
                return;
19521
              }
19522
19523
              _i++;
19524
            }
19525
          }
19526
        } else {
19527
          warning$1(false, 'A single row was passed to a <SuspenseList revealOrder="%s" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder);
19528
        }
19529
      }
19530
    }
19531
  }
19532
}
19533
19534
function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode) {
19535
  var renderState = workInProgress.memoizedState;
19536
19537
  if (renderState === null) {
19538
    workInProgress.memoizedState = {
19539
      isBackwards: isBackwards,
19540
      rendering: null,
19541
      last: lastContentRow,
19542
      tail: tail,
19543
      tailExpiration: 0,
19544
      tailMode: tailMode
19545
    };
19546
  } else {
19547
    // We can reuse the existing object from previous renders.
19548
    renderState.isBackwards = isBackwards;
19549
    renderState.rendering = null;
19550
    renderState.last = lastContentRow;
19551
    renderState.tail = tail;
19552
    renderState.tailExpiration = 0;
19553
    renderState.tailMode = tailMode;
19554
  }
19555
} // This can end up rendering this component multiple passes.
19556
// The first pass splits the children fibers into two sets. A head and tail.
19557
// We first render the head. If anything is in fallback state, we do another
19558
// pass through beginWork to rerender all children (including the tail) with
19559
// the force suspend context. If the first render didn't have anything in
19560
// in fallback state. Then we render each row in the tail one-by-one.
19561
// That happens in the completeWork phase without going back to beginWork.
19562
19563
19564
function updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime) {
19565
  var nextProps = workInProgress.pendingProps;
19566
  var revealOrder = nextProps.revealOrder;
19567
  var tailMode = nextProps.tail;
19568
  var newChildren = nextProps.children;
19569
  validateRevealOrder(revealOrder);
19570
  validateTailOptions(tailMode, revealOrder);
19571
  validateSuspenseListChildren(newChildren, revealOrder);
19572
  reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19573
  var suspenseContext = suspenseStackCursor.current;
19574
  var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
19575
19576
  if (shouldForceFallback) {
19577
    suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
19578
    workInProgress.effectTag |= DidCapture;
19579
  } else {
19580
    var didSuspendBefore = current$$1 !== null && (current$$1.effectTag & DidCapture) !== NoEffect;
19581
19582
    if (didSuspendBefore) {
19583
      // If we previously forced a fallback, we need to schedule work
19584
      // on any nested boundaries to let them know to try to render
19585
      // again. This is the same as context updating.
19586
      propagateSuspenseContextChange(workInProgress, workInProgress.child, renderExpirationTime);
19587
    }
19588
19589
    suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
19590
  }
19591
19592
  pushSuspenseContext(workInProgress, suspenseContext);
19593
19594
  if ((workInProgress.mode & BatchedMode) === NoMode) {
19595
    // Outside of batched mode, SuspenseList doesn't work so we just
19596
    // use make it a noop by treating it as the default revealOrder.
19597
    workInProgress.memoizedState = null;
19598
  } else {
19599
    switch (revealOrder) {
19600
      case 'forwards':
19601
        {
19602
          var lastContentRow = findLastContentRow(workInProgress.child);
19603
          var tail;
19604
19605
          if (lastContentRow === null) {
19606
            // The whole list is part of the tail.
19607
            // TODO: We could fast path by just rendering the tail now.
19608
            tail = workInProgress.child;
19609
            workInProgress.child = null;
19610
          } else {
19611
            // Disconnect the tail rows after the content row.
19612
            // We're going to render them separately later.
19613
            tail = lastContentRow.sibling;
19614
            lastContentRow.sibling = null;
19615
          }
19616
19617
          initSuspenseListRenderState(workInProgress, false, // isBackwards
19618
          tail, lastContentRow, tailMode);
19619
          break;
19620
        }
19621
19622
      case 'backwards':
19623
        {
19624
          // We're going to find the first row that has existing content.
19625
          // At the same time we're going to reverse the list of everything
19626
          // we pass in the meantime. That's going to be our tail in reverse
19627
          // order.
19628
          var _tail = null;
19629
          var row = workInProgress.child;
19630
          workInProgress.child = null;
19631
19632
          while (row !== null) {
19633
            var currentRow = row.alternate; // New rows can't be content rows.
19634
19635
            if (currentRow !== null && findFirstSuspended(currentRow) === null) {
19636
              // This is the beginning of the main content.
19637
              workInProgress.child = row;
19638
              break;
19639
            }
19640
19641
            var nextRow = row.sibling;
19642
            row.sibling = _tail;
19643
            _tail = row;
19644
            row = nextRow;
19645
          } // TODO: If workInProgress.child is null, we can continue on the tail immediately.
19646
19647
19648
          initSuspenseListRenderState(workInProgress, true, // isBackwards
19649
          _tail, null, // last
19650
          tailMode);
19651
          break;
19652
        }
19653
19654
      case 'together':
19655
        {
19656
          initSuspenseListRenderState(workInProgress, false, // isBackwards
19657
          null, // tail
19658
          null, // last
19659
          undefined);
19660
          break;
19661
        }
19662
19663
      default:
19664
        {
19665
          // The default reveal order is the same as not having
19666
          // a boundary.
19667
          workInProgress.memoizedState = null;
19668
        }
19669
    }
19670
  }
19671
19672
  return workInProgress.child;
19673
}
19674
19675
function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) {
19676
  pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
19677
  var nextChildren = workInProgress.pendingProps;
19678
19679
  if (current$$1 === null) {
19680
    // Portals are special because we don't append the children during mount
19681
    // but at commit. Therefore we need to track insertions which the normal
19682
    // flow doesn't do during mount. This doesn't happen at the root because
19683
    // the root always starts with a "current" with a null child.
19684
    // TODO: Consider unifying this with how the root works.
19685
    workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
19686
  } else {
19687
    reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19688
  }
19689
19690
  return workInProgress.child;
19691
}
19692
19693
function updateContextProvider(current$$1, workInProgress, renderExpirationTime) {
19694
  var providerType = workInProgress.type;
19695
  var context = providerType._context;
19696
  var newProps = workInProgress.pendingProps;
19697
  var oldProps = workInProgress.memoizedProps;
19698
  var newValue = newProps.value;
19699
19700
  {
19701
    var providerPropTypes = workInProgress.type.propTypes;
19702
19703
    if (providerPropTypes) {
19704
      checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
19705
    }
19706
  }
19707
19708
  pushProvider(workInProgress, newValue);
19709
19710
  if (oldProps !== null) {
19711
    var oldValue = oldProps.value;
19712
    var changedBits = calculateChangedBits(context, newValue, oldValue);
19713
19714
    if (changedBits === 0) {
19715
      // No change. Bailout early if children are the same.
19716
      if (oldProps.children === newProps.children && !hasContextChanged()) {
19717
        return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
19718
      }
19719
    } else {
19720
      // The context value changed. Search for matching consumers and schedule
19721
      // them to update.
19722
      propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
19723
    }
19724
  }
19725
19726
  var newChildren = newProps.children;
19727
  reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19728
  return workInProgress.child;
19729
}
19730
19731
var hasWarnedAboutUsingContextAsConsumer = false;
19732
19733
function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) {
19734
  var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In
19735
  // DEV mode, we create a separate object for Context.Consumer that acts
19736
  // like a proxy to Context. This proxy object adds unnecessary code in PROD
19737
  // so we use the old behaviour (Context.Consumer references Context) to
19738
  // reduce size and overhead. The separate object references context via
19739
  // a property called "_context", which also gives us the ability to check
19740
  // in DEV mode if this property exists or not and warn if it does not.
19741
19742
  {
19743
    if (context._context === undefined) {
19744
      // This may be because it's a Context (rather than a Consumer).
19745
      // Or it may be because it's older React where they're the same thing.
19746
      // We only want to warn if we're sure it's a new React.
19747
      if (context !== context.Consumer) {
19748
        if (!hasWarnedAboutUsingContextAsConsumer) {
19749
          hasWarnedAboutUsingContextAsConsumer = true;
19750
          warning$1(false, 'Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
19751
        }
19752
      }
19753
    } else {
19754
      context = context._context;
19755
    }
19756
  }
19757
19758
  var newProps = workInProgress.pendingProps;
19759
  var render = newProps.children;
19760
19761
  {
19762
    !(typeof render === 'function') ? warningWithoutStack$1(false, 'A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.') : void 0;
19763
  }
19764
19765
  prepareToReadContext(workInProgress, renderExpirationTime);
19766
  var newValue = readContext(context, newProps.unstable_observedBits);
19767
  var newChildren;
19768
19769
  {
19770
    ReactCurrentOwner$3.current = workInProgress;
19771
    setCurrentPhase('render');
19772
    newChildren = render(newValue);
19773
    setCurrentPhase(null);
19774
  } // React DevTools reads this flag.
19775
19776
19777
  workInProgress.effectTag |= PerformedWork;
19778
  reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19779
  return workInProgress.child;
19780
}
19781
19782
function updateFundamentalComponent$1(current$$1, workInProgress, renderExpirationTime) {
19783
  var fundamentalImpl = workInProgress.type.impl;
19784
19785
  if (fundamentalImpl.reconcileChildren === false) {
19786
    return null;
19787
  }
19788
19789
  var nextProps = workInProgress.pendingProps;
19790
  var nextChildren = nextProps.children;
19791
  reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19792
  return workInProgress.child;
19793
}
19794
19795
function updateScopeComponent(current$$1, workInProgress, renderExpirationTime) {
19796
  var nextProps = workInProgress.pendingProps;
19797
  var nextChildren = nextProps.children;
19798
  reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19799
  return workInProgress.child;
19800
}
19801
19802
function markWorkInProgressReceivedUpdate() {
19803
  didReceiveUpdate = true;
19804
}
19805
19806
function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) {
19807
  cancelWorkTimer(workInProgress);
19808
19809
  if (current$$1 !== null) {
19810
    // Reuse previous dependencies
19811
    workInProgress.dependencies = current$$1.dependencies;
19812
  }
19813
19814
  if (enableProfilerTimer) {
19815
    // Don't update "base" render times for bailouts.
19816
    stopProfilerTimerIfRunning(workInProgress);
19817
  }
19818
19819
  var updateExpirationTime = workInProgress.expirationTime;
19820
19821
  if (updateExpirationTime !== NoWork) {
19822
    markUnprocessedUpdateTime(updateExpirationTime);
19823
  } // Check if the children have any pending work.
19824
19825
19826
  var childExpirationTime = workInProgress.childExpirationTime;
19827
19828
  if (childExpirationTime < renderExpirationTime) {
19829
    // The children don't have any work either. We can skip them.
19830
    // TODO: Once we add back resuming, we should check if the children are
19831
    // a work-in-progress set. If so, we need to transfer their effects.
19832
    return null;
19833
  } else {
19834
    // This fiber doesn't have work, but its subtree does. Clone the child
19835
    // fibers and continue.
19836
    cloneChildFibers(current$$1, workInProgress);
19837
    return workInProgress.child;
19838
  }
19839
}
19840
19841
function remountFiber(current$$1, oldWorkInProgress, newWorkInProgress) {
19842
  {
19843
    var returnFiber = oldWorkInProgress.return;
19844
19845
    if (returnFiber === null) {
19846
      throw new Error('Cannot swap the root fiber.');
19847
    } // Disconnect from the old current.
19848
    // It will get deleted.
19849
19850
19851
    current$$1.alternate = null;
19852
    oldWorkInProgress.alternate = null; // Connect to the new tree.
19853
19854
    newWorkInProgress.index = oldWorkInProgress.index;
19855
    newWorkInProgress.sibling = oldWorkInProgress.sibling;
19856
    newWorkInProgress.return = oldWorkInProgress.return;
19857
    newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.
19858
19859
    if (oldWorkInProgress === returnFiber.child) {
19860
      returnFiber.child = newWorkInProgress;
19861
    } else {
19862
      var prevSibling = returnFiber.child;
19863
19864
      if (prevSibling === null) {
19865
        throw new Error('Expected parent to have a child.');
19866
      }
19867
19868
      while (prevSibling.sibling !== oldWorkInProgress) {
19869
        prevSibling = prevSibling.sibling;
19870
19871
        if (prevSibling === null) {
19872
          throw new Error('Expected to find the previous sibling.');
19873
        }
19874
      }
19875
19876
      prevSibling.sibling = newWorkInProgress;
19877
    } // Delete the old fiber and place the new one.
19878
    // Since the old fiber is disconnected, we have to schedule it manually.
19879
19880
19881
    var last = returnFiber.lastEffect;
19882
19883
    if (last !== null) {
19884
      last.nextEffect = current$$1;
19885
      returnFiber.lastEffect = current$$1;
19886
    } else {
19887
      returnFiber.firstEffect = returnFiber.lastEffect = current$$1;
19888
    }
19889
19890
    current$$1.nextEffect = null;
19891
    current$$1.effectTag = Deletion;
19892
    newWorkInProgress.effectTag |= Placement; // Restart work from the new fiber.
19893
19894
    return newWorkInProgress;
19895
  }
19896
}
19897
19898
function beginWork$1(current$$1, workInProgress, renderExpirationTime) {
19899
  var updateExpirationTime = workInProgress.expirationTime;
19900
19901
  {
19902
    if (workInProgress._debugNeedsRemount && current$$1 !== null) {
19903
      // This will restart the begin phase with a new fiber.
19904
      return remountFiber(current$$1, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.expirationTime));
19905
    }
19906
  }
19907
19908
  if (current$$1 !== null) {
19909
    var oldProps = current$$1.memoizedProps;
19910
    var newProps = workInProgress.pendingProps;
19911
19912
    if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:
19913
    workInProgress.type !== current$$1.type)) {
19914
      // If props or context changed, mark the fiber as having performed work.
19915
      // This may be unset if the props are determined to be equal later (memo).
19916
      didReceiveUpdate = true;
19917
    } else if (updateExpirationTime < renderExpirationTime) {
19918
      didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering
19919
      // the begin phase. There's still some bookkeeping we that needs to be done
19920
      // in this optimized path, mostly pushing stuff onto the stack.
19921
19922
      switch (workInProgress.tag) {
19923
        case HostRoot:
19924
          pushHostRootContext(workInProgress);
19925
          resetHydrationState();
19926
          break;
19927
19928
        case HostComponent:
19929
          pushHostContext(workInProgress);
19930
19931
          if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(workInProgress.type, newProps)) {
19932
            if (enableSchedulerTracing) {
19933
              markSpawnedWork(Never);
19934
            } // Schedule this fiber to re-render at offscreen priority. Then bailout.
19935
19936
19937
            workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
19938
            return null;
19939
          }
19940
19941
          break;
19942
19943
        case ClassComponent:
19944
          {
19945
            var Component = workInProgress.type;
19946
19947
            if (isContextProvider(Component)) {
19948
              pushContextProvider(workInProgress);
19949
            }
19950
19951
            break;
19952
          }
19953
19954
        case HostPortal:
19955
          pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
19956
          break;
19957
19958
        case ContextProvider:
19959
          {
19960
            var newValue = workInProgress.memoizedProps.value;
19961
            pushProvider(workInProgress, newValue);
19962
            break;
19963
          }
19964
19965
        case Profiler:
19966
          if (enableProfilerTimer) {
19967
            workInProgress.effectTag |= Update;
19968
          }
19969
19970
          break;
19971
19972
        case SuspenseComponent:
19973
          {
19974
            var state = workInProgress.memoizedState;
19975
19976
            if (state !== null) {
19977
              if (enableSuspenseServerRenderer) {
19978
                if (state.dehydrated !== null) {
19979
                  pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has
19980
                  // been unsuspended it has committed as a resolved Suspense component.
19981
                  // If it needs to be retried, it should have work scheduled on it.
19982
19983
                  workInProgress.effectTag |= DidCapture;
19984
                  break;
19985
                }
19986
              } // If this boundary is currently timed out, we need to decide
19987
              // whether to retry the primary children, or to skip over it and
19988
              // go straight to the fallback. Check the priority of the primary
19989
              // child fragment.
19990
19991
19992
              var primaryChildFragment = workInProgress.child;
19993
              var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
19994
19995
              if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
19996
                // The primary children have pending work. Use the normal path
19997
                // to attempt to render the primary children again.
19998
                return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
19999
              } else {
20000
                pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient
20001
                // priority. Bailout.
20002
20003
                var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
20004
20005
                if (child !== null) {
20006
                  // The fallback children have pending work. Skip over the
20007
                  // primary children and work on the fallback.
20008
                  return child.sibling;
20009
                } else {
20010
                  return null;
20011
                }
20012
              }
20013
            } else {
20014
              pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
20015
            }
20016
20017
            break;
20018
          }
20019
20020
        case SuspenseListComponent:
20021
          {
20022
            var didSuspendBefore = (current$$1.effectTag & DidCapture) !== NoEffect;
20023
            var hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;
20024
20025
            if (didSuspendBefore) {
20026
              if (hasChildWork) {
20027
                // If something was in fallback state last time, and we have all the
20028
                // same children then we're still in progressive loading state.
20029
                // Something might get unblocked by state updates or retries in the
20030
                // tree which will affect the tail. So we need to use the normal
20031
                // path to compute the correct tail.
20032
                return updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime);
20033
              } // If none of the children had any work, that means that none of
20034
              // them got retried so they'll still be blocked in the same way
20035
              // as before. We can fast bail out.
20036
20037
20038
              workInProgress.effectTag |= DidCapture;
20039
            } // If nothing suspended before and we're rendering the same children,
20040
            // then the tail doesn't matter. Anything new that suspends will work
20041
            // in the "together" mode, so we can continue from the state we had.
20042
20043
20044
            var renderState = workInProgress.memoizedState;
20045
20046
            if (renderState !== null) {
20047
              // Reset to the "together" mode in case we've started a different
20048
              // update in the past but didn't complete it.
20049
              renderState.rendering = null;
20050
              renderState.tail = null;
20051
            }
20052
20053
            pushSuspenseContext(workInProgress, suspenseStackCursor.current);
20054
20055
            if (hasChildWork) {
20056
              break;
20057
            } else {
20058
              // If none of the children had any work, that means that none of
20059
              // them got retried so they'll still be blocked in the same way
20060
              // as before. We can fast bail out.
20061
              return null;
20062
            }
20063
          }
20064
      }
20065
20066
      return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
20067
    } else {
20068
      // An update was scheduled on this fiber, but there are no new props
20069
      // nor legacy context. Set this to false. If an update queue or context
20070
      // consumer produces a changed value, it will set this to true. Otherwise,
20071
      // the component will assume the children have not changed and bail out.
20072
      didReceiveUpdate = false;
20073
    }
20074
  } else {
20075
    didReceiveUpdate = false;
20076
  } // Before entering the begin phase, clear the expiration time.
20077
20078
20079
  workInProgress.expirationTime = NoWork;
20080
20081
  switch (workInProgress.tag) {
20082
    case IndeterminateComponent:
20083
      {
20084
        return mountIndeterminateComponent(current$$1, workInProgress, workInProgress.type, renderExpirationTime);
20085
      }
20086
20087
    case LazyComponent:
20088
      {
20089
        var elementType = workInProgress.elementType;
20090
        return mountLazyComponent(current$$1, workInProgress, elementType, updateExpirationTime, renderExpirationTime);
20091
      }
20092
20093
    case FunctionComponent:
20094
      {
20095
        var _Component = workInProgress.type;
20096
        var unresolvedProps = workInProgress.pendingProps;
20097
        var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
20098
        return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime);
20099
      }
20100
20101
    case ClassComponent:
20102
      {
20103
        var _Component2 = workInProgress.type;
20104
        var _unresolvedProps = workInProgress.pendingProps;
20105
20106
        var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
20107
20108
        return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
20109
      }
20110
20111
    case HostRoot:
20112
      return updateHostRoot(current$$1, workInProgress, renderExpirationTime);
20113
20114
    case HostComponent:
20115
      return updateHostComponent(current$$1, workInProgress, renderExpirationTime);
20116
20117
    case HostText:
20118
      return updateHostText(current$$1, workInProgress);
20119
20120
    case SuspenseComponent:
20121
      return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
20122
20123
    case HostPortal:
20124
      return updatePortalComponent(current$$1, workInProgress, renderExpirationTime);
20125
20126
    case ForwardRef:
20127
      {
20128
        var type = workInProgress.type;
20129
        var _unresolvedProps2 = workInProgress.pendingProps;
20130
20131
        var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
20132
20133
        return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime);
20134
      }
20135
20136
    case Fragment:
20137
      return updateFragment(current$$1, workInProgress, renderExpirationTime);
20138
20139
    case Mode:
20140
      return updateMode(current$$1, workInProgress, renderExpirationTime);
20141
20142
    case Profiler:
20143
      return updateProfiler(current$$1, workInProgress, renderExpirationTime);
20144
20145
    case ContextProvider:
20146
      return updateContextProvider(current$$1, workInProgress, renderExpirationTime);
20147
20148
    case ContextConsumer:
20149
      return updateContextConsumer(current$$1, workInProgress, renderExpirationTime);
20150
20151
    case MemoComponent:
20152
      {
20153
        var _type2 = workInProgress.type;
20154
        var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.
20155
20156
        var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
20157
20158
        {
20159
          if (workInProgress.type !== workInProgress.elementType) {
20160
            var outerPropTypes = _type2.propTypes;
20161
20162
            if (outerPropTypes) {
20163
              checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only
20164
              'prop', getComponentName(_type2), getCurrentFiberStackInDev);
20165
            }
20166
          }
20167
        }
20168
20169
        _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
20170
        return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
20171
      }
20172
20173
    case SimpleMemoComponent:
20174
      {
20175
        return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
20176
      }
20177
20178
    case IncompleteClassComponent:
20179
      {
20180
        var _Component3 = workInProgress.type;
20181
        var _unresolvedProps4 = workInProgress.pendingProps;
20182
20183
        var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
20184
20185
        return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
20186
      }
20187
20188
    case SuspenseListComponent:
20189
      {
20190
        return updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime);
20191
      }
20192
20193
    case FundamentalComponent:
20194
      {
20195
        if (enableFundamentalAPI) {
20196
          return updateFundamentalComponent$1(current$$1, workInProgress, renderExpirationTime);
20197
        }
20198
20199
        break;
20200
      }
20201
20202
    case ScopeComponent:
20203
      {
20204
        if (enableScopeAPI) {
20205
          return updateScopeComponent(current$$1, workInProgress, renderExpirationTime);
20206
        }
20207
20208
        break;
20209
      }
20210
  }
20211
20212
  (function () {
20213
    {
20214
      {
20215
        throw ReactError(Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue."));
20216
      }
20217
    }
20218
  })();
20219
}
20220
20221
function createFundamentalStateInstance(currentFiber, props, impl, state) {
20222
  return {
20223
    currentFiber: currentFiber,
20224
    impl: impl,
20225
    instance: null,
20226
    prevProps: null,
20227
    props: props,
20228
    state: state
20229
  };
20230
}
20231
20232
function isFiberSuspenseAndTimedOut(fiber) {
20233
  return fiber.tag === SuspenseComponent && fiber.memoizedState !== null;
20234
}
20235
20236
function getSuspenseFallbackChild(fiber) {
20237
  return fiber.child.sibling.child;
20238
}
20239
20240
function collectScopedNodes(node, fn, scopedNodes) {
20241
  if (enableScopeAPI) {
20242
    if (node.tag === HostComponent) {
20243
      var _type = node.type,
20244
          memoizedProps = node.memoizedProps;
20245
20246
      if (fn(_type, memoizedProps) === true) {
20247
        scopedNodes.push(getPublicInstance(node.stateNode));
20248
      }
20249
    }
20250
20251
    var child = node.child;
20252
20253
    if (isFiberSuspenseAndTimedOut(node)) {
20254
      child = getSuspenseFallbackChild(node);
20255
    }
20256
20257
    if (child !== null) {
20258
      collectScopedNodesFromChildren(child, fn, scopedNodes);
20259
    }
20260
  }
20261
}
20262
20263
function collectScopedNodesFromChildren(startingChild, fn, scopedNodes) {
20264
  var child = startingChild;
20265
20266
  while (child !== null) {
20267
    collectScopedNodes(child, fn, scopedNodes);
20268
    child = child.sibling;
20269
  }
20270
}
20271
20272
function collectNearestScopeMethods(node, scope, childrenScopes) {
20273
  if (isValidScopeNode(node, scope)) {
20274
    childrenScopes.push(node.stateNode.methods);
20275
  } else {
20276
    var child = node.child;
20277
20278
    if (isFiberSuspenseAndTimedOut(node)) {
20279
      child = getSuspenseFallbackChild(node);
20280
    }
20281
20282
    if (child !== null) {
20283
      collectNearestChildScopeMethods(child, scope, childrenScopes);
20284
    }
20285
  }
20286
}
20287
20288
function collectNearestChildScopeMethods(startingChild, scope, childrenScopes) {
20289
  var child = startingChild;
20290
20291
  while (child !== null) {
20292
    collectNearestScopeMethods(child, scope, childrenScopes);
20293
    child = child.sibling;
20294
  }
20295
}
20296
20297
function isValidScopeNode(node, scope) {
20298
  return node.tag === ScopeComponent && node.type === scope;
20299
}
20300
20301
function createScopeMethods(scope, instance) {
20302
  var fn = scope.fn;
20303
  return {
20304
    getChildren: function () {
20305
      var currentFiber = instance.fiber;
20306
      var child = currentFiber.child;
20307
      var childrenScopes = [];
20308
20309
      if (child !== null) {
20310
        collectNearestChildScopeMethods(child, scope, childrenScopes);
20311
      }
20312
20313
      return childrenScopes.length === 0 ? null : childrenScopes;
20314
    },
20315
    getChildrenFromRoot: function () {
20316
      var currentFiber = instance.fiber;
20317
      var node = currentFiber;
20318
20319
      while (node !== null) {
20320
        var parent = node.return;
20321
20322
        if (parent === null) {
20323
          break;
20324
        }
20325
20326
        node = parent;
20327
20328
        if (node.tag === ScopeComponent && node.type === scope) {
20329
          break;
20330
        }
20331
      }
20332
20333
      var childrenScopes = [];
20334
      collectNearestChildScopeMethods(node.child, scope, childrenScopes);
20335
      return childrenScopes.length === 0 ? null : childrenScopes;
20336
    },
20337
    getParent: function () {
20338
      var node = instance.fiber.return;
20339
20340
      while (node !== null) {
20341
        if (node.tag === ScopeComponent && node.type === scope) {
20342
          return node.stateNode.methods;
20343
        }
20344
20345
        node = node.return;
20346
      }
20347
20348
      return null;
20349
    },
20350
    getProps: function () {
20351
      var currentFiber = instance.fiber;
20352
      return currentFiber.memoizedProps;
20353
    },
20354
    getScopedNodes: function () {
20355
      var currentFiber = instance.fiber;
20356
      var child = currentFiber.child;
20357
      var scopedNodes = [];
20358
20359
      if (child !== null) {
20360
        collectScopedNodesFromChildren(child, fn, scopedNodes);
20361
      }
20362
20363
      return scopedNodes.length === 0 ? null : scopedNodes;
20364
    }
20365
  };
20366
}
20367
20368
function markUpdate(workInProgress) {
20369
  // Tag the fiber with an update effect. This turns a Placement into
20370
  // a PlacementAndUpdate.
20371
  workInProgress.effectTag |= Update;
20372
}
20373
20374
function markRef$1(workInProgress) {
20375
  workInProgress.effectTag |= Ref;
20376
}
20377
20378
var appendAllChildren;
20379
var updateHostContainer;
20380
var updateHostComponent$1;
20381
var updateHostText$1;
20382
20383
if (supportsMutation) {
20384
  // Mutation mode
20385
  appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
20386
    // We only have the top Fiber that was created but we need recurse down its
20387
    // children to find all the terminal nodes.
20388
    var node = workInProgress.child;
20389
20390
    while (node !== null) {
20391
      if (node.tag === HostComponent || node.tag === HostText) {
20392
        appendInitialChild(parent, node.stateNode);
20393
      } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20394
        appendInitialChild(parent, node.stateNode.instance);
20395
      } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20396
        // down its children. Instead, we'll get insertions from each child in
20397
        // the portal directly.
20398
      } else if (node.child !== null) {
20399
        node.child.return = node;
20400
        node = node.child;
20401
        continue;
20402
      }
20403
20404
      if (node === workInProgress) {
20405
        return;
20406
      }
20407
20408
      while (node.sibling === null) {
20409
        if (node.return === null || node.return === workInProgress) {
20410
          return;
20411
        }
20412
20413
        node = node.return;
20414
      }
20415
20416
      node.sibling.return = node.return;
20417
      node = node.sibling;
20418
    }
20419
  };
20420
20421
  updateHostContainer = function (workInProgress) {// Noop
20422
  };
20423
20424
  updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
20425
    // If we have an alternate, that means this is an update and we need to
20426
    // schedule a side-effect to do the updates.
20427
    var oldProps = current.memoizedProps;
20428
20429
    if (oldProps === newProps) {
20430
      // In mutation mode, this is sufficient for a bailout because
20431
      // we won't touch this node even if children changed.
20432
      return;
20433
    } // If we get updated because one of our children updated, we don't
20434
    // have newProps so we'll have to reuse them.
20435
    // TODO: Split the update API as separate for the props vs. children.
20436
    // Even better would be if children weren't special cased at all tho.
20437
20438
20439
    var instance = workInProgress.stateNode;
20440
    var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host
20441
    // component is hitting the resume path. Figure out why. Possibly
20442
    // related to `hidden`.
20443
20444
    var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component.
20445
20446
    workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
20447
    // is a new ref we mark this as an update. All the work is done in commitWork.
20448
20449
    if (updatePayload) {
20450
      markUpdate(workInProgress);
20451
    }
20452
  };
20453
20454
  updateHostText$1 = function (current, workInProgress, oldText, newText) {
20455
    // If the text differs, mark it as an update. All the work in done in commitWork.
20456
    if (oldText !== newText) {
20457
      markUpdate(workInProgress);
20458
    }
20459
  };
20460
} else if (supportsPersistence) {
20461
  // Persistent host tree mode
20462
  appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
20463
    // We only have the top Fiber that was created but we need recurse down its
20464
    // children to find all the terminal nodes.
20465
    var node = workInProgress.child;
20466
20467
    while (node !== null) {
20468
      // eslint-disable-next-line no-labels
20469
      branches: if (node.tag === HostComponent) {
20470
        var instance = node.stateNode;
20471
20472
        if (needsVisibilityToggle && isHidden) {
20473
          // This child is inside a timed out tree. Hide it.
20474
          var props = node.memoizedProps;
20475
          var type = node.type;
20476
          instance = cloneHiddenInstance(instance, type, props, node);
20477
        }
20478
20479
        appendInitialChild(parent, instance);
20480
      } else if (node.tag === HostText) {
20481
        var _instance = node.stateNode;
20482
20483
        if (needsVisibilityToggle && isHidden) {
20484
          // This child is inside a timed out tree. Hide it.
20485
          var text = node.memoizedProps;
20486
          _instance = cloneHiddenTextInstance(_instance, text, node);
20487
        }
20488
20489
        appendInitialChild(parent, _instance);
20490
      } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20491
        var _instance2 = node.stateNode.instance;
20492
20493
        if (needsVisibilityToggle && isHidden) {
20494
          // This child is inside a timed out tree. Hide it.
20495
          var _props = node.memoizedProps;
20496
          var _type = node.type;
20497
          _instance2 = cloneHiddenInstance(_instance2, _type, _props, node);
20498
        }
20499
20500
        appendInitialChild(parent, _instance2);
20501
      } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20502
        // down its children. Instead, we'll get insertions from each child in
20503
        // the portal directly.
20504
      } else if (node.tag === SuspenseComponent) {
20505
        if ((node.effectTag & Update) !== NoEffect) {
20506
          // Need to toggle the visibility of the primary children.
20507
          var newIsHidden = node.memoizedState !== null;
20508
20509
          if (newIsHidden) {
20510
            var primaryChildParent = node.child;
20511
20512
            if (primaryChildParent !== null) {
20513
              if (primaryChildParent.child !== null) {
20514
                primaryChildParent.child.return = primaryChildParent;
20515
                appendAllChildren(parent, primaryChildParent, true, newIsHidden);
20516
              }
20517
20518
              var fallbackChildParent = primaryChildParent.sibling;
20519
20520
              if (fallbackChildParent !== null) {
20521
                fallbackChildParent.return = node;
20522
                node = fallbackChildParent;
20523
                continue;
20524
              }
20525
            }
20526
          }
20527
        }
20528
20529
        if (node.child !== null) {
20530
          // Continue traversing like normal
20531
          node.child.return = node;
20532
          node = node.child;
20533
          continue;
20534
        }
20535
      } else if (node.child !== null) {
20536
        node.child.return = node;
20537
        node = node.child;
20538
        continue;
20539
      } // $FlowFixMe This is correct but Flow is confused by the labeled break.
20540
20541
20542
      node = node;
20543
20544
      if (node === workInProgress) {
20545
        return;
20546
      }
20547
20548
      while (node.sibling === null) {
20549
        if (node.return === null || node.return === workInProgress) {
20550
          return;
20551
        }
20552
20553
        node = node.return;
20554
      }
20555
20556
      node.sibling.return = node.return;
20557
      node = node.sibling;
20558
    }
20559
  }; // An unfortunate fork of appendAllChildren because we have two different parent types.
20560
20561
20562
  var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
20563
    // We only have the top Fiber that was created but we need recurse down its
20564
    // children to find all the terminal nodes.
20565
    var node = workInProgress.child;
20566
20567
    while (node !== null) {
20568
      // eslint-disable-next-line no-labels
20569
      branches: if (node.tag === HostComponent) {
20570
        var instance = node.stateNode;
20571
20572
        if (needsVisibilityToggle && isHidden) {
20573
          // This child is inside a timed out tree. Hide it.
20574
          var props = node.memoizedProps;
20575
          var type = node.type;
20576
          instance = cloneHiddenInstance(instance, type, props, node);
20577
        }
20578
20579
        appendChildToContainerChildSet(containerChildSet, instance);
20580
      } else if (node.tag === HostText) {
20581
        var _instance3 = node.stateNode;
20582
20583
        if (needsVisibilityToggle && isHidden) {
20584
          // This child is inside a timed out tree. Hide it.
20585
          var text = node.memoizedProps;
20586
          _instance3 = cloneHiddenTextInstance(_instance3, text, node);
20587
        }
20588
20589
        appendChildToContainerChildSet(containerChildSet, _instance3);
20590
      } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20591
        var _instance4 = node.stateNode.instance;
20592
20593
        if (needsVisibilityToggle && isHidden) {
20594
          // This child is inside a timed out tree. Hide it.
20595
          var _props2 = node.memoizedProps;
20596
          var _type2 = node.type;
20597
          _instance4 = cloneHiddenInstance(_instance4, _type2, _props2, node);
20598
        }
20599
20600
        appendChildToContainerChildSet(containerChildSet, _instance4);
20601
      } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20602
        // down its children. Instead, we'll get insertions from each child in
20603
        // the portal directly.
20604
      } else if (node.tag === SuspenseComponent) {
20605
        if ((node.effectTag & Update) !== NoEffect) {
20606
          // Need to toggle the visibility of the primary children.
20607
          var newIsHidden = node.memoizedState !== null;
20608
20609
          if (newIsHidden) {
20610
            var primaryChildParent = node.child;
20611
20612
            if (primaryChildParent !== null) {
20613
              if (primaryChildParent.child !== null) {
20614
                primaryChildParent.child.return = primaryChildParent;
20615
                appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
20616
              }
20617
20618
              var fallbackChildParent = primaryChildParent.sibling;
20619
20620
              if (fallbackChildParent !== null) {
20621
                fallbackChildParent.return = node;
20622
                node = fallbackChildParent;
20623
                continue;
20624
              }
20625
            }
20626
          }
20627
        }
20628
20629
        if (node.child !== null) {
20630
          // Continue traversing like normal
20631
          node.child.return = node;
20632
          node = node.child;
20633
          continue;
20634
        }
20635
      } else if (node.child !== null) {
20636
        node.child.return = node;
20637
        node = node.child;
20638
        continue;
20639
      } // $FlowFixMe This is correct but Flow is confused by the labeled break.
20640
20641
20642
      node = node;
20643
20644
      if (node === workInProgress) {
20645
        return;
20646
      }
20647
20648
      while (node.sibling === null) {
20649
        if (node.return === null || node.return === workInProgress) {
20650
          return;
20651
        }
20652
20653
        node = node.return;
20654
      }
20655
20656
      node.sibling.return = node.return;
20657
      node = node.sibling;
20658
    }
20659
  };
20660
20661
  updateHostContainer = function (workInProgress) {
20662
    var portalOrRoot = workInProgress.stateNode;
20663
    var childrenUnchanged = workInProgress.firstEffect === null;
20664
20665
    if (childrenUnchanged) {// No changes, just reuse the existing instance.
20666
    } else {
20667
      var container = portalOrRoot.containerInfo;
20668
      var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set.
20669
20670
      appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
20671
      portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container.
20672
20673
      markUpdate(workInProgress);
20674
      finalizeContainerChildren(container, newChildSet);
20675
    }
20676
  };
20677
20678
  updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
20679
    var currentInstance = current.stateNode;
20680
    var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates.
20681
    // This guarantees that we can reuse all of them.
20682
20683
    var childrenUnchanged = workInProgress.firstEffect === null;
20684
20685
    if (childrenUnchanged && oldProps === newProps) {
20686
      // No changes, just reuse the existing instance.
20687
      // Note that this might release a previous clone.
20688
      workInProgress.stateNode = currentInstance;
20689
      return;
20690
    }
20691
20692
    var recyclableInstance = workInProgress.stateNode;
20693
    var currentHostContext = getHostContext();
20694
    var updatePayload = null;
20695
20696
    if (oldProps !== newProps) {
20697
      updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
20698
    }
20699
20700
    if (childrenUnchanged && updatePayload === null) {
20701
      // No changes, just reuse the existing instance.
20702
      // Note that this might release a previous clone.
20703
      workInProgress.stateNode = currentInstance;
20704
      return;
20705
    }
20706
20707
    var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
20708
20709
    if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
20710
      markUpdate(workInProgress);
20711
    }
20712
20713
    workInProgress.stateNode = newInstance;
20714
20715
    if (childrenUnchanged) {
20716
      // If there are no other effects in this tree, we need to flag this node as having one.
20717
      // Even though we're not going to use it for anything.
20718
      // Otherwise parents won't know that there are new children to propagate upwards.
20719
      markUpdate(workInProgress);
20720
    } else {
20721
      // If children might have changed, we have to add them all to the set.
20722
      appendAllChildren(newInstance, workInProgress, false, false);
20723
    }
20724
  };
20725
20726
  updateHostText$1 = function (current, workInProgress, oldText, newText) {
20727
    if (oldText !== newText) {
20728
      // If the text content differs, we'll create a new text instance for it.
20729
      var rootContainerInstance = getRootHostContainer();
20730
      var currentHostContext = getHostContext();
20731
      workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress); // We'll have to mark it as having an effect, even though we won't use the effect for anything.
20732
      // This lets the parents know that at least one of their children has changed.
20733
20734
      markUpdate(workInProgress);
20735
    }
20736
  };
20737
} else {
20738
  // No host operations
20739
  updateHostContainer = function (workInProgress) {// Noop
20740
  };
20741
20742
  updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {// Noop
20743
  };
20744
20745
  updateHostText$1 = function (current, workInProgress, oldText, newText) {// Noop
20746
  };
20747
}
20748
20749
function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
20750
  switch (renderState.tailMode) {
20751
    case 'hidden':
20752
      {
20753
        // Any insertions at the end of the tail list after this point
20754
        // should be invisible. If there are already mounted boundaries
20755
        // anything before them are not considered for collapsing.
20756
        // Therefore we need to go through the whole tail to find if
20757
        // there are any.
20758
        var tailNode = renderState.tail;
20759
        var lastTailNode = null;
20760
20761
        while (tailNode !== null) {
20762
          if (tailNode.alternate !== null) {
20763
            lastTailNode = tailNode;
20764
          }
20765
20766
          tailNode = tailNode.sibling;
20767
        } // Next we're simply going to delete all insertions after the
20768
        // last rendered item.
20769
20770
20771
        if (lastTailNode === null) {
20772
          // All remaining items in the tail are insertions.
20773
          renderState.tail = null;
20774
        } else {
20775
          // Detach the insertion after the last node that was already
20776
          // inserted.
20777
          lastTailNode.sibling = null;
20778
        }
20779
20780
        break;
20781
      }
20782
20783
    case 'collapsed':
20784
      {
20785
        // Any insertions at the end of the tail list after this point
20786
        // should be invisible. If there are already mounted boundaries
20787
        // anything before them are not considered for collapsing.
20788
        // Therefore we need to go through the whole tail to find if
20789
        // there are any.
20790
        var _tailNode = renderState.tail;
20791
        var _lastTailNode = null;
20792
20793
        while (_tailNode !== null) {
20794
          if (_tailNode.alternate !== null) {
20795
            _lastTailNode = _tailNode;
20796
          }
20797
20798
          _tailNode = _tailNode.sibling;
20799
        } // Next we're simply going to delete all insertions after the
20800
        // last rendered item.
20801
20802
20803
        if (_lastTailNode === null) {
20804
          // All remaining items in the tail are insertions.
20805
          if (!hasRenderedATailFallback && renderState.tail !== null) {
20806
            // We suspended during the head. We want to show at least one
20807
            // row at the tail. So we'll keep on and cut off the rest.
20808
            renderState.tail.sibling = null;
20809
          } else {
20810
            renderState.tail = null;
20811
          }
20812
        } else {
20813
          // Detach the insertion after the last node that was already
20814
          // inserted.
20815
          _lastTailNode.sibling = null;
20816
        }
20817
20818
        break;
20819
      }
20820
  }
20821
}
20822
20823
function completeWork(current, workInProgress, renderExpirationTime) {
20824
  var newProps = workInProgress.pendingProps;
20825
20826
  switch (workInProgress.tag) {
20827
    case IndeterminateComponent:
20828
      break;
20829
20830
    case LazyComponent:
20831
      break;
20832
20833
    case SimpleMemoComponent:
20834
    case FunctionComponent:
20835
      break;
20836
20837
    case ClassComponent:
20838
      {
20839
        var Component = workInProgress.type;
20840
20841
        if (isContextProvider(Component)) {
20842
          popContext(workInProgress);
20843
        }
20844
20845
        break;
20846
      }
20847
20848
    case HostRoot:
20849
      {
20850
        popHostContainer(workInProgress);
20851
        popTopLevelContextObject(workInProgress);
20852
        var fiberRoot = workInProgress.stateNode;
20853
20854
        if (fiberRoot.pendingContext) {
20855
          fiberRoot.context = fiberRoot.pendingContext;
20856
          fiberRoot.pendingContext = null;
20857
        }
20858
20859
        if (current === null || current.child === null) {
20860
          // If we hydrated, pop so that we can delete any remaining children
20861
          // that weren't hydrated.
20862
          var wasHydrated = popHydrationState(workInProgress);
20863
20864
          if (wasHydrated) {
20865
            // If we hydrated, then we'll need to schedule an update for
20866
            // the commit side-effects on the root.
20867
            markUpdate(workInProgress);
20868
          }
20869
        }
20870
20871
        updateHostContainer(workInProgress);
20872
        break;
20873
      }
20874
20875
    case HostComponent:
20876
      {
20877
        popHostContext(workInProgress);
20878
        var rootContainerInstance = getRootHostContainer();
20879
        var type = workInProgress.type;
20880
20881
        if (current !== null && workInProgress.stateNode != null) {
20882
          updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
20883
20884
          if (enableFlareAPI) {
20885
            var prevListeners = current.memoizedProps.listeners;
20886
            var nextListeners = newProps.listeners;
20887
20888
            if (prevListeners !== nextListeners) {
20889
              markUpdate(workInProgress);
20890
            }
20891
          }
20892
20893
          if (current.ref !== workInProgress.ref) {
20894
            markRef$1(workInProgress);
20895
          }
20896
        } else {
20897
          if (!newProps) {
20898
            (function () {
20899
              if (!(workInProgress.stateNode !== null)) {
20900
                {
20901
                  throw ReactError(Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."));
20902
                }
20903
              }
20904
            })(); // This can happen when we abort work.
20905
20906
20907
            break;
20908
          }
20909
20910
          var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context
20911
          // "stack" as the parent. Then append children as we go in beginWork
20912
          // or completeWork depending on we want to add then top->down or
20913
          // bottom->up. Top->down is faster in IE11.
20914
20915
          var _wasHydrated = popHydrationState(workInProgress);
20916
20917
          if (_wasHydrated) {
20918
            // TODO: Move this and createInstance step into the beginPhase
20919
            // to consolidate.
20920
            if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
20921
              // If changes to the hydrated node needs to be applied at the
20922
              // commit-phase we mark this as such.
20923
              markUpdate(workInProgress);
20924
            }
20925
20926
            if (enableFlareAPI) {
20927
              var listeners = newProps.listeners;
20928
20929
              if (listeners != null) {
20930
                updateEventListeners(listeners, workInProgress, rootContainerInstance);
20931
              }
20932
            }
20933
          } else {
20934
            var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
20935
            appendAllChildren(instance, workInProgress, false, false); // This needs to be set before we mount Flare event listeners
20936
20937
            workInProgress.stateNode = instance;
20938
20939
            if (enableFlareAPI) {
20940
              var _listeners = newProps.listeners;
20941
20942
              if (_listeners != null) {
20943
                updateEventListeners(_listeners, workInProgress, rootContainerInstance);
20944
              }
20945
            } // Certain renderers require commit-time effects for initial mount.
20946
            // (eg DOM renderer supports auto-focus for certain elements).
20947
            // Make sure such renderers get scheduled for later work.
20948
20949
20950
            if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
20951
              markUpdate(workInProgress);
20952
            }
20953
          }
20954
20955
          if (workInProgress.ref !== null) {
20956
            // If there is a ref on a host node we need to schedule a callback
20957
            markRef$1(workInProgress);
20958
          }
20959
        }
20960
20961
        break;
20962
      }
20963
20964
    case HostText:
20965
      {
20966
        var newText = newProps;
20967
20968
        if (current && workInProgress.stateNode != null) {
20969
          var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need
20970
          // to schedule a side-effect to do the updates.
20971
20972
          updateHostText$1(current, workInProgress, oldText, newText);
20973
        } else {
20974
          if (typeof newText !== 'string') {
20975
            (function () {
20976
              if (!(workInProgress.stateNode !== null)) {
20977
                {
20978
                  throw ReactError(Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."));
20979
                }
20980
              }
20981
            })(); // This can happen when we abort work.
20982
20983
          }
20984
20985
          var _rootContainerInstance = getRootHostContainer();
20986
20987
          var _currentHostContext = getHostContext();
20988
20989
          var _wasHydrated2 = popHydrationState(workInProgress);
20990
20991
          if (_wasHydrated2) {
20992
            if (prepareToHydrateHostTextInstance(workInProgress)) {
20993
              markUpdate(workInProgress);
20994
            }
20995
          } else {
20996
            workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
20997
          }
20998
        }
20999
21000
        break;
21001
      }
21002
21003
    case ForwardRef:
21004
      break;
21005
21006
    case SuspenseComponent:
21007
      {
21008
        popSuspenseContext(workInProgress);
21009
        var nextState = workInProgress.memoizedState;
21010
21011
        if (enableSuspenseServerRenderer) {
21012
          if (nextState !== null && nextState.dehydrated !== null) {
21013
            if (current === null) {
21014
              var _wasHydrated3 = popHydrationState(workInProgress);
21015
21016
              (function () {
21017
                if (!_wasHydrated3) {
21018
                  {
21019
                    throw ReactError(Error("A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React."));
21020
                  }
21021
                }
21022
              })();
21023
21024
              prepareToHydrateHostSuspenseInstance(workInProgress);
21025
21026
              if (enableSchedulerTracing) {
21027
                markSpawnedWork(Never);
21028
              }
21029
21030
              return null;
21031
            } else {
21032
              // We should never have been in a hydration state if we didn't have a current.
21033
              // However, in some of those paths, we might have reentered a hydration state
21034
              // and then we might be inside a hydration state. In that case, we'll need to
21035
              // exit out of it.
21036
              resetHydrationState();
21037
21038
              if ((workInProgress.effectTag & DidCapture) === NoEffect) {
21039
                // This boundary did not suspend so it's now hydrated and unsuspended.
21040
                workInProgress.memoizedState = null;
21041
              } // If nothing suspended, we need to schedule an effect to mark this boundary
21042
              // as having hydrated so events know that they're free be invoked.
21043
              // It's also a signal to replay events and the suspense callback.
21044
              // If something suspended, schedule an effect to attach retry listeners.
21045
              // So we might as well always mark this.
21046
21047
21048
              workInProgress.effectTag |= Update;
21049
              return null;
21050
            }
21051
          }
21052
        }
21053
21054
        if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
21055
          // Something suspended. Re-render with the fallback children.
21056
          workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list.
21057
21058
          return workInProgress;
21059
        }
21060
21061
        var nextDidTimeout = nextState !== null;
21062
        var prevDidTimeout = false;
21063
21064
        if (current === null) {
21065
          // In cases where we didn't find a suitable hydration boundary we never
21066
          // put this in dehydrated mode, but we still need to pop the hydration
21067
          // state since we might be inside the insertion tree.
21068
          popHydrationState(workInProgress);
21069
        } else {
21070
          var prevState = current.memoizedState;
21071
          prevDidTimeout = prevState !== null;
21072
21073
          if (!nextDidTimeout && prevState !== null) {
21074
            // We just switched from the fallback to the normal children.
21075
            // Delete the fallback.
21076
            // TODO: Would it be better to store the fallback fragment on
21077
            // the stateNode during the begin phase?
21078
            var currentFallbackChild = current.child.sibling;
21079
21080
            if (currentFallbackChild !== null) {
21081
              // Deletions go at the beginning of the return fiber's effect list
21082
              var first = workInProgress.firstEffect;
21083
21084
              if (first !== null) {
21085
                workInProgress.firstEffect = currentFallbackChild;
21086
                currentFallbackChild.nextEffect = first;
21087
              } else {
21088
                workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
21089
                currentFallbackChild.nextEffect = null;
21090
              }
21091
21092
              currentFallbackChild.effectTag = Deletion;
21093
            }
21094
          }
21095
        }
21096
21097
        if (nextDidTimeout && !prevDidTimeout) {
21098
          // If this subtreee is running in batched mode we can suspend,
21099
          // otherwise we won't suspend.
21100
          // TODO: This will still suspend a synchronous tree if anything
21101
          // in the concurrent tree already suspended during this render.
21102
          // This is a known bug.
21103
          if ((workInProgress.mode & BatchedMode) !== NoMode) {
21104
            // TODO: Move this back to throwException because this is too late
21105
            // if this is a large tree which is common for initial loads. We
21106
            // don't know if we should restart a render or not until we get
21107
            // this marker, and this is too late.
21108
            // If this render already had a ping or lower pri updates,
21109
            // and this is the first time we know we're going to suspend we
21110
            // should be able to immediately restart from within throwException.
21111
            var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true;
21112
21113
            if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
21114
              // If this was in an invisible tree or a new render, then showing
21115
              // this boundary is ok.
21116
              renderDidSuspend();
21117
            } else {
21118
              // Otherwise, we're going to have to hide content so we should
21119
              // suspend for longer if possible.
21120
              renderDidSuspendDelayIfPossible();
21121
            }
21122
          }
21123
        }
21124
21125
        if (supportsPersistence) {
21126
          // TODO: Only schedule updates if not prevDidTimeout.
21127
          if (nextDidTimeout) {
21128
            // If this boundary just timed out, schedule an effect to attach a
21129
            // retry listener to the proimse. This flag is also used to hide the
21130
            // primary children.
21131
            workInProgress.effectTag |= Update;
21132
          }
21133
        }
21134
21135
        if (supportsMutation) {
21136
          // TODO: Only schedule updates if these values are non equal, i.e. it changed.
21137
          if (nextDidTimeout || prevDidTimeout) {
21138
            // If this boundary just timed out, schedule an effect to attach a
21139
            // retry listener to the proimse. This flag is also used to hide the
21140
            // primary children. In mutation mode, we also need the flag to
21141
            // *unhide* children that were previously hidden, so check if the
21142
            // is currently timed out, too.
21143
            workInProgress.effectTag |= Update;
21144
          }
21145
        }
21146
21147
        if (enableSuspenseCallback && workInProgress.updateQueue !== null && workInProgress.memoizedProps.suspenseCallback != null) {
21148
          // Always notify the callback
21149
          workInProgress.effectTag |= Update;
21150
        }
21151
21152
        break;
21153
      }
21154
21155
    case Fragment:
21156
      break;
21157
21158
    case Mode:
21159
      break;
21160
21161
    case Profiler:
21162
      break;
21163
21164
    case HostPortal:
21165
      popHostContainer(workInProgress);
21166
      updateHostContainer(workInProgress);
21167
      break;
21168
21169
    case ContextProvider:
21170
      // Pop provider fiber
21171
      popProvider(workInProgress);
21172
      break;
21173
21174
    case ContextConsumer:
21175
      break;
21176
21177
    case MemoComponent:
21178
      break;
21179
21180
    case IncompleteClassComponent:
21181
      {
21182
        // Same as class component case. I put it down here so that the tags are
21183
        // sequential to ensure this switch is compiled to a jump table.
21184
        var _Component = workInProgress.type;
21185
21186
        if (isContextProvider(_Component)) {
21187
          popContext(workInProgress);
21188
        }
21189
21190
        break;
21191
      }
21192
21193
    case SuspenseListComponent:
21194
      {
21195
        popSuspenseContext(workInProgress);
21196
        var renderState = workInProgress.memoizedState;
21197
21198
        if (renderState === null) {
21199
          // We're running in the default, "independent" mode. We don't do anything
21200
          // in this mode.
21201
          break;
21202
        }
21203
21204
        var didSuspendAlready = (workInProgress.effectTag & DidCapture) !== NoEffect;
21205
        var renderedTail = renderState.rendering;
21206
21207
        if (renderedTail === null) {
21208
          // We just rendered the head.
21209
          if (!didSuspendAlready) {
21210
            // This is the first pass. We need to figure out if anything is still
21211
            // suspended in the rendered set.
21212
            // If new content unsuspended, but there's still some content that
21213
            // didn't. Then we need to do a second pass that forces everything
21214
            // to keep showing their fallbacks.
21215
            // We might be suspended if something in this render pass suspended, or
21216
            // something in the previous committed pass suspended. Otherwise,
21217
            // there's no chance so we can skip the expensive call to
21218
            // findFirstSuspended.
21219
            var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.effectTag & DidCapture) === NoEffect);
21220
21221
            if (!cannotBeSuspended) {
21222
              var row = workInProgress.child;
21223
21224
              while (row !== null) {
21225
                var suspended = findFirstSuspended(row);
21226
21227
                if (suspended !== null) {
21228
                  didSuspendAlready = true;
21229
                  workInProgress.effectTag |= DidCapture;
21230
                  cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as
21231
                  // part of the second pass. In that case nothing will subscribe to
21232
                  // its thennables. Instead, we'll transfer its thennables to the
21233
                  // SuspenseList so that it can retry if they resolve.
21234
                  // There might be multiple of these in the list but since we're
21235
                  // going to wait for all of them anyway, it doesn't really matter
21236
                  // which ones gets to ping. In theory we could get clever and keep
21237
                  // track of how many dependencies remain but it gets tricky because
21238
                  // in the meantime, we can add/remove/change items and dependencies.
21239
                  // We might bail out of the loop before finding any but that
21240
                  // doesn't matter since that means that the other boundaries that
21241
                  // we did find already has their listeners attached.
21242
21243
                  var newThennables = suspended.updateQueue;
21244
21245
                  if (newThennables !== null) {
21246
                    workInProgress.updateQueue = newThennables;
21247
                    workInProgress.effectTag |= Update;
21248
                  } // Rerender the whole list, but this time, we'll force fallbacks
21249
                  // to stay in place.
21250
                  // Reset the effect list before doing the second pass since that's now invalid.
21251
21252
21253
                  workInProgress.firstEffect = workInProgress.lastEffect = null; // Reset the child fibers to their original state.
21254
21255
                  resetChildFibers(workInProgress, renderExpirationTime); // Set up the Suspense Context to force suspense and immediately
21256
                  // rerender the children.
21257
21258
                  pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));
21259
                  return workInProgress.child;
21260
                }
21261
21262
                row = row.sibling;
21263
              }
21264
            }
21265
          } else {
21266
            cutOffTailIfNeeded(renderState, false);
21267
          } // Next we're going to render the tail.
21268
21269
        } else {
21270
          // Append the rendered row to the child list.
21271
          if (!didSuspendAlready) {
21272
            var _suspended = findFirstSuspended(renderedTail);
21273
21274
            if (_suspended !== null) {
21275
              workInProgress.effectTag |= DidCapture;
21276
              didSuspendAlready = true;
21277
              cutOffTailIfNeeded(renderState, true); // This might have been modified.
21278
21279
              if (renderState.tail === null && renderState.tailMode === 'hidden') {
21280
                // We need to delete the row we just rendered.
21281
                // Ensure we transfer the update queue to the parent.
21282
                var _newThennables = _suspended.updateQueue;
21283
21284
                if (_newThennables !== null) {
21285
                  workInProgress.updateQueue = _newThennables;
21286
                  workInProgress.effectTag |= Update;
21287
                } // Reset the effect list to what it w as before we rendered this
21288
                // child. The nested children have already appended themselves.
21289
21290
21291
                var lastEffect = workInProgress.lastEffect = renderState.lastEffect; // Remove any effects that were appended after this point.
21292
21293
                if (lastEffect !== null) {
21294
                  lastEffect.nextEffect = null;
21295
                } // We're done.
21296
21297
21298
                return null;
21299
              }
21300
            } else if (now() > renderState.tailExpiration && renderExpirationTime > Never) {
21301
              // We have now passed our CPU deadline and we'll just give up further
21302
              // attempts to render the main content and only render fallbacks.
21303
              // The assumption is that this is usually faster.
21304
              workInProgress.effectTag |= DidCapture;
21305
              didSuspendAlready = true;
21306
              cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
21307
              // to get it started back up to attempt the next item. If we can show
21308
              // them, then they really have the same priority as this render.
21309
              // So we'll pick it back up the very next render pass once we've had
21310
              // an opportunity to yield for paint.
21311
21312
              var nextPriority = renderExpirationTime - 1;
21313
              workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority;
21314
21315
              if (enableSchedulerTracing) {
21316
                markSpawnedWork(nextPriority);
21317
              }
21318
            }
21319
          }
21320
21321
          if (renderState.isBackwards) {
21322
            // The effect list of the backwards tail will have been added
21323
            // to the end. This breaks the guarantee that life-cycles fire in
21324
            // sibling order but that isn't a strong guarantee promised by React.
21325
            // Especially since these might also just pop in during future commits.
21326
            // Append to the beginning of the list.
21327
            renderedTail.sibling = workInProgress.child;
21328
            workInProgress.child = renderedTail;
21329
          } else {
21330
            var previousSibling = renderState.last;
21331
21332
            if (previousSibling !== null) {
21333
              previousSibling.sibling = renderedTail;
21334
            } else {
21335
              workInProgress.child = renderedTail;
21336
            }
21337
21338
            renderState.last = renderedTail;
21339
          }
21340
        }
21341
21342
        if (renderState.tail !== null) {
21343
          // We still have tail rows to render.
21344
          if (renderState.tailExpiration === 0) {
21345
            // Heuristic for how long we're willing to spend rendering rows
21346
            // until we just give up and show what we have so far.
21347
            var TAIL_EXPIRATION_TIMEOUT_MS = 500;
21348
            renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS;
21349
          } // Pop a row.
21350
21351
21352
          var next = renderState.tail;
21353
          renderState.rendering = next;
21354
          renderState.tail = next.sibling;
21355
          renderState.lastEffect = workInProgress.lastEffect;
21356
          next.sibling = null; // Restore the context.
21357
          // TODO: We can probably just avoid popping it instead and only
21358
          // setting it the first time we go from not suspended to suspended.
21359
21360
          var suspenseContext = suspenseStackCursor.current;
21361
21362
          if (didSuspendAlready) {
21363
            suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
21364
          } else {
21365
            suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
21366
          }
21367
21368
          pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.
21369
21370
          return next;
21371
        }
21372
21373
        break;
21374
      }
21375
21376
    case FundamentalComponent:
21377
      {
21378
        if (enableFundamentalAPI) {
21379
          var fundamentalImpl = workInProgress.type.impl;
21380
          var fundamentalInstance = workInProgress.stateNode;
21381
21382
          if (fundamentalInstance === null) {
21383
            var getInitialState = fundamentalImpl.getInitialState;
21384
            var fundamentalState;
21385
21386
            if (getInitialState !== undefined) {
21387
              fundamentalState = getInitialState(newProps);
21388
            }
21389
21390
            fundamentalInstance = workInProgress.stateNode = createFundamentalStateInstance(workInProgress, newProps, fundamentalImpl, fundamentalState || {});
21391
21392
            var _instance5 = getFundamentalComponentInstance(fundamentalInstance);
21393
21394
            fundamentalInstance.instance = _instance5;
21395
21396
            if (fundamentalImpl.reconcileChildren === false) {
21397
              return null;
21398
            }
21399
21400
            appendAllChildren(_instance5, workInProgress, false, false);
21401
            mountFundamentalComponent(fundamentalInstance);
21402
          } else {
21403
            // We fire update in commit phase
21404
            var prevProps = fundamentalInstance.props;
21405
            fundamentalInstance.prevProps = prevProps;
21406
            fundamentalInstance.props = newProps;
21407
            fundamentalInstance.currentFiber = workInProgress;
21408
21409
            if (supportsPersistence) {
21410
              var _instance6 = cloneFundamentalInstance(fundamentalInstance);
21411
21412
              fundamentalInstance.instance = _instance6;
21413
              appendAllChildren(_instance6, workInProgress, false, false);
21414
            }
21415
21416
            var shouldUpdate = shouldUpdateFundamentalComponent(fundamentalInstance);
21417
21418
            if (shouldUpdate) {
21419
              markUpdate(workInProgress);
21420
            }
21421
          }
21422
        }
21423
21424
        break;
21425
      }
21426
21427
    case ScopeComponent:
21428
      {
21429
        if (enableScopeAPI) {
21430
          if (current === null) {
21431
            var _type3 = workInProgress.type;
21432
            var scopeInstance = {
21433
              fiber: workInProgress,
21434
              methods: null
21435
            };
21436
            workInProgress.stateNode = scopeInstance;
21437
            scopeInstance.methods = createScopeMethods(_type3, scopeInstance);
21438
21439
            if (enableFlareAPI) {
21440
              var _listeners2 = newProps.listeners;
21441
21442
              if (_listeners2 != null) {
21443
                var _rootContainerInstance2 = getRootHostContainer();
21444
21445
                updateEventListeners(_listeners2, workInProgress, _rootContainerInstance2);
21446
              }
21447
            }
21448
21449
            if (workInProgress.ref !== null) {
21450
              markRef$1(workInProgress);
21451
              markUpdate(workInProgress);
21452
            }
21453
          } else {
21454
            if (enableFlareAPI) {
21455
              var _prevListeners = current.memoizedProps.listeners;
21456
              var _nextListeners = newProps.listeners;
21457
21458
              if (_prevListeners !== _nextListeners || workInProgress.ref !== null) {
21459
                markUpdate(workInProgress);
21460
              }
21461
            } else {
21462
              if (workInProgress.ref !== null) {
21463
                markUpdate(workInProgress);
21464
              }
21465
            }
21466
21467
            if (current.ref !== workInProgress.ref) {
21468
              markRef$1(workInProgress);
21469
            }
21470
          }
21471
        }
21472
21473
        break;
21474
      }
21475
21476
    default:
21477
      (function () {
21478
        {
21479
          {
21480
            throw ReactError(Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue."));
21481
          }
21482
        }
21483
      })();
21484
21485
  }
21486
21487
  return null;
21488
}
21489
21490
function unwindWork(workInProgress, renderExpirationTime) {
21491
  switch (workInProgress.tag) {
21492
    case ClassComponent:
21493
      {
21494
        var Component = workInProgress.type;
21495
21496
        if (isContextProvider(Component)) {
21497
          popContext(workInProgress);
21498
        }
21499
21500
        var effectTag = workInProgress.effectTag;
21501
21502
        if (effectTag & ShouldCapture) {
21503
          workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
21504
          return workInProgress;
21505
        }
21506
21507
        return null;
21508
      }
21509
21510
    case HostRoot:
21511
      {
21512
        popHostContainer(workInProgress);
21513
        popTopLevelContextObject(workInProgress);
21514
        var _effectTag = workInProgress.effectTag;
21515
21516
        (function () {
21517
          if (!((_effectTag & DidCapture) === NoEffect)) {
21518
            {
21519
              throw ReactError(Error("The root failed to unmount after an error. This is likely a bug in React. Please file an issue."));
21520
            }
21521
          }
21522
        })();
21523
21524
        workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
21525
        return workInProgress;
21526
      }
21527
21528
    case HostComponent:
21529
      {
21530
        // TODO: popHydrationState
21531
        popHostContext(workInProgress);
21532
        return null;
21533
      }
21534
21535
    case SuspenseComponent:
21536
      {
21537
        popSuspenseContext(workInProgress);
21538
21539
        if (enableSuspenseServerRenderer) {
21540
          var suspenseState = workInProgress.memoizedState;
21541
21542
          if (suspenseState !== null && suspenseState.dehydrated !== null) {
21543
            (function () {
21544
              if (!(workInProgress.alternate !== null)) {
21545
                {
21546
                  throw ReactError(Error("Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue."));
21547
                }
21548
              }
21549
            })();
21550
21551
            resetHydrationState();
21552
          }
21553
        }
21554
21555
        var _effectTag2 = workInProgress.effectTag;
21556
21557
        if (_effectTag2 & ShouldCapture) {
21558
          workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.
21559
21560
          return workInProgress;
21561
        }
21562
21563
        return null;
21564
      }
21565
21566
    case SuspenseListComponent:
21567
      {
21568
        popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been
21569
        // caught by a nested boundary. If not, it should bubble through.
21570
21571
        return null;
21572
      }
21573
21574
    case HostPortal:
21575
      popHostContainer(workInProgress);
21576
      return null;
21577
21578
    case ContextProvider:
21579
      popProvider(workInProgress);
21580
      return null;
21581
21582
    default:
21583
      return null;
21584
  }
21585
}
21586
21587
function unwindInterruptedWork(interruptedWork) {
21588
  switch (interruptedWork.tag) {
21589
    case ClassComponent:
21590
      {
21591
        var childContextTypes = interruptedWork.type.childContextTypes;
21592
21593
        if (childContextTypes !== null && childContextTypes !== undefined) {
21594
          popContext(interruptedWork);
21595
        }
21596
21597
        break;
21598
      }
21599
21600
    case HostRoot:
21601
      {
21602
        popHostContainer(interruptedWork);
21603
        popTopLevelContextObject(interruptedWork);
21604
        break;
21605
      }
21606
21607
    case HostComponent:
21608
      {
21609
        popHostContext(interruptedWork);
21610
        break;
21611
      }
21612
21613
    case HostPortal:
21614
      popHostContainer(interruptedWork);
21615
      break;
21616
21617
    case SuspenseComponent:
21618
      popSuspenseContext(interruptedWork);
21619
      break;
21620
21621
    case SuspenseListComponent:
21622
      popSuspenseContext(interruptedWork);
21623
      break;
21624
21625
    case ContextProvider:
21626
      popProvider(interruptedWork);
21627
      break;
21628
21629
    default:
21630
      break;
21631
  }
21632
}
21633
21634
function createCapturedValue(value, source) {
21635
  // If the value is an error, call this function immediately after it is thrown
21636
  // so the stack is accurate.
21637
  return {
21638
    value: value,
21639
    source: source,
21640
    stack: getStackByFiberInDevAndProd(source)
21641
  };
21642
}
21643
21644
// This module is forked in different environments.
21645
// By default, return `true` to log errors to the console.
21646
// Forks can return `false` if this isn't desirable.
21647
function showErrorDialog(capturedError) {
21648
  return true;
21649
}
21650
21651
function logCapturedError(capturedError) {
21652
  var logError = showErrorDialog(capturedError); // Allow injected showErrorDialog() to prevent default console.error logging.
21653
  // This enables renderers like ReactNative to better manage redbox behavior.
21654
21655
  if (logError === false) {
21656
    return;
21657
  }
21658
21659
  var error = capturedError.error;
21660
21661
  {
21662
    var componentName = capturedError.componentName,
21663
        componentStack = capturedError.componentStack,
21664
        errorBoundaryName = capturedError.errorBoundaryName,
21665
        errorBoundaryFound = capturedError.errorBoundaryFound,
21666
        willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling
21667
    // `preventDefault()` in window `error` handler.
21668
    // We record this information as an expando on the error.
21669
21670
    if (error != null && error._suppressLogging) {
21671
      if (errorBoundaryFound && willRetry) {
21672
        // The error is recoverable and was silenced.
21673
        // Ignore it and don't print the stack addendum.
21674
        // This is handy for testing error boundaries without noise.
21675
        return;
21676
      } // The error is fatal. Since the silencing might have
21677
      // been accidental, we'll surface it anyway.
21678
      // However, the browser would have silenced the original error
21679
      // so we'll print it first, and then print the stack addendum.
21680
21681
21682
      console.error(error); // For a more detailed description of this block, see:
21683
      // https://github.com/facebook/react/pull/13384
21684
    }
21685
21686
    var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:';
21687
    var errorBoundaryMessage; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
21688
21689
    if (errorBoundaryFound && errorBoundaryName) {
21690
      if (willRetry) {
21691
        errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
21692
      } else {
21693
        errorBoundaryMessage = "This error was initially handled by the error boundary " + errorBoundaryName + ".\n" + "Recreating the tree from scratch failed so React will unmount the tree.";
21694
      }
21695
    } else {
21696
      errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://fb.me/react-error-boundaries to learn more about error boundaries.';
21697
    }
21698
21699
    var combinedMessage = "" + componentNameMessage + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.
21700
    // We don't include the original error message and JS stack because the browser
21701
    // has already printed it. Even if the application swallows the error, it is still
21702
    // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
21703
21704
    console.error(combinedMessage);
21705
  }
21706
}
21707
21708
var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
21709
21710
{
21711
  didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
21712
}
21713
21714
var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
21715
function logError(boundary, errorInfo) {
21716
  var source = errorInfo.source;
21717
  var stack = errorInfo.stack;
21718
21719
  if (stack === null && source !== null) {
21720
    stack = getStackByFiberInDevAndProd(source);
21721
  }
21722
21723
  var capturedError = {
21724
    componentName: source !== null ? getComponentName(source.type) : null,
21725
    componentStack: stack !== null ? stack : '',
21726
    error: errorInfo.value,
21727
    errorBoundary: null,
21728
    errorBoundaryName: null,
21729
    errorBoundaryFound: false,
21730
    willRetry: false
21731
  };
21732
21733
  if (boundary !== null && boundary.tag === ClassComponent) {
21734
    capturedError.errorBoundary = boundary.stateNode;
21735
    capturedError.errorBoundaryName = getComponentName(boundary.type);
21736
    capturedError.errorBoundaryFound = true;
21737
    capturedError.willRetry = true;
21738
  }
21739
21740
  try {
21741
    logCapturedError(capturedError);
21742
  } catch (e) {
21743
    // This method must not throw, or React internal state will get messed up.
21744
    // If console.error is overridden, or logCapturedError() shows a dialog that throws,
21745
    // we want to report this error outside of the normal stack as a last resort.
21746
    // https://github.com/facebook/react/issues/13188
21747
    setTimeout(function () {
21748
      throw e;
21749
    });
21750
  }
21751
}
21752
21753
var callComponentWillUnmountWithTimer = function (current$$1, instance) {
21754
  startPhaseTimer(current$$1, 'componentWillUnmount');
21755
  instance.props = current$$1.memoizedProps;
21756
  instance.state = current$$1.memoizedState;
21757
  instance.componentWillUnmount();
21758
  stopPhaseTimer();
21759
}; // Capture errors so they don't interrupt unmounting.
21760
21761
21762
function safelyCallComponentWillUnmount(current$$1, instance) {
21763
  {
21764
    invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
21765
21766
    if (hasCaughtError()) {
21767
      var unmountError = clearCaughtError();
21768
      captureCommitPhaseError(current$$1, unmountError);
21769
    }
21770
  }
21771
}
21772
21773
function safelyDetachRef(current$$1) {
21774
  var ref = current$$1.ref;
21775
21776
  if (ref !== null) {
21777
    if (typeof ref === 'function') {
21778
      {
21779
        invokeGuardedCallback(null, ref, null, null);
21780
21781
        if (hasCaughtError()) {
21782
          var refError = clearCaughtError();
21783
          captureCommitPhaseError(current$$1, refError);
21784
        }
21785
      }
21786
    } else {
21787
      ref.current = null;
21788
    }
21789
  }
21790
}
21791
21792
function safelyCallDestroy(current$$1, destroy) {
21793
  {
21794
    invokeGuardedCallback(null, destroy, null);
21795
21796
    if (hasCaughtError()) {
21797
      var error = clearCaughtError();
21798
      captureCommitPhaseError(current$$1, error);
21799
    }
21800
  }
21801
}
21802
21803
function commitBeforeMutationLifeCycles(current$$1, finishedWork) {
21804
  switch (finishedWork.tag) {
21805
    case FunctionComponent:
21806
    case ForwardRef:
21807
    case SimpleMemoComponent:
21808
      {
21809
        commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
21810
        return;
21811
      }
21812
21813
    case ClassComponent:
21814
      {
21815
        if (finishedWork.effectTag & Snapshot) {
21816
          if (current$$1 !== null) {
21817
            var prevProps = current$$1.memoizedProps;
21818
            var prevState = current$$1.memoizedState;
21819
            startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
21820
            var instance = finishedWork.stateNode; // We could update instance props and state here,
21821
            // but instead we rely on them being set during last render.
21822
            // TODO: revisit this when we implement resuming.
21823
21824
            {
21825
              if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
21826
                !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
21827
                !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
21828
              }
21829
            }
21830
21831
            var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
21832
21833
            {
21834
              var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
21835
21836
              if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
21837
                didWarnSet.add(finishedWork.type);
21838
                warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
21839
              }
21840
            }
21841
21842
            instance.__reactInternalSnapshotBeforeUpdate = snapshot;
21843
            stopPhaseTimer();
21844
          }
21845
        }
21846
21847
        return;
21848
      }
21849
21850
    case HostRoot:
21851
    case HostComponent:
21852
    case HostText:
21853
    case HostPortal:
21854
    case IncompleteClassComponent:
21855
      // Nothing to do for these component types
21856
      return;
21857
21858
    default:
21859
      {
21860
        (function () {
21861
          {
21862
            {
21863
              throw ReactError(Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."));
21864
            }
21865
          }
21866
        })();
21867
      }
21868
  }
21869
}
21870
21871
function commitHookEffectList(unmountTag, mountTag, finishedWork) {
21872
  var updateQueue = finishedWork.updateQueue;
21873
  var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
21874
21875
  if (lastEffect !== null) {
21876
    var firstEffect = lastEffect.next;
21877
    var effect = firstEffect;
21878
21879
    do {
21880
      if ((effect.tag & unmountTag) !== NoEffect$1) {
21881
        // Unmount
21882
        var destroy = effect.destroy;
21883
        effect.destroy = undefined;
21884
21885
        if (destroy !== undefined) {
21886
          destroy();
21887
        }
21888
      }
21889
21890
      if ((effect.tag & mountTag) !== NoEffect$1) {
21891
        // Mount
21892
        var create = effect.create;
21893
        effect.destroy = create();
21894
21895
        {
21896
          var _destroy = effect.destroy;
21897
21898
          if (_destroy !== undefined && typeof _destroy !== 'function') {
21899
            var addendum = void 0;
21900
21901
            if (_destroy === null) {
21902
              addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
21903
            } else if (typeof _destroy.then === 'function') {
21904
              addendum = '\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + 'useEffect(() => {\n' + '  async function fetchData() {\n' + '    // You can await here\n' + '    const response = await MyAPI.getData(someId);\n' + '    // ...\n' + '  }\n' + '  fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching';
21905
            } else {
21906
              addendum = ' You returned: ' + _destroy;
21907
            }
21908
21909
            warningWithoutStack$1(false, 'An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
21910
          }
21911
        }
21912
      }
21913
21914
      effect = effect.next;
21915
    } while (effect !== firstEffect);
21916
  }
21917
}
21918
21919
function commitPassiveHookEffects(finishedWork) {
21920
  if ((finishedWork.effectTag & Passive) !== NoEffect) {
21921
    switch (finishedWork.tag) {
21922
      case FunctionComponent:
21923
      case ForwardRef:
21924
      case SimpleMemoComponent:
21925
        {
21926
          commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
21927
          commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
21928
          break;
21929
        }
21930
21931
      default:
21932
        break;
21933
    }
21934
  }
21935
}
21936
21937
function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) {
21938
  switch (finishedWork.tag) {
21939
    case FunctionComponent:
21940
    case ForwardRef:
21941
    case SimpleMemoComponent:
21942
      {
21943
        commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
21944
        break;
21945
      }
21946
21947
    case ClassComponent:
21948
      {
21949
        var instance = finishedWork.stateNode;
21950
21951
        if (finishedWork.effectTag & Update) {
21952
          if (current$$1 === null) {
21953
            startPhaseTimer(finishedWork, 'componentDidMount'); // We could update instance props and state here,
21954
            // but instead we rely on them being set during last render.
21955
            // TODO: revisit this when we implement resuming.
21956
21957
            {
21958
              if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
21959
                !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
21960
                !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
21961
              }
21962
            }
21963
21964
            instance.componentDidMount();
21965
            stopPhaseTimer();
21966
          } else {
21967
            var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);
21968
            var prevState = current$$1.memoizedState;
21969
            startPhaseTimer(finishedWork, 'componentDidUpdate'); // We could update instance props and state here,
21970
            // but instead we rely on them being set during last render.
21971
            // TODO: revisit this when we implement resuming.
21972
21973
            {
21974
              if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
21975
                !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
21976
                !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
21977
              }
21978
            }
21979
21980
            instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
21981
            stopPhaseTimer();
21982
          }
21983
        }
21984
21985
        var updateQueue = finishedWork.updateQueue;
21986
21987
        if (updateQueue !== null) {
21988
          {
21989
            if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
21990
              !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
21991
              !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
21992
            }
21993
          } // We could update instance props and state here,
21994
          // but instead we rely on them being set during last render.
21995
          // TODO: revisit this when we implement resuming.
21996
21997
21998
          commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
21999
        }
22000
22001
        return;
22002
      }
22003
22004
    case HostRoot:
22005
      {
22006
        var _updateQueue = finishedWork.updateQueue;
22007
22008
        if (_updateQueue !== null) {
22009
          var _instance = null;
22010
22011
          if (finishedWork.child !== null) {
22012
            switch (finishedWork.child.tag) {
22013
              case HostComponent:
22014
                _instance = getPublicInstance(finishedWork.child.stateNode);
22015
                break;
22016
22017
              case ClassComponent:
22018
                _instance = finishedWork.child.stateNode;
22019
                break;
22020
            }
22021
          }
22022
22023
          commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
22024
        }
22025
22026
        return;
22027
      }
22028
22029
    case HostComponent:
22030
      {
22031
        var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted
22032
        // (eg DOM renderer may schedule auto-focus for inputs and form controls).
22033
        // These effects should only be committed when components are first mounted,
22034
        // aka when there is no current/alternate.
22035
22036
        if (current$$1 === null && finishedWork.effectTag & Update) {
22037
          var type = finishedWork.type;
22038
          var props = finishedWork.memoizedProps;
22039
          commitMount(_instance2, type, props, finishedWork);
22040
        }
22041
22042
        return;
22043
      }
22044
22045
    case HostText:
22046
      {
22047
        // We have no life-cycles associated with text.
22048
        return;
22049
      }
22050
22051
    case HostPortal:
22052
      {
22053
        // We have no life-cycles associated with portals.
22054
        return;
22055
      }
22056
22057
    case Profiler:
22058
      {
22059
        if (enableProfilerTimer) {
22060
          var onRender = finishedWork.memoizedProps.onRender;
22061
22062
          if (typeof onRender === 'function') {
22063
            if (enableSchedulerTracing) {
22064
              onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
22065
            } else {
22066
              onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
22067
            }
22068
          }
22069
        }
22070
22071
        return;
22072
      }
22073
22074
    case SuspenseComponent:
22075
      {
22076
        commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
22077
        return;
22078
      }
22079
22080
    case SuspenseListComponent:
22081
    case IncompleteClassComponent:
22082
    case FundamentalComponent:
22083
    case ScopeComponent:
22084
      return;
22085
22086
    default:
22087
      {
22088
        (function () {
22089
          {
22090
            {
22091
              throw ReactError(Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."));
22092
            }
22093
          }
22094
        })();
22095
      }
22096
  }
22097
}
22098
22099
function hideOrUnhideAllChildren(finishedWork, isHidden) {
22100
  if (supportsMutation) {
22101
    // We only have the top Fiber that was inserted but we need to recurse down its
22102
    // children to find all the terminal nodes.
22103
    var node = finishedWork;
22104
22105
    while (true) {
22106
      if (node.tag === HostComponent) {
22107
        var instance = node.stateNode;
22108
22109
        if (isHidden) {
22110
          hideInstance(instance);
22111
        } else {
22112
          unhideInstance(node.stateNode, node.memoizedProps);
22113
        }
22114
      } else if (node.tag === HostText) {
22115
        var _instance3 = node.stateNode;
22116
22117
        if (isHidden) {
22118
          hideTextInstance(_instance3);
22119
        } else {
22120
          unhideTextInstance(_instance3, node.memoizedProps);
22121
        }
22122
      } else if (node.tag === SuspenseComponent && node.memoizedState !== null && node.memoizedState.dehydrated === null) {
22123
        // Found a nested Suspense component that timed out. Skip over the
22124
        // primary child fragment, which should remain hidden.
22125
        var fallbackChildFragment = node.child.sibling;
22126
        fallbackChildFragment.return = node;
22127
        node = fallbackChildFragment;
22128
        continue;
22129
      } else if (node.child !== null) {
22130
        node.child.return = node;
22131
        node = node.child;
22132
        continue;
22133
      }
22134
22135
      if (node === finishedWork) {
22136
        return;
22137
      }
22138
22139
      while (node.sibling === null) {
22140
        if (node.return === null || node.return === finishedWork) {
22141
          return;
22142
        }
22143
22144
        node = node.return;
22145
      }
22146
22147
      node.sibling.return = node.return;
22148
      node = node.sibling;
22149
    }
22150
  }
22151
}
22152
22153
function commitAttachRef(finishedWork) {
22154
  var ref = finishedWork.ref;
22155
22156
  if (ref !== null) {
22157
    var instance = finishedWork.stateNode;
22158
    var instanceToUse;
22159
22160
    switch (finishedWork.tag) {
22161
      case HostComponent:
22162
        instanceToUse = getPublicInstance(instance);
22163
        break;
22164
22165
      default:
22166
        instanceToUse = instance;
22167
    } // Moved outside to ensure DCE works with this flag
22168
22169
22170
    if (enableScopeAPI && finishedWork.tag === ScopeComponent) {
22171
      instanceToUse = instance.methods;
22172
    }
22173
22174
    if (typeof ref === 'function') {
22175
      ref(instanceToUse);
22176
    } else {
22177
      {
22178
        if (!ref.hasOwnProperty('current')) {
22179
          warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
22180
        }
22181
      }
22182
22183
      ref.current = instanceToUse;
22184
    }
22185
  }
22186
}
22187
22188
function commitDetachRef(current$$1) {
22189
  var currentRef = current$$1.ref;
22190
22191
  if (currentRef !== null) {
22192
    if (typeof currentRef === 'function') {
22193
      currentRef(null);
22194
    } else {
22195
      currentRef.current = null;
22196
    }
22197
  }
22198
} // User-originating errors (lifecycles and refs) should not interrupt
22199
// deletion, so don't let them throw. Host-originating errors should
22200
// interrupt deletion, so it's okay
22201
22202
22203
function commitUnmount(finishedRoot, current$$1, renderPriorityLevel) {
22204
  onCommitUnmount(current$$1);
22205
22206
  switch (current$$1.tag) {
22207
    case FunctionComponent:
22208
    case ForwardRef:
22209
    case MemoComponent:
22210
    case SimpleMemoComponent:
22211
      {
22212
        var updateQueue = current$$1.updateQueue;
22213
22214
        if (updateQueue !== null) {
22215
          var lastEffect = updateQueue.lastEffect;
22216
22217
          if (lastEffect !== null) {
22218
            var firstEffect = lastEffect.next; // When the owner fiber is deleted, the destroy function of a passive
22219
            // effect hook is called during the synchronous commit phase. This is
22220
            // a concession to implementation complexity. Calling it in the
22221
            // passive effect phase (like they usually are, when dependencies
22222
            // change during an update) would require either traversing the
22223
            // children of the deleted fiber again, or including unmount effects
22224
            // as part of the fiber effect list.
22225
            //
22226
            // Because this is during the sync commit phase, we need to change
22227
            // the priority.
22228
            //
22229
            // TODO: Reconsider this implementation trade off.
22230
22231
            var priorityLevel = renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel;
22232
            runWithPriority$2(priorityLevel, function () {
22233
              var effect = firstEffect;
22234
22235
              do {
22236
                var destroy = effect.destroy;
22237
22238
                if (destroy !== undefined) {
22239
                  safelyCallDestroy(current$$1, destroy);
22240
                }
22241
22242
                effect = effect.next;
22243
              } while (effect !== firstEffect);
22244
            });
22245
          }
22246
        }
22247
22248
        break;
22249
      }
22250
22251
    case ClassComponent:
22252
      {
22253
        safelyDetachRef(current$$1);
22254
        var instance = current$$1.stateNode;
22255
22256
        if (typeof instance.componentWillUnmount === 'function') {
22257
          safelyCallComponentWillUnmount(current$$1, instance);
22258
        }
22259
22260
        return;
22261
      }
22262
22263
    case HostComponent:
22264
      {
22265
        if (enableFlareAPI) {
22266
          var dependencies = current$$1.dependencies;
22267
22268
          if (dependencies !== null) {
22269
            var respondersMap = dependencies.responders;
22270
22271
            if (respondersMap !== null) {
22272
              var responderInstances = Array.from(respondersMap.values());
22273
22274
              for (var i = 0, length = responderInstances.length; i < length; i++) {
22275
                var responderInstance = responderInstances[i];
22276
                unmountResponderInstance(responderInstance);
22277
              }
22278
22279
              dependencies.responders = null;
22280
            }
22281
          }
22282
        }
22283
22284
        safelyDetachRef(current$$1);
22285
        return;
22286
      }
22287
22288
    case HostPortal:
22289
      {
22290
        // TODO: this is recursive.
22291
        // We are also not using this parent because
22292
        // the portal will get pushed immediately.
22293
        if (supportsMutation) {
22294
          unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel);
22295
        } else if (supportsPersistence) {
22296
          emptyPortalContainer(current$$1);
22297
        }
22298
22299
        return;
22300
      }
22301
22302
    case FundamentalComponent:
22303
      {
22304
        if (enableFundamentalAPI) {
22305
          var fundamentalInstance = current$$1.stateNode;
22306
22307
          if (fundamentalInstance !== null) {
22308
            unmountFundamentalComponent(fundamentalInstance);
22309
            current$$1.stateNode = null;
22310
          }
22311
        }
22312
22313
        return;
22314
      }
22315
22316
    case DehydratedFragment:
22317
      {
22318
        if (enableSuspenseCallback) {
22319
          var hydrationCallbacks = finishedRoot.hydrationCallbacks;
22320
22321
          if (hydrationCallbacks !== null) {
22322
            var onDeleted = hydrationCallbacks.onDeleted;
22323
22324
            if (onDeleted) {
22325
              onDeleted(current$$1.stateNode);
22326
            }
22327
          }
22328
        }
22329
22330
        return;
22331
      }
22332
22333
    case ScopeComponent:
22334
      {
22335
        if (enableScopeAPI) {
22336
          safelyDetachRef(current$$1);
22337
        }
22338
      }
22339
  }
22340
}
22341
22342
function commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) {
22343
  // While we're inside a removed host node we don't want to call
22344
  // removeChild on the inner nodes because they're removed by the top
22345
  // call anyway. We also want to call componentWillUnmount on all
22346
  // composites before this host node is removed from the tree. Therefore
22347
  // we do an inner loop while we're still inside the host node.
22348
  var node = root;
22349
22350
  while (true) {
22351
    commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because they may contain more composite or host nodes.
22352
    // Skip portals because commitUnmount() currently visits them recursively.
22353
22354
    if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above.
22355
    // If we don't use mutation we drill down into portals here instead.
22356
    !supportsMutation || node.tag !== HostPortal)) {
22357
      node.child.return = node;
22358
      node = node.child;
22359
      continue;
22360
    }
22361
22362
    if (node === root) {
22363
      return;
22364
    }
22365
22366
    while (node.sibling === null) {
22367
      if (node.return === null || node.return === root) {
22368
        return;
22369
      }
22370
22371
      node = node.return;
22372
    }
22373
22374
    node.sibling.return = node.return;
22375
    node = node.sibling;
22376
  }
22377
}
22378
22379
function detachFiber(current$$1) {
22380
  var alternate = current$$1.alternate; // Cut off the return pointers to disconnect it from the tree. Ideally, we
22381
  // should clear the child pointer of the parent alternate to let this
22382
  // get GC:ed but we don't know which for sure which parent is the current
22383
  // one so we'll settle for GC:ing the subtree of this child. This child
22384
  // itself will be GC:ed when the parent updates the next time.
22385
22386
  current$$1.return = null;
22387
  current$$1.child = null;
22388
  current$$1.memoizedState = null;
22389
  current$$1.updateQueue = null;
22390
  current$$1.dependencies = null;
22391
  current$$1.alternate = null;
22392
  current$$1.firstEffect = null;
22393
  current$$1.lastEffect = null;
22394
  current$$1.pendingProps = null;
22395
  current$$1.memoizedProps = null;
22396
22397
  if (alternate !== null) {
22398
    detachFiber(alternate);
22399
  }
22400
}
22401
22402
function emptyPortalContainer(current$$1) {
22403
  if (!supportsPersistence) {
22404
    return;
22405
  }
22406
22407
  var portal = current$$1.stateNode;
22408
  var containerInfo = portal.containerInfo;
22409
  var emptyChildSet = createContainerChildSet(containerInfo);
22410
  replaceContainerChildren(containerInfo, emptyChildSet);
22411
}
22412
22413
function commitContainer(finishedWork) {
22414
  if (!supportsPersistence) {
22415
    return;
22416
  }
22417
22418
  switch (finishedWork.tag) {
22419
    case ClassComponent:
22420
    case HostComponent:
22421
    case HostText:
22422
    case FundamentalComponent:
22423
      {
22424
        return;
22425
      }
22426
22427
    case HostRoot:
22428
    case HostPortal:
22429
      {
22430
        var portalOrRoot = finishedWork.stateNode;
22431
        var containerInfo = portalOrRoot.containerInfo,
22432
            pendingChildren = portalOrRoot.pendingChildren;
22433
        replaceContainerChildren(containerInfo, pendingChildren);
22434
        return;
22435
      }
22436
22437
    default:
22438
      {
22439
        (function () {
22440
          {
22441
            {
22442
              throw ReactError(Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."));
22443
            }
22444
          }
22445
        })();
22446
      }
22447
  }
22448
}
22449
22450
function getHostParentFiber(fiber) {
22451
  var parent = fiber.return;
22452
22453
  while (parent !== null) {
22454
    if (isHostParent(parent)) {
22455
      return parent;
22456
    }
22457
22458
    parent = parent.return;
22459
  }
22460
22461
  (function () {
22462
    {
22463
      {
22464
        throw ReactError(Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."));
22465
      }
22466
    }
22467
  })();
22468
}
22469
22470
function isHostParent(fiber) {
22471
  return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
22472
}
22473
22474
function getHostSibling(fiber) {
22475
  // We're going to search forward into the tree until we find a sibling host
22476
  // node. Unfortunately, if multiple insertions are done in a row we have to
22477
  // search past them. This leads to exponential search for the next sibling.
22478
  // TODO: Find a more efficient way to do this.
22479
  var node = fiber;
22480
22481
  siblings: while (true) {
22482
    // If we didn't find anything, let's try the next sibling.
22483
    while (node.sibling === null) {
22484
      if (node.return === null || isHostParent(node.return)) {
22485
        // If we pop out of the root or hit the parent the fiber we are the
22486
        // last sibling.
22487
        return null;
22488
      }
22489
22490
      node = node.return;
22491
    }
22492
22493
    node.sibling.return = node.return;
22494
    node = node.sibling;
22495
22496
    while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
22497
      // If it is not host node and, we might have a host node inside it.
22498
      // Try to search down until we find one.
22499
      if (node.effectTag & Placement) {
22500
        // If we don't have a child, try the siblings instead.
22501
        continue siblings;
22502
      } // If we don't have a child, try the siblings instead.
22503
      // We also skip portals because they are not part of this host tree.
22504
22505
22506
      if (node.child === null || node.tag === HostPortal) {
22507
        continue siblings;
22508
      } else {
22509
        node.child.return = node;
22510
        node = node.child;
22511
      }
22512
    } // Check if this host node is stable or about to be placed.
22513
22514
22515
    if (!(node.effectTag & Placement)) {
22516
      // Found it!
22517
      return node.stateNode;
22518
    }
22519
  }
22520
}
22521
22522
function commitPlacement(finishedWork) {
22523
  if (!supportsMutation) {
22524
    return;
22525
  } // Recursively insert all host nodes into the parent.
22526
22527
22528
  var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.
22529
22530
  var parent;
22531
  var isContainer;
22532
  var parentStateNode = parentFiber.stateNode;
22533
22534
  switch (parentFiber.tag) {
22535
    case HostComponent:
22536
      parent = parentStateNode;
22537
      isContainer = false;
22538
      break;
22539
22540
    case HostRoot:
22541
      parent = parentStateNode.containerInfo;
22542
      isContainer = true;
22543
      break;
22544
22545
    case HostPortal:
22546
      parent = parentStateNode.containerInfo;
22547
      isContainer = true;
22548
      break;
22549
22550
    case FundamentalComponent:
22551
      if (enableFundamentalAPI) {
22552
        parent = parentStateNode.instance;
22553
        isContainer = false;
22554
      }
22555
22556
    // eslint-disable-next-line-no-fallthrough
22557
22558
    default:
22559
      (function () {
22560
        {
22561
          {
22562
            throw ReactError(Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue."));
22563
          }
22564
        }
22565
      })();
22566
22567
  }
22568
22569
  if (parentFiber.effectTag & ContentReset) {
22570
    // Reset the text content of the parent before doing any insertions
22571
    resetTextContent(parent); // Clear ContentReset from the effect tag
22572
22573
    parentFiber.effectTag &= ~ContentReset;
22574
  }
22575
22576
  var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its
22577
  // children to find all the terminal nodes.
22578
22579
  var node = finishedWork;
22580
22581
  while (true) {
22582
    var isHost = node.tag === HostComponent || node.tag === HostText;
22583
22584
    if (isHost || enableFundamentalAPI && node.tag === FundamentalComponent) {
22585
      var stateNode = isHost ? node.stateNode : node.stateNode.instance;
22586
22587
      if (before) {
22588
        if (isContainer) {
22589
          insertInContainerBefore(parent, stateNode, before);
22590
        } else {
22591
          insertBefore(parent, stateNode, before);
22592
        }
22593
      } else {
22594
        if (isContainer) {
22595
          appendChildToContainer(parent, stateNode);
22596
        } else {
22597
          appendChild(parent, stateNode);
22598
        }
22599
      }
22600
    } else if (node.tag === HostPortal) {// If the insertion itself is a portal, then we don't want to traverse
22601
      // down its children. Instead, we'll get insertions from each child in
22602
      // the portal directly.
22603
    } else if (node.child !== null) {
22604
      node.child.return = node;
22605
      node = node.child;
22606
      continue;
22607
    }
22608
22609
    if (node === finishedWork) {
22610
      return;
22611
    }
22612
22613
    while (node.sibling === null) {
22614
      if (node.return === null || node.return === finishedWork) {
22615
        return;
22616
      }
22617
22618
      node = node.return;
22619
    }
22620
22621
    node.sibling.return = node.return;
22622
    node = node.sibling;
22623
  }
22624
}
22625
22626
function unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel) {
22627
  // We only have the top Fiber that was deleted but we need to recurse down its
22628
  // children to find all the terminal nodes.
22629
  var node = current$$1; // Each iteration, currentParent is populated with node's host parent if not
22630
  // currentParentIsValid.
22631
22632
  var currentParentIsValid = false; // Note: these two variables *must* always be updated together.
22633
22634
  var currentParent;
22635
  var currentParentIsContainer;
22636
22637
  while (true) {
22638
    if (!currentParentIsValid) {
22639
      var parent = node.return;
22640
22641
      findParent: while (true) {
22642
        (function () {
22643
          if (!(parent !== null)) {
22644
            {
22645
              throw ReactError(Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."));
22646
            }
22647
          }
22648
        })();
22649
22650
        var parentStateNode = parent.stateNode;
22651
22652
        switch (parent.tag) {
22653
          case HostComponent:
22654
            currentParent = parentStateNode;
22655
            currentParentIsContainer = false;
22656
            break findParent;
22657
22658
          case HostRoot:
22659
            currentParent = parentStateNode.containerInfo;
22660
            currentParentIsContainer = true;
22661
            break findParent;
22662
22663
          case HostPortal:
22664
            currentParent = parentStateNode.containerInfo;
22665
            currentParentIsContainer = true;
22666
            break findParent;
22667
22668
          case FundamentalComponent:
22669
            if (enableFundamentalAPI) {
22670
              currentParent = parentStateNode.instance;
22671
              currentParentIsContainer = false;
22672
            }
22673
22674
        }
22675
22676
        parent = parent.return;
22677
      }
22678
22679
      currentParentIsValid = true;
22680
    }
22681
22682
    if (node.tag === HostComponent || node.tag === HostText) {
22683
      commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the
22684
      // node from the tree.
22685
22686
      if (currentParentIsContainer) {
22687
        removeChildFromContainer(currentParent, node.stateNode);
22688
      } else {
22689
        removeChild(currentParent, node.stateNode);
22690
      } // Don't visit children because we already visited them.
22691
22692
    } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
22693
      var fundamentalNode = node.stateNode.instance;
22694
      commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the
22695
      // node from the tree.
22696
22697
      if (currentParentIsContainer) {
22698
        removeChildFromContainer(currentParent, fundamentalNode);
22699
      } else {
22700
        removeChild(currentParent, fundamentalNode);
22701
      }
22702
    } else if (enableSuspenseServerRenderer && node.tag === DehydratedFragment) {
22703
      if (enableSuspenseCallback) {
22704
        var hydrationCallbacks = finishedRoot.hydrationCallbacks;
22705
22706
        if (hydrationCallbacks !== null) {
22707
          var onDeleted = hydrationCallbacks.onDeleted;
22708
22709
          if (onDeleted) {
22710
            onDeleted(node.stateNode);
22711
          }
22712
        }
22713
      } // Delete the dehydrated suspense boundary and all of its content.
22714
22715
22716
      if (currentParentIsContainer) {
22717
        clearSuspenseBoundaryFromContainer(currentParent, node.stateNode);
22718
      } else {
22719
        clearSuspenseBoundary(currentParent, node.stateNode);
22720
      }
22721
    } else if (node.tag === HostPortal) {
22722
      if (node.child !== null) {
22723
        // When we go into a portal, it becomes the parent to remove from.
22724
        // We will reassign it back when we pop the portal on the way up.
22725
        currentParent = node.stateNode.containerInfo;
22726
        currentParentIsContainer = true; // Visit children because portals might contain host components.
22727
22728
        node.child.return = node;
22729
        node = node.child;
22730
        continue;
22731
      }
22732
    } else {
22733
      commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because we may find more host components below.
22734
22735
      if (node.child !== null) {
22736
        node.child.return = node;
22737
        node = node.child;
22738
        continue;
22739
      }
22740
    }
22741
22742
    if (node === current$$1) {
22743
      return;
22744
    }
22745
22746
    while (node.sibling === null) {
22747
      if (node.return === null || node.return === current$$1) {
22748
        return;
22749
      }
22750
22751
      node = node.return;
22752
22753
      if (node.tag === HostPortal) {
22754
        // When we go out of the portal, we need to restore the parent.
22755
        // Since we don't keep a stack of them, we will search for it.
22756
        currentParentIsValid = false;
22757
      }
22758
    }
22759
22760
    node.sibling.return = node.return;
22761
    node = node.sibling;
22762
  }
22763
}
22764
22765
function commitDeletion(finishedRoot, current$$1, renderPriorityLevel) {
22766
  if (supportsMutation) {
22767
    // Recursively delete all host nodes from the parent.
22768
    // Detach refs and call componentWillUnmount() on the whole subtree.
22769
    unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel);
22770
  } else {
22771
    // Detach refs and call componentWillUnmount() on the whole subtree.
22772
    commitNestedUnmounts(finishedRoot, current$$1, renderPriorityLevel);
22773
  }
22774
22775
  detachFiber(current$$1);
22776
}
22777
22778
function commitWork(current$$1, finishedWork) {
22779
  if (!supportsMutation) {
22780
    switch (finishedWork.tag) {
22781
      case FunctionComponent:
22782
      case ForwardRef:
22783
      case MemoComponent:
22784
      case SimpleMemoComponent:
22785
        {
22786
          // Note: We currently never use MountMutation, but useLayout uses
22787
          // UnmountMutation.
22788
          commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
22789
          return;
22790
        }
22791
22792
      case Profiler:
22793
        {
22794
          return;
22795
        }
22796
22797
      case SuspenseComponent:
22798
        {
22799
          commitSuspenseComponent(finishedWork);
22800
          attachSuspenseRetryListeners(finishedWork);
22801
          return;
22802
        }
22803
22804
      case SuspenseListComponent:
22805
        {
22806
          attachSuspenseRetryListeners(finishedWork);
22807
          return;
22808
        }
22809
22810
      case HostRoot:
22811
        {
22812
          if (supportsHydration) {
22813
            var root = finishedWork.stateNode;
22814
22815
            if (root.hydrate) {
22816
              // We've just hydrated. No need to hydrate again.
22817
              root.hydrate = false;
22818
              commitHydratedContainer(root.containerInfo);
22819
            }
22820
          }
22821
22822
          break;
22823
        }
22824
    }
22825
22826
    commitContainer(finishedWork);
22827
    return;
22828
  }
22829
22830
  switch (finishedWork.tag) {
22831
    case FunctionComponent:
22832
    case ForwardRef:
22833
    case MemoComponent:
22834
    case SimpleMemoComponent:
22835
      {
22836
        // Note: We currently never use MountMutation, but useLayout uses
22837
        // UnmountMutation.
22838
        commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
22839
        return;
22840
      }
22841
22842
    case ClassComponent:
22843
      {
22844
        return;
22845
      }
22846
22847
    case HostComponent:
22848
      {
22849
        var instance = finishedWork.stateNode;
22850
22851
        if (instance != null) {
22852
          // Commit the work prepared earlier.
22853
          var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
22854
          // as the newProps. The updatePayload will contain the real change in
22855
          // this case.
22856
22857
          var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps;
22858
          var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.
22859
22860
          var updatePayload = finishedWork.updateQueue;
22861
          finishedWork.updateQueue = null;
22862
22863
          if (updatePayload !== null) {
22864
            commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
22865
          }
22866
22867
          if (enableFlareAPI) {
22868
            var prevListeners = oldProps.listeners;
22869
            var nextListeners = newProps.listeners;
22870
22871
            if (prevListeners !== nextListeners) {
22872
              updateEventListeners(nextListeners, finishedWork, null);
22873
            }
22874
          }
22875
        }
22876
22877
        return;
22878
      }
22879
22880
    case HostText:
22881
      {
22882
        (function () {
22883
          if (!(finishedWork.stateNode !== null)) {
22884
            {
22885
              throw ReactError(Error("This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue."));
22886
            }
22887
          }
22888
        })();
22889
22890
        var textInstance = finishedWork.stateNode;
22891
        var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
22892
        // as the newProps. The updatePayload will contain the real change in
22893
        // this case.
22894
22895
        var oldText = current$$1 !== null ? current$$1.memoizedProps : newText;
22896
        commitTextUpdate(textInstance, oldText, newText);
22897
        return;
22898
      }
22899
22900
    case HostRoot:
22901
      {
22902
        if (supportsHydration) {
22903
          var _root = finishedWork.stateNode;
22904
22905
          if (_root.hydrate) {
22906
            // We've just hydrated. No need to hydrate again.
22907
            _root.hydrate = false;
22908
            commitHydratedContainer(_root.containerInfo);
22909
          }
22910
        }
22911
22912
        return;
22913
      }
22914
22915
    case Profiler:
22916
      {
22917
        return;
22918
      }
22919
22920
    case SuspenseComponent:
22921
      {
22922
        commitSuspenseComponent(finishedWork);
22923
        attachSuspenseRetryListeners(finishedWork);
22924
        return;
22925
      }
22926
22927
    case SuspenseListComponent:
22928
      {
22929
        attachSuspenseRetryListeners(finishedWork);
22930
        return;
22931
      }
22932
22933
    case IncompleteClassComponent:
22934
      {
22935
        return;
22936
      }
22937
22938
    case FundamentalComponent:
22939
      {
22940
        if (enableFundamentalAPI) {
22941
          var fundamentalInstance = finishedWork.stateNode;
22942
          updateFundamentalComponent(fundamentalInstance);
22943
        }
22944
22945
        return;
22946
      }
22947
22948
    case ScopeComponent:
22949
      {
22950
        if (enableScopeAPI) {
22951
          var scopeInstance = finishedWork.stateNode;
22952
          scopeInstance.fiber = finishedWork;
22953
22954
          if (enableFlareAPI) {
22955
            var _newProps = finishedWork.memoizedProps;
22956
22957
            var _oldProps = current$$1 !== null ? current$$1.memoizedProps : _newProps;
22958
22959
            var _prevListeners = _oldProps.listeners;
22960
            var _nextListeners = _newProps.listeners;
22961
22962
            if (_prevListeners !== _nextListeners) {
22963
              updateEventListeners(_nextListeners, finishedWork, null);
22964
            }
22965
          }
22966
        }
22967
22968
        return;
22969
      }
22970
22971
    default:
22972
      {
22973
        (function () {
22974
          {
22975
            {
22976
              throw ReactError(Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."));
22977
            }
22978
          }
22979
        })();
22980
      }
22981
  }
22982
}
22983
22984
function commitSuspenseComponent(finishedWork) {
22985
  var newState = finishedWork.memoizedState;
22986
  var newDidTimeout;
22987
  var primaryChildParent = finishedWork;
22988
22989
  if (newState === null) {
22990
    newDidTimeout = false;
22991
  } else {
22992
    newDidTimeout = true;
22993
    primaryChildParent = finishedWork.child;
22994
    markCommitTimeOfFallback();
22995
  }
22996
22997
  if (supportsMutation && primaryChildParent !== null) {
22998
    hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
22999
  }
23000
23001
  if (enableSuspenseCallback && newState !== null) {
23002
    var suspenseCallback = finishedWork.memoizedProps.suspenseCallback;
23003
23004
    if (typeof suspenseCallback === 'function') {
23005
      var thenables = finishedWork.updateQueue;
23006
23007
      if (thenables !== null) {
23008
        suspenseCallback(new Set(thenables));
23009
      }
23010
    } else {
23011
      if (suspenseCallback !== undefined) {
23012
        warning$1(false, 'Unexpected type for suspenseCallback.');
23013
      }
23014
    }
23015
  }
23016
}
23017
23018
function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
23019
  if (!supportsHydration) {
23020
    return;
23021
  }
23022
23023
  var newState = finishedWork.memoizedState;
23024
23025
  if (newState === null) {
23026
    var current$$1 = finishedWork.alternate;
23027
23028
    if (current$$1 !== null) {
23029
      var prevState = current$$1.memoizedState;
23030
23031
      if (prevState !== null) {
23032
        var suspenseInstance = prevState.dehydrated;
23033
23034
        if (suspenseInstance !== null) {
23035
          commitHydratedSuspenseInstance(suspenseInstance);
23036
23037
          if (enableSuspenseCallback) {
23038
            var hydrationCallbacks = finishedRoot.hydrationCallbacks;
23039
23040
            if (hydrationCallbacks !== null) {
23041
              var onHydrated = hydrationCallbacks.onHydrated;
23042
23043
              if (onHydrated) {
23044
                onHydrated(suspenseInstance);
23045
              }
23046
            }
23047
          }
23048
        }
23049
      }
23050
    }
23051
  }
23052
}
23053
23054
function attachSuspenseRetryListeners(finishedWork) {
23055
  // If this boundary just timed out, then it will have a set of thenables.
23056
  // For each thenable, attach a listener so that when it resolves, React
23057
  // attempts to re-render the boundary in the primary (pre-timeout) state.
23058
  var thenables = finishedWork.updateQueue;
23059
23060
  if (thenables !== null) {
23061
    finishedWork.updateQueue = null;
23062
    var retryCache = finishedWork.stateNode;
23063
23064
    if (retryCache === null) {
23065
      retryCache = finishedWork.stateNode = new PossiblyWeakSet();
23066
    }
23067
23068
    thenables.forEach(function (thenable) {
23069
      // Memoize using the boundary fiber to prevent redundant listeners.
23070
      var retry = resolveRetryThenable.bind(null, finishedWork, thenable);
23071
23072
      if (!retryCache.has(thenable)) {
23073
        if (enableSchedulerTracing) {
23074
          if (thenable.__reactDoNotTraceInteractions !== true) {
23075
            retry = tracing.unstable_wrap(retry);
23076
          }
23077
        }
23078
23079
        retryCache.add(thenable);
23080
        thenable.then(retry, retry);
23081
      }
23082
    });
23083
  }
23084
}
23085
23086
function commitResetTextContent(current$$1) {
23087
  if (!supportsMutation) {
23088
    return;
23089
  }
23090
23091
  resetTextContent(current$$1.stateNode);
23092
}
23093
23094
var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;
23095
23096
function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
23097
  var update = createUpdate(expirationTime, null); // Unmount the root by rendering null.
23098
23099
  update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property
23100
  // being called "element".
23101
23102
  update.payload = {
23103
    element: null
23104
  };
23105
  var error = errorInfo.value;
23106
23107
  update.callback = function () {
23108
    onUncaughtError(error);
23109
    logError(fiber, errorInfo);
23110
  };
23111
23112
  return update;
23113
}
23114
23115
function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
23116
  var update = createUpdate(expirationTime, null);
23117
  update.tag = CaptureUpdate;
23118
  var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
23119
23120
  if (typeof getDerivedStateFromError === 'function') {
23121
    var error = errorInfo.value;
23122
23123
    update.payload = function () {
23124
      logError(fiber, errorInfo);
23125
      return getDerivedStateFromError(error);
23126
    };
23127
  }
23128
23129
  var inst = fiber.stateNode;
23130
23131
  if (inst !== null && typeof inst.componentDidCatch === 'function') {
23132
    update.callback = function callback() {
23133
      {
23134
        markFailedErrorBoundaryForHotReloading(fiber);
23135
      }
23136
23137
      if (typeof getDerivedStateFromError !== 'function') {
23138
        // To preserve the preexisting retry behavior of error boundaries,
23139
        // we keep track of which ones already failed during this batch.
23140
        // This gets reset before we yield back to the browser.
23141
        // TODO: Warn in strict mode if getDerivedStateFromError is
23142
        // not defined.
23143
        markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined
23144
23145
        logError(fiber, errorInfo);
23146
      }
23147
23148
      var error = errorInfo.value;
23149
      var stack = errorInfo.stack;
23150
      this.componentDidCatch(error, {
23151
        componentStack: stack !== null ? stack : ''
23152
      });
23153
23154
      {
23155
        if (typeof getDerivedStateFromError !== 'function') {
23156
          // If componentDidCatch is the only error boundary method defined,
23157
          // then it needs to call setState to recover from errors.
23158
          // If no state update is scheduled then the boundary will swallow the error.
23159
          !(fiber.expirationTime === Sync) ? warningWithoutStack$1(false, '%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentName(fiber.type) || 'Unknown') : void 0;
23160
        }
23161
      }
23162
    };
23163
  } else {
23164
    update.callback = function () {
23165
      markFailedErrorBoundaryForHotReloading(fiber);
23166
    };
23167
  }
23168
23169
  return update;
23170
}
23171
23172
function attachPingListener(root, renderExpirationTime, thenable) {
23173
  // Attach a listener to the promise to "ping" the root and retry. But
23174
  // only if one does not already exist for the current render expiration
23175
  // time (which acts like a "thread ID" here).
23176
  var pingCache = root.pingCache;
23177
  var threadIDs;
23178
23179
  if (pingCache === null) {
23180
    pingCache = root.pingCache = new PossiblyWeakMap$1();
23181
    threadIDs = new Set();
23182
    pingCache.set(thenable, threadIDs);
23183
  } else {
23184
    threadIDs = pingCache.get(thenable);
23185
23186
    if (threadIDs === undefined) {
23187
      threadIDs = new Set();
23188
      pingCache.set(thenable, threadIDs);
23189
    }
23190
  }
23191
23192
  if (!threadIDs.has(renderExpirationTime)) {
23193
    // Memoize using the thread ID to prevent redundant listeners.
23194
    threadIDs.add(renderExpirationTime);
23195
    var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);
23196
    thenable.then(ping, ping);
23197
  }
23198
}
23199
23200
function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
23201
  // The source fiber did not complete.
23202
  sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid.
23203
23204
  sourceFiber.firstEffect = sourceFiber.lastEffect = null;
23205
23206
  if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
23207
    // This is a thenable.
23208
    var thenable = value;
23209
    checkForWrongSuspensePriorityInDEV(sourceFiber);
23210
    var hasInvisibleParentBoundary = hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext); // Schedule the nearest Suspense to re-render the timed out view.
23211
23212
    var _workInProgress = returnFiber;
23213
23214
    do {
23215
      if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary)) {
23216
        // Found the nearest boundary.
23217
        // Stash the promise on the boundary fiber. If the boundary times out, we'll
23218
        // attach another listener to flip the boundary back to its normal state.
23219
        var thenables = _workInProgress.updateQueue;
23220
23221
        if (thenables === null) {
23222
          var updateQueue = new Set();
23223
          updateQueue.add(thenable);
23224
          _workInProgress.updateQueue = updateQueue;
23225
        } else {
23226
          thenables.add(thenable);
23227
        } // If the boundary is outside of batched mode, we should *not*
23228
        // suspend the commit. Pretend as if the suspended component rendered
23229
        // null and keep rendering. In the commit phase, we'll schedule a
23230
        // subsequent synchronous update to re-render the Suspense.
23231
        //
23232
        // Note: It doesn't matter whether the component that suspended was
23233
        // inside a batched mode tree. If the Suspense is outside of it, we
23234
        // should *not* suspend the commit.
23235
23236
23237
        if ((_workInProgress.mode & BatchedMode) === NoMode) {
23238
          _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete.
23239
          // But we shouldn't call any lifecycle methods or callbacks. Remove
23240
          // all lifecycle effect tags.
23241
23242
          sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
23243
23244
          if (sourceFiber.tag === ClassComponent) {
23245
            var currentSourceFiber = sourceFiber.alternate;
23246
23247
            if (currentSourceFiber === null) {
23248
              // This is a new mount. Change the tag so it's not mistaken for a
23249
              // completed class component. For example, we should not call
23250
              // componentWillUnmount if it is deleted.
23251
              sourceFiber.tag = IncompleteClassComponent;
23252
            } else {
23253
              // When we try rendering again, we should not reuse the current fiber,
23254
              // since it's known to be in an inconsistent state. Use a force update to
23255
              // prevent a bail out.
23256
              var update = createUpdate(Sync, null);
23257
              update.tag = ForceUpdate;
23258
              enqueueUpdate(sourceFiber, update);
23259
            }
23260
          } // The source fiber did not complete. Mark it with Sync priority to
23261
          // indicate that it still has pending work.
23262
23263
23264
          sourceFiber.expirationTime = Sync; // Exit without suspending.
23265
23266
          return;
23267
        } // Confirmed that the boundary is in a concurrent mode tree. Continue
23268
        // with the normal suspend path.
23269
        //
23270
        // After this we'll use a set of heuristics to determine whether this
23271
        // render pass will run to completion or restart or "suspend" the commit.
23272
        // The actual logic for this is spread out in different places.
23273
        //
23274
        // This first principle is that if we're going to suspend when we complete
23275
        // a root, then we should also restart if we get an update or ping that
23276
        // might unsuspend it, and vice versa. The only reason to suspend is
23277
        // because you think you might want to restart before committing. However,
23278
        // it doesn't make sense to restart only while in the period we're suspended.
23279
        //
23280
        // Restarting too aggressively is also not good because it starves out any
23281
        // intermediate loading state. So we use heuristics to determine when.
23282
        // Suspense Heuristics
23283
        //
23284
        // If nothing threw a Promise or all the same fallbacks are already showing,
23285
        // then don't suspend/restart.
23286
        //
23287
        // If this is an initial render of a new tree of Suspense boundaries and
23288
        // those trigger a fallback, then don't suspend/restart. We want to ensure
23289
        // that we can show the initial loading state as quickly as possible.
23290
        //
23291
        // If we hit a "Delayed" case, such as when we'd switch from content back into
23292
        // a fallback, then we should always suspend/restart. SuspenseConfig applies to
23293
        // this case. If none is defined, JND is used instead.
23294
        //
23295
        // If we're already showing a fallback and it gets "retried", allowing us to show
23296
        // another level, but there's still an inner boundary that would show a fallback,
23297
        // then we suspend/restart for 500ms since the last time we showed a fallback
23298
        // anywhere in the tree. This effectively throttles progressive loading into a
23299
        // consistent train of commits. This also gives us an opportunity to restart to
23300
        // get to the completed state slightly earlier.
23301
        //
23302
        // If there's ambiguity due to batching it's resolved in preference of:
23303
        // 1) "delayed", 2) "initial render", 3) "retry".
23304
        //
23305
        // We want to ensure that a "busy" state doesn't get force committed. We want to
23306
        // ensure that new initial loading states can commit as soon as possible.
23307
23308
23309
        attachPingListener(root, renderExpirationTime, thenable);
23310
        _workInProgress.effectTag |= ShouldCapture;
23311
        _workInProgress.expirationTime = renderExpirationTime;
23312
        return;
23313
      } // This boundary already captured during this render. Continue to the next
23314
      // boundary.
23315
23316
23317
      _workInProgress = _workInProgress.return;
23318
    } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode.
23319
    // TODO: Use invariant so the message is stripped in prod?
23320
23321
23322
    value = new Error((getComponentName(sourceFiber.type) || 'A React component') + ' suspended while rendering, but no fallback UI was specified.\n' + '\n' + 'Add a <Suspense fallback=...> component higher in the tree to ' + 'provide a loading indicator or placeholder to display.' + getStackByFiberInDevAndProd(sourceFiber));
23323
  } // We didn't find a boundary that could handle this type of exception. Start
23324
  // over and traverse parent path again, this time treating the exception
23325
  // as an error.
23326
23327
23328
  renderDidError();
23329
  value = createCapturedValue(value, sourceFiber);
23330
  var workInProgress = returnFiber;
23331
23332
  do {
23333
    switch (workInProgress.tag) {
23334
      case HostRoot:
23335
        {
23336
          var _errorInfo = value;
23337
          workInProgress.effectTag |= ShouldCapture;
23338
          workInProgress.expirationTime = renderExpirationTime;
23339
23340
          var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
23341
23342
          enqueueCapturedUpdate(workInProgress, _update);
23343
          return;
23344
        }
23345
23346
      case ClassComponent:
23347
        // Capture and retry
23348
        var errorInfo = value;
23349
        var ctor = workInProgress.type;
23350
        var instance = workInProgress.stateNode;
23351
23352
        if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
23353
          workInProgress.effectTag |= ShouldCapture;
23354
          workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state
23355
23356
          var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
23357
23358
          enqueueCapturedUpdate(workInProgress, _update2);
23359
          return;
23360
        }
23361
23362
        break;
23363
23364
      default:
23365
        break;
23366
    }
23367
23368
    workInProgress = workInProgress.return;
23369
  } while (workInProgress !== null);
23370
}
23371
23372
var ceil = Math.ceil;
23373
var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
23374
var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
23375
var IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing;
23376
var NoContext =
23377
/*                    */
23378
0;
23379
var BatchedContext =
23380
/*               */
23381
1;
23382
var EventContext =
23383
/*                 */
23384
2;
23385
var DiscreteEventContext =
23386
/*         */
23387
4;
23388
var LegacyUnbatchedContext =
23389
/*       */
23390
8;
23391
var RenderContext =
23392
/*                */
23393
16;
23394
var CommitContext =
23395
/*                */
23396
32;
23397
var RootIncomplete = 0;
23398
var RootFatalErrored = 1;
23399
var RootErrored = 2;
23400
var RootSuspended = 3;
23401
var RootSuspendedWithDelay = 4;
23402
var RootCompleted = 5;
23403
var RootLocked = 6;
23404
// Describes where we are in the React execution stack
23405
var executionContext = NoContext; // The root we're working on
23406
23407
var workInProgressRoot = null; // The fiber we're working on
23408
23409
var workInProgress = null; // The expiration time we're rendering
23410
23411
var renderExpirationTime = NoWork; // Whether to root completed, errored, suspended, etc.
23412
23413
var workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown
23414
23415
var workInProgressRootFatalError = null; // Most recent event time among processed updates during this render.
23416
// This is conceptually a time stamp but expressed in terms of an ExpirationTime
23417
// because we deal mostly with expiration times in the hot path, so this avoids
23418
// the conversion happening in the hot path.
23419
23420
var workInProgressRootLatestProcessedExpirationTime = Sync;
23421
var workInProgressRootLatestSuspenseTimeout = Sync;
23422
var workInProgressRootCanSuspendUsingConfig = null; // The work left over by components that were visited during this render. Only
23423
// includes unprocessed updates, not work in bailed out children.
23424
23425
var workInProgressRootNextUnprocessedUpdateTime = NoWork; // If we're pinged while rendering we don't always restart immediately.
23426
// This flag determines if it might be worthwhile to restart if an opportunity
23427
// happens latere.
23428
23429
var workInProgressRootHasPendingPing = false; // The most recent time we committed a fallback. This lets us ensure a train
23430
// model where we don't commit new loading states in too quick succession.
23431
23432
var globalMostRecentFallbackTime = 0;
23433
var FALLBACK_THROTTLE_MS = 500;
23434
var nextEffect = null;
23435
var hasUncaughtError = false;
23436
var firstUncaughtError = null;
23437
var legacyErrorBoundariesThatAlreadyFailed = null;
23438
var rootDoesHavePassiveEffects = false;
23439
var rootWithPendingPassiveEffects = null;
23440
var pendingPassiveEffectsRenderPriority = NoPriority;
23441
var pendingPassiveEffectsExpirationTime = NoWork;
23442
var rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates
23443
23444
var NESTED_UPDATE_LIMIT = 50;
23445
var nestedUpdateCount = 0;
23446
var rootWithNestedUpdates = null;
23447
var NESTED_PASSIVE_UPDATE_LIMIT = 50;
23448
var nestedPassiveUpdateCount = 0;
23449
var interruptedBy = null; // Marks the need to reschedule pending interactions at these expiration times
23450
// during the commit phase. This enables them to be traced across components
23451
// that spawn new work during render. E.g. hidden boundaries, suspended SSR
23452
// hydration or SuspenseList.
23453
23454
var spawnedWorkDuringRender = null; // Expiration times are computed by adding to the current time (the start
23455
// time). However, if two updates are scheduled within the same event, we
23456
// should treat their start times as simultaneous, even if the actual clock
23457
// time has advanced between the first and second call.
23458
// In other words, because expiration times determine how updates are batched,
23459
// we want all updates of like priority that occur within the same event to
23460
// receive the same expiration time. Otherwise we get tearing.
23461
23462
var currentEventTime = NoWork;
23463
function requestCurrentTime() {
23464
  if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
23465
    // We're inside React, so it's fine to read the actual time.
23466
    return msToExpirationTime(now());
23467
  } // We're not inside React, so we may be in the middle of a browser event.
23468
23469
23470
  if (currentEventTime !== NoWork) {
23471
    // Use the same start time for all updates until we enter React again.
23472
    return currentEventTime;
23473
  } // This is the first update since React yielded. Compute a new start time.
23474
23475
23476
  currentEventTime = msToExpirationTime(now());
23477
  return currentEventTime;
23478
}
23479
function computeExpirationForFiber(currentTime, fiber, suspenseConfig) {
23480
  var mode = fiber.mode;
23481
23482
  if ((mode & BatchedMode) === NoMode) {
23483
    return Sync;
23484
  }
23485
23486
  var priorityLevel = getCurrentPriorityLevel();
23487
23488
  if ((mode & ConcurrentMode) === NoMode) {
23489
    return priorityLevel === ImmediatePriority ? Sync : Batched;
23490
  }
23491
23492
  if ((executionContext & RenderContext) !== NoContext) {
23493
    // Use whatever time we're already rendering
23494
    // TODO: Should there be a way to opt out, like with `runWithPriority`?
23495
    return renderExpirationTime;
23496
  }
23497
23498
  var expirationTime;
23499
23500
  if (suspenseConfig !== null) {
23501
    // Compute an expiration time based on the Suspense timeout.
23502
    expirationTime = computeSuspenseExpiration(currentTime, suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
23503
  } else {
23504
    // Compute an expiration time based on the Scheduler priority.
23505
    switch (priorityLevel) {
23506
      case ImmediatePriority:
23507
        expirationTime = Sync;
23508
        break;
23509
23510
      case UserBlockingPriority$2:
23511
        // TODO: Rename this to computeUserBlockingExpiration
23512
        expirationTime = computeInteractiveExpiration(currentTime);
23513
        break;
23514
23515
      case NormalPriority:
23516
      case LowPriority:
23517
        // TODO: Handle LowPriority
23518
        // TODO: Rename this to... something better.
23519
        expirationTime = computeAsyncExpiration(currentTime);
23520
        break;
23521
23522
      case IdlePriority:
23523
        expirationTime = Idle;
23524
        break;
23525
23526
      default:
23527
        (function () {
23528
          {
23529
            {
23530
              throw ReactError(Error("Expected a valid priority level"));
23531
            }
23532
          }
23533
        })();
23534
23535
    }
23536
  } // If we're in the middle of rendering a tree, do not update at the same
23537
  // expiration time that is already rendering.
23538
  // TODO: We shouldn't have to do this if the update is on a different root.
23539
  // Refactor computeExpirationForFiber + scheduleUpdate so we have access to
23540
  // the root when we check for this condition.
23541
23542
23543
  if (workInProgressRoot !== null && expirationTime === renderExpirationTime) {
23544
    // This is a trick to move this update into a separate batch
23545
    expirationTime -= 1;
23546
  }
23547
23548
  return expirationTime;
23549
}
23550
var lastUniqueAsyncExpiration = NoWork;
23551
function computeUniqueAsyncExpiration() {
23552
  var currentTime = requestCurrentTime();
23553
  var result = computeAsyncExpiration(currentTime);
23554
23555
  if (result <= lastUniqueAsyncExpiration) {
23556
    // Since we assume the current time monotonically increases, we only hit
23557
    // this branch when computeUniqueAsyncExpiration is fired multiple times
23558
    // within a 200ms window (or whatever the async bucket size is).
23559
    result -= 1;
23560
  }
23561
23562
  lastUniqueAsyncExpiration = result;
23563
  return result;
23564
}
23565
function scheduleUpdateOnFiber(fiber, expirationTime) {
23566
  checkForNestedUpdates();
23567
  warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber);
23568
  var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime);
23569
23570
  if (root === null) {
23571
    warnAboutUpdateOnUnmountedFiberInDEV(fiber);
23572
    return;
23573
  }
23574
23575
  checkForInterruption(fiber, expirationTime);
23576
  recordScheduleUpdate(); // TODO: computeExpirationForFiber also reads the priority. Pass the
23577
  // priority as an argument to that function and this one.
23578
23579
  var priorityLevel = getCurrentPriorityLevel();
23580
23581
  if (expirationTime === Sync) {
23582
    if ( // Check if we're inside unbatchedUpdates
23583
    (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering
23584
    (executionContext & (RenderContext | CommitContext)) === NoContext) {
23585
      // Register pending interactions on the root to avoid losing traced interaction data.
23586
      schedulePendingInteractions(root, expirationTime); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed
23587
      // root inside of batchedUpdates should be synchronous, but layout updates
23588
      // should be deferred until the end of the batch.
23589
23590
      performSyncWorkOnRoot(root);
23591
    } else {
23592
      ensureRootIsScheduled(root);
23593
      schedulePendingInteractions(root, expirationTime);
23594
23595
      if (executionContext === NoContext) {
23596
        // Flush the synchronous work now, unless we're already working or inside
23597
        // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
23598
        // scheduleCallbackForFiber to preserve the ability to schedule a callback
23599
        // without immediately flushing it. We only do this for user-initiated
23600
        // updates, to preserve historical behavior of sync mode.
23601
        flushSyncCallbackQueue();
23602
      }
23603
    }
23604
  } else {
23605
    ensureRootIsScheduled(root);
23606
    schedulePendingInteractions(root, expirationTime);
23607
  }
23608
23609
  if ((executionContext & DiscreteEventContext) !== NoContext && ( // Only updates at user-blocking priority or greater are considered
23610
  // discrete, even inside a discrete event.
23611
  priorityLevel === UserBlockingPriority$2 || priorityLevel === ImmediatePriority)) {
23612
    // This is the result of a discrete event. Track the lowest priority
23613
    // discrete update per root so we can flush them early, if needed.
23614
    if (rootsWithPendingDiscreteUpdates === null) {
23615
      rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]);
23616
    } else {
23617
      var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);
23618
23619
      if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) {
23620
        rootsWithPendingDiscreteUpdates.set(root, expirationTime);
23621
      }
23622
    }
23623
  }
23624
}
23625
var scheduleWork = scheduleUpdateOnFiber; // This is split into a separate function so we can mark a fiber with pending
23626
// work without treating it as a typical update that originates from an event;
23627
// e.g. retrying a Suspense boundary isn't an update, but it does schedule work
23628
// on a fiber.
23629
23630
function markUpdateTimeFromFiberToRoot(fiber, expirationTime) {
23631
  // Update the source fiber's expiration time
23632
  if (fiber.expirationTime < expirationTime) {
23633
    fiber.expirationTime = expirationTime;
23634
  }
23635
23636
  var alternate = fiber.alternate;
23637
23638
  if (alternate !== null && alternate.expirationTime < expirationTime) {
23639
    alternate.expirationTime = expirationTime;
23640
  } // Walk the parent path to the root and update the child expiration time.
23641
23642
23643
  var node = fiber.return;
23644
  var root = null;
23645
23646
  if (node === null && fiber.tag === HostRoot) {
23647
    root = fiber.stateNode;
23648
  } else {
23649
    while (node !== null) {
23650
      alternate = node.alternate;
23651
23652
      if (node.childExpirationTime < expirationTime) {
23653
        node.childExpirationTime = expirationTime;
23654
23655
        if (alternate !== null && alternate.childExpirationTime < expirationTime) {
23656
          alternate.childExpirationTime = expirationTime;
23657
        }
23658
      } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
23659
        alternate.childExpirationTime = expirationTime;
23660
      }
23661
23662
      if (node.return === null && node.tag === HostRoot) {
23663
        root = node.stateNode;
23664
        break;
23665
      }
23666
23667
      node = node.return;
23668
    }
23669
  }
23670
23671
  if (root !== null) {
23672
    if (workInProgressRoot === root) {
23673
      // Received an update to a tree that's in the middle of rendering. Mark
23674
      // that's unprocessed work on this root.
23675
      markUnprocessedUpdateTime(expirationTime);
23676
23677
      if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
23678
        // The root already suspended with a delay, which means this render
23679
        // definitely won't finish. Since we have a new update, let's mark it as
23680
        // suspended now, right before marking the incoming update. This has the
23681
        // effect of interrupting the current render and switching to the update.
23682
        // TODO: This happens to work when receiving an update during the render
23683
        // phase, because of the trick inside computeExpirationForFiber to
23684
        // subtract 1 from `renderExpirationTime` to move it into a
23685
        // separate bucket. But we should probably model it with an exception,
23686
        // using the same mechanism we use to force hydration of a subtree.
23687
        // TODO: This does not account for low pri updates that were already
23688
        // scheduled before the root started rendering. Need to track the next
23689
        // pending expiration time (perhaps by backtracking the return path) and
23690
        // then trigger a restart in the `renderDidSuspendDelayIfPossible` path.
23691
        markRootSuspendedAtTime(root, renderExpirationTime);
23692
      }
23693
    } // Mark that the root has a pending update.
23694
23695
23696
    markRootUpdatedAtTime(root, expirationTime);
23697
  }
23698
23699
  return root;
23700
}
23701
23702
function getNextRootExpirationTimeToWorkOn(root) {
23703
  // Determines the next expiration time that the root should render, taking
23704
  // into account levels that may be suspended, or levels that may have
23705
  // received a ping.
23706
  var lastExpiredTime = root.lastExpiredTime;
23707
23708
  if (lastExpiredTime !== NoWork) {
23709
    return lastExpiredTime;
23710
  } // "Pending" refers to any update that hasn't committed yet, including if it
23711
  // suspended. The "suspended" range is therefore a subset.
23712
23713
23714
  var firstPendingTime = root.firstPendingTime;
23715
23716
  if (!isRootSuspendedAtTime(root, firstPendingTime)) {
23717
    // The highest priority pending time is not suspended. Let's work on that.
23718
    return firstPendingTime;
23719
  } // If the first pending time is suspended, check if there's a lower priority
23720
  // pending level that we know about. Or check if we received a ping. Work
23721
  // on whichever is higher priority.
23722
23723
23724
  var lastPingedTime = root.lastPingedTime;
23725
  var nextKnownPendingLevel = root.nextKnownPendingLevel;
23726
  return lastPingedTime > nextKnownPendingLevel ? lastPingedTime : nextKnownPendingLevel;
23727
} // Use this function to schedule a task for a root. There's only one task per
23728
// root; if a task was already scheduled, we'll check to make sure the
23729
// expiration time of the existing task is the same as the expiration time of
23730
// the next level that the root has work on. This function is called on every
23731
// update, and right before exiting a task.
23732
23733
23734
function ensureRootIsScheduled(root) {
23735
  var lastExpiredTime = root.lastExpiredTime;
23736
23737
  if (lastExpiredTime !== NoWork) {
23738
    // Special case: Expired work should flush synchronously.
23739
    root.callbackExpirationTime = Sync;
23740
    root.callbackPriority = ImmediatePriority;
23741
    root.callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
23742
    return;
23743
  }
23744
23745
  var expirationTime = getNextRootExpirationTimeToWorkOn(root);
23746
  var existingCallbackNode = root.callbackNode;
23747
23748
  if (expirationTime === NoWork) {
23749
    // There's nothing to work on.
23750
    if (existingCallbackNode !== null) {
23751
      root.callbackNode = null;
23752
      root.callbackExpirationTime = NoWork;
23753
      root.callbackPriority = NoPriority;
23754
    }
23755
23756
    return;
23757
  } // TODO: If this is an update, we already read the current time. Pass the
23758
  // time as an argument.
23759
23760
23761
  var currentTime = requestCurrentTime();
23762
  var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime); // If there's an existing render task, confirm it has the correct priority and
23763
  // expiration time. Otherwise, we'll cancel it and schedule a new one.
23764
23765
  if (existingCallbackNode !== null) {
23766
    var existingCallbackPriority = root.callbackPriority;
23767
    var existingCallbackExpirationTime = root.callbackExpirationTime;
23768
23769
    if ( // Callback must have the exact same expiration time.
23770
    existingCallbackExpirationTime === expirationTime && // Callback must have greater or equal priority.
23771
    existingCallbackPriority >= priorityLevel) {
23772
      // Existing callback is sufficient.
23773
      return;
23774
    } // Need to schedule a new task.
23775
    // TODO: Instead of scheduling a new task, we should be able to change the
23776
    // priority of the existing one.
23777
23778
23779
    cancelCallback(existingCallbackNode);
23780
  }
23781
23782
  root.callbackExpirationTime = expirationTime;
23783
  root.callbackPriority = priorityLevel;
23784
  var callbackNode;
23785
23786
  if (expirationTime === Sync) {
23787
    // Sync React callbacks are scheduled on a special internal queue
23788
    callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
23789
  } else if (disableSchedulerTimeoutBasedOnReactExpirationTime) {
23790
    callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root));
23791
  } else {
23792
    callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root), // Compute a task timeout based on the expiration time. This also affects
23793
    // ordering because tasks are processed in timeout order.
23794
    {
23795
      timeout: expirationTimeToMs(expirationTime) - now()
23796
    });
23797
  }
23798
23799
  root.callbackNode = callbackNode;
23800
} // This is the entry point for every concurrent task, i.e. anything that
23801
// goes through Scheduler.
23802
23803
23804
function performConcurrentWorkOnRoot(root, didTimeout) {
23805
  // Since we know we're in a React event, we can clear the current
23806
  // event time. The next update will compute a new event time.
23807
  currentEventTime = NoWork;
23808
23809
  if (didTimeout) {
23810
    // The render task took too long to complete. Mark the current time as
23811
    // expired to synchronously render all expired work in a single batch.
23812
    var currentTime = requestCurrentTime();
23813
    markRootExpiredAtTime(root, currentTime); // This will schedule a synchronous callback.
23814
23815
    ensureRootIsScheduled(root);
23816
    return null;
23817
  } // Determine the next expiration time to work on, using the fields stored
23818
  // on the root.
23819
23820
23821
  var expirationTime = getNextRootExpirationTimeToWorkOn(root);
23822
23823
  if (expirationTime !== NoWork) {
23824
    var originalCallbackNode = root.callbackNode;
23825
23826
    (function () {
23827
      if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
23828
        {
23829
          throw ReactError(Error("Should not already be working."));
23830
        }
23831
      }
23832
    })();
23833
23834
    flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
23835
    // and prepare a fresh one. Otherwise we'll continue where we left off.
23836
23837
    if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) {
23838
      prepareFreshStack(root, expirationTime);
23839
      startWorkOnPendingInteractions(root, expirationTime);
23840
    } // If we have a work-in-progress fiber, it means there's still work to do
23841
    // in this root.
23842
23843
23844
    if (workInProgress !== null) {
23845
      var prevExecutionContext = executionContext;
23846
      executionContext |= RenderContext;
23847
      var prevDispatcher = pushDispatcher(root);
23848
      var prevInteractions = pushInteractions(root);
23849
      startWorkLoopTimer(workInProgress);
23850
23851
      do {
23852
        try {
23853
          workLoopConcurrent();
23854
          break;
23855
        } catch (thrownValue) {
23856
          handleError(root, thrownValue);
23857
        }
23858
      } while (true);
23859
23860
      resetContextDependencies();
23861
      executionContext = prevExecutionContext;
23862
      popDispatcher(prevDispatcher);
23863
23864
      if (enableSchedulerTracing) {
23865
        popInteractions(prevInteractions);
23866
      }
23867
23868
      if (workInProgressRootExitStatus === RootFatalErrored) {
23869
        var fatalError = workInProgressRootFatalError;
23870
        stopInterruptedWorkLoopTimer();
23871
        prepareFreshStack(root, expirationTime);
23872
        markRootSuspendedAtTime(root, expirationTime);
23873
        ensureRootIsScheduled(root);
23874
        throw fatalError;
23875
      }
23876
23877
      if (workInProgress !== null) {
23878
        // There's still work left over. Exit without committing.
23879
        stopInterruptedWorkLoopTimer();
23880
      } else {
23881
        // We now have a consistent tree. The next step is either to commit it,
23882
        // or, if something suspended, wait to commit it after a timeout.
23883
        stopFinishedWorkLoopTimer();
23884
        var finishedWork = root.finishedWork = root.current.alternate;
23885
        root.finishedExpirationTime = expirationTime;
23886
        resolveLocksOnRoot(root, expirationTime);
23887
        finishConcurrentRender(root, finishedWork, workInProgressRootExitStatus, expirationTime);
23888
      }
23889
23890
      ensureRootIsScheduled(root);
23891
23892
      if (root.callbackNode === originalCallbackNode) {
23893
        // The task node scheduled for this root is the same one that's
23894
        // currently executed. Need to return a continuation.
23895
        return performConcurrentWorkOnRoot.bind(null, root);
23896
      }
23897
    }
23898
  }
23899
23900
  return null;
23901
}
23902
23903
function finishConcurrentRender(root, finishedWork, exitStatus, expirationTime) {
23904
  // Set this to null to indicate there's no in-progress render.
23905
  workInProgressRoot = null;
23906
23907
  switch (exitStatus) {
23908
    case RootIncomplete:
23909
    case RootFatalErrored:
23910
      {
23911
        (function () {
23912
          {
23913
            {
23914
              throw ReactError(Error("Root did not complete. This is a bug in React."));
23915
            }
23916
          }
23917
        })();
23918
      }
23919
    // Flow knows about invariant, so it complains if I add a break
23920
    // statement, but eslint doesn't know about invariant, so it complains
23921
    // if I do. eslint-disable-next-line no-fallthrough
23922
23923
    case RootErrored:
23924
      {
23925
        if (expirationTime !== Idle) {
23926
          // If this was an async render, the error may have happened due to
23927
          // a mutation in a concurrent event. Try rendering one more time,
23928
          // synchronously, to see if the error goes away. If there are
23929
          // lower priority updates, let's include those, too, in case they
23930
          // fix the inconsistency. Render at Idle to include all updates.
23931
          markRootExpiredAtTime(root, Idle);
23932
          break;
23933
        } // Commit the root in its errored state.
23934
23935
23936
        commitRoot(root);
23937
        break;
23938
      }
23939
23940
    case RootSuspended:
23941
      {
23942
        markRootSuspendedAtTime(root, expirationTime);
23943
        var lastSuspendedTime = root.lastSuspendedTime;
23944
23945
        if (expirationTime === lastSuspendedTime) {
23946
          root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
23947
        }
23948
23949
        flushSuspensePriorityWarningInDEV(); // We have an acceptable loading state. We need to figure out if we
23950
        // should immediately commit it or wait a bit.
23951
        // If we have processed new updates during this render, we may now
23952
        // have a new loading state ready. We want to ensure that we commit
23953
        // that as soon as possible.
23954
23955
        var hasNotProcessedNewUpdates = workInProgressRootLatestProcessedExpirationTime === Sync;
23956
23957
        if (hasNotProcessedNewUpdates && // do not delay if we're inside an act() scope
23958
        !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current)) {
23959
          // If we have not processed any new updates during this pass, then
23960
          // this is either a retry of an existing fallback state or a
23961
          // hidden tree. Hidden trees shouldn't be batched with other work
23962
          // and after that's fixed it can only be a retry. We're going to
23963
          // throttle committing retries so that we don't show too many
23964
          // loading states too quickly.
23965
          var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.
23966
23967
          if (msUntilTimeout > 10) {
23968
            if (workInProgressRootHasPendingPing) {
23969
              var lastPingedTime = root.lastPingedTime;
23970
23971
              if (lastPingedTime === NoWork || lastPingedTime >= expirationTime) {
23972
                // This render was pinged but we didn't get to restart
23973
                // earlier so try restarting now instead.
23974
                root.lastPingedTime = expirationTime;
23975
                prepareFreshStack(root, expirationTime);
23976
                break;
23977
              }
23978
            }
23979
23980
            var nextTime = getNextRootExpirationTimeToWorkOn(root);
23981
23982
            if (nextTime !== NoWork && nextTime !== expirationTime) {
23983
              // There's additional work on this root.
23984
              break;
23985
            }
23986
23987
            if (lastSuspendedTime !== NoWork && lastSuspendedTime !== expirationTime) {
23988
              // We should prefer to render the fallback of at the last
23989
              // suspended level. Ping the last suspended level to try
23990
              // rendering it again.
23991
              root.lastPingedTime = lastSuspendedTime;
23992
              break;
23993
            } // The render is suspended, it hasn't timed out, and there's no
23994
            // lower priority work to do. Instead of committing the fallback
23995
            // immediately, wait for more data to arrive.
23996
23997
23998
            root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), msUntilTimeout);
23999
            break;
24000
          }
24001
        } // The work expired. Commit immediately.
24002
24003
24004
        commitRoot(root);
24005
        break;
24006
      }
24007
24008
    case RootSuspendedWithDelay:
24009
      {
24010
        markRootSuspendedAtTime(root, expirationTime);
24011
        var _lastSuspendedTime = root.lastSuspendedTime;
24012
24013
        if (expirationTime === _lastSuspendedTime) {
24014
          root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
24015
        }
24016
24017
        flushSuspensePriorityWarningInDEV();
24018
24019
        if ( // do not delay if we're inside an act() scope
24020
        !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current)) {
24021
          // We're suspended in a state that should be avoided. We'll try to
24022
          // avoid committing it for as long as the timeouts let us.
24023
          if (workInProgressRootHasPendingPing) {
24024
            var _lastPingedTime = root.lastPingedTime;
24025
24026
            if (_lastPingedTime === NoWork || _lastPingedTime >= expirationTime) {
24027
              // This render was pinged but we didn't get to restart earlier
24028
              // so try restarting now instead.
24029
              root.lastPingedTime = expirationTime;
24030
              prepareFreshStack(root, expirationTime);
24031
              break;
24032
            }
24033
          }
24034
24035
          var _nextTime = getNextRootExpirationTimeToWorkOn(root);
24036
24037
          if (_nextTime !== NoWork && _nextTime !== expirationTime) {
24038
            // There's additional work on this root.
24039
            break;
24040
          }
24041
24042
          if (_lastSuspendedTime !== NoWork && _lastSuspendedTime !== expirationTime) {
24043
            // We should prefer to render the fallback of at the last
24044
            // suspended level. Ping the last suspended level to try
24045
            // rendering it again.
24046
            root.lastPingedTime = _lastSuspendedTime;
24047
            break;
24048
          }
24049
24050
          var _msUntilTimeout;
24051
24052
          if (workInProgressRootLatestSuspenseTimeout !== Sync) {
24053
            // We have processed a suspense config whose expiration time we
24054
            // can use as the timeout.
24055
            _msUntilTimeout = expirationTimeToMs(workInProgressRootLatestSuspenseTimeout) - now();
24056
          } else if (workInProgressRootLatestProcessedExpirationTime === Sync) {
24057
            // This should never normally happen because only new updates
24058
            // cause delayed states, so we should have processed something.
24059
            // However, this could also happen in an offscreen tree.
24060
            _msUntilTimeout = 0;
24061
          } else {
24062
            // If we don't have a suspense config, we're going to use a
24063
            // heuristic to determine how long we can suspend.
24064
            var eventTimeMs = inferTimeFromExpirationTime(workInProgressRootLatestProcessedExpirationTime);
24065
            var currentTimeMs = now();
24066
            var timeUntilExpirationMs = expirationTimeToMs(expirationTime) - currentTimeMs;
24067
            var timeElapsed = currentTimeMs - eventTimeMs;
24068
24069
            if (timeElapsed < 0) {
24070
              // We get this wrong some time since we estimate the time.
24071
              timeElapsed = 0;
24072
            }
24073
24074
            _msUntilTimeout = jnd(timeElapsed) - timeElapsed; // Clamp the timeout to the expiration time. TODO: Once the
24075
            // event time is exact instead of inferred from expiration time
24076
            // we don't need this.
24077
24078
            if (timeUntilExpirationMs < _msUntilTimeout) {
24079
              _msUntilTimeout = timeUntilExpirationMs;
24080
            }
24081
          } // Don't bother with a very short suspense time.
24082
24083
24084
          if (_msUntilTimeout > 10) {
24085
            // The render is suspended, it hasn't timed out, and there's no
24086
            // lower priority work to do. Instead of committing the fallback
24087
            // immediately, wait for more data to arrive.
24088
            root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout);
24089
            break;
24090
          }
24091
        } // The work expired. Commit immediately.
24092
24093
24094
        commitRoot(root);
24095
        break;
24096
      }
24097
24098
    case RootCompleted:
24099
      {
24100
        // The work completed. Ready to commit.
24101
        if ( // do not delay if we're inside an act() scope
24102
        !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current) && workInProgressRootLatestProcessedExpirationTime !== Sync && workInProgressRootCanSuspendUsingConfig !== null) {
24103
          // If we have exceeded the minimum loading delay, which probably
24104
          // means we have shown a spinner already, we might have to suspend
24105
          // a bit longer to ensure that the spinner is shown for
24106
          // enough time.
24107
          var _msUntilTimeout2 = computeMsUntilSuspenseLoadingDelay(workInProgressRootLatestProcessedExpirationTime, expirationTime, workInProgressRootCanSuspendUsingConfig);
24108
24109
          if (_msUntilTimeout2 > 10) {
24110
            markRootSuspendedAtTime(root, expirationTime);
24111
            root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout2);
24112
            break;
24113
          }
24114
        }
24115
24116
        commitRoot(root);
24117
        break;
24118
      }
24119
24120
    case RootLocked:
24121
      {
24122
        // This root has a lock that prevents it from committing. Exit. If
24123
        // we begin work on the root again, without any intervening updates,
24124
        // it will finish without doing additional work.
24125
        markRootSuspendedAtTime(root, expirationTime);
24126
        break;
24127
      }
24128
24129
    default:
24130
      {
24131
        (function () {
24132
          {
24133
            {
24134
              throw ReactError(Error("Unknown root exit status."));
24135
            }
24136
          }
24137
        })();
24138
      }
24139
  }
24140
} // This is the entry point for synchronous tasks that don't go
24141
// through Scheduler
24142
24143
24144
function performSyncWorkOnRoot(root) {
24145
  // Check if there's expired work on this root. Otherwise, render at Sync.
24146
  var lastExpiredTime = root.lastExpiredTime;
24147
  var expirationTime = lastExpiredTime !== NoWork ? lastExpiredTime : Sync;
24148
24149
  if (root.finishedExpirationTime === expirationTime) {
24150
    // There's already a pending commit at this expiration time.
24151
    // TODO: This is poorly factored. This case only exists for the
24152
    // batch.commit() API.
24153
    commitRoot(root);
24154
  } else {
24155
    (function () {
24156
      if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
24157
        {
24158
          throw ReactError(Error("Should not already be working."));
24159
        }
24160
      }
24161
    })();
24162
24163
    flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
24164
    // and prepare a fresh one. Otherwise we'll continue where we left off.
24165
24166
    if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) {
24167
      prepareFreshStack(root, expirationTime);
24168
      startWorkOnPendingInteractions(root, expirationTime);
24169
    } // If we have a work-in-progress fiber, it means there's still work to do
24170
    // in this root.
24171
24172
24173
    if (workInProgress !== null) {
24174
      var prevExecutionContext = executionContext;
24175
      executionContext |= RenderContext;
24176
      var prevDispatcher = pushDispatcher(root);
24177
      var prevInteractions = pushInteractions(root);
24178
      startWorkLoopTimer(workInProgress);
24179
24180
      do {
24181
        try {
24182
          workLoopSync();
24183
          break;
24184
        } catch (thrownValue) {
24185
          handleError(root, thrownValue);
24186
        }
24187
      } while (true);
24188
24189
      resetContextDependencies();
24190
      executionContext = prevExecutionContext;
24191
      popDispatcher(prevDispatcher);
24192
24193
      if (enableSchedulerTracing) {
24194
        popInteractions(prevInteractions);
24195
      }
24196
24197
      if (workInProgressRootExitStatus === RootFatalErrored) {
24198
        var fatalError = workInProgressRootFatalError;
24199
        stopInterruptedWorkLoopTimer();
24200
        prepareFreshStack(root, expirationTime);
24201
        markRootSuspendedAtTime(root, expirationTime);
24202
        ensureRootIsScheduled(root);
24203
        throw fatalError;
24204
      }
24205
24206
      if (workInProgress !== null) {
24207
        // This is a sync render, so we should have finished the whole tree.
24208
        (function () {
24209
          {
24210
            {
24211
              throw ReactError(Error("Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue."));
24212
            }
24213
          }
24214
        })();
24215
      } else {
24216
        // We now have a consistent tree. Because this is a sync render, we
24217
        // will commit it even if something suspended. The only exception is
24218
        // if the root is locked (using the unstable_createBatch API).
24219
        stopFinishedWorkLoopTimer();
24220
        root.finishedWork = root.current.alternate;
24221
        root.finishedExpirationTime = expirationTime;
24222
        resolveLocksOnRoot(root, expirationTime);
24223
        finishSyncRender(root, workInProgressRootExitStatus, expirationTime);
24224
      } // Before exiting, make sure there's a callback scheduled for the next
24225
      // pending level.
24226
24227
24228
      ensureRootIsScheduled(root);
24229
    }
24230
  }
24231
24232
  return null;
24233
}
24234
24235
function finishSyncRender(root, exitStatus, expirationTime) {
24236
  if (exitStatus === RootLocked) {
24237
    // This root has a lock that prevents it from committing. Exit. If we
24238
    // begin work on the root again, without any intervening updates, it
24239
    // will finish without doing additional work.
24240
    markRootSuspendedAtTime(root, expirationTime);
24241
  } else {
24242
    // Set this to null to indicate there's no in-progress render.
24243
    workInProgressRoot = null;
24244
24245
    {
24246
      if (exitStatus === RootSuspended || exitStatus === RootSuspendedWithDelay) {
24247
        flushSuspensePriorityWarningInDEV();
24248
      }
24249
    }
24250
24251
    commitRoot(root);
24252
  }
24253
}
24254
24255
function flushRoot(root, expirationTime) {
24256
  if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
24257
    (function () {
24258
      {
24259
        {
24260
          throw ReactError(Error("work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method."));
24261
        }
24262
      }
24263
    })();
24264
  }
24265
24266
  markRootExpiredAtTime(root, expirationTime);
24267
  ensureRootIsScheduled(root);
24268
  flushSyncCallbackQueue();
24269
}
24270
function flushDiscreteUpdates() {
24271
  // TODO: Should be able to flush inside batchedUpdates, but not inside `act`.
24272
  // However, `act` uses `batchedUpdates`, so there's no way to distinguish
24273
  // those two cases. Need to fix this before exposing flushDiscreteUpdates
24274
  // as a public API.
24275
  if ((executionContext & (BatchedContext | RenderContext | CommitContext)) !== NoContext) {
24276
    if (true && (executionContext & RenderContext) !== NoContext) {
24277
      warning$1(false, 'unstable_flushDiscreteUpdates: Cannot flush updates when React is ' + 'already rendering.');
24278
    } // We're already rendering, so we can't synchronously flush pending work.
24279
    // This is probably a nested event dispatch triggered by a lifecycle/effect,
24280
    // like `el.focus()`. Exit.
24281
24282
24283
    return;
24284
  }
24285
24286
  flushPendingDiscreteUpdates(); // If the discrete updates scheduled passive effects, flush them now so that
24287
  // they fire before the next serial event.
24288
24289
  flushPassiveEffects();
24290
}
24291
24292
function resolveLocksOnRoot(root, expirationTime) {
24293
  var firstBatch = root.firstBatch;
24294
24295
  if (firstBatch !== null && firstBatch._defer && firstBatch._expirationTime >= expirationTime) {
24296
    scheduleCallback(NormalPriority, function () {
24297
      firstBatch._onComplete();
24298
24299
      return null;
24300
    });
24301
    workInProgressRootExitStatus = RootLocked;
24302
  }
24303
}
24304
24305
24306
24307
24308
function flushPendingDiscreteUpdates() {
24309
  if (rootsWithPendingDiscreteUpdates !== null) {
24310
    // For each root with pending discrete updates, schedule a callback to
24311
    // immediately flush them.
24312
    var roots = rootsWithPendingDiscreteUpdates;
24313
    rootsWithPendingDiscreteUpdates = null;
24314
    roots.forEach(function (expirationTime, root) {
24315
      markRootExpiredAtTime(root, expirationTime);
24316
      ensureRootIsScheduled(root);
24317
    }); // Now flush the immediate queue.
24318
24319
    flushSyncCallbackQueue();
24320
  }
24321
}
24322
24323
function batchedUpdates$1(fn, a) {
24324
  var prevExecutionContext = executionContext;
24325
  executionContext |= BatchedContext;
24326
24327
  try {
24328
    return fn(a);
24329
  } finally {
24330
    executionContext = prevExecutionContext;
24331
24332
    if (executionContext === NoContext) {
24333
      // Flush the immediate callbacks that were scheduled during this batch
24334
      flushSyncCallbackQueue();
24335
    }
24336
  }
24337
}
24338
function batchedEventUpdates$1(fn, a) {
24339
  var prevExecutionContext = executionContext;
24340
  executionContext |= EventContext;
24341
24342
  try {
24343
    return fn(a);
24344
  } finally {
24345
    executionContext = prevExecutionContext;
24346
24347
    if (executionContext === NoContext) {
24348
      // Flush the immediate callbacks that were scheduled during this batch
24349
      flushSyncCallbackQueue();
24350
    }
24351
  }
24352
}
24353
function discreteUpdates$1(fn, a, b, c) {
24354
  var prevExecutionContext = executionContext;
24355
  executionContext |= DiscreteEventContext;
24356
24357
  try {
24358
    // Should this
24359
    return runWithPriority$2(UserBlockingPriority$2, fn.bind(null, a, b, c));
24360
  } finally {
24361
    executionContext = prevExecutionContext;
24362
24363
    if (executionContext === NoContext) {
24364
      // Flush the immediate callbacks that were scheduled during this batch
24365
      flushSyncCallbackQueue();
24366
    }
24367
  }
24368
}
24369
function unbatchedUpdates(fn, a) {
24370
  var prevExecutionContext = executionContext;
24371
  executionContext &= ~BatchedContext;
24372
  executionContext |= LegacyUnbatchedContext;
24373
24374
  try {
24375
    return fn(a);
24376
  } finally {
24377
    executionContext = prevExecutionContext;
24378
24379
    if (executionContext === NoContext) {
24380
      // Flush the immediate callbacks that were scheduled during this batch
24381
      flushSyncCallbackQueue();
24382
    }
24383
  }
24384
}
24385
function flushSync(fn, a) {
24386
  if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
24387
    (function () {
24388
      {
24389
        {
24390
          throw ReactError(Error("flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering."));
24391
        }
24392
      }
24393
    })();
24394
  }
24395
24396
  var prevExecutionContext = executionContext;
24397
  executionContext |= BatchedContext;
24398
24399
  try {
24400
    return runWithPriority$2(ImmediatePriority, fn.bind(null, a));
24401
  } finally {
24402
    executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.
24403
    // Note that this will happen even if batchedUpdates is higher up
24404
    // the stack.
24405
24406
    flushSyncCallbackQueue();
24407
  }
24408
}
24409
function flushControlled(fn) {
24410
  var prevExecutionContext = executionContext;
24411
  executionContext |= BatchedContext;
24412
24413
  try {
24414
    runWithPriority$2(ImmediatePriority, fn);
24415
  } finally {
24416
    executionContext = prevExecutionContext;
24417
24418
    if (executionContext === NoContext) {
24419
      // Flush the immediate callbacks that were scheduled during this batch
24420
      flushSyncCallbackQueue();
24421
    }
24422
  }
24423
}
24424
24425
function prepareFreshStack(root, expirationTime) {
24426
  root.finishedWork = null;
24427
  root.finishedExpirationTime = NoWork;
24428
  var timeoutHandle = root.timeoutHandle;
24429
24430
  if (timeoutHandle !== noTimeout) {
24431
    // The root previous suspended and scheduled a timeout to commit a fallback
24432
    // state. Now that we have additional work, cancel the timeout.
24433
    root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
24434
24435
    cancelTimeout(timeoutHandle);
24436
  }
24437
24438
  if (workInProgress !== null) {
24439
    var interruptedWork = workInProgress.return;
24440
24441
    while (interruptedWork !== null) {
24442
      unwindInterruptedWork(interruptedWork);
24443
      interruptedWork = interruptedWork.return;
24444
    }
24445
  }
24446
24447
  workInProgressRoot = root;
24448
  workInProgress = createWorkInProgress(root.current, null, expirationTime);
24449
  renderExpirationTime = expirationTime;
24450
  workInProgressRootExitStatus = RootIncomplete;
24451
  workInProgressRootFatalError = null;
24452
  workInProgressRootLatestProcessedExpirationTime = Sync;
24453
  workInProgressRootLatestSuspenseTimeout = Sync;
24454
  workInProgressRootCanSuspendUsingConfig = null;
24455
  workInProgressRootNextUnprocessedUpdateTime = NoWork;
24456
  workInProgressRootHasPendingPing = false;
24457
24458
  if (enableSchedulerTracing) {
24459
    spawnedWorkDuringRender = null;
24460
  }
24461
24462
  {
24463
    ReactStrictModeWarnings.discardPendingWarnings();
24464
    componentsThatTriggeredHighPriSuspend = null;
24465
  }
24466
}
24467
24468
function handleError(root, thrownValue) {
24469
  do {
24470
    try {
24471
      // Reset module-level state that was set during the render phase.
24472
      resetContextDependencies();
24473
      resetHooks();
24474
24475
      if (workInProgress === null || workInProgress.return === null) {
24476
        // Expected to be working on a non-root fiber. This is a fatal error
24477
        // because there's no ancestor that can handle it; the root is
24478
        // supposed to capture all errors that weren't caught by an error
24479
        // boundary.
24480
        workInProgressRootExitStatus = RootFatalErrored;
24481
        workInProgressRootFatalError = thrownValue;
24482
        return null;
24483
      }
24484
24485
      if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
24486
        // Record the time spent rendering before an error was thrown. This
24487
        // avoids inaccurate Profiler durations in the case of a
24488
        // suspended render.
24489
        stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
24490
      }
24491
24492
      throwException(root, workInProgress.return, workInProgress, thrownValue, renderExpirationTime);
24493
      workInProgress = completeUnitOfWork(workInProgress);
24494
    } catch (yetAnotherThrownValue) {
24495
      // Something in the return path also threw.
24496
      thrownValue = yetAnotherThrownValue;
24497
      continue;
24498
    } // Return to the normal work loop.
24499
24500
24501
    return;
24502
  } while (true);
24503
}
24504
24505
function pushDispatcher(root) {
24506
  var prevDispatcher = ReactCurrentDispatcher.current;
24507
  ReactCurrentDispatcher.current = ContextOnlyDispatcher;
24508
24509
  if (prevDispatcher === null) {
24510
    // The React isomorphic package does not include a default dispatcher.
24511
    // Instead the first renderer will lazily attach one, in order to give
24512
    // nicer error messages.
24513
    return ContextOnlyDispatcher;
24514
  } else {
24515
    return prevDispatcher;
24516
  }
24517
}
24518
24519
function popDispatcher(prevDispatcher) {
24520
  ReactCurrentDispatcher.current = prevDispatcher;
24521
}
24522
24523
function pushInteractions(root) {
24524
  if (enableSchedulerTracing) {
24525
    var prevInteractions = tracing.__interactionsRef.current;
24526
    tracing.__interactionsRef.current = root.memoizedInteractions;
24527
    return prevInteractions;
24528
  }
24529
24530
  return null;
24531
}
24532
24533
function popInteractions(prevInteractions) {
24534
  if (enableSchedulerTracing) {
24535
    tracing.__interactionsRef.current = prevInteractions;
24536
  }
24537
}
24538
24539
function markCommitTimeOfFallback() {
24540
  globalMostRecentFallbackTime = now();
24541
}
24542
function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) {
24543
  if (expirationTime < workInProgressRootLatestProcessedExpirationTime && expirationTime > Idle) {
24544
    workInProgressRootLatestProcessedExpirationTime = expirationTime;
24545
  }
24546
24547
  if (suspenseConfig !== null) {
24548
    if (expirationTime < workInProgressRootLatestSuspenseTimeout && expirationTime > Idle) {
24549
      workInProgressRootLatestSuspenseTimeout = expirationTime; // Most of the time we only have one config and getting wrong is not bad.
24550
24551
      workInProgressRootCanSuspendUsingConfig = suspenseConfig;
24552
    }
24553
  }
24554
}
24555
function markUnprocessedUpdateTime(expirationTime) {
24556
  if (expirationTime > workInProgressRootNextUnprocessedUpdateTime) {
24557
    workInProgressRootNextUnprocessedUpdateTime = expirationTime;
24558
  }
24559
}
24560
function renderDidSuspend() {
24561
  if (workInProgressRootExitStatus === RootIncomplete) {
24562
    workInProgressRootExitStatus = RootSuspended;
24563
  }
24564
}
24565
function renderDidSuspendDelayIfPossible() {
24566
  if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {
24567
    workInProgressRootExitStatus = RootSuspendedWithDelay;
24568
  } // Check if there's a lower priority update somewhere else in the tree.
24569
24570
24571
  if (workInProgressRootNextUnprocessedUpdateTime !== NoWork && workInProgressRoot !== null) {
24572
    // Mark the current render as suspended, and then mark that there's a
24573
    // pending update.
24574
    // TODO: This should immediately interrupt the current render, instead
24575
    // of waiting until the next time we yield.
24576
    markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime);
24577
    markRootUpdatedAtTime(workInProgressRoot, workInProgressRootNextUnprocessedUpdateTime);
24578
  }
24579
}
24580
function renderDidError() {
24581
  if (workInProgressRootExitStatus !== RootCompleted) {
24582
    workInProgressRootExitStatus = RootErrored;
24583
  }
24584
} // Called during render to determine if anything has suspended.
24585
// Returns false if we're not sure.
24586
24587
function renderHasNotSuspendedYet() {
24588
  // If something errored or completed, we can't really be sure,
24589
  // so those are false.
24590
  return workInProgressRootExitStatus === RootIncomplete;
24591
}
24592
24593
function inferTimeFromExpirationTime(expirationTime) {
24594
  // We don't know exactly when the update was scheduled, but we can infer an
24595
  // approximate start time from the expiration time.
24596
  var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
24597
  return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
24598
}
24599
24600
function inferTimeFromExpirationTimeWithSuspenseConfig(expirationTime, suspenseConfig) {
24601
  // We don't know exactly when the update was scheduled, but we can infer an
24602
  // approximate start time from the expiration time by subtracting the timeout
24603
  // that was added to the event time.
24604
  var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
24605
  return earliestExpirationTimeMs - (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
24606
} // The work loop is an extremely hot path. Tell Closure not to inline it.
24607
24608
/** @noinline */
24609
24610
24611
function workLoopSync() {
24612
  // Already timed out, so perform work without checking if we need to yield.
24613
  while (workInProgress !== null) {
24614
    workInProgress = performUnitOfWork(workInProgress);
24615
  }
24616
}
24617
/** @noinline */
24618
24619
24620
function workLoopConcurrent() {
24621
  // Perform work until Scheduler asks us to yield
24622
  while (workInProgress !== null && !shouldYield()) {
24623
    workInProgress = performUnitOfWork(workInProgress);
24624
  }
24625
}
24626
24627
function performUnitOfWork(unitOfWork) {
24628
  // The current, flushed, state of this fiber is the alternate. Ideally
24629
  // nothing should rely on this, but relying on it here means that we don't
24630
  // need an additional field on the work in progress.
24631
  var current$$1 = unitOfWork.alternate;
24632
  startWorkTimer(unitOfWork);
24633
  setCurrentFiber(unitOfWork);
24634
  var next;
24635
24636
  if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) {
24637
    startProfilerTimer(unitOfWork);
24638
    next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime);
24639
    stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
24640
  } else {
24641
    next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime);
24642
  }
24643
24644
  resetCurrentFiber();
24645
  unitOfWork.memoizedProps = unitOfWork.pendingProps;
24646
24647
  if (next === null) {
24648
    // If this doesn't spawn new work, complete the current work.
24649
    next = completeUnitOfWork(unitOfWork);
24650
  }
24651
24652
  ReactCurrentOwner$2.current = null;
24653
  return next;
24654
}
24655
24656
function completeUnitOfWork(unitOfWork) {
24657
  // Attempt to complete the current unit of work, then move to the next
24658
  // sibling. If there are no more siblings, return to the parent fiber.
24659
  workInProgress = unitOfWork;
24660
24661
  do {
24662
    // The current, flushed, state of this fiber is the alternate. Ideally
24663
    // nothing should rely on this, but relying on it here means that we don't
24664
    // need an additional field on the work in progress.
24665
    var current$$1 = workInProgress.alternate;
24666
    var returnFiber = workInProgress.return; // Check if the work completed or if something threw.
24667
24668
    if ((workInProgress.effectTag & Incomplete) === NoEffect) {
24669
      setCurrentFiber(workInProgress);
24670
      var next = void 0;
24671
24672
      if (!enableProfilerTimer || (workInProgress.mode & ProfileMode) === NoMode) {
24673
        next = completeWork(current$$1, workInProgress, renderExpirationTime);
24674
      } else {
24675
        startProfilerTimer(workInProgress);
24676
        next = completeWork(current$$1, workInProgress, renderExpirationTime); // Update render duration assuming we didn't error.
24677
24678
        stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
24679
      }
24680
24681
      stopWorkTimer(workInProgress);
24682
      resetCurrentFiber();
24683
      resetChildExpirationTime(workInProgress);
24684
24685
      if (next !== null) {
24686
        // Completing this fiber spawned new work. Work on that next.
24687
        return next;
24688
      }
24689
24690
      if (returnFiber !== null && // Do not append effects to parents if a sibling failed to complete
24691
      (returnFiber.effectTag & Incomplete) === NoEffect) {
24692
        // Append all the effects of the subtree and this fiber onto the effect
24693
        // list of the parent. The completion order of the children affects the
24694
        // side-effect order.
24695
        if (returnFiber.firstEffect === null) {
24696
          returnFiber.firstEffect = workInProgress.firstEffect;
24697
        }
24698
24699
        if (workInProgress.lastEffect !== null) {
24700
          if (returnFiber.lastEffect !== null) {
24701
            returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
24702
          }
24703
24704
          returnFiber.lastEffect = workInProgress.lastEffect;
24705
        } // If this fiber had side-effects, we append it AFTER the children's
24706
        // side-effects. We can perform certain side-effects earlier if needed,
24707
        // by doing multiple passes over the effect list. We don't want to
24708
        // schedule our own side-effect on our own list because if end up
24709
        // reusing children we'll schedule this effect onto itself since we're
24710
        // at the end.
24711
24712
24713
        var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect
24714
        // list. PerformedWork effect is read by React DevTools but shouldn't be
24715
        // committed.
24716
24717
        if (effectTag > PerformedWork) {
24718
          if (returnFiber.lastEffect !== null) {
24719
            returnFiber.lastEffect.nextEffect = workInProgress;
24720
          } else {
24721
            returnFiber.firstEffect = workInProgress;
24722
          }
24723
24724
          returnFiber.lastEffect = workInProgress;
24725
        }
24726
      }
24727
    } else {
24728
      // This fiber did not complete because something threw. Pop values off
24729
      // the stack without entering the complete phase. If this is a boundary,
24730
      // capture values if possible.
24731
      var _next = unwindWork(workInProgress, renderExpirationTime); // Because this fiber did not complete, don't reset its expiration time.
24732
24733
24734
      if (enableProfilerTimer && (workInProgress.mode & ProfileMode) !== NoMode) {
24735
        // Record the render duration for the fiber that errored.
24736
        stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing.
24737
24738
        var actualDuration = workInProgress.actualDuration;
24739
        var child = workInProgress.child;
24740
24741
        while (child !== null) {
24742
          actualDuration += child.actualDuration;
24743
          child = child.sibling;
24744
        }
24745
24746
        workInProgress.actualDuration = actualDuration;
24747
      }
24748
24749
      if (_next !== null) {
24750
        // If completing this work spawned new work, do that next. We'll come
24751
        // back here again.
24752
        // Since we're restarting, remove anything that is not a host effect
24753
        // from the effect tag.
24754
        // TODO: The name stopFailedWorkTimer is misleading because Suspense
24755
        // also captures and restarts.
24756
        stopFailedWorkTimer(workInProgress);
24757
        _next.effectTag &= HostEffectMask;
24758
        return _next;
24759
      }
24760
24761
      stopWorkTimer(workInProgress);
24762
24763
      if (returnFiber !== null) {
24764
        // Mark the parent fiber as incomplete and clear its effect list.
24765
        returnFiber.firstEffect = returnFiber.lastEffect = null;
24766
        returnFiber.effectTag |= Incomplete;
24767
      }
24768
    }
24769
24770
    var siblingFiber = workInProgress.sibling;
24771
24772
    if (siblingFiber !== null) {
24773
      // If there is more work to do in this returnFiber, do that next.
24774
      return siblingFiber;
24775
    } // Otherwise, return to the parent
24776
24777
24778
    workInProgress = returnFiber;
24779
  } while (workInProgress !== null); // We've reached the root.
24780
24781
24782
  if (workInProgressRootExitStatus === RootIncomplete) {
24783
    workInProgressRootExitStatus = RootCompleted;
24784
  }
24785
24786
  return null;
24787
}
24788
24789
function getRemainingExpirationTime(fiber) {
24790
  var updateExpirationTime = fiber.expirationTime;
24791
  var childExpirationTime = fiber.childExpirationTime;
24792
  return updateExpirationTime > childExpirationTime ? updateExpirationTime : childExpirationTime;
24793
}
24794
24795
function resetChildExpirationTime(completedWork) {
24796
  if (renderExpirationTime !== Never && completedWork.childExpirationTime === Never) {
24797
    // The children of this component are hidden. Don't bubble their
24798
    // expiration times.
24799
    return;
24800
  }
24801
24802
  var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time.
24803
24804
  if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) {
24805
    // In profiling mode, resetChildExpirationTime is also used to reset
24806
    // profiler durations.
24807
    var actualDuration = completedWork.actualDuration;
24808
    var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will
24809
    // only be updated if work is done on the fiber (i.e. it doesn't bailout).
24810
    // When work is done, it should bubble to the parent's actualDuration. If
24811
    // the fiber has not been cloned though, (meaning no work was done), then
24812
    // this value will reflect the amount of time spent working on a previous
24813
    // render. In that case it should not bubble. We determine whether it was
24814
    // cloned by comparing the child pointer.
24815
24816
    var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;
24817
    var child = completedWork.child;
24818
24819
    while (child !== null) {
24820
      var childUpdateExpirationTime = child.expirationTime;
24821
      var childChildExpirationTime = child.childExpirationTime;
24822
24823
      if (childUpdateExpirationTime > newChildExpirationTime) {
24824
        newChildExpirationTime = childUpdateExpirationTime;
24825
      }
24826
24827
      if (childChildExpirationTime > newChildExpirationTime) {
24828
        newChildExpirationTime = childChildExpirationTime;
24829
      }
24830
24831
      if (shouldBubbleActualDurations) {
24832
        actualDuration += child.actualDuration;
24833
      }
24834
24835
      treeBaseDuration += child.treeBaseDuration;
24836
      child = child.sibling;
24837
    }
24838
24839
    completedWork.actualDuration = actualDuration;
24840
    completedWork.treeBaseDuration = treeBaseDuration;
24841
  } else {
24842
    var _child = completedWork.child;
24843
24844
    while (_child !== null) {
24845
      var _childUpdateExpirationTime = _child.expirationTime;
24846
      var _childChildExpirationTime = _child.childExpirationTime;
24847
24848
      if (_childUpdateExpirationTime > newChildExpirationTime) {
24849
        newChildExpirationTime = _childUpdateExpirationTime;
24850
      }
24851
24852
      if (_childChildExpirationTime > newChildExpirationTime) {
24853
        newChildExpirationTime = _childChildExpirationTime;
24854
      }
24855
24856
      _child = _child.sibling;
24857
    }
24858
  }
24859
24860
  completedWork.childExpirationTime = newChildExpirationTime;
24861
}
24862
24863
function commitRoot(root) {
24864
  var renderPriorityLevel = getCurrentPriorityLevel();
24865
  runWithPriority$2(ImmediatePriority, commitRootImpl.bind(null, root, renderPriorityLevel));
24866
  return null;
24867
}
24868
24869
function commitRootImpl(root, renderPriorityLevel) {
24870
  flushPassiveEffects();
24871
  flushRenderPhaseStrictModeWarningsInDEV();
24872
24873
  (function () {
24874
    if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
24875
      {
24876
        throw ReactError(Error("Should not already be working."));
24877
      }
24878
    }
24879
  })();
24880
24881
  var finishedWork = root.finishedWork;
24882
  var expirationTime = root.finishedExpirationTime;
24883
24884
  if (finishedWork === null) {
24885
    return null;
24886
  }
24887
24888
  root.finishedWork = null;
24889
  root.finishedExpirationTime = NoWork;
24890
24891
  (function () {
24892
    if (!(finishedWork !== root.current)) {
24893
      {
24894
        throw ReactError(Error("Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue."));
24895
      }
24896
    }
24897
  })(); // commitRoot never returns a continuation; it always finishes synchronously.
24898
  // So we can clear these now to allow a new callback to be scheduled.
24899
24900
24901
  root.callbackNode = null;
24902
  root.callbackExpirationTime = NoWork;
24903
  root.callbackPriority = NoPriority;
24904
  root.nextKnownPendingLevel = NoWork;
24905
  startCommitTimer(); // Update the first and last pending times on this root. The new first
24906
  // pending time is whatever is left on the root fiber.
24907
24908
  var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime(finishedWork);
24909
  markRootFinishedAtTime(root, expirationTime, remainingExpirationTimeBeforeCommit);
24910
24911
  if (root === workInProgressRoot) {
24912
    // We can reset these now that they are finished.
24913
    workInProgressRoot = null;
24914
    workInProgress = null;
24915
    renderExpirationTime = NoWork;
24916
  } else {} // This indicates that the last root we worked on is not the same one that
24917
  // we're committing now. This most commonly happens when a suspended root
24918
  // times out.
24919
  // Get the list of effects.
24920
24921
24922
  var firstEffect;
24923
24924
  if (finishedWork.effectTag > PerformedWork) {
24925
    // A fiber's effect list consists only of its children, not itself. So if
24926
    // the root has an effect, we need to add it to the end of the list. The
24927
    // resulting list is the set that would belong to the root's parent, if it
24928
    // had one; that is, all the effects in the tree including the root.
24929
    if (finishedWork.lastEffect !== null) {
24930
      finishedWork.lastEffect.nextEffect = finishedWork;
24931
      firstEffect = finishedWork.firstEffect;
24932
    } else {
24933
      firstEffect = finishedWork;
24934
    }
24935
  } else {
24936
    // There is no effect on the root.
24937
    firstEffect = finishedWork.firstEffect;
24938
  }
24939
24940
  if (firstEffect !== null) {
24941
    var prevExecutionContext = executionContext;
24942
    executionContext |= CommitContext;
24943
    var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles
24944
24945
    ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass
24946
    // of the effect list for each phase: all mutation effects come before all
24947
    // layout effects, and so on.
24948
    // The first phase a "before mutation" phase. We use this phase to read the
24949
    // state of the host tree right before we mutate it. This is where
24950
    // getSnapshotBeforeUpdate is called.
24951
24952
    startCommitSnapshotEffectsTimer();
24953
    prepareForCommit(root.containerInfo);
24954
    nextEffect = firstEffect;
24955
24956
    do {
24957
      {
24958
        invokeGuardedCallback(null, commitBeforeMutationEffects, null);
24959
24960
        if (hasCaughtError()) {
24961
          (function () {
24962
            if (!(nextEffect !== null)) {
24963
              {
24964
                throw ReactError(Error("Should be working on an effect."));
24965
              }
24966
            }
24967
          })();
24968
24969
          var error = clearCaughtError();
24970
          captureCommitPhaseError(nextEffect, error);
24971
          nextEffect = nextEffect.nextEffect;
24972
        }
24973
      }
24974
    } while (nextEffect !== null);
24975
24976
    stopCommitSnapshotEffectsTimer();
24977
24978
    if (enableProfilerTimer) {
24979
      // Mark the current commit time to be shared by all Profilers in this
24980
      // batch. This enables them to be grouped later.
24981
      recordCommitTime();
24982
    } // The next phase is the mutation phase, where we mutate the host tree.
24983
24984
24985
    startCommitHostEffectsTimer();
24986
    nextEffect = firstEffect;
24987
24988
    do {
24989
      {
24990
        invokeGuardedCallback(null, commitMutationEffects, null, root, renderPriorityLevel);
24991
24992
        if (hasCaughtError()) {
24993
          (function () {
24994
            if (!(nextEffect !== null)) {
24995
              {
24996
                throw ReactError(Error("Should be working on an effect."));
24997
              }
24998
            }
24999
          })();
25000
25001
          var _error = clearCaughtError();
25002
25003
          captureCommitPhaseError(nextEffect, _error);
25004
          nextEffect = nextEffect.nextEffect;
25005
        }
25006
      }
25007
    } while (nextEffect !== null);
25008
25009
    stopCommitHostEffectsTimer();
25010
    resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after
25011
    // the mutation phase, so that the previous tree is still current during
25012
    // componentWillUnmount, but before the layout phase, so that the finished
25013
    // work is current during componentDidMount/Update.
25014
25015
    root.current = finishedWork; // The next phase is the layout phase, where we call effects that read
25016
    // the host tree after it's been mutated. The idiomatic use case for this is
25017
    // layout, but class component lifecycles also fire here for legacy reasons.
25018
25019
    startCommitLifeCyclesTimer();
25020
    nextEffect = firstEffect;
25021
25022
    do {
25023
      {
25024
        invokeGuardedCallback(null, commitLayoutEffects, null, root, expirationTime);
25025
25026
        if (hasCaughtError()) {
25027
          (function () {
25028
            if (!(nextEffect !== null)) {
25029
              {
25030
                throw ReactError(Error("Should be working on an effect."));
25031
              }
25032
            }
25033
          })();
25034
25035
          var _error2 = clearCaughtError();
25036
25037
          captureCommitPhaseError(nextEffect, _error2);
25038
          nextEffect = nextEffect.nextEffect;
25039
        }
25040
      }
25041
    } while (nextEffect !== null);
25042
25043
    stopCommitLifeCyclesTimer();
25044
    nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an
25045
    // opportunity to paint.
25046
25047
    requestPaint();
25048
25049
    if (enableSchedulerTracing) {
25050
      popInteractions(prevInteractions);
25051
    }
25052
25053
    executionContext = prevExecutionContext;
25054
  } else {
25055
    // No effects.
25056
    root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were
25057
    // no effects.
25058
    // TODO: Maybe there's a better way to report this.
25059
25060
    startCommitSnapshotEffectsTimer();
25061
    stopCommitSnapshotEffectsTimer();
25062
25063
    if (enableProfilerTimer) {
25064
      recordCommitTime();
25065
    }
25066
25067
    startCommitHostEffectsTimer();
25068
    stopCommitHostEffectsTimer();
25069
    startCommitLifeCyclesTimer();
25070
    stopCommitLifeCyclesTimer();
25071
  }
25072
25073
  stopCommitTimer();
25074
  var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
25075
25076
  if (rootDoesHavePassiveEffects) {
25077
    // This commit has passive effects. Stash a reference to them. But don't
25078
    // schedule a callback until after flushing layout work.
25079
    rootDoesHavePassiveEffects = false;
25080
    rootWithPendingPassiveEffects = root;
25081
    pendingPassiveEffectsExpirationTime = expirationTime;
25082
    pendingPassiveEffectsRenderPriority = renderPriorityLevel;
25083
  } else {
25084
    // We are done with the effect chain at this point so let's clear the
25085
    // nextEffect pointers to assist with GC. If we have passive effects, we'll
25086
    // clear this in flushPassiveEffects.
25087
    nextEffect = firstEffect;
25088
25089
    while (nextEffect !== null) {
25090
      var nextNextEffect = nextEffect.nextEffect;
25091
      nextEffect.nextEffect = null;
25092
      nextEffect = nextNextEffect;
25093
    }
25094
  } // Check if there's remaining work on this root
25095
25096
25097
  var remainingExpirationTime = root.firstPendingTime;
25098
25099
  if (remainingExpirationTime !== NoWork) {
25100
    if (enableSchedulerTracing) {
25101
      if (spawnedWorkDuringRender !== null) {
25102
        var expirationTimes = spawnedWorkDuringRender;
25103
        spawnedWorkDuringRender = null;
25104
25105
        for (var i = 0; i < expirationTimes.length; i++) {
25106
          scheduleInteractions(root, expirationTimes[i], root.memoizedInteractions);
25107
        }
25108
      }
25109
25110
      schedulePendingInteractions(root, remainingExpirationTime);
25111
    }
25112
  } else {
25113
    // If there's no remaining work, we can clear the set of already failed
25114
    // error boundaries.
25115
    legacyErrorBoundariesThatAlreadyFailed = null;
25116
  }
25117
25118
  if (enableSchedulerTracing) {
25119
    if (!rootDidHavePassiveEffects) {
25120
      // If there are no passive effects, then we can complete the pending interactions.
25121
      // Otherwise, we'll wait until after the passive effects are flushed.
25122
      // Wait to do this until after remaining work has been scheduled,
25123
      // so that we don't prematurely signal complete for interactions when there's e.g. hidden work.
25124
      finishPendingInteractions(root, expirationTime);
25125
    }
25126
  }
25127
25128
  if (remainingExpirationTime === Sync) {
25129
    // Count the number of times the root synchronously re-renders without
25130
    // finishing. If there are too many, it indicates an infinite update loop.
25131
    if (root === rootWithNestedUpdates) {
25132
      nestedUpdateCount++;
25133
    } else {
25134
      nestedUpdateCount = 0;
25135
      rootWithNestedUpdates = root;
25136
    }
25137
  } else {
25138
    nestedUpdateCount = 0;
25139
  }
25140
25141
  onCommitRoot(finishedWork.stateNode, expirationTime); // Always call this before exiting `commitRoot`, to ensure that any
25142
  // additional work on this root is scheduled.
25143
25144
  ensureRootIsScheduled(root);
25145
25146
  if (hasUncaughtError) {
25147
    hasUncaughtError = false;
25148
    var _error3 = firstUncaughtError;
25149
    firstUncaughtError = null;
25150
    throw _error3;
25151
  }
25152
25153
  if ((executionContext & LegacyUnbatchedContext) !== NoContext) {
25154
    // This is a legacy edge case. We just committed the initial mount of
25155
    // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
25156
    // synchronously, but layout updates should be deferred until the end
25157
    // of the batch.
25158
    return null;
25159
  } // If layout work was scheduled, flush it now.
25160
25161
25162
  flushSyncCallbackQueue();
25163
  return null;
25164
}
25165
25166
function commitBeforeMutationEffects() {
25167
  while (nextEffect !== null) {
25168
    var effectTag = nextEffect.effectTag;
25169
25170
    if ((effectTag & Snapshot) !== NoEffect) {
25171
      setCurrentFiber(nextEffect);
25172
      recordEffect();
25173
      var current$$1 = nextEffect.alternate;
25174
      commitBeforeMutationLifeCycles(current$$1, nextEffect);
25175
      resetCurrentFiber();
25176
    }
25177
25178
    if ((effectTag & Passive) !== NoEffect) {
25179
      // If there are passive effects, schedule a callback to flush at
25180
      // the earliest opportunity.
25181
      if (!rootDoesHavePassiveEffects) {
25182
        rootDoesHavePassiveEffects = true;
25183
        scheduleCallback(NormalPriority, function () {
25184
          flushPassiveEffects();
25185
          return null;
25186
        });
25187
      }
25188
    }
25189
25190
    nextEffect = nextEffect.nextEffect;
25191
  }
25192
}
25193
25194
function commitMutationEffects(root, renderPriorityLevel) {
25195
  // TODO: Should probably move the bulk of this function to commitWork.
25196
  while (nextEffect !== null) {
25197
    setCurrentFiber(nextEffect);
25198
    var effectTag = nextEffect.effectTag;
25199
25200
    if (effectTag & ContentReset) {
25201
      commitResetTextContent(nextEffect);
25202
    }
25203
25204
    if (effectTag & Ref) {
25205
      var current$$1 = nextEffect.alternate;
25206
25207
      if (current$$1 !== null) {
25208
        commitDetachRef(current$$1);
25209
      }
25210
    } // The following switch statement is only concerned about placement,
25211
    // updates, and deletions. To avoid needing to add a case for every possible
25212
    // bitmap value, we remove the secondary effects from the effect tag and
25213
    // switch on that value.
25214
25215
25216
    var primaryEffectTag = effectTag & (Placement | Update | Deletion | Hydrating);
25217
25218
    switch (primaryEffectTag) {
25219
      case Placement:
25220
        {
25221
          commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
25222
          // inserted, before any life-cycles like componentDidMount gets called.
25223
          // TODO: findDOMNode doesn't rely on this any more but isMounted does
25224
          // and isMounted is deprecated anyway so we should be able to kill this.
25225
25226
          nextEffect.effectTag &= ~Placement;
25227
          break;
25228
        }
25229
25230
      case PlacementAndUpdate:
25231
        {
25232
          // Placement
25233
          commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
25234
          // inserted, before any life-cycles like componentDidMount gets called.
25235
25236
          nextEffect.effectTag &= ~Placement; // Update
25237
25238
          var _current = nextEffect.alternate;
25239
          commitWork(_current, nextEffect);
25240
          break;
25241
        }
25242
25243
      case Hydrating:
25244
        {
25245
          nextEffect.effectTag &= ~Hydrating;
25246
          break;
25247
        }
25248
25249
      case HydratingAndUpdate:
25250
        {
25251
          nextEffect.effectTag &= ~Hydrating; // Update
25252
25253
          var _current2 = nextEffect.alternate;
25254
          commitWork(_current2, nextEffect);
25255
          break;
25256
        }
25257
25258
      case Update:
25259
        {
25260
          var _current3 = nextEffect.alternate;
25261
          commitWork(_current3, nextEffect);
25262
          break;
25263
        }
25264
25265
      case Deletion:
25266
        {
25267
          commitDeletion(root, nextEffect, renderPriorityLevel);
25268
          break;
25269
        }
25270
    } // TODO: Only record a mutation effect if primaryEffectTag is non-zero.
25271
25272
25273
    recordEffect();
25274
    resetCurrentFiber();
25275
    nextEffect = nextEffect.nextEffect;
25276
  }
25277
}
25278
25279
function commitLayoutEffects(root, committedExpirationTime) {
25280
  // TODO: Should probably move the bulk of this function to commitWork.
25281
  while (nextEffect !== null) {
25282
    setCurrentFiber(nextEffect);
25283
    var effectTag = nextEffect.effectTag;
25284
25285
    if (effectTag & (Update | Callback)) {
25286
      recordEffect();
25287
      var current$$1 = nextEffect.alternate;
25288
      commitLifeCycles(root, current$$1, nextEffect, committedExpirationTime);
25289
    }
25290
25291
    if (effectTag & Ref) {
25292
      recordEffect();
25293
      commitAttachRef(nextEffect);
25294
    }
25295
25296
    resetCurrentFiber();
25297
    nextEffect = nextEffect.nextEffect;
25298
  }
25299
}
25300
25301
function flushPassiveEffects() {
25302
  if (pendingPassiveEffectsRenderPriority !== NoPriority) {
25303
    var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority ? NormalPriority : pendingPassiveEffectsRenderPriority;
25304
    pendingPassiveEffectsRenderPriority = NoPriority;
25305
    return runWithPriority$2(priorityLevel, flushPassiveEffectsImpl);
25306
  }
25307
}
25308
25309
function flushPassiveEffectsImpl() {
25310
  if (rootWithPendingPassiveEffects === null) {
25311
    return false;
25312
  }
25313
25314
  var root = rootWithPendingPassiveEffects;
25315
  var expirationTime = pendingPassiveEffectsExpirationTime;
25316
  rootWithPendingPassiveEffects = null;
25317
  pendingPassiveEffectsExpirationTime = NoWork;
25318
25319
  (function () {
25320
    if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
25321
      {
25322
        throw ReactError(Error("Cannot flush passive effects while already rendering."));
25323
      }
25324
    }
25325
  })();
25326
25327
  var prevExecutionContext = executionContext;
25328
  executionContext |= CommitContext;
25329
  var prevInteractions = pushInteractions(root); // Note: This currently assumes there are no passive effects on the root
25330
  // fiber, because the root is not part of its own effect list. This could
25331
  // change in the future.
25332
25333
  var effect = root.current.firstEffect;
25334
25335
  while (effect !== null) {
25336
    {
25337
      setCurrentFiber(effect);
25338
      invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
25339
25340
      if (hasCaughtError()) {
25341
        (function () {
25342
          if (!(effect !== null)) {
25343
            {
25344
              throw ReactError(Error("Should be working on an effect."));
25345
            }
25346
          }
25347
        })();
25348
25349
        var error = clearCaughtError();
25350
        captureCommitPhaseError(effect, error);
25351
      }
25352
25353
      resetCurrentFiber();
25354
    }
25355
25356
    var nextNextEffect = effect.nextEffect; // Remove nextEffect pointer to assist GC
25357
25358
    effect.nextEffect = null;
25359
    effect = nextNextEffect;
25360
  }
25361
25362
  if (enableSchedulerTracing) {
25363
    popInteractions(prevInteractions);
25364
    finishPendingInteractions(root, expirationTime);
25365
  }
25366
25367
  executionContext = prevExecutionContext;
25368
  flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this
25369
  // exceeds the limit, we'll fire a warning.
25370
25371
  nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;
25372
  return true;
25373
}
25374
25375
function isAlreadyFailedLegacyErrorBoundary(instance) {
25376
  return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
25377
}
25378
function markLegacyErrorBoundaryAsFailed(instance) {
25379
  if (legacyErrorBoundariesThatAlreadyFailed === null) {
25380
    legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
25381
  } else {
25382
    legacyErrorBoundariesThatAlreadyFailed.add(instance);
25383
  }
25384
}
25385
25386
function prepareToThrowUncaughtError(error) {
25387
  if (!hasUncaughtError) {
25388
    hasUncaughtError = true;
25389
    firstUncaughtError = error;
25390
  }
25391
}
25392
25393
var onUncaughtError = prepareToThrowUncaughtError;
25394
25395
function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
25396
  var errorInfo = createCapturedValue(error, sourceFiber);
25397
  var update = createRootErrorUpdate(rootFiber, errorInfo, Sync);
25398
  enqueueUpdate(rootFiber, update);
25399
  var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync);
25400
25401
  if (root !== null) {
25402
    ensureRootIsScheduled(root);
25403
    schedulePendingInteractions(root, Sync);
25404
  }
25405
}
25406
25407
function captureCommitPhaseError(sourceFiber, error) {
25408
  if (sourceFiber.tag === HostRoot) {
25409
    // Error was thrown at the root. There is no parent, so the root
25410
    // itself should capture it.
25411
    captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
25412
    return;
25413
  }
25414
25415
  var fiber = sourceFiber.return;
25416
25417
  while (fiber !== null) {
25418
    if (fiber.tag === HostRoot) {
25419
      captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
25420
      return;
25421
    } else if (fiber.tag === ClassComponent) {
25422
      var ctor = fiber.type;
25423
      var instance = fiber.stateNode;
25424
25425
      if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
25426
        var errorInfo = createCapturedValue(error, sourceFiber);
25427
        var update = createClassErrorUpdate(fiber, errorInfo, // TODO: This is always sync
25428
        Sync);
25429
        enqueueUpdate(fiber, update);
25430
        var root = markUpdateTimeFromFiberToRoot(fiber, Sync);
25431
25432
        if (root !== null) {
25433
          ensureRootIsScheduled(root);
25434
          schedulePendingInteractions(root, Sync);
25435
        }
25436
25437
        return;
25438
      }
25439
    }
25440
25441
    fiber = fiber.return;
25442
  }
25443
}
25444
function pingSuspendedRoot(root, thenable, suspendedTime) {
25445
  var pingCache = root.pingCache;
25446
25447
  if (pingCache !== null) {
25448
    // The thenable resolved, so we no longer need to memoize, because it will
25449
    // never be thrown again.
25450
    pingCache.delete(thenable);
25451
  }
25452
25453
  if (workInProgressRoot === root && renderExpirationTime === suspendedTime) {
25454
    // Received a ping at the same priority level at which we're currently
25455
    // rendering. We might want to restart this render. This should mirror
25456
    // the logic of whether or not a root suspends once it completes.
25457
    // TODO: If we're rendering sync either due to Sync, Batched or expired,
25458
    // we should probably never restart.
25459
    // If we're suspended with delay, we'll always suspend so we can always
25460
    // restart. If we're suspended without any updates, it might be a retry.
25461
    // If it's early in the retry we can restart. We can't know for sure
25462
    // whether we'll eventually process an update during this render pass,
25463
    // but it's somewhat unlikely that we get to a ping before that, since
25464
    // getting to the root most update is usually very fast.
25465
    if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && workInProgressRootLatestProcessedExpirationTime === Sync && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
25466
      // Restart from the root. Don't need to schedule a ping because
25467
      // we're already working on this tree.
25468
      prepareFreshStack(root, renderExpirationTime);
25469
    } else {
25470
      // Even though we can't restart right now, we might get an
25471
      // opportunity later. So we mark this render as having a ping.
25472
      workInProgressRootHasPendingPing = true;
25473
    }
25474
25475
    return;
25476
  }
25477
25478
  if (!isRootSuspendedAtTime(root, suspendedTime)) {
25479
    // The root is no longer suspended at this time.
25480
    return;
25481
  }
25482
25483
  var lastPingedTime = root.lastPingedTime;
25484
25485
  if (lastPingedTime !== NoWork && lastPingedTime < suspendedTime) {
25486
    // There's already a lower priority ping scheduled.
25487
    return;
25488
  } // Mark the time at which this ping was scheduled.
25489
25490
25491
  root.lastPingedTime = suspendedTime;
25492
25493
  if (root.finishedExpirationTime === suspendedTime) {
25494
    // If there's a pending fallback waiting to commit, throw it away.
25495
    root.finishedExpirationTime = NoWork;
25496
    root.finishedWork = null;
25497
  }
25498
25499
  ensureRootIsScheduled(root);
25500
  schedulePendingInteractions(root, suspendedTime);
25501
}
25502
25503
function retryTimedOutBoundary(boundaryFiber, retryTime) {
25504
  // The boundary fiber (a Suspense component or SuspenseList component)
25505
  // previously was rendered in its fallback state. One of the promises that
25506
  // suspended it has resolved, which means at least part of the tree was
25507
  // likely unblocked. Try rendering again, at a new expiration time.
25508
  if (retryTime === Never) {
25509
    var suspenseConfig = null; // Retries don't carry over the already committed update.
25510
25511
    var currentTime = requestCurrentTime();
25512
    retryTime = computeExpirationForFiber(currentTime, boundaryFiber, suspenseConfig);
25513
  } // TODO: Special case idle priority?
25514
25515
25516
  var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime);
25517
25518
  if (root !== null) {
25519
    ensureRootIsScheduled(root);
25520
    schedulePendingInteractions(root, retryTime);
25521
  }
25522
}
25523
25524
function retryDehydratedSuspenseBoundary(boundaryFiber) {
25525
  var suspenseState = boundaryFiber.memoizedState;
25526
  var retryTime = Never;
25527
25528
  if (suspenseState !== null) {
25529
    retryTime = suspenseState.retryTime;
25530
  }
25531
25532
  retryTimedOutBoundary(boundaryFiber, retryTime);
25533
}
25534
function resolveRetryThenable(boundaryFiber, thenable) {
25535
  var retryTime = Never; // Default
25536
25537
  var retryCache;
25538
25539
  if (enableSuspenseServerRenderer) {
25540
    switch (boundaryFiber.tag) {
25541
      case SuspenseComponent:
25542
        retryCache = boundaryFiber.stateNode;
25543
        var suspenseState = boundaryFiber.memoizedState;
25544
25545
        if (suspenseState !== null) {
25546
          retryTime = suspenseState.retryTime;
25547
        }
25548
25549
        break;
25550
25551
      case SuspenseListComponent:
25552
        retryCache = boundaryFiber.stateNode;
25553
        break;
25554
25555
      default:
25556
        (function () {
25557
          {
25558
            {
25559
              throw ReactError(Error("Pinged unknown suspense boundary type. This is probably a bug in React."));
25560
            }
25561
          }
25562
        })();
25563
25564
    }
25565
  } else {
25566
    retryCache = boundaryFiber.stateNode;
25567
  }
25568
25569
  if (retryCache !== null) {
25570
    // The thenable resolved, so we no longer need to memoize, because it will
25571
    // never be thrown again.
25572
    retryCache.delete(thenable);
25573
  }
25574
25575
  retryTimedOutBoundary(boundaryFiber, retryTime);
25576
} // Computes the next Just Noticeable Difference (JND) boundary.
25577
// The theory is that a person can't tell the difference between small differences in time.
25578
// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
25579
// difference in the experience. However, waiting for longer might mean that we can avoid
25580
// showing an intermediate loading state. The longer we have already waited, the harder it
25581
// is to tell small differences in time. Therefore, the longer we've already waited,
25582
// the longer we can wait additionally. At some point we have to give up though.
25583
// We pick a train model where the next boundary commits at a consistent schedule.
25584
// These particular numbers are vague estimates. We expect to adjust them based on research.
25585
25586
function jnd(timeElapsed) {
25587
  return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
25588
}
25589
25590
function computeMsUntilSuspenseLoadingDelay(mostRecentEventTime, committedExpirationTime, suspenseConfig) {
25591
  var busyMinDurationMs = suspenseConfig.busyMinDurationMs | 0;
25592
25593
  if (busyMinDurationMs <= 0) {
25594
    return 0;
25595
  }
25596
25597
  var busyDelayMs = suspenseConfig.busyDelayMs | 0; // Compute the time until this render pass would expire.
25598
25599
  var currentTimeMs = now();
25600
  var eventTimeMs = inferTimeFromExpirationTimeWithSuspenseConfig(mostRecentEventTime, suspenseConfig);
25601
  var timeElapsed = currentTimeMs - eventTimeMs;
25602
25603
  if (timeElapsed <= busyDelayMs) {
25604
    // If we haven't yet waited longer than the initial delay, we don't
25605
    // have to wait any additional time.
25606
    return 0;
25607
  }
25608
25609
  var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; // This is the value that is passed to `setTimeout`.
25610
25611
  return msUntilTimeout;
25612
}
25613
25614
function checkForNestedUpdates() {
25615
  if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
25616
    nestedUpdateCount = 0;
25617
    rootWithNestedUpdates = null;
25618
25619
    (function () {
25620
      {
25621
        {
25622
          throw ReactError(Error("Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops."));
25623
        }
25624
      }
25625
    })();
25626
  }
25627
25628
  {
25629
    if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
25630
      nestedPassiveUpdateCount = 0;
25631
      warning$1(false, 'Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.');
25632
    }
25633
  }
25634
}
25635
25636
function flushRenderPhaseStrictModeWarningsInDEV() {
25637
  {
25638
    ReactStrictModeWarnings.flushLegacyContextWarning();
25639
25640
    if (warnAboutDeprecatedLifecycles) {
25641
      ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
25642
    }
25643
  }
25644
}
25645
25646
function stopFinishedWorkLoopTimer() {
25647
  var didCompleteRoot = true;
25648
  stopWorkLoopTimer(interruptedBy, didCompleteRoot);
25649
  interruptedBy = null;
25650
}
25651
25652
function stopInterruptedWorkLoopTimer() {
25653
  // TODO: Track which fiber caused the interruption.
25654
  var didCompleteRoot = false;
25655
  stopWorkLoopTimer(interruptedBy, didCompleteRoot);
25656
  interruptedBy = null;
25657
}
25658
25659
function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) {
25660
  if (enableUserTimingAPI && workInProgressRoot !== null && updateExpirationTime > renderExpirationTime) {
25661
    interruptedBy = fiberThatReceivedUpdate;
25662
  }
25663
}
25664
25665
var didWarnStateUpdateForUnmountedComponent = null;
25666
25667
function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
25668
  {
25669
    var tag = fiber.tag;
25670
25671
    if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
25672
      // Only warn for user-defined components, not internal ones like Suspense.
25673
      return;
25674
    } // We show the whole stack but dedupe on the top component's name because
25675
    // the problematic code almost always lies inside that component.
25676
25677
25678
    var componentName = getComponentName(fiber.type) || 'ReactComponent';
25679
25680
    if (didWarnStateUpdateForUnmountedComponent !== null) {
25681
      if (didWarnStateUpdateForUnmountedComponent.has(componentName)) {
25682
        return;
25683
      }
25684
25685
      didWarnStateUpdateForUnmountedComponent.add(componentName);
25686
    } else {
25687
      didWarnStateUpdateForUnmountedComponent = new Set([componentName]);
25688
    }
25689
25690
    warningWithoutStack$1(false, "Can't perform a React state update on an unmounted component. This " + 'is a no-op, but it indicates a memory leak in your application. To ' + 'fix, cancel all subscriptions and asynchronous tasks in %s.%s', tag === ClassComponent ? 'the componentWillUnmount method' : 'a useEffect cleanup function', getStackByFiberInDevAndProd(fiber));
25691
  }
25692
}
25693
25694
var beginWork$$1;
25695
25696
if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
25697
  var dummyFiber = null;
25698
25699
  beginWork$$1 = function (current$$1, unitOfWork, expirationTime) {
25700
    // If a component throws an error, we replay it again in a synchronously
25701
    // dispatched event, so that the debugger will treat it as an uncaught
25702
    // error See ReactErrorUtils for more information.
25703
    // Before entering the begin phase, copy the work-in-progress onto a dummy
25704
    // fiber. If beginWork throws, we'll use this to reset the state.
25705
    var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
25706
25707
    try {
25708
      return beginWork$1(current$$1, unitOfWork, expirationTime);
25709
    } catch (originalError) {
25710
      if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
25711
        // Don't replay promises. Treat everything else like an error.
25712
        throw originalError;
25713
      } // Keep this code in sync with renderRoot; any changes here must have
25714
      // corresponding changes there.
25715
25716
25717
      resetContextDependencies();
25718
      resetHooks(); // Unwind the failed stack frame
25719
25720
      unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber.
25721
25722
      assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
25723
25724
      if (enableProfilerTimer && unitOfWork.mode & ProfileMode) {
25725
        // Reset the profiler timer.
25726
        startProfilerTimer(unitOfWork);
25727
      } // Run beginWork again.
25728
25729
25730
      invokeGuardedCallback(null, beginWork$1, null, current$$1, unitOfWork, expirationTime);
25731
25732
      if (hasCaughtError()) {
25733
        var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
25734
        // Rethrow this error instead of the original one.
25735
25736
        throw replayError;
25737
      } else {
25738
        // This branch is reachable if the render phase is impure.
25739
        throw originalError;
25740
      }
25741
    }
25742
  };
25743
} else {
25744
  beginWork$$1 = beginWork$1;
25745
}
25746
25747
var didWarnAboutUpdateInRender = false;
25748
var didWarnAboutUpdateInGetChildContext = false;
25749
25750
function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) {
25751
  {
25752
    if (fiber.tag === ClassComponent) {
25753
      switch (phase) {
25754
        case 'getChildContext':
25755
          if (didWarnAboutUpdateInGetChildContext) {
25756
            return;
25757
          }
25758
25759
          warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
25760
          didWarnAboutUpdateInGetChildContext = true;
25761
          break;
25762
25763
        case 'render':
25764
          if (didWarnAboutUpdateInRender) {
25765
            return;
25766
          }
25767
25768
          warningWithoutStack$1(false, 'Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure function of ' + 'props and state.');
25769
          didWarnAboutUpdateInRender = true;
25770
          break;
25771
      }
25772
    }
25773
  }
25774
} // a 'shared' variable that changes when act() opens/closes in tests.
25775
25776
25777
var IsThisRendererActing = {
25778
  current: false
25779
};
25780
function warnIfNotScopedWithMatchingAct(fiber) {
25781
  {
25782
    if (warnsIfNotActing === true && IsSomeRendererActing.current === true && IsThisRendererActing.current !== true) {
25783
      warningWithoutStack$1(false, "It looks like you're using the wrong act() around your test interactions.\n" + 'Be sure to use the matching version of act() corresponding to your renderer:\n\n' + '// for react-dom:\n' + "import {act} from 'react-dom/test-utils';\n" + '// ...\n' + 'act(() => ...);\n\n' + '// for react-test-renderer:\n' + "import TestRenderer from 'react-test-renderer';\n" + 'const {act} = TestRenderer;\n' + '// ...\n' + 'act(() => ...);' + '%s', getStackByFiberInDevAndProd(fiber));
25784
    }
25785
  }
25786
}
25787
function warnIfNotCurrentlyActingEffectsInDEV(fiber) {
25788
  {
25789
    if (warnsIfNotActing === true && (fiber.mode & StrictMode) !== NoMode && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
25790
      warningWithoutStack$1(false, 'An update to %s ran an effect, but was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + '  /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));
25791
    }
25792
  }
25793
}
25794
25795
function warnIfNotCurrentlyActingUpdatesInDEV(fiber) {
25796
  {
25797
    if (warnsIfNotActing === true && executionContext === NoContext && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
25798
      warningWithoutStack$1(false, 'An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + '  /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));
25799
    }
25800
  }
25801
}
25802
25803
var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler.
25804
25805
var didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked
25806
// scheduler is the actual recommendation. The alternative could be a testing build,
25807
// a new lib, or whatever; we dunno just yet. This message is for early adopters
25808
// to get their tests right.
25809
25810
function warnIfUnmockedScheduler(fiber) {
25811
  {
25812
    if (didWarnAboutUnmockedScheduler === false && Scheduler.unstable_flushAllWithoutAsserting === undefined) {
25813
      if (fiber.mode & BatchedMode || fiber.mode & ConcurrentMode) {
25814
        didWarnAboutUnmockedScheduler = true;
25815
        warningWithoutStack$1(false, 'In Concurrent or Sync modes, the "scheduler" module needs to be mocked ' + 'to guarantee consistent behaviour across tests and browsers. ' + 'For example, with jest: \n' + "jest.mock('scheduler', () => require('scheduler/unstable_mock'));\n\n" + 'For more info, visit https://fb.me/react-mock-scheduler');
25816
      } else if (warnAboutUnmockedScheduler === true) {
25817
        didWarnAboutUnmockedScheduler = true;
25818
        warningWithoutStack$1(false, 'Starting from React v17, the "scheduler" module will need to be mocked ' + 'to guarantee consistent behaviour across tests and browsers. ' + 'For example, with jest: \n' + "jest.mock('scheduler', () => require('scheduler/unstable_mock'));\n\n" + 'For more info, visit https://fb.me/react-mock-scheduler');
25819
      }
25820
    }
25821
  }
25822
}
25823
var componentsThatTriggeredHighPriSuspend = null;
25824
function checkForWrongSuspensePriorityInDEV(sourceFiber) {
25825
  {
25826
    var currentPriorityLevel = getCurrentPriorityLevel();
25827
25828
    if ((sourceFiber.mode & ConcurrentMode) !== NoEffect && (currentPriorityLevel === UserBlockingPriority$2 || currentPriorityLevel === ImmediatePriority)) {
25829
      var workInProgressNode = sourceFiber;
25830
25831
      while (workInProgressNode !== null) {
25832
        // Add the component that triggered the suspense
25833
        var current$$1 = workInProgressNode.alternate;
25834
25835
        if (current$$1 !== null) {
25836
          // TODO: warn component that triggers the high priority
25837
          // suspend is the HostRoot
25838
          switch (workInProgressNode.tag) {
25839
            case ClassComponent:
25840
              // Loop through the component's update queue and see whether the component
25841
              // has triggered any high priority updates
25842
              var updateQueue = current$$1.updateQueue;
25843
25844
              if (updateQueue !== null) {
25845
                var update = updateQueue.firstUpdate;
25846
25847
                while (update !== null) {
25848
                  var priorityLevel = update.priority;
25849
25850
                  if (priorityLevel === UserBlockingPriority$2 || priorityLevel === ImmediatePriority) {
25851
                    if (componentsThatTriggeredHighPriSuspend === null) {
25852
                      componentsThatTriggeredHighPriSuspend = new Set([getComponentName(workInProgressNode.type)]);
25853
                    } else {
25854
                      componentsThatTriggeredHighPriSuspend.add(getComponentName(workInProgressNode.type));
25855
                    }
25856
25857
                    break;
25858
                  }
25859
25860
                  update = update.next;
25861
                }
25862
              }
25863
25864
              break;
25865
25866
            case FunctionComponent:
25867
            case ForwardRef:
25868
            case SimpleMemoComponent:
25869
              if (workInProgressNode.memoizedState !== null && workInProgressNode.memoizedState.baseUpdate !== null) {
25870
                var _update = workInProgressNode.memoizedState.baseUpdate; // Loop through the functional component's memoized state to see whether
25871
                // the component has triggered any high pri updates
25872
25873
                while (_update !== null) {
25874
                  var priority = _update.priority;
25875
25876
                  if (priority === UserBlockingPriority$2 || priority === ImmediatePriority) {
25877
                    if (componentsThatTriggeredHighPriSuspend === null) {
25878
                      componentsThatTriggeredHighPriSuspend = new Set([getComponentName(workInProgressNode.type)]);
25879
                    } else {
25880
                      componentsThatTriggeredHighPriSuspend.add(getComponentName(workInProgressNode.type));
25881
                    }
25882
25883
                    break;
25884
                  }
25885
25886
                  if (_update.next === workInProgressNode.memoizedState.baseUpdate) {
25887
                    break;
25888
                  }
25889
25890
                  _update = _update.next;
25891
                }
25892
              }
25893
25894
              break;
25895
25896
            default:
25897
              break;
25898
          }
25899
        }
25900
25901
        workInProgressNode = workInProgressNode.return;
25902
      }
25903
    }
25904
  }
25905
}
25906
25907
function flushSuspensePriorityWarningInDEV() {
25908
  {
25909
    if (componentsThatTriggeredHighPriSuspend !== null) {
25910
      var componentNames = [];
25911
      componentsThatTriggeredHighPriSuspend.forEach(function (name) {
25912
        return componentNames.push(name);
25913
      });
25914
      componentsThatTriggeredHighPriSuspend = null;
25915
25916
      if (componentNames.length > 0) {
25917
        warningWithoutStack$1(false, '%s triggered a user-blocking update that suspended.' + '\n\n' + 'The fix is to split the update into multiple parts: a user-blocking ' + 'update to provide immediate feedback, and another update that ' + 'triggers the bulk of the changes.' + '\n\n' + 'Refer to the documentation for useSuspenseTransition to learn how ' + 'to implement this pattern.', // TODO: Add link to React docs with more information, once it exists
25918
        componentNames.sort().join(', '));
25919
      }
25920
    }
25921
  }
25922
}
25923
25924
function computeThreadID(root, expirationTime) {
25925
  // Interaction threads are unique per root and expiration time.
25926
  return expirationTime * 1000 + root.interactionThreadID;
25927
}
25928
25929
function markSpawnedWork(expirationTime) {
25930
  if (!enableSchedulerTracing) {
25931
    return;
25932
  }
25933
25934
  if (spawnedWorkDuringRender === null) {
25935
    spawnedWorkDuringRender = [expirationTime];
25936
  } else {
25937
    spawnedWorkDuringRender.push(expirationTime);
25938
  }
25939
}
25940
25941
function scheduleInteractions(root, expirationTime, interactions) {
25942
  if (!enableSchedulerTracing) {
25943
    return;
25944
  }
25945
25946
  if (interactions.size > 0) {
25947
    var pendingInteractionMap = root.pendingInteractionMap;
25948
    var pendingInteractions = pendingInteractionMap.get(expirationTime);
25949
25950
    if (pendingInteractions != null) {
25951
      interactions.forEach(function (interaction) {
25952
        if (!pendingInteractions.has(interaction)) {
25953
          // Update the pending async work count for previously unscheduled interaction.
25954
          interaction.__count++;
25955
        }
25956
25957
        pendingInteractions.add(interaction);
25958
      });
25959
    } else {
25960
      pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions.
25961
25962
      interactions.forEach(function (interaction) {
25963
        interaction.__count++;
25964
      });
25965
    }
25966
25967
    var subscriber = tracing.__subscriberRef.current;
25968
25969
    if (subscriber !== null) {
25970
      var threadID = computeThreadID(root, expirationTime);
25971
      subscriber.onWorkScheduled(interactions, threadID);
25972
    }
25973
  }
25974
}
25975
25976
function schedulePendingInteractions(root, expirationTime) {
25977
  // This is called when work is scheduled on a root.
25978
  // It associates the current interactions with the newly-scheduled expiration.
25979
  // They will be restored when that expiration is later committed.
25980
  if (!enableSchedulerTracing) {
25981
    return;
25982
  }
25983
25984
  scheduleInteractions(root, expirationTime, tracing.__interactionsRef.current);
25985
}
25986
25987
function startWorkOnPendingInteractions(root, expirationTime) {
25988
  // This is called when new work is started on a root.
25989
  if (!enableSchedulerTracing) {
25990
    return;
25991
  } // Determine which interactions this batch of work currently includes, So that
25992
  // we can accurately attribute time spent working on it, And so that cascading
25993
  // work triggered during the render phase will be associated with it.
25994
25995
25996
  var interactions = new Set();
25997
  root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
25998
    if (scheduledExpirationTime >= expirationTime) {
25999
      scheduledInteractions.forEach(function (interaction) {
26000
        return interactions.add(interaction);
26001
      });
26002
    }
26003
  }); // Store the current set of interactions on the FiberRoot for a few reasons:
26004
  // We can re-use it in hot functions like renderRoot() without having to
26005
  // recalculate it. We will also use it in commitWork() to pass to any Profiler
26006
  // onRender() hooks. This also provides DevTools with a way to access it when
26007
  // the onCommitRoot() hook is called.
26008
26009
  root.memoizedInteractions = interactions;
26010
26011
  if (interactions.size > 0) {
26012
    var subscriber = tracing.__subscriberRef.current;
26013
26014
    if (subscriber !== null) {
26015
      var threadID = computeThreadID(root, expirationTime);
26016
26017
      try {
26018
        subscriber.onWorkStarted(interactions, threadID);
26019
      } catch (error) {
26020
        // If the subscriber throws, rethrow it in a separate task
26021
        scheduleCallback(ImmediatePriority, function () {
26022
          throw error;
26023
        });
26024
      }
26025
    }
26026
  }
26027
}
26028
26029
function finishPendingInteractions(root, committedExpirationTime) {
26030
  if (!enableSchedulerTracing) {
26031
    return;
26032
  }
26033
26034
  var earliestRemainingTimeAfterCommit = root.firstPendingTime;
26035
  var subscriber;
26036
26037
  try {
26038
    subscriber = tracing.__subscriberRef.current;
26039
26040
    if (subscriber !== null && root.memoizedInteractions.size > 0) {
26041
      var threadID = computeThreadID(root, committedExpirationTime);
26042
      subscriber.onWorkStopped(root.memoizedInteractions, threadID);
26043
    }
26044
  } catch (error) {
26045
    // If the subscriber throws, rethrow it in a separate task
26046
    scheduleCallback(ImmediatePriority, function () {
26047
      throw error;
26048
    });
26049
  } finally {
26050
    // Clear completed interactions from the pending Map.
26051
    // Unless the render was suspended or cascading work was scheduled,
26052
    // In which case– leave pending interactions until the subsequent render.
26053
    var pendingInteractionMap = root.pendingInteractionMap;
26054
    pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
26055
      // Only decrement the pending interaction count if we're done.
26056
      // If there's still work at the current priority,
26057
      // That indicates that we are waiting for suspense data.
26058
      if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
26059
        pendingInteractionMap.delete(scheduledExpirationTime);
26060
        scheduledInteractions.forEach(function (interaction) {
26061
          interaction.__count--;
26062
26063
          if (subscriber !== null && interaction.__count === 0) {
26064
            try {
26065
              subscriber.onInteractionScheduledWorkCompleted(interaction);
26066
            } catch (error) {
26067
              // If the subscriber throws, rethrow it in a separate task
26068
              scheduleCallback(ImmediatePriority, function () {
26069
                throw error;
26070
              });
26071
            }
26072
          }
26073
        });
26074
      }
26075
    });
26076
  }
26077
}
26078
26079
var onCommitFiberRoot = null;
26080
var onCommitFiberUnmount = null;
26081
var hasLoggedError = false;
26082
var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
26083
function injectInternals(internals) {
26084
  if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
26085
    // No DevTools
26086
    return false;
26087
  }
26088
26089
  var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
26090
26091
  if (hook.isDisabled) {
26092
    // This isn't a real property on the hook, but it can be set to opt out
26093
    // of DevTools integration and associated warnings and logs.
26094
    // https://github.com/facebook/react/issues/3877
26095
    return true;
26096
  }
26097
26098
  if (!hook.supportsFiber) {
26099
    {
26100
      warningWithoutStack$1(false, 'The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://fb.me/react-devtools');
26101
    } // DevTools exists, even though it doesn't support Fiber.
26102
26103
26104
    return true;
26105
  }
26106
26107
  try {
26108
    var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.
26109
26110
    onCommitFiberRoot = function (root, expirationTime) {
26111
      try {
26112
        var didError = (root.current.effectTag & DidCapture) === DidCapture;
26113
26114
        if (enableProfilerTimer) {
26115
          var currentTime = requestCurrentTime();
26116
          var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime);
26117
          hook.onCommitFiberRoot(rendererID, root, priorityLevel, didError);
26118
        } else {
26119
          hook.onCommitFiberRoot(rendererID, root, undefined, didError);
26120
        }
26121
      } catch (err) {
26122
        if (true && !hasLoggedError) {
26123
          hasLoggedError = true;
26124
          warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
26125
        }
26126
      }
26127
    };
26128
26129
    onCommitFiberUnmount = function (fiber) {
26130
      try {
26131
        hook.onCommitFiberUnmount(rendererID, fiber);
26132
      } catch (err) {
26133
        if (true && !hasLoggedError) {
26134
          hasLoggedError = true;
26135
          warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
26136
        }
26137
      }
26138
    };
26139
  } catch (err) {
26140
    // Catch all errors because it is unsafe to throw during initialization.
26141
    {
26142
      warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
26143
    }
26144
  } // DevTools exists
26145
26146
26147
  return true;
26148
}
26149
function onCommitRoot(root, expirationTime) {
26150
  if (typeof onCommitFiberRoot === 'function') {
26151
    onCommitFiberRoot(root, expirationTime);
26152
  }
26153
}
26154
function onCommitUnmount(fiber) {
26155
  if (typeof onCommitFiberUnmount === 'function') {
26156
    onCommitFiberUnmount(fiber);
26157
  }
26158
}
26159
26160
var hasBadMapPolyfill;
26161
26162
{
26163
  hasBadMapPolyfill = false;
26164
26165
  try {
26166
    var nonExtensibleObject = Object.preventExtensions({});
26167
    var testMap = new Map([[nonExtensibleObject, null]]);
26168
    var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused.
26169
    // https://github.com/rollup/rollup/issues/1771
26170
    // TODO: we can remove these if Rollup fixes the bug.
26171
26172
    testMap.set(0, 0);
26173
    testSet.add(0);
26174
  } catch (e) {
26175
    // TODO: Consider warning about bad polyfills
26176
    hasBadMapPolyfill = true;
26177
  }
26178
}
26179
26180
var debugCounter = 1;
26181
26182
function FiberNode(tag, pendingProps, key, mode) {
26183
  // Instance
26184
  this.tag = tag;
26185
  this.key = key;
26186
  this.elementType = null;
26187
  this.type = null;
26188
  this.stateNode = null; // Fiber
26189
26190
  this.return = null;
26191
  this.child = null;
26192
  this.sibling = null;
26193
  this.index = 0;
26194
  this.ref = null;
26195
  this.pendingProps = pendingProps;
26196
  this.memoizedProps = null;
26197
  this.updateQueue = null;
26198
  this.memoizedState = null;
26199
  this.dependencies = null;
26200
  this.mode = mode; // Effects
26201
26202
  this.effectTag = NoEffect;
26203
  this.nextEffect = null;
26204
  this.firstEffect = null;
26205
  this.lastEffect = null;
26206
  this.expirationTime = NoWork;
26207
  this.childExpirationTime = NoWork;
26208
  this.alternate = null;
26209
26210
  if (enableProfilerTimer) {
26211
    // Note: The following is done to avoid a v8 performance cliff.
26212
    //
26213
    // Initializing the fields below to smis and later updating them with
26214
    // double values will cause Fibers to end up having separate shapes.
26215
    // This behavior/bug has something to do with Object.preventExtension().
26216
    // Fortunately this only impacts DEV builds.
26217
    // Unfortunately it makes React unusably slow for some applications.
26218
    // To work around this, initialize the fields below with doubles.
26219
    //
26220
    // Learn more about this here:
26221
    // https://github.com/facebook/react/issues/14365
26222
    // https://bugs.chromium.org/p/v8/issues/detail?id=8538
26223
    this.actualDuration = Number.NaN;
26224
    this.actualStartTime = Number.NaN;
26225
    this.selfBaseDuration = Number.NaN;
26226
    this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.
26227
    // This won't trigger the performance cliff mentioned above,
26228
    // and it simplifies other profiler code (including DevTools).
26229
26230
    this.actualDuration = 0;
26231
    this.actualStartTime = -1;
26232
    this.selfBaseDuration = 0;
26233
    this.treeBaseDuration = 0;
26234
  } // This is normally DEV-only except www when it adds listeners.
26235
  // TODO: remove the User Timing integration in favor of Root Events.
26236
26237
26238
  if (enableUserTimingAPI) {
26239
    this._debugID = debugCounter++;
26240
    this._debugIsCurrentlyTiming = false;
26241
  }
26242
26243
  {
26244
    this._debugSource = null;
26245
    this._debugOwner = null;
26246
    this._debugNeedsRemount = false;
26247
    this._debugHookTypes = null;
26248
26249
    if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
26250
      Object.preventExtensions(this);
26251
    }
26252
  }
26253
} // This is a constructor function, rather than a POJO constructor, still
26254
// please ensure we do the following:
26255
// 1) Nobody should add any instance methods on this. Instance methods can be
26256
//    more difficult to predict when they get optimized and they are almost
26257
//    never inlined properly in static compilers.
26258
// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
26259
//    always know when it is a fiber.
26260
// 3) We might want to experiment with using numeric keys since they are easier
26261
//    to optimize in a non-JIT environment.
26262
// 4) We can easily go from a constructor to a createFiber object literal if that
26263
//    is faster.
26264
// 5) It should be easy to port this to a C struct and keep a C implementation
26265
//    compatible.
26266
26267
26268
var createFiber = function (tag, pendingProps, key, mode) {
26269
  // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
26270
  return new FiberNode(tag, pendingProps, key, mode);
26271
};
26272
26273
function shouldConstruct(Component) {
26274
  var prototype = Component.prototype;
26275
  return !!(prototype && prototype.isReactComponent);
26276
}
26277
26278
function isSimpleFunctionComponent(type) {
26279
  return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
26280
}
26281
function resolveLazyComponentTag(Component) {
26282
  if (typeof Component === 'function') {
26283
    return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
26284
  } else if (Component !== undefined && Component !== null) {
26285
    var $$typeof = Component.$$typeof;
26286
26287
    if ($$typeof === REACT_FORWARD_REF_TYPE) {
26288
      return ForwardRef;
26289
    }
26290
26291
    if ($$typeof === REACT_MEMO_TYPE) {
26292
      return MemoComponent;
26293
    }
26294
  }
26295
26296
  return IndeterminateComponent;
26297
} // This is used to create an alternate fiber to do work on.
26298
26299
function createWorkInProgress(current, pendingProps, expirationTime) {
26300
  var workInProgress = current.alternate;
26301
26302
  if (workInProgress === null) {
26303
    // We use a double buffering pooling technique because we know that we'll
26304
    // only ever need at most two versions of a tree. We pool the "other" unused
26305
    // node that we're free to reuse. This is lazily created to avoid allocating
26306
    // extra objects for things that are never updated. It also allow us to
26307
    // reclaim the extra memory if needed.
26308
    workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
26309
    workInProgress.elementType = current.elementType;
26310
    workInProgress.type = current.type;
26311
    workInProgress.stateNode = current.stateNode;
26312
26313
    {
26314
      // DEV-only fields
26315
      workInProgress._debugID = current._debugID;
26316
      workInProgress._debugSource = current._debugSource;
26317
      workInProgress._debugOwner = current._debugOwner;
26318
      workInProgress._debugHookTypes = current._debugHookTypes;
26319
    }
26320
26321
    workInProgress.alternate = current;
26322
    current.alternate = workInProgress;
26323
  } else {
26324
    workInProgress.pendingProps = pendingProps; // We already have an alternate.
26325
    // Reset the effect tag.
26326
26327
    workInProgress.effectTag = NoEffect; // The effect list is no longer valid.
26328
26329
    workInProgress.nextEffect = null;
26330
    workInProgress.firstEffect = null;
26331
    workInProgress.lastEffect = null;
26332
26333
    if (enableProfilerTimer) {
26334
      // We intentionally reset, rather than copy, actualDuration & actualStartTime.
26335
      // This prevents time from endlessly accumulating in new commits.
26336
      // This has the downside of resetting values for different priority renders,
26337
      // But works for yielding (the common case) and should support resuming.
26338
      workInProgress.actualDuration = 0;
26339
      workInProgress.actualStartTime = -1;
26340
    }
26341
  }
26342
26343
  workInProgress.childExpirationTime = current.childExpirationTime;
26344
  workInProgress.expirationTime = current.expirationTime;
26345
  workInProgress.child = current.child;
26346
  workInProgress.memoizedProps = current.memoizedProps;
26347
  workInProgress.memoizedState = current.memoizedState;
26348
  workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
26349
  // it cannot be shared with the current fiber.
26350
26351
  var currentDependencies = current.dependencies;
26352
  workInProgress.dependencies = currentDependencies === null ? null : {
26353
    expirationTime: currentDependencies.expirationTime,
26354
    firstContext: currentDependencies.firstContext,
26355
    responders: currentDependencies.responders
26356
  }; // These will be overridden during the parent's reconciliation
26357
26358
  workInProgress.sibling = current.sibling;
26359
  workInProgress.index = current.index;
26360
  workInProgress.ref = current.ref;
26361
26362
  if (enableProfilerTimer) {
26363
    workInProgress.selfBaseDuration = current.selfBaseDuration;
26364
    workInProgress.treeBaseDuration = current.treeBaseDuration;
26365
  }
26366
26367
  {
26368
    workInProgress._debugNeedsRemount = current._debugNeedsRemount;
26369
26370
    switch (workInProgress.tag) {
26371
      case IndeterminateComponent:
26372
      case FunctionComponent:
26373
      case SimpleMemoComponent:
26374
        workInProgress.type = resolveFunctionForHotReloading(current.type);
26375
        break;
26376
26377
      case ClassComponent:
26378
        workInProgress.type = resolveClassForHotReloading(current.type);
26379
        break;
26380
26381
      case ForwardRef:
26382
        workInProgress.type = resolveForwardRefForHotReloading(current.type);
26383
        break;
26384
26385
      default:
26386
        break;
26387
    }
26388
  }
26389
26390
  return workInProgress;
26391
} // Used to reuse a Fiber for a second pass.
26392
26393
function resetWorkInProgress(workInProgress, renderExpirationTime) {
26394
  // This resets the Fiber to what createFiber or createWorkInProgress would
26395
  // have set the values to before during the first pass. Ideally this wouldn't
26396
  // be necessary but unfortunately many code paths reads from the workInProgress
26397
  // when they should be reading from current and writing to workInProgress.
26398
  // We assume pendingProps, index, key, ref, return are still untouched to
26399
  // avoid doing another reconciliation.
26400
  // Reset the effect tag but keep any Placement tags, since that's something
26401
  // that child fiber is setting, not the reconciliation.
26402
  workInProgress.effectTag &= Placement; // The effect list is no longer valid.
26403
26404
  workInProgress.nextEffect = null;
26405
  workInProgress.firstEffect = null;
26406
  workInProgress.lastEffect = null;
26407
  var current = workInProgress.alternate;
26408
26409
  if (current === null) {
26410
    // Reset to createFiber's initial values.
26411
    workInProgress.childExpirationTime = NoWork;
26412
    workInProgress.expirationTime = renderExpirationTime;
26413
    workInProgress.child = null;
26414
    workInProgress.memoizedProps = null;
26415
    workInProgress.memoizedState = null;
26416
    workInProgress.updateQueue = null;
26417
    workInProgress.dependencies = null;
26418
26419
    if (enableProfilerTimer) {
26420
      // Note: We don't reset the actualTime counts. It's useful to accumulate
26421
      // actual time across multiple render passes.
26422
      workInProgress.selfBaseDuration = 0;
26423
      workInProgress.treeBaseDuration = 0;
26424
    }
26425
  } else {
26426
    // Reset to the cloned values that createWorkInProgress would've.
26427
    workInProgress.childExpirationTime = current.childExpirationTime;
26428
    workInProgress.expirationTime = current.expirationTime;
26429
    workInProgress.child = current.child;
26430
    workInProgress.memoizedProps = current.memoizedProps;
26431
    workInProgress.memoizedState = current.memoizedState;
26432
    workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
26433
    // it cannot be shared with the current fiber.
26434
26435
    var currentDependencies = current.dependencies;
26436
    workInProgress.dependencies = currentDependencies === null ? null : {
26437
      expirationTime: currentDependencies.expirationTime,
26438
      firstContext: currentDependencies.firstContext,
26439
      responders: currentDependencies.responders
26440
    };
26441
26442
    if (enableProfilerTimer) {
26443
      // Note: We don't reset the actualTime counts. It's useful to accumulate
26444
      // actual time across multiple render passes.
26445
      workInProgress.selfBaseDuration = current.selfBaseDuration;
26446
      workInProgress.treeBaseDuration = current.treeBaseDuration;
26447
    }
26448
  }
26449
26450
  return workInProgress;
26451
}
26452
function createHostRootFiber(tag) {
26453
  var mode;
26454
26455
  if (tag === ConcurrentRoot) {
26456
    mode = ConcurrentMode | BatchedMode | StrictMode;
26457
  } else if (tag === BatchedRoot) {
26458
    mode = BatchedMode | StrictMode;
26459
  } else {
26460
    mode = NoMode;
26461
  }
26462
26463
  if (enableProfilerTimer && isDevToolsPresent) {
26464
    // Always collect profile timings when DevTools are present.
26465
    // This enables DevTools to start capturing timing at any point–
26466
    // Without some nodes in the tree having empty base times.
26467
    mode |= ProfileMode;
26468
  }
26469
26470
  return createFiber(HostRoot, null, null, mode);
26471
}
26472
function createFiberFromTypeAndProps(type, // React$ElementType
26473
key, pendingProps, owner, mode, expirationTime) {
26474
  var fiber;
26475
  var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
26476
26477
  var resolvedType = type;
26478
26479
  if (typeof type === 'function') {
26480
    if (shouldConstruct(type)) {
26481
      fiberTag = ClassComponent;
26482
26483
      {
26484
        resolvedType = resolveClassForHotReloading(resolvedType);
26485
      }
26486
    } else {
26487
      {
26488
        resolvedType = resolveFunctionForHotReloading(resolvedType);
26489
      }
26490
    }
26491
  } else if (typeof type === 'string') {
26492
    fiberTag = HostComponent;
26493
  } else {
26494
    getTag: switch (type) {
26495
      case REACT_FRAGMENT_TYPE:
26496
        return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
26497
26498
      case REACT_CONCURRENT_MODE_TYPE:
26499
        fiberTag = Mode;
26500
        mode |= ConcurrentMode | BatchedMode | StrictMode;
26501
        break;
26502
26503
      case REACT_STRICT_MODE_TYPE:
26504
        fiberTag = Mode;
26505
        mode |= StrictMode;
26506
        break;
26507
26508
      case REACT_PROFILER_TYPE:
26509
        return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
26510
26511
      case REACT_SUSPENSE_TYPE:
26512
        return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
26513
26514
      case REACT_SUSPENSE_LIST_TYPE:
26515
        return createFiberFromSuspenseList(pendingProps, mode, expirationTime, key);
26516
26517
      default:
26518
        {
26519
          if (typeof type === 'object' && type !== null) {
26520
            switch (type.$$typeof) {
26521
              case REACT_PROVIDER_TYPE:
26522
                fiberTag = ContextProvider;
26523
                break getTag;
26524
26525
              case REACT_CONTEXT_TYPE:
26526
                // This is a consumer
26527
                fiberTag = ContextConsumer;
26528
                break getTag;
26529
26530
              case REACT_FORWARD_REF_TYPE:
26531
                fiberTag = ForwardRef;
26532
26533
                {
26534
                  resolvedType = resolveForwardRefForHotReloading(resolvedType);
26535
                }
26536
26537
                break getTag;
26538
26539
              case REACT_MEMO_TYPE:
26540
                fiberTag = MemoComponent;
26541
                break getTag;
26542
26543
              case REACT_LAZY_TYPE:
26544
                fiberTag = LazyComponent;
26545
                resolvedType = null;
26546
                break getTag;
26547
26548
              case REACT_FUNDAMENTAL_TYPE:
26549
                if (enableFundamentalAPI) {
26550
                  return createFiberFromFundamental(type, pendingProps, mode, expirationTime, key);
26551
                }
26552
26553
                break;
26554
26555
              case REACT_SCOPE_TYPE:
26556
                if (enableScopeAPI) {
26557
                  return createFiberFromScope(type, pendingProps, mode, expirationTime, key);
26558
                }
26559
26560
            }
26561
          }
26562
26563
          var info = '';
26564
26565
          {
26566
            if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
26567
              info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
26568
            }
26569
26570
            var ownerName = owner ? getComponentName(owner.type) : null;
26571
26572
            if (ownerName) {
26573
              info += '\n\nCheck the render method of `' + ownerName + '`.';
26574
            }
26575
          }
26576
26577
          (function () {
26578
            {
26579
              {
26580
                throw ReactError(Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + (type == null ? type : typeof type) + "." + info));
26581
              }
26582
            }
26583
          })();
26584
        }
26585
    }
26586
  }
26587
26588
  fiber = createFiber(fiberTag, pendingProps, key, mode);
26589
  fiber.elementType = type;
26590
  fiber.type = resolvedType;
26591
  fiber.expirationTime = expirationTime;
26592
  return fiber;
26593
}
26594
function createFiberFromElement(element, mode, expirationTime) {
26595
  var owner = null;
26596
26597
  {
26598
    owner = element._owner;
26599
  }
26600
26601
  var type = element.type;
26602
  var key = element.key;
26603
  var pendingProps = element.props;
26604
  var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
26605
26606
  {
26607
    fiber._debugSource = element._source;
26608
    fiber._debugOwner = element._owner;
26609
  }
26610
26611
  return fiber;
26612
}
26613
function createFiberFromFragment(elements, mode, expirationTime, key) {
26614
  var fiber = createFiber(Fragment, elements, key, mode);
26615
  fiber.expirationTime = expirationTime;
26616
  return fiber;
26617
}
26618
function createFiberFromFundamental(fundamentalComponent, pendingProps, mode, expirationTime, key) {
26619
  var fiber = createFiber(FundamentalComponent, pendingProps, key, mode);
26620
  fiber.elementType = fundamentalComponent;
26621
  fiber.type = fundamentalComponent;
26622
  fiber.expirationTime = expirationTime;
26623
  return fiber;
26624
}
26625
26626
function createFiberFromScope(scope, pendingProps, mode, expirationTime, key) {
26627
  var fiber = createFiber(ScopeComponent, pendingProps, key, mode);
26628
  fiber.type = scope;
26629
  fiber.elementType = scope;
26630
  fiber.expirationTime = expirationTime;
26631
  return fiber;
26632
}
26633
26634
function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
26635
  {
26636
    if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
26637
      warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
26638
    }
26639
  }
26640
26641
  var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag.
26642
26643
  fiber.elementType = REACT_PROFILER_TYPE;
26644
  fiber.type = REACT_PROFILER_TYPE;
26645
  fiber.expirationTime = expirationTime;
26646
  return fiber;
26647
}
26648
26649
function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
26650
  var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
26651
  // This needs to be fixed in getComponentName so that it relies on the tag
26652
  // instead.
26653
26654
  fiber.type = REACT_SUSPENSE_TYPE;
26655
  fiber.elementType = REACT_SUSPENSE_TYPE;
26656
  fiber.expirationTime = expirationTime;
26657
  return fiber;
26658
}
26659
function createFiberFromSuspenseList(pendingProps, mode, expirationTime, key) {
26660
  var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
26661
26662
  {
26663
    // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag.
26664
    // This needs to be fixed in getComponentName so that it relies on the tag
26665
    // instead.
26666
    fiber.type = REACT_SUSPENSE_LIST_TYPE;
26667
  }
26668
26669
  fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
26670
  fiber.expirationTime = expirationTime;
26671
  return fiber;
26672
}
26673
function createFiberFromText(content, mode, expirationTime) {
26674
  var fiber = createFiber(HostText, content, null, mode);
26675
  fiber.expirationTime = expirationTime;
26676
  return fiber;
26677
}
26678
function createFiberFromHostInstanceForDeletion() {
26679
  var fiber = createFiber(HostComponent, null, null, NoMode); // TODO: These should not need a type.
26680
26681
  fiber.elementType = 'DELETED';
26682
  fiber.type = 'DELETED';
26683
  return fiber;
26684
}
26685
function createFiberFromDehydratedFragment(dehydratedNode) {
26686
  var fiber = createFiber(DehydratedFragment, null, null, NoMode);
26687
  fiber.stateNode = dehydratedNode;
26688
  return fiber;
26689
}
26690
function createFiberFromPortal(portal, mode, expirationTime) {
26691
  var pendingProps = portal.children !== null ? portal.children : [];
26692
  var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
26693
  fiber.expirationTime = expirationTime;
26694
  fiber.stateNode = {
26695
    containerInfo: portal.containerInfo,
26696
    pendingChildren: null,
26697
    // Used by persistent updates
26698
    implementation: portal.implementation
26699
  };
26700
  return fiber;
26701
} // Used for stashing WIP properties to replay failed work in DEV.
26702
26703
function assignFiberPropertiesInDEV(target, source) {
26704
  if (target === null) {
26705
    // This Fiber's initial properties will always be overwritten.
26706
    // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
26707
    target = createFiber(IndeterminateComponent, null, null, NoMode);
26708
  } // This is intentionally written as a list of all properties.
26709
  // We tried to use Object.assign() instead but this is called in
26710
  // the hottest path, and Object.assign() was too slow:
26711
  // https://github.com/facebook/react/issues/12502
26712
  // This code is DEV-only so size is not a concern.
26713
26714
26715
  target.tag = source.tag;
26716
  target.key = source.key;
26717
  target.elementType = source.elementType;
26718
  target.type = source.type;
26719
  target.stateNode = source.stateNode;
26720
  target.return = source.return;
26721
  target.child = source.child;
26722
  target.sibling = source.sibling;
26723
  target.index = source.index;
26724
  target.ref = source.ref;
26725
  target.pendingProps = source.pendingProps;
26726
  target.memoizedProps = source.memoizedProps;
26727
  target.updateQueue = source.updateQueue;
26728
  target.memoizedState = source.memoizedState;
26729
  target.dependencies = source.dependencies;
26730
  target.mode = source.mode;
26731
  target.effectTag = source.effectTag;
26732
  target.nextEffect = source.nextEffect;
26733
  target.firstEffect = source.firstEffect;
26734
  target.lastEffect = source.lastEffect;
26735
  target.expirationTime = source.expirationTime;
26736
  target.childExpirationTime = source.childExpirationTime;
26737
  target.alternate = source.alternate;
26738
26739
  if (enableProfilerTimer) {
26740
    target.actualDuration = source.actualDuration;
26741
    target.actualStartTime = source.actualStartTime;
26742
    target.selfBaseDuration = source.selfBaseDuration;
26743
    target.treeBaseDuration = source.treeBaseDuration;
26744
  }
26745
26746
  target._debugID = source._debugID;
26747
  target._debugSource = source._debugSource;
26748
  target._debugOwner = source._debugOwner;
26749
  target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
26750
  target._debugNeedsRemount = source._debugNeedsRemount;
26751
  target._debugHookTypes = source._debugHookTypes;
26752
  return target;
26753
}
26754
26755
function FiberRootNode(containerInfo, tag, hydrate) {
26756
  this.tag = tag;
26757
  this.current = null;
26758
  this.containerInfo = containerInfo;
26759
  this.pendingChildren = null;
26760
  this.pingCache = null;
26761
  this.finishedExpirationTime = NoWork;
26762
  this.finishedWork = null;
26763
  this.timeoutHandle = noTimeout;
26764
  this.context = null;
26765
  this.pendingContext = null;
26766
  this.hydrate = hydrate;
26767
  this.firstBatch = null;
26768
  this.callbackNode = null;
26769
  this.callbackPriority = NoPriority;
26770
  this.firstPendingTime = NoWork;
26771
  this.firstSuspendedTime = NoWork;
26772
  this.lastSuspendedTime = NoWork;
26773
  this.nextKnownPendingLevel = NoWork;
26774
  this.lastPingedTime = NoWork;
26775
  this.lastExpiredTime = NoWork;
26776
26777
  if (enableSchedulerTracing) {
26778
    this.interactionThreadID = tracing.unstable_getThreadID();
26779
    this.memoizedInteractions = new Set();
26780
    this.pendingInteractionMap = new Map();
26781
  }
26782
26783
  if (enableSuspenseCallback) {
26784
    this.hydrationCallbacks = null;
26785
  }
26786
}
26787
26788
function createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) {
26789
  var root = new FiberRootNode(containerInfo, tag, hydrate);
26790
26791
  if (enableSuspenseCallback) {
26792
    root.hydrationCallbacks = hydrationCallbacks;
26793
  } // Cyclic construction. This cheats the type system right now because
26794
  // stateNode is any.
26795
26796
26797
  var uninitializedFiber = createHostRootFiber(tag);
26798
  root.current = uninitializedFiber;
26799
  uninitializedFiber.stateNode = root;
26800
  return root;
26801
}
26802
function isRootSuspendedAtTime(root, expirationTime) {
26803
  var firstSuspendedTime = root.firstSuspendedTime;
26804
  var lastSuspendedTime = root.lastSuspendedTime;
26805
  return firstSuspendedTime !== NoWork && firstSuspendedTime >= expirationTime && lastSuspendedTime <= expirationTime;
26806
}
26807
function markRootSuspendedAtTime(root, expirationTime) {
26808
  var firstSuspendedTime = root.firstSuspendedTime;
26809
  var lastSuspendedTime = root.lastSuspendedTime;
26810
26811
  if (firstSuspendedTime < expirationTime) {
26812
    root.firstSuspendedTime = expirationTime;
26813
  }
26814
26815
  if (lastSuspendedTime > expirationTime || firstSuspendedTime === NoWork) {
26816
    root.lastSuspendedTime = expirationTime;
26817
  }
26818
26819
  if (expirationTime <= root.lastPingedTime) {
26820
    root.lastPingedTime = NoWork;
26821
  }
26822
26823
  if (expirationTime <= root.lastExpiredTime) {
26824
    root.lastExpiredTime = NoWork;
26825
  }
26826
}
26827
function markRootUpdatedAtTime(root, expirationTime) {
26828
  // Update the range of pending times
26829
  var firstPendingTime = root.firstPendingTime;
26830
26831
  if (expirationTime > firstPendingTime) {
26832
    root.firstPendingTime = expirationTime;
26833
  } // Update the range of suspended times. Treat everything lower priority or
26834
  // equal to this update as unsuspended.
26835
26836
26837
  var firstSuspendedTime = root.firstSuspendedTime;
26838
26839
  if (firstSuspendedTime !== NoWork) {
26840
    if (expirationTime >= firstSuspendedTime) {
26841
      // The entire suspended range is now unsuspended.
26842
      root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
26843
    } else if (expirationTime >= root.lastSuspendedTime) {
26844
      root.lastSuspendedTime = expirationTime + 1;
26845
    } // This is a pending level. Check if it's higher priority than the next
26846
    // known pending level.
26847
26848
26849
    if (expirationTime > root.nextKnownPendingLevel) {
26850
      root.nextKnownPendingLevel = expirationTime;
26851
    }
26852
  }
26853
}
26854
function markRootFinishedAtTime(root, finishedExpirationTime, remainingExpirationTime) {
26855
  // Update the range of pending times
26856
  root.firstPendingTime = remainingExpirationTime; // Update the range of suspended times. Treat everything higher priority or
26857
  // equal to this update as unsuspended.
26858
26859
  if (finishedExpirationTime <= root.lastSuspendedTime) {
26860
    // The entire suspended range is now unsuspended.
26861
    root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
26862
  } else if (finishedExpirationTime <= root.firstSuspendedTime) {
26863
    // Part of the suspended range is now unsuspended. Narrow the range to
26864
    // include everything between the unsuspended time (non-inclusive) and the
26865
    // last suspended time.
26866
    root.firstSuspendedTime = finishedExpirationTime - 1;
26867
  }
26868
26869
  if (finishedExpirationTime <= root.lastPingedTime) {
26870
    // Clear the pinged time
26871
    root.lastPingedTime = NoWork;
26872
  }
26873
26874
  if (finishedExpirationTime <= root.lastExpiredTime) {
26875
    // Clear the expired time
26876
    root.lastExpiredTime = NoWork;
26877
  }
26878
}
26879
function markRootExpiredAtTime(root, expirationTime) {
26880
  var lastExpiredTime = root.lastExpiredTime;
26881
26882
  if (lastExpiredTime === NoWork || lastExpiredTime > expirationTime) {
26883
    root.lastExpiredTime = expirationTime;
26884
  }
26885
}
26886
26887
// This lets us hook into Fiber to debug what it's doing.
26888
// See https://github.com/facebook/react/pull/8033.
26889
// This is not part of the public API, not even for React DevTools.
26890
// You may only inject a debugTool if you work on React Fiber itself.
26891
var ReactFiberInstrumentation = {
26892
  debugTool: null
26893
};
26894
var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
26895
26896
var didWarnAboutNestedUpdates;
26897
var didWarnAboutFindNodeInStrictMode;
26898
26899
{
26900
  didWarnAboutNestedUpdates = false;
26901
  didWarnAboutFindNodeInStrictMode = {};
26902
}
26903
26904
function getContextForSubtree(parentComponent) {
26905
  if (!parentComponent) {
26906
    return emptyContextObject;
26907
  }
26908
26909
  var fiber = get(parentComponent);
26910
  var parentContext = findCurrentUnmaskedContext(fiber);
26911
26912
  if (fiber.tag === ClassComponent) {
26913
    var Component = fiber.type;
26914
26915
    if (isContextProvider(Component)) {
26916
      return processChildContext(fiber, Component, parentContext);
26917
    }
26918
  }
26919
26920
  return parentContext;
26921
}
26922
26923
function scheduleRootUpdate(current$$1, element, expirationTime, suspenseConfig, callback) {
26924
  {
26925
    if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) {
26926
      didWarnAboutNestedUpdates = true;
26927
      warningWithoutStack$1(false, 'Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentName(current.type) || 'Unknown');
26928
    }
26929
  }
26930
26931
  var update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property
26932
  // being called "element".
26933
26934
  update.payload = {
26935
    element: element
26936
  };
26937
  callback = callback === undefined ? null : callback;
26938
26939
  if (callback !== null) {
26940
    !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
26941
    update.callback = callback;
26942
  }
26943
26944
  enqueueUpdate(current$$1, update);
26945
  scheduleWork(current$$1, expirationTime);
26946
  return expirationTime;
26947
}
26948
26949
function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, suspenseConfig, callback) {
26950
  // TODO: If this is a nested container, this won't be the root.
26951
  var current$$1 = container.current;
26952
26953
  {
26954
    if (ReactFiberInstrumentation_1.debugTool) {
26955
      if (current$$1.alternate === null) {
26956
        ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
26957
      } else if (element === null) {
26958
        ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
26959
      } else {
26960
        ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
26961
      }
26962
    }
26963
  }
26964
26965
  var context = getContextForSubtree(parentComponent);
26966
26967
  if (container.context === null) {
26968
    container.context = context;
26969
  } else {
26970
    container.pendingContext = context;
26971
  }
26972
26973
  return scheduleRootUpdate(current$$1, element, expirationTime, suspenseConfig, callback);
26974
}
26975
26976
function findHostInstance(component) {
26977
  var fiber = get(component);
26978
26979
  if (fiber === undefined) {
26980
    if (typeof component.render === 'function') {
26981
      (function () {
26982
        {
26983
          {
26984
            throw ReactError(Error("Unable to find node on an unmounted component."));
26985
          }
26986
        }
26987
      })();
26988
    } else {
26989
      (function () {
26990
        {
26991
          {
26992
            throw ReactError(Error("Argument appears to not be a ReactComponent. Keys: " + Object.keys(component)));
26993
          }
26994
        }
26995
      })();
26996
    }
26997
  }
26998
26999
  var hostFiber = findCurrentHostFiber(fiber);
27000
27001
  if (hostFiber === null) {
27002
    return null;
27003
  }
27004
27005
  return hostFiber.stateNode;
27006
}
27007
27008
function findHostInstanceWithWarning(component, methodName) {
27009
  {
27010
    var fiber = get(component);
27011
27012
    if (fiber === undefined) {
27013
      if (typeof component.render === 'function') {
27014
        (function () {
27015
          {
27016
            {
27017
              throw ReactError(Error("Unable to find node on an unmounted component."));
27018
            }
27019
          }
27020
        })();
27021
      } else {
27022
        (function () {
27023
          {
27024
            {
27025
              throw ReactError(Error("Argument appears to not be a ReactComponent. Keys: " + Object.keys(component)));
27026
            }
27027
          }
27028
        })();
27029
      }
27030
    }
27031
27032
    var hostFiber = findCurrentHostFiber(fiber);
27033
27034
    if (hostFiber === null) {
27035
      return null;
27036
    }
27037
27038
    if (hostFiber.mode & StrictMode) {
27039
      var componentName = getComponentName(fiber.type) || 'Component';
27040
27041
      if (!didWarnAboutFindNodeInStrictMode[componentName]) {
27042
        didWarnAboutFindNodeInStrictMode[componentName] = true;
27043
27044
        if (fiber.mode & StrictMode) {
27045
          warningWithoutStack$1(false, '%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-find-node%s', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));
27046
        } else {
27047
          warningWithoutStack$1(false, '%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-find-node%s', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));
27048
        }
27049
      }
27050
    }
27051
27052
    return hostFiber.stateNode;
27053
  }
27054
27055
  return findHostInstance(component);
27056
}
27057
27058
function createContainer(containerInfo, tag, hydrate, hydrationCallbacks) {
27059
  return createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks);
27060
}
27061
function updateContainer(element, container, parentComponent, callback) {
27062
  var current$$1 = container.current;
27063
  var currentTime = requestCurrentTime();
27064
27065
  {
27066
    // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
27067
    if ('undefined' !== typeof jest) {
27068
      warnIfUnmockedScheduler(current$$1);
27069
      warnIfNotScopedWithMatchingAct(current$$1);
27070
    }
27071
  }
27072
27073
  var suspenseConfig = requestCurrentSuspenseConfig();
27074
  var expirationTime = computeExpirationForFiber(currentTime, current$$1, suspenseConfig);
27075
  return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, suspenseConfig, callback);
27076
}
27077
function getPublicRootInstance(container) {
27078
  var containerFiber = container.current;
27079
27080
  if (!containerFiber.child) {
27081
    return null;
27082
  }
27083
27084
  switch (containerFiber.child.tag) {
27085
    case HostComponent:
27086
      return getPublicInstance(containerFiber.child.stateNode);
27087
27088
    default:
27089
      return containerFiber.child.stateNode;
27090
  }
27091
}
27092
function attemptSynchronousHydration$1(fiber) {
27093
  switch (fiber.tag) {
27094
    case HostRoot:
27095
      var root = fiber.stateNode;
27096
27097
      if (root.hydrate) {
27098
        // Flush the first scheduled "update".
27099
        flushRoot(root, root.firstPendingTime);
27100
      }
27101
27102
      break;
27103
27104
    case SuspenseComponent:
27105
      flushSync(function () {
27106
        return scheduleWork(fiber, Sync);
27107
      });
27108
      break;
27109
  }
27110
}
27111
function findHostInstanceWithNoPortals(fiber) {
27112
  var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
27113
27114
  if (hostFiber === null) {
27115
    return null;
27116
  }
27117
27118
  if (hostFiber.tag === FundamentalComponent) {
27119
    return hostFiber.stateNode.instance;
27120
  }
27121
27122
  return hostFiber.stateNode;
27123
}
27124
27125
var shouldSuspendImpl = function (fiber) {
27126
  return false;
27127
};
27128
27129
function shouldSuspend(fiber) {
27130
  return shouldSuspendImpl(fiber);
27131
}
27132
var overrideHookState = null;
27133
var overrideProps = null;
27134
var scheduleUpdate = null;
27135
var setSuspenseHandler = null;
27136
27137
{
27138
  var copyWithSetImpl = function (obj, path, idx, value) {
27139
    if (idx >= path.length) {
27140
      return value;
27141
    }
27142
27143
    var key = path[idx];
27144
    var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj); // $FlowFixMe number or string is fine here
27145
27146
    updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
27147
    return updated;
27148
  };
27149
27150
  var copyWithSet = function (obj, path, value) {
27151
    return copyWithSetImpl(obj, path, 0, value);
27152
  }; // Support DevTools editable values for useState and useReducer.
27153
27154
27155
  overrideHookState = function (fiber, id, path, value) {
27156
    // For now, the "id" of stateful hooks is just the stateful hook index.
27157
    // This may change in the future with e.g. nested hooks.
27158
    var currentHook = fiber.memoizedState;
27159
27160
    while (currentHook !== null && id > 0) {
27161
      currentHook = currentHook.next;
27162
      id--;
27163
    }
27164
27165
    if (currentHook !== null) {
27166
      var newState = copyWithSet(currentHook.memoizedState, path, value);
27167
      currentHook.memoizedState = newState;
27168
      currentHook.baseState = newState; // We aren't actually adding an update to the queue,
27169
      // because there is no update we can add for useReducer hooks that won't trigger an error.
27170
      // (There's no appropriate action type for DevTools overrides.)
27171
      // As a result though, React will see the scheduled update as a noop and bailout.
27172
      // Shallow cloning props works as a workaround for now to bypass the bailout check.
27173
27174
      fiber.memoizedProps = _assign({}, fiber.memoizedProps);
27175
      scheduleWork(fiber, Sync);
27176
    }
27177
  }; // Support DevTools props for function components, forwardRef, memo, host components, etc.
27178
27179
27180
  overrideProps = function (fiber, path, value) {
27181
    fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
27182
27183
    if (fiber.alternate) {
27184
      fiber.alternate.pendingProps = fiber.pendingProps;
27185
    }
27186
27187
    scheduleWork(fiber, Sync);
27188
  };
27189
27190
  scheduleUpdate = function (fiber) {
27191
    scheduleWork(fiber, Sync);
27192
  };
27193
27194
  setSuspenseHandler = function (newShouldSuspendImpl) {
27195
    shouldSuspendImpl = newShouldSuspendImpl;
27196
  };
27197
}
27198
27199
function injectIntoDevTools(devToolsConfig) {
27200
  var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
27201
  var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
27202
  return injectInternals(_assign({}, devToolsConfig, {
27203
    overrideHookState: overrideHookState,
27204
    overrideProps: overrideProps,
27205
    setSuspenseHandler: setSuspenseHandler,
27206
    scheduleUpdate: scheduleUpdate,
27207
    currentDispatcherRef: ReactCurrentDispatcher,
27208
    findHostInstanceByFiber: function (fiber) {
27209
      var hostFiber = findCurrentHostFiber(fiber);
27210
27211
      if (hostFiber === null) {
27212
        return null;
27213
      }
27214
27215
      return hostFiber.stateNode;
27216
    },
27217
    findFiberByHostInstance: function (instance) {
27218
      if (!findFiberByHostInstance) {
27219
        // Might not be implemented by the renderer.
27220
        return null;
27221
      }
27222
27223
      return findFiberByHostInstance(instance);
27224
    },
27225
    // React Refresh
27226
    findHostInstancesForRefresh: findHostInstancesForRefresh,
27227
    scheduleRefresh: scheduleRefresh,
27228
    scheduleRoot: scheduleRoot,
27229
    setRefreshHandler: setRefreshHandler,
27230
    // Enables DevTools to append owner stacks to error messages in DEV mode.
27231
    getCurrentFiber: function () {
27232
      return current;
27233
    }
27234
  }));
27235
}
27236
27237
// This file intentionally does *not* have the Flow annotation.
27238
// Don't add it. See `./inline-typed.js` for an explanation.
27239
27240
function createPortal$1(children, containerInfo, // TODO: figure out the API for cross-renderer implementation.
27241
implementation) {
27242
  var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
27243
  return {
27244
    // This tag allow us to uniquely identify this as a React Portal
27245
    $$typeof: REACT_PORTAL_TYPE,
27246
    key: key == null ? null : '' + key,
27247
    children: children,
27248
    containerInfo: containerInfo,
27249
    implementation: implementation
27250
  };
27251
}
27252
27253
// TODO: this is special because it gets imported during build.
27254
27255
var ReactVersion = '16.10.1';
27256
27257
// TODO: This type is shared between the reconciler and ReactDOM, but will
27258
// eventually be lifted out to the renderer.
27259
setAttemptSynchronousHydration(attemptSynchronousHydration$1);
27260
var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
27261
var topLevelUpdateWarnings;
27262
var warnOnInvalidCallback;
27263
var didWarnAboutUnstableCreatePortal = false;
27264
27265
{
27266
  if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype
27267
  Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype
27268
  Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
27269
    warningWithoutStack$1(false, 'React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');
27270
  }
27271
27272
  topLevelUpdateWarnings = function (container) {
27273
    if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
27274
      var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
27275
27276
      if (hostInstance) {
27277
        !(hostInstance.parentNode === container) ? warningWithoutStack$1(false, 'render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.') : void 0;
27278
      }
27279
    }
27280
27281
    var isRootRenderedBySomeReact = !!container._reactRootContainer;
27282
    var rootEl = getReactRootElementInContainer(container);
27283
    var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));
27284
    !(!hasNonRootReactChild || isRootRenderedBySomeReact) ? warningWithoutStack$1(false, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : void 0;
27285
    !(container.nodeType !== ELEMENT_NODE || !container.tagName || container.tagName.toUpperCase() !== 'BODY') ? warningWithoutStack$1(false, 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : void 0;
27286
  };
27287
27288
  warnOnInvalidCallback = function (callback, callerName) {
27289
    !(callback === null || typeof callback === 'function') ? warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback) : void 0;
27290
  };
27291
}
27292
27293
setRestoreImplementation(restoreControlledState$$1);
27294
27295
function ReactBatch(root) {
27296
  var expirationTime = computeUniqueAsyncExpiration();
27297
  this._expirationTime = expirationTime;
27298
  this._root = root;
27299
  this._next = null;
27300
  this._callbacks = null;
27301
  this._didComplete = false;
27302
  this._hasChildren = false;
27303
  this._children = null;
27304
  this._defer = true;
27305
}
27306
27307
ReactBatch.prototype.render = function (children) {
27308
  var _this = this;
27309
27310
  (function () {
27311
    if (!_this._defer) {
27312
      {
27313
        throw ReactError(Error("batch.render: Cannot render a batch that already committed."));
27314
      }
27315
    }
27316
  })();
27317
27318
  this._hasChildren = true;
27319
  this._children = children;
27320
  var internalRoot = this._root._internalRoot;
27321
  var expirationTime = this._expirationTime;
27322
  var work = new ReactWork();
27323
  updateContainerAtExpirationTime(children, internalRoot, null, expirationTime, null, work._onCommit);
27324
  return work;
27325
};
27326
27327
ReactBatch.prototype.then = function (onComplete) {
27328
  if (this._didComplete) {
27329
    onComplete();
27330
    return;
27331
  }
27332
27333
  var callbacks = this._callbacks;
27334
27335
  if (callbacks === null) {
27336
    callbacks = this._callbacks = [];
27337
  }
27338
27339
  callbacks.push(onComplete);
27340
};
27341
27342
ReactBatch.prototype.commit = function () {
27343
  var _this2 = this;
27344
27345
  var internalRoot = this._root._internalRoot;
27346
  var firstBatch = internalRoot.firstBatch;
27347
27348
  (function () {
27349
    if (!(_this2._defer && firstBatch !== null)) {
27350
      {
27351
        throw ReactError(Error("batch.commit: Cannot commit a batch multiple times."));
27352
      }
27353
    }
27354
  })();
27355
27356
  if (!this._hasChildren) {
27357
    // This batch is empty. Return.
27358
    this._next = null;
27359
    this._defer = false;
27360
    return;
27361
  }
27362
27363
  var expirationTime = this._expirationTime; // Ensure this is the first batch in the list.
27364
27365
  if (firstBatch !== this) {
27366
    // This batch is not the earliest batch. We need to move it to the front.
27367
    // Update its expiration time to be the expiration time of the earliest
27368
    // batch, so that we can flush it without flushing the other batches.
27369
    if (this._hasChildren) {
27370
      expirationTime = this._expirationTime = firstBatch._expirationTime; // Rendering this batch again ensures its children will be the final state
27371
      // when we flush (updates are processed in insertion order: last
27372
      // update wins).
27373
      // TODO: This forces a restart. Should we print a warning?
27374
27375
      this.render(this._children);
27376
    } // Remove the batch from the list.
27377
27378
27379
    var previous = null;
27380
    var batch = firstBatch;
27381
27382
    while (batch !== this) {
27383
      previous = batch;
27384
      batch = batch._next;
27385
    }
27386
27387
    (function () {
27388
      if (!(previous !== null)) {
27389
        {
27390
          throw ReactError(Error("batch.commit: Cannot commit a batch multiple times."));
27391
        }
27392
      }
27393
    })();
27394
27395
    previous._next = batch._next; // Add it to the front.
27396
27397
    this._next = firstBatch;
27398
    firstBatch = internalRoot.firstBatch = this;
27399
  } // Synchronously flush all the work up to this batch's expiration time.
27400
27401
27402
  this._defer = false;
27403
  flushRoot(internalRoot, expirationTime); // Pop the batch from the list.
27404
27405
  var next = this._next;
27406
  this._next = null;
27407
  firstBatch = internalRoot.firstBatch = next; // Append the next earliest batch's children to the update queue.
27408
27409
  if (firstBatch !== null && firstBatch._hasChildren) {
27410
    firstBatch.render(firstBatch._children);
27411
  }
27412
};
27413
27414
ReactBatch.prototype._onComplete = function () {
27415
  if (this._didComplete) {
27416
    return;
27417
  }
27418
27419
  this._didComplete = true;
27420
  var callbacks = this._callbacks;
27421
27422
  if (callbacks === null) {
27423
    return;
27424
  } // TODO: Error handling.
27425
27426
27427
  for (var i = 0; i < callbacks.length; i++) {
27428
    var _callback = callbacks[i];
27429
27430
    _callback();
27431
  }
27432
};
27433
27434
function ReactWork() {
27435
  this._callbacks = null;
27436
  this._didCommit = false; // TODO: Avoid need to bind by replacing callbacks in the update queue with
27437
  // list of Work objects.
27438
27439
  this._onCommit = this._onCommit.bind(this);
27440
}
27441
27442
ReactWork.prototype.then = function (onCommit) {
27443
  if (this._didCommit) {
27444
    onCommit();
27445
    return;
27446
  }
27447
27448
  var callbacks = this._callbacks;
27449
27450
  if (callbacks === null) {
27451
    callbacks = this._callbacks = [];
27452
  }
27453
27454
  callbacks.push(onCommit);
27455
};
27456
27457
ReactWork.prototype._onCommit = function () {
27458
  if (this._didCommit) {
27459
    return;
27460
  }
27461
27462
  this._didCommit = true;
27463
  var callbacks = this._callbacks;
27464
27465
  if (callbacks === null) {
27466
    return;
27467
  } // TODO: Error handling.
27468
27469
27470
  for (var i = 0; i < callbacks.length; i++) {
27471
    var _callback2 = callbacks[i];
27472
27473
    (function () {
27474
      if (!(typeof _callback2 === 'function')) {
27475
        {
27476
          throw ReactError(Error("Invalid argument passed as callback. Expected a function. Instead received: " + _callback2));
27477
        }
27478
      }
27479
    })();
27480
27481
    _callback2();
27482
  }
27483
};
27484
27485
function createRootImpl(container, tag, options) {
27486
  // Tag is either LegacyRoot or Concurrent Root
27487
  var hydrate = options != null && options.hydrate === true;
27488
  var hydrationCallbacks = options != null && options.hydrationOptions || null;
27489
  var root = createContainer(container, tag, hydrate, hydrationCallbacks);
27490
  markContainerAsRoot(root.current, container);
27491
27492
  if (hydrate && tag !== LegacyRoot) {
27493
    var doc = container.nodeType === DOCUMENT_NODE ? container : container.ownerDocument;
27494
    eagerlyTrapReplayableEvents(doc);
27495
  }
27496
27497
  return root;
27498
}
27499
27500
function ReactSyncRoot(container, tag, options) {
27501
  this._internalRoot = createRootImpl(container, tag, options);
27502
}
27503
27504
function ReactRoot(container, options) {
27505
  this._internalRoot = createRootImpl(container, ConcurrentRoot, options);
27506
}
27507
27508
ReactRoot.prototype.render = ReactSyncRoot.prototype.render = function (children, callback) {
27509
  var root = this._internalRoot;
27510
  var work = new ReactWork();
27511
  callback = callback === undefined ? null : callback;
27512
27513
  {
27514
    warnOnInvalidCallback(callback, 'render');
27515
  }
27516
27517
  if (callback !== null) {
27518
    work.then(callback);
27519
  }
27520
27521
  updateContainer(children, root, null, work._onCommit);
27522
  return work;
27523
};
27524
27525
ReactRoot.prototype.unmount = ReactSyncRoot.prototype.unmount = function (callback) {
27526
  var root = this._internalRoot;
27527
  var work = new ReactWork();
27528
  callback = callback === undefined ? null : callback;
27529
27530
  {
27531
    warnOnInvalidCallback(callback, 'render');
27532
  }
27533
27534
  if (callback !== null) {
27535
    work.then(callback);
27536
  }
27537
27538
  updateContainer(null, root, null, work._onCommit);
27539
  return work;
27540
}; // Sync roots cannot create batches. Only concurrent ones.
27541
27542
27543
ReactRoot.prototype.createBatch = function () {
27544
  var batch = new ReactBatch(this);
27545
  var expirationTime = batch._expirationTime;
27546
  var internalRoot = this._internalRoot;
27547
  var firstBatch = internalRoot.firstBatch;
27548
27549
  if (firstBatch === null) {
27550
    internalRoot.firstBatch = batch;
27551
    batch._next = null;
27552
  } else {
27553
    // Insert sorted by expiration time then insertion order
27554
    var insertAfter = null;
27555
    var insertBefore = firstBatch;
27556
27557
    while (insertBefore !== null && insertBefore._expirationTime >= expirationTime) {
27558
      insertAfter = insertBefore;
27559
      insertBefore = insertBefore._next;
27560
    }
27561
27562
    batch._next = insertBefore;
27563
27564
    if (insertAfter !== null) {
27565
      insertAfter._next = batch;
27566
    }
27567
  }
27568
27569
  return batch;
27570
};
27571
/**
27572
 * True if the supplied DOM node is a valid node element.
27573
 *
27574
 * @param {?DOMElement} node The candidate DOM node.
27575
 * @return {boolean} True if the DOM is a valid DOM node.
27576
 * @internal
27577
 */
27578
27579
27580
function isValidContainer(node) {
27581
  return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable '));
27582
}
27583
27584
function getReactRootElementInContainer(container) {
27585
  if (!container) {
27586
    return null;
27587
  }
27588
27589
  if (container.nodeType === DOCUMENT_NODE) {
27590
    return container.documentElement;
27591
  } else {
27592
    return container.firstChild;
27593
  }
27594
}
27595
27596
function shouldHydrateDueToLegacyHeuristic(container) {
27597
  var rootElement = getReactRootElementInContainer(container);
27598
  return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
27599
}
27600
27601
setBatchingImplementation(batchedUpdates$1, discreteUpdates$1, flushDiscreteUpdates, batchedEventUpdates$1);
27602
var warnedAboutHydrateAPI = false;
27603
27604
function legacyCreateRootFromDOMContainer(container, forceHydrate) {
27605
  var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container); // First clear any existing content.
27606
27607
  if (!shouldHydrate) {
27608
    var warned = false;
27609
    var rootSibling;
27610
27611
    while (rootSibling = container.lastChild) {
27612
      {
27613
        if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
27614
          warned = true;
27615
          warningWithoutStack$1(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.');
27616
        }
27617
      }
27618
27619
      container.removeChild(rootSibling);
27620
    }
27621
  }
27622
27623
  {
27624
    if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
27625
      warnedAboutHydrateAPI = true;
27626
      lowPriorityWarningWithoutStack$1(false, 'render(): Calling ReactDOM.render() to hydrate server-rendered markup ' + 'will stop working in React v17. Replace the ReactDOM.render() call ' + 'with ReactDOM.hydrate() if you want React to attach to the server HTML.');
27627
    }
27628
  } // Legacy roots are not batched.
27629
27630
27631
  return new ReactSyncRoot(container, LegacyRoot, shouldHydrate ? {
27632
    hydrate: true
27633
  } : undefined);
27634
}
27635
27636
function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
27637
  {
27638
    topLevelUpdateWarnings(container);
27639
    warnOnInvalidCallback(callback === undefined ? null : callback, 'render');
27640
  } // TODO: Without `any` type, Flow says "Property cannot be accessed on any
27641
  // member of intersection type." Whyyyyyy.
27642
27643
27644
  var root = container._reactRootContainer;
27645
  var fiberRoot;
27646
27647
  if (!root) {
27648
    // Initial mount
27649
    root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
27650
    fiberRoot = root._internalRoot;
27651
27652
    if (typeof callback === 'function') {
27653
      var originalCallback = callback;
27654
27655
      callback = function () {
27656
        var instance = getPublicRootInstance(fiberRoot);
27657
        originalCallback.call(instance);
27658
      };
27659
    } // Initial mount should not be batched.
27660
27661
27662
    unbatchedUpdates(function () {
27663
      updateContainer(children, fiberRoot, parentComponent, callback);
27664
    });
27665
  } else {
27666
    fiberRoot = root._internalRoot;
27667
27668
    if (typeof callback === 'function') {
27669
      var _originalCallback = callback;
27670
27671
      callback = function () {
27672
        var instance = getPublicRootInstance(fiberRoot);
27673
27674
        _originalCallback.call(instance);
27675
      };
27676
    } // Update
27677
27678
27679
    updateContainer(children, fiberRoot, parentComponent, callback);
27680
  }
27681
27682
  return getPublicRootInstance(fiberRoot);
27683
}
27684
27685
function createPortal$$1(children, container) {
27686
  var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
27687
27688
  (function () {
27689
    if (!isValidContainer(container)) {
27690
      {
27691
        throw ReactError(Error("Target container is not a DOM element."));
27692
      }
27693
    }
27694
  })(); // TODO: pass ReactDOM portal implementation as third argument
27695
27696
27697
  return createPortal$1(children, container, null, key);
27698
}
27699
27700
var ReactDOM = {
27701
  createPortal: createPortal$$1,
27702
  findDOMNode: function (componentOrElement) {
27703
    {
27704
      var owner = ReactCurrentOwner.current;
27705
27706
      if (owner !== null && owner.stateNode !== null) {
27707
        var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
27708
        !warnedAboutRefsInRender ? warningWithoutStack$1(false, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(owner.type) || 'A component') : void 0;
27709
        owner.stateNode._warnedAboutRefsInRender = true;
27710
      }
27711
    }
27712
27713
    if (componentOrElement == null) {
27714
      return null;
27715
    }
27716
27717
    if (componentOrElement.nodeType === ELEMENT_NODE) {
27718
      return componentOrElement;
27719
    }
27720
27721
    {
27722
      return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
27723
    }
27724
27725
    return findHostInstance(componentOrElement);
27726
  },
27727
  hydrate: function (element, container, callback) {
27728
    (function () {
27729
      if (!isValidContainer(container)) {
27730
        {
27731
          throw ReactError(Error("Target container is not a DOM element."));
27732
        }
27733
      }
27734
    })();
27735
27736
    {
27737
      !!container._reactHasBeenPassedToCreateRootDEV ? warningWithoutStack$1(false, 'You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOM.%s(). This is not supported. ' + 'Did you mean to call createRoot(container, {hydrate: true}).render(element)?', enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot') : void 0;
27738
    } // TODO: throw or warn if we couldn't hydrate?
27739
27740
27741
    return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
27742
  },
27743
  render: function (element, container, callback) {
27744
    (function () {
27745
      if (!isValidContainer(container)) {
27746
        {
27747
          throw ReactError(Error("Target container is not a DOM element."));
27748
        }
27749
      }
27750
    })();
27751
27752
    {
27753
      !!container._reactHasBeenPassedToCreateRootDEV ? warningWithoutStack$1(false, 'You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOM.%s(). This is not supported. ' + 'Did you mean to call root.render(element)?', enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot') : void 0;
27754
    }
27755
27756
    return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
27757
  },
27758
  unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) {
27759
    (function () {
27760
      if (!isValidContainer(containerNode)) {
27761
        {
27762
          throw ReactError(Error("Target container is not a DOM element."));
27763
        }
27764
      }
27765
    })();
27766
27767
    (function () {
27768
      if (!(parentComponent != null && has(parentComponent))) {
27769
        {
27770
          throw ReactError(Error("parentComponent must be a valid React Component"));
27771
        }
27772
      }
27773
    })();
27774
27775
    return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
27776
  },
27777
  unmountComponentAtNode: function (container) {
27778
    (function () {
27779
      if (!isValidContainer(container)) {
27780
        {
27781
          throw ReactError(Error("unmountComponentAtNode(...): Target container is not a DOM element."));
27782
        }
27783
      }
27784
    })();
27785
27786
    {
27787
      !!container._reactHasBeenPassedToCreateRootDEV ? warningWithoutStack$1(false, 'You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOM.%s(). This is not supported. Did you mean to call root.unmount()?', enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot') : void 0;
27788
    }
27789
27790
    if (container._reactRootContainer) {
27791
      {
27792
        var rootEl = getReactRootElementInContainer(container);
27793
        var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);
27794
        !!renderedByDifferentReact ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0;
27795
      } // Unmount should not be batched.
27796
27797
27798
      unbatchedUpdates(function () {
27799
        legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
27800
          container._reactRootContainer = null;
27801
        });
27802
      }); // If you call unmountComponentAtNode twice in quick succession, you'll
27803
      // get `true` twice. That's probably fine?
27804
27805
      return true;
27806
    } else {
27807
      {
27808
        var _rootEl = getReactRootElementInContainer(container);
27809
27810
        var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl)); // Check if the container itself is a React root node.
27811
27812
        var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;
27813
        !!hasNonRootReactChild ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : void 0;
27814
      }
27815
27816
      return false;
27817
    }
27818
  },
27819
  // Temporary alias since we already shipped React 16 RC with it.
27820
  // TODO: remove in React 17.
27821
  unstable_createPortal: function () {
27822
    if (!didWarnAboutUnstableCreatePortal) {
27823
      didWarnAboutUnstableCreatePortal = true;
27824
      lowPriorityWarningWithoutStack$1(false, 'The ReactDOM.unstable_createPortal() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactDOM.createPortal() instead. It has the exact same API, ' + 'but without the "unstable_" prefix.');
27825
    }
27826
27827
    return createPortal$$1.apply(void 0, arguments);
27828
  },
27829
  unstable_batchedUpdates: batchedUpdates$1,
27830
  // TODO remove this legacy method, unstable_discreteUpdates replaces it
27831
  unstable_interactiveUpdates: function (fn, a, b, c) {
27832
    flushDiscreteUpdates();
27833
    return discreteUpdates$1(fn, a, b, c);
27834
  },
27835
  unstable_discreteUpdates: discreteUpdates$1,
27836
  unstable_flushDiscreteUpdates: flushDiscreteUpdates,
27837
  flushSync: flushSync,
27838
  unstable_createRoot: createRoot,
27839
  unstable_createSyncRoot: createSyncRoot,
27840
  unstable_flushControlled: flushControlled,
27841
  __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
27842
    // Keep in sync with ReactDOMUnstableNativeDependencies.js
27843
    // ReactTestUtils.js, and ReactTestUtilsAct.js. This is an array for better minification.
27844
    Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injection.injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch, flushPassiveEffects, IsThisRendererActing]
27845
  }
27846
};
27847
27848
function createRoot(container, options) {
27849
  var functionName = enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot';
27850
27851
  (function () {
27852
    if (!isValidContainer(container)) {
27853
      {
27854
        throw ReactError(Error(functionName + "(...): Target container is not a DOM element."));
27855
      }
27856
    }
27857
  })();
27858
27859
  warnIfReactDOMContainerInDEV(container);
27860
  return new ReactRoot(container, options);
27861
}
27862
27863
function createSyncRoot(container, options) {
27864
  var functionName = enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot';
27865
27866
  (function () {
27867
    if (!isValidContainer(container)) {
27868
      {
27869
        throw ReactError(Error(functionName + "(...): Target container is not a DOM element."));
27870
      }
27871
    }
27872
  })();
27873
27874
  warnIfReactDOMContainerInDEV(container);
27875
  return new ReactSyncRoot(container, BatchedRoot, options);
27876
}
27877
27878
function warnIfReactDOMContainerInDEV(container) {
27879
  {
27880
    !!container._reactRootContainer ? warningWithoutStack$1(false, 'You are calling ReactDOM.%s() on a container that was previously ' + 'passed to ReactDOM.render(). This is not supported.', enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot') : void 0;
27881
    container._reactHasBeenPassedToCreateRootDEV = true;
27882
  }
27883
}
27884
27885
if (enableStableConcurrentModeAPIs) {
27886
  ReactDOM.createRoot = createRoot;
27887
  ReactDOM.createSyncRoot = createSyncRoot;
27888
}
27889
27890
var foundDevTools = injectIntoDevTools({
27891
  findFiberByHostInstance: getClosestInstanceFromNode,
27892
  bundleType: 1,
27893
  version: ReactVersion,
27894
  rendererPackageName: 'react-dom'
27895
});
27896
27897
{
27898
  if (!foundDevTools && canUseDOM && window.top === window.self) {
27899
    // If we're in Chrome or Firefox, provide a download link if not installed.
27900
    if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
27901
      var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://.
27902
27903
      if (/^(https?|file):$/.test(protocol)) {
27904
        console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://fb.me/react-devtools' + (protocol === 'file:' ? '\nYou might need to use a local HTTP server (instead of file://): ' + 'https://fb.me/react-devtools-faq' : ''), 'font-weight:bold');
27905
      }
27906
    }
27907
  }
27908
}
27909
27910
27911
27912
var ReactDOM$2 = Object.freeze({
27913
	default: ReactDOM
27914
});
27915
27916
var ReactDOM$3 = ( ReactDOM$2 && ReactDOM ) || ReactDOM$2;
27917
27918
// TODO: decide on the top-level export form.
27919
// This is hacky but makes it work with both Rollup and Jest.
27920
27921
27922
var reactDom = ReactDOM$3.default || ReactDOM$3;
27923
27924
module.exports = reactDom;
27925
  })();
27926
}
27927