UNPKG

770 kBJavaScriptView Raw
1/** @license React v16.8.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(function (global, factory) {
13 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) :
14 typeof define === 'function' && define.amd ? define(['react'], factory) :
15 (global.ReactDOM = factory(global.React));
16}(this, (function (React) { 'use strict';
17
18/**
19 * Use invariant() to assert state which your program assumes to be true.
20 *
21 * Provide sprintf-style format (only %s is supported) and arguments
22 * to provide information about what broke and what you were
23 * expecting.
24 *
25 * The invariant message will be stripped in production, but the invariant
26 * will remain to ensure logic does not differ in production.
27 */
28
29var validateFormat = function () {};
30
31{
32 validateFormat = function (format) {
33 if (format === undefined) {
34 throw new Error('invariant requires an error message argument');
35 }
36 };
37}
38
39function invariant(condition, format, a, b, c, d, e, f) {
40 validateFormat(format);
41
42 if (!condition) {
43 var error = void 0;
44 if (format === undefined) {
45 error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
46 } else {
47 var args = [a, b, c, d, e, f];
48 var argIndex = 0;
49 error = new Error(format.replace(/%s/g, function () {
50 return args[argIndex++];
51 }));
52 error.name = 'Invariant Violation';
53 }
54
55 error.framesToPop = 1; // we don't care about invariant's own frame
56 throw error;
57 }
58}
59
60// Relying on the `invariant()` implementation lets us
61// preserve the format and params in the www builds.
62
63!React ? invariant(false, 'ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.') : void 0;
64
65var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {
66 var funcArgs = Array.prototype.slice.call(arguments, 3);
67 try {
68 func.apply(context, funcArgs);
69 } catch (error) {
70 this.onError(error);
71 }
72};
73
74{
75 // In DEV mode, we swap out invokeGuardedCallback for a special version
76 // that plays more nicely with the browser's DevTools. The idea is to preserve
77 // "Pause on exceptions" behavior. Because React wraps all user-provided
78 // functions in invokeGuardedCallback, and the production version of
79 // invokeGuardedCallback uses a try-catch, all user exceptions are treated
80 // like caught exceptions, and the DevTools won't pause unless the developer
81 // takes the extra step of enabling pause on caught exceptions. This is
82 // untintuitive, though, because even though React has caught the error, from
83 // the developer's perspective, the error is uncaught.
84 //
85 // To preserve the expected "Pause on exceptions" behavior, we don't use a
86 // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
87 // DOM node, and call the user-provided callback from inside an event handler
88 // for that fake event. If the callback throws, the error is "captured" using
89 // a global event handler. But because the error happens in a different
90 // event loop context, it does not interrupt the normal program flow.
91 // Effectively, this gives us try-catch behavior without actually using
92 // try-catch. Neat!
93
94 // Check that the browser supports the APIs we need to implement our special
95 // DEV version of invokeGuardedCallback
96 if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
97 var fakeNode = document.createElement('react');
98
99 var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {
100 // If document doesn't exist we know for sure we will crash in this method
101 // when we call document.createEvent(). However this can cause confusing
102 // errors: https://github.com/facebookincubator/create-react-app/issues/3482
103 // So we preemptively throw with a better message instead.
104 !(typeof document !== 'undefined') ? invariant(false, '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.') : void 0;
105 var evt = document.createEvent('Event');
106
107 // Keeps track of whether the user-provided callback threw an error. We
108 // set this to true at the beginning, then set it to false right after
109 // calling the function. If the function errors, `didError` will never be
110 // set to false. This strategy works even if the browser is flaky and
111 // fails to call our global error handler, because it doesn't rely on
112 // the error event at all.
113 var didError = true;
114
115 // Keeps track of the value of window.event so that we can reset it
116 // during the callback to let user code access window.event in the
117 // browsers that support it.
118 var windowEvent = window.event;
119
120 // Keeps track of the descriptor of window.event to restore it after event
121 // dispatching: https://github.com/facebook/react/issues/13688
122 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');
123
124 // Create an event handler for our fake event. We will synchronously
125 // dispatch our fake event using `dispatchEvent`. Inside the handler, we
126 // call the user-provided callback.
127 var funcArgs = Array.prototype.slice.call(arguments, 3);
128 function callCallback() {
129 // We immediately remove the callback from event listeners so that
130 // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
131 // nested call would trigger the fake event handlers of any call higher
132 // in the stack.
133 fakeNode.removeEventListener(evtType, callCallback, false);
134
135 // We check for window.hasOwnProperty('event') to prevent the
136 // window.event assignment in both IE <= 10 as they throw an error
137 // "Member not found" in strict mode, and in Firefox which does not
138 // support window.event.
139 if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
140 window.event = windowEvent;
141 }
142
143 func.apply(context, funcArgs);
144 didError = false;
145 }
146
147 // Create a global error event handler. We use this to capture the value
148 // that was thrown. It's possible that this error handler will fire more
149 // than once; for example, if non-React code also calls `dispatchEvent`
150 // and a handler for that event throws. We should be resilient to most of
151 // those cases. Even if our error event handler fires more than once, the
152 // last error event is always used. If the callback actually does error,
153 // we know that the last error event is the correct one, because it's not
154 // possible for anything else to have happened in between our callback
155 // erroring and the code that follows the `dispatchEvent` call below. If
156 // the callback doesn't error, but the error event was fired, we know to
157 // ignore it because `didError` will be false, as described above.
158 var error = void 0;
159 // Use this to track whether the error event is ever called.
160 var didSetError = false;
161 var isCrossOriginError = false;
162
163 function handleWindowError(event) {
164 error = event.error;
165 didSetError = true;
166 if (error === null && event.colno === 0 && event.lineno === 0) {
167 isCrossOriginError = true;
168 }
169 if (event.defaultPrevented) {
170 // Some other error handler has prevented default.
171 // Browsers silence the error report if this happens.
172 // We'll remember this to later decide whether to log it or not.
173 if (error != null && typeof error === 'object') {
174 try {
175 error._suppressLogging = true;
176 } catch (inner) {
177 // Ignore.
178 }
179 }
180 }
181 }
182
183 // Create a fake event type.
184 var evtType = 'react-' + (name ? name : 'invokeguardedcallback');
185
186 // Attach our event handlers
187 window.addEventListener('error', handleWindowError);
188 fakeNode.addEventListener(evtType, callCallback, false);
189
190 // Synchronously dispatch our fake event. If the user-provided function
191 // errors, it will trigger our global error handler.
192 evt.initEvent(evtType, false, false);
193 fakeNode.dispatchEvent(evt);
194
195 if (windowEventDescriptor) {
196 Object.defineProperty(window, 'event', windowEventDescriptor);
197 }
198
199 if (didError) {
200 if (!didSetError) {
201 // The callback errored, but the error event never fired.
202 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.');
203 } else if (isCrossOriginError) {
204 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.');
205 }
206 this.onError(error);
207 }
208
209 // Remove our event listeners
210 window.removeEventListener('error', handleWindowError);
211 };
212
213 invokeGuardedCallbackImpl = invokeGuardedCallbackDev;
214 }
215}
216
217var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
218
219// Used by Fiber to simulate a try-catch.
220var hasError = false;
221var caughtError = null;
222
223// Used by event system to capture/rethrow the first error.
224var hasRethrowError = false;
225var rethrowError = null;
226
227var reporter = {
228 onError: function (error) {
229 hasError = true;
230 caughtError = error;
231 }
232};
233
234/**
235 * Call a function while guarding against errors that happens within it.
236 * Returns an error if it throws, otherwise null.
237 *
238 * In production, this is implemented using a try-catch. The reason we don't
239 * use a try-catch directly is so that we can swap out a different
240 * implementation in DEV mode.
241 *
242 * @param {String} name of the guard to use for logging or debugging
243 * @param {Function} func The function to invoke
244 * @param {*} context The context to use when calling the function
245 * @param {...*} args Arguments for function
246 */
247function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
248 hasError = false;
249 caughtError = null;
250 invokeGuardedCallbackImpl$1.apply(reporter, arguments);
251}
252
253/**
254 * Same as invokeGuardedCallback, but instead of returning an error, it stores
255 * it in a global so it can be rethrown by `rethrowCaughtError` later.
256 * TODO: See if caughtError and rethrowError can be unified.
257 *
258 * @param {String} name of the guard to use for logging or debugging
259 * @param {Function} func The function to invoke
260 * @param {*} context The context to use when calling the function
261 * @param {...*} args Arguments for function
262 */
263function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
264 invokeGuardedCallback.apply(this, arguments);
265 if (hasError) {
266 var error = clearCaughtError();
267 if (!hasRethrowError) {
268 hasRethrowError = true;
269 rethrowError = error;
270 }
271 }
272}
273
274/**
275 * During execution of guarded functions we will capture the first error which
276 * we will rethrow to be handled by the top level error handler.
277 */
278function rethrowCaughtError() {
279 if (hasRethrowError) {
280 var error = rethrowError;
281 hasRethrowError = false;
282 rethrowError = null;
283 throw error;
284 }
285}
286
287function hasCaughtError() {
288 return hasError;
289}
290
291function clearCaughtError() {
292 if (hasError) {
293 var error = caughtError;
294 hasError = false;
295 caughtError = null;
296 return error;
297 } else {
298 invariant(false, 'clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.');
299 }
300}
301
302/**
303 * Injectable ordering of event plugins.
304 */
305var eventPluginOrder = null;
306
307/**
308 * Injectable mapping from names to event plugin modules.
309 */
310var namesToPlugins = {};
311
312/**
313 * Recomputes the plugin list using the injected plugins and plugin ordering.
314 *
315 * @private
316 */
317function recomputePluginOrdering() {
318 if (!eventPluginOrder) {
319 // Wait until an `eventPluginOrder` is injected.
320 return;
321 }
322 for (var pluginName in namesToPlugins) {
323 var pluginModule = namesToPlugins[pluginName];
324 var pluginIndex = eventPluginOrder.indexOf(pluginName);
325 !(pluginIndex > -1) ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : void 0;
326 if (plugins[pluginIndex]) {
327 continue;
328 }
329 !pluginModule.extractEvents ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : void 0;
330 plugins[pluginIndex] = pluginModule;
331 var publishedEvents = pluginModule.eventTypes;
332 for (var eventName in publishedEvents) {
333 !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : void 0;
334 }
335 }
336}
337
338/**
339 * Publishes an event so that it can be dispatched by the supplied plugin.
340 *
341 * @param {object} dispatchConfig Dispatch configuration for the event.
342 * @param {object} PluginModule Plugin publishing the event.
343 * @return {boolean} True if the event was successfully published.
344 * @private
345 */
346function publishEventForPlugin(dispatchConfig, pluginModule, eventName) {
347 !!eventNameDispatchConfigs.hasOwnProperty(eventName) ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : void 0;
348 eventNameDispatchConfigs[eventName] = dispatchConfig;
349
350 var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
351 if (phasedRegistrationNames) {
352 for (var phaseName in phasedRegistrationNames) {
353 if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
354 var phasedRegistrationName = phasedRegistrationNames[phaseName];
355 publishRegistrationName(phasedRegistrationName, pluginModule, eventName);
356 }
357 }
358 return true;
359 } else if (dispatchConfig.registrationName) {
360 publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);
361 return true;
362 }
363 return false;
364}
365
366/**
367 * Publishes a registration name that is used to identify dispatched events.
368 *
369 * @param {string} registrationName Registration name to add.
370 * @param {object} PluginModule Plugin publishing the event.
371 * @private
372 */
373function publishRegistrationName(registrationName, pluginModule, eventName) {
374 !!registrationNameModules[registrationName] ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : void 0;
375 registrationNameModules[registrationName] = pluginModule;
376 registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;
377
378 {
379 var lowerCasedName = registrationName.toLowerCase();
380 possibleRegistrationNames[lowerCasedName] = registrationName;
381
382 if (registrationName === 'onDoubleClick') {
383 possibleRegistrationNames.ondblclick = registrationName;
384 }
385 }
386}
387
388/**
389 * Registers plugins so that they can extract and dispatch events.
390 *
391 * @see {EventPluginHub}
392 */
393
394/**
395 * Ordered list of injected plugins.
396 */
397var plugins = [];
398
399/**
400 * Mapping from event name to dispatch config
401 */
402var eventNameDispatchConfigs = {};
403
404/**
405 * Mapping from registration name to plugin module
406 */
407var registrationNameModules = {};
408
409/**
410 * Mapping from registration name to event name
411 */
412var registrationNameDependencies = {};
413
414/**
415 * Mapping from lowercase registration names to the properly cased version,
416 * used to warn in the case of missing event handlers. Available
417 * only in true.
418 * @type {Object}
419 */
420var possibleRegistrationNames = {};
421// Trust the developer to only use possibleRegistrationNames in true
422
423/**
424 * Injects an ordering of plugins (by plugin name). This allows the ordering
425 * to be decoupled from injection of the actual plugins so that ordering is
426 * always deterministic regardless of packaging, on-the-fly injection, etc.
427 *
428 * @param {array} InjectedEventPluginOrder
429 * @internal
430 * @see {EventPluginHub.injection.injectEventPluginOrder}
431 */
432function injectEventPluginOrder(injectedEventPluginOrder) {
433 !!eventPluginOrder ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : void 0;
434 // Clone the ordering so it cannot be dynamically mutated.
435 eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
436 recomputePluginOrdering();
437}
438
439/**
440 * Injects plugins to be used by `EventPluginHub`. The plugin names must be
441 * in the ordering injected by `injectEventPluginOrder`.
442 *
443 * Plugins can be injected as part of page initialization or on-the-fly.
444 *
445 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
446 * @internal
447 * @see {EventPluginHub.injection.injectEventPluginsByName}
448 */
449function injectEventPluginsByName(injectedNamesToPlugins) {
450 var isOrderingDirty = false;
451 for (var pluginName in injectedNamesToPlugins) {
452 if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
453 continue;
454 }
455 var pluginModule = injectedNamesToPlugins[pluginName];
456 if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {
457 !!namesToPlugins[pluginName] ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : void 0;
458 namesToPlugins[pluginName] = pluginModule;
459 isOrderingDirty = true;
460 }
461 }
462 if (isOrderingDirty) {
463 recomputePluginOrdering();
464 }
465}
466
467/**
468 * Similar to invariant but only logs a warning if the condition is not met.
469 * This can be used to log issues in development environments in critical
470 * paths. Removing the logging code for production environments will keep the
471 * same logic and follow the same code paths.
472 */
473
474var warningWithoutStack = function () {};
475
476{
477 warningWithoutStack = function (condition, format) {
478 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
479 args[_key - 2] = arguments[_key];
480 }
481
482 if (format === undefined) {
483 throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
484 }
485 if (args.length > 8) {
486 // Check before the condition to catch violations early.
487 throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
488 }
489 if (condition) {
490 return;
491 }
492 if (typeof console !== 'undefined') {
493 var argsWithFormat = args.map(function (item) {
494 return '' + item;
495 });
496 argsWithFormat.unshift('Warning: ' + format);
497
498 // We intentionally don't use spread (or .apply) directly because it
499 // breaks IE9: https://github.com/facebook/react/issues/13610
500 Function.prototype.apply.call(console.error, console, argsWithFormat);
501 }
502 try {
503 // --- Welcome to debugging React ---
504 // This error was thrown as a convenience so that you can use this stack
505 // to find the callsite that caused this warning to fire.
506 var argIndex = 0;
507 var message = 'Warning: ' + format.replace(/%s/g, function () {
508 return args[argIndex++];
509 });
510 throw new Error(message);
511 } catch (x) {}
512 };
513}
514
515var warningWithoutStack$1 = warningWithoutStack;
516
517var getFiberCurrentPropsFromNode = null;
518var getInstanceFromNode = null;
519var getNodeFromInstance = null;
520
521function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) {
522 getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;
523 getInstanceFromNode = getInstanceFromNodeImpl;
524 getNodeFromInstance = getNodeFromInstanceImpl;
525 {
526 !(getNodeFromInstance && getInstanceFromNode) ? warningWithoutStack$1(false, 'EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0;
527 }
528}
529
530var validateEventDispatches = void 0;
531{
532 validateEventDispatches = function (event) {
533 var dispatchListeners = event._dispatchListeners;
534 var dispatchInstances = event._dispatchInstances;
535
536 var listenersIsArr = Array.isArray(dispatchListeners);
537 var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
538
539 var instancesIsArr = Array.isArray(dispatchInstances);
540 var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
541
542 !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, 'EventPluginUtils: Invalid `event`.') : void 0;
543 };
544}
545
546/**
547 * Dispatch the event to the listener.
548 * @param {SyntheticEvent} event SyntheticEvent to handle
549 * @param {function} listener Application-level callback
550 * @param {*} inst Internal component instance
551 */
552function executeDispatch(event, listener, inst) {
553 var type = event.type || 'unknown-event';
554 event.currentTarget = getNodeFromInstance(inst);
555 invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
556 event.currentTarget = null;
557}
558
559/**
560 * Standard/simple iteration through an event's collected dispatches.
561 */
562function executeDispatchesInOrder(event) {
563 var dispatchListeners = event._dispatchListeners;
564 var dispatchInstances = event._dispatchInstances;
565 {
566 validateEventDispatches(event);
567 }
568 if (Array.isArray(dispatchListeners)) {
569 for (var i = 0; i < dispatchListeners.length; i++) {
570 if (event.isPropagationStopped()) {
571 break;
572 }
573 // Listeners and Instances are two parallel arrays that are always in sync.
574 executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
575 }
576 } else if (dispatchListeners) {
577 executeDispatch(event, dispatchListeners, dispatchInstances);
578 }
579 event._dispatchListeners = null;
580 event._dispatchInstances = null;
581}
582
583/**
584 * @see executeDispatchesInOrderStopAtTrueImpl
585 */
586
587
588/**
589 * Execution of a "direct" dispatch - there must be at most one dispatch
590 * accumulated on the event or it is considered an error. It doesn't really make
591 * sense for an event with multiple dispatches (bubbled) to keep track of the
592 * return values at each dispatch execution, but it does tend to make sense when
593 * dealing with "direct" dispatches.
594 *
595 * @return {*} The return value of executing the single dispatch.
596 */
597
598
599/**
600 * @param {SyntheticEvent} event
601 * @return {boolean} True iff number of dispatches accumulated is greater than 0.
602 */
603
604/**
605 * Accumulates items that must not be null or undefined into the first one. This
606 * is used to conserve memory by avoiding array allocations, and thus sacrifices
607 * API cleanness. Since `current` can be null before being passed in and not
608 * null after this function, make sure to assign it back to `current`:
609 *
610 * `a = accumulateInto(a, b);`
611 *
612 * This API should be sparingly used. Try `accumulate` for something cleaner.
613 *
614 * @return {*|array<*>} An accumulation of items.
615 */
616
617function accumulateInto(current, next) {
618 !(next != null) ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : void 0;
619
620 if (current == null) {
621 return next;
622 }
623
624 // Both are not empty. Warning: Never call x.concat(y) when you are not
625 // certain that x is an Array (x could be a string with concat method).
626 if (Array.isArray(current)) {
627 if (Array.isArray(next)) {
628 current.push.apply(current, next);
629 return current;
630 }
631 current.push(next);
632 return current;
633 }
634
635 if (Array.isArray(next)) {
636 // A bit too dangerous to mutate `next`.
637 return [current].concat(next);
638 }
639
640 return [current, next];
641}
642
643/**
644 * @param {array} arr an "accumulation" of items which is either an Array or
645 * a single item. Useful when paired with the `accumulate` module. This is a
646 * simple utility that allows us to reason about a collection of items, but
647 * handling the case when there is exactly one item (and we do not need to
648 * allocate an array).
649 * @param {function} cb Callback invoked with each element or a collection.
650 * @param {?} [scope] Scope used as `this` in a callback.
651 */
652function forEachAccumulated(arr, cb, scope) {
653 if (Array.isArray(arr)) {
654 arr.forEach(cb, scope);
655 } else if (arr) {
656 cb.call(scope, arr);
657 }
658}
659
660/**
661 * Internal queue of events that have accumulated their dispatches and are
662 * waiting to have their dispatches executed.
663 */
664var eventQueue = null;
665
666/**
667 * Dispatches an event and releases it back into the pool, unless persistent.
668 *
669 * @param {?object} event Synthetic event to be dispatched.
670 * @private
671 */
672var executeDispatchesAndRelease = function (event) {
673 if (event) {
674 executeDispatchesInOrder(event);
675
676 if (!event.isPersistent()) {
677 event.constructor.release(event);
678 }
679 }
680};
681var executeDispatchesAndReleaseTopLevel = function (e) {
682 return executeDispatchesAndRelease(e);
683};
684
685function isInteractive(tag) {
686 return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
687}
688
689function shouldPreventMouseEvent(name, type, props) {
690 switch (name) {
691 case 'onClick':
692 case 'onClickCapture':
693 case 'onDoubleClick':
694 case 'onDoubleClickCapture':
695 case 'onMouseDown':
696 case 'onMouseDownCapture':
697 case 'onMouseMove':
698 case 'onMouseMoveCapture':
699 case 'onMouseUp':
700 case 'onMouseUpCapture':
701 return !!(props.disabled && isInteractive(type));
702 default:
703 return false;
704 }
705}
706
707/**
708 * This is a unified interface for event plugins to be installed and configured.
709 *
710 * Event plugins can implement the following properties:
711 *
712 * `extractEvents` {function(string, DOMEventTarget, string, object): *}
713 * Required. When a top-level event is fired, this method is expected to
714 * extract synthetic events that will in turn be queued and dispatched.
715 *
716 * `eventTypes` {object}
717 * Optional, plugins that fire events must publish a mapping of registration
718 * names that are used to register listeners. Values of this mapping must
719 * be objects that contain `registrationName` or `phasedRegistrationNames`.
720 *
721 * `executeDispatch` {function(object, function, string)}
722 * Optional, allows plugins to override how an event gets dispatched. By
723 * default, the listener is simply invoked.
724 *
725 * Each plugin that is injected into `EventsPluginHub` is immediately operable.
726 *
727 * @public
728 */
729
730/**
731 * Methods for injecting dependencies.
732 */
733var injection = {
734 /**
735 * @param {array} InjectedEventPluginOrder
736 * @public
737 */
738 injectEventPluginOrder: injectEventPluginOrder,
739
740 /**
741 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
742 */
743 injectEventPluginsByName: injectEventPluginsByName
744};
745
746/**
747 * @param {object} inst The instance, which is the source of events.
748 * @param {string} registrationName Name of listener (e.g. `onClick`).
749 * @return {?function} The stored callback.
750 */
751function getListener(inst, registrationName) {
752 var listener = void 0;
753
754 // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
755 // live here; needs to be moved to a better place soon
756 var stateNode = inst.stateNode;
757 if (!stateNode) {
758 // Work in progress (ex: onload events in incremental mode).
759 return null;
760 }
761 var props = getFiberCurrentPropsFromNode(stateNode);
762 if (!props) {
763 // Work in progress.
764 return null;
765 }
766 listener = props[registrationName];
767 if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
768 return null;
769 }
770 !(!listener || typeof listener === 'function') ? invariant(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener) : void 0;
771 return listener;
772}
773
774/**
775 * Allows registered plugins an opportunity to extract events from top-level
776 * native browser events.
777 *
778 * @return {*} An accumulation of synthetic events.
779 * @internal
780 */
781function extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
782 var events = null;
783 for (var i = 0; i < plugins.length; i++) {
784 // Not every plugin in the ordering may be loaded at runtime.
785 var possiblePlugin = plugins[i];
786 if (possiblePlugin) {
787 var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
788 if (extractedEvents) {
789 events = accumulateInto(events, extractedEvents);
790 }
791 }
792 }
793 return events;
794}
795
796function runEventsInBatch(events) {
797 if (events !== null) {
798 eventQueue = accumulateInto(eventQueue, events);
799 }
800
801 // Set `eventQueue` to null before processing it so that we can tell if more
802 // events get enqueued while processing.
803 var processingEventQueue = eventQueue;
804 eventQueue = null;
805
806 if (!processingEventQueue) {
807 return;
808 }
809
810 forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
811 !!eventQueue ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : void 0;
812 // This would be a good time to rethrow if any of the event handlers threw.
813 rethrowCaughtError();
814}
815
816function runExtractedEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
817 var events = extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
818 runEventsInBatch(events);
819}
820
821var FunctionComponent = 0;
822var ClassComponent = 1;
823var IndeterminateComponent = 2; // Before we know whether it is function or class
824var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
825var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
826var HostComponent = 5;
827var HostText = 6;
828var Fragment = 7;
829var Mode = 8;
830var ContextConsumer = 9;
831var ContextProvider = 10;
832var ForwardRef = 11;
833var Profiler = 12;
834var SuspenseComponent = 13;
835var MemoComponent = 14;
836var SimpleMemoComponent = 15;
837var LazyComponent = 16;
838var IncompleteClassComponent = 17;
839
840var randomKey = Math.random().toString(36).slice(2);
841var internalInstanceKey = '__reactInternalInstance$' + randomKey;
842var internalEventHandlersKey = '__reactEventHandlers$' + randomKey;
843
844function precacheFiberNode(hostInst, node) {
845 node[internalInstanceKey] = hostInst;
846}
847
848/**
849 * Given a DOM node, return the closest ReactDOMComponent or
850 * ReactDOMTextComponent instance ancestor.
851 */
852function getClosestInstanceFromNode(node) {
853 if (node[internalInstanceKey]) {
854 return node[internalInstanceKey];
855 }
856
857 while (!node[internalInstanceKey]) {
858 if (node.parentNode) {
859 node = node.parentNode;
860 } else {
861 // Top of the tree. This node must not be part of a React tree (or is
862 // unmounted, potentially).
863 return null;
864 }
865 }
866
867 var inst = node[internalInstanceKey];
868 if (inst.tag === HostComponent || inst.tag === HostText) {
869 // In Fiber, this will always be the deepest root.
870 return inst;
871 }
872
873 return null;
874}
875
876/**
877 * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
878 * instance, or null if the node was not rendered by this React.
879 */
880function getInstanceFromNode$1(node) {
881 var inst = node[internalInstanceKey];
882 if (inst) {
883 if (inst.tag === HostComponent || inst.tag === HostText) {
884 return inst;
885 } else {
886 return null;
887 }
888 }
889 return null;
890}
891
892/**
893 * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
894 * DOM node.
895 */
896function getNodeFromInstance$1(inst) {
897 if (inst.tag === HostComponent || inst.tag === HostText) {
898 // In Fiber this, is just the state node right now. We assume it will be
899 // a host component or host text.
900 return inst.stateNode;
901 }
902
903 // Without this first invariant, passing a non-DOM-component triggers the next
904 // invariant for a missing parent, which is super confusing.
905 invariant(false, 'getNodeFromInstance: Invalid argument.');
906}
907
908function getFiberCurrentPropsFromNode$1(node) {
909 return node[internalEventHandlersKey] || null;
910}
911
912function updateFiberProps(node, props) {
913 node[internalEventHandlersKey] = props;
914}
915
916function getParent(inst) {
917 do {
918 inst = inst.return;
919 // TODO: If this is a HostRoot we might want to bail out.
920 // That is depending on if we want nested subtrees (layers) to bubble
921 // events to their parent. We could also go through parentNode on the
922 // host node but that wouldn't work for React Native and doesn't let us
923 // do the portal feature.
924 } while (inst && inst.tag !== HostComponent);
925 if (inst) {
926 return inst;
927 }
928 return null;
929}
930
931/**
932 * Return the lowest common ancestor of A and B, or null if they are in
933 * different trees.
934 */
935function getLowestCommonAncestor(instA, instB) {
936 var depthA = 0;
937 for (var tempA = instA; tempA; tempA = getParent(tempA)) {
938 depthA++;
939 }
940 var depthB = 0;
941 for (var tempB = instB; tempB; tempB = getParent(tempB)) {
942 depthB++;
943 }
944
945 // If A is deeper, crawl up.
946 while (depthA - depthB > 0) {
947 instA = getParent(instA);
948 depthA--;
949 }
950
951 // If B is deeper, crawl up.
952 while (depthB - depthA > 0) {
953 instB = getParent(instB);
954 depthB--;
955 }
956
957 // Walk in lockstep until we find a match.
958 var depth = depthA;
959 while (depth--) {
960 if (instA === instB || instA === instB.alternate) {
961 return instA;
962 }
963 instA = getParent(instA);
964 instB = getParent(instB);
965 }
966 return null;
967}
968
969/**
970 * Return if A is an ancestor of B.
971 */
972
973
974/**
975 * Return the parent instance of the passed-in instance.
976 */
977
978
979/**
980 * Simulates the traversal of a two-phase, capture/bubble event dispatch.
981 */
982function traverseTwoPhase(inst, fn, arg) {
983 var path = [];
984 while (inst) {
985 path.push(inst);
986 inst = getParent(inst);
987 }
988 var i = void 0;
989 for (i = path.length; i-- > 0;) {
990 fn(path[i], 'captured', arg);
991 }
992 for (i = 0; i < path.length; i++) {
993 fn(path[i], 'bubbled', arg);
994 }
995}
996
997/**
998 * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
999 * should would receive a `mouseEnter` or `mouseLeave` event.
1000 *
1001 * Does not invoke the callback on the nearest common ancestor because nothing
1002 * "entered" or "left" that element.
1003 */
1004function traverseEnterLeave(from, to, fn, argFrom, argTo) {
1005 var common = from && to ? getLowestCommonAncestor(from, to) : null;
1006 var pathFrom = [];
1007 while (true) {
1008 if (!from) {
1009 break;
1010 }
1011 if (from === common) {
1012 break;
1013 }
1014 var alternate = from.alternate;
1015 if (alternate !== null && alternate === common) {
1016 break;
1017 }
1018 pathFrom.push(from);
1019 from = getParent(from);
1020 }
1021 var pathTo = [];
1022 while (true) {
1023 if (!to) {
1024 break;
1025 }
1026 if (to === common) {
1027 break;
1028 }
1029 var _alternate = to.alternate;
1030 if (_alternate !== null && _alternate === common) {
1031 break;
1032 }
1033 pathTo.push(to);
1034 to = getParent(to);
1035 }
1036 for (var i = 0; i < pathFrom.length; i++) {
1037 fn(pathFrom[i], 'bubbled', argFrom);
1038 }
1039 for (var _i = pathTo.length; _i-- > 0;) {
1040 fn(pathTo[_i], 'captured', argTo);
1041 }
1042}
1043
1044/**
1045 * Some event types have a notion of different registration names for different
1046 * "phases" of propagation. This finds listeners by a given phase.
1047 */
1048function listenerAtPhase(inst, event, propagationPhase) {
1049 var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
1050 return getListener(inst, registrationName);
1051}
1052
1053/**
1054 * A small set of propagation patterns, each of which will accept a small amount
1055 * of information, and generate a set of "dispatch ready event objects" - which
1056 * are sets of events that have already been annotated with a set of dispatched
1057 * listener functions/ids. The API is designed this way to discourage these
1058 * propagation strategies from actually executing the dispatches, since we
1059 * always want to collect the entire set of dispatches before executing even a
1060 * single one.
1061 */
1062
1063/**
1064 * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
1065 * here, allows us to not have to bind or create functions for each event.
1066 * Mutating the event's members allows us to not have to create a wrapping
1067 * "dispatch" object that pairs the event with the listener.
1068 */
1069function accumulateDirectionalDispatches(inst, phase, event) {
1070 {
1071 !inst ? warningWithoutStack$1(false, 'Dispatching inst must not be null') : void 0;
1072 }
1073 var listener = listenerAtPhase(inst, event, phase);
1074 if (listener) {
1075 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
1076 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
1077 }
1078}
1079
1080/**
1081 * Collect dispatches (must be entirely collected before dispatching - see unit
1082 * tests). Lazily allocate the array to conserve memory. We must loop through
1083 * each event and perform the traversal for each one. We cannot perform a
1084 * single traversal for the entire collection of events because each event may
1085 * have a different target.
1086 */
1087function accumulateTwoPhaseDispatchesSingle(event) {
1088 if (event && event.dispatchConfig.phasedRegistrationNames) {
1089 traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
1090 }
1091}
1092
1093/**
1094 * Accumulates without regard to direction, does not look for phased
1095 * registration names. Same as `accumulateDirectDispatchesSingle` but without
1096 * requiring that the `dispatchMarker` be the same as the dispatched ID.
1097 */
1098function accumulateDispatches(inst, ignoredDirection, event) {
1099 if (inst && event && event.dispatchConfig.registrationName) {
1100 var registrationName = event.dispatchConfig.registrationName;
1101 var listener = getListener(inst, registrationName);
1102 if (listener) {
1103 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
1104 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
1105 }
1106 }
1107}
1108
1109/**
1110 * Accumulates dispatches on an `SyntheticEvent`, but only for the
1111 * `dispatchMarker`.
1112 * @param {SyntheticEvent} event
1113 */
1114function accumulateDirectDispatchesSingle(event) {
1115 if (event && event.dispatchConfig.registrationName) {
1116 accumulateDispatches(event._targetInst, null, event);
1117 }
1118}
1119
1120function accumulateTwoPhaseDispatches(events) {
1121 forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
1122}
1123
1124
1125
1126function accumulateEnterLeaveDispatches(leave, enter, from, to) {
1127 traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
1128}
1129
1130function accumulateDirectDispatches(events) {
1131 forEachAccumulated(events, accumulateDirectDispatchesSingle);
1132}
1133
1134var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
1135
1136// Do not uses the below two methods directly!
1137// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.
1138// (It is the only module that is allowed to access these methods.)
1139
1140function unsafeCastStringToDOMTopLevelType(topLevelType) {
1141 return topLevelType;
1142}
1143
1144function unsafeCastDOMTopLevelTypeToString(topLevelType) {
1145 return topLevelType;
1146}
1147
1148/**
1149 * Generate a mapping of standard vendor prefixes using the defined style property and event name.
1150 *
1151 * @param {string} styleProp
1152 * @param {string} eventName
1153 * @returns {object}
1154 */
1155function makePrefixMap(styleProp, eventName) {
1156 var prefixes = {};
1157
1158 prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
1159 prefixes['Webkit' + styleProp] = 'webkit' + eventName;
1160 prefixes['Moz' + styleProp] = 'moz' + eventName;
1161
1162 return prefixes;
1163}
1164
1165/**
1166 * A list of event names to a configurable list of vendor prefixes.
1167 */
1168var vendorPrefixes = {
1169 animationend: makePrefixMap('Animation', 'AnimationEnd'),
1170 animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
1171 animationstart: makePrefixMap('Animation', 'AnimationStart'),
1172 transitionend: makePrefixMap('Transition', 'TransitionEnd')
1173};
1174
1175/**
1176 * Event names that have already been detected and prefixed (if applicable).
1177 */
1178var prefixedEventNames = {};
1179
1180/**
1181 * Element to check for prefixes on.
1182 */
1183var style = {};
1184
1185/**
1186 * Bootstrap if a DOM exists.
1187 */
1188if (canUseDOM) {
1189 style = document.createElement('div').style;
1190
1191 // On some platforms, in particular some releases of Android 4.x,
1192 // the un-prefixed "animation" and "transition" properties are defined on the
1193 // style object but the events that fire will still be prefixed, so we need
1194 // to check if the un-prefixed events are usable, and if not remove them from the map.
1195 if (!('AnimationEvent' in window)) {
1196 delete vendorPrefixes.animationend.animation;
1197 delete vendorPrefixes.animationiteration.animation;
1198 delete vendorPrefixes.animationstart.animation;
1199 }
1200
1201 // Same as above
1202 if (!('TransitionEvent' in window)) {
1203 delete vendorPrefixes.transitionend.transition;
1204 }
1205}
1206
1207/**
1208 * Attempts to determine the correct vendor prefixed event name.
1209 *
1210 * @param {string} eventName
1211 * @returns {string}
1212 */
1213function getVendorPrefixedEventName(eventName) {
1214 if (prefixedEventNames[eventName]) {
1215 return prefixedEventNames[eventName];
1216 } else if (!vendorPrefixes[eventName]) {
1217 return eventName;
1218 }
1219
1220 var prefixMap = vendorPrefixes[eventName];
1221
1222 for (var styleProp in prefixMap) {
1223 if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
1224 return prefixedEventNames[eventName] = prefixMap[styleProp];
1225 }
1226 }
1227
1228 return eventName;
1229}
1230
1231/**
1232 * To identify top level events in ReactDOM, we use constants defined by this
1233 * module. This is the only module that uses the unsafe* methods to express
1234 * that the constants actually correspond to the browser event names. This lets
1235 * us save some bundle size by avoiding a top level type -> event name map.
1236 * The rest of ReactDOM code should import top level types from this file.
1237 */
1238var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
1239var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
1240var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));
1241var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
1242var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
1243var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
1244var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
1245var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
1246var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
1247var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
1248var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
1249var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
1250var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');
1251var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');
1252var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
1253var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
1254var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
1255var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
1256var TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick');
1257var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
1258var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
1259var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
1260var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
1261var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
1262var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
1263var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
1264var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
1265var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
1266var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
1267var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
1268var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
1269var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
1270var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
1271var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture');
1272var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
1273var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid');
1274var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
1275var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
1276var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
1277var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
1278var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
1279var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
1280var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
1281var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture');
1282var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
1283var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
1284var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
1285var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
1286var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
1287var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
1288var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
1289var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
1290var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
1291var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel');
1292var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown');
1293
1294
1295var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove');
1296var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout');
1297var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover');
1298var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup');
1299var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
1300var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
1301var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset');
1302var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
1303var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
1304var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
1305var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
1306var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
1307var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit');
1308var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
1309var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
1310var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
1311var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
1312var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
1313var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
1314var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
1315var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
1316var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
1317var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
1318var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
1319var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel');
1320
1321// List of events that need to be individually attached to media elements.
1322// Note that events in this list will *not* be listened to at the top level
1323// unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.
1324var 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];
1325
1326function getRawEventName(topLevelType) {
1327 return unsafeCastDOMTopLevelTypeToString(topLevelType);
1328}
1329
1330/**
1331 * These variables store information about text content of a target node,
1332 * allowing comparison of content before and after a given event.
1333 *
1334 * Identify the node where selection currently begins, then observe
1335 * both its text content and its current position in the DOM. Since the
1336 * browser may natively replace the target node during composition, we can
1337 * use its position to find its replacement.
1338 *
1339 *
1340 */
1341
1342var root = null;
1343var startText = null;
1344var fallbackText = null;
1345
1346function initialize(nativeEventTarget) {
1347 root = nativeEventTarget;
1348 startText = getText();
1349 return true;
1350}
1351
1352function reset() {
1353 root = null;
1354 startText = null;
1355 fallbackText = null;
1356}
1357
1358function getData() {
1359 if (fallbackText) {
1360 return fallbackText;
1361 }
1362
1363 var start = void 0;
1364 var startValue = startText;
1365 var startLength = startValue.length;
1366 var end = void 0;
1367 var endValue = getText();
1368 var endLength = endValue.length;
1369
1370 for (start = 0; start < startLength; start++) {
1371 if (startValue[start] !== endValue[start]) {
1372 break;
1373 }
1374 }
1375
1376 var minEnd = startLength - start;
1377 for (end = 1; end <= minEnd; end++) {
1378 if (startValue[startLength - end] !== endValue[endLength - end]) {
1379 break;
1380 }
1381 }
1382
1383 var sliceTail = end > 1 ? 1 - end : undefined;
1384 fallbackText = endValue.slice(start, sliceTail);
1385 return fallbackText;
1386}
1387
1388function getText() {
1389 if ('value' in root) {
1390 return root.value;
1391 }
1392 return root.textContent;
1393}
1394
1395var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1396
1397var _assign = ReactInternals.assign;
1398
1399/* eslint valid-typeof: 0 */
1400
1401var EVENT_POOL_SIZE = 10;
1402
1403/**
1404 * @interface Event
1405 * @see http://www.w3.org/TR/DOM-Level-3-Events/
1406 */
1407var EventInterface = {
1408 type: null,
1409 target: null,
1410 // currentTarget is set when dispatching; no use in copying it here
1411 currentTarget: function () {
1412 return null;
1413 },
1414 eventPhase: null,
1415 bubbles: null,
1416 cancelable: null,
1417 timeStamp: function (event) {
1418 return event.timeStamp || Date.now();
1419 },
1420 defaultPrevented: null,
1421 isTrusted: null
1422};
1423
1424function functionThatReturnsTrue() {
1425 return true;
1426}
1427
1428function functionThatReturnsFalse() {
1429 return false;
1430}
1431
1432/**
1433 * Synthetic events are dispatched by event plugins, typically in response to a
1434 * top-level event delegation handler.
1435 *
1436 * These systems should generally use pooling to reduce the frequency of garbage
1437 * collection. The system should check `isPersistent` to determine whether the
1438 * event should be released into the pool after being dispatched. Users that
1439 * need a persisted event should invoke `persist`.
1440 *
1441 * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
1442 * normalizing browser quirks. Subclasses do not necessarily have to implement a
1443 * DOM interface; custom application-specific events can also subclass this.
1444 *
1445 * @param {object} dispatchConfig Configuration used to dispatch this event.
1446 * @param {*} targetInst Marker identifying the event target.
1447 * @param {object} nativeEvent Native browser event.
1448 * @param {DOMEventTarget} nativeEventTarget Target node.
1449 */
1450function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
1451 {
1452 // these have a getter/setter for warnings
1453 delete this.nativeEvent;
1454 delete this.preventDefault;
1455 delete this.stopPropagation;
1456 delete this.isDefaultPrevented;
1457 delete this.isPropagationStopped;
1458 }
1459
1460 this.dispatchConfig = dispatchConfig;
1461 this._targetInst = targetInst;
1462 this.nativeEvent = nativeEvent;
1463
1464 var Interface = this.constructor.Interface;
1465 for (var propName in Interface) {
1466 if (!Interface.hasOwnProperty(propName)) {
1467 continue;
1468 }
1469 {
1470 delete this[propName]; // this has a getter/setter for warnings
1471 }
1472 var normalize = Interface[propName];
1473 if (normalize) {
1474 this[propName] = normalize(nativeEvent);
1475 } else {
1476 if (propName === 'target') {
1477 this.target = nativeEventTarget;
1478 } else {
1479 this[propName] = nativeEvent[propName];
1480 }
1481 }
1482 }
1483
1484 var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
1485 if (defaultPrevented) {
1486 this.isDefaultPrevented = functionThatReturnsTrue;
1487 } else {
1488 this.isDefaultPrevented = functionThatReturnsFalse;
1489 }
1490 this.isPropagationStopped = functionThatReturnsFalse;
1491 return this;
1492}
1493
1494_assign(SyntheticEvent.prototype, {
1495 preventDefault: function () {
1496 this.defaultPrevented = true;
1497 var event = this.nativeEvent;
1498 if (!event) {
1499 return;
1500 }
1501
1502 if (event.preventDefault) {
1503 event.preventDefault();
1504 } else if (typeof event.returnValue !== 'unknown') {
1505 event.returnValue = false;
1506 }
1507 this.isDefaultPrevented = functionThatReturnsTrue;
1508 },
1509
1510 stopPropagation: function () {
1511 var event = this.nativeEvent;
1512 if (!event) {
1513 return;
1514 }
1515
1516 if (event.stopPropagation) {
1517 event.stopPropagation();
1518 } else if (typeof event.cancelBubble !== 'unknown') {
1519 // The ChangeEventPlugin registers a "propertychange" event for
1520 // IE. This event does not support bubbling or cancelling, and
1521 // any references to cancelBubble throw "Member not found". A
1522 // typeof check of "unknown" circumvents this issue (and is also
1523 // IE specific).
1524 event.cancelBubble = true;
1525 }
1526
1527 this.isPropagationStopped = functionThatReturnsTrue;
1528 },
1529
1530 /**
1531 * We release all dispatched `SyntheticEvent`s after each event loop, adding
1532 * them back into the pool. This allows a way to hold onto a reference that
1533 * won't be added back into the pool.
1534 */
1535 persist: function () {
1536 this.isPersistent = functionThatReturnsTrue;
1537 },
1538
1539 /**
1540 * Checks if this event should be released back into the pool.
1541 *
1542 * @return {boolean} True if this should not be released, false otherwise.
1543 */
1544 isPersistent: functionThatReturnsFalse,
1545
1546 /**
1547 * `PooledClass` looks for `destructor` on each instance it releases.
1548 */
1549 destructor: function () {
1550 var Interface = this.constructor.Interface;
1551 for (var propName in Interface) {
1552 {
1553 Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
1554 }
1555 }
1556 this.dispatchConfig = null;
1557 this._targetInst = null;
1558 this.nativeEvent = null;
1559 this.isDefaultPrevented = functionThatReturnsFalse;
1560 this.isPropagationStopped = functionThatReturnsFalse;
1561 this._dispatchListeners = null;
1562 this._dispatchInstances = null;
1563 {
1564 Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
1565 Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
1566 Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
1567 Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
1568 Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
1569 }
1570 }
1571});
1572
1573SyntheticEvent.Interface = EventInterface;
1574
1575/**
1576 * Helper to reduce boilerplate when creating subclasses.
1577 */
1578SyntheticEvent.extend = function (Interface) {
1579 var Super = this;
1580
1581 var E = function () {};
1582 E.prototype = Super.prototype;
1583 var prototype = new E();
1584
1585 function Class() {
1586 return Super.apply(this, arguments);
1587 }
1588 _assign(prototype, Class.prototype);
1589 Class.prototype = prototype;
1590 Class.prototype.constructor = Class;
1591
1592 Class.Interface = _assign({}, Super.Interface, Interface);
1593 Class.extend = Super.extend;
1594 addEventPoolingTo(Class);
1595
1596 return Class;
1597};
1598
1599addEventPoolingTo(SyntheticEvent);
1600
1601/**
1602 * Helper to nullify syntheticEvent instance properties when destructing
1603 *
1604 * @param {String} propName
1605 * @param {?object} getVal
1606 * @return {object} defineProperty object
1607 */
1608function getPooledWarningPropertyDefinition(propName, getVal) {
1609 var isFunction = typeof getVal === 'function';
1610 return {
1611 configurable: true,
1612 set: set,
1613 get: get
1614 };
1615
1616 function set(val) {
1617 var action = isFunction ? 'setting the method' : 'setting the property';
1618 warn(action, 'This is effectively a no-op');
1619 return val;
1620 }
1621
1622 function get() {
1623 var action = isFunction ? 'accessing the method' : 'accessing the property';
1624 var result = isFunction ? 'This is a no-op function' : 'This is set to null';
1625 warn(action, result);
1626 return getVal;
1627 }
1628
1629 function warn(action, result) {
1630 var warningCondition = false;
1631 !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;
1632 }
1633}
1634
1635function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
1636 var EventConstructor = this;
1637 if (EventConstructor.eventPool.length) {
1638 var instance = EventConstructor.eventPool.pop();
1639 EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
1640 return instance;
1641 }
1642 return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
1643}
1644
1645function releasePooledEvent(event) {
1646 var EventConstructor = this;
1647 !(event instanceof EventConstructor) ? invariant(false, 'Trying to release an event instance into a pool of a different type.') : void 0;
1648 event.destructor();
1649 if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
1650 EventConstructor.eventPool.push(event);
1651 }
1652}
1653
1654function addEventPoolingTo(EventConstructor) {
1655 EventConstructor.eventPool = [];
1656 EventConstructor.getPooled = getPooledEvent;
1657 EventConstructor.release = releasePooledEvent;
1658}
1659
1660/**
1661 * @interface Event
1662 * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
1663 */
1664var SyntheticCompositionEvent = SyntheticEvent.extend({
1665 data: null
1666});
1667
1668/**
1669 * @interface Event
1670 * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
1671 * /#events-inputevents
1672 */
1673var SyntheticInputEvent = SyntheticEvent.extend({
1674 data: null
1675});
1676
1677var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
1678var START_KEYCODE = 229;
1679
1680var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
1681
1682var documentMode = null;
1683if (canUseDOM && 'documentMode' in document) {
1684 documentMode = document.documentMode;
1685}
1686
1687// Webkit offers a very useful `textInput` event that can be used to
1688// directly represent `beforeInput`. The IE `textinput` event is not as
1689// useful, so we don't use it.
1690var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode;
1691
1692// In IE9+, we have access to composition events, but the data supplied
1693// by the native compositionend event may be incorrect. Japanese ideographic
1694// spaces, for instance (\u3000) are not recorded correctly.
1695var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
1696
1697var SPACEBAR_CODE = 32;
1698var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
1699
1700// Events and their corresponding property names.
1701var eventTypes = {
1702 beforeInput: {
1703 phasedRegistrationNames: {
1704 bubbled: 'onBeforeInput',
1705 captured: 'onBeforeInputCapture'
1706 },
1707 dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]
1708 },
1709 compositionEnd: {
1710 phasedRegistrationNames: {
1711 bubbled: 'onCompositionEnd',
1712 captured: 'onCompositionEndCapture'
1713 },
1714 dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
1715 },
1716 compositionStart: {
1717 phasedRegistrationNames: {
1718 bubbled: 'onCompositionStart',
1719 captured: 'onCompositionStartCapture'
1720 },
1721 dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
1722 },
1723 compositionUpdate: {
1724 phasedRegistrationNames: {
1725 bubbled: 'onCompositionUpdate',
1726 captured: 'onCompositionUpdateCapture'
1727 },
1728 dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
1729 }
1730};
1731
1732// Track whether we've ever handled a keypress on the space key.
1733var hasSpaceKeypress = false;
1734
1735/**
1736 * Return whether a native keypress event is assumed to be a command.
1737 * This is required because Firefox fires `keypress` events for key commands
1738 * (cut, copy, select-all, etc.) even though no character is inserted.
1739 */
1740function isKeypressCommand(nativeEvent) {
1741 return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
1742 // ctrlKey && altKey is equivalent to AltGr, and is not a command.
1743 !(nativeEvent.ctrlKey && nativeEvent.altKey);
1744}
1745
1746/**
1747 * Translate native top level events into event types.
1748 *
1749 * @param {string} topLevelType
1750 * @return {object}
1751 */
1752function getCompositionEventType(topLevelType) {
1753 switch (topLevelType) {
1754 case TOP_COMPOSITION_START:
1755 return eventTypes.compositionStart;
1756 case TOP_COMPOSITION_END:
1757 return eventTypes.compositionEnd;
1758 case TOP_COMPOSITION_UPDATE:
1759 return eventTypes.compositionUpdate;
1760 }
1761}
1762
1763/**
1764 * Does our fallback best-guess model think this event signifies that
1765 * composition has begun?
1766 *
1767 * @param {string} topLevelType
1768 * @param {object} nativeEvent
1769 * @return {boolean}
1770 */
1771function isFallbackCompositionStart(topLevelType, nativeEvent) {
1772 return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;
1773}
1774
1775/**
1776 * Does our fallback mode think that this event is the end of composition?
1777 *
1778 * @param {string} topLevelType
1779 * @param {object} nativeEvent
1780 * @return {boolean}
1781 */
1782function isFallbackCompositionEnd(topLevelType, nativeEvent) {
1783 switch (topLevelType) {
1784 case TOP_KEY_UP:
1785 // Command keys insert or clear IME input.
1786 return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
1787 case TOP_KEY_DOWN:
1788 // Expect IME keyCode on each keydown. If we get any other
1789 // code we must have exited earlier.
1790 return nativeEvent.keyCode !== START_KEYCODE;
1791 case TOP_KEY_PRESS:
1792 case TOP_MOUSE_DOWN:
1793 case TOP_BLUR:
1794 // Events are not possible without cancelling IME.
1795 return true;
1796 default:
1797 return false;
1798 }
1799}
1800
1801/**
1802 * Google Input Tools provides composition data via a CustomEvent,
1803 * with the `data` property populated in the `detail` object. If this
1804 * is available on the event object, use it. If not, this is a plain
1805 * composition event and we have nothing special to extract.
1806 *
1807 * @param {object} nativeEvent
1808 * @return {?string}
1809 */
1810function getDataFromCustomEvent(nativeEvent) {
1811 var detail = nativeEvent.detail;
1812 if (typeof detail === 'object' && 'data' in detail) {
1813 return detail.data;
1814 }
1815 return null;
1816}
1817
1818/**
1819 * Check if a composition event was triggered by Korean IME.
1820 * Our fallback mode does not work well with IE's Korean IME,
1821 * so just use native composition events when Korean IME is used.
1822 * Although CompositionEvent.locale property is deprecated,
1823 * it is available in IE, where our fallback mode is enabled.
1824 *
1825 * @param {object} nativeEvent
1826 * @return {boolean}
1827 */
1828function isUsingKoreanIME(nativeEvent) {
1829 return nativeEvent.locale === 'ko';
1830}
1831
1832// Track the current IME composition status, if any.
1833var isComposing = false;
1834
1835/**
1836 * @return {?object} A SyntheticCompositionEvent.
1837 */
1838function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
1839 var eventType = void 0;
1840 var fallbackData = void 0;
1841
1842 if (canUseCompositionEvent) {
1843 eventType = getCompositionEventType(topLevelType);
1844 } else if (!isComposing) {
1845 if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
1846 eventType = eventTypes.compositionStart;
1847 }
1848 } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
1849 eventType = eventTypes.compositionEnd;
1850 }
1851
1852 if (!eventType) {
1853 return null;
1854 }
1855
1856 if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
1857 // The current composition is stored statically and must not be
1858 // overwritten while composition continues.
1859 if (!isComposing && eventType === eventTypes.compositionStart) {
1860 isComposing = initialize(nativeEventTarget);
1861 } else if (eventType === eventTypes.compositionEnd) {
1862 if (isComposing) {
1863 fallbackData = getData();
1864 }
1865 }
1866 }
1867
1868 var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
1869
1870 if (fallbackData) {
1871 // Inject data generated from fallback path into the synthetic event.
1872 // This matches the property of native CompositionEventInterface.
1873 event.data = fallbackData;
1874 } else {
1875 var customData = getDataFromCustomEvent(nativeEvent);
1876 if (customData !== null) {
1877 event.data = customData;
1878 }
1879 }
1880
1881 accumulateTwoPhaseDispatches(event);
1882 return event;
1883}
1884
1885/**
1886 * @param {TopLevelType} topLevelType Number from `TopLevelType`.
1887 * @param {object} nativeEvent Native browser event.
1888 * @return {?string} The string corresponding to this `beforeInput` event.
1889 */
1890function getNativeBeforeInputChars(topLevelType, nativeEvent) {
1891 switch (topLevelType) {
1892 case TOP_COMPOSITION_END:
1893 return getDataFromCustomEvent(nativeEvent);
1894 case TOP_KEY_PRESS:
1895 /**
1896 * If native `textInput` events are available, our goal is to make
1897 * use of them. However, there is a special case: the spacebar key.
1898 * In Webkit, preventing default on a spacebar `textInput` event
1899 * cancels character insertion, but it *also* causes the browser
1900 * to fall back to its default spacebar behavior of scrolling the
1901 * page.
1902 *
1903 * Tracking at:
1904 * https://code.google.com/p/chromium/issues/detail?id=355103
1905 *
1906 * To avoid this issue, use the keypress event as if no `textInput`
1907 * event is available.
1908 */
1909 var which = nativeEvent.which;
1910 if (which !== SPACEBAR_CODE) {
1911 return null;
1912 }
1913
1914 hasSpaceKeypress = true;
1915 return SPACEBAR_CHAR;
1916
1917 case TOP_TEXT_INPUT:
1918 // Record the characters to be added to the DOM.
1919 var chars = nativeEvent.data;
1920
1921 // If it's a spacebar character, assume that we have already handled
1922 // it at the keypress level and bail immediately. Android Chrome
1923 // doesn't give us keycodes, so we need to ignore it.
1924 if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
1925 return null;
1926 }
1927
1928 return chars;
1929
1930 default:
1931 // For other native event types, do nothing.
1932 return null;
1933 }
1934}
1935
1936/**
1937 * For browsers that do not provide the `textInput` event, extract the
1938 * appropriate string to use for SyntheticInputEvent.
1939 *
1940 * @param {number} topLevelType Number from `TopLevelEventTypes`.
1941 * @param {object} nativeEvent Native browser event.
1942 * @return {?string} The fallback string for this `beforeInput` event.
1943 */
1944function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
1945 // If we are currently composing (IME) and using a fallback to do so,
1946 // try to extract the composed characters from the fallback object.
1947 // If composition event is available, we extract a string only at
1948 // compositionevent, otherwise extract it at fallback events.
1949 if (isComposing) {
1950 if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {
1951 var chars = getData();
1952 reset();
1953 isComposing = false;
1954 return chars;
1955 }
1956 return null;
1957 }
1958
1959 switch (topLevelType) {
1960 case TOP_PASTE:
1961 // If a paste event occurs after a keypress, throw out the input
1962 // chars. Paste events should not lead to BeforeInput events.
1963 return null;
1964 case TOP_KEY_PRESS:
1965 /**
1966 * As of v27, Firefox may fire keypress events even when no character
1967 * will be inserted. A few possibilities:
1968 *
1969 * - `which` is `0`. Arrow keys, Esc key, etc.
1970 *
1971 * - `which` is the pressed key code, but no char is available.
1972 * Ex: 'AltGr + d` in Polish. There is no modified character for
1973 * this key combination and no character is inserted into the
1974 * document, but FF fires the keypress for char code `100` anyway.
1975 * No `input` event will occur.
1976 *
1977 * - `which` is the pressed key code, but a command combination is
1978 * being used. Ex: `Cmd+C`. No character is inserted, and no
1979 * `input` event will occur.
1980 */
1981 if (!isKeypressCommand(nativeEvent)) {
1982 // IE fires the `keypress` event when a user types an emoji via
1983 // Touch keyboard of Windows. In such a case, the `char` property
1984 // holds an emoji character like `\uD83D\uDE0A`. Because its length
1985 // is 2, the property `which` does not represent an emoji correctly.
1986 // In such a case, we directly return the `char` property instead of
1987 // using `which`.
1988 if (nativeEvent.char && nativeEvent.char.length > 1) {
1989 return nativeEvent.char;
1990 } else if (nativeEvent.which) {
1991 return String.fromCharCode(nativeEvent.which);
1992 }
1993 }
1994 return null;
1995 case TOP_COMPOSITION_END:
1996 return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
1997 default:
1998 return null;
1999 }
2000}
2001
2002/**
2003 * Extract a SyntheticInputEvent for `beforeInput`, based on either native
2004 * `textInput` or fallback behavior.
2005 *
2006 * @return {?object} A SyntheticInputEvent.
2007 */
2008function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
2009 var chars = void 0;
2010
2011 if (canUseTextInputEvent) {
2012 chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
2013 } else {
2014 chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
2015 }
2016
2017 // If no characters are being inserted, no BeforeInput event should
2018 // be fired.
2019 if (!chars) {
2020 return null;
2021 }
2022
2023 var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);
2024
2025 event.data = chars;
2026 accumulateTwoPhaseDispatches(event);
2027 return event;
2028}
2029
2030/**
2031 * Create an `onBeforeInput` event to match
2032 * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
2033 *
2034 * This event plugin is based on the native `textInput` event
2035 * available in Chrome, Safari, Opera, and IE. This event fires after
2036 * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
2037 *
2038 * `beforeInput` is spec'd but not implemented in any browsers, and
2039 * the `input` event does not provide any useful information about what has
2040 * actually been added, contrary to the spec. Thus, `textInput` is the best
2041 * available event to identify the characters that have actually been inserted
2042 * into the target node.
2043 *
2044 * This plugin is also responsible for emitting `composition` events, thus
2045 * allowing us to share composition fallback code for both `beforeInput` and
2046 * `composition` event types.
2047 */
2048var BeforeInputEventPlugin = {
2049 eventTypes: eventTypes,
2050
2051 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
2052 var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
2053
2054 var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
2055
2056 if (composition === null) {
2057 return beforeInput;
2058 }
2059
2060 if (beforeInput === null) {
2061 return composition;
2062 }
2063
2064 return [composition, beforeInput];
2065 }
2066};
2067
2068// Use to restore controlled state after a change event has fired.
2069
2070var restoreImpl = null;
2071var restoreTarget = null;
2072var restoreQueue = null;
2073
2074function restoreStateOfTarget(target) {
2075 // We perform this translation at the end of the event loop so that we
2076 // always receive the correct fiber here
2077 var internalInstance = getInstanceFromNode(target);
2078 if (!internalInstance) {
2079 // Unmounted
2080 return;
2081 }
2082 !(typeof restoreImpl === 'function') ? invariant(false, '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.') : void 0;
2083 var props = getFiberCurrentPropsFromNode(internalInstance.stateNode);
2084 restoreImpl(internalInstance.stateNode, internalInstance.type, props);
2085}
2086
2087function setRestoreImplementation(impl) {
2088 restoreImpl = impl;
2089}
2090
2091function enqueueStateRestore(target) {
2092 if (restoreTarget) {
2093 if (restoreQueue) {
2094 restoreQueue.push(target);
2095 } else {
2096 restoreQueue = [target];
2097 }
2098 } else {
2099 restoreTarget = target;
2100 }
2101}
2102
2103function needsStateRestore() {
2104 return restoreTarget !== null || restoreQueue !== null;
2105}
2106
2107function restoreStateIfNeeded() {
2108 if (!restoreTarget) {
2109 return;
2110 }
2111 var target = restoreTarget;
2112 var queuedTargets = restoreQueue;
2113 restoreTarget = null;
2114 restoreQueue = null;
2115
2116 restoreStateOfTarget(target);
2117 if (queuedTargets) {
2118 for (var i = 0; i < queuedTargets.length; i++) {
2119 restoreStateOfTarget(queuedTargets[i]);
2120 }
2121 }
2122}
2123
2124// Used as a way to call batchedUpdates when we don't have a reference to
2125// the renderer. Such as when we're dispatching events or if third party
2126// libraries need to call batchedUpdates. Eventually, this API will go away when
2127// everything is batched by default. We'll then have a similar API to opt-out of
2128// scheduled work and instead do synchronous work.
2129
2130// Defaults
2131var _batchedUpdatesImpl = function (fn, bookkeeping) {
2132 return fn(bookkeeping);
2133};
2134var _interactiveUpdatesImpl = function (fn, a, b) {
2135 return fn(a, b);
2136};
2137var _flushInteractiveUpdatesImpl = function () {};
2138
2139var isBatching = false;
2140function batchedUpdates(fn, bookkeeping) {
2141 if (isBatching) {
2142 // If we are currently inside another batch, we need to wait until it
2143 // fully completes before restoring state.
2144 return fn(bookkeeping);
2145 }
2146 isBatching = true;
2147 try {
2148 return _batchedUpdatesImpl(fn, bookkeeping);
2149 } finally {
2150 // Here we wait until all updates have propagated, which is important
2151 // when using controlled components within layers:
2152 // https://github.com/facebook/react/issues/1698
2153 // Then we restore state of any controlled component.
2154 isBatching = false;
2155 var controlledComponentsHavePendingUpdates = needsStateRestore();
2156 if (controlledComponentsHavePendingUpdates) {
2157 // If a controlled event was fired, we may need to restore the state of
2158 // the DOM node back to the controlled value. This is necessary when React
2159 // bails out of the update without touching the DOM.
2160 _flushInteractiveUpdatesImpl();
2161 restoreStateIfNeeded();
2162 }
2163 }
2164}
2165
2166function interactiveUpdates(fn, a, b) {
2167 return _interactiveUpdatesImpl(fn, a, b);
2168}
2169
2170
2171
2172function setBatchingImplementation(batchedUpdatesImpl, interactiveUpdatesImpl, flushInteractiveUpdatesImpl) {
2173 _batchedUpdatesImpl = batchedUpdatesImpl;
2174 _interactiveUpdatesImpl = interactiveUpdatesImpl;
2175 _flushInteractiveUpdatesImpl = flushInteractiveUpdatesImpl;
2176}
2177
2178/**
2179 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
2180 */
2181var supportedInputTypes = {
2182 color: true,
2183 date: true,
2184 datetime: true,
2185 'datetime-local': true,
2186 email: true,
2187 month: true,
2188 number: true,
2189 password: true,
2190 range: true,
2191 search: true,
2192 tel: true,
2193 text: true,
2194 time: true,
2195 url: true,
2196 week: true
2197};
2198
2199function isTextInputElement(elem) {
2200 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
2201
2202 if (nodeName === 'input') {
2203 return !!supportedInputTypes[elem.type];
2204 }
2205
2206 if (nodeName === 'textarea') {
2207 return true;
2208 }
2209
2210 return false;
2211}
2212
2213/**
2214 * HTML nodeType values that represent the type of the node
2215 */
2216
2217var ELEMENT_NODE = 1;
2218var TEXT_NODE = 3;
2219var COMMENT_NODE = 8;
2220var DOCUMENT_NODE = 9;
2221var DOCUMENT_FRAGMENT_NODE = 11;
2222
2223/**
2224 * Gets the target node from a native browser event by accounting for
2225 * inconsistencies in browser DOM APIs.
2226 *
2227 * @param {object} nativeEvent Native browser event.
2228 * @return {DOMEventTarget} Target node.
2229 */
2230function getEventTarget(nativeEvent) {
2231 // Fallback to nativeEvent.srcElement for IE9
2232 // https://github.com/facebook/react/issues/12506
2233 var target = nativeEvent.target || nativeEvent.srcElement || window;
2234
2235 // Normalize SVG <use> element events #4963
2236 if (target.correspondingUseElement) {
2237 target = target.correspondingUseElement;
2238 }
2239
2240 // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
2241 // @see http://www.quirksmode.org/js/events_properties.html
2242 return target.nodeType === TEXT_NODE ? target.parentNode : target;
2243}
2244
2245/**
2246 * Checks if an event is supported in the current execution environment.
2247 *
2248 * NOTE: This will not work correctly for non-generic events such as `change`,
2249 * `reset`, `load`, `error`, and `select`.
2250 *
2251 * Borrows from Modernizr.
2252 *
2253 * @param {string} eventNameSuffix Event name, e.g. "click".
2254 * @return {boolean} True if the event is supported.
2255 * @internal
2256 * @license Modernizr 3.0.0pre (Custom Build) | MIT
2257 */
2258function isEventSupported(eventNameSuffix) {
2259 if (!canUseDOM) {
2260 return false;
2261 }
2262
2263 var eventName = 'on' + eventNameSuffix;
2264 var isSupported = eventName in document;
2265
2266 if (!isSupported) {
2267 var element = document.createElement('div');
2268 element.setAttribute(eventName, 'return;');
2269 isSupported = typeof element[eventName] === 'function';
2270 }
2271
2272 return isSupported;
2273}
2274
2275function isCheckable(elem) {
2276 var type = elem.type;
2277 var nodeName = elem.nodeName;
2278 return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
2279}
2280
2281function getTracker(node) {
2282 return node._valueTracker;
2283}
2284
2285function detachTracker(node) {
2286 node._valueTracker = null;
2287}
2288
2289function getValueFromNode(node) {
2290 var value = '';
2291 if (!node) {
2292 return value;
2293 }
2294
2295 if (isCheckable(node)) {
2296 value = node.checked ? 'true' : 'false';
2297 } else {
2298 value = node.value;
2299 }
2300
2301 return value;
2302}
2303
2304function trackValueOnNode(node) {
2305 var valueField = isCheckable(node) ? 'checked' : 'value';
2306 var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
2307
2308 var currentValue = '' + node[valueField];
2309
2310 // if someone has already defined a value or Safari, then bail
2311 // and don't track value will cause over reporting of changes,
2312 // but it's better then a hard failure
2313 // (needed for certain tests that spyOn input values and Safari)
2314 if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
2315 return;
2316 }
2317 var get = descriptor.get,
2318 set = descriptor.set;
2319
2320 Object.defineProperty(node, valueField, {
2321 configurable: true,
2322 get: function () {
2323 return get.call(this);
2324 },
2325 set: function (value) {
2326 currentValue = '' + value;
2327 set.call(this, value);
2328 }
2329 });
2330 // We could've passed this the first time
2331 // but it triggers a bug in IE11 and Edge 14/15.
2332 // Calling defineProperty() again should be equivalent.
2333 // https://github.com/facebook/react/issues/11768
2334 Object.defineProperty(node, valueField, {
2335 enumerable: descriptor.enumerable
2336 });
2337
2338 var tracker = {
2339 getValue: function () {
2340 return currentValue;
2341 },
2342 setValue: function (value) {
2343 currentValue = '' + value;
2344 },
2345 stopTracking: function () {
2346 detachTracker(node);
2347 delete node[valueField];
2348 }
2349 };
2350 return tracker;
2351}
2352
2353function track(node) {
2354 if (getTracker(node)) {
2355 return;
2356 }
2357
2358 // TODO: Once it's just Fiber we can move this to node._wrapperState
2359 node._valueTracker = trackValueOnNode(node);
2360}
2361
2362function updateValueIfChanged(node) {
2363 if (!node) {
2364 return false;
2365 }
2366
2367 var tracker = getTracker(node);
2368 // if there is no tracker at this point it's unlikely
2369 // that trying again will succeed
2370 if (!tracker) {
2371 return true;
2372 }
2373
2374 var lastValue = tracker.getValue();
2375 var nextValue = getValueFromNode(node);
2376 if (nextValue !== lastValue) {
2377 tracker.setValue(nextValue);
2378 return true;
2379 }
2380 return false;
2381}
2382
2383var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
2384
2385// Prevent newer renderers from RTE when used with older react package versions.
2386// Current owner and dispatcher used to share the same ref,
2387// but PR #14548 split them out to better support the react-debug-tools package.
2388if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
2389 ReactSharedInternals.ReactCurrentDispatcher = {
2390 current: null
2391 };
2392}
2393
2394var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
2395
2396var describeComponentFrame = function (name, source, ownerName) {
2397 var sourceInfo = '';
2398 if (source) {
2399 var path = source.fileName;
2400 var fileName = path.replace(BEFORE_SLASH_RE, '');
2401 {
2402 // In DEV, include code for a common special case:
2403 // prefer "folder/index.js" instead of just "index.js".
2404 if (/^index\./.test(fileName)) {
2405 var match = path.match(BEFORE_SLASH_RE);
2406 if (match) {
2407 var pathBeforeSlash = match[1];
2408 if (pathBeforeSlash) {
2409 var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
2410 fileName = folderName + '/' + fileName;
2411 }
2412 }
2413 }
2414 }
2415 sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
2416 } else if (ownerName) {
2417 sourceInfo = ' (created by ' + ownerName + ')';
2418 }
2419 return '\n in ' + (name || 'Unknown') + sourceInfo;
2420};
2421
2422// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
2423// nor polyfill, then a plain number is used for performance.
2424var hasSymbol = typeof Symbol === 'function' && Symbol.for;
2425
2426var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
2427var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
2428var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
2429var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
2430var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
2431var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
2432var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
2433
2434var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
2435var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
2436var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
2437var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
2438var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
2439
2440var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
2441var FAUX_ITERATOR_SYMBOL = '@@iterator';
2442
2443function getIteratorFn(maybeIterable) {
2444 if (maybeIterable === null || typeof maybeIterable !== 'object') {
2445 return null;
2446 }
2447 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
2448 if (typeof maybeIterator === 'function') {
2449 return maybeIterator;
2450 }
2451 return null;
2452}
2453
2454var Pending = 0;
2455var Resolved = 1;
2456var Rejected = 2;
2457
2458function refineResolvedLazyComponent(lazyComponent) {
2459 return lazyComponent._status === Resolved ? lazyComponent._result : null;
2460}
2461
2462function getWrappedName(outerType, innerType, wrapperName) {
2463 var functionName = innerType.displayName || innerType.name || '';
2464 return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName);
2465}
2466
2467function getComponentName(type) {
2468 if (type == null) {
2469 // Host root, text node or just invalid type.
2470 return null;
2471 }
2472 {
2473 if (typeof type.tag === 'number') {
2474 warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
2475 }
2476 }
2477 if (typeof type === 'function') {
2478 return type.displayName || type.name || null;
2479 }
2480 if (typeof type === 'string') {
2481 return type;
2482 }
2483 switch (type) {
2484 case REACT_CONCURRENT_MODE_TYPE:
2485 return 'ConcurrentMode';
2486 case REACT_FRAGMENT_TYPE:
2487 return 'Fragment';
2488 case REACT_PORTAL_TYPE:
2489 return 'Portal';
2490 case REACT_PROFILER_TYPE:
2491 return 'Profiler';
2492 case REACT_STRICT_MODE_TYPE:
2493 return 'StrictMode';
2494 case REACT_SUSPENSE_TYPE:
2495 return 'Suspense';
2496 }
2497 if (typeof type === 'object') {
2498 switch (type.$$typeof) {
2499 case REACT_CONTEXT_TYPE:
2500 return 'Context.Consumer';
2501 case REACT_PROVIDER_TYPE:
2502 return 'Context.Provider';
2503 case REACT_FORWARD_REF_TYPE:
2504 return getWrappedName(type, type.render, 'ForwardRef');
2505 case REACT_MEMO_TYPE:
2506 return getComponentName(type.type);
2507 case REACT_LAZY_TYPE:
2508 {
2509 var thenable = type;
2510 var resolvedThenable = refineResolvedLazyComponent(thenable);
2511 if (resolvedThenable) {
2512 return getComponentName(resolvedThenable);
2513 }
2514 }
2515 }
2516 }
2517 return null;
2518}
2519
2520var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
2521
2522function describeFiber(fiber) {
2523 switch (fiber.tag) {
2524 case HostRoot:
2525 case HostPortal:
2526 case HostText:
2527 case Fragment:
2528 case ContextProvider:
2529 case ContextConsumer:
2530 return '';
2531 default:
2532 var owner = fiber._debugOwner;
2533 var source = fiber._debugSource;
2534 var name = getComponentName(fiber.type);
2535 var ownerName = null;
2536 if (owner) {
2537 ownerName = getComponentName(owner.type);
2538 }
2539 return describeComponentFrame(name, source, ownerName);
2540 }
2541}
2542
2543function getStackByFiberInDevAndProd(workInProgress) {
2544 var info = '';
2545 var node = workInProgress;
2546 do {
2547 info += describeFiber(node);
2548 node = node.return;
2549 } while (node);
2550 return info;
2551}
2552
2553var current = null;
2554var phase = null;
2555
2556function getCurrentFiberOwnerNameInDevOrNull() {
2557 {
2558 if (current === null) {
2559 return null;
2560 }
2561 var owner = current._debugOwner;
2562 if (owner !== null && typeof owner !== 'undefined') {
2563 return getComponentName(owner.type);
2564 }
2565 }
2566 return null;
2567}
2568
2569function getCurrentFiberStackInDev() {
2570 {
2571 if (current === null) {
2572 return '';
2573 }
2574 // Safe because if current fiber exists, we are reconciling,
2575 // and it is guaranteed to be the work-in-progress version.
2576 return getStackByFiberInDevAndProd(current);
2577 }
2578 return '';
2579}
2580
2581function resetCurrentFiber() {
2582 {
2583 ReactDebugCurrentFrame.getCurrentStack = null;
2584 current = null;
2585 phase = null;
2586 }
2587}
2588
2589function setCurrentFiber(fiber) {
2590 {
2591 ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev;
2592 current = fiber;
2593 phase = null;
2594 }
2595}
2596
2597function setCurrentPhase(lifeCyclePhase) {
2598 {
2599 phase = lifeCyclePhase;
2600 }
2601}
2602
2603/**
2604 * Similar to invariant but only logs a warning if the condition is not met.
2605 * This can be used to log issues in development environments in critical
2606 * paths. Removing the logging code for production environments will keep the
2607 * same logic and follow the same code paths.
2608 */
2609
2610var warning = warningWithoutStack$1;
2611
2612{
2613 warning = function (condition, format) {
2614 if (condition) {
2615 return;
2616 }
2617 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
2618 var stack = ReactDebugCurrentFrame.getStackAddendum();
2619 // eslint-disable-next-line react-internal/warning-and-invariant-args
2620
2621 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
2622 args[_key - 2] = arguments[_key];
2623 }
2624
2625 warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack]));
2626 };
2627}
2628
2629var warning$1 = warning;
2630
2631// A reserved attribute.
2632// It is handled by React separately and shouldn't be written to the DOM.
2633var RESERVED = 0;
2634
2635// A simple string attribute.
2636// Attributes that aren't in the whitelist are presumed to have this type.
2637var STRING = 1;
2638
2639// A string attribute that accepts booleans in React. In HTML, these are called
2640// "enumerated" attributes with "true" and "false" as possible values.
2641// When true, it should be set to a "true" string.
2642// When false, it should be set to a "false" string.
2643var BOOLEANISH_STRING = 2;
2644
2645// A real boolean attribute.
2646// When true, it should be present (set either to an empty string or its name).
2647// When false, it should be omitted.
2648var BOOLEAN = 3;
2649
2650// An attribute that can be used as a flag as well as with a value.
2651// When true, it should be present (set either to an empty string or its name).
2652// When false, it should be omitted.
2653// For any other value, should be present with that value.
2654var OVERLOADED_BOOLEAN = 4;
2655
2656// An attribute that must be numeric or parse as a numeric.
2657// When falsy, it should be removed.
2658var NUMERIC = 5;
2659
2660// An attribute that must be positive numeric or parse as a positive numeric.
2661// When falsy, it should be removed.
2662var POSITIVE_NUMERIC = 6;
2663
2664/* eslint-disable max-len */
2665var 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';
2666/* eslint-enable max-len */
2667var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040';
2668
2669
2670var ROOT_ATTRIBUTE_NAME = 'data-reactroot';
2671var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
2672
2673var hasOwnProperty = Object.prototype.hasOwnProperty;
2674var illegalAttributeNameCache = {};
2675var validatedAttributeNameCache = {};
2676
2677function isAttributeNameSafe(attributeName) {
2678 if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
2679 return true;
2680 }
2681 if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
2682 return false;
2683 }
2684 if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
2685 validatedAttributeNameCache[attributeName] = true;
2686 return true;
2687 }
2688 illegalAttributeNameCache[attributeName] = true;
2689 {
2690 warning$1(false, 'Invalid attribute name: `%s`', attributeName);
2691 }
2692 return false;
2693}
2694
2695function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
2696 if (propertyInfo !== null) {
2697 return propertyInfo.type === RESERVED;
2698 }
2699 if (isCustomComponentTag) {
2700 return false;
2701 }
2702 if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
2703 return true;
2704 }
2705 return false;
2706}
2707
2708function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
2709 if (propertyInfo !== null && propertyInfo.type === RESERVED) {
2710 return false;
2711 }
2712 switch (typeof value) {
2713 case 'function':
2714 // $FlowIssue symbol is perfectly valid here
2715 case 'symbol':
2716 // eslint-disable-line
2717 return true;
2718 case 'boolean':
2719 {
2720 if (isCustomComponentTag) {
2721 return false;
2722 }
2723 if (propertyInfo !== null) {
2724 return !propertyInfo.acceptsBooleans;
2725 } else {
2726 var prefix = name.toLowerCase().slice(0, 5);
2727 return prefix !== 'data-' && prefix !== 'aria-';
2728 }
2729 }
2730 default:
2731 return false;
2732 }
2733}
2734
2735function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
2736 if (value === null || typeof value === 'undefined') {
2737 return true;
2738 }
2739 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
2740 return true;
2741 }
2742 if (isCustomComponentTag) {
2743 return false;
2744 }
2745 if (propertyInfo !== null) {
2746 switch (propertyInfo.type) {
2747 case BOOLEAN:
2748 return !value;
2749 case OVERLOADED_BOOLEAN:
2750 return value === false;
2751 case NUMERIC:
2752 return isNaN(value);
2753 case POSITIVE_NUMERIC:
2754 return isNaN(value) || value < 1;
2755 }
2756 }
2757 return false;
2758}
2759
2760function getPropertyInfo(name) {
2761 return properties.hasOwnProperty(name) ? properties[name] : null;
2762}
2763
2764function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace) {
2765 this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
2766 this.attributeName = attributeName;
2767 this.attributeNamespace = attributeNamespace;
2768 this.mustUseProperty = mustUseProperty;
2769 this.propertyName = name;
2770 this.type = type;
2771}
2772
2773// When adding attributes to this list, be sure to also add them to
2774// the `possibleStandardNames` module to ensure casing and incorrect
2775// name warnings.
2776var properties = {};
2777
2778// These props are reserved by React. They shouldn't be written to the DOM.
2779['children', 'dangerouslySetInnerHTML',
2780// TODO: This prevents the assignment of defaultValue to regular
2781// elements (not just inputs). Now that ReactDOMInput assigns to the
2782// defaultValue property -- do we need this?
2783'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'].forEach(function (name) {
2784 properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
2785 name, // attributeName
2786 null);
2787} // attributeNamespace
2788);
2789
2790// A few React string attributes have a different name.
2791// This is a mapping from React prop names to the attribute names.
2792[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
2793 var name = _ref[0],
2794 attributeName = _ref[1];
2795
2796 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2797 attributeName, // attributeName
2798 null);
2799} // attributeNamespace
2800);
2801
2802// These are "enumerated" HTML attributes that accept "true" and "false".
2803// In React, we let users pass `true` and `false` even though technically
2804// these aren't boolean attributes (they are coerced to strings).
2805['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
2806 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2807 name.toLowerCase(), // attributeName
2808 null);
2809} // attributeNamespace
2810);
2811
2812// These are "enumerated" SVG attributes that accept "true" and "false".
2813// In React, we let users pass `true` and `false` even though technically
2814// these aren't boolean attributes (they are coerced to strings).
2815// Since these are SVG attributes, their attribute names are case-sensitive.
2816['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
2817 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2818 name, // attributeName
2819 null);
2820} // attributeNamespace
2821);
2822
2823// These are HTML boolean attributes.
2824['allowFullScreen', 'async',
2825// Note: there is a special case that prevents it from being written to the DOM
2826// on the client side because the browsers are inconsistent. Instead we call focus().
2827'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless',
2828// Microdata
2829'itemScope'].forEach(function (name) {
2830 properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
2831 name.toLowerCase(), // attributeName
2832 null);
2833} // attributeNamespace
2834);
2835
2836// These are the few React props that we set as DOM properties
2837// rather than attributes. These are all booleans.
2838['checked',
2839// Note: `option.selected` is not updated if `select.multiple` is
2840// disabled with `removeAttribute`. We have special logic for handling this.
2841'multiple', 'muted', 'selected'].forEach(function (name) {
2842 properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
2843 name, // attributeName
2844 null);
2845} // attributeNamespace
2846);
2847
2848// These are HTML attributes that are "overloaded booleans": they behave like
2849// booleans, but can also accept a string value.
2850['capture', 'download'].forEach(function (name) {
2851 properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
2852 name, // attributeName
2853 null);
2854} // attributeNamespace
2855);
2856
2857// These are HTML attributes that must be positive numbers.
2858['cols', 'rows', 'size', 'span'].forEach(function (name) {
2859 properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
2860 name, // attributeName
2861 null);
2862} // attributeNamespace
2863);
2864
2865// These are HTML attributes that must be numbers.
2866['rowSpan', 'start'].forEach(function (name) {
2867 properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
2868 name.toLowerCase(), // attributeName
2869 null);
2870} // attributeNamespace
2871);
2872
2873var CAMELIZE = /[\-\:]([a-z])/g;
2874var capitalize = function (token) {
2875 return token[1].toUpperCase();
2876};
2877
2878// This is a list of all SVG attributes that need special casing, namespacing,
2879// or boolean value assignment. Regular attributes that just accept strings
2880// and have the same names are omitted, just like in the HTML whitelist.
2881// Some of these attributes can be hard to find. This list was created by
2882// scrapping the MDN documentation.
2883['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) {
2884 var name = attributeName.replace(CAMELIZE, capitalize);
2885 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2886 attributeName, null);
2887} // attributeNamespace
2888);
2889
2890// String SVG attributes with the xlink namespace.
2891['xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type'].forEach(function (attributeName) {
2892 var name = attributeName.replace(CAMELIZE, capitalize);
2893 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2894 attributeName, 'http://www.w3.org/1999/xlink');
2895});
2896
2897// String SVG attributes with the xml namespace.
2898['xml:base', 'xml:lang', 'xml:space'].forEach(function (attributeName) {
2899 var name = attributeName.replace(CAMELIZE, capitalize);
2900 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2901 attributeName, 'http://www.w3.org/XML/1998/namespace');
2902});
2903
2904// Special case: this attribute exists both in HTML and SVG.
2905// Its "tabindex" attribute name is case-sensitive in SVG so we can't just use
2906// its React `tabIndex` name, like we do for attributes that exist only in HTML.
2907properties.tabIndex = new PropertyInfoRecord('tabIndex', STRING, false, // mustUseProperty
2908'tabindex', // attributeName
2909null);
2910
2911/**
2912 * Get the value for a property on a node. Only used in DEV for SSR validation.
2913 * The "expected" argument is used as a hint of what the expected value is.
2914 * Some properties have multiple equivalent values.
2915 */
2916function getValueForProperty(node, name, expected, propertyInfo) {
2917 {
2918 if (propertyInfo.mustUseProperty) {
2919 var propertyName = propertyInfo.propertyName;
2920
2921 return node[propertyName];
2922 } else {
2923 var attributeName = propertyInfo.attributeName;
2924
2925 var stringValue = null;
2926
2927 if (propertyInfo.type === OVERLOADED_BOOLEAN) {
2928 if (node.hasAttribute(attributeName)) {
2929 var value = node.getAttribute(attributeName);
2930 if (value === '') {
2931 return true;
2932 }
2933 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2934 return value;
2935 }
2936 if (value === '' + expected) {
2937 return expected;
2938 }
2939 return value;
2940 }
2941 } else if (node.hasAttribute(attributeName)) {
2942 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2943 // We had an attribute but shouldn't have had one, so read it
2944 // for the error message.
2945 return node.getAttribute(attributeName);
2946 }
2947 if (propertyInfo.type === BOOLEAN) {
2948 // If this was a boolean, it doesn't matter what the value is
2949 // the fact that we have it is the same as the expected.
2950 return expected;
2951 }
2952 // Even if this property uses a namespace we use getAttribute
2953 // because we assume its namespaced name is the same as our config.
2954 // To use getAttributeNS we need the local name which we don't have
2955 // in our config atm.
2956 stringValue = node.getAttribute(attributeName);
2957 }
2958
2959 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2960 return stringValue === null ? expected : stringValue;
2961 } else if (stringValue === '' + expected) {
2962 return expected;
2963 } else {
2964 return stringValue;
2965 }
2966 }
2967 }
2968}
2969
2970/**
2971 * Get the value for a attribute on a node. Only used in DEV for SSR validation.
2972 * The third argument is used as a hint of what the expected value is. Some
2973 * attributes have multiple equivalent values.
2974 */
2975function getValueForAttribute(node, name, expected) {
2976 {
2977 if (!isAttributeNameSafe(name)) {
2978 return;
2979 }
2980 if (!node.hasAttribute(name)) {
2981 return expected === undefined ? undefined : null;
2982 }
2983 var value = node.getAttribute(name);
2984 if (value === '' + expected) {
2985 return expected;
2986 }
2987 return value;
2988 }
2989}
2990
2991/**
2992 * Sets the value for a property on a node.
2993 *
2994 * @param {DOMElement} node
2995 * @param {string} name
2996 * @param {*} value
2997 */
2998function setValueForProperty(node, name, value, isCustomComponentTag) {
2999 var propertyInfo = getPropertyInfo(name);
3000 if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
3001 return;
3002 }
3003 if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
3004 value = null;
3005 }
3006 // If the prop isn't in the special list, treat it as a simple attribute.
3007 if (isCustomComponentTag || propertyInfo === null) {
3008 if (isAttributeNameSafe(name)) {
3009 var _attributeName = name;
3010 if (value === null) {
3011 node.removeAttribute(_attributeName);
3012 } else {
3013 node.setAttribute(_attributeName, '' + value);
3014 }
3015 }
3016 return;
3017 }
3018 var mustUseProperty = propertyInfo.mustUseProperty;
3019
3020 if (mustUseProperty) {
3021 var propertyName = propertyInfo.propertyName;
3022
3023 if (value === null) {
3024 var type = propertyInfo.type;
3025
3026 node[propertyName] = type === BOOLEAN ? false : '';
3027 } else {
3028 // Contrary to `setAttribute`, object properties are properly
3029 // `toString`ed by IE8/9.
3030 node[propertyName] = value;
3031 }
3032 return;
3033 }
3034 // The rest are treated as attributes with special cases.
3035 var attributeName = propertyInfo.attributeName,
3036 attributeNamespace = propertyInfo.attributeNamespace;
3037
3038 if (value === null) {
3039 node.removeAttribute(attributeName);
3040 } else {
3041 var _type = propertyInfo.type;
3042
3043 var attributeValue = void 0;
3044 if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
3045 attributeValue = '';
3046 } else {
3047 // `setAttribute` with objects becomes only `[object]` in IE8/9,
3048 // ('' + value) makes it output the correct toString()-value.
3049 attributeValue = '' + value;
3050 }
3051 if (attributeNamespace) {
3052 node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
3053 } else {
3054 node.setAttribute(attributeName, attributeValue);
3055 }
3056 }
3057}
3058
3059// Flow does not allow string concatenation of most non-string types. To work
3060// around this limitation, we use an opaque type that can only be obtained by
3061// passing the value through getToStringValue first.
3062function toString(value) {
3063 return '' + value;
3064}
3065
3066function getToStringValue(value) {
3067 switch (typeof value) {
3068 case 'boolean':
3069 case 'number':
3070 case 'object':
3071 case 'string':
3072 case 'undefined':
3073 return value;
3074 default:
3075 // function, symbol are assigned as empty strings
3076 return '';
3077 }
3078}
3079
3080/**
3081 * Copyright (c) 2013-present, Facebook, Inc.
3082 *
3083 * This source code is licensed under the MIT license found in the
3084 * LICENSE file in the root directory of this source tree.
3085 */
3086
3087
3088
3089var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
3090
3091var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
3092
3093/**
3094 * Copyright (c) 2013-present, Facebook, Inc.
3095 *
3096 * This source code is licensed under the MIT license found in the
3097 * LICENSE file in the root directory of this source tree.
3098 */
3099
3100
3101
3102var printWarning = function() {};
3103
3104{
3105 var ReactPropTypesSecret = ReactPropTypesSecret_1;
3106 var loggedTypeFailures = {};
3107
3108 printWarning = function(text) {
3109 var message = 'Warning: ' + text;
3110 if (typeof console !== 'undefined') {
3111 console.error(message);
3112 }
3113 try {
3114 // --- Welcome to debugging React ---
3115 // This error was thrown as a convenience so that you can use this stack
3116 // to find the callsite that caused this warning to fire.
3117 throw new Error(message);
3118 } catch (x) {}
3119 };
3120}
3121
3122/**
3123 * Assert that the values match with the type specs.
3124 * Error messages are memorized and will only be shown once.
3125 *
3126 * @param {object} typeSpecs Map of name to a ReactPropType
3127 * @param {object} values Runtime values that need to be type-checked
3128 * @param {string} location e.g. "prop", "context", "child context"
3129 * @param {string} componentName Name of the component for error messages.
3130 * @param {?Function} getStack Returns the component stack.
3131 * @private
3132 */
3133function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
3134 {
3135 for (var typeSpecName in typeSpecs) {
3136 if (typeSpecs.hasOwnProperty(typeSpecName)) {
3137 var error;
3138 // Prop type validation may throw. In case they do, we don't want to
3139 // fail the render phase where it didn't fail before. So we log it.
3140 // After these have been cleaned up, we'll let them throw.
3141 try {
3142 // This is intentionally an invariant that gets caught. It's the same
3143 // behavior as without this statement except with a better message.
3144 if (typeof typeSpecs[typeSpecName] !== 'function') {
3145 var err = Error(
3146 (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
3147 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
3148 );
3149 err.name = 'Invariant Violation';
3150 throw err;
3151 }
3152 error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
3153 } catch (ex) {
3154 error = ex;
3155 }
3156 if (error && !(error instanceof Error)) {
3157 printWarning(
3158 (componentName || 'React class') + ': type specification of ' +
3159 location + ' `' + typeSpecName + '` is invalid; the type checker ' +
3160 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
3161 'You may have forgotten to pass an argument to the type checker ' +
3162 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
3163 'shape all require an argument).'
3164 );
3165
3166 }
3167 if (error instanceof Error && !(error.message in loggedTypeFailures)) {
3168 // Only monitor this failure once because there tends to be a lot of the
3169 // same error.
3170 loggedTypeFailures[error.message] = true;
3171
3172 var stack = getStack ? getStack() : '';
3173
3174 printWarning(
3175 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
3176 );
3177 }
3178 }
3179 }
3180 }
3181}
3182
3183var checkPropTypes_1 = checkPropTypes;
3184
3185var ReactDebugCurrentFrame$1 = null;
3186
3187var ReactControlledValuePropTypes = {
3188 checkPropTypes: null
3189};
3190
3191{
3192 ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
3193
3194 var hasReadOnlyValue = {
3195 button: true,
3196 checkbox: true,
3197 image: true,
3198 hidden: true,
3199 radio: true,
3200 reset: true,
3201 submit: true
3202 };
3203
3204 var propTypes = {
3205 value: function (props, propName, componentName) {
3206 if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null) {
3207 return null;
3208 }
3209 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`.');
3210 },
3211 checked: function (props, propName, componentName) {
3212 if (props.onChange || props.readOnly || props.disabled || props[propName] == null) {
3213 return null;
3214 }
3215 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`.');
3216 }
3217 };
3218
3219 /**
3220 * Provide a linked `value` attribute for controlled forms. You should not use
3221 * this outside of the ReactDOM controlled form components.
3222 */
3223 ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) {
3224 checkPropTypes_1(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$1.getStackAddendum);
3225 };
3226}
3227
3228var enableUserTimingAPI = true;
3229
3230// Helps identify side effects in begin-phase lifecycle hooks and setState reducers:
3231var debugRenderPhaseSideEffects = false;
3232
3233// In some cases, StrictMode should also double-render lifecycles.
3234// This can be confusing for tests though,
3235// And it can be bad for performance in production.
3236// This feature flag can be used to control the behavior:
3237var debugRenderPhaseSideEffectsForStrictMode = true;
3238
3239// To preserve the "Pause on caught exceptions" behavior of the debugger, we
3240// replay the begin phase of a failed component inside invokeGuardedCallback.
3241var replayFailedUnitOfWorkWithInvokeGuardedCallback = true;
3242
3243// Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:
3244var warnAboutDeprecatedLifecycles = false;
3245
3246// Gather advanced timing metrics for Profiler subtrees.
3247var enableProfilerTimer = true;
3248
3249// Trace which interactions trigger each commit.
3250var enableSchedulerTracing = true;
3251
3252// Only used in www builds.
3253 // TODO: true? Here it might just be false.
3254
3255// Only used in www builds.
3256
3257
3258// Only used in www builds.
3259
3260
3261// React Fire: prevent the value and checked attributes from syncing
3262// with their related DOM properties
3263var disableInputAttributeSyncing = false;
3264
3265// These APIs will no longer be "unstable" in the upcoming 16.7 release,
3266// Control this behavior with a flag to support 16.6 minor releases in the meanwhile.
3267var enableStableConcurrentModeAPIs = false;
3268
3269var warnAboutShorthandPropertyCollision = false;
3270
3271// TODO: direct imports like some-package/src/* are bad. Fix me.
3272var didWarnValueDefaultValue = false;
3273var didWarnCheckedDefaultChecked = false;
3274var didWarnControlledToUncontrolled = false;
3275var didWarnUncontrolledToControlled = false;
3276
3277function isControlled(props) {
3278 var usesChecked = props.type === 'checkbox' || props.type === 'radio';
3279 return usesChecked ? props.checked != null : props.value != null;
3280}
3281
3282/**
3283 * Implements an <input> host component that allows setting these optional
3284 * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
3285 *
3286 * If `checked` or `value` are not supplied (or null/undefined), user actions
3287 * that affect the checked state or value will trigger updates to the element.
3288 *
3289 * If they are supplied (and not null/undefined), the rendered element will not
3290 * trigger updates to the element. Instead, the props must change in order for
3291 * the rendered element to be updated.
3292 *
3293 * The rendered element will be initialized as unchecked (or `defaultChecked`)
3294 * with an empty value (or `defaultValue`).
3295 *
3296 * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
3297 */
3298
3299function getHostProps(element, props) {
3300 var node = element;
3301 var checked = props.checked;
3302
3303 var hostProps = _assign({}, props, {
3304 defaultChecked: undefined,
3305 defaultValue: undefined,
3306 value: undefined,
3307 checked: checked != null ? checked : node._wrapperState.initialChecked
3308 });
3309
3310 return hostProps;
3311}
3312
3313function initWrapperState(element, props) {
3314 {
3315 ReactControlledValuePropTypes.checkPropTypes('input', props);
3316
3317 if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
3318 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);
3319 didWarnCheckedDefaultChecked = true;
3320 }
3321 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
3322 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);
3323 didWarnValueDefaultValue = true;
3324 }
3325 }
3326
3327 var node = element;
3328 var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
3329
3330 node._wrapperState = {
3331 initialChecked: props.checked != null ? props.checked : props.defaultChecked,
3332 initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
3333 controlled: isControlled(props)
3334 };
3335}
3336
3337function updateChecked(element, props) {
3338 var node = element;
3339 var checked = props.checked;
3340 if (checked != null) {
3341 setValueForProperty(node, 'checked', checked, false);
3342 }
3343}
3344
3345function updateWrapper(element, props) {
3346 var node = element;
3347 {
3348 var _controlled = isControlled(props);
3349
3350 if (!node._wrapperState.controlled && _controlled && !didWarnUncontrolledToControlled) {
3351 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);
3352 didWarnUncontrolledToControlled = true;
3353 }
3354 if (node._wrapperState.controlled && !_controlled && !didWarnControlledToUncontrolled) {
3355 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);
3356 didWarnControlledToUncontrolled = true;
3357 }
3358 }
3359
3360 updateChecked(element, props);
3361
3362 var value = getToStringValue(props.value);
3363 var type = props.type;
3364
3365 if (value != null) {
3366 if (type === 'number') {
3367 if (value === 0 && node.value === '' ||
3368 // We explicitly want to coerce to number here if possible.
3369 // eslint-disable-next-line
3370 node.value != value) {
3371 node.value = toString(value);
3372 }
3373 } else if (node.value !== toString(value)) {
3374 node.value = toString(value);
3375 }
3376 } else if (type === 'submit' || type === 'reset') {
3377 // Submit/reset inputs need the attribute removed completely to avoid
3378 // blank-text buttons.
3379 node.removeAttribute('value');
3380 return;
3381 }
3382
3383 if (disableInputAttributeSyncing) {
3384 // When not syncing the value attribute, React only assigns a new value
3385 // whenever the defaultValue React prop has changed. When not present,
3386 // React does nothing
3387 if (props.hasOwnProperty('defaultValue')) {
3388 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
3389 }
3390 } else {
3391 // When syncing the value attribute, the value comes from a cascade of
3392 // properties:
3393 // 1. The value React property
3394 // 2. The defaultValue React property
3395 // 3. Otherwise there should be no change
3396 if (props.hasOwnProperty('value')) {
3397 setDefaultValue(node, props.type, value);
3398 } else if (props.hasOwnProperty('defaultValue')) {
3399 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
3400 }
3401 }
3402
3403 if (disableInputAttributeSyncing) {
3404 // When not syncing the checked attribute, the attribute is directly
3405 // controllable from the defaultValue React property. It needs to be
3406 // updated as new props come in.
3407 if (props.defaultChecked == null) {
3408 node.removeAttribute('checked');
3409 } else {
3410 node.defaultChecked = !!props.defaultChecked;
3411 }
3412 } else {
3413 // When syncing the checked attribute, it only changes when it needs
3414 // to be removed, such as transitioning from a checkbox into a text input
3415 if (props.checked == null && props.defaultChecked != null) {
3416 node.defaultChecked = !!props.defaultChecked;
3417 }
3418 }
3419}
3420
3421function postMountWrapper(element, props, isHydrating) {
3422 var node = element;
3423
3424 // Do not assign value if it is already set. This prevents user text input
3425 // from being lost during SSR hydration.
3426 if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
3427 var type = props.type;
3428 var isButton = type === 'submit' || type === 'reset';
3429
3430 // Avoid setting value attribute on submit/reset inputs as it overrides the
3431 // default value provided by the browser. See: #12872
3432 if (isButton && (props.value === undefined || props.value === null)) {
3433 return;
3434 }
3435
3436 var _initialValue = toString(node._wrapperState.initialValue);
3437
3438 // Do not assign value if it is already set. This prevents user text input
3439 // from being lost during SSR hydration.
3440 if (!isHydrating) {
3441 if (disableInputAttributeSyncing) {
3442 var value = getToStringValue(props.value);
3443
3444 // When not syncing the value attribute, the value property points
3445 // directly to the React prop. Only assign it if it exists.
3446 if (value != null) {
3447 // Always assign on buttons so that it is possible to assign an
3448 // empty string to clear button text.
3449 //
3450 // Otherwise, do not re-assign the value property if is empty. This
3451 // potentially avoids a DOM write and prevents Firefox (~60.0.1) from
3452 // prematurely marking required inputs as invalid. Equality is compared
3453 // to the current value in case the browser provided value is not an
3454 // empty string.
3455 if (isButton || value !== node.value) {
3456 node.value = toString(value);
3457 }
3458 }
3459 } else {
3460 // When syncing the value attribute, the value property should use
3461 // the wrapperState._initialValue property. This uses:
3462 //
3463 // 1. The value React property when present
3464 // 2. The defaultValue React property when present
3465 // 3. An empty string
3466 if (_initialValue !== node.value) {
3467 node.value = _initialValue;
3468 }
3469 }
3470 }
3471
3472 if (disableInputAttributeSyncing) {
3473 // When not syncing the value attribute, assign the value attribute
3474 // directly from the defaultValue React property (when present)
3475 var defaultValue = getToStringValue(props.defaultValue);
3476 if (defaultValue != null) {
3477 node.defaultValue = toString(defaultValue);
3478 }
3479 } else {
3480 // Otherwise, the value attribute is synchronized to the property,
3481 // so we assign defaultValue to the same thing as the value property
3482 // assignment step above.
3483 node.defaultValue = _initialValue;
3484 }
3485 }
3486
3487 // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
3488 // this is needed to work around a chrome bug where setting defaultChecked
3489 // will sometimes influence the value of checked (even after detachment).
3490 // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
3491 // We need to temporarily unset name to avoid disrupting radio button groups.
3492 var name = node.name;
3493 if (name !== '') {
3494 node.name = '';
3495 }
3496
3497 if (disableInputAttributeSyncing) {
3498 // When not syncing the checked attribute, the checked property
3499 // never gets assigned. It must be manually set. We don't want
3500 // to do this when hydrating so that existing user input isn't
3501 // modified
3502 if (!isHydrating) {
3503 updateChecked(element, props);
3504 }
3505
3506 // Only assign the checked attribute if it is defined. This saves
3507 // a DOM write when controlling the checked attribute isn't needed
3508 // (text inputs, submit/reset)
3509 if (props.hasOwnProperty('defaultChecked')) {
3510 node.defaultChecked = !node.defaultChecked;
3511 node.defaultChecked = !!props.defaultChecked;
3512 }
3513 } else {
3514 // When syncing the checked attribute, both the checked property and
3515 // attribute are assigned at the same time using defaultChecked. This uses:
3516 //
3517 // 1. The checked React property when present
3518 // 2. The defaultChecked React property when present
3519 // 3. Otherwise, false
3520 node.defaultChecked = !node.defaultChecked;
3521 node.defaultChecked = !!node._wrapperState.initialChecked;
3522 }
3523
3524 if (name !== '') {
3525 node.name = name;
3526 }
3527}
3528
3529function restoreControlledState(element, props) {
3530 var node = element;
3531 updateWrapper(node, props);
3532 updateNamedCousins(node, props);
3533}
3534
3535function updateNamedCousins(rootNode, props) {
3536 var name = props.name;
3537 if (props.type === 'radio' && name != null) {
3538 var queryRoot = rootNode;
3539
3540 while (queryRoot.parentNode) {
3541 queryRoot = queryRoot.parentNode;
3542 }
3543
3544 // If `rootNode.form` was non-null, then we could try `form.elements`,
3545 // but that sometimes behaves strangely in IE8. We could also try using
3546 // `form.getElementsByName`, but that will only return direct children
3547 // and won't include inputs that use the HTML5 `form=` attribute. Since
3548 // the input might not even be in a form. It might not even be in the
3549 // document. Let's just use the local `querySelectorAll` to ensure we don't
3550 // miss anything.
3551 var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
3552
3553 for (var i = 0; i < group.length; i++) {
3554 var otherNode = group[i];
3555 if (otherNode === rootNode || otherNode.form !== rootNode.form) {
3556 continue;
3557 }
3558 // This will throw if radio buttons rendered by different copies of React
3559 // and the same name are rendered into the same form (same as #1939).
3560 // That's probably okay; we don't support it just as we don't support
3561 // mixing React radio buttons with non-React ones.
3562 var otherProps = getFiberCurrentPropsFromNode$1(otherNode);
3563 !otherProps ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : void 0;
3564
3565 // We need update the tracked value on the named cousin since the value
3566 // was changed but the input saw no event or value set
3567 updateValueIfChanged(otherNode);
3568
3569 // If this is a controlled radio button group, forcing the input that
3570 // was previously checked to update will cause it to be come re-checked
3571 // as appropriate.
3572 updateWrapper(otherNode, otherProps);
3573 }
3574 }
3575}
3576
3577// In Chrome, assigning defaultValue to certain input types triggers input validation.
3578// For number inputs, the display value loses trailing decimal points. For email inputs,
3579// Chrome raises "The specified value <x> is not a valid email address".
3580//
3581// Here we check to see if the defaultValue has actually changed, avoiding these problems
3582// when the user is inputting text
3583//
3584// https://github.com/facebook/react/issues/7253
3585function setDefaultValue(node, type, value) {
3586 if (
3587 // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
3588 type !== 'number' || node.ownerDocument.activeElement !== node) {
3589 if (value == null) {
3590 node.defaultValue = toString(node._wrapperState.initialValue);
3591 } else if (node.defaultValue !== toString(value)) {
3592 node.defaultValue = toString(value);
3593 }
3594 }
3595}
3596
3597var eventTypes$1 = {
3598 change: {
3599 phasedRegistrationNames: {
3600 bubbled: 'onChange',
3601 captured: 'onChangeCapture'
3602 },
3603 dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE]
3604 }
3605};
3606
3607function createAndAccumulateChangeEvent(inst, nativeEvent, target) {
3608 var event = SyntheticEvent.getPooled(eventTypes$1.change, inst, nativeEvent, target);
3609 event.type = 'change';
3610 // Flag this event loop as needing state restore.
3611 enqueueStateRestore(target);
3612 accumulateTwoPhaseDispatches(event);
3613 return event;
3614}
3615/**
3616 * For IE shims
3617 */
3618var activeElement = null;
3619var activeElementInst = null;
3620
3621/**
3622 * SECTION: handle `change` event
3623 */
3624function shouldUseChangeEvent(elem) {
3625 var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
3626 return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
3627}
3628
3629function manualDispatchChangeEvent(nativeEvent) {
3630 var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent));
3631
3632 // If change and propertychange bubbled, we'd just bind to it like all the
3633 // other events and have it go through ReactBrowserEventEmitter. Since it
3634 // doesn't, we manually listen for the events and so we have to enqueue and
3635 // process the abstract event manually.
3636 //
3637 // Batching is necessary here in order to ensure that all event handlers run
3638 // before the next rerender (including event handlers attached to ancestor
3639 // elements instead of directly on the input). Without this, controlled
3640 // components don't work properly in conjunction with event bubbling because
3641 // the component is rerendered and the value reverted before all the event
3642 // handlers can run. See https://github.com/facebook/react/issues/708.
3643 batchedUpdates(runEventInBatch, event);
3644}
3645
3646function runEventInBatch(event) {
3647 runEventsInBatch(event);
3648}
3649
3650function getInstIfValueChanged(targetInst) {
3651 var targetNode = getNodeFromInstance$1(targetInst);
3652 if (updateValueIfChanged(targetNode)) {
3653 return targetInst;
3654 }
3655}
3656
3657function getTargetInstForChangeEvent(topLevelType, targetInst) {
3658 if (topLevelType === TOP_CHANGE) {
3659 return targetInst;
3660 }
3661}
3662
3663/**
3664 * SECTION: handle `input` event
3665 */
3666var isInputEventSupported = false;
3667if (canUseDOM) {
3668 // IE9 claims to support the input event but fails to trigger it when
3669 // deleting text, so we ignore its input events.
3670 isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
3671}
3672
3673/**
3674 * (For IE <=9) Starts tracking propertychange events on the passed-in element
3675 * and override the value property so that we can distinguish user events from
3676 * value changes in JS.
3677 */
3678function startWatchingForValueChange(target, targetInst) {
3679 activeElement = target;
3680 activeElementInst = targetInst;
3681 activeElement.attachEvent('onpropertychange', handlePropertyChange);
3682}
3683
3684/**
3685 * (For IE <=9) Removes the event listeners from the currently-tracked element,
3686 * if any exists.
3687 */
3688function stopWatchingForValueChange() {
3689 if (!activeElement) {
3690 return;
3691 }
3692 activeElement.detachEvent('onpropertychange', handlePropertyChange);
3693 activeElement = null;
3694 activeElementInst = null;
3695}
3696
3697/**
3698 * (For IE <=9) Handles a propertychange event, sending a `change` event if
3699 * the value of the active element has changed.
3700 */
3701function handlePropertyChange(nativeEvent) {
3702 if (nativeEvent.propertyName !== 'value') {
3703 return;
3704 }
3705 if (getInstIfValueChanged(activeElementInst)) {
3706 manualDispatchChangeEvent(nativeEvent);
3707 }
3708}
3709
3710function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
3711 if (topLevelType === TOP_FOCUS) {
3712 // In IE9, propertychange fires for most input events but is buggy and
3713 // doesn't fire when text is deleted, but conveniently, selectionchange
3714 // appears to fire in all of the remaining cases so we catch those and
3715 // forward the event if the value has changed
3716 // In either case, we don't want to call the event handler if the value
3717 // is changed from JS so we redefine a setter for `.value` that updates
3718 // our activeElementValue variable, allowing us to ignore those changes
3719 //
3720 // stopWatching() should be a noop here but we call it just in case we
3721 // missed a blur event somehow.
3722 stopWatchingForValueChange();
3723 startWatchingForValueChange(target, targetInst);
3724 } else if (topLevelType === TOP_BLUR) {
3725 stopWatchingForValueChange();
3726 }
3727}
3728
3729// For IE8 and IE9.
3730function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {
3731 if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {
3732 // On the selectionchange event, the target is just document which isn't
3733 // helpful for us so just check activeElement instead.
3734 //
3735 // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
3736 // propertychange on the first input event after setting `value` from a
3737 // script and fires only keydown, keypress, keyup. Catching keyup usually
3738 // gets it and catching keydown lets us fire an event for the first
3739 // keystroke if user does a key repeat (it'll be a little delayed: right
3740 // before the second keystroke). Other input methods (e.g., paste) seem to
3741 // fire selectionchange normally.
3742 return getInstIfValueChanged(activeElementInst);
3743 }
3744}
3745
3746/**
3747 * SECTION: handle `click` event
3748 */
3749function shouldUseClickEvent(elem) {
3750 // Use the `click` event to detect changes to checkbox and radio inputs.
3751 // This approach works across all browsers, whereas `change` does not fire
3752 // until `blur` in IE8.
3753 var nodeName = elem.nodeName;
3754 return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
3755}
3756
3757function getTargetInstForClickEvent(topLevelType, targetInst) {
3758 if (topLevelType === TOP_CLICK) {
3759 return getInstIfValueChanged(targetInst);
3760 }
3761}
3762
3763function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {
3764 if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) {
3765 return getInstIfValueChanged(targetInst);
3766 }
3767}
3768
3769function handleControlledInputBlur(node) {
3770 var state = node._wrapperState;
3771
3772 if (!state || !state.controlled || node.type !== 'number') {
3773 return;
3774 }
3775
3776 if (!disableInputAttributeSyncing) {
3777 // If controlled, assign the value attribute to the current value on blur
3778 setDefaultValue(node, 'number', node.value);
3779 }
3780}
3781
3782/**
3783 * This plugin creates an `onChange` event that normalizes change events
3784 * across form elements. This event fires at a time when it's possible to
3785 * change the element's value without seeing a flicker.
3786 *
3787 * Supported elements are:
3788 * - input (see `isTextInputElement`)
3789 * - textarea
3790 * - select
3791 */
3792var ChangeEventPlugin = {
3793 eventTypes: eventTypes$1,
3794
3795 _isInputEventSupported: isInputEventSupported,
3796
3797 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
3798 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
3799
3800 var getTargetInstFunc = void 0,
3801 handleEventFunc = void 0;
3802 if (shouldUseChangeEvent(targetNode)) {
3803 getTargetInstFunc = getTargetInstForChangeEvent;
3804 } else if (isTextInputElement(targetNode)) {
3805 if (isInputEventSupported) {
3806 getTargetInstFunc = getTargetInstForInputOrChangeEvent;
3807 } else {
3808 getTargetInstFunc = getTargetInstForInputEventPolyfill;
3809 handleEventFunc = handleEventsForInputEventPolyfill;
3810 }
3811 } else if (shouldUseClickEvent(targetNode)) {
3812 getTargetInstFunc = getTargetInstForClickEvent;
3813 }
3814
3815 if (getTargetInstFunc) {
3816 var inst = getTargetInstFunc(topLevelType, targetInst);
3817 if (inst) {
3818 var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget);
3819 return event;
3820 }
3821 }
3822
3823 if (handleEventFunc) {
3824 handleEventFunc(topLevelType, targetNode, targetInst);
3825 }
3826
3827 // When blurring, set the value attribute for number inputs
3828 if (topLevelType === TOP_BLUR) {
3829 handleControlledInputBlur(targetNode);
3830 }
3831 }
3832};
3833
3834/**
3835 * Module that is injectable into `EventPluginHub`, that specifies a
3836 * deterministic ordering of `EventPlugin`s. A convenient way to reason about
3837 * plugins, without having to package every one of them. This is better than
3838 * having plugins be ordered in the same order that they are injected because
3839 * that ordering would be influenced by the packaging order.
3840 * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
3841 * preventing default on events is convenient in `SimpleEventPlugin` handlers.
3842 */
3843var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];
3844
3845var SyntheticUIEvent = SyntheticEvent.extend({
3846 view: null,
3847 detail: null
3848});
3849
3850var modifierKeyToProp = {
3851 Alt: 'altKey',
3852 Control: 'ctrlKey',
3853 Meta: 'metaKey',
3854 Shift: 'shiftKey'
3855};
3856
3857// Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
3858// getModifierState. If getModifierState is not supported, we map it to a set of
3859// modifier keys exposed by the event. In this case, Lock-keys are not supported.
3860/**
3861 * Translation from modifier key to the associated property in the event.
3862 * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
3863 */
3864
3865function modifierStateGetter(keyArg) {
3866 var syntheticEvent = this;
3867 var nativeEvent = syntheticEvent.nativeEvent;
3868 if (nativeEvent.getModifierState) {
3869 return nativeEvent.getModifierState(keyArg);
3870 }
3871 var keyProp = modifierKeyToProp[keyArg];
3872 return keyProp ? !!nativeEvent[keyProp] : false;
3873}
3874
3875function getEventModifierState(nativeEvent) {
3876 return modifierStateGetter;
3877}
3878
3879var previousScreenX = 0;
3880var previousScreenY = 0;
3881// Use flags to signal movementX/Y has already been set
3882var isMovementXSet = false;
3883var isMovementYSet = false;
3884
3885/**
3886 * @interface MouseEvent
3887 * @see http://www.w3.org/TR/DOM-Level-3-Events/
3888 */
3889var SyntheticMouseEvent = SyntheticUIEvent.extend({
3890 screenX: null,
3891 screenY: null,
3892 clientX: null,
3893 clientY: null,
3894 pageX: null,
3895 pageY: null,
3896 ctrlKey: null,
3897 shiftKey: null,
3898 altKey: null,
3899 metaKey: null,
3900 getModifierState: getEventModifierState,
3901 button: null,
3902 buttons: null,
3903 relatedTarget: function (event) {
3904 return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
3905 },
3906 movementX: function (event) {
3907 if ('movementX' in event) {
3908 return event.movementX;
3909 }
3910
3911 var screenX = previousScreenX;
3912 previousScreenX = event.screenX;
3913
3914 if (!isMovementXSet) {
3915 isMovementXSet = true;
3916 return 0;
3917 }
3918
3919 return event.type === 'mousemove' ? event.screenX - screenX : 0;
3920 },
3921 movementY: function (event) {
3922 if ('movementY' in event) {
3923 return event.movementY;
3924 }
3925
3926 var screenY = previousScreenY;
3927 previousScreenY = event.screenY;
3928
3929 if (!isMovementYSet) {
3930 isMovementYSet = true;
3931 return 0;
3932 }
3933
3934 return event.type === 'mousemove' ? event.screenY - screenY : 0;
3935 }
3936});
3937
3938/**
3939 * @interface PointerEvent
3940 * @see http://www.w3.org/TR/pointerevents/
3941 */
3942var SyntheticPointerEvent = SyntheticMouseEvent.extend({
3943 pointerId: null,
3944 width: null,
3945 height: null,
3946 pressure: null,
3947 tangentialPressure: null,
3948 tiltX: null,
3949 tiltY: null,
3950 twist: null,
3951 pointerType: null,
3952 isPrimary: null
3953});
3954
3955var eventTypes$2 = {
3956 mouseEnter: {
3957 registrationName: 'onMouseEnter',
3958 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
3959 },
3960 mouseLeave: {
3961 registrationName: 'onMouseLeave',
3962 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
3963 },
3964 pointerEnter: {
3965 registrationName: 'onPointerEnter',
3966 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
3967 },
3968 pointerLeave: {
3969 registrationName: 'onPointerLeave',
3970 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
3971 }
3972};
3973
3974var EnterLeaveEventPlugin = {
3975 eventTypes: eventTypes$2,
3976
3977 /**
3978 * For almost every interaction we care about, there will be both a top-level
3979 * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
3980 * we do not extract duplicate events. However, moving the mouse into the
3981 * browser from outside will not fire a `mouseout` event. In this case, we use
3982 * the `mouseover` top-level event.
3983 */
3984 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
3985 var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
3986 var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;
3987
3988 if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
3989 return null;
3990 }
3991
3992 if (!isOutEvent && !isOverEvent) {
3993 // Must not be a mouse or pointer in or out - ignoring.
3994 return null;
3995 }
3996
3997 var win = void 0;
3998 if (nativeEventTarget.window === nativeEventTarget) {
3999 // `nativeEventTarget` is probably a window object.
4000 win = nativeEventTarget;
4001 } else {
4002 // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
4003 var doc = nativeEventTarget.ownerDocument;
4004 if (doc) {
4005 win = doc.defaultView || doc.parentWindow;
4006 } else {
4007 win = window;
4008 }
4009 }
4010
4011 var from = void 0;
4012 var to = void 0;
4013 if (isOutEvent) {
4014 from = targetInst;
4015 var related = nativeEvent.relatedTarget || nativeEvent.toElement;
4016 to = related ? getClosestInstanceFromNode(related) : null;
4017 } else {
4018 // Moving to a node from outside the window.
4019 from = null;
4020 to = targetInst;
4021 }
4022
4023 if (from === to) {
4024 // Nothing pertains to our managed components.
4025 return null;
4026 }
4027
4028 var eventInterface = void 0,
4029 leaveEventType = void 0,
4030 enterEventType = void 0,
4031 eventTypePrefix = void 0;
4032
4033 if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
4034 eventInterface = SyntheticMouseEvent;
4035 leaveEventType = eventTypes$2.mouseLeave;
4036 enterEventType = eventTypes$2.mouseEnter;
4037 eventTypePrefix = 'mouse';
4038 } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {
4039 eventInterface = SyntheticPointerEvent;
4040 leaveEventType = eventTypes$2.pointerLeave;
4041 enterEventType = eventTypes$2.pointerEnter;
4042 eventTypePrefix = 'pointer';
4043 }
4044
4045 var fromNode = from == null ? win : getNodeFromInstance$1(from);
4046 var toNode = to == null ? win : getNodeFromInstance$1(to);
4047
4048 var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);
4049 leave.type = eventTypePrefix + 'leave';
4050 leave.target = fromNode;
4051 leave.relatedTarget = toNode;
4052
4053 var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);
4054 enter.type = eventTypePrefix + 'enter';
4055 enter.target = toNode;
4056 enter.relatedTarget = fromNode;
4057
4058 accumulateEnterLeaveDispatches(leave, enter, from, to);
4059
4060 return [leave, enter];
4061 }
4062};
4063
4064/**
4065 * inlined Object.is polyfill to avoid requiring consumers ship their own
4066 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
4067 */
4068function is(x, y) {
4069 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
4070 ;
4071}
4072
4073var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
4074
4075/**
4076 * Performs equality by iterating through keys on an object and returning false
4077 * when any key has values which are not strictly equal between the arguments.
4078 * Returns true when the values of all keys are strictly equal.
4079 */
4080function shallowEqual(objA, objB) {
4081 if (is(objA, objB)) {
4082 return true;
4083 }
4084
4085 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
4086 return false;
4087 }
4088
4089 var keysA = Object.keys(objA);
4090 var keysB = Object.keys(objB);
4091
4092 if (keysA.length !== keysB.length) {
4093 return false;
4094 }
4095
4096 // Test for A's keys different from B.
4097 for (var i = 0; i < keysA.length; i++) {
4098 if (!hasOwnProperty$1.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
4099 return false;
4100 }
4101 }
4102
4103 return true;
4104}
4105
4106/**
4107 * `ReactInstanceMap` maintains a mapping from a public facing stateful
4108 * instance (key) and the internal representation (value). This allows public
4109 * methods to accept the user facing instance as an argument and map them back
4110 * to internal methods.
4111 *
4112 * Note that this module is currently shared and assumed to be stateless.
4113 * If this becomes an actual Map, that will break.
4114 */
4115
4116/**
4117 * This API should be called `delete` but we'd have to make sure to always
4118 * transform these to strings for IE support. When this transform is fully
4119 * supported we can rename it.
4120 */
4121
4122
4123function get(key) {
4124 return key._reactInternalFiber;
4125}
4126
4127function has(key) {
4128 return key._reactInternalFiber !== undefined;
4129}
4130
4131function set(key, value) {
4132 key._reactInternalFiber = value;
4133}
4134
4135// Don't change these two values. They're used by React Dev Tools.
4136var NoEffect = /* */0;
4137var PerformedWork = /* */1;
4138
4139// You can change the rest (and add more).
4140var Placement = /* */2;
4141var Update = /* */4;
4142var PlacementAndUpdate = /* */6;
4143var Deletion = /* */8;
4144var ContentReset = /* */16;
4145var Callback = /* */32;
4146var DidCapture = /* */64;
4147var Ref = /* */128;
4148var Snapshot = /* */256;
4149var Passive = /* */512;
4150
4151// Passive & Update & Callback & Ref & Snapshot
4152var LifecycleEffectMask = /* */932;
4153
4154// Union of all host effects
4155var HostEffectMask = /* */1023;
4156
4157var Incomplete = /* */1024;
4158var ShouldCapture = /* */2048;
4159
4160var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
4161
4162var MOUNTING = 1;
4163var MOUNTED = 2;
4164var UNMOUNTED = 3;
4165
4166function isFiberMountedImpl(fiber) {
4167 var node = fiber;
4168 if (!fiber.alternate) {
4169 // If there is no alternate, this might be a new tree that isn't inserted
4170 // yet. If it is, then it will have a pending insertion effect on it.
4171 if ((node.effectTag & Placement) !== NoEffect) {
4172 return MOUNTING;
4173 }
4174 while (node.return) {
4175 node = node.return;
4176 if ((node.effectTag & Placement) !== NoEffect) {
4177 return MOUNTING;
4178 }
4179 }
4180 } else {
4181 while (node.return) {
4182 node = node.return;
4183 }
4184 }
4185 if (node.tag === HostRoot) {
4186 // TODO: Check if this was a nested HostRoot when used with
4187 // renderContainerIntoSubtree.
4188 return MOUNTED;
4189 }
4190 // If we didn't hit the root, that means that we're in an disconnected tree
4191 // that has been unmounted.
4192 return UNMOUNTED;
4193}
4194
4195function isFiberMounted(fiber) {
4196 return isFiberMountedImpl(fiber) === MOUNTED;
4197}
4198
4199function isMounted(component) {
4200 {
4201 var owner = ReactCurrentOwner$1.current;
4202 if (owner !== null && owner.tag === ClassComponent) {
4203 var ownerFiber = owner;
4204 var instance = ownerFiber.stateNode;
4205 !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;
4206 instance._warnedAboutRefsInRender = true;
4207 }
4208 }
4209
4210 var fiber = get(component);
4211 if (!fiber) {
4212 return false;
4213 }
4214 return isFiberMountedImpl(fiber) === MOUNTED;
4215}
4216
4217function assertIsMounted(fiber) {
4218 !(isFiberMountedImpl(fiber) === MOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
4219}
4220
4221function findCurrentFiberUsingSlowPath(fiber) {
4222 var alternate = fiber.alternate;
4223 if (!alternate) {
4224 // If there is no alternate, then we only need to check if it is mounted.
4225 var state = isFiberMountedImpl(fiber);
4226 !(state !== UNMOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
4227 if (state === MOUNTING) {
4228 return null;
4229 }
4230 return fiber;
4231 }
4232 // If we have two possible branches, we'll walk backwards up to the root
4233 // to see what path the root points to. On the way we may hit one of the
4234 // special cases and we'll deal with them.
4235 var a = fiber;
4236 var b = alternate;
4237 while (true) {
4238 var parentA = a.return;
4239 var parentB = parentA ? parentA.alternate : null;
4240 if (!parentA || !parentB) {
4241 // We're at the root.
4242 break;
4243 }
4244
4245 // If both copies of the parent fiber point to the same child, we can
4246 // assume that the child is current. This happens when we bailout on low
4247 // priority: the bailed out fiber's child reuses the current child.
4248 if (parentA.child === parentB.child) {
4249 var child = parentA.child;
4250 while (child) {
4251 if (child === a) {
4252 // We've determined that A is the current branch.
4253 assertIsMounted(parentA);
4254 return fiber;
4255 }
4256 if (child === b) {
4257 // We've determined that B is the current branch.
4258 assertIsMounted(parentA);
4259 return alternate;
4260 }
4261 child = child.sibling;
4262 }
4263 // We should never have an alternate for any mounting node. So the only
4264 // way this could possibly happen is if this was unmounted, if at all.
4265 invariant(false, 'Unable to find node on an unmounted component.');
4266 }
4267
4268 if (a.return !== b.return) {
4269 // The return pointer of A and the return pointer of B point to different
4270 // fibers. We assume that return pointers never criss-cross, so A must
4271 // belong to the child set of A.return, and B must belong to the child
4272 // set of B.return.
4273 a = parentA;
4274 b = parentB;
4275 } else {
4276 // The return pointers point to the same fiber. We'll have to use the
4277 // default, slow path: scan the child sets of each parent alternate to see
4278 // which child belongs to which set.
4279 //
4280 // Search parent A's child set
4281 var didFindChild = false;
4282 var _child = parentA.child;
4283 while (_child) {
4284 if (_child === a) {
4285 didFindChild = true;
4286 a = parentA;
4287 b = parentB;
4288 break;
4289 }
4290 if (_child === b) {
4291 didFindChild = true;
4292 b = parentA;
4293 a = parentB;
4294 break;
4295 }
4296 _child = _child.sibling;
4297 }
4298 if (!didFindChild) {
4299 // Search parent B's child set
4300 _child = parentB.child;
4301 while (_child) {
4302 if (_child === a) {
4303 didFindChild = true;
4304 a = parentB;
4305 b = parentA;
4306 break;
4307 }
4308 if (_child === b) {
4309 didFindChild = true;
4310 b = parentB;
4311 a = parentA;
4312 break;
4313 }
4314 _child = _child.sibling;
4315 }
4316 !didFindChild ? invariant(false, 'Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.') : void 0;
4317 }
4318 }
4319
4320 !(a.alternate === b) ? invariant(false, 'Return fibers should always be each others\' alternates. This error is likely caused by a bug in React. Please file an issue.') : void 0;
4321 }
4322 // If the root is not a host container, we're in a disconnected tree. I.e.
4323 // unmounted.
4324 !(a.tag === HostRoot) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
4325 if (a.stateNode.current === a) {
4326 // We've determined that A is the current branch.
4327 return fiber;
4328 }
4329 // Otherwise B has to be current branch.
4330 return alternate;
4331}
4332
4333function findCurrentHostFiber(parent) {
4334 var currentParent = findCurrentFiberUsingSlowPath(parent);
4335 if (!currentParent) {
4336 return null;
4337 }
4338
4339 // Next we'll drill down this component to find the first HostComponent/Text.
4340 var node = currentParent;
4341 while (true) {
4342 if (node.tag === HostComponent || node.tag === HostText) {
4343 return node;
4344 } else if (node.child) {
4345 node.child.return = node;
4346 node = node.child;
4347 continue;
4348 }
4349 if (node === currentParent) {
4350 return null;
4351 }
4352 while (!node.sibling) {
4353 if (!node.return || node.return === currentParent) {
4354 return null;
4355 }
4356 node = node.return;
4357 }
4358 node.sibling.return = node.return;
4359 node = node.sibling;
4360 }
4361 // Flow needs the return null here, but ESLint complains about it.
4362 // eslint-disable-next-line no-unreachable
4363 return null;
4364}
4365
4366function findCurrentHostFiberWithNoPortals(parent) {
4367 var currentParent = findCurrentFiberUsingSlowPath(parent);
4368 if (!currentParent) {
4369 return null;
4370 }
4371
4372 // Next we'll drill down this component to find the first HostComponent/Text.
4373 var node = currentParent;
4374 while (true) {
4375 if (node.tag === HostComponent || node.tag === HostText) {
4376 return node;
4377 } else if (node.child && node.tag !== HostPortal) {
4378 node.child.return = node;
4379 node = node.child;
4380 continue;
4381 }
4382 if (node === currentParent) {
4383 return null;
4384 }
4385 while (!node.sibling) {
4386 if (!node.return || node.return === currentParent) {
4387 return null;
4388 }
4389 node = node.return;
4390 }
4391 node.sibling.return = node.return;
4392 node = node.sibling;
4393 }
4394 // Flow needs the return null here, but ESLint complains about it.
4395 // eslint-disable-next-line no-unreachable
4396 return null;
4397}
4398
4399function addEventBubbleListener(element, eventType, listener) {
4400 element.addEventListener(eventType, listener, false);
4401}
4402
4403function addEventCaptureListener(element, eventType, listener) {
4404 element.addEventListener(eventType, listener, true);
4405}
4406
4407/**
4408 * @interface Event
4409 * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
4410 * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
4411 */
4412var SyntheticAnimationEvent = SyntheticEvent.extend({
4413 animationName: null,
4414 elapsedTime: null,
4415 pseudoElement: null
4416});
4417
4418/**
4419 * @interface Event
4420 * @see http://www.w3.org/TR/clipboard-apis/
4421 */
4422var SyntheticClipboardEvent = SyntheticEvent.extend({
4423 clipboardData: function (event) {
4424 return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
4425 }
4426});
4427
4428/**
4429 * @interface FocusEvent
4430 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4431 */
4432var SyntheticFocusEvent = SyntheticUIEvent.extend({
4433 relatedTarget: null
4434});
4435
4436/**
4437 * `charCode` represents the actual "character code" and is safe to use with
4438 * `String.fromCharCode`. As such, only keys that correspond to printable
4439 * characters produce a valid `charCode`, the only exception to this is Enter.
4440 * The Tab-key is considered non-printable and does not have a `charCode`,
4441 * presumably because it does not produce a tab-character in browsers.
4442 *
4443 * @param {object} nativeEvent Native browser event.
4444 * @return {number} Normalized `charCode` property.
4445 */
4446function getEventCharCode(nativeEvent) {
4447 var charCode = void 0;
4448 var keyCode = nativeEvent.keyCode;
4449
4450 if ('charCode' in nativeEvent) {
4451 charCode = nativeEvent.charCode;
4452
4453 // FF does not set `charCode` for the Enter-key, check against `keyCode`.
4454 if (charCode === 0 && keyCode === 13) {
4455 charCode = 13;
4456 }
4457 } else {
4458 // IE8 does not implement `charCode`, but `keyCode` has the correct value.
4459 charCode = keyCode;
4460 }
4461
4462 // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
4463 // report Enter as charCode 10 when ctrl is pressed.
4464 if (charCode === 10) {
4465 charCode = 13;
4466 }
4467
4468 // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
4469 // Must not discard the (non-)printable Enter-key.
4470 if (charCode >= 32 || charCode === 13) {
4471 return charCode;
4472 }
4473
4474 return 0;
4475}
4476
4477/**
4478 * Normalization of deprecated HTML5 `key` values
4479 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
4480 */
4481var normalizeKey = {
4482 Esc: 'Escape',
4483 Spacebar: ' ',
4484 Left: 'ArrowLeft',
4485 Up: 'ArrowUp',
4486 Right: 'ArrowRight',
4487 Down: 'ArrowDown',
4488 Del: 'Delete',
4489 Win: 'OS',
4490 Menu: 'ContextMenu',
4491 Apps: 'ContextMenu',
4492 Scroll: 'ScrollLock',
4493 MozPrintableKey: 'Unidentified'
4494};
4495
4496/**
4497 * Translation from legacy `keyCode` to HTML5 `key`
4498 * Only special keys supported, all others depend on keyboard layout or browser
4499 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
4500 */
4501var translateToKey = {
4502 '8': 'Backspace',
4503 '9': 'Tab',
4504 '12': 'Clear',
4505 '13': 'Enter',
4506 '16': 'Shift',
4507 '17': 'Control',
4508 '18': 'Alt',
4509 '19': 'Pause',
4510 '20': 'CapsLock',
4511 '27': 'Escape',
4512 '32': ' ',
4513 '33': 'PageUp',
4514 '34': 'PageDown',
4515 '35': 'End',
4516 '36': 'Home',
4517 '37': 'ArrowLeft',
4518 '38': 'ArrowUp',
4519 '39': 'ArrowRight',
4520 '40': 'ArrowDown',
4521 '45': 'Insert',
4522 '46': 'Delete',
4523 '112': 'F1',
4524 '113': 'F2',
4525 '114': 'F3',
4526 '115': 'F4',
4527 '116': 'F5',
4528 '117': 'F6',
4529 '118': 'F7',
4530 '119': 'F8',
4531 '120': 'F9',
4532 '121': 'F10',
4533 '122': 'F11',
4534 '123': 'F12',
4535 '144': 'NumLock',
4536 '145': 'ScrollLock',
4537 '224': 'Meta'
4538};
4539
4540/**
4541 * @param {object} nativeEvent Native browser event.
4542 * @return {string} Normalized `key` property.
4543 */
4544function getEventKey(nativeEvent) {
4545 if (nativeEvent.key) {
4546 // Normalize inconsistent values reported by browsers due to
4547 // implementations of a working draft specification.
4548
4549 // FireFox implements `key` but returns `MozPrintableKey` for all
4550 // printable characters (normalized to `Unidentified`), ignore it.
4551 var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
4552 if (key !== 'Unidentified') {
4553 return key;
4554 }
4555 }
4556
4557 // Browser does not implement `key`, polyfill as much of it as we can.
4558 if (nativeEvent.type === 'keypress') {
4559 var charCode = getEventCharCode(nativeEvent);
4560
4561 // The enter-key is technically both printable and non-printable and can
4562 // thus be captured by `keypress`, no other non-printable key should.
4563 return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
4564 }
4565 if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
4566 // While user keyboard layout determines the actual meaning of each
4567 // `keyCode` value, almost all function keys have a universal value.
4568 return translateToKey[nativeEvent.keyCode] || 'Unidentified';
4569 }
4570 return '';
4571}
4572
4573/**
4574 * @interface KeyboardEvent
4575 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4576 */
4577var SyntheticKeyboardEvent = SyntheticUIEvent.extend({
4578 key: getEventKey,
4579 location: null,
4580 ctrlKey: null,
4581 shiftKey: null,
4582 altKey: null,
4583 metaKey: null,
4584 repeat: null,
4585 locale: null,
4586 getModifierState: getEventModifierState,
4587 // Legacy Interface
4588 charCode: function (event) {
4589 // `charCode` is the result of a KeyPress event and represents the value of
4590 // the actual printable character.
4591
4592 // KeyPress is deprecated, but its replacement is not yet final and not
4593 // implemented in any major browser. Only KeyPress has charCode.
4594 if (event.type === 'keypress') {
4595 return getEventCharCode(event);
4596 }
4597 return 0;
4598 },
4599 keyCode: function (event) {
4600 // `keyCode` is the result of a KeyDown/Up event and represents the value of
4601 // physical keyboard key.
4602
4603 // The actual meaning of the value depends on the users' keyboard layout
4604 // which cannot be detected. Assuming that it is a US keyboard layout
4605 // provides a surprisingly accurate mapping for US and European users.
4606 // Due to this, it is left to the user to implement at this time.
4607 if (event.type === 'keydown' || event.type === 'keyup') {
4608 return event.keyCode;
4609 }
4610 return 0;
4611 },
4612 which: function (event) {
4613 // `which` is an alias for either `keyCode` or `charCode` depending on the
4614 // type of the event.
4615 if (event.type === 'keypress') {
4616 return getEventCharCode(event);
4617 }
4618 if (event.type === 'keydown' || event.type === 'keyup') {
4619 return event.keyCode;
4620 }
4621 return 0;
4622 }
4623});
4624
4625/**
4626 * @interface DragEvent
4627 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4628 */
4629var SyntheticDragEvent = SyntheticMouseEvent.extend({
4630 dataTransfer: null
4631});
4632
4633/**
4634 * @interface TouchEvent
4635 * @see http://www.w3.org/TR/touch-events/
4636 */
4637var SyntheticTouchEvent = SyntheticUIEvent.extend({
4638 touches: null,
4639 targetTouches: null,
4640 changedTouches: null,
4641 altKey: null,
4642 metaKey: null,
4643 ctrlKey: null,
4644 shiftKey: null,
4645 getModifierState: getEventModifierState
4646});
4647
4648/**
4649 * @interface Event
4650 * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
4651 * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
4652 */
4653var SyntheticTransitionEvent = SyntheticEvent.extend({
4654 propertyName: null,
4655 elapsedTime: null,
4656 pseudoElement: null
4657});
4658
4659/**
4660 * @interface WheelEvent
4661 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4662 */
4663var SyntheticWheelEvent = SyntheticMouseEvent.extend({
4664 deltaX: function (event) {
4665 return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
4666 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
4667 },
4668 deltaY: function (event) {
4669 return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
4670 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
4671 'wheelDelta' in event ? -event.wheelDelta : 0;
4672 },
4673
4674 deltaZ: null,
4675
4676 // Browsers without "deltaMode" is reporting in raw wheel delta where one
4677 // notch on the scroll is always +/- 120, roughly equivalent to pixels.
4678 // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
4679 // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
4680 deltaMode: null
4681});
4682
4683/**
4684 * Turns
4685 * ['abort', ...]
4686 * into
4687 * eventTypes = {
4688 * 'abort': {
4689 * phasedRegistrationNames: {
4690 * bubbled: 'onAbort',
4691 * captured: 'onAbortCapture',
4692 * },
4693 * dependencies: [TOP_ABORT],
4694 * },
4695 * ...
4696 * };
4697 * topLevelEventsToDispatchConfig = new Map([
4698 * [TOP_ABORT, { sameConfig }],
4699 * ]);
4700 */
4701
4702var interactiveEventTypeNames = [[TOP_BLUR, 'blur'], [TOP_CANCEL, 'cancel'], [TOP_CLICK, 'click'], [TOP_CLOSE, 'close'], [TOP_CONTEXT_MENU, 'contextMenu'], [TOP_COPY, 'copy'], [TOP_CUT, 'cut'], [TOP_AUX_CLICK, 'auxClick'], [TOP_DOUBLE_CLICK, 'doubleClick'], [TOP_DRAG_END, 'dragEnd'], [TOP_DRAG_START, 'dragStart'], [TOP_DROP, 'drop'], [TOP_FOCUS, 'focus'], [TOP_INPUT, 'input'], [TOP_INVALID, 'invalid'], [TOP_KEY_DOWN, 'keyDown'], [TOP_KEY_PRESS, 'keyPress'], [TOP_KEY_UP, 'keyUp'], [TOP_MOUSE_DOWN, 'mouseDown'], [TOP_MOUSE_UP, 'mouseUp'], [TOP_PASTE, 'paste'], [TOP_PAUSE, 'pause'], [TOP_PLAY, 'play'], [TOP_POINTER_CANCEL, 'pointerCancel'], [TOP_POINTER_DOWN, 'pointerDown'], [TOP_POINTER_UP, 'pointerUp'], [TOP_RATE_CHANGE, 'rateChange'], [TOP_RESET, 'reset'], [TOP_SEEKED, 'seeked'], [TOP_SUBMIT, 'submit'], [TOP_TOUCH_CANCEL, 'touchCancel'], [TOP_TOUCH_END, 'touchEnd'], [TOP_TOUCH_START, 'touchStart'], [TOP_VOLUME_CHANGE, 'volumeChange']];
4703var nonInteractiveEventTypeNames = [[TOP_ABORT, 'abort'], [TOP_ANIMATION_END, 'animationEnd'], [TOP_ANIMATION_ITERATION, 'animationIteration'], [TOP_ANIMATION_START, 'animationStart'], [TOP_CAN_PLAY, 'canPlay'], [TOP_CAN_PLAY_THROUGH, 'canPlayThrough'], [TOP_DRAG, 'drag'], [TOP_DRAG_ENTER, 'dragEnter'], [TOP_DRAG_EXIT, 'dragExit'], [TOP_DRAG_LEAVE, 'dragLeave'], [TOP_DRAG_OVER, 'dragOver'], [TOP_DURATION_CHANGE, 'durationChange'], [TOP_EMPTIED, 'emptied'], [TOP_ENCRYPTED, 'encrypted'], [TOP_ENDED, 'ended'], [TOP_ERROR, 'error'], [TOP_GOT_POINTER_CAPTURE, 'gotPointerCapture'], [TOP_LOAD, 'load'], [TOP_LOADED_DATA, 'loadedData'], [TOP_LOADED_METADATA, 'loadedMetadata'], [TOP_LOAD_START, 'loadStart'], [TOP_LOST_POINTER_CAPTURE, 'lostPointerCapture'], [TOP_MOUSE_MOVE, 'mouseMove'], [TOP_MOUSE_OUT, 'mouseOut'], [TOP_MOUSE_OVER, 'mouseOver'], [TOP_PLAYING, 'playing'], [TOP_POINTER_MOVE, 'pointerMove'], [TOP_POINTER_OUT, 'pointerOut'], [TOP_POINTER_OVER, 'pointerOver'], [TOP_PROGRESS, 'progress'], [TOP_SCROLL, 'scroll'], [TOP_SEEKING, 'seeking'], [TOP_STALLED, 'stalled'], [TOP_SUSPEND, 'suspend'], [TOP_TIME_UPDATE, 'timeUpdate'], [TOP_TOGGLE, 'toggle'], [TOP_TOUCH_MOVE, 'touchMove'], [TOP_TRANSITION_END, 'transitionEnd'], [TOP_WAITING, 'waiting'], [TOP_WHEEL, 'wheel']];
4704
4705var eventTypes$4 = {};
4706var topLevelEventsToDispatchConfig = {};
4707
4708function addEventTypeNameToConfig(_ref, isInteractive) {
4709 var topEvent = _ref[0],
4710 event = _ref[1];
4711
4712 var capitalizedEvent = event[0].toUpperCase() + event.slice(1);
4713 var onEvent = 'on' + capitalizedEvent;
4714
4715 var type = {
4716 phasedRegistrationNames: {
4717 bubbled: onEvent,
4718 captured: onEvent + 'Capture'
4719 },
4720 dependencies: [topEvent],
4721 isInteractive: isInteractive
4722 };
4723 eventTypes$4[event] = type;
4724 topLevelEventsToDispatchConfig[topEvent] = type;
4725}
4726
4727interactiveEventTypeNames.forEach(function (eventTuple) {
4728 addEventTypeNameToConfig(eventTuple, true);
4729});
4730nonInteractiveEventTypeNames.forEach(function (eventTuple) {
4731 addEventTypeNameToConfig(eventTuple, false);
4732});
4733
4734// Only used in DEV for exhaustiveness validation.
4735var 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];
4736
4737var SimpleEventPlugin = {
4738 eventTypes: eventTypes$4,
4739
4740 isInteractiveTopLevelEventType: function (topLevelType) {
4741 var config = topLevelEventsToDispatchConfig[topLevelType];
4742 return config !== undefined && config.isInteractive === true;
4743 },
4744
4745
4746 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
4747 var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
4748 if (!dispatchConfig) {
4749 return null;
4750 }
4751 var EventConstructor = void 0;
4752 switch (topLevelType) {
4753 case TOP_KEY_PRESS:
4754 // Firefox creates a keypress event for function keys too. This removes
4755 // the unwanted keypress events. Enter is however both printable and
4756 // non-printable. One would expect Tab to be as well (but it isn't).
4757 if (getEventCharCode(nativeEvent) === 0) {
4758 return null;
4759 }
4760 /* falls through */
4761 case TOP_KEY_DOWN:
4762 case TOP_KEY_UP:
4763 EventConstructor = SyntheticKeyboardEvent;
4764 break;
4765 case TOP_BLUR:
4766 case TOP_FOCUS:
4767 EventConstructor = SyntheticFocusEvent;
4768 break;
4769 case TOP_CLICK:
4770 // Firefox creates a click event on right mouse clicks. This removes the
4771 // unwanted click events.
4772 if (nativeEvent.button === 2) {
4773 return null;
4774 }
4775 /* falls through */
4776 case TOP_AUX_CLICK:
4777 case TOP_DOUBLE_CLICK:
4778 case TOP_MOUSE_DOWN:
4779 case TOP_MOUSE_MOVE:
4780 case TOP_MOUSE_UP:
4781 // TODO: Disabled elements should not respond to mouse events
4782 /* falls through */
4783 case TOP_MOUSE_OUT:
4784 case TOP_MOUSE_OVER:
4785 case TOP_CONTEXT_MENU:
4786 EventConstructor = SyntheticMouseEvent;
4787 break;
4788 case TOP_DRAG:
4789 case TOP_DRAG_END:
4790 case TOP_DRAG_ENTER:
4791 case TOP_DRAG_EXIT:
4792 case TOP_DRAG_LEAVE:
4793 case TOP_DRAG_OVER:
4794 case TOP_DRAG_START:
4795 case TOP_DROP:
4796 EventConstructor = SyntheticDragEvent;
4797 break;
4798 case TOP_TOUCH_CANCEL:
4799 case TOP_TOUCH_END:
4800 case TOP_TOUCH_MOVE:
4801 case TOP_TOUCH_START:
4802 EventConstructor = SyntheticTouchEvent;
4803 break;
4804 case TOP_ANIMATION_END:
4805 case TOP_ANIMATION_ITERATION:
4806 case TOP_ANIMATION_START:
4807 EventConstructor = SyntheticAnimationEvent;
4808 break;
4809 case TOP_TRANSITION_END:
4810 EventConstructor = SyntheticTransitionEvent;
4811 break;
4812 case TOP_SCROLL:
4813 EventConstructor = SyntheticUIEvent;
4814 break;
4815 case TOP_WHEEL:
4816 EventConstructor = SyntheticWheelEvent;
4817 break;
4818 case TOP_COPY:
4819 case TOP_CUT:
4820 case TOP_PASTE:
4821 EventConstructor = SyntheticClipboardEvent;
4822 break;
4823 case TOP_GOT_POINTER_CAPTURE:
4824 case TOP_LOST_POINTER_CAPTURE:
4825 case TOP_POINTER_CANCEL:
4826 case TOP_POINTER_DOWN:
4827 case TOP_POINTER_MOVE:
4828 case TOP_POINTER_OUT:
4829 case TOP_POINTER_OVER:
4830 case TOP_POINTER_UP:
4831 EventConstructor = SyntheticPointerEvent;
4832 break;
4833 default:
4834 {
4835 if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {
4836 warningWithoutStack$1(false, 'SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType);
4837 }
4838 }
4839 // HTML Events
4840 // @see http://www.w3.org/TR/html5/index.html#events-0
4841 EventConstructor = SyntheticEvent;
4842 break;
4843 }
4844 var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
4845 accumulateTwoPhaseDispatches(event);
4846 return event;
4847 }
4848};
4849
4850var isInteractiveTopLevelEventType = SimpleEventPlugin.isInteractiveTopLevelEventType;
4851
4852
4853var CALLBACK_BOOKKEEPING_POOL_SIZE = 10;
4854var callbackBookkeepingPool = [];
4855
4856/**
4857 * Find the deepest React component completely containing the root of the
4858 * passed-in instance (for use when entire React trees are nested within each
4859 * other). If React trees are not nested, returns null.
4860 */
4861function findRootContainerNode(inst) {
4862 // TODO: It may be a good idea to cache this to prevent unnecessary DOM
4863 // traversal, but caching is difficult to do correctly without using a
4864 // mutation observer to listen for all DOM changes.
4865 while (inst.return) {
4866 inst = inst.return;
4867 }
4868 if (inst.tag !== HostRoot) {
4869 // This can happen if we're in a detached tree.
4870 return null;
4871 }
4872 return inst.stateNode.containerInfo;
4873}
4874
4875// Used to store ancestor hierarchy in top level callback
4876function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst) {
4877 if (callbackBookkeepingPool.length) {
4878 var instance = callbackBookkeepingPool.pop();
4879 instance.topLevelType = topLevelType;
4880 instance.nativeEvent = nativeEvent;
4881 instance.targetInst = targetInst;
4882 return instance;
4883 }
4884 return {
4885 topLevelType: topLevelType,
4886 nativeEvent: nativeEvent,
4887 targetInst: targetInst,
4888 ancestors: []
4889 };
4890}
4891
4892function releaseTopLevelCallbackBookKeeping(instance) {
4893 instance.topLevelType = null;
4894 instance.nativeEvent = null;
4895 instance.targetInst = null;
4896 instance.ancestors.length = 0;
4897 if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) {
4898 callbackBookkeepingPool.push(instance);
4899 }
4900}
4901
4902function handleTopLevel(bookKeeping) {
4903 var targetInst = bookKeeping.targetInst;
4904
4905 // Loop through the hierarchy, in case there's any nested components.
4906 // It's important that we build the array of ancestors before calling any
4907 // event handlers, because event handlers can modify the DOM, leading to
4908 // inconsistencies with ReactMount's node cache. See #1105.
4909 var ancestor = targetInst;
4910 do {
4911 if (!ancestor) {
4912 bookKeeping.ancestors.push(ancestor);
4913 break;
4914 }
4915 var root = findRootContainerNode(ancestor);
4916 if (!root) {
4917 break;
4918 }
4919 bookKeeping.ancestors.push(ancestor);
4920 ancestor = getClosestInstanceFromNode(root);
4921 } while (ancestor);
4922
4923 for (var i = 0; i < bookKeeping.ancestors.length; i++) {
4924 targetInst = bookKeeping.ancestors[i];
4925 runExtractedEventsInBatch(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
4926 }
4927}
4928
4929// TODO: can we stop exporting these?
4930var _enabled = true;
4931
4932function setEnabled(enabled) {
4933 _enabled = !!enabled;
4934}
4935
4936function isEnabled() {
4937 return _enabled;
4938}
4939
4940/**
4941 * Traps top-level events by using event bubbling.
4942 *
4943 * @param {number} topLevelType Number from `TopLevelEventTypes`.
4944 * @param {object} element Element on which to attach listener.
4945 * @return {?object} An object with a remove function which will forcefully
4946 * remove the listener.
4947 * @internal
4948 */
4949function trapBubbledEvent(topLevelType, element) {
4950 if (!element) {
4951 return null;
4952 }
4953 var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent;
4954
4955 addEventBubbleListener(element, getRawEventName(topLevelType),
4956 // Check if interactive and wrap in interactiveUpdates
4957 dispatch.bind(null, topLevelType));
4958}
4959
4960/**
4961 * Traps a top-level event by using event capturing.
4962 *
4963 * @param {number} topLevelType Number from `TopLevelEventTypes`.
4964 * @param {object} element Element on which to attach listener.
4965 * @return {?object} An object with a remove function which will forcefully
4966 * remove the listener.
4967 * @internal
4968 */
4969function trapCapturedEvent(topLevelType, element) {
4970 if (!element) {
4971 return null;
4972 }
4973 var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent;
4974
4975 addEventCaptureListener(element, getRawEventName(topLevelType),
4976 // Check if interactive and wrap in interactiveUpdates
4977 dispatch.bind(null, topLevelType));
4978}
4979
4980function dispatchInteractiveEvent(topLevelType, nativeEvent) {
4981 interactiveUpdates(dispatchEvent, topLevelType, nativeEvent);
4982}
4983
4984function dispatchEvent(topLevelType, nativeEvent) {
4985 if (!_enabled) {
4986 return;
4987 }
4988
4989 var nativeEventTarget = getEventTarget(nativeEvent);
4990 var targetInst = getClosestInstanceFromNode(nativeEventTarget);
4991 if (targetInst !== null && typeof targetInst.tag === 'number' && !isFiberMounted(targetInst)) {
4992 // If we get an event (ex: img onload) before committing that
4993 // component's mount, ignore it for now (that is, treat it as if it was an
4994 // event on a non-React tree). We might also consider queueing events and
4995 // dispatching them after the mount.
4996 targetInst = null;
4997 }
4998
4999 var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst);
5000
5001 try {
5002 // Event queue being processed in the same cycle allows
5003 // `preventDefault`.
5004 batchedUpdates(handleTopLevel, bookKeeping);
5005 } finally {
5006 releaseTopLevelCallbackBookKeeping(bookKeeping);
5007 }
5008}
5009
5010/**
5011 * Summary of `ReactBrowserEventEmitter` event handling:
5012 *
5013 * - Top-level delegation is used to trap most native browser events. This
5014 * may only occur in the main thread and is the responsibility of
5015 * ReactDOMEventListener, which is injected and can therefore support
5016 * pluggable event sources. This is the only work that occurs in the main
5017 * thread.
5018 *
5019 * - We normalize and de-duplicate events to account for browser quirks. This
5020 * may be done in the worker thread.
5021 *
5022 * - Forward these native events (with the associated top-level type used to
5023 * trap it) to `EventPluginHub`, which in turn will ask plugins if they want
5024 * to extract any synthetic events.
5025 *
5026 * - The `EventPluginHub` will then process each event by annotating them with
5027 * "dispatches", a sequence of listeners and IDs that care about that event.
5028 *
5029 * - The `EventPluginHub` then dispatches the events.
5030 *
5031 * Overview of React and the event system:
5032 *
5033 * +------------+ .
5034 * | DOM | .
5035 * +------------+ .
5036 * | .
5037 * v .
5038 * +------------+ .
5039 * | ReactEvent | .
5040 * | Listener | .
5041 * +------------+ . +-----------+
5042 * | . +--------+|SimpleEvent|
5043 * | . | |Plugin |
5044 * +-----|------+ . v +-----------+
5045 * | | | . +--------------+ +------------+
5046 * | +-----------.--->|EventPluginHub| | Event |
5047 * | | . | | +-----------+ | Propagators|
5048 * | ReactEvent | . | | |TapEvent | |------------|
5049 * | Emitter | . | |<---+|Plugin | |other plugin|
5050 * | | . | | +-----------+ | utilities |
5051 * | +-----------.--->| | +------------+
5052 * | | | . +--------------+
5053 * +-----|------+ . ^ +-----------+
5054 * | . | |Enter/Leave|
5055 * + . +-------+|Plugin |
5056 * +-------------+ . +-----------+
5057 * | application | .
5058 * |-------------| .
5059 * | | .
5060 * | | .
5061 * +-------------+ .
5062 * .
5063 * React Core . General Purpose Event Plugin System
5064 */
5065
5066var alreadyListeningTo = {};
5067var reactTopListenersCounter = 0;
5068
5069/**
5070 * To ensure no conflicts with other potential React instances on the page
5071 */
5072var topListenersIDKey = '_reactListenersID' + ('' + Math.random()).slice(2);
5073
5074function getListeningForDocument(mountAt) {
5075 // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
5076 // directly.
5077 if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) {
5078 mountAt[topListenersIDKey] = reactTopListenersCounter++;
5079 alreadyListeningTo[mountAt[topListenersIDKey]] = {};
5080 }
5081 return alreadyListeningTo[mountAt[topListenersIDKey]];
5082}
5083
5084/**
5085 * We listen for bubbled touch events on the document object.
5086 *
5087 * Firefox v8.01 (and possibly others) exhibited strange behavior when
5088 * mounting `onmousemove` events at some node that was not the document
5089 * element. The symptoms were that if your mouse is not moving over something
5090 * contained within that mount point (for example on the background) the
5091 * top-level listeners for `onmousemove` won't be called. However, if you
5092 * register the `mousemove` on the document object, then it will of course
5093 * catch all `mousemove`s. This along with iOS quirks, justifies restricting
5094 * top-level listeners to the document object only, at least for these
5095 * movement types of events and possibly all events.
5096 *
5097 * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
5098 *
5099 * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
5100 * they bubble to document.
5101 *
5102 * @param {string} registrationName Name of listener (e.g. `onClick`).
5103 * @param {object} mountAt Container where to mount the listener
5104 */
5105function listenTo(registrationName, mountAt) {
5106 var isListening = getListeningForDocument(mountAt);
5107 var dependencies = registrationNameDependencies[registrationName];
5108
5109 for (var i = 0; i < dependencies.length; i++) {
5110 var dependency = dependencies[i];
5111 if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
5112 switch (dependency) {
5113 case TOP_SCROLL:
5114 trapCapturedEvent(TOP_SCROLL, mountAt);
5115 break;
5116 case TOP_FOCUS:
5117 case TOP_BLUR:
5118 trapCapturedEvent(TOP_FOCUS, mountAt);
5119 trapCapturedEvent(TOP_BLUR, mountAt);
5120 // We set the flag for a single dependency later in this function,
5121 // but this ensures we mark both as attached rather than just one.
5122 isListening[TOP_BLUR] = true;
5123 isListening[TOP_FOCUS] = true;
5124 break;
5125 case TOP_CANCEL:
5126 case TOP_CLOSE:
5127 if (isEventSupported(getRawEventName(dependency))) {
5128 trapCapturedEvent(dependency, mountAt);
5129 }
5130 break;
5131 case TOP_INVALID:
5132 case TOP_SUBMIT:
5133 case TOP_RESET:
5134 // We listen to them on the target DOM elements.
5135 // Some of them bubble so we don't want them to fire twice.
5136 break;
5137 default:
5138 // By default, listen on the top level to all non-media events.
5139 // Media events don't bubble so adding the listener wouldn't do anything.
5140 var isMediaEvent = mediaEventTypes.indexOf(dependency) !== -1;
5141 if (!isMediaEvent) {
5142 trapBubbledEvent(dependency, mountAt);
5143 }
5144 break;
5145 }
5146 isListening[dependency] = true;
5147 }
5148 }
5149}
5150
5151function isListeningToAllDependencies(registrationName, mountAt) {
5152 var isListening = getListeningForDocument(mountAt);
5153 var dependencies = registrationNameDependencies[registrationName];
5154 for (var i = 0; i < dependencies.length; i++) {
5155 var dependency = dependencies[i];
5156 if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
5157 return false;
5158 }
5159 }
5160 return true;
5161}
5162
5163function getActiveElement(doc) {
5164 doc = doc || (typeof document !== 'undefined' ? document : undefined);
5165 if (typeof doc === 'undefined') {
5166 return null;
5167 }
5168 try {
5169 return doc.activeElement || doc.body;
5170 } catch (e) {
5171 return doc.body;
5172 }
5173}
5174
5175/**
5176 * Given any node return the first leaf node without children.
5177 *
5178 * @param {DOMElement|DOMTextNode} node
5179 * @return {DOMElement|DOMTextNode}
5180 */
5181function getLeafNode(node) {
5182 while (node && node.firstChild) {
5183 node = node.firstChild;
5184 }
5185 return node;
5186}
5187
5188/**
5189 * Get the next sibling within a container. This will walk up the
5190 * DOM if a node's siblings have been exhausted.
5191 *
5192 * @param {DOMElement|DOMTextNode} node
5193 * @return {?DOMElement|DOMTextNode}
5194 */
5195function getSiblingNode(node) {
5196 while (node) {
5197 if (node.nextSibling) {
5198 return node.nextSibling;
5199 }
5200 node = node.parentNode;
5201 }
5202}
5203
5204/**
5205 * Get object describing the nodes which contain characters at offset.
5206 *
5207 * @param {DOMElement|DOMTextNode} root
5208 * @param {number} offset
5209 * @return {?object}
5210 */
5211function getNodeForCharacterOffset(root, offset) {
5212 var node = getLeafNode(root);
5213 var nodeStart = 0;
5214 var nodeEnd = 0;
5215
5216 while (node) {
5217 if (node.nodeType === TEXT_NODE) {
5218 nodeEnd = nodeStart + node.textContent.length;
5219
5220 if (nodeStart <= offset && nodeEnd >= offset) {
5221 return {
5222 node: node,
5223 offset: offset - nodeStart
5224 };
5225 }
5226
5227 nodeStart = nodeEnd;
5228 }
5229
5230 node = getLeafNode(getSiblingNode(node));
5231 }
5232}
5233
5234/**
5235 * @param {DOMElement} outerNode
5236 * @return {?object}
5237 */
5238function getOffsets(outerNode) {
5239 var ownerDocument = outerNode.ownerDocument;
5240
5241 var win = ownerDocument && ownerDocument.defaultView || window;
5242 var selection = win.getSelection && win.getSelection();
5243
5244 if (!selection || selection.rangeCount === 0) {
5245 return null;
5246 }
5247
5248 var anchorNode = selection.anchorNode,
5249 anchorOffset = selection.anchorOffset,
5250 focusNode = selection.focusNode,
5251 focusOffset = selection.focusOffset;
5252
5253 // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
5254 // up/down buttons on an <input type="number">. Anonymous divs do not seem to
5255 // expose properties, triggering a "Permission denied error" if any of its
5256 // properties are accessed. The only seemingly possible way to avoid erroring
5257 // is to access a property that typically works for non-anonymous divs and
5258 // catch any error that may otherwise arise. See
5259 // https://bugzilla.mozilla.org/show_bug.cgi?id=208427
5260
5261 try {
5262 /* eslint-disable no-unused-expressions */
5263 anchorNode.nodeType;
5264 focusNode.nodeType;
5265 /* eslint-enable no-unused-expressions */
5266 } catch (e) {
5267 return null;
5268 }
5269
5270 return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
5271}
5272
5273/**
5274 * Returns {start, end} where `start` is the character/codepoint index of
5275 * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
5276 * `end` is the index of (focusNode, focusOffset).
5277 *
5278 * Returns null if you pass in garbage input but we should probably just crash.
5279 *
5280 * Exported only for testing.
5281 */
5282function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
5283 var length = 0;
5284 var start = -1;
5285 var end = -1;
5286 var indexWithinAnchor = 0;
5287 var indexWithinFocus = 0;
5288 var node = outerNode;
5289 var parentNode = null;
5290
5291 outer: while (true) {
5292 var next = null;
5293
5294 while (true) {
5295 if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
5296 start = length + anchorOffset;
5297 }
5298 if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
5299 end = length + focusOffset;
5300 }
5301
5302 if (node.nodeType === TEXT_NODE) {
5303 length += node.nodeValue.length;
5304 }
5305
5306 if ((next = node.firstChild) === null) {
5307 break;
5308 }
5309 // Moving from `node` to its first child `next`.
5310 parentNode = node;
5311 node = next;
5312 }
5313
5314 while (true) {
5315 if (node === outerNode) {
5316 // If `outerNode` has children, this is always the second time visiting
5317 // it. If it has no children, this is still the first loop, and the only
5318 // valid selection is anchorNode and focusNode both equal to this node
5319 // and both offsets 0, in which case we will have handled above.
5320 break outer;
5321 }
5322 if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
5323 start = length;
5324 }
5325 if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
5326 end = length;
5327 }
5328 if ((next = node.nextSibling) !== null) {
5329 break;
5330 }
5331 node = parentNode;
5332 parentNode = node.parentNode;
5333 }
5334
5335 // Moving from `node` to its next sibling `next`.
5336 node = next;
5337 }
5338
5339 if (start === -1 || end === -1) {
5340 // This should never happen. (Would happen if the anchor/focus nodes aren't
5341 // actually inside the passed-in node.)
5342 return null;
5343 }
5344
5345 return {
5346 start: start,
5347 end: end
5348 };
5349}
5350
5351/**
5352 * In modern non-IE browsers, we can support both forward and backward
5353 * selections.
5354 *
5355 * Note: IE10+ supports the Selection object, but it does not support
5356 * the `extend` method, which means that even in modern IE, it's not possible
5357 * to programmatically create a backward selection. Thus, for all IE
5358 * versions, we use the old IE API to create our selections.
5359 *
5360 * @param {DOMElement|DOMTextNode} node
5361 * @param {object} offsets
5362 */
5363function setOffsets(node, offsets) {
5364 var doc = node.ownerDocument || document;
5365 var win = doc && doc.defaultView || window;
5366
5367 // Edge fails with "Object expected" in some scenarios.
5368 // (For instance: TinyMCE editor used in a list component that supports pasting to add more,
5369 // fails when pasting 100+ items)
5370 if (!win.getSelection) {
5371 return;
5372 }
5373
5374 var selection = win.getSelection();
5375 var length = node.textContent.length;
5376 var start = Math.min(offsets.start, length);
5377 var end = offsets.end === undefined ? start : Math.min(offsets.end, length);
5378
5379 // IE 11 uses modern selection, but doesn't support the extend method.
5380 // Flip backward selections, so we can set with a single range.
5381 if (!selection.extend && start > end) {
5382 var temp = end;
5383 end = start;
5384 start = temp;
5385 }
5386
5387 var startMarker = getNodeForCharacterOffset(node, start);
5388 var endMarker = getNodeForCharacterOffset(node, end);
5389
5390 if (startMarker && endMarker) {
5391 if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
5392 return;
5393 }
5394 var range = doc.createRange();
5395 range.setStart(startMarker.node, startMarker.offset);
5396 selection.removeAllRanges();
5397
5398 if (start > end) {
5399 selection.addRange(range);
5400 selection.extend(endMarker.node, endMarker.offset);
5401 } else {
5402 range.setEnd(endMarker.node, endMarker.offset);
5403 selection.addRange(range);
5404 }
5405 }
5406}
5407
5408function isTextNode(node) {
5409 return node && node.nodeType === TEXT_NODE;
5410}
5411
5412function containsNode(outerNode, innerNode) {
5413 if (!outerNode || !innerNode) {
5414 return false;
5415 } else if (outerNode === innerNode) {
5416 return true;
5417 } else if (isTextNode(outerNode)) {
5418 return false;
5419 } else if (isTextNode(innerNode)) {
5420 return containsNode(outerNode, innerNode.parentNode);
5421 } else if ('contains' in outerNode) {
5422 return outerNode.contains(innerNode);
5423 } else if (outerNode.compareDocumentPosition) {
5424 return !!(outerNode.compareDocumentPosition(innerNode) & 16);
5425 } else {
5426 return false;
5427 }
5428}
5429
5430function isInDocument(node) {
5431 return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
5432}
5433
5434function getActiveElementDeep() {
5435 var win = window;
5436 var element = getActiveElement();
5437 while (element instanceof win.HTMLIFrameElement) {
5438 // Accessing the contentDocument of a HTMLIframeElement can cause the browser
5439 // to throw, e.g. if it has a cross-origin src attribute
5440 try {
5441 win = element.contentDocument.defaultView;
5442 } catch (e) {
5443 return element;
5444 }
5445 element = getActiveElement(win.document);
5446 }
5447 return element;
5448}
5449
5450/**
5451 * @ReactInputSelection: React input selection module. Based on Selection.js,
5452 * but modified to be suitable for react and has a couple of bug fixes (doesn't
5453 * assume buttons have range selections allowed).
5454 * Input selection module for React.
5455 */
5456
5457/**
5458 * @hasSelectionCapabilities: we get the element types that support selection
5459 * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
5460 * and `selectionEnd` rows.
5461 */
5462function hasSelectionCapabilities(elem) {
5463 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
5464 return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
5465}
5466
5467function getSelectionInformation() {
5468 var focusedElem = getActiveElementDeep();
5469 return {
5470 focusedElem: focusedElem,
5471 selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection$1(focusedElem) : null
5472 };
5473}
5474
5475/**
5476 * @restoreSelection: If any selection information was potentially lost,
5477 * restore it. This is useful when performing operations that could remove dom
5478 * nodes and place them back in, resulting in focus being lost.
5479 */
5480function restoreSelection(priorSelectionInformation) {
5481 var curFocusedElem = getActiveElementDeep();
5482 var priorFocusedElem = priorSelectionInformation.focusedElem;
5483 var priorSelectionRange = priorSelectionInformation.selectionRange;
5484 if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
5485 if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
5486 setSelection(priorFocusedElem, priorSelectionRange);
5487 }
5488
5489 // Focusing a node can change the scroll position, which is undesirable
5490 var ancestors = [];
5491 var ancestor = priorFocusedElem;
5492 while (ancestor = ancestor.parentNode) {
5493 if (ancestor.nodeType === ELEMENT_NODE) {
5494 ancestors.push({
5495 element: ancestor,
5496 left: ancestor.scrollLeft,
5497 top: ancestor.scrollTop
5498 });
5499 }
5500 }
5501
5502 if (typeof priorFocusedElem.focus === 'function') {
5503 priorFocusedElem.focus();
5504 }
5505
5506 for (var i = 0; i < ancestors.length; i++) {
5507 var info = ancestors[i];
5508 info.element.scrollLeft = info.left;
5509 info.element.scrollTop = info.top;
5510 }
5511 }
5512}
5513
5514/**
5515 * @getSelection: Gets the selection bounds of a focused textarea, input or
5516 * contentEditable node.
5517 * -@input: Look up selection bounds of this input
5518 * -@return {start: selectionStart, end: selectionEnd}
5519 */
5520function getSelection$1(input) {
5521 var selection = void 0;
5522
5523 if ('selectionStart' in input) {
5524 // Modern browser with input or textarea.
5525 selection = {
5526 start: input.selectionStart,
5527 end: input.selectionEnd
5528 };
5529 } else {
5530 // Content editable or old IE textarea.
5531 selection = getOffsets(input);
5532 }
5533
5534 return selection || { start: 0, end: 0 };
5535}
5536
5537/**
5538 * @setSelection: Sets the selection bounds of a textarea or input and focuses
5539 * the input.
5540 * -@input Set selection bounds of this input or textarea
5541 * -@offsets Object of same form that is returned from get*
5542 */
5543function setSelection(input, offsets) {
5544 var start = offsets.start,
5545 end = offsets.end;
5546
5547 if (end === undefined) {
5548 end = start;
5549 }
5550
5551 if ('selectionStart' in input) {
5552 input.selectionStart = start;
5553 input.selectionEnd = Math.min(end, input.value.length);
5554 } else {
5555 setOffsets(input, offsets);
5556 }
5557}
5558
5559var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;
5560
5561var eventTypes$3 = {
5562 select: {
5563 phasedRegistrationNames: {
5564 bubbled: 'onSelect',
5565 captured: 'onSelectCapture'
5566 },
5567 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]
5568 }
5569};
5570
5571var activeElement$1 = null;
5572var activeElementInst$1 = null;
5573var lastSelection = null;
5574var mouseDown = false;
5575
5576/**
5577 * Get an object which is a unique representation of the current selection.
5578 *
5579 * The return value will not be consistent across nodes or browsers, but
5580 * two identical selections on the same node will return identical objects.
5581 *
5582 * @param {DOMElement} node
5583 * @return {object}
5584 */
5585function getSelection(node) {
5586 if ('selectionStart' in node && hasSelectionCapabilities(node)) {
5587 return {
5588 start: node.selectionStart,
5589 end: node.selectionEnd
5590 };
5591 } else {
5592 var win = node.ownerDocument && node.ownerDocument.defaultView || window;
5593 var selection = win.getSelection();
5594 return {
5595 anchorNode: selection.anchorNode,
5596 anchorOffset: selection.anchorOffset,
5597 focusNode: selection.focusNode,
5598 focusOffset: selection.focusOffset
5599 };
5600 }
5601}
5602
5603/**
5604 * Get document associated with the event target.
5605 *
5606 * @param {object} nativeEventTarget
5607 * @return {Document}
5608 */
5609function getEventTargetDocument(eventTarget) {
5610 return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
5611}
5612
5613/**
5614 * Poll selection to see whether it's changed.
5615 *
5616 * @param {object} nativeEvent
5617 * @param {object} nativeEventTarget
5618 * @return {?SyntheticEvent}
5619 */
5620function constructSelectEvent(nativeEvent, nativeEventTarget) {
5621 // Ensure we have the right element, and that the user is not dragging a
5622 // selection (this matches native `select` event behavior). In HTML5, select
5623 // fires only on input and textarea thus if there's no focused element we
5624 // won't dispatch.
5625 var doc = getEventTargetDocument(nativeEventTarget);
5626
5627 if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
5628 return null;
5629 }
5630
5631 // Only fire when selection has actually changed.
5632 var currentSelection = getSelection(activeElement$1);
5633 if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
5634 lastSelection = currentSelection;
5635
5636 var syntheticEvent = SyntheticEvent.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget);
5637
5638 syntheticEvent.type = 'select';
5639 syntheticEvent.target = activeElement$1;
5640
5641 accumulateTwoPhaseDispatches(syntheticEvent);
5642
5643 return syntheticEvent;
5644 }
5645
5646 return null;
5647}
5648
5649/**
5650 * This plugin creates an `onSelect` event that normalizes select events
5651 * across form elements.
5652 *
5653 * Supported elements are:
5654 * - input (see `isTextInputElement`)
5655 * - textarea
5656 * - contentEditable
5657 *
5658 * This differs from native browser implementations in the following ways:
5659 * - Fires on contentEditable fields as well as inputs.
5660 * - Fires for collapsed selection.
5661 * - Fires after user input.
5662 */
5663var SelectEventPlugin = {
5664 eventTypes: eventTypes$3,
5665
5666 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
5667 var doc = getEventTargetDocument(nativeEventTarget);
5668 // Track whether all listeners exists for this plugin. If none exist, we do
5669 // not extract events. See #3639.
5670 if (!doc || !isListeningToAllDependencies('onSelect', doc)) {
5671 return null;
5672 }
5673
5674 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
5675
5676 switch (topLevelType) {
5677 // Track the input node that has focus.
5678 case TOP_FOCUS:
5679 if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
5680 activeElement$1 = targetNode;
5681 activeElementInst$1 = targetInst;
5682 lastSelection = null;
5683 }
5684 break;
5685 case TOP_BLUR:
5686 activeElement$1 = null;
5687 activeElementInst$1 = null;
5688 lastSelection = null;
5689 break;
5690 // Don't fire the event while the user is dragging. This matches the
5691 // semantics of the native select event.
5692 case TOP_MOUSE_DOWN:
5693 mouseDown = true;
5694 break;
5695 case TOP_CONTEXT_MENU:
5696 case TOP_MOUSE_UP:
5697 case TOP_DRAG_END:
5698 mouseDown = false;
5699 return constructSelectEvent(nativeEvent, nativeEventTarget);
5700 // Chrome and IE fire non-standard event when selection is changed (and
5701 // sometimes when it hasn't). IE's event fires out of order with respect
5702 // to key and input events on deletion, so we discard it.
5703 //
5704 // Firefox doesn't support selectionchange, so check selection status
5705 // after each key entry. The selection changes after keydown and before
5706 // keyup, but we check on keydown as well in the case of holding down a
5707 // key, when multiple keydown events are fired but only one keyup is.
5708 // This is also our approach for IE handling, for the reason above.
5709 case TOP_SELECTION_CHANGE:
5710 if (skipSelectionChangeEvent) {
5711 break;
5712 }
5713 // falls through
5714 case TOP_KEY_DOWN:
5715 case TOP_KEY_UP:
5716 return constructSelectEvent(nativeEvent, nativeEventTarget);
5717 }
5718
5719 return null;
5720 }
5721};
5722
5723/**
5724 * Inject modules for resolving DOM hierarchy and plugin ordering.
5725 */
5726injection.injectEventPluginOrder(DOMEventPluginOrder);
5727setComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);
5728
5729/**
5730 * Some important event plugins included by default (without having to require
5731 * them).
5732 */
5733injection.injectEventPluginsByName({
5734 SimpleEventPlugin: SimpleEventPlugin,
5735 EnterLeaveEventPlugin: EnterLeaveEventPlugin,
5736 ChangeEventPlugin: ChangeEventPlugin,
5737 SelectEventPlugin: SelectEventPlugin,
5738 BeforeInputEventPlugin: BeforeInputEventPlugin
5739});
5740
5741var didWarnSelectedSetOnOption = false;
5742var didWarnInvalidChild = false;
5743
5744function flattenChildren(children) {
5745 var content = '';
5746
5747 // Flatten children. We'll warn if they are invalid
5748 // during validateProps() which runs for hydration too.
5749 // Note that this would throw on non-element objects.
5750 // Elements are stringified (which is normally irrelevant
5751 // but matters for <fbt>).
5752 React.Children.forEach(children, function (child) {
5753 if (child == null) {
5754 return;
5755 }
5756 content += child;
5757 // Note: we don't warn about invalid children here.
5758 // Instead, this is done separately below so that
5759 // it happens during the hydration codepath too.
5760 });
5761
5762 return content;
5763}
5764
5765/**
5766 * Implements an <option> host component that warns when `selected` is set.
5767 */
5768
5769function validateProps(element, props) {
5770 {
5771 // This mirrors the codepath above, but runs for hydration too.
5772 // Warn about invalid children here so that client and hydration are consistent.
5773 // TODO: this seems like it could cause a DEV-only throw for hydration
5774 // if children contains a non-element object. We should try to avoid that.
5775 if (typeof props.children === 'object' && props.children !== null) {
5776 React.Children.forEach(props.children, function (child) {
5777 if (child == null) {
5778 return;
5779 }
5780 if (typeof child === 'string' || typeof child === 'number') {
5781 return;
5782 }
5783 if (typeof child.type !== 'string') {
5784 return;
5785 }
5786 if (!didWarnInvalidChild) {
5787 didWarnInvalidChild = true;
5788 warning$1(false, 'Only strings and numbers are supported as <option> children.');
5789 }
5790 });
5791 }
5792
5793 // TODO: Remove support for `selected` in <option>.
5794 if (props.selected != null && !didWarnSelectedSetOnOption) {
5795 warning$1(false, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
5796 didWarnSelectedSetOnOption = true;
5797 }
5798 }
5799}
5800
5801function postMountWrapper$1(element, props) {
5802 // value="" should make a value attribute (#6219)
5803 if (props.value != null) {
5804 element.setAttribute('value', toString(getToStringValue(props.value)));
5805 }
5806}
5807
5808function getHostProps$1(element, props) {
5809 var hostProps = _assign({ children: undefined }, props);
5810 var content = flattenChildren(props.children);
5811
5812 if (content) {
5813 hostProps.children = content;
5814 }
5815
5816 return hostProps;
5817}
5818
5819// TODO: direct imports like some-package/src/* are bad. Fix me.
5820var didWarnValueDefaultValue$1 = void 0;
5821
5822{
5823 didWarnValueDefaultValue$1 = false;
5824}
5825
5826function getDeclarationErrorAddendum() {
5827 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
5828 if (ownerName) {
5829 return '\n\nCheck the render method of `' + ownerName + '`.';
5830 }
5831 return '';
5832}
5833
5834var valuePropNames = ['value', 'defaultValue'];
5835
5836/**
5837 * Validation function for `value` and `defaultValue`.
5838 */
5839function checkSelectPropTypes(props) {
5840 ReactControlledValuePropTypes.checkPropTypes('select', props);
5841
5842 for (var i = 0; i < valuePropNames.length; i++) {
5843 var propName = valuePropNames[i];
5844 if (props[propName] == null) {
5845 continue;
5846 }
5847 var isArray = Array.isArray(props[propName]);
5848 if (props.multiple && !isArray) {
5849 warning$1(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
5850 } else if (!props.multiple && isArray) {
5851 warning$1(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
5852 }
5853 }
5854}
5855
5856function updateOptions(node, multiple, propValue, setDefaultSelected) {
5857 var options = node.options;
5858
5859 if (multiple) {
5860 var selectedValues = propValue;
5861 var selectedValue = {};
5862 for (var i = 0; i < selectedValues.length; i++) {
5863 // Prefix to avoid chaos with special keys.
5864 selectedValue['$' + selectedValues[i]] = true;
5865 }
5866 for (var _i = 0; _i < options.length; _i++) {
5867 var selected = selectedValue.hasOwnProperty('$' + options[_i].value);
5868 if (options[_i].selected !== selected) {
5869 options[_i].selected = selected;
5870 }
5871 if (selected && setDefaultSelected) {
5872 options[_i].defaultSelected = true;
5873 }
5874 }
5875 } else {
5876 // Do not set `select.value` as exact behavior isn't consistent across all
5877 // browsers for all cases.
5878 var _selectedValue = toString(getToStringValue(propValue));
5879 var defaultSelected = null;
5880 for (var _i2 = 0; _i2 < options.length; _i2++) {
5881 if (options[_i2].value === _selectedValue) {
5882 options[_i2].selected = true;
5883 if (setDefaultSelected) {
5884 options[_i2].defaultSelected = true;
5885 }
5886 return;
5887 }
5888 if (defaultSelected === null && !options[_i2].disabled) {
5889 defaultSelected = options[_i2];
5890 }
5891 }
5892 if (defaultSelected !== null) {
5893 defaultSelected.selected = true;
5894 }
5895 }
5896}
5897
5898/**
5899 * Implements a <select> host component that allows optionally setting the
5900 * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
5901 * stringable. If `multiple` is true, the prop must be an array of stringables.
5902 *
5903 * If `value` is not supplied (or null/undefined), user actions that change the
5904 * selected option will trigger updates to the rendered options.
5905 *
5906 * If it is supplied (and not null/undefined), the rendered options will not
5907 * update in response to user actions. Instead, the `value` prop must change in
5908 * order for the rendered options to update.
5909 *
5910 * If `defaultValue` is provided, any options with the supplied values will be
5911 * selected.
5912 */
5913
5914function getHostProps$2(element, props) {
5915 return _assign({}, props, {
5916 value: undefined
5917 });
5918}
5919
5920function initWrapperState$1(element, props) {
5921 var node = element;
5922 {
5923 checkSelectPropTypes(props);
5924 }
5925
5926 node._wrapperState = {
5927 wasMultiple: !!props.multiple
5928 };
5929
5930 {
5931 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
5932 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');
5933 didWarnValueDefaultValue$1 = true;
5934 }
5935 }
5936}
5937
5938function postMountWrapper$2(element, props) {
5939 var node = element;
5940 node.multiple = !!props.multiple;
5941 var value = props.value;
5942 if (value != null) {
5943 updateOptions(node, !!props.multiple, value, false);
5944 } else if (props.defaultValue != null) {
5945 updateOptions(node, !!props.multiple, props.defaultValue, true);
5946 }
5947}
5948
5949function postUpdateWrapper(element, props) {
5950 var node = element;
5951 var wasMultiple = node._wrapperState.wasMultiple;
5952 node._wrapperState.wasMultiple = !!props.multiple;
5953
5954 var value = props.value;
5955 if (value != null) {
5956 updateOptions(node, !!props.multiple, value, false);
5957 } else if (wasMultiple !== !!props.multiple) {
5958 // For simplicity, reapply `defaultValue` if `multiple` is toggled.
5959 if (props.defaultValue != null) {
5960 updateOptions(node, !!props.multiple, props.defaultValue, true);
5961 } else {
5962 // Revert the select back to its default unselected state.
5963 updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
5964 }
5965 }
5966}
5967
5968function restoreControlledState$2(element, props) {
5969 var node = element;
5970 var value = props.value;
5971
5972 if (value != null) {
5973 updateOptions(node, !!props.multiple, value, false);
5974 }
5975}
5976
5977var didWarnValDefaultVal = false;
5978
5979/**
5980 * Implements a <textarea> host component that allows setting `value`, and
5981 * `defaultValue`. This differs from the traditional DOM API because value is
5982 * usually set as PCDATA children.
5983 *
5984 * If `value` is not supplied (or null/undefined), user actions that affect the
5985 * value will trigger updates to the element.
5986 *
5987 * If `value` is supplied (and not null/undefined), the rendered element will
5988 * not trigger updates to the element. Instead, the `value` prop must change in
5989 * order for the rendered element to be updated.
5990 *
5991 * The rendered element will be initialized with an empty value, the prop
5992 * `defaultValue` if specified, or the children content (deprecated).
5993 */
5994
5995function getHostProps$3(element, props) {
5996 var node = element;
5997 !(props.dangerouslySetInnerHTML == null) ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : void 0;
5998
5999 // Always set children to the same thing. In IE9, the selection range will
6000 // get reset if `textContent` is mutated. We could add a check in setTextContent
6001 // to only set the value if/when the value differs from the node value (which would
6002 // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
6003 // solution. The value can be a boolean or object so that's why it's forced
6004 // to be a string.
6005 var hostProps = _assign({}, props, {
6006 value: undefined,
6007 defaultValue: undefined,
6008 children: toString(node._wrapperState.initialValue)
6009 });
6010
6011 return hostProps;
6012}
6013
6014function initWrapperState$2(element, props) {
6015 var node = element;
6016 {
6017 ReactControlledValuePropTypes.checkPropTypes('textarea', props);
6018 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
6019 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');
6020 didWarnValDefaultVal = true;
6021 }
6022 }
6023
6024 var initialValue = props.value;
6025
6026 // Only bother fetching default value if we're going to use it
6027 if (initialValue == null) {
6028 var defaultValue = props.defaultValue;
6029 // TODO (yungsters): Remove support for children content in <textarea>.
6030 var children = props.children;
6031 if (children != null) {
6032 {
6033 warning$1(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
6034 }
6035 !(defaultValue == null) ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : void 0;
6036 if (Array.isArray(children)) {
6037 !(children.length <= 1) ? invariant(false, '<textarea> can only have at most one child.') : void 0;
6038 children = children[0];
6039 }
6040
6041 defaultValue = children;
6042 }
6043 if (defaultValue == null) {
6044 defaultValue = '';
6045 }
6046 initialValue = defaultValue;
6047 }
6048
6049 node._wrapperState = {
6050 initialValue: getToStringValue(initialValue)
6051 };
6052}
6053
6054function updateWrapper$1(element, props) {
6055 var node = element;
6056 var value = getToStringValue(props.value);
6057 var defaultValue = getToStringValue(props.defaultValue);
6058 if (value != null) {
6059 // Cast `value` to a string to ensure the value is set correctly. While
6060 // browsers typically do this as necessary, jsdom doesn't.
6061 var newValue = toString(value);
6062 // To avoid side effects (such as losing text selection), only set value if changed
6063 if (newValue !== node.value) {
6064 node.value = newValue;
6065 }
6066 if (props.defaultValue == null && node.defaultValue !== newValue) {
6067 node.defaultValue = newValue;
6068 }
6069 }
6070 if (defaultValue != null) {
6071 node.defaultValue = toString(defaultValue);
6072 }
6073}
6074
6075function postMountWrapper$3(element, props) {
6076 var node = element;
6077 // This is in postMount because we need access to the DOM node, which is not
6078 // available until after the component has mounted.
6079 var textContent = node.textContent;
6080
6081 // Only set node.value if textContent is equal to the expected
6082 // initial value. In IE10/IE11 there is a bug where the placeholder attribute
6083 // will populate textContent as well.
6084 // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
6085 if (textContent === node._wrapperState.initialValue) {
6086 node.value = textContent;
6087 }
6088}
6089
6090function restoreControlledState$3(element, props) {
6091 // DOM component is still mounted; update
6092 updateWrapper$1(element, props);
6093}
6094
6095var HTML_NAMESPACE$1 = 'http://www.w3.org/1999/xhtml';
6096var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
6097var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
6098
6099var Namespaces = {
6100 html: HTML_NAMESPACE$1,
6101 mathml: MATH_NAMESPACE,
6102 svg: SVG_NAMESPACE
6103};
6104
6105// Assumes there is no parent namespace.
6106function getIntrinsicNamespace(type) {
6107 switch (type) {
6108 case 'svg':
6109 return SVG_NAMESPACE;
6110 case 'math':
6111 return MATH_NAMESPACE;
6112 default:
6113 return HTML_NAMESPACE$1;
6114 }
6115}
6116
6117function getChildNamespace(parentNamespace, type) {
6118 if (parentNamespace == null || parentNamespace === HTML_NAMESPACE$1) {
6119 // No (or default) parent namespace: potential entry point.
6120 return getIntrinsicNamespace(type);
6121 }
6122 if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
6123 // We're leaving SVG.
6124 return HTML_NAMESPACE$1;
6125 }
6126 // By default, pass namespace below.
6127 return parentNamespace;
6128}
6129
6130/* globals MSApp */
6131
6132/**
6133 * Create a function which has 'unsafe' privileges (required by windows8 apps)
6134 */
6135var createMicrosoftUnsafeLocalFunction = function (func) {
6136 if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
6137 return function (arg0, arg1, arg2, arg3) {
6138 MSApp.execUnsafeLocalFunction(function () {
6139 return func(arg0, arg1, arg2, arg3);
6140 });
6141 };
6142 } else {
6143 return func;
6144 }
6145};
6146
6147// SVG temp container for IE lacking innerHTML
6148var reusableSVGContainer = void 0;
6149
6150/**
6151 * Set the innerHTML property of a node
6152 *
6153 * @param {DOMElement} node
6154 * @param {string} html
6155 * @internal
6156 */
6157var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
6158 // IE does not have innerHTML for SVG nodes, so instead we inject the
6159 // new markup in a temp node and then move the child nodes across into
6160 // the target node
6161
6162 if (node.namespaceURI === Namespaces.svg && !('innerHTML' in node)) {
6163 reusableSVGContainer = reusableSVGContainer || document.createElement('div');
6164 reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
6165 var svgNode = reusableSVGContainer.firstChild;
6166 while (node.firstChild) {
6167 node.removeChild(node.firstChild);
6168 }
6169 while (svgNode.firstChild) {
6170 node.appendChild(svgNode.firstChild);
6171 }
6172 } else {
6173 node.innerHTML = html;
6174 }
6175});
6176
6177/**
6178 * Set the textContent property of a node. For text updates, it's faster
6179 * to set the `nodeValue` of the Text node directly instead of using
6180 * `.textContent` which will remove the existing node and create a new one.
6181 *
6182 * @param {DOMElement} node
6183 * @param {string} text
6184 * @internal
6185 */
6186var setTextContent = function (node, text) {
6187 if (text) {
6188 var firstChild = node.firstChild;
6189
6190 if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
6191 firstChild.nodeValue = text;
6192 return;
6193 }
6194 }
6195 node.textContent = text;
6196};
6197
6198// List derived from Gecko source code:
6199// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
6200var shorthandToLonghand = {
6201 animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
6202 background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
6203 backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
6204 border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6205 borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
6206 borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
6207 borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
6208 borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
6209 borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
6210 borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
6211 borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
6212 borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
6213 borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
6214 borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
6215 borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
6216 borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6217 borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
6218 columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
6219 columns: ['columnCount', 'columnWidth'],
6220 flex: ['flexBasis', 'flexGrow', 'flexShrink'],
6221 flexFlow: ['flexDirection', 'flexWrap'],
6222 font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
6223 fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
6224 gap: ['columnGap', 'rowGap'],
6225 grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6226 gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
6227 gridColumn: ['gridColumnEnd', 'gridColumnStart'],
6228 gridColumnGap: ['columnGap'],
6229 gridGap: ['columnGap', 'rowGap'],
6230 gridRow: ['gridRowEnd', 'gridRowStart'],
6231 gridRowGap: ['rowGap'],
6232 gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6233 listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
6234 margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
6235 marker: ['markerEnd', 'markerMid', 'markerStart'],
6236 mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
6237 maskPosition: ['maskPositionX', 'maskPositionY'],
6238 outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
6239 overflow: ['overflowX', 'overflowY'],
6240 padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
6241 placeContent: ['alignContent', 'justifyContent'],
6242 placeItems: ['alignItems', 'justifyItems'],
6243 placeSelf: ['alignSelf', 'justifySelf'],
6244 textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
6245 textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
6246 transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
6247 wordWrap: ['overflowWrap']
6248};
6249
6250/**
6251 * CSS properties which accept numbers but are not in units of "px".
6252 */
6253var isUnitlessNumber = {
6254 animationIterationCount: true,
6255 borderImageOutset: true,
6256 borderImageSlice: true,
6257 borderImageWidth: true,
6258 boxFlex: true,
6259 boxFlexGroup: true,
6260 boxOrdinalGroup: true,
6261 columnCount: true,
6262 columns: true,
6263 flex: true,
6264 flexGrow: true,
6265 flexPositive: true,
6266 flexShrink: true,
6267 flexNegative: true,
6268 flexOrder: true,
6269 gridArea: true,
6270 gridRow: true,
6271 gridRowEnd: true,
6272 gridRowSpan: true,
6273 gridRowStart: true,
6274 gridColumn: true,
6275 gridColumnEnd: true,
6276 gridColumnSpan: true,
6277 gridColumnStart: true,
6278 fontWeight: true,
6279 lineClamp: true,
6280 lineHeight: true,
6281 opacity: true,
6282 order: true,
6283 orphans: true,
6284 tabSize: true,
6285 widows: true,
6286 zIndex: true,
6287 zoom: true,
6288
6289 // SVG-related properties
6290 fillOpacity: true,
6291 floodOpacity: true,
6292 stopOpacity: true,
6293 strokeDasharray: true,
6294 strokeDashoffset: true,
6295 strokeMiterlimit: true,
6296 strokeOpacity: true,
6297 strokeWidth: true
6298};
6299
6300/**
6301 * @param {string} prefix vendor-specific prefix, eg: Webkit
6302 * @param {string} key style name, eg: transitionDuration
6303 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
6304 * WebkitTransitionDuration
6305 */
6306function prefixKey(prefix, key) {
6307 return prefix + key.charAt(0).toUpperCase() + key.substring(1);
6308}
6309
6310/**
6311 * Support style names that may come passed in prefixed by adding permutations
6312 * of vendor prefixes.
6313 */
6314var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
6315
6316// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
6317// infinite loop, because it iterates over the newly added props too.
6318Object.keys(isUnitlessNumber).forEach(function (prop) {
6319 prefixes.forEach(function (prefix) {
6320 isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
6321 });
6322});
6323
6324/**
6325 * Convert a value into the proper css writable value. The style name `name`
6326 * should be logical (no hyphens), as specified
6327 * in `CSSProperty.isUnitlessNumber`.
6328 *
6329 * @param {string} name CSS property name such as `topMargin`.
6330 * @param {*} value CSS property value such as `10px`.
6331 * @return {string} Normalized style value with dimensions applied.
6332 */
6333function dangerousStyleValue(name, value, isCustomProperty) {
6334 // Note that we've removed escapeTextForBrowser() calls here since the
6335 // whole string will be escaped when the attribute is injected into
6336 // the markup. If you provide unsafe user data here they can inject
6337 // arbitrary CSS which may be problematic (I couldn't repro this):
6338 // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
6339 // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
6340 // This is not an XSS hole but instead a potential CSS injection issue
6341 // which has lead to a greater discussion about how we're going to
6342 // trust URLs moving forward. See #2115901
6343
6344 var isEmpty = value == null || typeof value === 'boolean' || value === '';
6345 if (isEmpty) {
6346 return '';
6347 }
6348
6349 if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
6350 return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
6351 }
6352
6353 return ('' + value).trim();
6354}
6355
6356var uppercasePattern = /([A-Z])/g;
6357var msPattern = /^ms-/;
6358
6359/**
6360 * Hyphenates a camelcased CSS property name, for example:
6361 *
6362 * > hyphenateStyleName('backgroundColor')
6363 * < "background-color"
6364 * > hyphenateStyleName('MozTransition')
6365 * < "-moz-transition"
6366 * > hyphenateStyleName('msTransition')
6367 * < "-ms-transition"
6368 *
6369 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
6370 * is converted to `-ms-`.
6371 */
6372function hyphenateStyleName(name) {
6373 return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
6374}
6375
6376var warnValidStyle = function () {};
6377
6378{
6379 // 'msTransform' is correct, but the other prefixes should be capitalized
6380 var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
6381 var msPattern$1 = /^-ms-/;
6382 var hyphenPattern = /-(.)/g;
6383
6384 // style values shouldn't contain a semicolon
6385 var badStyleValueWithSemicolonPattern = /;\s*$/;
6386
6387 var warnedStyleNames = {};
6388 var warnedStyleValues = {};
6389 var warnedForNaNValue = false;
6390 var warnedForInfinityValue = false;
6391
6392 var camelize = function (string) {
6393 return string.replace(hyphenPattern, function (_, character) {
6394 return character.toUpperCase();
6395 });
6396 };
6397
6398 var warnHyphenatedStyleName = function (name) {
6399 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6400 return;
6401 }
6402
6403 warnedStyleNames[name] = true;
6404 warning$1(false, 'Unsupported style property %s. Did you mean %s?', name,
6405 // As Andi Smith suggests
6406 // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
6407 // is converted to lowercase `ms`.
6408 camelize(name.replace(msPattern$1, 'ms-')));
6409 };
6410
6411 var warnBadVendoredStyleName = function (name) {
6412 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6413 return;
6414 }
6415
6416 warnedStyleNames[name] = true;
6417 warning$1(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
6418 };
6419
6420 var warnStyleValueWithSemicolon = function (name, value) {
6421 if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
6422 return;
6423 }
6424
6425 warnedStyleValues[value] = true;
6426 warning$1(false, "Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
6427 };
6428
6429 var warnStyleValueIsNaN = function (name, value) {
6430 if (warnedForNaNValue) {
6431 return;
6432 }
6433
6434 warnedForNaNValue = true;
6435 warning$1(false, '`NaN` is an invalid value for the `%s` css style property.', name);
6436 };
6437
6438 var warnStyleValueIsInfinity = function (name, value) {
6439 if (warnedForInfinityValue) {
6440 return;
6441 }
6442
6443 warnedForInfinityValue = true;
6444 warning$1(false, '`Infinity` is an invalid value for the `%s` css style property.', name);
6445 };
6446
6447 warnValidStyle = function (name, value) {
6448 if (name.indexOf('-') > -1) {
6449 warnHyphenatedStyleName(name);
6450 } else if (badVendoredStyleNamePattern.test(name)) {
6451 warnBadVendoredStyleName(name);
6452 } else if (badStyleValueWithSemicolonPattern.test(value)) {
6453 warnStyleValueWithSemicolon(name, value);
6454 }
6455
6456 if (typeof value === 'number') {
6457 if (isNaN(value)) {
6458 warnStyleValueIsNaN(name, value);
6459 } else if (!isFinite(value)) {
6460 warnStyleValueIsInfinity(name, value);
6461 }
6462 }
6463 };
6464}
6465
6466var warnValidStyle$1 = warnValidStyle;
6467
6468/**
6469 * Operations for dealing with CSS properties.
6470 */
6471
6472/**
6473 * This creates a string that is expected to be equivalent to the style
6474 * attribute generated by server-side rendering. It by-passes warnings and
6475 * security checks so it's not safe to use this value for anything other than
6476 * comparison. It is only used in DEV for SSR validation.
6477 */
6478function createDangerousStringForStyles(styles) {
6479 {
6480 var serialized = '';
6481 var delimiter = '';
6482 for (var styleName in styles) {
6483 if (!styles.hasOwnProperty(styleName)) {
6484 continue;
6485 }
6486 var styleValue = styles[styleName];
6487 if (styleValue != null) {
6488 var isCustomProperty = styleName.indexOf('--') === 0;
6489 serialized += delimiter + hyphenateStyleName(styleName) + ':';
6490 serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
6491
6492 delimiter = ';';
6493 }
6494 }
6495 return serialized || null;
6496 }
6497}
6498
6499/**
6500 * Sets the value for multiple styles on a node. If a value is specified as
6501 * '' (empty string), the corresponding style property will be unset.
6502 *
6503 * @param {DOMElement} node
6504 * @param {object} styles
6505 */
6506function setValueForStyles(node, styles) {
6507 var style = node.style;
6508 for (var styleName in styles) {
6509 if (!styles.hasOwnProperty(styleName)) {
6510 continue;
6511 }
6512 var isCustomProperty = styleName.indexOf('--') === 0;
6513 {
6514 if (!isCustomProperty) {
6515 warnValidStyle$1(styleName, styles[styleName]);
6516 }
6517 }
6518 var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
6519 if (styleName === 'float') {
6520 styleName = 'cssFloat';
6521 }
6522 if (isCustomProperty) {
6523 style.setProperty(styleName, styleValue);
6524 } else {
6525 style[styleName] = styleValue;
6526 }
6527 }
6528}
6529
6530function isValueEmpty(value) {
6531 return value == null || typeof value === 'boolean' || value === '';
6532}
6533
6534/**
6535 * Given {color: 'red', overflow: 'hidden'} returns {
6536 * color: 'color',
6537 * overflowX: 'overflow',
6538 * overflowY: 'overflow',
6539 * }. This can be read as "the overflowY property was set by the overflow
6540 * shorthand". That is, the values are the property that each was derived from.
6541 */
6542function expandShorthandMap(styles) {
6543 var expanded = {};
6544 for (var key in styles) {
6545 var longhands = shorthandToLonghand[key] || [key];
6546 for (var i = 0; i < longhands.length; i++) {
6547 expanded[longhands[i]] = key;
6548 }
6549 }
6550 return expanded;
6551}
6552
6553/**
6554 * When mixing shorthand and longhand property names, we warn during updates if
6555 * we expect an incorrect result to occur. In particular, we warn for:
6556 *
6557 * Updating a shorthand property (longhand gets overwritten):
6558 * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
6559 * becomes .style.font = 'baz'
6560 * Removing a shorthand property (longhand gets lost too):
6561 * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
6562 * becomes .style.font = ''
6563 * Removing a longhand property (should revert to shorthand; doesn't):
6564 * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
6565 * becomes .style.fontVariant = ''
6566 */
6567function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
6568 if (!warnAboutShorthandPropertyCollision) {
6569 return;
6570 }
6571
6572 if (!nextStyles) {
6573 return;
6574 }
6575
6576 var expandedUpdates = expandShorthandMap(styleUpdates);
6577 var expandedStyles = expandShorthandMap(nextStyles);
6578 var warnedAbout = {};
6579 for (var key in expandedUpdates) {
6580 var originalKey = expandedUpdates[key];
6581 var correctOriginalKey = expandedStyles[key];
6582 if (correctOriginalKey && originalKey !== correctOriginalKey) {
6583 var warningKey = originalKey + ',' + correctOriginalKey;
6584 if (warnedAbout[warningKey]) {
6585 continue;
6586 }
6587 warnedAbout[warningKey] = true;
6588 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);
6589 }
6590 }
6591}
6592
6593// For HTML, certain tags should omit their close tag. We keep a whitelist for
6594// those special-case tags.
6595
6596var omittedCloseTags = {
6597 area: true,
6598 base: true,
6599 br: true,
6600 col: true,
6601 embed: true,
6602 hr: true,
6603 img: true,
6604 input: true,
6605 keygen: true,
6606 link: true,
6607 meta: true,
6608 param: true,
6609 source: true,
6610 track: true,
6611 wbr: true
6612 // NOTE: menuitem's close tag should be omitted, but that causes problems.
6613};
6614
6615// For HTML, certain tags cannot have children. This has the same purpose as
6616// `omittedCloseTags` except that `menuitem` should still have its closing tag.
6617
6618var voidElementTags = _assign({
6619 menuitem: true
6620}, omittedCloseTags);
6621
6622// TODO: We can remove this if we add invariantWithStack()
6623// or add stack by default to invariants where possible.
6624var HTML$1 = '__html';
6625
6626var ReactDebugCurrentFrame$2 = null;
6627{
6628 ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame;
6629}
6630
6631function assertValidProps(tag, props) {
6632 if (!props) {
6633 return;
6634 }
6635 // Note the use of `==` which checks for null or undefined.
6636 if (voidElementTags[tag]) {
6637 !(props.children == null && props.dangerouslySetInnerHTML == null) ? invariant(false, '%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s', tag, ReactDebugCurrentFrame$2.getStackAddendum()) : void 0;
6638 }
6639 if (props.dangerouslySetInnerHTML != null) {
6640 !(props.children == null) ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : void 0;
6641 !(typeof props.dangerouslySetInnerHTML === 'object' && HTML$1 in props.dangerouslySetInnerHTML) ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.') : void 0;
6642 }
6643 {
6644 !(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;
6645 }
6646 !(props.style == null || typeof props.style === 'object') ? invariant(false, 'The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}} when using JSX.%s', ReactDebugCurrentFrame$2.getStackAddendum()) : void 0;
6647}
6648
6649function isCustomComponent(tagName, props) {
6650 if (tagName.indexOf('-') === -1) {
6651 return typeof props.is === 'string';
6652 }
6653 switch (tagName) {
6654 // These are reserved SVG and MathML elements.
6655 // We don't mind this whitelist too much because we expect it to never grow.
6656 // The alternative is to track the namespace in a few places which is convoluted.
6657 // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
6658 case 'annotation-xml':
6659 case 'color-profile':
6660 case 'font-face':
6661 case 'font-face-src':
6662 case 'font-face-uri':
6663 case 'font-face-format':
6664 case 'font-face-name':
6665 case 'missing-glyph':
6666 return false;
6667 default:
6668 return true;
6669 }
6670}
6671
6672// When adding attributes to the HTML or SVG whitelist, be sure to
6673// also add them to this module to ensure casing and incorrect name
6674// warnings.
6675var possibleStandardNames = {
6676 // HTML
6677 accept: 'accept',
6678 acceptcharset: 'acceptCharset',
6679 'accept-charset': 'acceptCharset',
6680 accesskey: 'accessKey',
6681 action: 'action',
6682 allowfullscreen: 'allowFullScreen',
6683 alt: 'alt',
6684 as: 'as',
6685 async: 'async',
6686 autocapitalize: 'autoCapitalize',
6687 autocomplete: 'autoComplete',
6688 autocorrect: 'autoCorrect',
6689 autofocus: 'autoFocus',
6690 autoplay: 'autoPlay',
6691 autosave: 'autoSave',
6692 capture: 'capture',
6693 cellpadding: 'cellPadding',
6694 cellspacing: 'cellSpacing',
6695 challenge: 'challenge',
6696 charset: 'charSet',
6697 checked: 'checked',
6698 children: 'children',
6699 cite: 'cite',
6700 class: 'className',
6701 classid: 'classID',
6702 classname: 'className',
6703 cols: 'cols',
6704 colspan: 'colSpan',
6705 content: 'content',
6706 contenteditable: 'contentEditable',
6707 contextmenu: 'contextMenu',
6708 controls: 'controls',
6709 controlslist: 'controlsList',
6710 coords: 'coords',
6711 crossorigin: 'crossOrigin',
6712 dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
6713 data: 'data',
6714 datetime: 'dateTime',
6715 default: 'default',
6716 defaultchecked: 'defaultChecked',
6717 defaultvalue: 'defaultValue',
6718 defer: 'defer',
6719 dir: 'dir',
6720 disabled: 'disabled',
6721 download: 'download',
6722 draggable: 'draggable',
6723 enctype: 'encType',
6724 for: 'htmlFor',
6725 form: 'form',
6726 formmethod: 'formMethod',
6727 formaction: 'formAction',
6728 formenctype: 'formEncType',
6729 formnovalidate: 'formNoValidate',
6730 formtarget: 'formTarget',
6731 frameborder: 'frameBorder',
6732 headers: 'headers',
6733 height: 'height',
6734 hidden: 'hidden',
6735 high: 'high',
6736 href: 'href',
6737 hreflang: 'hrefLang',
6738 htmlfor: 'htmlFor',
6739 httpequiv: 'httpEquiv',
6740 'http-equiv': 'httpEquiv',
6741 icon: 'icon',
6742 id: 'id',
6743 innerhtml: 'innerHTML',
6744 inputmode: 'inputMode',
6745 integrity: 'integrity',
6746 is: 'is',
6747 itemid: 'itemID',
6748 itemprop: 'itemProp',
6749 itemref: 'itemRef',
6750 itemscope: 'itemScope',
6751 itemtype: 'itemType',
6752 keyparams: 'keyParams',
6753 keytype: 'keyType',
6754 kind: 'kind',
6755 label: 'label',
6756 lang: 'lang',
6757 list: 'list',
6758 loop: 'loop',
6759 low: 'low',
6760 manifest: 'manifest',
6761 marginwidth: 'marginWidth',
6762 marginheight: 'marginHeight',
6763 max: 'max',
6764 maxlength: 'maxLength',
6765 media: 'media',
6766 mediagroup: 'mediaGroup',
6767 method: 'method',
6768 min: 'min',
6769 minlength: 'minLength',
6770 multiple: 'multiple',
6771 muted: 'muted',
6772 name: 'name',
6773 nomodule: 'noModule',
6774 nonce: 'nonce',
6775 novalidate: 'noValidate',
6776 open: 'open',
6777 optimum: 'optimum',
6778 pattern: 'pattern',
6779 placeholder: 'placeholder',
6780 playsinline: 'playsInline',
6781 poster: 'poster',
6782 preload: 'preload',
6783 profile: 'profile',
6784 radiogroup: 'radioGroup',
6785 readonly: 'readOnly',
6786 referrerpolicy: 'referrerPolicy',
6787 rel: 'rel',
6788 required: 'required',
6789 reversed: 'reversed',
6790 role: 'role',
6791 rows: 'rows',
6792 rowspan: 'rowSpan',
6793 sandbox: 'sandbox',
6794 scope: 'scope',
6795 scoped: 'scoped',
6796 scrolling: 'scrolling',
6797 seamless: 'seamless',
6798 selected: 'selected',
6799 shape: 'shape',
6800 size: 'size',
6801 sizes: 'sizes',
6802 span: 'span',
6803 spellcheck: 'spellCheck',
6804 src: 'src',
6805 srcdoc: 'srcDoc',
6806 srclang: 'srcLang',
6807 srcset: 'srcSet',
6808 start: 'start',
6809 step: 'step',
6810 style: 'style',
6811 summary: 'summary',
6812 tabindex: 'tabIndex',
6813 target: 'target',
6814 title: 'title',
6815 type: 'type',
6816 usemap: 'useMap',
6817 value: 'value',
6818 width: 'width',
6819 wmode: 'wmode',
6820 wrap: 'wrap',
6821
6822 // SVG
6823 about: 'about',
6824 accentheight: 'accentHeight',
6825 'accent-height': 'accentHeight',
6826 accumulate: 'accumulate',
6827 additive: 'additive',
6828 alignmentbaseline: 'alignmentBaseline',
6829 'alignment-baseline': 'alignmentBaseline',
6830 allowreorder: 'allowReorder',
6831 alphabetic: 'alphabetic',
6832 amplitude: 'amplitude',
6833 arabicform: 'arabicForm',
6834 'arabic-form': 'arabicForm',
6835 ascent: 'ascent',
6836 attributename: 'attributeName',
6837 attributetype: 'attributeType',
6838 autoreverse: 'autoReverse',
6839 azimuth: 'azimuth',
6840 basefrequency: 'baseFrequency',
6841 baselineshift: 'baselineShift',
6842 'baseline-shift': 'baselineShift',
6843 baseprofile: 'baseProfile',
6844 bbox: 'bbox',
6845 begin: 'begin',
6846 bias: 'bias',
6847 by: 'by',
6848 calcmode: 'calcMode',
6849 capheight: 'capHeight',
6850 'cap-height': 'capHeight',
6851 clip: 'clip',
6852 clippath: 'clipPath',
6853 'clip-path': 'clipPath',
6854 clippathunits: 'clipPathUnits',
6855 cliprule: 'clipRule',
6856 'clip-rule': 'clipRule',
6857 color: 'color',
6858 colorinterpolation: 'colorInterpolation',
6859 'color-interpolation': 'colorInterpolation',
6860 colorinterpolationfilters: 'colorInterpolationFilters',
6861 'color-interpolation-filters': 'colorInterpolationFilters',
6862 colorprofile: 'colorProfile',
6863 'color-profile': 'colorProfile',
6864 colorrendering: 'colorRendering',
6865 'color-rendering': 'colorRendering',
6866 contentscripttype: 'contentScriptType',
6867 contentstyletype: 'contentStyleType',
6868 cursor: 'cursor',
6869 cx: 'cx',
6870 cy: 'cy',
6871 d: 'd',
6872 datatype: 'datatype',
6873 decelerate: 'decelerate',
6874 descent: 'descent',
6875 diffuseconstant: 'diffuseConstant',
6876 direction: 'direction',
6877 display: 'display',
6878 divisor: 'divisor',
6879 dominantbaseline: 'dominantBaseline',
6880 'dominant-baseline': 'dominantBaseline',
6881 dur: 'dur',
6882 dx: 'dx',
6883 dy: 'dy',
6884 edgemode: 'edgeMode',
6885 elevation: 'elevation',
6886 enablebackground: 'enableBackground',
6887 'enable-background': 'enableBackground',
6888 end: 'end',
6889 exponent: 'exponent',
6890 externalresourcesrequired: 'externalResourcesRequired',
6891 fill: 'fill',
6892 fillopacity: 'fillOpacity',
6893 'fill-opacity': 'fillOpacity',
6894 fillrule: 'fillRule',
6895 'fill-rule': 'fillRule',
6896 filter: 'filter',
6897 filterres: 'filterRes',
6898 filterunits: 'filterUnits',
6899 floodopacity: 'floodOpacity',
6900 'flood-opacity': 'floodOpacity',
6901 floodcolor: 'floodColor',
6902 'flood-color': 'floodColor',
6903 focusable: 'focusable',
6904 fontfamily: 'fontFamily',
6905 'font-family': 'fontFamily',
6906 fontsize: 'fontSize',
6907 'font-size': 'fontSize',
6908 fontsizeadjust: 'fontSizeAdjust',
6909 'font-size-adjust': 'fontSizeAdjust',
6910 fontstretch: 'fontStretch',
6911 'font-stretch': 'fontStretch',
6912 fontstyle: 'fontStyle',
6913 'font-style': 'fontStyle',
6914 fontvariant: 'fontVariant',
6915 'font-variant': 'fontVariant',
6916 fontweight: 'fontWeight',
6917 'font-weight': 'fontWeight',
6918 format: 'format',
6919 from: 'from',
6920 fx: 'fx',
6921 fy: 'fy',
6922 g1: 'g1',
6923 g2: 'g2',
6924 glyphname: 'glyphName',
6925 'glyph-name': 'glyphName',
6926 glyphorientationhorizontal: 'glyphOrientationHorizontal',
6927 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
6928 glyphorientationvertical: 'glyphOrientationVertical',
6929 'glyph-orientation-vertical': 'glyphOrientationVertical',
6930 glyphref: 'glyphRef',
6931 gradienttransform: 'gradientTransform',
6932 gradientunits: 'gradientUnits',
6933 hanging: 'hanging',
6934 horizadvx: 'horizAdvX',
6935 'horiz-adv-x': 'horizAdvX',
6936 horizoriginx: 'horizOriginX',
6937 'horiz-origin-x': 'horizOriginX',
6938 ideographic: 'ideographic',
6939 imagerendering: 'imageRendering',
6940 'image-rendering': 'imageRendering',
6941 in2: 'in2',
6942 in: 'in',
6943 inlist: 'inlist',
6944 intercept: 'intercept',
6945 k1: 'k1',
6946 k2: 'k2',
6947 k3: 'k3',
6948 k4: 'k4',
6949 k: 'k',
6950 kernelmatrix: 'kernelMatrix',
6951 kernelunitlength: 'kernelUnitLength',
6952 kerning: 'kerning',
6953 keypoints: 'keyPoints',
6954 keysplines: 'keySplines',
6955 keytimes: 'keyTimes',
6956 lengthadjust: 'lengthAdjust',
6957 letterspacing: 'letterSpacing',
6958 'letter-spacing': 'letterSpacing',
6959 lightingcolor: 'lightingColor',
6960 'lighting-color': 'lightingColor',
6961 limitingconeangle: 'limitingConeAngle',
6962 local: 'local',
6963 markerend: 'markerEnd',
6964 'marker-end': 'markerEnd',
6965 markerheight: 'markerHeight',
6966 markermid: 'markerMid',
6967 'marker-mid': 'markerMid',
6968 markerstart: 'markerStart',
6969 'marker-start': 'markerStart',
6970 markerunits: 'markerUnits',
6971 markerwidth: 'markerWidth',
6972 mask: 'mask',
6973 maskcontentunits: 'maskContentUnits',
6974 maskunits: 'maskUnits',
6975 mathematical: 'mathematical',
6976 mode: 'mode',
6977 numoctaves: 'numOctaves',
6978 offset: 'offset',
6979 opacity: 'opacity',
6980 operator: 'operator',
6981 order: 'order',
6982 orient: 'orient',
6983 orientation: 'orientation',
6984 origin: 'origin',
6985 overflow: 'overflow',
6986 overlineposition: 'overlinePosition',
6987 'overline-position': 'overlinePosition',
6988 overlinethickness: 'overlineThickness',
6989 'overline-thickness': 'overlineThickness',
6990 paintorder: 'paintOrder',
6991 'paint-order': 'paintOrder',
6992 panose1: 'panose1',
6993 'panose-1': 'panose1',
6994 pathlength: 'pathLength',
6995 patterncontentunits: 'patternContentUnits',
6996 patterntransform: 'patternTransform',
6997 patternunits: 'patternUnits',
6998 pointerevents: 'pointerEvents',
6999 'pointer-events': 'pointerEvents',
7000 points: 'points',
7001 pointsatx: 'pointsAtX',
7002 pointsaty: 'pointsAtY',
7003 pointsatz: 'pointsAtZ',
7004 prefix: 'prefix',
7005 preservealpha: 'preserveAlpha',
7006 preserveaspectratio: 'preserveAspectRatio',
7007 primitiveunits: 'primitiveUnits',
7008 property: 'property',
7009 r: 'r',
7010 radius: 'radius',
7011 refx: 'refX',
7012 refy: 'refY',
7013 renderingintent: 'renderingIntent',
7014 'rendering-intent': 'renderingIntent',
7015 repeatcount: 'repeatCount',
7016 repeatdur: 'repeatDur',
7017 requiredextensions: 'requiredExtensions',
7018 requiredfeatures: 'requiredFeatures',
7019 resource: 'resource',
7020 restart: 'restart',
7021 result: 'result',
7022 results: 'results',
7023 rotate: 'rotate',
7024 rx: 'rx',
7025 ry: 'ry',
7026 scale: 'scale',
7027 security: 'security',
7028 seed: 'seed',
7029 shaperendering: 'shapeRendering',
7030 'shape-rendering': 'shapeRendering',
7031 slope: 'slope',
7032 spacing: 'spacing',
7033 specularconstant: 'specularConstant',
7034 specularexponent: 'specularExponent',
7035 speed: 'speed',
7036 spreadmethod: 'spreadMethod',
7037 startoffset: 'startOffset',
7038 stddeviation: 'stdDeviation',
7039 stemh: 'stemh',
7040 stemv: 'stemv',
7041 stitchtiles: 'stitchTiles',
7042 stopcolor: 'stopColor',
7043 'stop-color': 'stopColor',
7044 stopopacity: 'stopOpacity',
7045 'stop-opacity': 'stopOpacity',
7046 strikethroughposition: 'strikethroughPosition',
7047 'strikethrough-position': 'strikethroughPosition',
7048 strikethroughthickness: 'strikethroughThickness',
7049 'strikethrough-thickness': 'strikethroughThickness',
7050 string: 'string',
7051 stroke: 'stroke',
7052 strokedasharray: 'strokeDasharray',
7053 'stroke-dasharray': 'strokeDasharray',
7054 strokedashoffset: 'strokeDashoffset',
7055 'stroke-dashoffset': 'strokeDashoffset',
7056 strokelinecap: 'strokeLinecap',
7057 'stroke-linecap': 'strokeLinecap',
7058 strokelinejoin: 'strokeLinejoin',
7059 'stroke-linejoin': 'strokeLinejoin',
7060 strokemiterlimit: 'strokeMiterlimit',
7061 'stroke-miterlimit': 'strokeMiterlimit',
7062 strokewidth: 'strokeWidth',
7063 'stroke-width': 'strokeWidth',
7064 strokeopacity: 'strokeOpacity',
7065 'stroke-opacity': 'strokeOpacity',
7066 suppresscontenteditablewarning: 'suppressContentEditableWarning',
7067 suppresshydrationwarning: 'suppressHydrationWarning',
7068 surfacescale: 'surfaceScale',
7069 systemlanguage: 'systemLanguage',
7070 tablevalues: 'tableValues',
7071 targetx: 'targetX',
7072 targety: 'targetY',
7073 textanchor: 'textAnchor',
7074 'text-anchor': 'textAnchor',
7075 textdecoration: 'textDecoration',
7076 'text-decoration': 'textDecoration',
7077 textlength: 'textLength',
7078 textrendering: 'textRendering',
7079 'text-rendering': 'textRendering',
7080 to: 'to',
7081 transform: 'transform',
7082 typeof: 'typeof',
7083 u1: 'u1',
7084 u2: 'u2',
7085 underlineposition: 'underlinePosition',
7086 'underline-position': 'underlinePosition',
7087 underlinethickness: 'underlineThickness',
7088 'underline-thickness': 'underlineThickness',
7089 unicode: 'unicode',
7090 unicodebidi: 'unicodeBidi',
7091 'unicode-bidi': 'unicodeBidi',
7092 unicoderange: 'unicodeRange',
7093 'unicode-range': 'unicodeRange',
7094 unitsperem: 'unitsPerEm',
7095 'units-per-em': 'unitsPerEm',
7096 unselectable: 'unselectable',
7097 valphabetic: 'vAlphabetic',
7098 'v-alphabetic': 'vAlphabetic',
7099 values: 'values',
7100 vectoreffect: 'vectorEffect',
7101 'vector-effect': 'vectorEffect',
7102 version: 'version',
7103 vertadvy: 'vertAdvY',
7104 'vert-adv-y': 'vertAdvY',
7105 vertoriginx: 'vertOriginX',
7106 'vert-origin-x': 'vertOriginX',
7107 vertoriginy: 'vertOriginY',
7108 'vert-origin-y': 'vertOriginY',
7109 vhanging: 'vHanging',
7110 'v-hanging': 'vHanging',
7111 videographic: 'vIdeographic',
7112 'v-ideographic': 'vIdeographic',
7113 viewbox: 'viewBox',
7114 viewtarget: 'viewTarget',
7115 visibility: 'visibility',
7116 vmathematical: 'vMathematical',
7117 'v-mathematical': 'vMathematical',
7118 vocab: 'vocab',
7119 widths: 'widths',
7120 wordspacing: 'wordSpacing',
7121 'word-spacing': 'wordSpacing',
7122 writingmode: 'writingMode',
7123 'writing-mode': 'writingMode',
7124 x1: 'x1',
7125 x2: 'x2',
7126 x: 'x',
7127 xchannelselector: 'xChannelSelector',
7128 xheight: 'xHeight',
7129 'x-height': 'xHeight',
7130 xlinkactuate: 'xlinkActuate',
7131 'xlink:actuate': 'xlinkActuate',
7132 xlinkarcrole: 'xlinkArcrole',
7133 'xlink:arcrole': 'xlinkArcrole',
7134 xlinkhref: 'xlinkHref',
7135 'xlink:href': 'xlinkHref',
7136 xlinkrole: 'xlinkRole',
7137 'xlink:role': 'xlinkRole',
7138 xlinkshow: 'xlinkShow',
7139 'xlink:show': 'xlinkShow',
7140 xlinktitle: 'xlinkTitle',
7141 'xlink:title': 'xlinkTitle',
7142 xlinktype: 'xlinkType',
7143 'xlink:type': 'xlinkType',
7144 xmlbase: 'xmlBase',
7145 'xml:base': 'xmlBase',
7146 xmllang: 'xmlLang',
7147 'xml:lang': 'xmlLang',
7148 xmlns: 'xmlns',
7149 'xml:space': 'xmlSpace',
7150 xmlnsxlink: 'xmlnsXlink',
7151 'xmlns:xlink': 'xmlnsXlink',
7152 xmlspace: 'xmlSpace',
7153 y1: 'y1',
7154 y2: 'y2',
7155 y: 'y',
7156 ychannelselector: 'yChannelSelector',
7157 z: 'z',
7158 zoomandpan: 'zoomAndPan'
7159};
7160
7161var ariaProperties = {
7162 'aria-current': 0, // state
7163 'aria-details': 0,
7164 'aria-disabled': 0, // state
7165 'aria-hidden': 0, // state
7166 'aria-invalid': 0, // state
7167 'aria-keyshortcuts': 0,
7168 'aria-label': 0,
7169 'aria-roledescription': 0,
7170 // Widget Attributes
7171 'aria-autocomplete': 0,
7172 'aria-checked': 0,
7173 'aria-expanded': 0,
7174 'aria-haspopup': 0,
7175 'aria-level': 0,
7176 'aria-modal': 0,
7177 'aria-multiline': 0,
7178 'aria-multiselectable': 0,
7179 'aria-orientation': 0,
7180 'aria-placeholder': 0,
7181 'aria-pressed': 0,
7182 'aria-readonly': 0,
7183 'aria-required': 0,
7184 'aria-selected': 0,
7185 'aria-sort': 0,
7186 'aria-valuemax': 0,
7187 'aria-valuemin': 0,
7188 'aria-valuenow': 0,
7189 'aria-valuetext': 0,
7190 // Live Region Attributes
7191 'aria-atomic': 0,
7192 'aria-busy': 0,
7193 'aria-live': 0,
7194 'aria-relevant': 0,
7195 // Drag-and-Drop Attributes
7196 'aria-dropeffect': 0,
7197 'aria-grabbed': 0,
7198 // Relationship Attributes
7199 'aria-activedescendant': 0,
7200 'aria-colcount': 0,
7201 'aria-colindex': 0,
7202 'aria-colspan': 0,
7203 'aria-controls': 0,
7204 'aria-describedby': 0,
7205 'aria-errormessage': 0,
7206 'aria-flowto': 0,
7207 'aria-labelledby': 0,
7208 'aria-owns': 0,
7209 'aria-posinset': 0,
7210 'aria-rowcount': 0,
7211 'aria-rowindex': 0,
7212 'aria-rowspan': 0,
7213 'aria-setsize': 0
7214};
7215
7216var warnedProperties = {};
7217var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7218var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7219
7220var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
7221
7222function validateProperty(tagName, name) {
7223 if (hasOwnProperty$2.call(warnedProperties, name) && warnedProperties[name]) {
7224 return true;
7225 }
7226
7227 if (rARIACamel.test(name)) {
7228 var ariaName = 'aria-' + name.slice(4).toLowerCase();
7229 var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null;
7230
7231 // If this is an aria-* attribute, but is not listed in the known DOM
7232 // DOM properties, then it is an invalid aria-* attribute.
7233 if (correctName == null) {
7234 warning$1(false, 'Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
7235 warnedProperties[name] = true;
7236 return true;
7237 }
7238 // aria-* attributes should be lowercase; suggest the lowercase version.
7239 if (name !== correctName) {
7240 warning$1(false, 'Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
7241 warnedProperties[name] = true;
7242 return true;
7243 }
7244 }
7245
7246 if (rARIA.test(name)) {
7247 var lowerCasedName = name.toLowerCase();
7248 var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null;
7249
7250 // If this is an aria-* attribute, but is not listed in the known DOM
7251 // DOM properties, then it is an invalid aria-* attribute.
7252 if (standardName == null) {
7253 warnedProperties[name] = true;
7254 return false;
7255 }
7256 // aria-* attributes should be lowercase; suggest the lowercase version.
7257 if (name !== standardName) {
7258 warning$1(false, 'Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
7259 warnedProperties[name] = true;
7260 return true;
7261 }
7262 }
7263
7264 return true;
7265}
7266
7267function warnInvalidARIAProps(type, props) {
7268 var invalidProps = [];
7269
7270 for (var key in props) {
7271 var isValid = validateProperty(type, key);
7272 if (!isValid) {
7273 invalidProps.push(key);
7274 }
7275 }
7276
7277 var unknownPropString = invalidProps.map(function (prop) {
7278 return '`' + prop + '`';
7279 }).join(', ');
7280
7281 if (invalidProps.length === 1) {
7282 warning$1(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7283 } else if (invalidProps.length > 1) {
7284 warning$1(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7285 }
7286}
7287
7288function validateProperties(type, props) {
7289 if (isCustomComponent(type, props)) {
7290 return;
7291 }
7292 warnInvalidARIAProps(type, props);
7293}
7294
7295var didWarnValueNull = false;
7296
7297function validateProperties$1(type, props) {
7298 if (type !== 'input' && type !== 'textarea' && type !== 'select') {
7299 return;
7300 }
7301
7302 if (props != null && props.value === null && !didWarnValueNull) {
7303 didWarnValueNull = true;
7304 if (type === 'select' && props.multiple) {
7305 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);
7306 } else {
7307 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);
7308 }
7309 }
7310}
7311
7312var validateProperty$1 = function () {};
7313
7314{
7315 var warnedProperties$1 = {};
7316 var _hasOwnProperty = Object.prototype.hasOwnProperty;
7317 var EVENT_NAME_REGEX = /^on./;
7318 var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
7319 var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7320 var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7321
7322 validateProperty$1 = function (tagName, name, value, canUseEventSystem) {
7323 if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
7324 return true;
7325 }
7326
7327 var lowerCasedName = name.toLowerCase();
7328 if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
7329 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.');
7330 warnedProperties$1[name] = true;
7331 return true;
7332 }
7333
7334 // We can't rely on the event system being injected on the server.
7335 if (canUseEventSystem) {
7336 if (registrationNameModules.hasOwnProperty(name)) {
7337 return true;
7338 }
7339 var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
7340 if (registrationName != null) {
7341 warning$1(false, 'Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
7342 warnedProperties$1[name] = true;
7343 return true;
7344 }
7345 if (EVENT_NAME_REGEX.test(name)) {
7346 warning$1(false, 'Unknown event handler property `%s`. It will be ignored.', name);
7347 warnedProperties$1[name] = true;
7348 return true;
7349 }
7350 } else if (EVENT_NAME_REGEX.test(name)) {
7351 // If no event plugins have been injected, we are in a server environment.
7352 // So we can't tell if the event name is correct for sure, but we can filter
7353 // out known bad ones like `onclick`. We can't suggest a specific replacement though.
7354 if (INVALID_EVENT_NAME_REGEX.test(name)) {
7355 warning$1(false, 'Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
7356 }
7357 warnedProperties$1[name] = true;
7358 return true;
7359 }
7360
7361 // Let the ARIA attribute hook validate ARIA attributes
7362 if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
7363 return true;
7364 }
7365
7366 if (lowerCasedName === 'innerhtml') {
7367 warning$1(false, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
7368 warnedProperties$1[name] = true;
7369 return true;
7370 }
7371
7372 if (lowerCasedName === 'aria') {
7373 warning$1(false, 'The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
7374 warnedProperties$1[name] = true;
7375 return true;
7376 }
7377
7378 if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
7379 warning$1(false, 'Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
7380 warnedProperties$1[name] = true;
7381 return true;
7382 }
7383
7384 if (typeof value === 'number' && isNaN(value)) {
7385 warning$1(false, 'Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
7386 warnedProperties$1[name] = true;
7387 return true;
7388 }
7389
7390 var propertyInfo = getPropertyInfo(name);
7391 var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED;
7392
7393 // Known attributes should match the casing specified in the property config.
7394 if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
7395 var standardName = possibleStandardNames[lowerCasedName];
7396 if (standardName !== name) {
7397 warning$1(false, 'Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
7398 warnedProperties$1[name] = true;
7399 return true;
7400 }
7401 } else if (!isReserved && name !== lowerCasedName) {
7402 // Unknown attributes should have lowercase casing since that's how they
7403 // will be cased anyway with server rendering.
7404 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);
7405 warnedProperties$1[name] = true;
7406 return true;
7407 }
7408
7409 if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7410 if (value) {
7411 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);
7412 } else {
7413 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);
7414 }
7415 warnedProperties$1[name] = true;
7416 return true;
7417 }
7418
7419 // Now that we've validated casing, do not validate
7420 // data types for reserved props
7421 if (isReserved) {
7422 return true;
7423 }
7424
7425 // Warn when a known attribute is a bad type
7426 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7427 warnedProperties$1[name] = true;
7428 return false;
7429 }
7430
7431 // Warn when passing the strings 'false' or 'true' into a boolean prop
7432 if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
7433 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);
7434 warnedProperties$1[name] = true;
7435 return true;
7436 }
7437
7438 return true;
7439 };
7440}
7441
7442var warnUnknownProperties = function (type, props, canUseEventSystem) {
7443 var unknownProps = [];
7444 for (var key in props) {
7445 var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);
7446 if (!isValid) {
7447 unknownProps.push(key);
7448 }
7449 }
7450
7451 var unknownPropString = unknownProps.map(function (prop) {
7452 return '`' + prop + '`';
7453 }).join(', ');
7454 if (unknownProps.length === 1) {
7455 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);
7456 } else if (unknownProps.length > 1) {
7457 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);
7458 }
7459};
7460
7461function validateProperties$2(type, props, canUseEventSystem) {
7462 if (isCustomComponent(type, props)) {
7463 return;
7464 }
7465 warnUnknownProperties(type, props, canUseEventSystem);
7466}
7467
7468// TODO: direct imports like some-package/src/* are bad. Fix me.
7469var didWarnInvalidHydration = false;
7470var didWarnShadyDOM = false;
7471
7472var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
7473var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
7474var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
7475var AUTOFOCUS = 'autoFocus';
7476var CHILDREN = 'children';
7477var STYLE$1 = 'style';
7478var HTML = '__html';
7479
7480var HTML_NAMESPACE = Namespaces.html;
7481
7482
7483var warnedUnknownTags = void 0;
7484var suppressHydrationWarning = void 0;
7485
7486var validatePropertiesInDevelopment = void 0;
7487var warnForTextDifference = void 0;
7488var warnForPropDifference = void 0;
7489var warnForExtraAttributes = void 0;
7490var warnForInvalidEventListener = void 0;
7491var canDiffStyleForHydrationWarning = void 0;
7492
7493var normalizeMarkupForTextOrAttribute = void 0;
7494var normalizeHTML = void 0;
7495
7496{
7497 warnedUnknownTags = {
7498 // Chrome is the only major browser not shipping <time>. But as of July
7499 // 2017 it intends to ship it due to widespread usage. We intentionally
7500 // *don't* warn for <time> even if it's unrecognized by Chrome because
7501 // it soon will be, and many apps have been using it anyway.
7502 time: true,
7503 // There are working polyfills for <dialog>. Let people use it.
7504 dialog: true,
7505 // Electron ships a custom <webview> tag to display external web content in
7506 // an isolated frame and process.
7507 // This tag is not present in non Electron environments such as JSDom which
7508 // is often used for testing purposes.
7509 // @see https://electronjs.org/docs/api/webview-tag
7510 webview: true
7511 };
7512
7513 validatePropertiesInDevelopment = function (type, props) {
7514 validateProperties(type, props);
7515 validateProperties$1(type, props);
7516 validateProperties$2(type, props, /* canUseEventSystem */true);
7517 };
7518
7519 // IE 11 parses & normalizes the style attribute as opposed to other
7520 // browsers. It adds spaces and sorts the properties in some
7521 // non-alphabetical order. Handling that would require sorting CSS
7522 // properties in the client & server versions or applying
7523 // `expectedStyle` to a temporary DOM node to read its `style` attribute
7524 // normalized. Since it only affects IE, we're skipping style warnings
7525 // in that browser completely in favor of doing all that work.
7526 // See https://github.com/facebook/react/issues/11807
7527 canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode;
7528
7529 // HTML parsing normalizes CR and CRLF to LF.
7530 // It also can turn \u0000 into \uFFFD inside attributes.
7531 // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
7532 // If we have a mismatch, it might be caused by that.
7533 // We will still patch up in this case but not fire the warning.
7534 var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
7535 var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
7536
7537 normalizeMarkupForTextOrAttribute = function (markup) {
7538 var markupString = typeof markup === 'string' ? markup : '' + markup;
7539 return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
7540 };
7541
7542 warnForTextDifference = function (serverText, clientText) {
7543 if (didWarnInvalidHydration) {
7544 return;
7545 }
7546 var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
7547 var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
7548 if (normalizedServerText === normalizedClientText) {
7549 return;
7550 }
7551 didWarnInvalidHydration = true;
7552 warningWithoutStack$1(false, 'Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
7553 };
7554
7555 warnForPropDifference = function (propName, serverValue, clientValue) {
7556 if (didWarnInvalidHydration) {
7557 return;
7558 }
7559 var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
7560 var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
7561 if (normalizedServerValue === normalizedClientValue) {
7562 return;
7563 }
7564 didWarnInvalidHydration = true;
7565 warningWithoutStack$1(false, 'Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
7566 };
7567
7568 warnForExtraAttributes = function (attributeNames) {
7569 if (didWarnInvalidHydration) {
7570 return;
7571 }
7572 didWarnInvalidHydration = true;
7573 var names = [];
7574 attributeNames.forEach(function (name) {
7575 names.push(name);
7576 });
7577 warningWithoutStack$1(false, 'Extra attributes from the server: %s', names);
7578 };
7579
7580 warnForInvalidEventListener = function (registrationName, listener) {
7581 if (listener === false) {
7582 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);
7583 } else {
7584 warning$1(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
7585 }
7586 };
7587
7588 // Parse the HTML and read it back to normalize the HTML string so that it
7589 // can be used for comparison.
7590 normalizeHTML = function (parent, html) {
7591 // We could have created a separate document here to avoid
7592 // re-initializing custom elements if they exist. But this breaks
7593 // how <noscript> is being handled. So we use the same document.
7594 // See the discussion in https://github.com/facebook/react/pull/11157.
7595 var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
7596 testElement.innerHTML = html;
7597 return testElement.innerHTML;
7598 };
7599}
7600
7601function ensureListeningTo(rootContainerElement, registrationName) {
7602 var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;
7603 var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;
7604 listenTo(registrationName, doc);
7605}
7606
7607function getOwnerDocumentFromRootContainer(rootContainerElement) {
7608 return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
7609}
7610
7611function noop() {}
7612
7613function trapClickOnNonInteractiveElement(node) {
7614 // Mobile Safari does not fire properly bubble click events on
7615 // non-interactive elements, which means delegated click listeners do not
7616 // fire. The workaround for this bug involves attaching an empty click
7617 // listener on the target node.
7618 // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
7619 // Just set it using the onclick property so that we don't have to manage any
7620 // bookkeeping for it. Not sure if we need to clear it when the listener is
7621 // removed.
7622 // TODO: Only do this for the relevant Safaris maybe?
7623 node.onclick = noop;
7624}
7625
7626function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
7627 for (var propKey in nextProps) {
7628 if (!nextProps.hasOwnProperty(propKey)) {
7629 continue;
7630 }
7631 var nextProp = nextProps[propKey];
7632 if (propKey === STYLE$1) {
7633 {
7634 if (nextProp) {
7635 // Freeze the next style object so that we can assume it won't be
7636 // mutated. We have already warned for this in the past.
7637 Object.freeze(nextProp);
7638 }
7639 }
7640 // Relies on `updateStylesByID` not mutating `styleUpdates`.
7641 setValueForStyles(domElement, nextProp);
7642 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7643 var nextHtml = nextProp ? nextProp[HTML] : undefined;
7644 if (nextHtml != null) {
7645 setInnerHTML(domElement, nextHtml);
7646 }
7647 } else if (propKey === CHILDREN) {
7648 if (typeof nextProp === 'string') {
7649 // Avoid setting initial textContent when the text is empty. In IE11 setting
7650 // textContent on a <textarea> will cause the placeholder to not
7651 // show within the <textarea> until it has been focused and blurred again.
7652 // https://github.com/facebook/react/issues/6731#issuecomment-254874553
7653 var canSetTextContent = tag !== 'textarea' || nextProp !== '';
7654 if (canSetTextContent) {
7655 setTextContent(domElement, nextProp);
7656 }
7657 } else if (typeof nextProp === 'number') {
7658 setTextContent(domElement, '' + nextProp);
7659 }
7660 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
7661 // Noop
7662 } else if (propKey === AUTOFOCUS) {
7663 // We polyfill it separately on the client during commit.
7664 // We could have excluded it in the property list instead of
7665 // adding a special case here, but then it wouldn't be emitted
7666 // on server rendering (but we *do* want to emit it in SSR).
7667 } else if (registrationNameModules.hasOwnProperty(propKey)) {
7668 if (nextProp != null) {
7669 if (true && typeof nextProp !== 'function') {
7670 warnForInvalidEventListener(propKey, nextProp);
7671 }
7672 ensureListeningTo(rootContainerElement, propKey);
7673 }
7674 } else if (nextProp != null) {
7675 setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
7676 }
7677 }
7678}
7679
7680function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
7681 // TODO: Handle wasCustomComponentTag
7682 for (var i = 0; i < updatePayload.length; i += 2) {
7683 var propKey = updatePayload[i];
7684 var propValue = updatePayload[i + 1];
7685 if (propKey === STYLE$1) {
7686 setValueForStyles(domElement, propValue);
7687 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7688 setInnerHTML(domElement, propValue);
7689 } else if (propKey === CHILDREN) {
7690 setTextContent(domElement, propValue);
7691 } else {
7692 setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
7693 }
7694 }
7695}
7696
7697function createElement(type, props, rootContainerElement, parentNamespace) {
7698 var isCustomComponentTag = void 0;
7699
7700 // We create tags in the namespace of their parent container, except HTML
7701 // tags get no namespace.
7702 var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
7703 var domElement = void 0;
7704 var namespaceURI = parentNamespace;
7705 if (namespaceURI === HTML_NAMESPACE) {
7706 namespaceURI = getIntrinsicNamespace(type);
7707 }
7708 if (namespaceURI === HTML_NAMESPACE) {
7709 {
7710 isCustomComponentTag = isCustomComponent(type, props);
7711 // Should this check be gated by parent namespace? Not sure we want to
7712 // allow <SVG> or <mATH>.
7713 !(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;
7714 }
7715
7716 if (type === 'script') {
7717 // Create the script via .innerHTML so its "parser-inserted" flag is
7718 // set to true and it does not execute
7719 var div = ownerDocument.createElement('div');
7720 div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
7721 // This is guaranteed to yield a script element.
7722 var firstChild = div.firstChild;
7723 domElement = div.removeChild(firstChild);
7724 } else if (typeof props.is === 'string') {
7725 // $FlowIssue `createElement` should be updated for Web Components
7726 domElement = ownerDocument.createElement(type, { is: props.is });
7727 } else {
7728 // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
7729 // See discussion in https://github.com/facebook/react/pull/6896
7730 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
7731 domElement = ownerDocument.createElement(type);
7732 // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple`
7733 // attribute on `select`s needs to be added before `option`s are inserted. This prevents
7734 // a bug where the `select` does not scroll to the correct option because singular
7735 // `select` elements automatically pick the first item.
7736 // See https://github.com/facebook/react/issues/13222
7737 if (type === 'select' && props.multiple) {
7738 var node = domElement;
7739 node.multiple = true;
7740 }
7741 }
7742 } else {
7743 domElement = ownerDocument.createElementNS(namespaceURI, type);
7744 }
7745
7746 {
7747 if (namespaceURI === HTML_NAMESPACE) {
7748 if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {
7749 warnedUnknownTags[type] = true;
7750 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);
7751 }
7752 }
7753 }
7754
7755 return domElement;
7756}
7757
7758function createTextNode(text, rootContainerElement) {
7759 return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
7760}
7761
7762function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
7763 var isCustomComponentTag = isCustomComponent(tag, rawProps);
7764 {
7765 validatePropertiesInDevelopment(tag, rawProps);
7766 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
7767 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
7768 didWarnShadyDOM = true;
7769 }
7770 }
7771
7772 // TODO: Make sure that we check isMounted before firing any of these events.
7773 var props = void 0;
7774 switch (tag) {
7775 case 'iframe':
7776 case 'object':
7777 trapBubbledEvent(TOP_LOAD, domElement);
7778 props = rawProps;
7779 break;
7780 case 'video':
7781 case 'audio':
7782 // Create listener for each media event
7783 for (var i = 0; i < mediaEventTypes.length; i++) {
7784 trapBubbledEvent(mediaEventTypes[i], domElement);
7785 }
7786 props = rawProps;
7787 break;
7788 case 'source':
7789 trapBubbledEvent(TOP_ERROR, domElement);
7790 props = rawProps;
7791 break;
7792 case 'img':
7793 case 'image':
7794 case 'link':
7795 trapBubbledEvent(TOP_ERROR, domElement);
7796 trapBubbledEvent(TOP_LOAD, domElement);
7797 props = rawProps;
7798 break;
7799 case 'form':
7800 trapBubbledEvent(TOP_RESET, domElement);
7801 trapBubbledEvent(TOP_SUBMIT, domElement);
7802 props = rawProps;
7803 break;
7804 case 'details':
7805 trapBubbledEvent(TOP_TOGGLE, domElement);
7806 props = rawProps;
7807 break;
7808 case 'input':
7809 initWrapperState(domElement, rawProps);
7810 props = getHostProps(domElement, rawProps);
7811 trapBubbledEvent(TOP_INVALID, domElement);
7812 // For controlled components we always need to ensure we're listening
7813 // to onChange. Even if there is no listener.
7814 ensureListeningTo(rootContainerElement, 'onChange');
7815 break;
7816 case 'option':
7817 validateProps(domElement, rawProps);
7818 props = getHostProps$1(domElement, rawProps);
7819 break;
7820 case 'select':
7821 initWrapperState$1(domElement, rawProps);
7822 props = getHostProps$2(domElement, rawProps);
7823 trapBubbledEvent(TOP_INVALID, domElement);
7824 // For controlled components we always need to ensure we're listening
7825 // to onChange. Even if there is no listener.
7826 ensureListeningTo(rootContainerElement, 'onChange');
7827 break;
7828 case 'textarea':
7829 initWrapperState$2(domElement, rawProps);
7830 props = getHostProps$3(domElement, rawProps);
7831 trapBubbledEvent(TOP_INVALID, domElement);
7832 // For controlled components we always need to ensure we're listening
7833 // to onChange. Even if there is no listener.
7834 ensureListeningTo(rootContainerElement, 'onChange');
7835 break;
7836 default:
7837 props = rawProps;
7838 }
7839
7840 assertValidProps(tag, props);
7841
7842 setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
7843
7844 switch (tag) {
7845 case 'input':
7846 // TODO: Make sure we check if this is still unmounted or do any clean
7847 // up necessary since we never stop tracking anymore.
7848 track(domElement);
7849 postMountWrapper(domElement, rawProps, false);
7850 break;
7851 case 'textarea':
7852 // TODO: Make sure we check if this is still unmounted or do any clean
7853 // up necessary since we never stop tracking anymore.
7854 track(domElement);
7855 postMountWrapper$3(domElement, rawProps);
7856 break;
7857 case 'option':
7858 postMountWrapper$1(domElement, rawProps);
7859 break;
7860 case 'select':
7861 postMountWrapper$2(domElement, rawProps);
7862 break;
7863 default:
7864 if (typeof props.onClick === 'function') {
7865 // TODO: This cast may not be sound for SVG, MathML or custom elements.
7866 trapClickOnNonInteractiveElement(domElement);
7867 }
7868 break;
7869 }
7870}
7871
7872// Calculate the diff between the two objects.
7873function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
7874 {
7875 validatePropertiesInDevelopment(tag, nextRawProps);
7876 }
7877
7878 var updatePayload = null;
7879
7880 var lastProps = void 0;
7881 var nextProps = void 0;
7882 switch (tag) {
7883 case 'input':
7884 lastProps = getHostProps(domElement, lastRawProps);
7885 nextProps = getHostProps(domElement, nextRawProps);
7886 updatePayload = [];
7887 break;
7888 case 'option':
7889 lastProps = getHostProps$1(domElement, lastRawProps);
7890 nextProps = getHostProps$1(domElement, nextRawProps);
7891 updatePayload = [];
7892 break;
7893 case 'select':
7894 lastProps = getHostProps$2(domElement, lastRawProps);
7895 nextProps = getHostProps$2(domElement, nextRawProps);
7896 updatePayload = [];
7897 break;
7898 case 'textarea':
7899 lastProps = getHostProps$3(domElement, lastRawProps);
7900 nextProps = getHostProps$3(domElement, nextRawProps);
7901 updatePayload = [];
7902 break;
7903 default:
7904 lastProps = lastRawProps;
7905 nextProps = nextRawProps;
7906 if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
7907 // TODO: This cast may not be sound for SVG, MathML or custom elements.
7908 trapClickOnNonInteractiveElement(domElement);
7909 }
7910 break;
7911 }
7912
7913 assertValidProps(tag, nextProps);
7914
7915 var propKey = void 0;
7916 var styleName = void 0;
7917 var styleUpdates = null;
7918 for (propKey in lastProps) {
7919 if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
7920 continue;
7921 }
7922 if (propKey === STYLE$1) {
7923 var lastStyle = lastProps[propKey];
7924 for (styleName in lastStyle) {
7925 if (lastStyle.hasOwnProperty(styleName)) {
7926 if (!styleUpdates) {
7927 styleUpdates = {};
7928 }
7929 styleUpdates[styleName] = '';
7930 }
7931 }
7932 } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) {
7933 // Noop. This is handled by the clear text mechanism.
7934 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
7935 // Noop
7936 } else if (propKey === AUTOFOCUS) {
7937 // Noop. It doesn't work on updates anyway.
7938 } else if (registrationNameModules.hasOwnProperty(propKey)) {
7939 // This is a special case. If any listener updates we need to ensure
7940 // that the "current" fiber pointer gets updated so we need a commit
7941 // to update this element.
7942 if (!updatePayload) {
7943 updatePayload = [];
7944 }
7945 } else {
7946 // For all other deleted properties we add it to the queue. We use
7947 // the whitelist in the commit phase instead.
7948 (updatePayload = updatePayload || []).push(propKey, null);
7949 }
7950 }
7951 for (propKey in nextProps) {
7952 var nextProp = nextProps[propKey];
7953 var lastProp = lastProps != null ? lastProps[propKey] : undefined;
7954 if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
7955 continue;
7956 }
7957 if (propKey === STYLE$1) {
7958 {
7959 if (nextProp) {
7960 // Freeze the next style object so that we can assume it won't be
7961 // mutated. We have already warned for this in the past.
7962 Object.freeze(nextProp);
7963 }
7964 }
7965 if (lastProp) {
7966 // Unset styles on `lastProp` but not on `nextProp`.
7967 for (styleName in lastProp) {
7968 if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
7969 if (!styleUpdates) {
7970 styleUpdates = {};
7971 }
7972 styleUpdates[styleName] = '';
7973 }
7974 }
7975 // Update styles that changed since `lastProp`.
7976 for (styleName in nextProp) {
7977 if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
7978 if (!styleUpdates) {
7979 styleUpdates = {};
7980 }
7981 styleUpdates[styleName] = nextProp[styleName];
7982 }
7983 }
7984 } else {
7985 // Relies on `updateStylesByID` not mutating `styleUpdates`.
7986 if (!styleUpdates) {
7987 if (!updatePayload) {
7988 updatePayload = [];
7989 }
7990 updatePayload.push(propKey, styleUpdates);
7991 }
7992 styleUpdates = nextProp;
7993 }
7994 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7995 var nextHtml = nextProp ? nextProp[HTML] : undefined;
7996 var lastHtml = lastProp ? lastProp[HTML] : undefined;
7997 if (nextHtml != null) {
7998 if (lastHtml !== nextHtml) {
7999 (updatePayload = updatePayload || []).push(propKey, '' + nextHtml);
8000 }
8001 } else {
8002 // TODO: It might be too late to clear this if we have children
8003 // inserted already.
8004 }
8005 } else if (propKey === CHILDREN) {
8006 if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {
8007 (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
8008 }
8009 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
8010 // Noop
8011 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8012 if (nextProp != null) {
8013 // We eagerly listen to this even though we haven't committed yet.
8014 if (true && typeof nextProp !== 'function') {
8015 warnForInvalidEventListener(propKey, nextProp);
8016 }
8017 ensureListeningTo(rootContainerElement, propKey);
8018 }
8019 if (!updatePayload && lastProp !== nextProp) {
8020 // This is a special case. If any listener updates we need to ensure
8021 // that the "current" props pointer gets updated so we need a commit
8022 // to update this element.
8023 updatePayload = [];
8024 }
8025 } else {
8026 // For any other property we always add it to the queue and then we
8027 // filter it out using the whitelist during the commit.
8028 (updatePayload = updatePayload || []).push(propKey, nextProp);
8029 }
8030 }
8031 if (styleUpdates) {
8032 {
8033 validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE$1]);
8034 }
8035 (updatePayload = updatePayload || []).push(STYLE$1, styleUpdates);
8036 }
8037 return updatePayload;
8038}
8039
8040// Apply the diff.
8041function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
8042 // Update checked *before* name.
8043 // In the middle of an update, it is possible to have multiple checked.
8044 // When a checked radio tries to change name, browser makes another radio's checked false.
8045 if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
8046 updateChecked(domElement, nextRawProps);
8047 }
8048
8049 var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
8050 var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
8051 // Apply the diff.
8052 updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag);
8053
8054 // TODO: Ensure that an update gets scheduled if any of the special props
8055 // changed.
8056 switch (tag) {
8057 case 'input':
8058 // Update the wrapper around inputs *after* updating props. This has to
8059 // happen after `updateDOMProperties`. Otherwise HTML5 input validations
8060 // raise warnings and prevent the new value from being assigned.
8061 updateWrapper(domElement, nextRawProps);
8062 break;
8063 case 'textarea':
8064 updateWrapper$1(domElement, nextRawProps);
8065 break;
8066 case 'select':
8067 // <select> value update needs to occur after <option> children
8068 // reconciliation
8069 postUpdateWrapper(domElement, nextRawProps);
8070 break;
8071 }
8072}
8073
8074function getPossibleStandardName(propName) {
8075 {
8076 var lowerCasedName = propName.toLowerCase();
8077 if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
8078 return null;
8079 }
8080 return possibleStandardNames[lowerCasedName] || null;
8081 }
8082 return null;
8083}
8084
8085function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {
8086 var isCustomComponentTag = void 0;
8087 var extraAttributeNames = void 0;
8088
8089 {
8090 suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING$1] === true;
8091 isCustomComponentTag = isCustomComponent(tag, rawProps);
8092 validatePropertiesInDevelopment(tag, rawProps);
8093 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
8094 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
8095 didWarnShadyDOM = true;
8096 }
8097 }
8098
8099 // TODO: Make sure that we check isMounted before firing any of these events.
8100 switch (tag) {
8101 case 'iframe':
8102 case 'object':
8103 trapBubbledEvent(TOP_LOAD, domElement);
8104 break;
8105 case 'video':
8106 case 'audio':
8107 // Create listener for each media event
8108 for (var i = 0; i < mediaEventTypes.length; i++) {
8109 trapBubbledEvent(mediaEventTypes[i], domElement);
8110 }
8111 break;
8112 case 'source':
8113 trapBubbledEvent(TOP_ERROR, domElement);
8114 break;
8115 case 'img':
8116 case 'image':
8117 case 'link':
8118 trapBubbledEvent(TOP_ERROR, domElement);
8119 trapBubbledEvent(TOP_LOAD, domElement);
8120 break;
8121 case 'form':
8122 trapBubbledEvent(TOP_RESET, domElement);
8123 trapBubbledEvent(TOP_SUBMIT, domElement);
8124 break;
8125 case 'details':
8126 trapBubbledEvent(TOP_TOGGLE, domElement);
8127 break;
8128 case 'input':
8129 initWrapperState(domElement, rawProps);
8130 trapBubbledEvent(TOP_INVALID, domElement);
8131 // For controlled components we always need to ensure we're listening
8132 // to onChange. Even if there is no listener.
8133 ensureListeningTo(rootContainerElement, 'onChange');
8134 break;
8135 case 'option':
8136 validateProps(domElement, rawProps);
8137 break;
8138 case 'select':
8139 initWrapperState$1(domElement, rawProps);
8140 trapBubbledEvent(TOP_INVALID, domElement);
8141 // For controlled components we always need to ensure we're listening
8142 // to onChange. Even if there is no listener.
8143 ensureListeningTo(rootContainerElement, 'onChange');
8144 break;
8145 case 'textarea':
8146 initWrapperState$2(domElement, rawProps);
8147 trapBubbledEvent(TOP_INVALID, domElement);
8148 // For controlled components we always need to ensure we're listening
8149 // to onChange. Even if there is no listener.
8150 ensureListeningTo(rootContainerElement, 'onChange');
8151 break;
8152 }
8153
8154 assertValidProps(tag, rawProps);
8155
8156 {
8157 extraAttributeNames = new Set();
8158 var attributes = domElement.attributes;
8159 for (var _i = 0; _i < attributes.length; _i++) {
8160 var name = attributes[_i].name.toLowerCase();
8161 switch (name) {
8162 // Built-in SSR attribute is whitelisted
8163 case 'data-reactroot':
8164 break;
8165 // Controlled attributes are not validated
8166 // TODO: Only ignore them on controlled tags.
8167 case 'value':
8168 break;
8169 case 'checked':
8170 break;
8171 case 'selected':
8172 break;
8173 default:
8174 // Intentionally use the original name.
8175 // See discussion in https://github.com/facebook/react/pull/10676.
8176 extraAttributeNames.add(attributes[_i].name);
8177 }
8178 }
8179 }
8180
8181 var updatePayload = null;
8182 for (var propKey in rawProps) {
8183 if (!rawProps.hasOwnProperty(propKey)) {
8184 continue;
8185 }
8186 var nextProp = rawProps[propKey];
8187 if (propKey === CHILDREN) {
8188 // For text content children we compare against textContent. This
8189 // might match additional HTML that is hidden when we read it using
8190 // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
8191 // satisfies our requirement. Our requirement is not to produce perfect
8192 // HTML and attributes. Ideally we should preserve structure but it's
8193 // ok not to if the visible content is still enough to indicate what
8194 // even listeners these nodes might be wired up to.
8195 // TODO: Warn if there is more than a single textNode as a child.
8196 // TODO: Should we use domElement.firstChild.nodeValue to compare?
8197 if (typeof nextProp === 'string') {
8198 if (domElement.textContent !== nextProp) {
8199 if (true && !suppressHydrationWarning) {
8200 warnForTextDifference(domElement.textContent, nextProp);
8201 }
8202 updatePayload = [CHILDREN, nextProp];
8203 }
8204 } else if (typeof nextProp === 'number') {
8205 if (domElement.textContent !== '' + nextProp) {
8206 if (true && !suppressHydrationWarning) {
8207 warnForTextDifference(domElement.textContent, nextProp);
8208 }
8209 updatePayload = [CHILDREN, '' + nextProp];
8210 }
8211 }
8212 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8213 if (nextProp != null) {
8214 if (true && typeof nextProp !== 'function') {
8215 warnForInvalidEventListener(propKey, nextProp);
8216 }
8217 ensureListeningTo(rootContainerElement, propKey);
8218 }
8219 } else if (true &&
8220 // Convince Flow we've calculated it (it's DEV-only in this method.)
8221 typeof isCustomComponentTag === 'boolean') {
8222 // Validate that the properties correspond to their expected values.
8223 var serverValue = void 0;
8224 var propertyInfo = getPropertyInfo(propKey);
8225 if (suppressHydrationWarning) {
8226 // Don't bother comparing. We're ignoring all these warnings.
8227 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1 ||
8228 // Controlled attributes are not validated
8229 // TODO: Only ignore them on controlled tags.
8230 propKey === 'value' || propKey === 'checked' || propKey === 'selected') {
8231 // Noop
8232 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8233 var serverHTML = domElement.innerHTML;
8234 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8235 var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : '');
8236 if (expectedHTML !== serverHTML) {
8237 warnForPropDifference(propKey, serverHTML, expectedHTML);
8238 }
8239 } else if (propKey === STYLE$1) {
8240 // $FlowFixMe - Should be inferred as not undefined.
8241 extraAttributeNames.delete(propKey);
8242
8243 if (canDiffStyleForHydrationWarning) {
8244 var expectedStyle = createDangerousStringForStyles(nextProp);
8245 serverValue = domElement.getAttribute('style');
8246 if (expectedStyle !== serverValue) {
8247 warnForPropDifference(propKey, serverValue, expectedStyle);
8248 }
8249 }
8250 } else if (isCustomComponentTag) {
8251 // $FlowFixMe - Should be inferred as not undefined.
8252 extraAttributeNames.delete(propKey.toLowerCase());
8253 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8254
8255 if (nextProp !== serverValue) {
8256 warnForPropDifference(propKey, serverValue, nextProp);
8257 }
8258 } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
8259 var isMismatchDueToBadCasing = false;
8260 if (propertyInfo !== null) {
8261 // $FlowFixMe - Should be inferred as not undefined.
8262 extraAttributeNames.delete(propertyInfo.attributeName);
8263 serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
8264 } else {
8265 var ownNamespace = parentNamespace;
8266 if (ownNamespace === HTML_NAMESPACE) {
8267 ownNamespace = getIntrinsicNamespace(tag);
8268 }
8269 if (ownNamespace === HTML_NAMESPACE) {
8270 // $FlowFixMe - Should be inferred as not undefined.
8271 extraAttributeNames.delete(propKey.toLowerCase());
8272 } else {
8273 var standardName = getPossibleStandardName(propKey);
8274 if (standardName !== null && standardName !== propKey) {
8275 // If an SVG prop is supplied with bad casing, it will
8276 // be successfully parsed from HTML, but will produce a mismatch
8277 // (and would be incorrectly rendered on the client).
8278 // However, we already warn about bad casing elsewhere.
8279 // So we'll skip the misleading extra mismatch warning in this case.
8280 isMismatchDueToBadCasing = true;
8281 // $FlowFixMe - Should be inferred as not undefined.
8282 extraAttributeNames.delete(standardName);
8283 }
8284 // $FlowFixMe - Should be inferred as not undefined.
8285 extraAttributeNames.delete(propKey);
8286 }
8287 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8288 }
8289
8290 if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
8291 warnForPropDifference(propKey, serverValue, nextProp);
8292 }
8293 }
8294 }
8295 }
8296
8297 {
8298 // $FlowFixMe - Should be inferred as not undefined.
8299 if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
8300 // $FlowFixMe - Should be inferred as not undefined.
8301 warnForExtraAttributes(extraAttributeNames);
8302 }
8303 }
8304
8305 switch (tag) {
8306 case 'input':
8307 // TODO: Make sure we check if this is still unmounted or do any clean
8308 // up necessary since we never stop tracking anymore.
8309 track(domElement);
8310 postMountWrapper(domElement, rawProps, true);
8311 break;
8312 case 'textarea':
8313 // TODO: Make sure we check if this is still unmounted or do any clean
8314 // up necessary since we never stop tracking anymore.
8315 track(domElement);
8316 postMountWrapper$3(domElement, rawProps);
8317 break;
8318 case 'select':
8319 case 'option':
8320 // For input and textarea we current always set the value property at
8321 // post mount to force it to diverge from attributes. However, for
8322 // option and select we don't quite do the same thing and select
8323 // is not resilient to the DOM state changing so we don't do that here.
8324 // TODO: Consider not doing this for input and textarea.
8325 break;
8326 default:
8327 if (typeof rawProps.onClick === 'function') {
8328 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8329 trapClickOnNonInteractiveElement(domElement);
8330 }
8331 break;
8332 }
8333
8334 return updatePayload;
8335}
8336
8337function diffHydratedText(textNode, text) {
8338 var isDifferent = textNode.nodeValue !== text;
8339 return isDifferent;
8340}
8341
8342function warnForUnmatchedText(textNode, text) {
8343 {
8344 warnForTextDifference(textNode.nodeValue, text);
8345 }
8346}
8347
8348function warnForDeletedHydratableElement(parentNode, child) {
8349 {
8350 if (didWarnInvalidHydration) {
8351 return;
8352 }
8353 didWarnInvalidHydration = true;
8354 warningWithoutStack$1(false, 'Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
8355 }
8356}
8357
8358function warnForDeletedHydratableText(parentNode, child) {
8359 {
8360 if (didWarnInvalidHydration) {
8361 return;
8362 }
8363 didWarnInvalidHydration = true;
8364 warningWithoutStack$1(false, 'Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
8365 }
8366}
8367
8368function warnForInsertedHydratedElement(parentNode, tag, props) {
8369 {
8370 if (didWarnInvalidHydration) {
8371 return;
8372 }
8373 didWarnInvalidHydration = true;
8374 warningWithoutStack$1(false, 'Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
8375 }
8376}
8377
8378function warnForInsertedHydratedText(parentNode, text) {
8379 {
8380 if (text === '') {
8381 // We expect to insert empty text nodes since they're not represented in
8382 // the HTML.
8383 // TODO: Remove this special case if we can just avoid inserting empty
8384 // text nodes.
8385 return;
8386 }
8387 if (didWarnInvalidHydration) {
8388 return;
8389 }
8390 didWarnInvalidHydration = true;
8391 warningWithoutStack$1(false, 'Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
8392 }
8393}
8394
8395function restoreControlledState$1(domElement, tag, props) {
8396 switch (tag) {
8397 case 'input':
8398 restoreControlledState(domElement, props);
8399 return;
8400 case 'textarea':
8401 restoreControlledState$3(domElement, props);
8402 return;
8403 case 'select':
8404 restoreControlledState$2(domElement, props);
8405 return;
8406 }
8407}
8408
8409// TODO: direct imports like some-package/src/* are bad. Fix me.
8410var validateDOMNesting = function () {};
8411var updatedAncestorInfo = function () {};
8412
8413{
8414 // This validation code was written based on the HTML5 parsing spec:
8415 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
8416 //
8417 // Note: this does not catch all invalid nesting, nor does it try to (as it's
8418 // not clear what practical benefit doing so provides); instead, we warn only
8419 // for cases where the parser will give a parse tree differing from what React
8420 // intended. For example, <b><div></div></b> is invalid but we don't warn
8421 // because it still parses correctly; we do warn for other cases like nested
8422 // <p> tags where the beginning of the second element implicitly closes the
8423 // first, causing a confusing mess.
8424
8425 // https://html.spec.whatwg.org/multipage/syntax.html#special
8426 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'];
8427
8428 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
8429 var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template',
8430
8431 // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
8432 // TODO: Distinguish by namespace here -- for <title>, including it here
8433 // errs on the side of fewer warnings
8434 'foreignObject', 'desc', 'title'];
8435
8436 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
8437 var buttonScopeTags = inScopeTags.concat(['button']);
8438
8439 // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
8440 var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
8441
8442 var emptyAncestorInfo = {
8443 current: null,
8444
8445 formTag: null,
8446 aTagInScope: null,
8447 buttonTagInScope: null,
8448 nobrTagInScope: null,
8449 pTagInButtonScope: null,
8450
8451 listItemTagAutoclosing: null,
8452 dlItemTagAutoclosing: null
8453 };
8454
8455 updatedAncestorInfo = function (oldInfo, tag) {
8456 var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
8457 var info = { tag: tag };
8458
8459 if (inScopeTags.indexOf(tag) !== -1) {
8460 ancestorInfo.aTagInScope = null;
8461 ancestorInfo.buttonTagInScope = null;
8462 ancestorInfo.nobrTagInScope = null;
8463 }
8464 if (buttonScopeTags.indexOf(tag) !== -1) {
8465 ancestorInfo.pTagInButtonScope = null;
8466 }
8467
8468 // See rules for 'li', 'dd', 'dt' start tags in
8469 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
8470 if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
8471 ancestorInfo.listItemTagAutoclosing = null;
8472 ancestorInfo.dlItemTagAutoclosing = null;
8473 }
8474
8475 ancestorInfo.current = info;
8476
8477 if (tag === 'form') {
8478 ancestorInfo.formTag = info;
8479 }
8480 if (tag === 'a') {
8481 ancestorInfo.aTagInScope = info;
8482 }
8483 if (tag === 'button') {
8484 ancestorInfo.buttonTagInScope = info;
8485 }
8486 if (tag === 'nobr') {
8487 ancestorInfo.nobrTagInScope = info;
8488 }
8489 if (tag === 'p') {
8490 ancestorInfo.pTagInButtonScope = info;
8491 }
8492 if (tag === 'li') {
8493 ancestorInfo.listItemTagAutoclosing = info;
8494 }
8495 if (tag === 'dd' || tag === 'dt') {
8496 ancestorInfo.dlItemTagAutoclosing = info;
8497 }
8498
8499 return ancestorInfo;
8500 };
8501
8502 /**
8503 * Returns whether
8504 */
8505 var isTagValidWithParent = function (tag, parentTag) {
8506 // First, let's check if we're in an unusual parsing mode...
8507 switch (parentTag) {
8508 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
8509 case 'select':
8510 return tag === 'option' || tag === 'optgroup' || tag === '#text';
8511 case 'optgroup':
8512 return tag === 'option' || tag === '#text';
8513 // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
8514 // but
8515 case 'option':
8516 return tag === '#text';
8517 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
8518 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
8519 // No special behavior since these rules fall back to "in body" mode for
8520 // all except special table nodes which cause bad parsing behavior anyway.
8521
8522 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
8523 case 'tr':
8524 return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
8525 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
8526 case 'tbody':
8527 case 'thead':
8528 case 'tfoot':
8529 return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
8530 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
8531 case 'colgroup':
8532 return tag === 'col' || tag === 'template';
8533 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
8534 case 'table':
8535 return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
8536 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
8537 case 'head':
8538 return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
8539 // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
8540 case 'html':
8541 return tag === 'head' || tag === 'body';
8542 case '#document':
8543 return tag === 'html';
8544 }
8545
8546 // Probably in the "in body" parsing mode, so we outlaw only tag combos
8547 // where the parsing rules cause implicit opens or closes to be added.
8548 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
8549 switch (tag) {
8550 case 'h1':
8551 case 'h2':
8552 case 'h3':
8553 case 'h4':
8554 case 'h5':
8555 case 'h6':
8556 return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
8557
8558 case 'rp':
8559 case 'rt':
8560 return impliedEndTags.indexOf(parentTag) === -1;
8561
8562 case 'body':
8563 case 'caption':
8564 case 'col':
8565 case 'colgroup':
8566 case 'frame':
8567 case 'head':
8568 case 'html':
8569 case 'tbody':
8570 case 'td':
8571 case 'tfoot':
8572 case 'th':
8573 case 'thead':
8574 case 'tr':
8575 // These tags are only valid with a few parents that have special child
8576 // parsing rules -- if we're down here, then none of those matched and
8577 // so we allow it only if we don't know what the parent is, as all other
8578 // cases are invalid.
8579 return parentTag == null;
8580 }
8581
8582 return true;
8583 };
8584
8585 /**
8586 * Returns whether
8587 */
8588 var findInvalidAncestorForTag = function (tag, ancestorInfo) {
8589 switch (tag) {
8590 case 'address':
8591 case 'article':
8592 case 'aside':
8593 case 'blockquote':
8594 case 'center':
8595 case 'details':
8596 case 'dialog':
8597 case 'dir':
8598 case 'div':
8599 case 'dl':
8600 case 'fieldset':
8601 case 'figcaption':
8602 case 'figure':
8603 case 'footer':
8604 case 'header':
8605 case 'hgroup':
8606 case 'main':
8607 case 'menu':
8608 case 'nav':
8609 case 'ol':
8610 case 'p':
8611 case 'section':
8612 case 'summary':
8613 case 'ul':
8614 case 'pre':
8615 case 'listing':
8616 case 'table':
8617 case 'hr':
8618 case 'xmp':
8619 case 'h1':
8620 case 'h2':
8621 case 'h3':
8622 case 'h4':
8623 case 'h5':
8624 case 'h6':
8625 return ancestorInfo.pTagInButtonScope;
8626
8627 case 'form':
8628 return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
8629
8630 case 'li':
8631 return ancestorInfo.listItemTagAutoclosing;
8632
8633 case 'dd':
8634 case 'dt':
8635 return ancestorInfo.dlItemTagAutoclosing;
8636
8637 case 'button':
8638 return ancestorInfo.buttonTagInScope;
8639
8640 case 'a':
8641 // Spec says something about storing a list of markers, but it sounds
8642 // equivalent to this check.
8643 return ancestorInfo.aTagInScope;
8644
8645 case 'nobr':
8646 return ancestorInfo.nobrTagInScope;
8647 }
8648
8649 return null;
8650 };
8651
8652 var didWarn = {};
8653
8654 validateDOMNesting = function (childTag, childText, ancestorInfo) {
8655 ancestorInfo = ancestorInfo || emptyAncestorInfo;
8656 var parentInfo = ancestorInfo.current;
8657 var parentTag = parentInfo && parentInfo.tag;
8658
8659 if (childText != null) {
8660 !(childTag == null) ? warningWithoutStack$1(false, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0;
8661 childTag = '#text';
8662 }
8663
8664 var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
8665 var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
8666 var invalidParentOrAncestor = invalidParent || invalidAncestor;
8667 if (!invalidParentOrAncestor) {
8668 return;
8669 }
8670
8671 var ancestorTag = invalidParentOrAncestor.tag;
8672 var addendum = getCurrentFiberStackInDev();
8673
8674 var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;
8675 if (didWarn[warnKey]) {
8676 return;
8677 }
8678 didWarn[warnKey] = true;
8679
8680 var tagDisplayName = childTag;
8681 var whitespaceInfo = '';
8682 if (childTag === '#text') {
8683 if (/\S/.test(childText)) {
8684 tagDisplayName = 'Text nodes';
8685 } else {
8686 tagDisplayName = 'Whitespace text nodes';
8687 whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
8688 }
8689 } else {
8690 tagDisplayName = '<' + childTag + '>';
8691 }
8692
8693 if (invalidParent) {
8694 var info = '';
8695 if (ancestorTag === 'table' && childTag === 'tr') {
8696 info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.';
8697 }
8698 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info, addendum);
8699 } else {
8700 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.%s', tagDisplayName, ancestorTag, addendum);
8701 }
8702 };
8703}
8704
8705var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
8706
8707var _ReactInternals$Sched = ReactInternals$1.Scheduler;
8708var unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback;
8709var unstable_now = _ReactInternals$Sched.unstable_now;
8710var unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback;
8711var unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield;
8712var unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode;
8713var unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution;
8714var unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution;
8715
8716// Renderers that don't support persistence
8717// can re-export everything from this module.
8718
8719function shim() {
8720 invariant(false, 'The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.');
8721}
8722
8723// Persistence (when unsupported)
8724var supportsPersistence = false;
8725var cloneInstance = shim;
8726var createContainerChildSet = shim;
8727var appendChildToContainerChildSet = shim;
8728var finalizeContainerChildren = shim;
8729var replaceContainerChildren = shim;
8730var cloneHiddenInstance = shim;
8731var cloneUnhiddenInstance = shim;
8732var createHiddenTextInstance = shim;
8733
8734var SUPPRESS_HYDRATION_WARNING = void 0;
8735{
8736 SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
8737}
8738
8739var STYLE = 'style';
8740
8741var eventsEnabled = null;
8742var selectionInformation = null;
8743
8744function shouldAutoFocusHostComponent(type, props) {
8745 switch (type) {
8746 case 'button':
8747 case 'input':
8748 case 'select':
8749 case 'textarea':
8750 return !!props.autoFocus;
8751 }
8752 return false;
8753}
8754
8755function getRootHostContext(rootContainerInstance) {
8756 var type = void 0;
8757 var namespace = void 0;
8758 var nodeType = rootContainerInstance.nodeType;
8759 switch (nodeType) {
8760 case DOCUMENT_NODE:
8761 case DOCUMENT_FRAGMENT_NODE:
8762 {
8763 type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
8764 var root = rootContainerInstance.documentElement;
8765 namespace = root ? root.namespaceURI : getChildNamespace(null, '');
8766 break;
8767 }
8768 default:
8769 {
8770 var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
8771 var ownNamespace = container.namespaceURI || null;
8772 type = container.tagName;
8773 namespace = getChildNamespace(ownNamespace, type);
8774 break;
8775 }
8776 }
8777 {
8778 var validatedTag = type.toLowerCase();
8779 var _ancestorInfo = updatedAncestorInfo(null, validatedTag);
8780 return { namespace: namespace, ancestorInfo: _ancestorInfo };
8781 }
8782 return namespace;
8783}
8784
8785function getChildHostContext(parentHostContext, type, rootContainerInstance) {
8786 {
8787 var parentHostContextDev = parentHostContext;
8788 var _namespace = getChildNamespace(parentHostContextDev.namespace, type);
8789 var _ancestorInfo2 = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
8790 return { namespace: _namespace, ancestorInfo: _ancestorInfo2 };
8791 }
8792 var parentNamespace = parentHostContext;
8793 return getChildNamespace(parentNamespace, type);
8794}
8795
8796function getPublicInstance(instance) {
8797 return instance;
8798}
8799
8800function prepareForCommit(containerInfo) {
8801 eventsEnabled = isEnabled();
8802 selectionInformation = getSelectionInformation();
8803 setEnabled(false);
8804}
8805
8806function resetAfterCommit(containerInfo) {
8807 restoreSelection(selectionInformation);
8808 selectionInformation = null;
8809 setEnabled(eventsEnabled);
8810 eventsEnabled = null;
8811}
8812
8813function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
8814 var parentNamespace = void 0;
8815 {
8816 // TODO: take namespace into account when validating.
8817 var hostContextDev = hostContext;
8818 validateDOMNesting(type, null, hostContextDev.ancestorInfo);
8819 if (typeof props.children === 'string' || typeof props.children === 'number') {
8820 var string = '' + props.children;
8821 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
8822 validateDOMNesting(null, string, ownAncestorInfo);
8823 }
8824 parentNamespace = hostContextDev.namespace;
8825 }
8826 var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
8827 precacheFiberNode(internalInstanceHandle, domElement);
8828 updateFiberProps(domElement, props);
8829 return domElement;
8830}
8831
8832function appendInitialChild(parentInstance, child) {
8833 parentInstance.appendChild(child);
8834}
8835
8836function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
8837 setInitialProperties(domElement, type, props, rootContainerInstance);
8838 return shouldAutoFocusHostComponent(type, props);
8839}
8840
8841function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
8842 {
8843 var hostContextDev = hostContext;
8844 if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
8845 var string = '' + newProps.children;
8846 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
8847 validateDOMNesting(null, string, ownAncestorInfo);
8848 }
8849 }
8850 return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);
8851}
8852
8853function shouldSetTextContent(type, props) {
8854 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;
8855}
8856
8857function shouldDeprioritizeSubtree(type, props) {
8858 return !!props.hidden;
8859}
8860
8861function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
8862 {
8863 var hostContextDev = hostContext;
8864 validateDOMNesting(null, text, hostContextDev.ancestorInfo);
8865 }
8866 var textNode = createTextNode(text, rootContainerInstance);
8867 precacheFiberNode(internalInstanceHandle, textNode);
8868 return textNode;
8869}
8870
8871var isPrimaryRenderer = true;
8872// This initialization code may run even on server environments
8873// if a component just imports ReactDOM (e.g. for findDOMNode).
8874// Some environments might not have setTimeout or clearTimeout.
8875var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
8876var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
8877var noTimeout = -1;
8878var schedulePassiveEffects = unstable_scheduleCallback;
8879var cancelPassiveEffects = unstable_cancelCallback;
8880
8881// -------------------
8882// Mutation
8883// -------------------
8884
8885var supportsMutation = true;
8886
8887function commitMount(domElement, type, newProps, internalInstanceHandle) {
8888 // Despite the naming that might imply otherwise, this method only
8889 // fires if there is an `Update` effect scheduled during mounting.
8890 // This happens if `finalizeInitialChildren` returns `true` (which it
8891 // does to implement the `autoFocus` attribute on the client). But
8892 // there are also other cases when this might happen (such as patching
8893 // up text content during hydration mismatch). So we'll check this again.
8894 if (shouldAutoFocusHostComponent(type, newProps)) {
8895 domElement.focus();
8896 }
8897}
8898
8899function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
8900 // Update the props handle so that we know which props are the ones with
8901 // with current event handlers.
8902 updateFiberProps(domElement, newProps);
8903 // Apply the diff to the DOM node.
8904 updateProperties(domElement, updatePayload, type, oldProps, newProps);
8905}
8906
8907function resetTextContent(domElement) {
8908 setTextContent(domElement, '');
8909}
8910
8911function commitTextUpdate(textInstance, oldText, newText) {
8912 textInstance.nodeValue = newText;
8913}
8914
8915function appendChild(parentInstance, child) {
8916 parentInstance.appendChild(child);
8917}
8918
8919function appendChildToContainer(container, child) {
8920 var parentNode = void 0;
8921 if (container.nodeType === COMMENT_NODE) {
8922 parentNode = container.parentNode;
8923 parentNode.insertBefore(child, container);
8924 } else {
8925 parentNode = container;
8926 parentNode.appendChild(child);
8927 }
8928 // This container might be used for a portal.
8929 // If something inside a portal is clicked, that click should bubble
8930 // through the React tree. However, on Mobile Safari the click would
8931 // never bubble through the *DOM* tree unless an ancestor with onclick
8932 // event exists. So we wouldn't see it and dispatch it.
8933 // This is why we ensure that non React root containers have inline onclick
8934 // defined.
8935 // https://github.com/facebook/react/issues/11918
8936 var reactRootContainer = container._reactRootContainer;
8937 if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
8938 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8939 trapClickOnNonInteractiveElement(parentNode);
8940 }
8941}
8942
8943function insertBefore(parentInstance, child, beforeChild) {
8944 parentInstance.insertBefore(child, beforeChild);
8945}
8946
8947function insertInContainerBefore(container, child, beforeChild) {
8948 if (container.nodeType === COMMENT_NODE) {
8949 container.parentNode.insertBefore(child, beforeChild);
8950 } else {
8951 container.insertBefore(child, beforeChild);
8952 }
8953}
8954
8955function removeChild(parentInstance, child) {
8956 parentInstance.removeChild(child);
8957}
8958
8959function removeChildFromContainer(container, child) {
8960 if (container.nodeType === COMMENT_NODE) {
8961 container.parentNode.removeChild(child);
8962 } else {
8963 container.removeChild(child);
8964 }
8965}
8966
8967function hideInstance(instance) {
8968 // TODO: Does this work for all element types? What about MathML? Should we
8969 // pass host context to this method?
8970 instance = instance;
8971 instance.style.display = 'none';
8972}
8973
8974function hideTextInstance(textInstance) {
8975 textInstance.nodeValue = '';
8976}
8977
8978function unhideInstance(instance, props) {
8979 instance = instance;
8980 var styleProp = props[STYLE];
8981 var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
8982 instance.style.display = dangerousStyleValue('display', display);
8983}
8984
8985function unhideTextInstance(textInstance, text) {
8986 textInstance.nodeValue = text;
8987}
8988
8989// -------------------
8990// Hydration
8991// -------------------
8992
8993var supportsHydration = true;
8994
8995function canHydrateInstance(instance, type, props) {
8996 if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
8997 return null;
8998 }
8999 // This has now been refined to an element node.
9000 return instance;
9001}
9002
9003function canHydrateTextInstance(instance, text) {
9004 if (text === '' || instance.nodeType !== TEXT_NODE) {
9005 // Empty strings are not parsed by HTML so there won't be a correct match here.
9006 return null;
9007 }
9008 // This has now been refined to a text node.
9009 return instance;
9010}
9011
9012function getNextHydratableSibling(instance) {
9013 var node = instance.nextSibling;
9014 // Skip non-hydratable nodes.
9015 while (node && node.nodeType !== ELEMENT_NODE && node.nodeType !== TEXT_NODE) {
9016 node = node.nextSibling;
9017 }
9018 return node;
9019}
9020
9021function getFirstHydratableChild(parentInstance) {
9022 var next = parentInstance.firstChild;
9023 // Skip non-hydratable nodes.
9024 while (next && next.nodeType !== ELEMENT_NODE && next.nodeType !== TEXT_NODE) {
9025 next = next.nextSibling;
9026 }
9027 return next;
9028}
9029
9030function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
9031 precacheFiberNode(internalInstanceHandle, instance);
9032 // TODO: Possibly defer this until the commit phase where all the events
9033 // get attached.
9034 updateFiberProps(instance, props);
9035 var parentNamespace = void 0;
9036 {
9037 var hostContextDev = hostContext;
9038 parentNamespace = hostContextDev.namespace;
9039 }
9040 return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);
9041}
9042
9043function hydrateTextInstance(textInstance, text, internalInstanceHandle) {
9044 precacheFiberNode(internalInstanceHandle, textInstance);
9045 return diffHydratedText(textInstance, text);
9046}
9047
9048function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {
9049 {
9050 warnForUnmatchedText(textInstance, text);
9051 }
9052}
9053
9054function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {
9055 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9056 warnForUnmatchedText(textInstance, text);
9057 }
9058}
9059
9060function didNotHydrateContainerInstance(parentContainer, instance) {
9061 {
9062 if (instance.nodeType === ELEMENT_NODE) {
9063 warnForDeletedHydratableElement(parentContainer, instance);
9064 } else {
9065 warnForDeletedHydratableText(parentContainer, instance);
9066 }
9067 }
9068}
9069
9070function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {
9071 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9072 if (instance.nodeType === ELEMENT_NODE) {
9073 warnForDeletedHydratableElement(parentInstance, instance);
9074 } else {
9075 warnForDeletedHydratableText(parentInstance, instance);
9076 }
9077 }
9078}
9079
9080function didNotFindHydratableContainerInstance(parentContainer, type, props) {
9081 {
9082 warnForInsertedHydratedElement(parentContainer, type, props);
9083 }
9084}
9085
9086function didNotFindHydratableContainerTextInstance(parentContainer, text) {
9087 {
9088 warnForInsertedHydratedText(parentContainer, text);
9089 }
9090}
9091
9092function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {
9093 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9094 warnForInsertedHydratedElement(parentInstance, type, props);
9095 }
9096}
9097
9098function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {
9099 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9100 warnForInsertedHydratedText(parentInstance, text);
9101 }
9102}
9103
9104// Prefix measurements so that it's possible to filter them.
9105// Longer prefixes are hard to read in DevTools.
9106var reactEmoji = '\u269B';
9107var warningEmoji = '\u26D4';
9108var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function';
9109
9110// Keep track of current fiber so that we know the path to unwind on pause.
9111// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
9112var currentFiber = null;
9113// If we're in the middle of user code, which fiber and method is it?
9114// Reusing `currentFiber` would be confusing for this because user code fiber
9115// can change during commit phase too, but we don't need to unwind it (since
9116// lifecycles in the commit phase don't resemble a tree).
9117var currentPhase = null;
9118var currentPhaseFiber = null;
9119// Did lifecycle hook schedule an update? This is often a performance problem,
9120// so we will keep track of it, and include it in the report.
9121// Track commits caused by cascading updates.
9122var isCommitting = false;
9123var hasScheduledUpdateInCurrentCommit = false;
9124var hasScheduledUpdateInCurrentPhase = false;
9125var commitCountInCurrentWorkLoop = 0;
9126var effectCountInCurrentCommit = 0;
9127var isWaitingForCallback = false;
9128// During commits, we only show a measurement once per method name
9129// to avoid stretch the commit phase with measurement overhead.
9130var labelsInCurrentCommit = new Set();
9131
9132var formatMarkName = function (markName) {
9133 return reactEmoji + ' ' + markName;
9134};
9135
9136var formatLabel = function (label, warning) {
9137 var prefix = warning ? warningEmoji + ' ' : reactEmoji + ' ';
9138 var suffix = warning ? ' Warning: ' + warning : '';
9139 return '' + prefix + label + suffix;
9140};
9141
9142var beginMark = function (markName) {
9143 performance.mark(formatMarkName(markName));
9144};
9145
9146var clearMark = function (markName) {
9147 performance.clearMarks(formatMarkName(markName));
9148};
9149
9150var endMark = function (label, markName, warning) {
9151 var formattedMarkName = formatMarkName(markName);
9152 var formattedLabel = formatLabel(label, warning);
9153 try {
9154 performance.measure(formattedLabel, formattedMarkName);
9155 } catch (err) {}
9156 // If previous mark was missing for some reason, this will throw.
9157 // This could only happen if React crashed in an unexpected place earlier.
9158 // Don't pile on with more errors.
9159
9160 // Clear marks immediately to avoid growing buffer.
9161 performance.clearMarks(formattedMarkName);
9162 performance.clearMeasures(formattedLabel);
9163};
9164
9165var getFiberMarkName = function (label, debugID) {
9166 return label + ' (#' + debugID + ')';
9167};
9168
9169var getFiberLabel = function (componentName, isMounted, phase) {
9170 if (phase === null) {
9171 // These are composite component total time measurements.
9172 return componentName + ' [' + (isMounted ? 'update' : 'mount') + ']';
9173 } else {
9174 // Composite component methods.
9175 return componentName + '.' + phase;
9176 }
9177};
9178
9179var beginFiberMark = function (fiber, phase) {
9180 var componentName = getComponentName(fiber.type) || 'Unknown';
9181 var debugID = fiber._debugID;
9182 var isMounted = fiber.alternate !== null;
9183 var label = getFiberLabel(componentName, isMounted, phase);
9184
9185 if (isCommitting && labelsInCurrentCommit.has(label)) {
9186 // During the commit phase, we don't show duplicate labels because
9187 // there is a fixed overhead for every measurement, and we don't
9188 // want to stretch the commit phase beyond necessary.
9189 return false;
9190 }
9191 labelsInCurrentCommit.add(label);
9192
9193 var markName = getFiberMarkName(label, debugID);
9194 beginMark(markName);
9195 return true;
9196};
9197
9198var clearFiberMark = function (fiber, phase) {
9199 var componentName = getComponentName(fiber.type) || 'Unknown';
9200 var debugID = fiber._debugID;
9201 var isMounted = fiber.alternate !== null;
9202 var label = getFiberLabel(componentName, isMounted, phase);
9203 var markName = getFiberMarkName(label, debugID);
9204 clearMark(markName);
9205};
9206
9207var endFiberMark = function (fiber, phase, warning) {
9208 var componentName = getComponentName(fiber.type) || 'Unknown';
9209 var debugID = fiber._debugID;
9210 var isMounted = fiber.alternate !== null;
9211 var label = getFiberLabel(componentName, isMounted, phase);
9212 var markName = getFiberMarkName(label, debugID);
9213 endMark(label, markName, warning);
9214};
9215
9216var shouldIgnoreFiber = function (fiber) {
9217 // Host components should be skipped in the timeline.
9218 // We could check typeof fiber.type, but does this work with RN?
9219 switch (fiber.tag) {
9220 case HostRoot:
9221 case HostComponent:
9222 case HostText:
9223 case HostPortal:
9224 case Fragment:
9225 case ContextProvider:
9226 case ContextConsumer:
9227 case Mode:
9228 return true;
9229 default:
9230 return false;
9231 }
9232};
9233
9234var clearPendingPhaseMeasurement = function () {
9235 if (currentPhase !== null && currentPhaseFiber !== null) {
9236 clearFiberMark(currentPhaseFiber, currentPhase);
9237 }
9238 currentPhaseFiber = null;
9239 currentPhase = null;
9240 hasScheduledUpdateInCurrentPhase = false;
9241};
9242
9243var pauseTimers = function () {
9244 // Stops all currently active measurements so that they can be resumed
9245 // if we continue in a later deferred loop from the same unit of work.
9246 var fiber = currentFiber;
9247 while (fiber) {
9248 if (fiber._debugIsCurrentlyTiming) {
9249 endFiberMark(fiber, null, null);
9250 }
9251 fiber = fiber.return;
9252 }
9253};
9254
9255var resumeTimersRecursively = function (fiber) {
9256 if (fiber.return !== null) {
9257 resumeTimersRecursively(fiber.return);
9258 }
9259 if (fiber._debugIsCurrentlyTiming) {
9260 beginFiberMark(fiber, null);
9261 }
9262};
9263
9264var resumeTimers = function () {
9265 // Resumes all measurements that were active during the last deferred loop.
9266 if (currentFiber !== null) {
9267 resumeTimersRecursively(currentFiber);
9268 }
9269};
9270
9271function recordEffect() {
9272 if (enableUserTimingAPI) {
9273 effectCountInCurrentCommit++;
9274 }
9275}
9276
9277function recordScheduleUpdate() {
9278 if (enableUserTimingAPI) {
9279 if (isCommitting) {
9280 hasScheduledUpdateInCurrentCommit = true;
9281 }
9282 if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
9283 hasScheduledUpdateInCurrentPhase = true;
9284 }
9285 }
9286}
9287
9288function startRequestCallbackTimer() {
9289 if (enableUserTimingAPI) {
9290 if (supportsUserTiming && !isWaitingForCallback) {
9291 isWaitingForCallback = true;
9292 beginMark('(Waiting for async callback...)');
9293 }
9294 }
9295}
9296
9297function stopRequestCallbackTimer(didExpire, expirationTime) {
9298 if (enableUserTimingAPI) {
9299 if (supportsUserTiming) {
9300 isWaitingForCallback = false;
9301 var warning = didExpire ? 'React was blocked by main thread' : null;
9302 endMark('(Waiting for async callback... will force flush in ' + expirationTime + ' ms)', '(Waiting for async callback...)', warning);
9303 }
9304 }
9305}
9306
9307function startWorkTimer(fiber) {
9308 if (enableUserTimingAPI) {
9309 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9310 return;
9311 }
9312 // If we pause, this is the fiber to unwind from.
9313 currentFiber = fiber;
9314 if (!beginFiberMark(fiber, null)) {
9315 return;
9316 }
9317 fiber._debugIsCurrentlyTiming = true;
9318 }
9319}
9320
9321function cancelWorkTimer(fiber) {
9322 if (enableUserTimingAPI) {
9323 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9324 return;
9325 }
9326 // Remember we shouldn't complete measurement for this fiber.
9327 // Otherwise flamechart will be deep even for small updates.
9328 fiber._debugIsCurrentlyTiming = false;
9329 clearFiberMark(fiber, null);
9330 }
9331}
9332
9333function stopWorkTimer(fiber) {
9334 if (enableUserTimingAPI) {
9335 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9336 return;
9337 }
9338 // If we pause, its parent is the fiber to unwind from.
9339 currentFiber = fiber.return;
9340 if (!fiber._debugIsCurrentlyTiming) {
9341 return;
9342 }
9343 fiber._debugIsCurrentlyTiming = false;
9344 endFiberMark(fiber, null, null);
9345 }
9346}
9347
9348function stopFailedWorkTimer(fiber) {
9349 if (enableUserTimingAPI) {
9350 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9351 return;
9352 }
9353 // If we pause, its parent is the fiber to unwind from.
9354 currentFiber = fiber.return;
9355 if (!fiber._debugIsCurrentlyTiming) {
9356 return;
9357 }
9358 fiber._debugIsCurrentlyTiming = false;
9359 var warning = fiber.tag === SuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
9360 endFiberMark(fiber, null, warning);
9361 }
9362}
9363
9364function startPhaseTimer(fiber, phase) {
9365 if (enableUserTimingAPI) {
9366 if (!supportsUserTiming) {
9367 return;
9368 }
9369 clearPendingPhaseMeasurement();
9370 if (!beginFiberMark(fiber, phase)) {
9371 return;
9372 }
9373 currentPhaseFiber = fiber;
9374 currentPhase = phase;
9375 }
9376}
9377
9378function stopPhaseTimer() {
9379 if (enableUserTimingAPI) {
9380 if (!supportsUserTiming) {
9381 return;
9382 }
9383 if (currentPhase !== null && currentPhaseFiber !== null) {
9384 var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
9385 endFiberMark(currentPhaseFiber, currentPhase, warning);
9386 }
9387 currentPhase = null;
9388 currentPhaseFiber = null;
9389 }
9390}
9391
9392function startWorkLoopTimer(nextUnitOfWork) {
9393 if (enableUserTimingAPI) {
9394 currentFiber = nextUnitOfWork;
9395 if (!supportsUserTiming) {
9396 return;
9397 }
9398 commitCountInCurrentWorkLoop = 0;
9399 // This is top level call.
9400 // Any other measurements are performed within.
9401 beginMark('(React Tree Reconciliation)');
9402 // Resume any measurements that were in progress during the last loop.
9403 resumeTimers();
9404 }
9405}
9406
9407function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
9408 if (enableUserTimingAPI) {
9409 if (!supportsUserTiming) {
9410 return;
9411 }
9412 var warning = null;
9413 if (interruptedBy !== null) {
9414 if (interruptedBy.tag === HostRoot) {
9415 warning = 'A top-level update interrupted the previous render';
9416 } else {
9417 var componentName = getComponentName(interruptedBy.type) || 'Unknown';
9418 warning = 'An update to ' + componentName + ' interrupted the previous render';
9419 }
9420 } else if (commitCountInCurrentWorkLoop > 1) {
9421 warning = 'There were cascading updates';
9422 }
9423 commitCountInCurrentWorkLoop = 0;
9424 var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)';
9425 // Pause any measurements until the next loop.
9426 pauseTimers();
9427 endMark(label, '(React Tree Reconciliation)', warning);
9428 }
9429}
9430
9431function startCommitTimer() {
9432 if (enableUserTimingAPI) {
9433 if (!supportsUserTiming) {
9434 return;
9435 }
9436 isCommitting = true;
9437 hasScheduledUpdateInCurrentCommit = false;
9438 labelsInCurrentCommit.clear();
9439 beginMark('(Committing Changes)');
9440 }
9441}
9442
9443function stopCommitTimer() {
9444 if (enableUserTimingAPI) {
9445 if (!supportsUserTiming) {
9446 return;
9447 }
9448
9449 var warning = null;
9450 if (hasScheduledUpdateInCurrentCommit) {
9451 warning = 'Lifecycle hook scheduled a cascading update';
9452 } else if (commitCountInCurrentWorkLoop > 0) {
9453 warning = 'Caused by a cascading update in earlier commit';
9454 }
9455 hasScheduledUpdateInCurrentCommit = false;
9456 commitCountInCurrentWorkLoop++;
9457 isCommitting = false;
9458 labelsInCurrentCommit.clear();
9459
9460 endMark('(Committing Changes)', '(Committing Changes)', warning);
9461 }
9462}
9463
9464function startCommitSnapshotEffectsTimer() {
9465 if (enableUserTimingAPI) {
9466 if (!supportsUserTiming) {
9467 return;
9468 }
9469 effectCountInCurrentCommit = 0;
9470 beginMark('(Committing Snapshot Effects)');
9471 }
9472}
9473
9474function stopCommitSnapshotEffectsTimer() {
9475 if (enableUserTimingAPI) {
9476 if (!supportsUserTiming) {
9477 return;
9478 }
9479 var count = effectCountInCurrentCommit;
9480 effectCountInCurrentCommit = 0;
9481 endMark('(Committing Snapshot Effects: ' + count + ' Total)', '(Committing Snapshot Effects)', null);
9482 }
9483}
9484
9485function startCommitHostEffectsTimer() {
9486 if (enableUserTimingAPI) {
9487 if (!supportsUserTiming) {
9488 return;
9489 }
9490 effectCountInCurrentCommit = 0;
9491 beginMark('(Committing Host Effects)');
9492 }
9493}
9494
9495function stopCommitHostEffectsTimer() {
9496 if (enableUserTimingAPI) {
9497 if (!supportsUserTiming) {
9498 return;
9499 }
9500 var count = effectCountInCurrentCommit;
9501 effectCountInCurrentCommit = 0;
9502 endMark('(Committing Host Effects: ' + count + ' Total)', '(Committing Host Effects)', null);
9503 }
9504}
9505
9506function startCommitLifeCyclesTimer() {
9507 if (enableUserTimingAPI) {
9508 if (!supportsUserTiming) {
9509 return;
9510 }
9511 effectCountInCurrentCommit = 0;
9512 beginMark('(Calling Lifecycle Methods)');
9513 }
9514}
9515
9516function stopCommitLifeCyclesTimer() {
9517 if (enableUserTimingAPI) {
9518 if (!supportsUserTiming) {
9519 return;
9520 }
9521 var count = effectCountInCurrentCommit;
9522 effectCountInCurrentCommit = 0;
9523 endMark('(Calling Lifecycle Methods: ' + count + ' Total)', '(Calling Lifecycle Methods)', null);
9524 }
9525}
9526
9527var valueStack = [];
9528
9529var fiberStack = void 0;
9530
9531{
9532 fiberStack = [];
9533}
9534
9535var index = -1;
9536
9537function createCursor(defaultValue) {
9538 return {
9539 current: defaultValue
9540 };
9541}
9542
9543function pop(cursor, fiber) {
9544 if (index < 0) {
9545 {
9546 warningWithoutStack$1(false, 'Unexpected pop.');
9547 }
9548 return;
9549 }
9550
9551 {
9552 if (fiber !== fiberStack[index]) {
9553 warningWithoutStack$1(false, 'Unexpected Fiber popped.');
9554 }
9555 }
9556
9557 cursor.current = valueStack[index];
9558
9559 valueStack[index] = null;
9560
9561 {
9562 fiberStack[index] = null;
9563 }
9564
9565 index--;
9566}
9567
9568function push(cursor, value, fiber) {
9569 index++;
9570
9571 valueStack[index] = cursor.current;
9572
9573 {
9574 fiberStack[index] = fiber;
9575 }
9576
9577 cursor.current = value;
9578}
9579
9580function checkThatStackIsEmpty() {
9581 {
9582 if (index !== -1) {
9583 warningWithoutStack$1(false, 'Expected an empty stack. Something was not reset properly.');
9584 }
9585 }
9586}
9587
9588function resetStackAfterFatalErrorInDev() {
9589 {
9590 index = -1;
9591 valueStack.length = 0;
9592 fiberStack.length = 0;
9593 }
9594}
9595
9596var warnedAboutMissingGetChildContext = void 0;
9597
9598{
9599 warnedAboutMissingGetChildContext = {};
9600}
9601
9602var emptyContextObject = {};
9603{
9604 Object.freeze(emptyContextObject);
9605}
9606
9607// A cursor to the current merged context object on the stack.
9608var contextStackCursor = createCursor(emptyContextObject);
9609// A cursor to a boolean indicating whether the context has changed.
9610var didPerformWorkStackCursor = createCursor(false);
9611// Keep track of the previous context object that was on the stack.
9612// We use this to get access to the parent context after we have already
9613// pushed the next context provider, and now need to merge their contexts.
9614var previousContext = emptyContextObject;
9615
9616function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
9617 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
9618 // If the fiber is a context provider itself, when we read its context
9619 // we may have already pushed its own child context on the stack. A context
9620 // provider should not "see" its own child context. Therefore we read the
9621 // previous (parent) context instead for a context provider.
9622 return previousContext;
9623 }
9624 return contextStackCursor.current;
9625}
9626
9627function cacheContext(workInProgress, unmaskedContext, maskedContext) {
9628 var instance = workInProgress.stateNode;
9629 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
9630 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
9631}
9632
9633function getMaskedContext(workInProgress, unmaskedContext) {
9634 var type = workInProgress.type;
9635 var contextTypes = type.contextTypes;
9636 if (!contextTypes) {
9637 return emptyContextObject;
9638 }
9639
9640 // Avoid recreating masked context unless unmasked context has changed.
9641 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
9642 // This may trigger infinite loops if componentWillReceiveProps calls setState.
9643 var instance = workInProgress.stateNode;
9644 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
9645 return instance.__reactInternalMemoizedMaskedChildContext;
9646 }
9647
9648 var context = {};
9649 for (var key in contextTypes) {
9650 context[key] = unmaskedContext[key];
9651 }
9652
9653 {
9654 var name = getComponentName(type) || 'Unknown';
9655 checkPropTypes_1(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
9656 }
9657
9658 // Cache unmasked context so we can avoid recreating masked context unless necessary.
9659 // Context is created before the class component is instantiated so check for instance.
9660 if (instance) {
9661 cacheContext(workInProgress, unmaskedContext, context);
9662 }
9663
9664 return context;
9665}
9666
9667function hasContextChanged() {
9668 return didPerformWorkStackCursor.current;
9669}
9670
9671function isContextProvider(type) {
9672 var childContextTypes = type.childContextTypes;
9673 return childContextTypes !== null && childContextTypes !== undefined;
9674}
9675
9676function popContext(fiber) {
9677 pop(didPerformWorkStackCursor, fiber);
9678 pop(contextStackCursor, fiber);
9679}
9680
9681function popTopLevelContextObject(fiber) {
9682 pop(didPerformWorkStackCursor, fiber);
9683 pop(contextStackCursor, fiber);
9684}
9685
9686function pushTopLevelContextObject(fiber, context, didChange) {
9687 !(contextStackCursor.current === emptyContextObject) ? invariant(false, 'Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.') : void 0;
9688
9689 push(contextStackCursor, context, fiber);
9690 push(didPerformWorkStackCursor, didChange, fiber);
9691}
9692
9693function processChildContext(fiber, type, parentContext) {
9694 var instance = fiber.stateNode;
9695 var childContextTypes = type.childContextTypes;
9696
9697 // TODO (bvaughn) Replace this behavior with an invariant() in the future.
9698 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
9699 if (typeof instance.getChildContext !== 'function') {
9700 {
9701 var componentName = getComponentName(type) || 'Unknown';
9702
9703 if (!warnedAboutMissingGetChildContext[componentName]) {
9704 warnedAboutMissingGetChildContext[componentName] = true;
9705 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);
9706 }
9707 }
9708 return parentContext;
9709 }
9710
9711 var childContext = void 0;
9712 {
9713 setCurrentPhase('getChildContext');
9714 }
9715 startPhaseTimer(fiber, 'getChildContext');
9716 childContext = instance.getChildContext();
9717 stopPhaseTimer();
9718 {
9719 setCurrentPhase(null);
9720 }
9721 for (var contextKey in childContext) {
9722 !(contextKey in childContextTypes) ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName(type) || 'Unknown', contextKey) : void 0;
9723 }
9724 {
9725 var name = getComponentName(type) || 'Unknown';
9726 checkPropTypes_1(childContextTypes, childContext, 'child context', name,
9727 // In practice, there is one case in which we won't get a stack. It's when
9728 // somebody calls unstable_renderSubtreeIntoContainer() and we process
9729 // context from the parent component instance. The stack will be missing
9730 // because it's outside of the reconciliation, and so the pointer has not
9731 // been set. This is rare and doesn't matter. We'll also remove that API.
9732 getCurrentFiberStackInDev);
9733 }
9734
9735 return _assign({}, parentContext, childContext);
9736}
9737
9738function pushContextProvider(workInProgress) {
9739 var instance = workInProgress.stateNode;
9740 // We push the context as early as possible to ensure stack integrity.
9741 // If the instance does not exist yet, we will push null at first,
9742 // and replace it on the stack later when invalidating the context.
9743 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject;
9744
9745 // Remember the parent context so we can merge with it later.
9746 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
9747 previousContext = contextStackCursor.current;
9748 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
9749 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
9750
9751 return true;
9752}
9753
9754function invalidateContextProvider(workInProgress, type, didChange) {
9755 var instance = workInProgress.stateNode;
9756 !instance ? invariant(false, 'Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.') : void 0;
9757
9758 if (didChange) {
9759 // Merge parent and own context.
9760 // Skip this if we're not updating due to sCU.
9761 // This avoids unnecessarily recomputing memoized values.
9762 var mergedContext = processChildContext(workInProgress, type, previousContext);
9763 instance.__reactInternalMemoizedMergedChildContext = mergedContext;
9764
9765 // Replace the old (or empty) context with the new one.
9766 // It is important to unwind the context in the reverse order.
9767 pop(didPerformWorkStackCursor, workInProgress);
9768 pop(contextStackCursor, workInProgress);
9769 // Now push the new context and mark that it has changed.
9770 push(contextStackCursor, mergedContext, workInProgress);
9771 push(didPerformWorkStackCursor, didChange, workInProgress);
9772 } else {
9773 pop(didPerformWorkStackCursor, workInProgress);
9774 push(didPerformWorkStackCursor, didChange, workInProgress);
9775 }
9776}
9777
9778function findCurrentUnmaskedContext(fiber) {
9779 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
9780 // makes sense elsewhere
9781 !(isFiberMounted(fiber) && fiber.tag === ClassComponent) ? invariant(false, 'Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.') : void 0;
9782
9783 var node = fiber;
9784 do {
9785 switch (node.tag) {
9786 case HostRoot:
9787 return node.stateNode.context;
9788 case ClassComponent:
9789 {
9790 var Component = node.type;
9791 if (isContextProvider(Component)) {
9792 return node.stateNode.__reactInternalMemoizedMergedChildContext;
9793 }
9794 break;
9795 }
9796 }
9797 node = node.return;
9798 } while (node !== null);
9799 invariant(false, 'Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.');
9800}
9801
9802var onCommitFiberRoot = null;
9803var onCommitFiberUnmount = null;
9804var hasLoggedError = false;
9805
9806function catchErrors(fn) {
9807 return function (arg) {
9808 try {
9809 return fn(arg);
9810 } catch (err) {
9811 if (true && !hasLoggedError) {
9812 hasLoggedError = true;
9813 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
9814 }
9815 }
9816 };
9817}
9818
9819var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
9820
9821function injectInternals(internals) {
9822 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
9823 // No DevTools
9824 return false;
9825 }
9826 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
9827 if (hook.isDisabled) {
9828 // This isn't a real property on the hook, but it can be set to opt out
9829 // of DevTools integration and associated warnings and logs.
9830 // https://github.com/facebook/react/issues/3877
9831 return true;
9832 }
9833 if (!hook.supportsFiber) {
9834 {
9835 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');
9836 }
9837 // DevTools exists, even though it doesn't support Fiber.
9838 return true;
9839 }
9840 try {
9841 var rendererID = hook.inject(internals);
9842 // We have successfully injected, so now it is safe to set up hooks.
9843 onCommitFiberRoot = catchErrors(function (root) {
9844 return hook.onCommitFiberRoot(rendererID, root);
9845 });
9846 onCommitFiberUnmount = catchErrors(function (fiber) {
9847 return hook.onCommitFiberUnmount(rendererID, fiber);
9848 });
9849 } catch (err) {
9850 // Catch all errors because it is unsafe to throw during initialization.
9851 {
9852 warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
9853 }
9854 }
9855 // DevTools exists
9856 return true;
9857}
9858
9859function onCommitRoot(root) {
9860 if (typeof onCommitFiberRoot === 'function') {
9861 onCommitFiberRoot(root);
9862 }
9863}
9864
9865function onCommitUnmount(fiber) {
9866 if (typeof onCommitFiberUnmount === 'function') {
9867 onCommitFiberUnmount(fiber);
9868 }
9869}
9870
9871// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
9872// Math.pow(2, 30) - 1
9873// 0b111111111111111111111111111111
9874var maxSigned31BitInt = 1073741823;
9875
9876var NoWork = 0;
9877var Never = 1;
9878var Sync = maxSigned31BitInt;
9879
9880var UNIT_SIZE = 10;
9881var MAGIC_NUMBER_OFFSET = maxSigned31BitInt - 1;
9882
9883// 1 unit of expiration time represents 10ms.
9884function msToExpirationTime(ms) {
9885 // Always add an offset so that we don't clash with the magic number for NoWork.
9886 return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
9887}
9888
9889function expirationTimeToMs(expirationTime) {
9890 return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
9891}
9892
9893function ceiling(num, precision) {
9894 return ((num / precision | 0) + 1) * precision;
9895}
9896
9897function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
9898 return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
9899}
9900
9901var LOW_PRIORITY_EXPIRATION = 5000;
9902var LOW_PRIORITY_BATCH_SIZE = 250;
9903
9904function computeAsyncExpiration(currentTime) {
9905 return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
9906}
9907
9908// We intentionally set a higher expiration time for interactive updates in
9909// dev than in production.
9910//
9911// If the main thread is being blocked so long that you hit the expiration,
9912// it's a problem that could be solved with better scheduling.
9913//
9914// People will be more likely to notice this and fix it with the long
9915// expiration time in development.
9916//
9917// In production we opt for better UX at the risk of masking scheduling
9918// problems, by expiring fast.
9919var HIGH_PRIORITY_EXPIRATION = 500;
9920var HIGH_PRIORITY_BATCH_SIZE = 100;
9921
9922function computeInteractiveExpiration(currentTime) {
9923 return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
9924}
9925
9926var NoContext = 0;
9927var ConcurrentMode = 1;
9928var StrictMode = 2;
9929var ProfileMode = 4;
9930
9931var hasBadMapPolyfill = void 0;
9932
9933{
9934 hasBadMapPolyfill = false;
9935 try {
9936 var nonExtensibleObject = Object.preventExtensions({});
9937 var testMap = new Map([[nonExtensibleObject, null]]);
9938 var testSet = new Set([nonExtensibleObject]);
9939 // This is necessary for Rollup to not consider these unused.
9940 // https://github.com/rollup/rollup/issues/1771
9941 // TODO: we can remove these if Rollup fixes the bug.
9942 testMap.set(0, 0);
9943 testSet.add(0);
9944 } catch (e) {
9945 // TODO: Consider warning about bad polyfills
9946 hasBadMapPolyfill = true;
9947 }
9948}
9949
9950// A Fiber is work on a Component that needs to be done or was done. There can
9951// be more than one per component.
9952
9953
9954var debugCounter = void 0;
9955
9956{
9957 debugCounter = 1;
9958}
9959
9960function FiberNode(tag, pendingProps, key, mode) {
9961 // Instance
9962 this.tag = tag;
9963 this.key = key;
9964 this.elementType = null;
9965 this.type = null;
9966 this.stateNode = null;
9967
9968 // Fiber
9969 this.return = null;
9970 this.child = null;
9971 this.sibling = null;
9972 this.index = 0;
9973
9974 this.ref = null;
9975
9976 this.pendingProps = pendingProps;
9977 this.memoizedProps = null;
9978 this.updateQueue = null;
9979 this.memoizedState = null;
9980 this.contextDependencies = null;
9981
9982 this.mode = mode;
9983
9984 // Effects
9985 this.effectTag = NoEffect;
9986 this.nextEffect = null;
9987
9988 this.firstEffect = null;
9989 this.lastEffect = null;
9990
9991 this.expirationTime = NoWork;
9992 this.childExpirationTime = NoWork;
9993
9994 this.alternate = null;
9995
9996 if (enableProfilerTimer) {
9997 // Note: The following is done to avoid a v8 performance cliff.
9998 //
9999 // Initializing the fields below to smis and later updating them with
10000 // double values will cause Fibers to end up having separate shapes.
10001 // This behavior/bug has something to do with Object.preventExtension().
10002 // Fortunately this only impacts DEV builds.
10003 // Unfortunately it makes React unusably slow for some applications.
10004 // To work around this, initialize the fields below with doubles.
10005 //
10006 // Learn more about this here:
10007 // https://github.com/facebook/react/issues/14365
10008 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
10009 this.actualDuration = Number.NaN;
10010 this.actualStartTime = Number.NaN;
10011 this.selfBaseDuration = Number.NaN;
10012 this.treeBaseDuration = Number.NaN;
10013
10014 // It's okay to replace the initial doubles with smis after initialization.
10015 // This won't trigger the performance cliff mentioned above,
10016 // and it simplifies other profiler code (including DevTools).
10017 this.actualDuration = 0;
10018 this.actualStartTime = -1;
10019 this.selfBaseDuration = 0;
10020 this.treeBaseDuration = 0;
10021 }
10022
10023 {
10024 this._debugID = debugCounter++;
10025 this._debugSource = null;
10026 this._debugOwner = null;
10027 this._debugIsCurrentlyTiming = false;
10028 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
10029 Object.preventExtensions(this);
10030 }
10031 }
10032}
10033
10034// This is a constructor function, rather than a POJO constructor, still
10035// please ensure we do the following:
10036// 1) Nobody should add any instance methods on this. Instance methods can be
10037// more difficult to predict when they get optimized and they are almost
10038// never inlined properly in static compilers.
10039// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
10040// always know when it is a fiber.
10041// 3) We might want to experiment with using numeric keys since they are easier
10042// to optimize in a non-JIT environment.
10043// 4) We can easily go from a constructor to a createFiber object literal if that
10044// is faster.
10045// 5) It should be easy to port this to a C struct and keep a C implementation
10046// compatible.
10047var createFiber = function (tag, pendingProps, key, mode) {
10048 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
10049 return new FiberNode(tag, pendingProps, key, mode);
10050};
10051
10052function shouldConstruct(Component) {
10053 var prototype = Component.prototype;
10054 return !!(prototype && prototype.isReactComponent);
10055}
10056
10057function isSimpleFunctionComponent(type) {
10058 return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
10059}
10060
10061function resolveLazyComponentTag(Component) {
10062 if (typeof Component === 'function') {
10063 return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
10064 } else if (Component !== undefined && Component !== null) {
10065 var $$typeof = Component.$$typeof;
10066 if ($$typeof === REACT_FORWARD_REF_TYPE) {
10067 return ForwardRef;
10068 }
10069 if ($$typeof === REACT_MEMO_TYPE) {
10070 return MemoComponent;
10071 }
10072 }
10073 return IndeterminateComponent;
10074}
10075
10076// This is used to create an alternate fiber to do work on.
10077function createWorkInProgress(current, pendingProps, expirationTime) {
10078 var workInProgress = current.alternate;
10079 if (workInProgress === null) {
10080 // We use a double buffering pooling technique because we know that we'll
10081 // only ever need at most two versions of a tree. We pool the "other" unused
10082 // node that we're free to reuse. This is lazily created to avoid allocating
10083 // extra objects for things that are never updated. It also allow us to
10084 // reclaim the extra memory if needed.
10085 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
10086 workInProgress.elementType = current.elementType;
10087 workInProgress.type = current.type;
10088 workInProgress.stateNode = current.stateNode;
10089
10090 {
10091 // DEV-only fields
10092 workInProgress._debugID = current._debugID;
10093 workInProgress._debugSource = current._debugSource;
10094 workInProgress._debugOwner = current._debugOwner;
10095 }
10096
10097 workInProgress.alternate = current;
10098 current.alternate = workInProgress;
10099 } else {
10100 workInProgress.pendingProps = pendingProps;
10101
10102 // We already have an alternate.
10103 // Reset the effect tag.
10104 workInProgress.effectTag = NoEffect;
10105
10106 // The effect list is no longer valid.
10107 workInProgress.nextEffect = null;
10108 workInProgress.firstEffect = null;
10109 workInProgress.lastEffect = null;
10110
10111 if (enableProfilerTimer) {
10112 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
10113 // This prevents time from endlessly accumulating in new commits.
10114 // This has the downside of resetting values for different priority renders,
10115 // But works for yielding (the common case) and should support resuming.
10116 workInProgress.actualDuration = 0;
10117 workInProgress.actualStartTime = -1;
10118 }
10119 }
10120
10121 workInProgress.childExpirationTime = current.childExpirationTime;
10122 workInProgress.expirationTime = current.expirationTime;
10123
10124 workInProgress.child = current.child;
10125 workInProgress.memoizedProps = current.memoizedProps;
10126 workInProgress.memoizedState = current.memoizedState;
10127 workInProgress.updateQueue = current.updateQueue;
10128 workInProgress.contextDependencies = current.contextDependencies;
10129
10130 // These will be overridden during the parent's reconciliation
10131 workInProgress.sibling = current.sibling;
10132 workInProgress.index = current.index;
10133 workInProgress.ref = current.ref;
10134
10135 if (enableProfilerTimer) {
10136 workInProgress.selfBaseDuration = current.selfBaseDuration;
10137 workInProgress.treeBaseDuration = current.treeBaseDuration;
10138 }
10139
10140 return workInProgress;
10141}
10142
10143function createHostRootFiber(isConcurrent) {
10144 var mode = isConcurrent ? ConcurrentMode | StrictMode : NoContext;
10145
10146 if (enableProfilerTimer && isDevToolsPresent) {
10147 // Always collect profile timings when DevTools are present.
10148 // This enables DevTools to start capturing timing at any point–
10149 // Without some nodes in the tree having empty base times.
10150 mode |= ProfileMode;
10151 }
10152
10153 return createFiber(HostRoot, null, null, mode);
10154}
10155
10156function createFiberFromTypeAndProps(type, // React$ElementType
10157key, pendingProps, owner, mode, expirationTime) {
10158 var fiber = void 0;
10159
10160 var fiberTag = IndeterminateComponent;
10161 // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
10162 var resolvedType = type;
10163 if (typeof type === 'function') {
10164 if (shouldConstruct(type)) {
10165 fiberTag = ClassComponent;
10166 }
10167 } else if (typeof type === 'string') {
10168 fiberTag = HostComponent;
10169 } else {
10170 getTag: switch (type) {
10171 case REACT_FRAGMENT_TYPE:
10172 return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
10173 case REACT_CONCURRENT_MODE_TYPE:
10174 return createFiberFromMode(pendingProps, mode | ConcurrentMode | StrictMode, expirationTime, key);
10175 case REACT_STRICT_MODE_TYPE:
10176 return createFiberFromMode(pendingProps, mode | StrictMode, expirationTime, key);
10177 case REACT_PROFILER_TYPE:
10178 return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
10179 case REACT_SUSPENSE_TYPE:
10180 return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
10181 default:
10182 {
10183 if (typeof type === 'object' && type !== null) {
10184 switch (type.$$typeof) {
10185 case REACT_PROVIDER_TYPE:
10186 fiberTag = ContextProvider;
10187 break getTag;
10188 case REACT_CONTEXT_TYPE:
10189 // This is a consumer
10190 fiberTag = ContextConsumer;
10191 break getTag;
10192 case REACT_FORWARD_REF_TYPE:
10193 fiberTag = ForwardRef;
10194 break getTag;
10195 case REACT_MEMO_TYPE:
10196 fiberTag = MemoComponent;
10197 break getTag;
10198 case REACT_LAZY_TYPE:
10199 fiberTag = LazyComponent;
10200 resolvedType = null;
10201 break getTag;
10202 }
10203 }
10204 var info = '';
10205 {
10206 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
10207 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.';
10208 }
10209 var ownerName = owner ? getComponentName(owner.type) : null;
10210 if (ownerName) {
10211 info += '\n\nCheck the render method of `' + ownerName + '`.';
10212 }
10213 }
10214 invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', type == null ? type : typeof type, info);
10215 }
10216 }
10217 }
10218
10219 fiber = createFiber(fiberTag, pendingProps, key, mode);
10220 fiber.elementType = type;
10221 fiber.type = resolvedType;
10222 fiber.expirationTime = expirationTime;
10223
10224 return fiber;
10225}
10226
10227function createFiberFromElement(element, mode, expirationTime) {
10228 var owner = null;
10229 {
10230 owner = element._owner;
10231 }
10232 var type = element.type;
10233 var key = element.key;
10234 var pendingProps = element.props;
10235 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
10236 {
10237 fiber._debugSource = element._source;
10238 fiber._debugOwner = element._owner;
10239 }
10240 return fiber;
10241}
10242
10243function createFiberFromFragment(elements, mode, expirationTime, key) {
10244 var fiber = createFiber(Fragment, elements, key, mode);
10245 fiber.expirationTime = expirationTime;
10246 return fiber;
10247}
10248
10249function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
10250 {
10251 if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
10252 warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
10253 }
10254 }
10255
10256 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
10257 // TODO: The Profiler fiber shouldn't have a type. It has a tag.
10258 fiber.elementType = REACT_PROFILER_TYPE;
10259 fiber.type = REACT_PROFILER_TYPE;
10260 fiber.expirationTime = expirationTime;
10261
10262 return fiber;
10263}
10264
10265function createFiberFromMode(pendingProps, mode, expirationTime, key) {
10266 var fiber = createFiber(Mode, pendingProps, key, mode);
10267
10268 // TODO: The Mode fiber shouldn't have a type. It has a tag.
10269 var type = (mode & ConcurrentMode) === NoContext ? REACT_STRICT_MODE_TYPE : REACT_CONCURRENT_MODE_TYPE;
10270 fiber.elementType = type;
10271 fiber.type = type;
10272
10273 fiber.expirationTime = expirationTime;
10274 return fiber;
10275}
10276
10277function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
10278 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
10279
10280 // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
10281 var type = REACT_SUSPENSE_TYPE;
10282 fiber.elementType = type;
10283 fiber.type = type;
10284
10285 fiber.expirationTime = expirationTime;
10286 return fiber;
10287}
10288
10289function createFiberFromText(content, mode, expirationTime) {
10290 var fiber = createFiber(HostText, content, null, mode);
10291 fiber.expirationTime = expirationTime;
10292 return fiber;
10293}
10294
10295function createFiberFromHostInstanceForDeletion() {
10296 var fiber = createFiber(HostComponent, null, null, NoContext);
10297 // TODO: These should not need a type.
10298 fiber.elementType = 'DELETED';
10299 fiber.type = 'DELETED';
10300 return fiber;
10301}
10302
10303function createFiberFromPortal(portal, mode, expirationTime) {
10304 var pendingProps = portal.children !== null ? portal.children : [];
10305 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
10306 fiber.expirationTime = expirationTime;
10307 fiber.stateNode = {
10308 containerInfo: portal.containerInfo,
10309 pendingChildren: null, // Used by persistent updates
10310 implementation: portal.implementation
10311 };
10312 return fiber;
10313}
10314
10315// Used for stashing WIP properties to replay failed work in DEV.
10316function assignFiberPropertiesInDEV(target, source) {
10317 if (target === null) {
10318 // This Fiber's initial properties will always be overwritten.
10319 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
10320 target = createFiber(IndeterminateComponent, null, null, NoContext);
10321 }
10322
10323 // This is intentionally written as a list of all properties.
10324 // We tried to use Object.assign() instead but this is called in
10325 // the hottest path, and Object.assign() was too slow:
10326 // https://github.com/facebook/react/issues/12502
10327 // This code is DEV-only so size is not a concern.
10328
10329 target.tag = source.tag;
10330 target.key = source.key;
10331 target.elementType = source.elementType;
10332 target.type = source.type;
10333 target.stateNode = source.stateNode;
10334 target.return = source.return;
10335 target.child = source.child;
10336 target.sibling = source.sibling;
10337 target.index = source.index;
10338 target.ref = source.ref;
10339 target.pendingProps = source.pendingProps;
10340 target.memoizedProps = source.memoizedProps;
10341 target.updateQueue = source.updateQueue;
10342 target.memoizedState = source.memoizedState;
10343 target.contextDependencies = source.contextDependencies;
10344 target.mode = source.mode;
10345 target.effectTag = source.effectTag;
10346 target.nextEffect = source.nextEffect;
10347 target.firstEffect = source.firstEffect;
10348 target.lastEffect = source.lastEffect;
10349 target.expirationTime = source.expirationTime;
10350 target.childExpirationTime = source.childExpirationTime;
10351 target.alternate = source.alternate;
10352 if (enableProfilerTimer) {
10353 target.actualDuration = source.actualDuration;
10354 target.actualStartTime = source.actualStartTime;
10355 target.selfBaseDuration = source.selfBaseDuration;
10356 target.treeBaseDuration = source.treeBaseDuration;
10357 }
10358 target._debugID = source._debugID;
10359 target._debugSource = source._debugSource;
10360 target._debugOwner = source._debugOwner;
10361 target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
10362 return target;
10363}
10364
10365var ReactInternals$2 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
10366
10367var _ReactInternals$Sched$1 = ReactInternals$2.SchedulerTracing;
10368var __interactionsRef = _ReactInternals$Sched$1.__interactionsRef;
10369var __subscriberRef = _ReactInternals$Sched$1.__subscriberRef;
10370var unstable_clear = _ReactInternals$Sched$1.unstable_clear;
10371var unstable_getCurrent = _ReactInternals$Sched$1.unstable_getCurrent;
10372var unstable_getThreadID = _ReactInternals$Sched$1.unstable_getThreadID;
10373var unstable_subscribe = _ReactInternals$Sched$1.unstable_subscribe;
10374var unstable_trace = _ReactInternals$Sched$1.unstable_trace;
10375var unstable_unsubscribe = _ReactInternals$Sched$1.unstable_unsubscribe;
10376var unstable_wrap = _ReactInternals$Sched$1.unstable_wrap;
10377
10378// TODO: This should be lifted into the renderer.
10379
10380
10381// The following attributes are only used by interaction tracing builds.
10382// They enable interactions to be associated with their async work,
10383// And expose interaction metadata to the React DevTools Profiler plugin.
10384// Note that these attributes are only defined when the enableSchedulerTracing flag is enabled.
10385
10386
10387// Exported FiberRoot type includes all properties,
10388// To avoid requiring potentially error-prone :any casts throughout the project.
10389// Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true).
10390// The types are defined separately within this file to ensure they stay in sync.
10391// (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.)
10392
10393
10394function createFiberRoot(containerInfo, isConcurrent, hydrate) {
10395 // Cyclic construction. This cheats the type system right now because
10396 // stateNode is any.
10397 var uninitializedFiber = createHostRootFiber(isConcurrent);
10398
10399 var root = void 0;
10400 if (enableSchedulerTracing) {
10401 root = {
10402 current: uninitializedFiber,
10403 containerInfo: containerInfo,
10404 pendingChildren: null,
10405
10406 earliestPendingTime: NoWork,
10407 latestPendingTime: NoWork,
10408 earliestSuspendedTime: NoWork,
10409 latestSuspendedTime: NoWork,
10410 latestPingedTime: NoWork,
10411
10412 pingCache: null,
10413
10414 didError: false,
10415
10416 pendingCommitExpirationTime: NoWork,
10417 finishedWork: null,
10418 timeoutHandle: noTimeout,
10419 context: null,
10420 pendingContext: null,
10421 hydrate: hydrate,
10422 nextExpirationTimeToWorkOn: NoWork,
10423 expirationTime: NoWork,
10424 firstBatch: null,
10425 nextScheduledRoot: null,
10426
10427 interactionThreadID: unstable_getThreadID(),
10428 memoizedInteractions: new Set(),
10429 pendingInteractionMap: new Map()
10430 };
10431 } else {
10432 root = {
10433 current: uninitializedFiber,
10434 containerInfo: containerInfo,
10435 pendingChildren: null,
10436
10437 pingCache: null,
10438
10439 earliestPendingTime: NoWork,
10440 latestPendingTime: NoWork,
10441 earliestSuspendedTime: NoWork,
10442 latestSuspendedTime: NoWork,
10443 latestPingedTime: NoWork,
10444
10445 didError: false,
10446
10447 pendingCommitExpirationTime: NoWork,
10448 finishedWork: null,
10449 timeoutHandle: noTimeout,
10450 context: null,
10451 pendingContext: null,
10452 hydrate: hydrate,
10453 nextExpirationTimeToWorkOn: NoWork,
10454 expirationTime: NoWork,
10455 firstBatch: null,
10456 nextScheduledRoot: null
10457 };
10458 }
10459
10460 uninitializedFiber.stateNode = root;
10461
10462 // The reason for the way the Flow types are structured in this file,
10463 // Is to avoid needing :any casts everywhere interaction tracing fields are used.
10464 // Unfortunately that requires an :any cast for non-interaction tracing capable builds.
10465 // $FlowFixMe Remove this :any cast and replace it with something better.
10466 return root;
10467}
10468
10469/**
10470 * Forked from fbjs/warning:
10471 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
10472 *
10473 * Only change is we use console.warn instead of console.error,
10474 * and do nothing when 'console' is not supported.
10475 * This really simplifies the code.
10476 * ---
10477 * Similar to invariant but only logs a warning if the condition is not met.
10478 * This can be used to log issues in development environments in critical
10479 * paths. Removing the logging code for production environments will keep the
10480 * same logic and follow the same code paths.
10481 */
10482
10483var lowPriorityWarning = function () {};
10484
10485{
10486 var printWarning$1 = function (format) {
10487 for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
10488 args[_key - 1] = arguments[_key];
10489 }
10490
10491 var argIndex = 0;
10492 var message = 'Warning: ' + format.replace(/%s/g, function () {
10493 return args[argIndex++];
10494 });
10495 if (typeof console !== 'undefined') {
10496 console.warn(message);
10497 }
10498 try {
10499 // --- Welcome to debugging React ---
10500 // This error was thrown as a convenience so that you can use this stack
10501 // to find the callsite that caused this warning to fire.
10502 throw new Error(message);
10503 } catch (x) {}
10504 };
10505
10506 lowPriorityWarning = function (condition, format) {
10507 if (format === undefined) {
10508 throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
10509 }
10510 if (!condition) {
10511 for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
10512 args[_key2 - 2] = arguments[_key2];
10513 }
10514
10515 printWarning$1.apply(undefined, [format].concat(args));
10516 }
10517 };
10518}
10519
10520var lowPriorityWarning$1 = lowPriorityWarning;
10521
10522var ReactStrictModeWarnings = {
10523 discardPendingWarnings: function () {},
10524 flushPendingDeprecationWarnings: function () {},
10525 flushPendingUnsafeLifecycleWarnings: function () {},
10526 recordDeprecationWarnings: function (fiber, instance) {},
10527 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
10528 recordLegacyContextWarning: function (fiber, instance) {},
10529 flushLegacyContextWarning: function () {}
10530};
10531
10532{
10533 var LIFECYCLE_SUGGESTIONS = {
10534 UNSAFE_componentWillMount: 'componentDidMount',
10535 UNSAFE_componentWillReceiveProps: 'static getDerivedStateFromProps',
10536 UNSAFE_componentWillUpdate: 'componentDidUpdate'
10537 };
10538
10539 var pendingComponentWillMountWarnings = [];
10540 var pendingComponentWillReceivePropsWarnings = [];
10541 var pendingComponentWillUpdateWarnings = [];
10542 var pendingUnsafeLifecycleWarnings = new Map();
10543 var pendingLegacyContextWarning = new Map();
10544
10545 // Tracks components we have already warned about.
10546 var didWarnAboutDeprecatedLifecycles = new Set();
10547 var didWarnAboutUnsafeLifecycles = new Set();
10548 var didWarnAboutLegacyContext = new Set();
10549
10550 var setToSortedString = function (set) {
10551 var array = [];
10552 set.forEach(function (value) {
10553 array.push(value);
10554 });
10555 return array.sort().join(', ');
10556 };
10557
10558 ReactStrictModeWarnings.discardPendingWarnings = function () {
10559 pendingComponentWillMountWarnings = [];
10560 pendingComponentWillReceivePropsWarnings = [];
10561 pendingComponentWillUpdateWarnings = [];
10562 pendingUnsafeLifecycleWarnings = new Map();
10563 pendingLegacyContextWarning = new Map();
10564 };
10565
10566 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
10567 pendingUnsafeLifecycleWarnings.forEach(function (lifecycleWarningsMap, strictRoot) {
10568 var lifecyclesWarningMessages = [];
10569
10570 Object.keys(lifecycleWarningsMap).forEach(function (lifecycle) {
10571 var lifecycleWarnings = lifecycleWarningsMap[lifecycle];
10572 if (lifecycleWarnings.length > 0) {
10573 var componentNames = new Set();
10574 lifecycleWarnings.forEach(function (fiber) {
10575 componentNames.add(getComponentName(fiber.type) || 'Component');
10576 didWarnAboutUnsafeLifecycles.add(fiber.type);
10577 });
10578
10579 var formatted = lifecycle.replace('UNSAFE_', '');
10580 var suggestion = LIFECYCLE_SUGGESTIONS[lifecycle];
10581 var sortedComponentNames = setToSortedString(componentNames);
10582
10583 lifecyclesWarningMessages.push(formatted + ': Please update the following components to use ' + (suggestion + ' instead: ' + sortedComponentNames));
10584 }
10585 });
10586
10587 if (lifecyclesWarningMessages.length > 0) {
10588 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
10589
10590 warningWithoutStack$1(false, 'Unsafe lifecycle methods were found within a strict-mode tree:%s' + '\n\n%s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-strict-mode-warnings', strictRootComponentStack, lifecyclesWarningMessages.join('\n\n'));
10591 }
10592 });
10593
10594 pendingUnsafeLifecycleWarnings = new Map();
10595 };
10596
10597 var findStrictRoot = function (fiber) {
10598 var maybeStrictRoot = null;
10599
10600 var node = fiber;
10601 while (node !== null) {
10602 if (node.mode & StrictMode) {
10603 maybeStrictRoot = node;
10604 }
10605 node = node.return;
10606 }
10607
10608 return maybeStrictRoot;
10609 };
10610
10611 ReactStrictModeWarnings.flushPendingDeprecationWarnings = function () {
10612 if (pendingComponentWillMountWarnings.length > 0) {
10613 var uniqueNames = new Set();
10614 pendingComponentWillMountWarnings.forEach(function (fiber) {
10615 uniqueNames.add(getComponentName(fiber.type) || 'Component');
10616 didWarnAboutDeprecatedLifecycles.add(fiber.type);
10617 });
10618
10619 var sortedNames = setToSortedString(uniqueNames);
10620
10621 lowPriorityWarning$1(false, 'componentWillMount is deprecated and will be removed in the next major version. ' + 'Use componentDidMount instead. As a temporary workaround, ' + 'you can rename to UNSAFE_componentWillMount.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', sortedNames);
10622
10623 pendingComponentWillMountWarnings = [];
10624 }
10625
10626 if (pendingComponentWillReceivePropsWarnings.length > 0) {
10627 var _uniqueNames = new Set();
10628 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
10629 _uniqueNames.add(getComponentName(fiber.type) || 'Component');
10630 didWarnAboutDeprecatedLifecycles.add(fiber.type);
10631 });
10632
10633 var _sortedNames = setToSortedString(_uniqueNames);
10634
10635 lowPriorityWarning$1(false, 'componentWillReceiveProps is deprecated and will be removed in the next major version. ' + 'Use static getDerivedStateFromProps instead.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', _sortedNames);
10636
10637 pendingComponentWillReceivePropsWarnings = [];
10638 }
10639
10640 if (pendingComponentWillUpdateWarnings.length > 0) {
10641 var _uniqueNames2 = new Set();
10642 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
10643 _uniqueNames2.add(getComponentName(fiber.type) || 'Component');
10644 didWarnAboutDeprecatedLifecycles.add(fiber.type);
10645 });
10646
10647 var _sortedNames2 = setToSortedString(_uniqueNames2);
10648
10649 lowPriorityWarning$1(false, 'componentWillUpdate is deprecated and will be removed in the next major version. ' + 'Use componentDidUpdate instead. As a temporary workaround, ' + 'you can rename to UNSAFE_componentWillUpdate.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', _sortedNames2);
10650
10651 pendingComponentWillUpdateWarnings = [];
10652 }
10653 };
10654
10655 ReactStrictModeWarnings.recordDeprecationWarnings = function (fiber, instance) {
10656 // Dedup strategy: Warn once per component.
10657 if (didWarnAboutDeprecatedLifecycles.has(fiber.type)) {
10658 return;
10659 }
10660
10661 // Don't warn about react-lifecycles-compat polyfilled components.
10662 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
10663 pendingComponentWillMountWarnings.push(fiber);
10664 }
10665 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
10666 pendingComponentWillReceivePropsWarnings.push(fiber);
10667 }
10668 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
10669 pendingComponentWillUpdateWarnings.push(fiber);
10670 }
10671 };
10672
10673 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
10674 var strictRoot = findStrictRoot(fiber);
10675 if (strictRoot === null) {
10676 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.');
10677 return;
10678 }
10679
10680 // Dedup strategy: Warn once per component.
10681 // This is difficult to track any other way since component names
10682 // are often vague and are likely to collide between 3rd party libraries.
10683 // An expand property is probably okay to use here since it's DEV-only,
10684 // and will only be set in the event of serious warnings.
10685 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
10686 return;
10687 }
10688
10689 var warningsForRoot = void 0;
10690 if (!pendingUnsafeLifecycleWarnings.has(strictRoot)) {
10691 warningsForRoot = {
10692 UNSAFE_componentWillMount: [],
10693 UNSAFE_componentWillReceiveProps: [],
10694 UNSAFE_componentWillUpdate: []
10695 };
10696
10697 pendingUnsafeLifecycleWarnings.set(strictRoot, warningsForRoot);
10698 } else {
10699 warningsForRoot = pendingUnsafeLifecycleWarnings.get(strictRoot);
10700 }
10701
10702 var unsafeLifecycles = [];
10703 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillMount === 'function') {
10704 unsafeLifecycles.push('UNSAFE_componentWillMount');
10705 }
10706 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
10707 unsafeLifecycles.push('UNSAFE_componentWillReceiveProps');
10708 }
10709 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillUpdate === 'function') {
10710 unsafeLifecycles.push('UNSAFE_componentWillUpdate');
10711 }
10712
10713 if (unsafeLifecycles.length > 0) {
10714 unsafeLifecycles.forEach(function (lifecycle) {
10715 warningsForRoot[lifecycle].push(fiber);
10716 });
10717 }
10718 };
10719
10720 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
10721 var strictRoot = findStrictRoot(fiber);
10722 if (strictRoot === null) {
10723 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.');
10724 return;
10725 }
10726
10727 // Dedup strategy: Warn once per component.
10728 if (didWarnAboutLegacyContext.has(fiber.type)) {
10729 return;
10730 }
10731
10732 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
10733
10734 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
10735 if (warningsForRoot === undefined) {
10736 warningsForRoot = [];
10737 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
10738 }
10739 warningsForRoot.push(fiber);
10740 }
10741 };
10742
10743 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
10744 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
10745 var uniqueNames = new Set();
10746 fiberArray.forEach(function (fiber) {
10747 uniqueNames.add(getComponentName(fiber.type) || 'Component');
10748 didWarnAboutLegacyContext.add(fiber.type);
10749 });
10750
10751 var sortedNames = setToSortedString(uniqueNames);
10752 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
10753
10754 warningWithoutStack$1(false, 'Legacy context API has been detected within a strict-mode tree: %s' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-strict-mode-warnings', strictRootComponentStack, sortedNames);
10755 });
10756 };
10757}
10758
10759// This lets us hook into Fiber to debug what it's doing.
10760// See https://github.com/facebook/react/pull/8033.
10761// This is not part of the public API, not even for React DevTools.
10762// You may only inject a debugTool if you work on React Fiber itself.
10763var ReactFiberInstrumentation = {
10764 debugTool: null
10765};
10766
10767var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
10768
10769// TODO: Offscreen updates should never suspend. However, a promise that
10770// suspended inside an offscreen subtree should be able to ping at the priority
10771// of the outer render.
10772
10773function markPendingPriorityLevel(root, expirationTime) {
10774 // If there's a gap between completing a failed root and retrying it,
10775 // additional updates may be scheduled. Clear `didError`, in case the update
10776 // is sufficient to fix the error.
10777 root.didError = false;
10778
10779 // Update the latest and earliest pending times
10780 var earliestPendingTime = root.earliestPendingTime;
10781 if (earliestPendingTime === NoWork) {
10782 // No other pending updates.
10783 root.earliestPendingTime = root.latestPendingTime = expirationTime;
10784 } else {
10785 if (earliestPendingTime < expirationTime) {
10786 // This is the earliest pending update.
10787 root.earliestPendingTime = expirationTime;
10788 } else {
10789 var latestPendingTime = root.latestPendingTime;
10790 if (latestPendingTime > expirationTime) {
10791 // This is the latest pending update
10792 root.latestPendingTime = expirationTime;
10793 }
10794 }
10795 }
10796 findNextExpirationTimeToWorkOn(expirationTime, root);
10797}
10798
10799function markCommittedPriorityLevels(root, earliestRemainingTime) {
10800 root.didError = false;
10801
10802 if (earliestRemainingTime === NoWork) {
10803 // Fast path. There's no remaining work. Clear everything.
10804 root.earliestPendingTime = NoWork;
10805 root.latestPendingTime = NoWork;
10806 root.earliestSuspendedTime = NoWork;
10807 root.latestSuspendedTime = NoWork;
10808 root.latestPingedTime = NoWork;
10809 findNextExpirationTimeToWorkOn(NoWork, root);
10810 return;
10811 }
10812
10813 if (earliestRemainingTime < root.latestPingedTime) {
10814 root.latestPingedTime = NoWork;
10815 }
10816
10817 // Let's see if the previous latest known pending level was just flushed.
10818 var latestPendingTime = root.latestPendingTime;
10819 if (latestPendingTime !== NoWork) {
10820 if (latestPendingTime > earliestRemainingTime) {
10821 // We've flushed all the known pending levels.
10822 root.earliestPendingTime = root.latestPendingTime = NoWork;
10823 } else {
10824 var earliestPendingTime = root.earliestPendingTime;
10825 if (earliestPendingTime > earliestRemainingTime) {
10826 // We've flushed the earliest known pending level. Set this to the
10827 // latest pending time.
10828 root.earliestPendingTime = root.latestPendingTime;
10829 }
10830 }
10831 }
10832
10833 // Now let's handle the earliest remaining level in the whole tree. We need to
10834 // decide whether to treat it as a pending level or as suspended. Check
10835 // it falls within the range of known suspended levels.
10836
10837 var earliestSuspendedTime = root.earliestSuspendedTime;
10838 if (earliestSuspendedTime === NoWork) {
10839 // There's no suspended work. Treat the earliest remaining level as a
10840 // pending level.
10841 markPendingPriorityLevel(root, earliestRemainingTime);
10842 findNextExpirationTimeToWorkOn(NoWork, root);
10843 return;
10844 }
10845
10846 var latestSuspendedTime = root.latestSuspendedTime;
10847 if (earliestRemainingTime < latestSuspendedTime) {
10848 // The earliest remaining level is later than all the suspended work. That
10849 // means we've flushed all the suspended work.
10850 root.earliestSuspendedTime = NoWork;
10851 root.latestSuspendedTime = NoWork;
10852 root.latestPingedTime = NoWork;
10853
10854 // There's no suspended work. Treat the earliest remaining level as a
10855 // pending level.
10856 markPendingPriorityLevel(root, earliestRemainingTime);
10857 findNextExpirationTimeToWorkOn(NoWork, root);
10858 return;
10859 }
10860
10861 if (earliestRemainingTime > earliestSuspendedTime) {
10862 // The earliest remaining time is earlier than all the suspended work.
10863 // Treat it as a pending update.
10864 markPendingPriorityLevel(root, earliestRemainingTime);
10865 findNextExpirationTimeToWorkOn(NoWork, root);
10866 return;
10867 }
10868
10869 // The earliest remaining time falls within the range of known suspended
10870 // levels. We should treat this as suspended work.
10871 findNextExpirationTimeToWorkOn(NoWork, root);
10872}
10873
10874function hasLowerPriorityWork(root, erroredExpirationTime) {
10875 var latestPendingTime = root.latestPendingTime;
10876 var latestSuspendedTime = root.latestSuspendedTime;
10877 var latestPingedTime = root.latestPingedTime;
10878 return latestPendingTime !== NoWork && latestPendingTime < erroredExpirationTime || latestSuspendedTime !== NoWork && latestSuspendedTime < erroredExpirationTime || latestPingedTime !== NoWork && latestPingedTime < erroredExpirationTime;
10879}
10880
10881function isPriorityLevelSuspended(root, expirationTime) {
10882 var earliestSuspendedTime = root.earliestSuspendedTime;
10883 var latestSuspendedTime = root.latestSuspendedTime;
10884 return earliestSuspendedTime !== NoWork && expirationTime <= earliestSuspendedTime && expirationTime >= latestSuspendedTime;
10885}
10886
10887function markSuspendedPriorityLevel(root, suspendedTime) {
10888 root.didError = false;
10889 clearPing(root, suspendedTime);
10890
10891 // First, check the known pending levels and update them if needed.
10892 var earliestPendingTime = root.earliestPendingTime;
10893 var latestPendingTime = root.latestPendingTime;
10894 if (earliestPendingTime === suspendedTime) {
10895 if (latestPendingTime === suspendedTime) {
10896 // Both known pending levels were suspended. Clear them.
10897 root.earliestPendingTime = root.latestPendingTime = NoWork;
10898 } else {
10899 // The earliest pending level was suspended. Clear by setting it to the
10900 // latest pending level.
10901 root.earliestPendingTime = latestPendingTime;
10902 }
10903 } else if (latestPendingTime === suspendedTime) {
10904 // The latest pending level was suspended. Clear by setting it to the
10905 // latest pending level.
10906 root.latestPendingTime = earliestPendingTime;
10907 }
10908
10909 // Finally, update the known suspended levels.
10910 var earliestSuspendedTime = root.earliestSuspendedTime;
10911 var latestSuspendedTime = root.latestSuspendedTime;
10912 if (earliestSuspendedTime === NoWork) {
10913 // No other suspended levels.
10914 root.earliestSuspendedTime = root.latestSuspendedTime = suspendedTime;
10915 } else {
10916 if (earliestSuspendedTime < suspendedTime) {
10917 // This is the earliest suspended level.
10918 root.earliestSuspendedTime = suspendedTime;
10919 } else if (latestSuspendedTime > suspendedTime) {
10920 // This is the latest suspended level
10921 root.latestSuspendedTime = suspendedTime;
10922 }
10923 }
10924
10925 findNextExpirationTimeToWorkOn(suspendedTime, root);
10926}
10927
10928function markPingedPriorityLevel(root, pingedTime) {
10929 root.didError = false;
10930
10931 // TODO: When we add back resuming, we need to ensure the progressed work
10932 // is thrown out and not reused during the restarted render. One way to
10933 // invalidate the progressed work is to restart at expirationTime + 1.
10934 var latestPingedTime = root.latestPingedTime;
10935 if (latestPingedTime === NoWork || latestPingedTime > pingedTime) {
10936 root.latestPingedTime = pingedTime;
10937 }
10938 findNextExpirationTimeToWorkOn(pingedTime, root);
10939}
10940
10941function clearPing(root, completedTime) {
10942 var latestPingedTime = root.latestPingedTime;
10943 if (latestPingedTime >= completedTime) {
10944 root.latestPingedTime = NoWork;
10945 }
10946}
10947
10948function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) {
10949 var earliestExpirationTime = renderExpirationTime;
10950
10951 var earliestPendingTime = root.earliestPendingTime;
10952 var earliestSuspendedTime = root.earliestSuspendedTime;
10953 if (earliestPendingTime > earliestExpirationTime) {
10954 earliestExpirationTime = earliestPendingTime;
10955 }
10956 if (earliestSuspendedTime > earliestExpirationTime) {
10957 earliestExpirationTime = earliestSuspendedTime;
10958 }
10959 return earliestExpirationTime;
10960}
10961
10962function didExpireAtExpirationTime(root, currentTime) {
10963 var expirationTime = root.expirationTime;
10964 if (expirationTime !== NoWork && currentTime <= expirationTime) {
10965 // The root has expired. Flush all work up to the current time.
10966 root.nextExpirationTimeToWorkOn = currentTime;
10967 }
10968}
10969
10970function findNextExpirationTimeToWorkOn(completedExpirationTime, root) {
10971 var earliestSuspendedTime = root.earliestSuspendedTime;
10972 var latestSuspendedTime = root.latestSuspendedTime;
10973 var earliestPendingTime = root.earliestPendingTime;
10974 var latestPingedTime = root.latestPingedTime;
10975
10976 // Work on the earliest pending time. Failing that, work on the latest
10977 // pinged time.
10978 var nextExpirationTimeToWorkOn = earliestPendingTime !== NoWork ? earliestPendingTime : latestPingedTime;
10979
10980 // If there is no pending or pinged work, check if there's suspended work
10981 // that's lower priority than what we just completed.
10982 if (nextExpirationTimeToWorkOn === NoWork && (completedExpirationTime === NoWork || latestSuspendedTime < completedExpirationTime)) {
10983 // The lowest priority suspended work is the work most likely to be
10984 // committed next. Let's start rendering it again, so that if it times out,
10985 // it's ready to commit.
10986 nextExpirationTimeToWorkOn = latestSuspendedTime;
10987 }
10988
10989 var expirationTime = nextExpirationTimeToWorkOn;
10990 if (expirationTime !== NoWork && earliestSuspendedTime > expirationTime) {
10991 // Expire using the earliest known expiration time.
10992 expirationTime = earliestSuspendedTime;
10993 }
10994
10995 root.nextExpirationTimeToWorkOn = nextExpirationTimeToWorkOn;
10996 root.expirationTime = expirationTime;
10997}
10998
10999function resolveDefaultProps(Component, baseProps) {
11000 if (Component && Component.defaultProps) {
11001 // Resolve default props. Taken from ReactElement
11002 var props = _assign({}, baseProps);
11003 var defaultProps = Component.defaultProps;
11004 for (var propName in defaultProps) {
11005 if (props[propName] === undefined) {
11006 props[propName] = defaultProps[propName];
11007 }
11008 }
11009 return props;
11010 }
11011 return baseProps;
11012}
11013
11014function readLazyComponentType(lazyComponent) {
11015 var status = lazyComponent._status;
11016 var result = lazyComponent._result;
11017 switch (status) {
11018 case Resolved:
11019 {
11020 var Component = result;
11021 return Component;
11022 }
11023 case Rejected:
11024 {
11025 var error = result;
11026 throw error;
11027 }
11028 case Pending:
11029 {
11030 var thenable = result;
11031 throw thenable;
11032 }
11033 default:
11034 {
11035 lazyComponent._status = Pending;
11036 var ctor = lazyComponent._ctor;
11037 var _thenable = ctor();
11038 _thenable.then(function (moduleObject) {
11039 if (lazyComponent._status === Pending) {
11040 var defaultExport = moduleObject.default;
11041 {
11042 if (defaultExport === undefined) {
11043 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);
11044 }
11045 }
11046 lazyComponent._status = Resolved;
11047 lazyComponent._result = defaultExport;
11048 }
11049 }, function (error) {
11050 if (lazyComponent._status === Pending) {
11051 lazyComponent._status = Rejected;
11052 lazyComponent._result = error;
11053 }
11054 });
11055 // Handle synchronous thenables.
11056 switch (lazyComponent._status) {
11057 case Resolved:
11058 return lazyComponent._result;
11059 case Rejected:
11060 throw lazyComponent._result;
11061 }
11062 lazyComponent._result = _thenable;
11063 throw _thenable;
11064 }
11065 }
11066}
11067
11068var fakeInternalInstance = {};
11069var isArray$1 = Array.isArray;
11070
11071// React.Component uses a shared frozen object by default.
11072// We'll use it to determine whether we need to initialize legacy refs.
11073var emptyRefsObject = new React.Component().refs;
11074
11075var didWarnAboutStateAssignmentForComponent = void 0;
11076var didWarnAboutUninitializedState = void 0;
11077var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0;
11078var didWarnAboutLegacyLifecyclesAndDerivedState = void 0;
11079var didWarnAboutUndefinedDerivedState = void 0;
11080var warnOnUndefinedDerivedState = void 0;
11081var warnOnInvalidCallback$1 = void 0;
11082var didWarnAboutDirectlyAssigningPropsToState = void 0;
11083var didWarnAboutContextTypeAndContextTypes = void 0;
11084var didWarnAboutInvalidateContextType = void 0;
11085
11086{
11087 didWarnAboutStateAssignmentForComponent = new Set();
11088 didWarnAboutUninitializedState = new Set();
11089 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
11090 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
11091 didWarnAboutDirectlyAssigningPropsToState = new Set();
11092 didWarnAboutUndefinedDerivedState = new Set();
11093 didWarnAboutContextTypeAndContextTypes = new Set();
11094 didWarnAboutInvalidateContextType = new Set();
11095
11096 var didWarnOnInvalidCallback = new Set();
11097
11098 warnOnInvalidCallback$1 = function (callback, callerName) {
11099 if (callback === null || typeof callback === 'function') {
11100 return;
11101 }
11102 var key = callerName + '_' + callback;
11103 if (!didWarnOnInvalidCallback.has(key)) {
11104 didWarnOnInvalidCallback.add(key);
11105 warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
11106 }
11107 };
11108
11109 warnOnUndefinedDerivedState = function (type, partialState) {
11110 if (partialState === undefined) {
11111 var componentName = getComponentName(type) || 'Component';
11112 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
11113 didWarnAboutUndefinedDerivedState.add(componentName);
11114 warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
11115 }
11116 }
11117 };
11118
11119 // This is so gross but it's at least non-critical and can be removed if
11120 // it causes problems. This is meant to give a nicer error message for
11121 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
11122 // ...)) which otherwise throws a "_processChildContext is not a function"
11123 // exception.
11124 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
11125 enumerable: false,
11126 value: function () {
11127 invariant(false, '_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).');
11128 }
11129 });
11130 Object.freeze(fakeInternalInstance);
11131}
11132
11133function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
11134 var prevState = workInProgress.memoizedState;
11135
11136 {
11137 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
11138 // Invoke the function an extra time to help detect side-effects.
11139 getDerivedStateFromProps(nextProps, prevState);
11140 }
11141 }
11142
11143 var partialState = getDerivedStateFromProps(nextProps, prevState);
11144
11145 {
11146 warnOnUndefinedDerivedState(ctor, partialState);
11147 }
11148 // Merge the partial state and the previous state.
11149 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
11150 workInProgress.memoizedState = memoizedState;
11151
11152 // Once the update queue is empty, persist the derived state onto the
11153 // base state.
11154 var updateQueue = workInProgress.updateQueue;
11155 if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
11156 updateQueue.baseState = memoizedState;
11157 }
11158}
11159
11160var classComponentUpdater = {
11161 isMounted: isMounted,
11162 enqueueSetState: function (inst, payload, callback) {
11163 var fiber = get(inst);
11164 var currentTime = requestCurrentTime();
11165 var expirationTime = computeExpirationForFiber(currentTime, fiber);
11166
11167 var update = createUpdate(expirationTime);
11168 update.payload = payload;
11169 if (callback !== undefined && callback !== null) {
11170 {
11171 warnOnInvalidCallback$1(callback, 'setState');
11172 }
11173 update.callback = callback;
11174 }
11175
11176 flushPassiveEffects();
11177 enqueueUpdate(fiber, update);
11178 scheduleWork(fiber, expirationTime);
11179 },
11180 enqueueReplaceState: function (inst, payload, callback) {
11181 var fiber = get(inst);
11182 var currentTime = requestCurrentTime();
11183 var expirationTime = computeExpirationForFiber(currentTime, fiber);
11184
11185 var update = createUpdate(expirationTime);
11186 update.tag = ReplaceState;
11187 update.payload = payload;
11188
11189 if (callback !== undefined && callback !== null) {
11190 {
11191 warnOnInvalidCallback$1(callback, 'replaceState');
11192 }
11193 update.callback = callback;
11194 }
11195
11196 flushPassiveEffects();
11197 enqueueUpdate(fiber, update);
11198 scheduleWork(fiber, expirationTime);
11199 },
11200 enqueueForceUpdate: function (inst, callback) {
11201 var fiber = get(inst);
11202 var currentTime = requestCurrentTime();
11203 var expirationTime = computeExpirationForFiber(currentTime, fiber);
11204
11205 var update = createUpdate(expirationTime);
11206 update.tag = ForceUpdate;
11207
11208 if (callback !== undefined && callback !== null) {
11209 {
11210 warnOnInvalidCallback$1(callback, 'forceUpdate');
11211 }
11212 update.callback = callback;
11213 }
11214
11215 flushPassiveEffects();
11216 enqueueUpdate(fiber, update);
11217 scheduleWork(fiber, expirationTime);
11218 }
11219};
11220
11221function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
11222 var instance = workInProgress.stateNode;
11223 if (typeof instance.shouldComponentUpdate === 'function') {
11224 startPhaseTimer(workInProgress, 'shouldComponentUpdate');
11225 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
11226 stopPhaseTimer();
11227
11228 {
11229 !(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;
11230 }
11231
11232 return shouldUpdate;
11233 }
11234
11235 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
11236 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
11237 }
11238
11239 return true;
11240}
11241
11242function checkClassInstance(workInProgress, ctor, newProps) {
11243 var instance = workInProgress.stateNode;
11244 {
11245 var name = getComponentName(ctor) || 'Component';
11246 var renderPresent = instance.render;
11247
11248 if (!renderPresent) {
11249 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
11250 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
11251 } else {
11252 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
11253 }
11254 }
11255
11256 var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
11257 !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;
11258 var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
11259 !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;
11260 var noInstancePropTypes = !instance.propTypes;
11261 !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
11262 var noInstanceContextType = !instance.contextType;
11263 !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0;
11264 var noInstanceContextTypes = !instance.contextTypes;
11265 !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
11266
11267 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
11268 didWarnAboutContextTypeAndContextTypes.add(ctor);
11269 warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
11270 }
11271
11272 var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
11273 !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;
11274 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
11275 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');
11276 }
11277 var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
11278 !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
11279 var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
11280 !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;
11281 var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
11282 !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
11283 var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
11284 !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
11285 var hasMutatedProps = instance.props !== newProps;
11286 !(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;
11287 var noInstanceDefaultProps = !instance.defaultProps;
11288 !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;
11289
11290 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
11291 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
11292 warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
11293 }
11294
11295 var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
11296 !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;
11297 var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function';
11298 !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;
11299 var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function';
11300 !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;
11301 var _state = instance.state;
11302 if (_state && (typeof _state !== 'object' || isArray$1(_state))) {
11303 warningWithoutStack$1(false, '%s.state: must be set to an object or null', name);
11304 }
11305 if (typeof instance.getChildContext === 'function') {
11306 !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
11307 }
11308 }
11309}
11310
11311function adoptClassInstance(workInProgress, instance) {
11312 instance.updater = classComponentUpdater;
11313 workInProgress.stateNode = instance;
11314 // The instance needs access to the fiber so that it can schedule updates
11315 set(instance, workInProgress);
11316 {
11317 instance._reactInternalInstance = fakeInternalInstance;
11318 }
11319}
11320
11321function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) {
11322 var isLegacyContextConsumer = false;
11323 var unmaskedContext = emptyContextObject;
11324 var context = null;
11325 var contextType = ctor.contextType;
11326 if (typeof contextType === 'object' && contextType !== null) {
11327 {
11328 if (contextType.$$typeof !== REACT_CONTEXT_TYPE && !didWarnAboutInvalidateContextType.has(ctor)) {
11329 didWarnAboutInvalidateContextType.add(ctor);
11330 warningWithoutStack$1(false, '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext(). ' + 'Did you accidentally pass the Context.Provider instead?', getComponentName(ctor) || 'Component');
11331 }
11332 }
11333
11334 context = readContext(contextType);
11335 } else {
11336 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11337 var contextTypes = ctor.contextTypes;
11338 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
11339 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
11340 }
11341
11342 // Instantiate twice to help detect side-effects.
11343 {
11344 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
11345 new ctor(props, context); // eslint-disable-line no-new
11346 }
11347 }
11348
11349 var instance = new ctor(props, context);
11350 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
11351 adoptClassInstance(workInProgress, instance);
11352
11353 {
11354 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
11355 var componentName = getComponentName(ctor) || 'Component';
11356 if (!didWarnAboutUninitializedState.has(componentName)) {
11357 didWarnAboutUninitializedState.add(componentName);
11358 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);
11359 }
11360 }
11361
11362 // If new component APIs are defined, "unsafe" lifecycles won't be called.
11363 // Warn about these lifecycles if they are present.
11364 // Don't warn about react-lifecycles-compat polyfilled methods though.
11365 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
11366 var foundWillMountName = null;
11367 var foundWillReceivePropsName = null;
11368 var foundWillUpdateName = null;
11369 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
11370 foundWillMountName = 'componentWillMount';
11371 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
11372 foundWillMountName = 'UNSAFE_componentWillMount';
11373 }
11374 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
11375 foundWillReceivePropsName = 'componentWillReceiveProps';
11376 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
11377 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
11378 }
11379 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
11380 foundWillUpdateName = 'componentWillUpdate';
11381 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
11382 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
11383 }
11384 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
11385 var _componentName = getComponentName(ctor) || 'Component';
11386 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
11387 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
11388 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
11389 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-async-component-lifecycle-hooks', _componentName, newApiName, foundWillMountName !== null ? '\n ' + foundWillMountName : '', foundWillReceivePropsName !== null ? '\n ' + foundWillReceivePropsName : '', foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : '');
11390 }
11391 }
11392 }
11393 }
11394
11395 // Cache unmasked context so we can avoid recreating masked context unless necessary.
11396 // ReactFiberContext usually updates this cache but can't for newly-created instances.
11397 if (isLegacyContextConsumer) {
11398 cacheContext(workInProgress, unmaskedContext, context);
11399 }
11400
11401 return instance;
11402}
11403
11404function callComponentWillMount(workInProgress, instance) {
11405 startPhaseTimer(workInProgress, 'componentWillMount');
11406 var oldState = instance.state;
11407
11408 if (typeof instance.componentWillMount === 'function') {
11409 instance.componentWillMount();
11410 }
11411 if (typeof instance.UNSAFE_componentWillMount === 'function') {
11412 instance.UNSAFE_componentWillMount();
11413 }
11414
11415 stopPhaseTimer();
11416
11417 if (oldState !== instance.state) {
11418 {
11419 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');
11420 }
11421 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
11422 }
11423}
11424
11425function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
11426 var oldState = instance.state;
11427 startPhaseTimer(workInProgress, 'componentWillReceiveProps');
11428 if (typeof instance.componentWillReceiveProps === 'function') {
11429 instance.componentWillReceiveProps(newProps, nextContext);
11430 }
11431 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
11432 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
11433 }
11434 stopPhaseTimer();
11435
11436 if (instance.state !== oldState) {
11437 {
11438 var componentName = getComponentName(workInProgress.type) || 'Component';
11439 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
11440 didWarnAboutStateAssignmentForComponent.add(componentName);
11441 warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
11442 }
11443 }
11444 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
11445 }
11446}
11447
11448// Invokes the mount life-cycles on a previously never rendered instance.
11449function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
11450 {
11451 checkClassInstance(workInProgress, ctor, newProps);
11452 }
11453
11454 var instance = workInProgress.stateNode;
11455 instance.props = newProps;
11456 instance.state = workInProgress.memoizedState;
11457 instance.refs = emptyRefsObject;
11458
11459 var contextType = ctor.contextType;
11460 if (typeof contextType === 'object' && contextType !== null) {
11461 instance.context = readContext(contextType);
11462 } else {
11463 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11464 instance.context = getMaskedContext(workInProgress, unmaskedContext);
11465 }
11466
11467 {
11468 if (instance.state === newProps) {
11469 var componentName = getComponentName(ctor) || 'Component';
11470 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
11471 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
11472 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);
11473 }
11474 }
11475
11476 if (workInProgress.mode & StrictMode) {
11477 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
11478
11479 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
11480 }
11481
11482 if (warnAboutDeprecatedLifecycles) {
11483 ReactStrictModeWarnings.recordDeprecationWarnings(workInProgress, instance);
11484 }
11485 }
11486
11487 var updateQueue = workInProgress.updateQueue;
11488 if (updateQueue !== null) {
11489 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11490 instance.state = workInProgress.memoizedState;
11491 }
11492
11493 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
11494 if (typeof getDerivedStateFromProps === 'function') {
11495 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
11496 instance.state = workInProgress.memoizedState;
11497 }
11498
11499 // In order to support react-lifecycles-compat polyfilled components,
11500 // Unsafe lifecycles should not be invoked for components using the new APIs.
11501 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
11502 callComponentWillMount(workInProgress, instance);
11503 // If we had additional state updates during this life-cycle, let's
11504 // process them now.
11505 updateQueue = workInProgress.updateQueue;
11506 if (updateQueue !== null) {
11507 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11508 instance.state = workInProgress.memoizedState;
11509 }
11510 }
11511
11512 if (typeof instance.componentDidMount === 'function') {
11513 workInProgress.effectTag |= Update;
11514 }
11515}
11516
11517function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
11518 var instance = workInProgress.stateNode;
11519
11520 var oldProps = workInProgress.memoizedProps;
11521 instance.props = oldProps;
11522
11523 var oldContext = instance.context;
11524 var contextType = ctor.contextType;
11525 var nextContext = void 0;
11526 if (typeof contextType === 'object' && contextType !== null) {
11527 nextContext = readContext(contextType);
11528 } else {
11529 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11530 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
11531 }
11532
11533 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
11534 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
11535
11536 // Note: During these life-cycles, instance.props/instance.state are what
11537 // ever the previously attempted to render - not the "current". However,
11538 // during componentDidUpdate we pass the "current" props.
11539
11540 // In order to support react-lifecycles-compat polyfilled components,
11541 // Unsafe lifecycles should not be invoked for components using the new APIs.
11542 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
11543 if (oldProps !== newProps || oldContext !== nextContext) {
11544 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
11545 }
11546 }
11547
11548 resetHasForceUpdateBeforeProcessing();
11549
11550 var oldState = workInProgress.memoizedState;
11551 var newState = instance.state = oldState;
11552 var updateQueue = workInProgress.updateQueue;
11553 if (updateQueue !== null) {
11554 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11555 newState = workInProgress.memoizedState;
11556 }
11557 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
11558 // If an update was already in progress, we should schedule an Update
11559 // effect even though we're bailing out, so that cWU/cDU are called.
11560 if (typeof instance.componentDidMount === 'function') {
11561 workInProgress.effectTag |= Update;
11562 }
11563 return false;
11564 }
11565
11566 if (typeof getDerivedStateFromProps === 'function') {
11567 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
11568 newState = workInProgress.memoizedState;
11569 }
11570
11571 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
11572
11573 if (shouldUpdate) {
11574 // In order to support react-lifecycles-compat polyfilled components,
11575 // Unsafe lifecycles should not be invoked for components using the new APIs.
11576 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
11577 startPhaseTimer(workInProgress, 'componentWillMount');
11578 if (typeof instance.componentWillMount === 'function') {
11579 instance.componentWillMount();
11580 }
11581 if (typeof instance.UNSAFE_componentWillMount === 'function') {
11582 instance.UNSAFE_componentWillMount();
11583 }
11584 stopPhaseTimer();
11585 }
11586 if (typeof instance.componentDidMount === 'function') {
11587 workInProgress.effectTag |= Update;
11588 }
11589 } else {
11590 // If an update was already in progress, we should schedule an Update
11591 // effect even though we're bailing out, so that cWU/cDU are called.
11592 if (typeof instance.componentDidMount === 'function') {
11593 workInProgress.effectTag |= Update;
11594 }
11595
11596 // If shouldComponentUpdate returned false, we should still update the
11597 // memoized state to indicate that this work can be reused.
11598 workInProgress.memoizedProps = newProps;
11599 workInProgress.memoizedState = newState;
11600 }
11601
11602 // Update the existing instance's state, props, and context pointers even
11603 // if shouldComponentUpdate returns false.
11604 instance.props = newProps;
11605 instance.state = newState;
11606 instance.context = nextContext;
11607
11608 return shouldUpdate;
11609}
11610
11611// Invokes the update life-cycles and returns false if it shouldn't rerender.
11612function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
11613 var instance = workInProgress.stateNode;
11614
11615 var oldProps = workInProgress.memoizedProps;
11616 instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
11617
11618 var oldContext = instance.context;
11619 var contextType = ctor.contextType;
11620 var nextContext = void 0;
11621 if (typeof contextType === 'object' && contextType !== null) {
11622 nextContext = readContext(contextType);
11623 } else {
11624 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11625 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
11626 }
11627
11628 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
11629 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
11630
11631 // Note: During these life-cycles, instance.props/instance.state are what
11632 // ever the previously attempted to render - not the "current". However,
11633 // during componentDidUpdate we pass the "current" props.
11634
11635 // In order to support react-lifecycles-compat polyfilled components,
11636 // Unsafe lifecycles should not be invoked for components using the new APIs.
11637 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
11638 if (oldProps !== newProps || oldContext !== nextContext) {
11639 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
11640 }
11641 }
11642
11643 resetHasForceUpdateBeforeProcessing();
11644
11645 var oldState = workInProgress.memoizedState;
11646 var newState = instance.state = oldState;
11647 var updateQueue = workInProgress.updateQueue;
11648 if (updateQueue !== null) {
11649 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11650 newState = workInProgress.memoizedState;
11651 }
11652
11653 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
11654 // If an update was already in progress, we should schedule an Update
11655 // effect even though we're bailing out, so that cWU/cDU are called.
11656 if (typeof instance.componentDidUpdate === 'function') {
11657 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11658 workInProgress.effectTag |= Update;
11659 }
11660 }
11661 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
11662 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11663 workInProgress.effectTag |= Snapshot;
11664 }
11665 }
11666 return false;
11667 }
11668
11669 if (typeof getDerivedStateFromProps === 'function') {
11670 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
11671 newState = workInProgress.memoizedState;
11672 }
11673
11674 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
11675
11676 if (shouldUpdate) {
11677 // In order to support react-lifecycles-compat polyfilled components,
11678 // Unsafe lifecycles should not be invoked for components using the new APIs.
11679 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
11680 startPhaseTimer(workInProgress, 'componentWillUpdate');
11681 if (typeof instance.componentWillUpdate === 'function') {
11682 instance.componentWillUpdate(newProps, newState, nextContext);
11683 }
11684 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
11685 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
11686 }
11687 stopPhaseTimer();
11688 }
11689 if (typeof instance.componentDidUpdate === 'function') {
11690 workInProgress.effectTag |= Update;
11691 }
11692 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
11693 workInProgress.effectTag |= Snapshot;
11694 }
11695 } else {
11696 // If an update was already in progress, we should schedule an Update
11697 // effect even though we're bailing out, so that cWU/cDU are called.
11698 if (typeof instance.componentDidUpdate === 'function') {
11699 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11700 workInProgress.effectTag |= Update;
11701 }
11702 }
11703 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
11704 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11705 workInProgress.effectTag |= Snapshot;
11706 }
11707 }
11708
11709 // If shouldComponentUpdate returned false, we should still update the
11710 // memoized props/state to indicate that this work can be reused.
11711 workInProgress.memoizedProps = newProps;
11712 workInProgress.memoizedState = newState;
11713 }
11714
11715 // Update the existing instance's state, props, and context pointers even
11716 // if shouldComponentUpdate returns false.
11717 instance.props = newProps;
11718 instance.state = newState;
11719 instance.context = nextContext;
11720
11721 return shouldUpdate;
11722}
11723
11724var didWarnAboutMaps = void 0;
11725var didWarnAboutGenerators = void 0;
11726var didWarnAboutStringRefInStrictMode = void 0;
11727var ownerHasKeyUseWarning = void 0;
11728var ownerHasFunctionTypeWarning = void 0;
11729var warnForMissingKey = function (child) {};
11730
11731{
11732 didWarnAboutMaps = false;
11733 didWarnAboutGenerators = false;
11734 didWarnAboutStringRefInStrictMode = {};
11735
11736 /**
11737 * Warn if there's no key explicitly set on dynamic arrays of children or
11738 * object keys are not valid. This allows us to keep track of children between
11739 * updates.
11740 */
11741 ownerHasKeyUseWarning = {};
11742 ownerHasFunctionTypeWarning = {};
11743
11744 warnForMissingKey = function (child) {
11745 if (child === null || typeof child !== 'object') {
11746 return;
11747 }
11748 if (!child._store || child._store.validated || child.key != null) {
11749 return;
11750 }
11751 !(typeof child._store === 'object') ? invariant(false, 'React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.') : void 0;
11752 child._store.validated = true;
11753
11754 var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
11755 if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
11756 return;
11757 }
11758 ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
11759
11760 warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
11761 };
11762}
11763
11764var isArray = Array.isArray;
11765
11766function coerceRef(returnFiber, current$$1, element) {
11767 var mixedRef = element.ref;
11768 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
11769 {
11770 if (returnFiber.mode & StrictMode) {
11771 var componentName = getComponentName(returnFiber.type) || 'Component';
11772 if (!didWarnAboutStringRefInStrictMode[componentName]) {
11773 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 createRef() instead.' + '\n%s' + '\n\nLearn more about using refs safely here:' + '\nhttps://fb.me/react-strict-mode-string-ref', mixedRef, getStackByFiberInDevAndProd(returnFiber));
11774 didWarnAboutStringRefInStrictMode[componentName] = true;
11775 }
11776 }
11777 }
11778
11779 if (element._owner) {
11780 var owner = element._owner;
11781 var inst = void 0;
11782 if (owner) {
11783 var ownerFiber = owner;
11784 !(ownerFiber.tag === ClassComponent) ? invariant(false, 'Function components cannot have refs. Did you mean to use React.forwardRef()?') : void 0;
11785 inst = ownerFiber.stateNode;
11786 }
11787 !inst ? invariant(false, 'Missing owner for string ref %s. This error is likely caused by a bug in React. Please file an issue.', mixedRef) : void 0;
11788 var stringRef = '' + mixedRef;
11789 // Check if previous string ref matches new string ref
11790 if (current$$1 !== null && current$$1.ref !== null && typeof current$$1.ref === 'function' && current$$1.ref._stringRef === stringRef) {
11791 return current$$1.ref;
11792 }
11793 var ref = function (value) {
11794 var refs = inst.refs;
11795 if (refs === emptyRefsObject) {
11796 // This is a lazy pooled frozen object, so we need to initialize.
11797 refs = inst.refs = {};
11798 }
11799 if (value === null) {
11800 delete refs[stringRef];
11801 } else {
11802 refs[stringRef] = value;
11803 }
11804 };
11805 ref._stringRef = stringRef;
11806 return ref;
11807 } else {
11808 !(typeof mixedRef === 'string') ? invariant(false, 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.') : void 0;
11809 !element._owner ? invariant(false, 'Element ref was specified as a string (%s) 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.', mixedRef) : void 0;
11810 }
11811 }
11812 return mixedRef;
11813}
11814
11815function throwOnInvalidObjectType(returnFiber, newChild) {
11816 if (returnFiber.type !== 'textarea') {
11817 var addendum = '';
11818 {
11819 addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
11820 }
11821 invariant(false, 'Objects are not valid as a React child (found: %s).%s', Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild, addendum);
11822 }
11823}
11824
11825function warnOnFunctionType() {
11826 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();
11827
11828 if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
11829 return;
11830 }
11831 ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
11832
11833 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.');
11834}
11835
11836// This wrapper function exists because I expect to clone the code in each path
11837// to be able to optimize each path individually by branching early. This needs
11838// a compiler or we can do it manually. Helpers that don't need this branching
11839// live outside of this function.
11840function ChildReconciler(shouldTrackSideEffects) {
11841 function deleteChild(returnFiber, childToDelete) {
11842 if (!shouldTrackSideEffects) {
11843 // Noop.
11844 return;
11845 }
11846 // Deletions are added in reversed order so we add it to the front.
11847 // At this point, the return fiber's effect list is empty except for
11848 // deletions, so we can just append the deletion to the list. The remaining
11849 // effects aren't added until the complete phase. Once we implement
11850 // resuming, this may not be true.
11851 var last = returnFiber.lastEffect;
11852 if (last !== null) {
11853 last.nextEffect = childToDelete;
11854 returnFiber.lastEffect = childToDelete;
11855 } else {
11856 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
11857 }
11858 childToDelete.nextEffect = null;
11859 childToDelete.effectTag = Deletion;
11860 }
11861
11862 function deleteRemainingChildren(returnFiber, currentFirstChild) {
11863 if (!shouldTrackSideEffects) {
11864 // Noop.
11865 return null;
11866 }
11867
11868 // TODO: For the shouldClone case, this could be micro-optimized a bit by
11869 // assuming that after the first child we've already added everything.
11870 var childToDelete = currentFirstChild;
11871 while (childToDelete !== null) {
11872 deleteChild(returnFiber, childToDelete);
11873 childToDelete = childToDelete.sibling;
11874 }
11875 return null;
11876 }
11877
11878 function mapRemainingChildren(returnFiber, currentFirstChild) {
11879 // Add the remaining children to a temporary map so that we can find them by
11880 // keys quickly. Implicit (null) keys get added to this set with their index
11881 var existingChildren = new Map();
11882
11883 var existingChild = currentFirstChild;
11884 while (existingChild !== null) {
11885 if (existingChild.key !== null) {
11886 existingChildren.set(existingChild.key, existingChild);
11887 } else {
11888 existingChildren.set(existingChild.index, existingChild);
11889 }
11890 existingChild = existingChild.sibling;
11891 }
11892 return existingChildren;
11893 }
11894
11895 function useFiber(fiber, pendingProps, expirationTime) {
11896 // We currently set sibling to null and index to 0 here because it is easy
11897 // to forget to do before returning it. E.g. for the single child case.
11898 var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
11899 clone.index = 0;
11900 clone.sibling = null;
11901 return clone;
11902 }
11903
11904 function placeChild(newFiber, lastPlacedIndex, newIndex) {
11905 newFiber.index = newIndex;
11906 if (!shouldTrackSideEffects) {
11907 // Noop.
11908 return lastPlacedIndex;
11909 }
11910 var current$$1 = newFiber.alternate;
11911 if (current$$1 !== null) {
11912 var oldIndex = current$$1.index;
11913 if (oldIndex < lastPlacedIndex) {
11914 // This is a move.
11915 newFiber.effectTag = Placement;
11916 return lastPlacedIndex;
11917 } else {
11918 // This item can stay in place.
11919 return oldIndex;
11920 }
11921 } else {
11922 // This is an insertion.
11923 newFiber.effectTag = Placement;
11924 return lastPlacedIndex;
11925 }
11926 }
11927
11928 function placeSingleChild(newFiber) {
11929 // This is simpler for the single child case. We only need to do a
11930 // placement for inserting new children.
11931 if (shouldTrackSideEffects && newFiber.alternate === null) {
11932 newFiber.effectTag = Placement;
11933 }
11934 return newFiber;
11935 }
11936
11937 function updateTextNode(returnFiber, current$$1, textContent, expirationTime) {
11938 if (current$$1 === null || current$$1.tag !== HostText) {
11939 // Insert
11940 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
11941 created.return = returnFiber;
11942 return created;
11943 } else {
11944 // Update
11945 var existing = useFiber(current$$1, textContent, expirationTime);
11946 existing.return = returnFiber;
11947 return existing;
11948 }
11949 }
11950
11951 function updateElement(returnFiber, current$$1, element, expirationTime) {
11952 if (current$$1 !== null && current$$1.elementType === element.type) {
11953 // Move based on index
11954 var existing = useFiber(current$$1, element.props, expirationTime);
11955 existing.ref = coerceRef(returnFiber, current$$1, element);
11956 existing.return = returnFiber;
11957 {
11958 existing._debugSource = element._source;
11959 existing._debugOwner = element._owner;
11960 }
11961 return existing;
11962 } else {
11963 // Insert
11964 var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
11965 created.ref = coerceRef(returnFiber, current$$1, element);
11966 created.return = returnFiber;
11967 return created;
11968 }
11969 }
11970
11971 function updatePortal(returnFiber, current$$1, portal, expirationTime) {
11972 if (current$$1 === null || current$$1.tag !== HostPortal || current$$1.stateNode.containerInfo !== portal.containerInfo || current$$1.stateNode.implementation !== portal.implementation) {
11973 // Insert
11974 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
11975 created.return = returnFiber;
11976 return created;
11977 } else {
11978 // Update
11979 var existing = useFiber(current$$1, portal.children || [], expirationTime);
11980 existing.return = returnFiber;
11981 return existing;
11982 }
11983 }
11984
11985 function updateFragment(returnFiber, current$$1, fragment, expirationTime, key) {
11986 if (current$$1 === null || current$$1.tag !== Fragment) {
11987 // Insert
11988 var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
11989 created.return = returnFiber;
11990 return created;
11991 } else {
11992 // Update
11993 var existing = useFiber(current$$1, fragment, expirationTime);
11994 existing.return = returnFiber;
11995 return existing;
11996 }
11997 }
11998
11999 function createChild(returnFiber, newChild, expirationTime) {
12000 if (typeof newChild === 'string' || typeof newChild === 'number') {
12001 // Text nodes don't have keys. If the previous node is implicitly keyed
12002 // we can continue to replace it without aborting even if it is not a text
12003 // node.
12004 var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
12005 created.return = returnFiber;
12006 return created;
12007 }
12008
12009 if (typeof newChild === 'object' && newChild !== null) {
12010 switch (newChild.$$typeof) {
12011 case REACT_ELEMENT_TYPE:
12012 {
12013 var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
12014 _created.ref = coerceRef(returnFiber, null, newChild);
12015 _created.return = returnFiber;
12016 return _created;
12017 }
12018 case REACT_PORTAL_TYPE:
12019 {
12020 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
12021 _created2.return = returnFiber;
12022 return _created2;
12023 }
12024 }
12025
12026 if (isArray(newChild) || getIteratorFn(newChild)) {
12027 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
12028 _created3.return = returnFiber;
12029 return _created3;
12030 }
12031
12032 throwOnInvalidObjectType(returnFiber, newChild);
12033 }
12034
12035 {
12036 if (typeof newChild === 'function') {
12037 warnOnFunctionType();
12038 }
12039 }
12040
12041 return null;
12042 }
12043
12044 function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
12045 // Update the fiber if the keys match, otherwise return null.
12046
12047 var key = oldFiber !== null ? oldFiber.key : null;
12048
12049 if (typeof newChild === 'string' || typeof newChild === 'number') {
12050 // Text nodes don't have keys. If the previous node is implicitly keyed
12051 // we can continue to replace it without aborting even if it is not a text
12052 // node.
12053 if (key !== null) {
12054 return null;
12055 }
12056 return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
12057 }
12058
12059 if (typeof newChild === 'object' && newChild !== null) {
12060 switch (newChild.$$typeof) {
12061 case REACT_ELEMENT_TYPE:
12062 {
12063 if (newChild.key === key) {
12064 if (newChild.type === REACT_FRAGMENT_TYPE) {
12065 return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
12066 }
12067 return updateElement(returnFiber, oldFiber, newChild, expirationTime);
12068 } else {
12069 return null;
12070 }
12071 }
12072 case REACT_PORTAL_TYPE:
12073 {
12074 if (newChild.key === key) {
12075 return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
12076 } else {
12077 return null;
12078 }
12079 }
12080 }
12081
12082 if (isArray(newChild) || getIteratorFn(newChild)) {
12083 if (key !== null) {
12084 return null;
12085 }
12086
12087 return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
12088 }
12089
12090 throwOnInvalidObjectType(returnFiber, newChild);
12091 }
12092
12093 {
12094 if (typeof newChild === 'function') {
12095 warnOnFunctionType();
12096 }
12097 }
12098
12099 return null;
12100 }
12101
12102 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
12103 if (typeof newChild === 'string' || typeof newChild === 'number') {
12104 // Text nodes don't have keys, so we neither have to check the old nor
12105 // new node for the key. If both are text nodes, they match.
12106 var matchedFiber = existingChildren.get(newIdx) || null;
12107 return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
12108 }
12109
12110 if (typeof newChild === 'object' && newChild !== null) {
12111 switch (newChild.$$typeof) {
12112 case REACT_ELEMENT_TYPE:
12113 {
12114 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
12115 if (newChild.type === REACT_FRAGMENT_TYPE) {
12116 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
12117 }
12118 return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
12119 }
12120 case REACT_PORTAL_TYPE:
12121 {
12122 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
12123 return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
12124 }
12125 }
12126
12127 if (isArray(newChild) || getIteratorFn(newChild)) {
12128 var _matchedFiber3 = existingChildren.get(newIdx) || null;
12129 return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
12130 }
12131
12132 throwOnInvalidObjectType(returnFiber, newChild);
12133 }
12134
12135 {
12136 if (typeof newChild === 'function') {
12137 warnOnFunctionType();
12138 }
12139 }
12140
12141 return null;
12142 }
12143
12144 /**
12145 * Warns if there is a duplicate or missing key
12146 */
12147 function warnOnInvalidKey(child, knownKeys) {
12148 {
12149 if (typeof child !== 'object' || child === null) {
12150 return knownKeys;
12151 }
12152 switch (child.$$typeof) {
12153 case REACT_ELEMENT_TYPE:
12154 case REACT_PORTAL_TYPE:
12155 warnForMissingKey(child);
12156 var key = child.key;
12157 if (typeof key !== 'string') {
12158 break;
12159 }
12160 if (knownKeys === null) {
12161 knownKeys = new Set();
12162 knownKeys.add(key);
12163 break;
12164 }
12165 if (!knownKeys.has(key)) {
12166 knownKeys.add(key);
12167 break;
12168 }
12169 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);
12170 break;
12171 default:
12172 break;
12173 }
12174 }
12175 return knownKeys;
12176 }
12177
12178 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
12179 // This algorithm can't optimize by searching from boths ends since we
12180 // don't have backpointers on fibers. I'm trying to see how far we can get
12181 // with that model. If it ends up not being worth the tradeoffs, we can
12182 // add it later.
12183
12184 // Even with a two ended optimization, we'd want to optimize for the case
12185 // where there are few changes and brute force the comparison instead of
12186 // going for the Map. It'd like to explore hitting that path first in
12187 // forward-only mode and only go for the Map once we notice that we need
12188 // lots of look ahead. This doesn't handle reversal as well as two ended
12189 // search but that's unusual. Besides, for the two ended optimization to
12190 // work on Iterables, we'd need to copy the whole set.
12191
12192 // In this first iteration, we'll just live with hitting the bad case
12193 // (adding everything to a Map) in for every insert/move.
12194
12195 // If you change this code, also update reconcileChildrenIterator() which
12196 // uses the same algorithm.
12197
12198 {
12199 // First, validate keys.
12200 var knownKeys = null;
12201 for (var i = 0; i < newChildren.length; i++) {
12202 var child = newChildren[i];
12203 knownKeys = warnOnInvalidKey(child, knownKeys);
12204 }
12205 }
12206
12207 var resultingFirstChild = null;
12208 var previousNewFiber = null;
12209
12210 var oldFiber = currentFirstChild;
12211 var lastPlacedIndex = 0;
12212 var newIdx = 0;
12213 var nextOldFiber = null;
12214 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
12215 if (oldFiber.index > newIdx) {
12216 nextOldFiber = oldFiber;
12217 oldFiber = null;
12218 } else {
12219 nextOldFiber = oldFiber.sibling;
12220 }
12221 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
12222 if (newFiber === null) {
12223 // TODO: This breaks on empty slots like null children. That's
12224 // unfortunate because it triggers the slow path all the time. We need
12225 // a better way to communicate whether this was a miss or null,
12226 // boolean, undefined, etc.
12227 if (oldFiber === null) {
12228 oldFiber = nextOldFiber;
12229 }
12230 break;
12231 }
12232 if (shouldTrackSideEffects) {
12233 if (oldFiber && newFiber.alternate === null) {
12234 // We matched the slot, but we didn't reuse the existing fiber, so we
12235 // need to delete the existing child.
12236 deleteChild(returnFiber, oldFiber);
12237 }
12238 }
12239 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
12240 if (previousNewFiber === null) {
12241 // TODO: Move out of the loop. This only happens for the first run.
12242 resultingFirstChild = newFiber;
12243 } else {
12244 // TODO: Defer siblings if we're not at the right index for this slot.
12245 // I.e. if we had null values before, then we want to defer this
12246 // for each null value. However, we also don't want to call updateSlot
12247 // with the previous one.
12248 previousNewFiber.sibling = newFiber;
12249 }
12250 previousNewFiber = newFiber;
12251 oldFiber = nextOldFiber;
12252 }
12253
12254 if (newIdx === newChildren.length) {
12255 // We've reached the end of the new children. We can delete the rest.
12256 deleteRemainingChildren(returnFiber, oldFiber);
12257 return resultingFirstChild;
12258 }
12259
12260 if (oldFiber === null) {
12261 // If we don't have any more existing children we can choose a fast path
12262 // since the rest will all be insertions.
12263 for (; newIdx < newChildren.length; newIdx++) {
12264 var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
12265 if (!_newFiber) {
12266 continue;
12267 }
12268 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
12269 if (previousNewFiber === null) {
12270 // TODO: Move out of the loop. This only happens for the first run.
12271 resultingFirstChild = _newFiber;
12272 } else {
12273 previousNewFiber.sibling = _newFiber;
12274 }
12275 previousNewFiber = _newFiber;
12276 }
12277 return resultingFirstChild;
12278 }
12279
12280 // Add all children to a key map for quick lookups.
12281 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
12282
12283 // Keep scanning and use the map to restore deleted items as moves.
12284 for (; newIdx < newChildren.length; newIdx++) {
12285 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
12286 if (_newFiber2) {
12287 if (shouldTrackSideEffects) {
12288 if (_newFiber2.alternate !== null) {
12289 // The new fiber is a work in progress, but if there exists a
12290 // current, that means that we reused the fiber. We need to delete
12291 // it from the child list so that we don't add it to the deletion
12292 // list.
12293 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
12294 }
12295 }
12296 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
12297 if (previousNewFiber === null) {
12298 resultingFirstChild = _newFiber2;
12299 } else {
12300 previousNewFiber.sibling = _newFiber2;
12301 }
12302 previousNewFiber = _newFiber2;
12303 }
12304 }
12305
12306 if (shouldTrackSideEffects) {
12307 // Any existing children that weren't consumed above were deleted. We need
12308 // to add them to the deletion list.
12309 existingChildren.forEach(function (child) {
12310 return deleteChild(returnFiber, child);
12311 });
12312 }
12313
12314 return resultingFirstChild;
12315 }
12316
12317 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
12318 // This is the same implementation as reconcileChildrenArray(),
12319 // but using the iterator instead.
12320
12321 var iteratorFn = getIteratorFn(newChildrenIterable);
12322 !(typeof iteratorFn === 'function') ? invariant(false, 'An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.') : void 0;
12323
12324 {
12325 // We don't support rendering Generators because it's a mutation.
12326 // See https://github.com/facebook/react/issues/12995
12327 if (typeof Symbol === 'function' &&
12328 // $FlowFixMe Flow doesn't know about toStringTag
12329 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
12330 !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;
12331 didWarnAboutGenerators = true;
12332 }
12333
12334 // Warn about using Maps as children
12335 if (newChildrenIterable.entries === iteratorFn) {
12336 !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;
12337 didWarnAboutMaps = true;
12338 }
12339
12340 // First, validate keys.
12341 // We'll get a different iterator later for the main pass.
12342 var _newChildren = iteratorFn.call(newChildrenIterable);
12343 if (_newChildren) {
12344 var knownKeys = null;
12345 var _step = _newChildren.next();
12346 for (; !_step.done; _step = _newChildren.next()) {
12347 var child = _step.value;
12348 knownKeys = warnOnInvalidKey(child, knownKeys);
12349 }
12350 }
12351 }
12352
12353 var newChildren = iteratorFn.call(newChildrenIterable);
12354 !(newChildren != null) ? invariant(false, 'An iterable object provided no iterator.') : void 0;
12355
12356 var resultingFirstChild = null;
12357 var previousNewFiber = null;
12358
12359 var oldFiber = currentFirstChild;
12360 var lastPlacedIndex = 0;
12361 var newIdx = 0;
12362 var nextOldFiber = null;
12363
12364 var step = newChildren.next();
12365 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
12366 if (oldFiber.index > newIdx) {
12367 nextOldFiber = oldFiber;
12368 oldFiber = null;
12369 } else {
12370 nextOldFiber = oldFiber.sibling;
12371 }
12372 var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
12373 if (newFiber === null) {
12374 // TODO: This breaks on empty slots like null children. That's
12375 // unfortunate because it triggers the slow path all the time. We need
12376 // a better way to communicate whether this was a miss or null,
12377 // boolean, undefined, etc.
12378 if (!oldFiber) {
12379 oldFiber = nextOldFiber;
12380 }
12381 break;
12382 }
12383 if (shouldTrackSideEffects) {
12384 if (oldFiber && newFiber.alternate === null) {
12385 // We matched the slot, but we didn't reuse the existing fiber, so we
12386 // need to delete the existing child.
12387 deleteChild(returnFiber, oldFiber);
12388 }
12389 }
12390 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
12391 if (previousNewFiber === null) {
12392 // TODO: Move out of the loop. This only happens for the first run.
12393 resultingFirstChild = newFiber;
12394 } else {
12395 // TODO: Defer siblings if we're not at the right index for this slot.
12396 // I.e. if we had null values before, then we want to defer this
12397 // for each null value. However, we also don't want to call updateSlot
12398 // with the previous one.
12399 previousNewFiber.sibling = newFiber;
12400 }
12401 previousNewFiber = newFiber;
12402 oldFiber = nextOldFiber;
12403 }
12404
12405 if (step.done) {
12406 // We've reached the end of the new children. We can delete the rest.
12407 deleteRemainingChildren(returnFiber, oldFiber);
12408 return resultingFirstChild;
12409 }
12410
12411 if (oldFiber === null) {
12412 // If we don't have any more existing children we can choose a fast path
12413 // since the rest will all be insertions.
12414 for (; !step.done; newIdx++, step = newChildren.next()) {
12415 var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
12416 if (_newFiber3 === null) {
12417 continue;
12418 }
12419 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
12420 if (previousNewFiber === null) {
12421 // TODO: Move out of the loop. This only happens for the first run.
12422 resultingFirstChild = _newFiber3;
12423 } else {
12424 previousNewFiber.sibling = _newFiber3;
12425 }
12426 previousNewFiber = _newFiber3;
12427 }
12428 return resultingFirstChild;
12429 }
12430
12431 // Add all children to a key map for quick lookups.
12432 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
12433
12434 // Keep scanning and use the map to restore deleted items as moves.
12435 for (; !step.done; newIdx++, step = newChildren.next()) {
12436 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
12437 if (_newFiber4 !== null) {
12438 if (shouldTrackSideEffects) {
12439 if (_newFiber4.alternate !== null) {
12440 // The new fiber is a work in progress, but if there exists a
12441 // current, that means that we reused the fiber. We need to delete
12442 // it from the child list so that we don't add it to the deletion
12443 // list.
12444 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
12445 }
12446 }
12447 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
12448 if (previousNewFiber === null) {
12449 resultingFirstChild = _newFiber4;
12450 } else {
12451 previousNewFiber.sibling = _newFiber4;
12452 }
12453 previousNewFiber = _newFiber4;
12454 }
12455 }
12456
12457 if (shouldTrackSideEffects) {
12458 // Any existing children that weren't consumed above were deleted. We need
12459 // to add them to the deletion list.
12460 existingChildren.forEach(function (child) {
12461 return deleteChild(returnFiber, child);
12462 });
12463 }
12464
12465 return resultingFirstChild;
12466 }
12467
12468 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
12469 // There's no need to check for keys on text nodes since we don't have a
12470 // way to define them.
12471 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
12472 // We already have an existing node so let's just update it and delete
12473 // the rest.
12474 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
12475 var existing = useFiber(currentFirstChild, textContent, expirationTime);
12476 existing.return = returnFiber;
12477 return existing;
12478 }
12479 // The existing first child is not a text node so we need to create one
12480 // and delete the existing ones.
12481 deleteRemainingChildren(returnFiber, currentFirstChild);
12482 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
12483 created.return = returnFiber;
12484 return created;
12485 }
12486
12487 function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
12488 var key = element.key;
12489 var child = currentFirstChild;
12490 while (child !== null) {
12491 // TODO: If key === null and child.key === null, then this only applies to
12492 // the first item in the list.
12493 if (child.key === key) {
12494 if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.elementType === element.type) {
12495 deleteRemainingChildren(returnFiber, child.sibling);
12496 var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
12497 existing.ref = coerceRef(returnFiber, child, element);
12498 existing.return = returnFiber;
12499 {
12500 existing._debugSource = element._source;
12501 existing._debugOwner = element._owner;
12502 }
12503 return existing;
12504 } else {
12505 deleteRemainingChildren(returnFiber, child);
12506 break;
12507 }
12508 } else {
12509 deleteChild(returnFiber, child);
12510 }
12511 child = child.sibling;
12512 }
12513
12514 if (element.type === REACT_FRAGMENT_TYPE) {
12515 var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
12516 created.return = returnFiber;
12517 return created;
12518 } else {
12519 var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
12520 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
12521 _created4.return = returnFiber;
12522 return _created4;
12523 }
12524 }
12525
12526 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
12527 var key = portal.key;
12528 var child = currentFirstChild;
12529 while (child !== null) {
12530 // TODO: If key === null and child.key === null, then this only applies to
12531 // the first item in the list.
12532 if (child.key === key) {
12533 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
12534 deleteRemainingChildren(returnFiber, child.sibling);
12535 var existing = useFiber(child, portal.children || [], expirationTime);
12536 existing.return = returnFiber;
12537 return existing;
12538 } else {
12539 deleteRemainingChildren(returnFiber, child);
12540 break;
12541 }
12542 } else {
12543 deleteChild(returnFiber, child);
12544 }
12545 child = child.sibling;
12546 }
12547
12548 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
12549 created.return = returnFiber;
12550 return created;
12551 }
12552
12553 // This API will tag the children with the side-effect of the reconciliation
12554 // itself. They will be added to the side-effect list as we pass through the
12555 // children and the parent.
12556 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
12557 // This function is not recursive.
12558 // If the top level item is an array, we treat it as a set of children,
12559 // not as a fragment. Nested arrays on the other hand will be treated as
12560 // fragment nodes. Recursion happens at the normal flow.
12561
12562 // Handle top level unkeyed fragments as if they were arrays.
12563 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
12564 // We treat the ambiguous cases above the same.
12565 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
12566 if (isUnkeyedTopLevelFragment) {
12567 newChild = newChild.props.children;
12568 }
12569
12570 // Handle object types
12571 var isObject = typeof newChild === 'object' && newChild !== null;
12572
12573 if (isObject) {
12574 switch (newChild.$$typeof) {
12575 case REACT_ELEMENT_TYPE:
12576 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
12577 case REACT_PORTAL_TYPE:
12578 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
12579 }
12580 }
12581
12582 if (typeof newChild === 'string' || typeof newChild === 'number') {
12583 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
12584 }
12585
12586 if (isArray(newChild)) {
12587 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
12588 }
12589
12590 if (getIteratorFn(newChild)) {
12591 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
12592 }
12593
12594 if (isObject) {
12595 throwOnInvalidObjectType(returnFiber, newChild);
12596 }
12597
12598 {
12599 if (typeof newChild === 'function') {
12600 warnOnFunctionType();
12601 }
12602 }
12603 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
12604 // If the new child is undefined, and the return fiber is a composite
12605 // component, throw an error. If Fiber return types are disabled,
12606 // we already threw above.
12607 switch (returnFiber.tag) {
12608 case ClassComponent:
12609 {
12610 {
12611 var instance = returnFiber.stateNode;
12612 if (instance.render._isMockFunction) {
12613 // We allow auto-mocks to proceed as if they're returning null.
12614 break;
12615 }
12616 }
12617 }
12618 // Intentionally fall through to the next case, which handles both
12619 // functions and classes
12620 // eslint-disable-next-lined no-fallthrough
12621 case FunctionComponent:
12622 {
12623 var Component = returnFiber.type;
12624 invariant(false, '%s(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.', Component.displayName || Component.name || 'Component');
12625 }
12626 }
12627 }
12628
12629 // Remaining cases are all treated as empty.
12630 return deleteRemainingChildren(returnFiber, currentFirstChild);
12631 }
12632
12633 return reconcileChildFibers;
12634}
12635
12636var reconcileChildFibers = ChildReconciler(true);
12637var mountChildFibers = ChildReconciler(false);
12638
12639function cloneChildFibers(current$$1, workInProgress) {
12640 !(current$$1 === null || workInProgress.child === current$$1.child) ? invariant(false, 'Resuming work not yet implemented.') : void 0;
12641
12642 if (workInProgress.child === null) {
12643 return;
12644 }
12645
12646 var currentChild = workInProgress.child;
12647 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
12648 workInProgress.child = newChild;
12649
12650 newChild.return = workInProgress;
12651 while (currentChild.sibling !== null) {
12652 currentChild = currentChild.sibling;
12653 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
12654 newChild.return = workInProgress;
12655 }
12656 newChild.sibling = null;
12657}
12658
12659var NO_CONTEXT = {};
12660
12661var contextStackCursor$1 = createCursor(NO_CONTEXT);
12662var contextFiberStackCursor = createCursor(NO_CONTEXT);
12663var rootInstanceStackCursor = createCursor(NO_CONTEXT);
12664
12665function requiredContext(c) {
12666 !(c !== NO_CONTEXT) ? invariant(false, 'Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.') : void 0;
12667 return c;
12668}
12669
12670function getRootHostContainer() {
12671 var rootInstance = requiredContext(rootInstanceStackCursor.current);
12672 return rootInstance;
12673}
12674
12675function pushHostContainer(fiber, nextRootInstance) {
12676 // Push current root instance onto the stack;
12677 // This allows us to reset root when portals are popped.
12678 push(rootInstanceStackCursor, nextRootInstance, fiber);
12679 // Track the context and the Fiber that provided it.
12680 // This enables us to pop only Fibers that provide unique contexts.
12681 push(contextFiberStackCursor, fiber, fiber);
12682
12683 // Finally, we need to push the host context to the stack.
12684 // However, we can't just call getRootHostContext() and push it because
12685 // we'd have a different number of entries on the stack depending on
12686 // whether getRootHostContext() throws somewhere in renderer code or not.
12687 // So we push an empty value first. This lets us safely unwind on errors.
12688 push(contextStackCursor$1, NO_CONTEXT, fiber);
12689 var nextRootContext = getRootHostContext(nextRootInstance);
12690 // Now that we know this function doesn't throw, replace it.
12691 pop(contextStackCursor$1, fiber);
12692 push(contextStackCursor$1, nextRootContext, fiber);
12693}
12694
12695function popHostContainer(fiber) {
12696 pop(contextStackCursor$1, fiber);
12697 pop(contextFiberStackCursor, fiber);
12698 pop(rootInstanceStackCursor, fiber);
12699}
12700
12701function getHostContext() {
12702 var context = requiredContext(contextStackCursor$1.current);
12703 return context;
12704}
12705
12706function pushHostContext(fiber) {
12707 var rootInstance = requiredContext(rootInstanceStackCursor.current);
12708 var context = requiredContext(contextStackCursor$1.current);
12709 var nextContext = getChildHostContext(context, fiber.type, rootInstance);
12710
12711 // Don't push this Fiber's context unless it's unique.
12712 if (context === nextContext) {
12713 return;
12714 }
12715
12716 // Track the context and the Fiber that provided it.
12717 // This enables us to pop only Fibers that provide unique contexts.
12718 push(contextFiberStackCursor, fiber, fiber);
12719 push(contextStackCursor$1, nextContext, fiber);
12720}
12721
12722function popHostContext(fiber) {
12723 // Do not pop unless this Fiber provided the current context.
12724 // pushHostContext() only pushes Fibers that provide unique contexts.
12725 if (contextFiberStackCursor.current !== fiber) {
12726 return;
12727 }
12728
12729 pop(contextStackCursor$1, fiber);
12730 pop(contextFiberStackCursor, fiber);
12731}
12732
12733var NoEffect$1 = /* */0;
12734var UnmountSnapshot = /* */2;
12735var UnmountMutation = /* */4;
12736var MountMutation = /* */8;
12737var UnmountLayout = /* */16;
12738var MountLayout = /* */32;
12739var MountPassive = /* */64;
12740var UnmountPassive = /* */128;
12741
12742var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
12743
12744
12745var didWarnAboutMismatchedHooksForComponent = void 0;
12746{
12747 didWarnAboutMismatchedHooksForComponent = new Set();
12748}
12749
12750// These are set right before calling the component.
12751var renderExpirationTime = NoWork;
12752// The work-in-progress fiber. I've named it differently to distinguish it from
12753// the work-in-progress hook.
12754var currentlyRenderingFiber$1 = null;
12755
12756// Hooks are stored as a linked list on the fiber's memoizedState field. The
12757// current hook list is the list that belongs to the current fiber. The
12758// work-in-progress hook list is a new list that will be added to the
12759// work-in-progress fiber.
12760var firstCurrentHook = null;
12761var currentHook = null;
12762var nextCurrentHook = null;
12763var firstWorkInProgressHook = null;
12764var workInProgressHook = null;
12765var nextWorkInProgressHook = null;
12766
12767var remainingExpirationTime = NoWork;
12768var componentUpdateQueue = null;
12769var sideEffectTag = 0;
12770
12771// Updates scheduled during render will trigger an immediate re-render at the
12772// end of the current pass. We can't store these updates on the normal queue,
12773// because if the work is aborted, they should be discarded. Because this is
12774// a relatively rare case, we also don't want to add an additional field to
12775// either the hook or queue object types. So we store them in a lazily create
12776// map of queue -> render-phase updates, which are discarded once the component
12777// completes without re-rendering.
12778
12779// Whether an update was scheduled during the currently executing render pass.
12780var didScheduleRenderPhaseUpdate = false;
12781// Lazily created map of render-phase updates
12782var renderPhaseUpdates = null;
12783// Counter to prevent infinite loops.
12784var numberOfReRenders = 0;
12785var RE_RENDER_LIMIT = 25;
12786
12787// In DEV, this is the name of the currently executing primitive hook
12788var currentHookNameInDev = null;
12789
12790function warnOnHookMismatchInDev() {
12791 {
12792 var componentName = getComponentName(currentlyRenderingFiber$1.type);
12793 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
12794 didWarnAboutMismatchedHooksForComponent.add(componentName);
12795
12796 var secondColumnStart = 22;
12797
12798 var table = '';
12799 var prevHook = firstCurrentHook;
12800 var nextHook = firstWorkInProgressHook;
12801 var n = 1;
12802 while (prevHook !== null && nextHook !== null) {
12803 var oldHookName = prevHook._debugType;
12804 var newHookName = nextHook._debugType;
12805
12806 var row = n + '. ' + oldHookName;
12807
12808 // Extra space so second column lines up
12809 // lol @ IE not supporting String#repeat
12810 while (row.length < secondColumnStart) {
12811 row += ' ';
12812 }
12813
12814 row += newHookName + '\n';
12815
12816 table += row;
12817 prevHook = prevHook.next;
12818 nextHook = nextHook.next;
12819 n++;
12820 }
12821
12822 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);
12823 }
12824 }
12825}
12826
12827function throwInvalidHookError() {
12828 invariant(false, 'Hooks can only be called inside the body of a function component. (https://fb.me/react-invalid-hook-call)');
12829}
12830
12831function areHookInputsEqual(nextDeps, prevDeps) {
12832 if (prevDeps === null) {
12833 {
12834 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);
12835 }
12836 return false;
12837 }
12838
12839 {
12840 // Don't bother comparing lengths in prod because these arrays should be
12841 // passed inline.
12842 if (nextDeps.length !== prevDeps.length) {
12843 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, '[' + nextDeps.join(', ') + ']', '[' + prevDeps.join(', ') + ']');
12844 }
12845 }
12846 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
12847 if (is(nextDeps[i], prevDeps[i])) {
12848 continue;
12849 }
12850 return false;
12851 }
12852 return true;
12853}
12854
12855function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) {
12856 renderExpirationTime = nextRenderExpirationTime;
12857 currentlyRenderingFiber$1 = workInProgress;
12858 firstCurrentHook = nextCurrentHook = current !== null ? current.memoizedState : null;
12859
12860 // The following should have already been reset
12861 // currentHook = null;
12862 // workInProgressHook = null;
12863
12864 // remainingExpirationTime = NoWork;
12865 // componentUpdateQueue = null;
12866
12867 // didScheduleRenderPhaseUpdate = false;
12868 // renderPhaseUpdates = null;
12869 // numberOfReRenders = 0;
12870 // sideEffectTag = 0;
12871
12872 {
12873 ReactCurrentDispatcher$1.current = nextCurrentHook === null ? HooksDispatcherOnMountInDEV : HooksDispatcherOnUpdateInDEV;
12874 }
12875
12876 var children = Component(props, refOrContext);
12877
12878 if (didScheduleRenderPhaseUpdate) {
12879 do {
12880 didScheduleRenderPhaseUpdate = false;
12881 numberOfReRenders += 1;
12882
12883 // Start over from the beginning of the list
12884 firstCurrentHook = nextCurrentHook = current !== null ? current.memoizedState : null;
12885 nextWorkInProgressHook = firstWorkInProgressHook;
12886
12887 currentHook = null;
12888 workInProgressHook = null;
12889 componentUpdateQueue = null;
12890
12891 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
12892
12893 children = Component(props, refOrContext);
12894 } while (didScheduleRenderPhaseUpdate);
12895
12896 renderPhaseUpdates = null;
12897 numberOfReRenders = 0;
12898 }
12899
12900 {
12901 currentHookNameInDev = null;
12902 }
12903
12904 // We can assume the previous dispatcher is always this one, since we set it
12905 // at the beginning of the render phase and there's no re-entrancy.
12906 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
12907
12908 var renderedWork = currentlyRenderingFiber$1;
12909
12910 renderedWork.memoizedState = firstWorkInProgressHook;
12911 renderedWork.expirationTime = remainingExpirationTime;
12912 renderedWork.updateQueue = componentUpdateQueue;
12913 renderedWork.effectTag |= sideEffectTag;
12914
12915 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
12916
12917 renderExpirationTime = NoWork;
12918 currentlyRenderingFiber$1 = null;
12919
12920 firstCurrentHook = null;
12921 currentHook = null;
12922 nextCurrentHook = null;
12923 firstWorkInProgressHook = null;
12924 workInProgressHook = null;
12925 nextWorkInProgressHook = null;
12926
12927 remainingExpirationTime = NoWork;
12928 componentUpdateQueue = null;
12929 sideEffectTag = 0;
12930
12931 // These were reset above
12932 // didScheduleRenderPhaseUpdate = false;
12933 // renderPhaseUpdates = null;
12934 // numberOfReRenders = 0;
12935
12936 !!didRenderTooFewHooks ? invariant(false, 'Rendered fewer hooks than expected. This may be caused by an accidental early return statement.') : void 0;
12937
12938 return children;
12939}
12940
12941function bailoutHooks(current, workInProgress, expirationTime) {
12942 workInProgress.updateQueue = current.updateQueue;
12943 workInProgress.effectTag &= ~(Passive | Update);
12944 if (current.expirationTime <= expirationTime) {
12945 current.expirationTime = NoWork;
12946 }
12947}
12948
12949function resetHooks() {
12950 // We can assume the previous dispatcher is always this one, since we set it
12951 // at the beginning of the render phase and there's no re-entrancy.
12952 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
12953
12954 // This is used to reset the state of this module when a component throws.
12955 // It's also called inside mountIndeterminateComponent if we determine the
12956 // component is a module-style component.
12957 renderExpirationTime = NoWork;
12958 currentlyRenderingFiber$1 = null;
12959
12960 firstCurrentHook = null;
12961 currentHook = null;
12962 nextCurrentHook = null;
12963 firstWorkInProgressHook = null;
12964 workInProgressHook = null;
12965 nextWorkInProgressHook = null;
12966
12967 remainingExpirationTime = NoWork;
12968 componentUpdateQueue = null;
12969 sideEffectTag = 0;
12970
12971 {
12972 currentHookNameInDev = null;
12973 }
12974
12975 didScheduleRenderPhaseUpdate = false;
12976 renderPhaseUpdates = null;
12977 numberOfReRenders = 0;
12978}
12979
12980function mountWorkInProgressHook() {
12981 var hook = {
12982 memoizedState: null,
12983
12984 baseState: null,
12985 queue: null,
12986 baseUpdate: null,
12987
12988 next: null
12989 };
12990
12991 {
12992 hook._debugType = currentHookNameInDev;
12993 if (currentlyRenderingFiber$1 !== null && currentlyRenderingFiber$1.alternate !== null) {
12994 warning$1(false, '%s: Rendered more hooks than during the previous render. This is ' + 'not currently supported and may lead to unexpected behavior.', getComponentName(currentlyRenderingFiber$1.type));
12995 }
12996 }
12997 if (workInProgressHook === null) {
12998 // This is the first hook in the list
12999 firstWorkInProgressHook = workInProgressHook = hook;
13000 } else {
13001 // Append to the end of the list
13002 workInProgressHook = workInProgressHook.next = hook;
13003 }
13004 return workInProgressHook;
13005}
13006
13007function updateWorkInProgressHook() {
13008 // This function is used both for updates and for re-renders triggered by a
13009 // render phase update. It assumes there is either a current hook we can
13010 // clone, or a work-in-progress hook from a previous render pass that we can
13011 // use as a base. When we reach the end of the base list, we must switch to
13012 // the dispatcher used for mounts.
13013 if (nextWorkInProgressHook !== null) {
13014 // There's already a work-in-progress. Reuse it.
13015 workInProgressHook = nextWorkInProgressHook;
13016 nextWorkInProgressHook = workInProgressHook.next;
13017
13018 currentHook = nextCurrentHook;
13019 nextCurrentHook = currentHook !== null ? currentHook.next : null;
13020 } else {
13021 // Clone from the current hook.
13022 !(nextCurrentHook !== null) ? invariant(false, 'Rendered more hooks than during the previous render.') : void 0;
13023 currentHook = nextCurrentHook;
13024
13025 var newHook = {
13026 memoizedState: currentHook.memoizedState,
13027
13028 baseState: currentHook.baseState,
13029 queue: currentHook.queue,
13030 baseUpdate: currentHook.baseUpdate,
13031
13032 next: null
13033 };
13034
13035 if (workInProgressHook === null) {
13036 // This is the first hook in the list.
13037 workInProgressHook = firstWorkInProgressHook = newHook;
13038 } else {
13039 // Append to the end of the list.
13040 workInProgressHook = workInProgressHook.next = newHook;
13041 }
13042 nextCurrentHook = currentHook.next;
13043
13044 {
13045 newHook._debugType = currentHookNameInDev;
13046 if (currentHookNameInDev !== currentHook._debugType) {
13047 warnOnHookMismatchInDev();
13048 }
13049 }
13050 }
13051 return workInProgressHook;
13052}
13053
13054function createFunctionComponentUpdateQueue() {
13055 return {
13056 lastEffect: null
13057 };
13058}
13059
13060function basicStateReducer(state, action) {
13061 return typeof action === 'function' ? action(state) : action;
13062}
13063
13064function mountContext(context, observedBits) {
13065 {
13066 mountWorkInProgressHook();
13067 }
13068 return readContext(context, observedBits);
13069}
13070
13071function updateContext(context, observedBits) {
13072 {
13073 updateWorkInProgressHook();
13074 }
13075 return readContext(context, observedBits);
13076}
13077
13078function mountReducer(reducer, initialArg, init) {
13079 var hook = mountWorkInProgressHook();
13080 var initialState = void 0;
13081 if (init !== undefined) {
13082 initialState = init(initialArg);
13083 } else {
13084 initialState = initialArg;
13085 }
13086 hook.memoizedState = hook.baseState = initialState;
13087 var queue = hook.queue = {
13088 last: null,
13089 dispatch: null,
13090 eagerReducer: reducer,
13091 eagerState: initialState
13092 };
13093 var dispatch = queue.dispatch = dispatchAction.bind(null,
13094 // Flow doesn't know this is non-null, but we do.
13095 currentlyRenderingFiber$1, queue);
13096 return [hook.memoizedState, dispatch];
13097}
13098
13099function updateReducer(reducer, initialArg, init) {
13100 var hook = updateWorkInProgressHook();
13101 var queue = hook.queue;
13102 !(queue !== null) ? invariant(false, 'Should have a queue. This is likely a bug in React. Please file an issue.') : void 0;
13103
13104 if (numberOfReRenders > 0) {
13105 // This is a re-render. Apply the new render phase updates to the previous
13106 var _dispatch = queue.dispatch;
13107 if (renderPhaseUpdates !== null) {
13108 // Render phase updates are stored in a map of queue -> linked list
13109 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
13110 if (firstRenderPhaseUpdate !== undefined) {
13111 renderPhaseUpdates.delete(queue);
13112 var newState = hook.memoizedState;
13113 var update = firstRenderPhaseUpdate;
13114 do {
13115 // Process this render phase update. We don't have to check the
13116 // priority because it will always be the same as the current
13117 // render's.
13118 var _action = update.action;
13119 newState = reducer(newState, _action);
13120 update = update.next;
13121 } while (update !== null);
13122
13123 // Mark that the fiber performed work, but only if the new state is
13124 // different from the current state.
13125 if (!is(newState, hook.memoizedState)) {
13126 markWorkInProgressReceivedUpdate();
13127 }
13128
13129 hook.memoizedState = newState;
13130
13131 // Don't persist the state accumlated from the render phase updates to
13132 // the base state unless the queue is empty.
13133 // TODO: Not sure if this is the desired semantics, but it's what we
13134 // do for gDSFP. I can't remember why.
13135 if (hook.baseUpdate === queue.last) {
13136 hook.baseState = newState;
13137 }
13138
13139 return [newState, _dispatch];
13140 }
13141 }
13142 return [hook.memoizedState, _dispatch];
13143 }
13144
13145 // The last update in the entire queue
13146 var last = queue.last;
13147 // The last update that is part of the base state.
13148 var baseUpdate = hook.baseUpdate;
13149 var baseState = hook.baseState;
13150
13151 // Find the first unprocessed update.
13152 var first = void 0;
13153 if (baseUpdate !== null) {
13154 if (last !== null) {
13155 // For the first update, the queue is a circular linked list where
13156 // `queue.last.next = queue.first`. Once the first update commits, and
13157 // the `baseUpdate` is no longer empty, we can unravel the list.
13158 last.next = null;
13159 }
13160 first = baseUpdate.next;
13161 } else {
13162 first = last !== null ? last.next : null;
13163 }
13164 if (first !== null) {
13165 var _newState = baseState;
13166 var newBaseState = null;
13167 var newBaseUpdate = null;
13168 var prevUpdate = baseUpdate;
13169 var _update = first;
13170 var didSkip = false;
13171 do {
13172 var updateExpirationTime = _update.expirationTime;
13173 if (updateExpirationTime < renderExpirationTime) {
13174 // Priority is insufficient. Skip this update. If this is the first
13175 // skipped update, the previous update/state is the new base
13176 // update/state.
13177 if (!didSkip) {
13178 didSkip = true;
13179 newBaseUpdate = prevUpdate;
13180 newBaseState = _newState;
13181 }
13182 // Update the remaining priority in the queue.
13183 if (updateExpirationTime > remainingExpirationTime) {
13184 remainingExpirationTime = updateExpirationTime;
13185 }
13186 } else {
13187 // Process this update.
13188 if (_update.eagerReducer === reducer) {
13189 // If this update was processed eagerly, and its reducer matches the
13190 // current reducer, we can use the eagerly computed state.
13191 _newState = _update.eagerState;
13192 } else {
13193 var _action2 = _update.action;
13194 _newState = reducer(_newState, _action2);
13195 }
13196 }
13197 prevUpdate = _update;
13198 _update = _update.next;
13199 } while (_update !== null && _update !== first);
13200
13201 if (!didSkip) {
13202 newBaseUpdate = prevUpdate;
13203 newBaseState = _newState;
13204 }
13205
13206 // Mark that the fiber performed work, but only if the new state is
13207 // different from the current state.
13208 if (!is(_newState, hook.memoizedState)) {
13209 markWorkInProgressReceivedUpdate();
13210 }
13211
13212 hook.memoizedState = _newState;
13213 hook.baseUpdate = newBaseUpdate;
13214 hook.baseState = newBaseState;
13215
13216 queue.eagerReducer = reducer;
13217 queue.eagerState = _newState;
13218 }
13219
13220 var dispatch = queue.dispatch;
13221 return [hook.memoizedState, dispatch];
13222}
13223
13224function mountState(initialState) {
13225 var hook = mountWorkInProgressHook();
13226 if (typeof initialState === 'function') {
13227 initialState = initialState();
13228 }
13229 hook.memoizedState = hook.baseState = initialState;
13230 var queue = hook.queue = {
13231 last: null,
13232 dispatch: null,
13233 eagerReducer: basicStateReducer,
13234 eagerState: initialState
13235 };
13236 var dispatch = queue.dispatch = dispatchAction.bind(null,
13237 // Flow doesn't know this is non-null, but we do.
13238 currentlyRenderingFiber$1, queue);
13239 return [hook.memoizedState, dispatch];
13240}
13241
13242function updateState(initialState) {
13243 return updateReducer(basicStateReducer, initialState);
13244}
13245
13246function pushEffect(tag, create, destroy, deps) {
13247 var effect = {
13248 tag: tag,
13249 create: create,
13250 destroy: destroy,
13251 deps: deps,
13252 // Circular
13253 next: null
13254 };
13255 if (componentUpdateQueue === null) {
13256 componentUpdateQueue = createFunctionComponentUpdateQueue();
13257 componentUpdateQueue.lastEffect = effect.next = effect;
13258 } else {
13259 var _lastEffect = componentUpdateQueue.lastEffect;
13260 if (_lastEffect === null) {
13261 componentUpdateQueue.lastEffect = effect.next = effect;
13262 } else {
13263 var firstEffect = _lastEffect.next;
13264 _lastEffect.next = effect;
13265 effect.next = firstEffect;
13266 componentUpdateQueue.lastEffect = effect;
13267 }
13268 }
13269 return effect;
13270}
13271
13272function mountRef(initialValue) {
13273 var hook = mountWorkInProgressHook();
13274 var ref = { current: initialValue };
13275 {
13276 Object.seal(ref);
13277 }
13278 hook.memoizedState = ref;
13279 return ref;
13280}
13281
13282function updateRef(initialValue) {
13283 var hook = updateWorkInProgressHook();
13284 return hook.memoizedState;
13285}
13286
13287function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
13288 var hook = mountWorkInProgressHook();
13289 var nextDeps = deps === undefined ? null : deps;
13290 sideEffectTag |= fiberEffectTag;
13291 hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps);
13292}
13293
13294function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
13295 var hook = updateWorkInProgressHook();
13296 var nextDeps = deps === undefined ? null : deps;
13297 var destroy = undefined;
13298
13299 if (currentHook !== null) {
13300 var prevEffect = currentHook.memoizedState;
13301 destroy = prevEffect.destroy;
13302 if (nextDeps !== null) {
13303 var prevDeps = prevEffect.deps;
13304 if (areHookInputsEqual(nextDeps, prevDeps)) {
13305 pushEffect(NoEffect$1, create, destroy, nextDeps);
13306 return;
13307 }
13308 }
13309 }
13310
13311 sideEffectTag |= fiberEffectTag;
13312 hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps);
13313}
13314
13315function mountEffect(create, deps) {
13316 return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
13317}
13318
13319function updateEffect(create, deps) {
13320 return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
13321}
13322
13323function mountLayoutEffect(create, deps) {
13324 return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
13325}
13326
13327function updateLayoutEffect(create, deps) {
13328 return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
13329}
13330
13331function imperativeHandleEffect(create, ref) {
13332 if (typeof ref === 'function') {
13333 var refCallback = ref;
13334 var _inst = create();
13335 refCallback(_inst);
13336 return function () {
13337 refCallback(null);
13338 };
13339 } else if (ref !== null && ref !== undefined) {
13340 var refObject = ref;
13341 {
13342 !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;
13343 }
13344 var _inst2 = create();
13345 refObject.current = _inst2;
13346 return function () {
13347 refObject.current = null;
13348 };
13349 }
13350}
13351
13352function mountImperativeHandle(ref, create, deps) {
13353 {
13354 !(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;
13355 }
13356
13357 // TODO: If deps are provided, should we skip comparing the ref itself?
13358 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : [ref];
13359
13360 return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
13361}
13362
13363function updateImperativeHandle(ref, create, deps) {
13364 {
13365 !(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;
13366 }
13367
13368 // TODO: If deps are provided, should we skip comparing the ref itself?
13369 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : [ref];
13370
13371 return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
13372}
13373
13374function mountDebugValue(value, formatterFn) {
13375 // This hook is normally a no-op.
13376 // The react-debug-hooks package injects its own implementation
13377 // so that e.g. DevTools can display custom hook values.
13378}
13379
13380var updateDebugValue = mountDebugValue;
13381
13382function mountCallback(callback, deps) {
13383 var hook = mountWorkInProgressHook();
13384 var nextDeps = deps === undefined ? null : deps;
13385 hook.memoizedState = [callback, nextDeps];
13386 return callback;
13387}
13388
13389function updateCallback(callback, deps) {
13390 var hook = updateWorkInProgressHook();
13391 var nextDeps = deps === undefined ? null : deps;
13392 var prevState = hook.memoizedState;
13393 if (prevState !== null) {
13394 if (nextDeps !== null) {
13395 var prevDeps = prevState[1];
13396 if (areHookInputsEqual(nextDeps, prevDeps)) {
13397 return prevState[0];
13398 }
13399 }
13400 }
13401 hook.memoizedState = [callback, nextDeps];
13402 return callback;
13403}
13404
13405function mountMemo(nextCreate, deps) {
13406 var hook = mountWorkInProgressHook();
13407 var nextDeps = deps === undefined ? null : deps;
13408 var nextValue = nextCreate();
13409 hook.memoizedState = [nextValue, nextDeps];
13410 return nextValue;
13411}
13412
13413function updateMemo(nextCreate, deps) {
13414 var hook = updateWorkInProgressHook();
13415 var nextDeps = deps === undefined ? null : deps;
13416 var prevState = hook.memoizedState;
13417 if (prevState !== null) {
13418 // Assume these are defined. If they're not, areHookInputsEqual will warn.
13419 if (nextDeps !== null) {
13420 var prevDeps = prevState[1];
13421 if (areHookInputsEqual(nextDeps, prevDeps)) {
13422 return prevState[0];
13423 }
13424 }
13425 }
13426 var nextValue = nextCreate();
13427 hook.memoizedState = [nextValue, nextDeps];
13428 return nextValue;
13429}
13430
13431// in a test-like environment, we want to warn if dispatchAction()
13432// is called outside of a batchedUpdates/TestUtils.act(...) call.
13433var shouldWarnForUnbatchedSetState = false;
13434
13435{
13436 // jest isnt' a 'global', it's just exposed to tests via a wrapped function
13437 // further, this isn't a test file, so flow doesn't recognize the symbol. So...
13438 // $FlowExpectedError - because requirements don't give a damn about your type sigs.
13439 if ('undefined' !== typeof jest) {
13440 shouldWarnForUnbatchedSetState = true;
13441 }
13442}
13443
13444function dispatchAction(fiber, queue, action) {
13445 !(numberOfReRenders < RE_RENDER_LIMIT) ? invariant(false, 'Too many re-renders. React limits the number of renders to prevent an infinite loop.') : void 0;
13446
13447 {
13448 !(arguments.length <= 3) ? 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;
13449 }
13450
13451 var alternate = fiber.alternate;
13452 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
13453 // This is a render phase update. Stash it in a lazily-created map of
13454 // queue -> linked list of updates. After this render pass, we'll restart
13455 // and apply the stashed updates on top of the work-in-progress hook.
13456 didScheduleRenderPhaseUpdate = true;
13457 var update = {
13458 expirationTime: renderExpirationTime,
13459 action: action,
13460 eagerReducer: null,
13461 eagerState: null,
13462 next: null
13463 };
13464 if (renderPhaseUpdates === null) {
13465 renderPhaseUpdates = new Map();
13466 }
13467 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
13468 if (firstRenderPhaseUpdate === undefined) {
13469 renderPhaseUpdates.set(queue, update);
13470 } else {
13471 // Append the update to the end of the list.
13472 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
13473 while (lastRenderPhaseUpdate.next !== null) {
13474 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
13475 }
13476 lastRenderPhaseUpdate.next = update;
13477 }
13478 } else {
13479 flushPassiveEffects();
13480
13481 var currentTime = requestCurrentTime();
13482 var _expirationTime = computeExpirationForFiber(currentTime, fiber);
13483
13484 var _update2 = {
13485 expirationTime: _expirationTime,
13486 action: action,
13487 eagerReducer: null,
13488 eagerState: null,
13489 next: null
13490 };
13491
13492 // Append the update to the end of the list.
13493 var _last = queue.last;
13494 if (_last === null) {
13495 // This is the first update. Create a circular list.
13496 _update2.next = _update2;
13497 } else {
13498 var first = _last.next;
13499 if (first !== null) {
13500 // Still circular.
13501 _update2.next = first;
13502 }
13503 _last.next = _update2;
13504 }
13505 queue.last = _update2;
13506
13507 if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
13508 // The queue is currently empty, which means we can eagerly compute the
13509 // next state before entering the render phase. If the new state is the
13510 // same as the current state, we may be able to bail out entirely.
13511 var _eagerReducer = queue.eagerReducer;
13512 if (_eagerReducer !== null) {
13513 var prevDispatcher = void 0;
13514 {
13515 prevDispatcher = ReactCurrentDispatcher$1.current;
13516 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13517 }
13518 try {
13519 var currentState = queue.eagerState;
13520 var _eagerState = _eagerReducer(currentState, action);
13521 // Stash the eagerly computed state, and the reducer used to compute
13522 // it, on the update object. If the reducer hasn't changed by the
13523 // time we enter the render phase, then the eager state can be used
13524 // without calling the reducer again.
13525 _update2.eagerReducer = _eagerReducer;
13526 _update2.eagerState = _eagerState;
13527 if (is(_eagerState, currentState)) {
13528 // Fast path. We can bail out without scheduling React to re-render.
13529 // It's still possible that we'll need to rebase this update later,
13530 // if the component re-renders for a different reason and by that
13531 // time the reducer has changed.
13532 return;
13533 }
13534 } catch (error) {
13535 // Suppress the error. It will throw again in the render phase.
13536 } finally {
13537 {
13538 ReactCurrentDispatcher$1.current = prevDispatcher;
13539 }
13540 }
13541 }
13542 }
13543 {
13544 if (shouldWarnForUnbatchedSetState === true) {
13545 warnIfNotCurrentlyBatchingInDev(fiber);
13546 }
13547 }
13548 scheduleWork(fiber, _expirationTime);
13549 }
13550}
13551
13552var ContextOnlyDispatcher = {
13553 readContext: readContext,
13554
13555 useCallback: throwInvalidHookError,
13556 useContext: throwInvalidHookError,
13557 useEffect: throwInvalidHookError,
13558 useImperativeHandle: throwInvalidHookError,
13559 useLayoutEffect: throwInvalidHookError,
13560 useMemo: throwInvalidHookError,
13561 useReducer: throwInvalidHookError,
13562 useRef: throwInvalidHookError,
13563 useState: throwInvalidHookError,
13564 useDebugValue: throwInvalidHookError
13565};
13566
13567var HooksDispatcherOnMountInDEV = null;
13568var HooksDispatcherOnUpdateInDEV = null;
13569var InvalidNestedHooksDispatcherOnMountInDEV = null;
13570var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
13571
13572{
13573 var warnInvalidContextAccess = function () {
13574 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().');
13575 };
13576
13577 var warnInvalidHookAccess = function () {
13578 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');
13579 };
13580
13581 HooksDispatcherOnMountInDEV = {
13582 readContext: function (context, observedBits) {
13583 return readContext(context, observedBits);
13584 },
13585 useCallback: function (callback, deps) {
13586 currentHookNameInDev = 'useCallback';
13587 return mountCallback(callback, deps);
13588 },
13589 useContext: function (context, observedBits) {
13590 currentHookNameInDev = 'useContext';
13591 return mountContext(context, observedBits);
13592 },
13593 useEffect: function (create, deps) {
13594 currentHookNameInDev = 'useEffect';
13595 return mountEffect(create, deps);
13596 },
13597 useImperativeHandle: function (ref, create, deps) {
13598 currentHookNameInDev = 'useImperativeHandle';
13599 return mountImperativeHandle(ref, create, deps);
13600 },
13601 useLayoutEffect: function (create, deps) {
13602 currentHookNameInDev = 'useLayoutEffect';
13603 return mountLayoutEffect(create, deps);
13604 },
13605 useMemo: function (create, deps) {
13606 currentHookNameInDev = 'useMemo';
13607 var prevDispatcher = ReactCurrentDispatcher$1.current;
13608 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13609 try {
13610 return mountMemo(create, deps);
13611 } finally {
13612 ReactCurrentDispatcher$1.current = prevDispatcher;
13613 }
13614 },
13615 useReducer: function (reducer, initialArg, init) {
13616 currentHookNameInDev = 'useReducer';
13617 var prevDispatcher = ReactCurrentDispatcher$1.current;
13618 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13619 try {
13620 return mountReducer(reducer, initialArg, init);
13621 } finally {
13622 ReactCurrentDispatcher$1.current = prevDispatcher;
13623 }
13624 },
13625 useRef: function (initialValue) {
13626 currentHookNameInDev = 'useRef';
13627 return mountRef(initialValue);
13628 },
13629 useState: function (initialState) {
13630 currentHookNameInDev = 'useState';
13631 var prevDispatcher = ReactCurrentDispatcher$1.current;
13632 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13633 try {
13634 return mountState(initialState);
13635 } finally {
13636 ReactCurrentDispatcher$1.current = prevDispatcher;
13637 }
13638 },
13639 useDebugValue: function (value, formatterFn) {
13640 currentHookNameInDev = 'useDebugValue';
13641 return mountDebugValue(value, formatterFn);
13642 }
13643 };
13644
13645 HooksDispatcherOnUpdateInDEV = {
13646 readContext: function (context, observedBits) {
13647 return readContext(context, observedBits);
13648 },
13649 useCallback: function (callback, deps) {
13650 currentHookNameInDev = 'useCallback';
13651 return updateCallback(callback, deps);
13652 },
13653 useContext: function (context, observedBits) {
13654 currentHookNameInDev = 'useContext';
13655 return updateContext(context, observedBits);
13656 },
13657 useEffect: function (create, deps) {
13658 currentHookNameInDev = 'useEffect';
13659 return updateEffect(create, deps);
13660 },
13661 useImperativeHandle: function (ref, create, deps) {
13662 currentHookNameInDev = 'useImperativeHandle';
13663 return updateImperativeHandle(ref, create, deps);
13664 },
13665 useLayoutEffect: function (create, deps) {
13666 currentHookNameInDev = 'useLayoutEffect';
13667 return updateLayoutEffect(create, deps);
13668 },
13669 useMemo: function (create, deps) {
13670 currentHookNameInDev = 'useMemo';
13671 var prevDispatcher = ReactCurrentDispatcher$1.current;
13672 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13673 try {
13674 return updateMemo(create, deps);
13675 } finally {
13676 ReactCurrentDispatcher$1.current = prevDispatcher;
13677 }
13678 },
13679 useReducer: function (reducer, initialArg, init) {
13680 currentHookNameInDev = 'useReducer';
13681 var prevDispatcher = ReactCurrentDispatcher$1.current;
13682 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13683 try {
13684 return updateReducer(reducer, initialArg, init);
13685 } finally {
13686 ReactCurrentDispatcher$1.current = prevDispatcher;
13687 }
13688 },
13689 useRef: function (initialValue) {
13690 currentHookNameInDev = 'useRef';
13691 return updateRef(initialValue);
13692 },
13693 useState: function (initialState) {
13694 currentHookNameInDev = 'useState';
13695 var prevDispatcher = ReactCurrentDispatcher$1.current;
13696 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13697 try {
13698 return updateState(initialState);
13699 } finally {
13700 ReactCurrentDispatcher$1.current = prevDispatcher;
13701 }
13702 },
13703 useDebugValue: function (value, formatterFn) {
13704 currentHookNameInDev = 'useDebugValue';
13705 return updateDebugValue(value, formatterFn);
13706 }
13707 };
13708
13709 InvalidNestedHooksDispatcherOnMountInDEV = {
13710 readContext: function (context, observedBits) {
13711 warnInvalidContextAccess();
13712 return readContext(context, observedBits);
13713 },
13714 useCallback: function (callback, deps) {
13715 currentHookNameInDev = 'useCallback';
13716 warnInvalidHookAccess();
13717 return mountCallback(callback, deps);
13718 },
13719 useContext: function (context, observedBits) {
13720 currentHookNameInDev = 'useContext';
13721 warnInvalidHookAccess();
13722 return mountContext(context, observedBits);
13723 },
13724 useEffect: function (create, deps) {
13725 currentHookNameInDev = 'useEffect';
13726 warnInvalidHookAccess();
13727 return mountEffect(create, deps);
13728 },
13729 useImperativeHandle: function (ref, create, deps) {
13730 currentHookNameInDev = 'useImperativeHandle';
13731 warnInvalidHookAccess();
13732 return mountImperativeHandle(ref, create, deps);
13733 },
13734 useLayoutEffect: function (create, deps) {
13735 currentHookNameInDev = 'useLayoutEffect';
13736 warnInvalidHookAccess();
13737 return mountLayoutEffect(create, deps);
13738 },
13739 useMemo: function (create, deps) {
13740 currentHookNameInDev = 'useMemo';
13741 warnInvalidHookAccess();
13742 var prevDispatcher = ReactCurrentDispatcher$1.current;
13743 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13744 try {
13745 return mountMemo(create, deps);
13746 } finally {
13747 ReactCurrentDispatcher$1.current = prevDispatcher;
13748 }
13749 },
13750 useReducer: function (reducer, initialArg, init) {
13751 currentHookNameInDev = 'useReducer';
13752 warnInvalidHookAccess();
13753 var prevDispatcher = ReactCurrentDispatcher$1.current;
13754 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13755 try {
13756 return mountReducer(reducer, initialArg, init);
13757 } finally {
13758 ReactCurrentDispatcher$1.current = prevDispatcher;
13759 }
13760 },
13761 useRef: function (initialValue) {
13762 currentHookNameInDev = 'useRef';
13763 warnInvalidHookAccess();
13764 return mountRef(initialValue);
13765 },
13766 useState: function (initialState) {
13767 currentHookNameInDev = 'useState';
13768 warnInvalidHookAccess();
13769 var prevDispatcher = ReactCurrentDispatcher$1.current;
13770 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13771 try {
13772 return mountState(initialState);
13773 } finally {
13774 ReactCurrentDispatcher$1.current = prevDispatcher;
13775 }
13776 },
13777 useDebugValue: function (value, formatterFn) {
13778 currentHookNameInDev = 'useDebugValue';
13779 warnInvalidHookAccess();
13780 return mountDebugValue(value, formatterFn);
13781 }
13782 };
13783
13784 InvalidNestedHooksDispatcherOnUpdateInDEV = {
13785 readContext: function (context, observedBits) {
13786 warnInvalidContextAccess();
13787 return readContext(context, observedBits);
13788 },
13789 useCallback: function (callback, deps) {
13790 currentHookNameInDev = 'useCallback';
13791 warnInvalidHookAccess();
13792 return updateCallback(callback, deps);
13793 },
13794 useContext: function (context, observedBits) {
13795 currentHookNameInDev = 'useContext';
13796 warnInvalidHookAccess();
13797 return updateContext(context, observedBits);
13798 },
13799 useEffect: function (create, deps) {
13800 currentHookNameInDev = 'useEffect';
13801 warnInvalidHookAccess();
13802 return updateEffect(create, deps);
13803 },
13804 useImperativeHandle: function (ref, create, deps) {
13805 currentHookNameInDev = 'useImperativeHandle';
13806 warnInvalidHookAccess();
13807 return updateImperativeHandle(ref, create, deps);
13808 },
13809 useLayoutEffect: function (create, deps) {
13810 currentHookNameInDev = 'useLayoutEffect';
13811 warnInvalidHookAccess();
13812 return updateLayoutEffect(create, deps);
13813 },
13814 useMemo: function (create, deps) {
13815 currentHookNameInDev = 'useMemo';
13816 warnInvalidHookAccess();
13817 var prevDispatcher = ReactCurrentDispatcher$1.current;
13818 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13819 try {
13820 return updateMemo(create, deps);
13821 } finally {
13822 ReactCurrentDispatcher$1.current = prevDispatcher;
13823 }
13824 },
13825 useReducer: function (reducer, initialArg, init) {
13826 currentHookNameInDev = 'useReducer';
13827 warnInvalidHookAccess();
13828 var prevDispatcher = ReactCurrentDispatcher$1.current;
13829 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13830 try {
13831 return updateReducer(reducer, initialArg, init);
13832 } finally {
13833 ReactCurrentDispatcher$1.current = prevDispatcher;
13834 }
13835 },
13836 useRef: function (initialValue) {
13837 currentHookNameInDev = 'useRef';
13838 warnInvalidHookAccess();
13839 return updateRef(initialValue);
13840 },
13841 useState: function (initialState) {
13842 currentHookNameInDev = 'useState';
13843 warnInvalidHookAccess();
13844 var prevDispatcher = ReactCurrentDispatcher$1.current;
13845 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13846 try {
13847 return updateState(initialState);
13848 } finally {
13849 ReactCurrentDispatcher$1.current = prevDispatcher;
13850 }
13851 },
13852 useDebugValue: function (value, formatterFn) {
13853 currentHookNameInDev = 'useDebugValue';
13854 warnInvalidHookAccess();
13855 return updateDebugValue(value, formatterFn);
13856 }
13857 };
13858}
13859
13860var commitTime = 0;
13861var profilerStartTime = -1;
13862
13863function getCommitTime() {
13864 return commitTime;
13865}
13866
13867function recordCommitTime() {
13868 if (!enableProfilerTimer) {
13869 return;
13870 }
13871 commitTime = unstable_now();
13872}
13873
13874function startProfilerTimer(fiber) {
13875 if (!enableProfilerTimer) {
13876 return;
13877 }
13878
13879 profilerStartTime = unstable_now();
13880
13881 if (fiber.actualStartTime < 0) {
13882 fiber.actualStartTime = unstable_now();
13883 }
13884}
13885
13886function stopProfilerTimerIfRunning(fiber) {
13887 if (!enableProfilerTimer) {
13888 return;
13889 }
13890 profilerStartTime = -1;
13891}
13892
13893function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
13894 if (!enableProfilerTimer) {
13895 return;
13896 }
13897
13898 if (profilerStartTime >= 0) {
13899 var elapsedTime = unstable_now() - profilerStartTime;
13900 fiber.actualDuration += elapsedTime;
13901 if (overrideBaseTime) {
13902 fiber.selfBaseDuration = elapsedTime;
13903 }
13904 profilerStartTime = -1;
13905 }
13906}
13907
13908// The deepest Fiber on the stack involved in a hydration context.
13909// This may have been an insertion or a hydration.
13910var hydrationParentFiber = null;
13911var nextHydratableInstance = null;
13912var isHydrating = false;
13913
13914function enterHydrationState(fiber) {
13915 if (!supportsHydration) {
13916 return false;
13917 }
13918
13919 var parentInstance = fiber.stateNode.containerInfo;
13920 nextHydratableInstance = getFirstHydratableChild(parentInstance);
13921 hydrationParentFiber = fiber;
13922 isHydrating = true;
13923 return true;
13924}
13925
13926function deleteHydratableInstance(returnFiber, instance) {
13927 {
13928 switch (returnFiber.tag) {
13929 case HostRoot:
13930 didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
13931 break;
13932 case HostComponent:
13933 didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
13934 break;
13935 }
13936 }
13937
13938 var childToDelete = createFiberFromHostInstanceForDeletion();
13939 childToDelete.stateNode = instance;
13940 childToDelete.return = returnFiber;
13941 childToDelete.effectTag = Deletion;
13942
13943 // This might seem like it belongs on progressedFirstDeletion. However,
13944 // these children are not part of the reconciliation list of children.
13945 // Even if we abort and rereconcile the children, that will try to hydrate
13946 // again and the nodes are still in the host tree so these will be
13947 // recreated.
13948 if (returnFiber.lastEffect !== null) {
13949 returnFiber.lastEffect.nextEffect = childToDelete;
13950 returnFiber.lastEffect = childToDelete;
13951 } else {
13952 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
13953 }
13954}
13955
13956function insertNonHydratedInstance(returnFiber, fiber) {
13957 fiber.effectTag |= Placement;
13958 {
13959 switch (returnFiber.tag) {
13960 case HostRoot:
13961 {
13962 var parentContainer = returnFiber.stateNode.containerInfo;
13963 switch (fiber.tag) {
13964 case HostComponent:
13965 var type = fiber.type;
13966 var props = fiber.pendingProps;
13967 didNotFindHydratableContainerInstance(parentContainer, type, props);
13968 break;
13969 case HostText:
13970 var text = fiber.pendingProps;
13971 didNotFindHydratableContainerTextInstance(parentContainer, text);
13972 break;
13973 }
13974 break;
13975 }
13976 case HostComponent:
13977 {
13978 var parentType = returnFiber.type;
13979 var parentProps = returnFiber.memoizedProps;
13980 var parentInstance = returnFiber.stateNode;
13981 switch (fiber.tag) {
13982 case HostComponent:
13983 var _type = fiber.type;
13984 var _props = fiber.pendingProps;
13985 didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
13986 break;
13987 case HostText:
13988 var _text = fiber.pendingProps;
13989 didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
13990 break;
13991 }
13992 break;
13993 }
13994 default:
13995 return;
13996 }
13997 }
13998}
13999
14000function tryHydrate(fiber, nextInstance) {
14001 switch (fiber.tag) {
14002 case HostComponent:
14003 {
14004 var type = fiber.type;
14005 var props = fiber.pendingProps;
14006 var instance = canHydrateInstance(nextInstance, type, props);
14007 if (instance !== null) {
14008 fiber.stateNode = instance;
14009 return true;
14010 }
14011 return false;
14012 }
14013 case HostText:
14014 {
14015 var text = fiber.pendingProps;
14016 var textInstance = canHydrateTextInstance(nextInstance, text);
14017 if (textInstance !== null) {
14018 fiber.stateNode = textInstance;
14019 return true;
14020 }
14021 return false;
14022 }
14023 default:
14024 return false;
14025 }
14026}
14027
14028function tryToClaimNextHydratableInstance(fiber) {
14029 if (!isHydrating) {
14030 return;
14031 }
14032 var nextInstance = nextHydratableInstance;
14033 if (!nextInstance) {
14034 // Nothing to hydrate. Make it an insertion.
14035 insertNonHydratedInstance(hydrationParentFiber, fiber);
14036 isHydrating = false;
14037 hydrationParentFiber = fiber;
14038 return;
14039 }
14040 var firstAttemptedInstance = nextInstance;
14041 if (!tryHydrate(fiber, nextInstance)) {
14042 // If we can't hydrate this instance let's try the next one.
14043 // We use this as a heuristic. It's based on intuition and not data so it
14044 // might be flawed or unnecessary.
14045 nextInstance = getNextHydratableSibling(firstAttemptedInstance);
14046 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
14047 // Nothing to hydrate. Make it an insertion.
14048 insertNonHydratedInstance(hydrationParentFiber, fiber);
14049 isHydrating = false;
14050 hydrationParentFiber = fiber;
14051 return;
14052 }
14053 // We matched the next one, we'll now assume that the first one was
14054 // superfluous and we'll delete it. Since we can't eagerly delete it
14055 // we'll have to schedule a deletion. To do that, this node needs a dummy
14056 // fiber associated with it.
14057 deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
14058 }
14059 hydrationParentFiber = fiber;
14060 nextHydratableInstance = getFirstHydratableChild(nextInstance);
14061}
14062
14063function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
14064 if (!supportsHydration) {
14065 invariant(false, 'Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
14066 }
14067
14068 var instance = fiber.stateNode;
14069 var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber);
14070 // TODO: Type this specific to this type of component.
14071 fiber.updateQueue = updatePayload;
14072 // If the update payload indicates that there is a change or if there
14073 // is a new ref we mark this as an update.
14074 if (updatePayload !== null) {
14075 return true;
14076 }
14077 return false;
14078}
14079
14080function prepareToHydrateHostTextInstance(fiber) {
14081 if (!supportsHydration) {
14082 invariant(false, 'Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
14083 }
14084
14085 var textInstance = fiber.stateNode;
14086 var textContent = fiber.memoizedProps;
14087 var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
14088 {
14089 if (shouldUpdate) {
14090 // We assume that prepareToHydrateHostTextInstance is called in a context where the
14091 // hydration parent is the parent host component of this host text.
14092 var returnFiber = hydrationParentFiber;
14093 if (returnFiber !== null) {
14094 switch (returnFiber.tag) {
14095 case HostRoot:
14096 {
14097 var parentContainer = returnFiber.stateNode.containerInfo;
14098 didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
14099 break;
14100 }
14101 case HostComponent:
14102 {
14103 var parentType = returnFiber.type;
14104 var parentProps = returnFiber.memoizedProps;
14105 var parentInstance = returnFiber.stateNode;
14106 didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
14107 break;
14108 }
14109 }
14110 }
14111 }
14112 }
14113 return shouldUpdate;
14114}
14115
14116function popToNextHostParent(fiber) {
14117 var parent = fiber.return;
14118 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot) {
14119 parent = parent.return;
14120 }
14121 hydrationParentFiber = parent;
14122}
14123
14124function popHydrationState(fiber) {
14125 if (!supportsHydration) {
14126 return false;
14127 }
14128 if (fiber !== hydrationParentFiber) {
14129 // We're deeper than the current hydration context, inside an inserted
14130 // tree.
14131 return false;
14132 }
14133 if (!isHydrating) {
14134 // If we're not currently hydrating but we're in a hydration context, then
14135 // we were an insertion and now need to pop up reenter hydration of our
14136 // siblings.
14137 popToNextHostParent(fiber);
14138 isHydrating = true;
14139 return false;
14140 }
14141
14142 var type = fiber.type;
14143
14144 // If we have any remaining hydratable nodes, we need to delete them now.
14145 // We only do this deeper than head and body since they tend to have random
14146 // other nodes in them. We also ignore components with pure text content in
14147 // side of them.
14148 // TODO: Better heuristic.
14149 if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
14150 var nextInstance = nextHydratableInstance;
14151 while (nextInstance) {
14152 deleteHydratableInstance(fiber, nextInstance);
14153 nextInstance = getNextHydratableSibling(nextInstance);
14154 }
14155 }
14156
14157 popToNextHostParent(fiber);
14158 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
14159 return true;
14160}
14161
14162function resetHydrationState() {
14163 if (!supportsHydration) {
14164 return;
14165 }
14166
14167 hydrationParentFiber = null;
14168 nextHydratableInstance = null;
14169 isHydrating = false;
14170}
14171
14172var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
14173
14174var didReceiveUpdate = false;
14175
14176var didWarnAboutBadClass = void 0;
14177var didWarnAboutContextTypeOnFunctionComponent = void 0;
14178var didWarnAboutGetDerivedStateOnFunctionComponent = void 0;
14179var didWarnAboutFunctionRefs = void 0;
14180var didWarnAboutReassigningProps = void 0;
14181
14182{
14183 didWarnAboutBadClass = {};
14184 didWarnAboutContextTypeOnFunctionComponent = {};
14185 didWarnAboutGetDerivedStateOnFunctionComponent = {};
14186 didWarnAboutFunctionRefs = {};
14187 didWarnAboutReassigningProps = false;
14188}
14189
14190function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) {
14191 if (current$$1 === null) {
14192 // If this is a fresh new component that hasn't been rendered yet, we
14193 // won't update its child set by applying minimal side-effects. Instead,
14194 // we will add them all to the child before it gets rendered. That means
14195 // we can optimize this reconciliation pass by not tracking side-effects.
14196 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
14197 } else {
14198 // If the current child is the same as the work in progress, it means that
14199 // we haven't yet started any work on these children. Therefore, we use
14200 // the clone algorithm to create a copy of all the current children.
14201
14202 // If we had any progressed work already, that is invalid at this point so
14203 // let's throw it out.
14204 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime);
14205 }
14206}
14207
14208function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) {
14209 // This function is fork of reconcileChildren. It's used in cases where we
14210 // want to reconcile without matching against the existing set. This has the
14211 // effect of all current children being unmounted; even if the type and key
14212 // are the same, the old child is unmounted and a new child is created.
14213 //
14214 // To do this, we're going to go through the reconcile algorithm twice. In
14215 // the first pass, we schedule a deletion for all the current children by
14216 // passing null.
14217 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime);
14218 // In the second pass, we mount the new children. The trick here is that we
14219 // pass null in place of where we usually pass the current child set. This has
14220 // the effect of remounting all children regardless of whether their their
14221 // identity matches.
14222 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
14223}
14224
14225function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
14226 {
14227 if (workInProgress.type !== workInProgress.elementType) {
14228 // Lazy component props can't be validated in createElement
14229 // because they're only guaranteed to be resolved here.
14230 var innerPropTypes = Component.propTypes;
14231 if (innerPropTypes) {
14232 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
14233 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14234 }
14235 }
14236 }
14237
14238 var render = Component.render;
14239 var ref = workInProgress.ref;
14240
14241 // The rest is a fork of updateFunctionComponent
14242 var nextChildren = void 0;
14243 prepareToReadContext(workInProgress, renderExpirationTime);
14244 {
14245 ReactCurrentOwner$3.current = workInProgress;
14246 setCurrentPhase('render');
14247 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
14248 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14249 // Only double-render components with Hooks
14250 if (workInProgress.memoizedState !== null) {
14251 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
14252 }
14253 }
14254 setCurrentPhase(null);
14255 }
14256
14257 if (current$$1 !== null && !didReceiveUpdate) {
14258 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
14259 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14260 }
14261
14262 // React DevTools reads this flag.
14263 workInProgress.effectTag |= PerformedWork;
14264 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14265 return workInProgress.child;
14266}
14267
14268function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
14269 if (current$$1 === null) {
14270 var type = Component.type;
14271 if (isSimpleFunctionComponent(type) && Component.compare === null &&
14272 // SimpleMemoComponent codepath doesn't resolve outer props either.
14273 Component.defaultProps === undefined) {
14274 // If this is a plain function component without default props,
14275 // and with only the default shallow comparison, we upgrade it
14276 // to a SimpleMemoComponent to allow fast path updates.
14277 workInProgress.tag = SimpleMemoComponent;
14278 workInProgress.type = type;
14279 {
14280 validateFunctionComponentInDev(workInProgress, type);
14281 }
14282 return updateSimpleMemoComponent(current$$1, workInProgress, type, nextProps, updateExpirationTime, renderExpirationTime);
14283 }
14284 {
14285 var innerPropTypes = type.propTypes;
14286 if (innerPropTypes) {
14287 // Inner memo component props aren't currently validated in createElement.
14288 // We could move it there, but we'd still need this for lazy code path.
14289 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
14290 'prop', getComponentName(type), getCurrentFiberStackInDev);
14291 }
14292 }
14293 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
14294 child.ref = workInProgress.ref;
14295 child.return = workInProgress;
14296 workInProgress.child = child;
14297 return child;
14298 }
14299 {
14300 var _type = Component.type;
14301 var _innerPropTypes = _type.propTypes;
14302 if (_innerPropTypes) {
14303 // Inner memo component props aren't currently validated in createElement.
14304 // We could move it there, but we'd still need this for lazy code path.
14305 checkPropTypes_1(_innerPropTypes, nextProps, // Resolved props
14306 'prop', getComponentName(_type), getCurrentFiberStackInDev);
14307 }
14308 }
14309 var currentChild = current$$1.child; // This is always exactly one child
14310 if (updateExpirationTime < renderExpirationTime) {
14311 // This will be the props with resolved defaultProps,
14312 // unlike current.memoizedProps which will be the unresolved ones.
14313 var prevProps = currentChild.memoizedProps;
14314 // Default to shallow comparison
14315 var compare = Component.compare;
14316 compare = compare !== null ? compare : shallowEqual;
14317 if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
14318 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14319 }
14320 }
14321 // React DevTools reads this flag.
14322 workInProgress.effectTag |= PerformedWork;
14323 var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
14324 newChild.ref = workInProgress.ref;
14325 newChild.return = workInProgress;
14326 workInProgress.child = newChild;
14327 return newChild;
14328}
14329
14330function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
14331 {
14332 if (workInProgress.type !== workInProgress.elementType) {
14333 // Lazy component props can't be validated in createElement
14334 // because they're only guaranteed to be resolved here.
14335 var outerMemoType = workInProgress.elementType;
14336 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
14337 // We warn when you define propTypes on lazy()
14338 // so let's just skip over it to find memo() outer wrapper.
14339 // Inner props for memo are validated later.
14340 outerMemoType = refineResolvedLazyComponent(outerMemoType);
14341 }
14342 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
14343 if (outerPropTypes) {
14344 checkPropTypes_1(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
14345 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
14346 }
14347 // Inner propTypes will be validated in the function component path.
14348 }
14349 }
14350 if (current$$1 !== null) {
14351 var prevProps = current$$1.memoizedProps;
14352 if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
14353 didReceiveUpdate = false;
14354 if (updateExpirationTime < renderExpirationTime) {
14355 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14356 }
14357 }
14358 }
14359 return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
14360}
14361
14362function updateFragment(current$$1, workInProgress, renderExpirationTime) {
14363 var nextChildren = workInProgress.pendingProps;
14364 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14365 return workInProgress.child;
14366}
14367
14368function updateMode(current$$1, workInProgress, renderExpirationTime) {
14369 var nextChildren = workInProgress.pendingProps.children;
14370 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14371 return workInProgress.child;
14372}
14373
14374function updateProfiler(current$$1, workInProgress, renderExpirationTime) {
14375 if (enableProfilerTimer) {
14376 workInProgress.effectTag |= Update;
14377 }
14378 var nextProps = workInProgress.pendingProps;
14379 var nextChildren = nextProps.children;
14380 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14381 return workInProgress.child;
14382}
14383
14384function markRef(current$$1, workInProgress) {
14385 var ref = workInProgress.ref;
14386 if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) {
14387 // Schedule a Ref effect
14388 workInProgress.effectTag |= Ref;
14389 }
14390}
14391
14392function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
14393 {
14394 if (workInProgress.type !== workInProgress.elementType) {
14395 // Lazy component props can't be validated in createElement
14396 // because they're only guaranteed to be resolved here.
14397 var innerPropTypes = Component.propTypes;
14398 if (innerPropTypes) {
14399 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
14400 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14401 }
14402 }
14403 }
14404
14405 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
14406 var context = getMaskedContext(workInProgress, unmaskedContext);
14407
14408 var nextChildren = void 0;
14409 prepareToReadContext(workInProgress, renderExpirationTime);
14410 {
14411 ReactCurrentOwner$3.current = workInProgress;
14412 setCurrentPhase('render');
14413 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
14414 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14415 // Only double-render components with Hooks
14416 if (workInProgress.memoizedState !== null) {
14417 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
14418 }
14419 }
14420 setCurrentPhase(null);
14421 }
14422
14423 if (current$$1 !== null && !didReceiveUpdate) {
14424 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
14425 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14426 }
14427
14428 // React DevTools reads this flag.
14429 workInProgress.effectTag |= PerformedWork;
14430 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14431 return workInProgress.child;
14432}
14433
14434function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
14435 {
14436 if (workInProgress.type !== workInProgress.elementType) {
14437 // Lazy component props can't be validated in createElement
14438 // because they're only guaranteed to be resolved here.
14439 var innerPropTypes = Component.propTypes;
14440 if (innerPropTypes) {
14441 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
14442 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14443 }
14444 }
14445 }
14446
14447 // Push context providers early to prevent context stack mismatches.
14448 // During mounting we don't know the child context yet as the instance doesn't exist.
14449 // We will invalidate the child context in finishClassComponent() right after rendering.
14450 var hasContext = void 0;
14451 if (isContextProvider(Component)) {
14452 hasContext = true;
14453 pushContextProvider(workInProgress);
14454 } else {
14455 hasContext = false;
14456 }
14457 prepareToReadContext(workInProgress, renderExpirationTime);
14458
14459 var instance = workInProgress.stateNode;
14460 var shouldUpdate = void 0;
14461 if (instance === null) {
14462 if (current$$1 !== null) {
14463 // An class component without an instance only mounts if it suspended
14464 // inside a non- concurrent tree, in an inconsistent state. We want to
14465 // tree it like a new mount, even though an empty version of it already
14466 // committed. Disconnect the alternate pointers.
14467 current$$1.alternate = null;
14468 workInProgress.alternate = null;
14469 // Since this is conceptually a new fiber, schedule a Placement effect
14470 workInProgress.effectTag |= Placement;
14471 }
14472 // In the initial pass we might need to construct the instance.
14473 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14474 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14475 shouldUpdate = true;
14476 } else if (current$$1 === null) {
14477 // In a resume, we'll already have an instance we can reuse.
14478 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14479 } else {
14480 shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
14481 }
14482 var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
14483 {
14484 var inst = workInProgress.stateNode;
14485 if (inst.props !== nextProps) {
14486 !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;
14487 didWarnAboutReassigningProps = true;
14488 }
14489 }
14490 return nextUnitOfWork;
14491}
14492
14493function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
14494 // Refs should update even if shouldComponentUpdate returns false
14495 markRef(current$$1, workInProgress);
14496
14497 var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
14498
14499 if (!shouldUpdate && !didCaptureError) {
14500 // Context providers should defer to sCU for rendering
14501 if (hasContext) {
14502 invalidateContextProvider(workInProgress, Component, false);
14503 }
14504
14505 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14506 }
14507
14508 var instance = workInProgress.stateNode;
14509
14510 // Rerender
14511 ReactCurrentOwner$3.current = workInProgress;
14512 var nextChildren = void 0;
14513 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
14514 // If we captured an error, but getDerivedStateFrom catch is not defined,
14515 // unmount all the children. componentDidCatch will schedule an update to
14516 // re-render a fallback. This is temporary until we migrate everyone to
14517 // the new API.
14518 // TODO: Warn in a future release.
14519 nextChildren = null;
14520
14521 if (enableProfilerTimer) {
14522 stopProfilerTimerIfRunning(workInProgress);
14523 }
14524 } else {
14525 {
14526 setCurrentPhase('render');
14527 nextChildren = instance.render();
14528 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14529 instance.render();
14530 }
14531 setCurrentPhase(null);
14532 }
14533 }
14534
14535 // React DevTools reads this flag.
14536 workInProgress.effectTag |= PerformedWork;
14537 if (current$$1 !== null && didCaptureError) {
14538 // If we're recovering from an error, reconcile without reusing any of
14539 // the existing children. Conceptually, the normal children and the children
14540 // that are shown on error are two different sets, so we shouldn't reuse
14541 // normal children even if their identities match.
14542 forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime);
14543 } else {
14544 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14545 }
14546
14547 // Memoize state using the values we just used to render.
14548 // TODO: Restructure so we never read values from the instance.
14549 workInProgress.memoizedState = instance.state;
14550
14551 // The context might have changed so we need to recalculate it.
14552 if (hasContext) {
14553 invalidateContextProvider(workInProgress, Component, true);
14554 }
14555
14556 return workInProgress.child;
14557}
14558
14559function pushHostRootContext(workInProgress) {
14560 var root = workInProgress.stateNode;
14561 if (root.pendingContext) {
14562 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
14563 } else if (root.context) {
14564 // Should always be set
14565 pushTopLevelContextObject(workInProgress, root.context, false);
14566 }
14567 pushHostContainer(workInProgress, root.containerInfo);
14568}
14569
14570function updateHostRoot(current$$1, workInProgress, renderExpirationTime) {
14571 pushHostRootContext(workInProgress);
14572 var updateQueue = workInProgress.updateQueue;
14573 !(updateQueue !== null) ? invariant(false, '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.') : void 0;
14574 var nextProps = workInProgress.pendingProps;
14575 var prevState = workInProgress.memoizedState;
14576 var prevChildren = prevState !== null ? prevState.element : null;
14577 processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
14578 var nextState = workInProgress.memoizedState;
14579 // Caution: React DevTools currently depends on this property
14580 // being called "element".
14581 var nextChildren = nextState.element;
14582 if (nextChildren === prevChildren) {
14583 // If the state is the same as before, that's a bailout because we had
14584 // no work that expires at this time.
14585 resetHydrationState();
14586 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14587 }
14588 var root = workInProgress.stateNode;
14589 if ((current$$1 === null || current$$1.child === null) && root.hydrate && enterHydrationState(workInProgress)) {
14590 // If we don't have any current children this might be the first pass.
14591 // We always try to hydrate. If this isn't a hydration pass there won't
14592 // be any children to hydrate which is effectively the same thing as
14593 // not hydrating.
14594
14595 // This is a bit of a hack. We track the host root as a placement to
14596 // know that we're currently in a mounting state. That way isMounted
14597 // works as expected. We must reset this before committing.
14598 // TODO: Delete this when we delete isMounted and findDOMNode.
14599 workInProgress.effectTag |= Placement;
14600
14601 // Ensure that children mount into this root without tracking
14602 // side-effects. This ensures that we don't store Placement effects on
14603 // nodes that will be hydrated.
14604 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
14605 } else {
14606 // Otherwise reset hydration state in case we aborted and resumed another
14607 // root.
14608 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14609 resetHydrationState();
14610 }
14611 return workInProgress.child;
14612}
14613
14614function updateHostComponent(current$$1, workInProgress, renderExpirationTime) {
14615 pushHostContext(workInProgress);
14616
14617 if (current$$1 === null) {
14618 tryToClaimNextHydratableInstance(workInProgress);
14619 }
14620
14621 var type = workInProgress.type;
14622 var nextProps = workInProgress.pendingProps;
14623 var prevProps = current$$1 !== null ? current$$1.memoizedProps : null;
14624
14625 var nextChildren = nextProps.children;
14626 var isDirectTextChild = shouldSetTextContent(type, nextProps);
14627
14628 if (isDirectTextChild) {
14629 // We special case a direct text child of a host node. This is a common
14630 // case. We won't handle it as a reified child. We will instead handle
14631 // this in the host environment that also have access to this prop. That
14632 // avoids allocating another HostText fiber and traversing it.
14633 nextChildren = null;
14634 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
14635 // If we're switching from a direct text child to a normal child, or to
14636 // empty, we need to schedule the text content to be reset.
14637 workInProgress.effectTag |= ContentReset;
14638 }
14639
14640 markRef(current$$1, workInProgress);
14641
14642 // Check the host config to see if the children are offscreen/hidden.
14643 if (renderExpirationTime !== Never && workInProgress.mode & ConcurrentMode && shouldDeprioritizeSubtree(type, nextProps)) {
14644 // Schedule this fiber to re-render at offscreen priority. Then bailout.
14645 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
14646 return null;
14647 }
14648
14649 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14650 return workInProgress.child;
14651}
14652
14653function updateHostText(current$$1, workInProgress) {
14654 if (current$$1 === null) {
14655 tryToClaimNextHydratableInstance(workInProgress);
14656 }
14657 // Nothing to do here. This is terminal. We'll do the completion step
14658 // immediately after.
14659 return null;
14660}
14661
14662function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
14663 if (_current !== null) {
14664 // An lazy component only mounts if it suspended inside a non-
14665 // concurrent tree, in an inconsistent state. We want to treat it like
14666 // a new mount, even though an empty version of it already committed.
14667 // Disconnect the alternate pointers.
14668 _current.alternate = null;
14669 workInProgress.alternate = null;
14670 // Since this is conceptually a new fiber, schedule a Placement effect
14671 workInProgress.effectTag |= Placement;
14672 }
14673
14674 var props = workInProgress.pendingProps;
14675 // We can't start a User Timing measurement with correct label yet.
14676 // Cancel and resume right after we know the tag.
14677 cancelWorkTimer(workInProgress);
14678 var Component = readLazyComponentType(elementType);
14679 // Store the unwrapped component in the type.
14680 workInProgress.type = Component;
14681 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
14682 startWorkTimer(workInProgress);
14683 var resolvedProps = resolveDefaultProps(Component, props);
14684 var child = void 0;
14685 switch (resolvedTag) {
14686 case FunctionComponent:
14687 {
14688 {
14689 validateFunctionComponentInDev(workInProgress, Component);
14690 }
14691 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
14692 break;
14693 }
14694 case ClassComponent:
14695 {
14696 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
14697 break;
14698 }
14699 case ForwardRef:
14700 {
14701 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
14702 break;
14703 }
14704 case MemoComponent:
14705 {
14706 {
14707 if (workInProgress.type !== workInProgress.elementType) {
14708 var outerPropTypes = Component.propTypes;
14709 if (outerPropTypes) {
14710 checkPropTypes_1(outerPropTypes, resolvedProps, // Resolved for outer only
14711 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14712 }
14713 }
14714 }
14715 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
14716 updateExpirationTime, renderExpirationTime);
14717 break;
14718 }
14719 default:
14720 {
14721 var hint = '';
14722 {
14723 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
14724 hint = ' Did you wrap a component in React.lazy() more than once?';
14725 }
14726 }
14727 // This message intentionally doesn't mention ForwardRef or MemoComponent
14728 // because the fact that it's a separate type of work is an
14729 // implementation detail.
14730 invariant(false, 'Element type is invalid. Received a promise that resolves to: %s. Lazy element type must resolve to a class or function.%s', Component, hint);
14731 }
14732 }
14733 return child;
14734}
14735
14736function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
14737 if (_current !== null) {
14738 // An incomplete component only mounts if it suspended inside a non-
14739 // concurrent tree, in an inconsistent state. We want to treat it like
14740 // a new mount, even though an empty version of it already committed.
14741 // Disconnect the alternate pointers.
14742 _current.alternate = null;
14743 workInProgress.alternate = null;
14744 // Since this is conceptually a new fiber, schedule a Placement effect
14745 workInProgress.effectTag |= Placement;
14746 }
14747
14748 // Promote the fiber to a class and try rendering again.
14749 workInProgress.tag = ClassComponent;
14750
14751 // The rest of this function is a fork of `updateClassComponent`
14752
14753 // Push context providers early to prevent context stack mismatches.
14754 // During mounting we don't know the child context yet as the instance doesn't exist.
14755 // We will invalidate the child context in finishClassComponent() right after rendering.
14756 var hasContext = void 0;
14757 if (isContextProvider(Component)) {
14758 hasContext = true;
14759 pushContextProvider(workInProgress);
14760 } else {
14761 hasContext = false;
14762 }
14763 prepareToReadContext(workInProgress, renderExpirationTime);
14764
14765 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14766 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14767
14768 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
14769}
14770
14771function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
14772 if (_current !== null) {
14773 // An indeterminate component only mounts if it suspended inside a non-
14774 // concurrent tree, in an inconsistent state. We want to treat it like
14775 // a new mount, even though an empty version of it already committed.
14776 // Disconnect the alternate pointers.
14777 _current.alternate = null;
14778 workInProgress.alternate = null;
14779 // Since this is conceptually a new fiber, schedule a Placement effect
14780 workInProgress.effectTag |= Placement;
14781 }
14782
14783 var props = workInProgress.pendingProps;
14784 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
14785 var context = getMaskedContext(workInProgress, unmaskedContext);
14786
14787 prepareToReadContext(workInProgress, renderExpirationTime);
14788
14789 var value = void 0;
14790
14791 {
14792 if (Component.prototype && typeof Component.prototype.render === 'function') {
14793 var componentName = getComponentName(Component) || 'Unknown';
14794
14795 if (!didWarnAboutBadClass[componentName]) {
14796 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);
14797 didWarnAboutBadClass[componentName] = true;
14798 }
14799 }
14800
14801 if (workInProgress.mode & StrictMode) {
14802 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
14803 }
14804
14805 ReactCurrentOwner$3.current = workInProgress;
14806 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
14807 }
14808 // React DevTools reads this flag.
14809 workInProgress.effectTag |= PerformedWork;
14810
14811 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
14812 // Proceed under the assumption that this is a class instance
14813 workInProgress.tag = ClassComponent;
14814
14815 // Throw out any hooks that were used.
14816 resetHooks();
14817
14818 // Push context providers early to prevent context stack mismatches.
14819 // During mounting we don't know the child context yet as the instance doesn't exist.
14820 // We will invalidate the child context in finishClassComponent() right after rendering.
14821 var hasContext = false;
14822 if (isContextProvider(Component)) {
14823 hasContext = true;
14824 pushContextProvider(workInProgress);
14825 } else {
14826 hasContext = false;
14827 }
14828
14829 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
14830
14831 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
14832 if (typeof getDerivedStateFromProps === 'function') {
14833 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
14834 }
14835
14836 adoptClassInstance(workInProgress, value);
14837 mountClassInstance(workInProgress, Component, props, renderExpirationTime);
14838 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
14839 } else {
14840 // Proceed under the assumption that this is a function component
14841 workInProgress.tag = FunctionComponent;
14842 {
14843 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14844 // Only double-render components with Hooks
14845 if (workInProgress.memoizedState !== null) {
14846 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
14847 }
14848 }
14849 }
14850 reconcileChildren(null, workInProgress, value, renderExpirationTime);
14851 {
14852 validateFunctionComponentInDev(workInProgress, Component);
14853 }
14854 return workInProgress.child;
14855 }
14856}
14857
14858function validateFunctionComponentInDev(workInProgress, Component) {
14859 if (Component) {
14860 !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
14861 }
14862 if (workInProgress.ref !== null) {
14863 var info = '';
14864 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
14865 if (ownerName) {
14866 info += '\n\nCheck the render method of `' + ownerName + '`.';
14867 }
14868
14869 var warningKey = ownerName || workInProgress._debugID || '';
14870 var debugSource = workInProgress._debugSource;
14871 if (debugSource) {
14872 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
14873 }
14874 if (!didWarnAboutFunctionRefs[warningKey]) {
14875 didWarnAboutFunctionRefs[warningKey] = true;
14876 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);
14877 }
14878 }
14879
14880 if (typeof Component.getDerivedStateFromProps === 'function') {
14881 var componentName = getComponentName(Component) || 'Unknown';
14882
14883 if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) {
14884 warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', componentName);
14885 didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true;
14886 }
14887 }
14888
14889 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
14890 var _componentName = getComponentName(Component) || 'Unknown';
14891
14892 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName]) {
14893 warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName);
14894 didWarnAboutContextTypeOnFunctionComponent[_componentName] = true;
14895 }
14896 }
14897}
14898
14899function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
14900 var mode = workInProgress.mode;
14901 var nextProps = workInProgress.pendingProps;
14902
14903 // We should attempt to render the primary children unless this boundary
14904 // already suspended during this render (`alreadyCaptured` is true).
14905 var nextState = workInProgress.memoizedState;
14906
14907 var nextDidTimeout = void 0;
14908 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
14909 // This is the first attempt.
14910 nextState = null;
14911 nextDidTimeout = false;
14912 } else {
14913 // Something in this boundary's subtree already suspended. Switch to
14914 // rendering the fallback children.
14915 nextState = {
14916 timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork
14917 };
14918 nextDidTimeout = true;
14919 workInProgress.effectTag &= ~DidCapture;
14920 }
14921
14922 // This next part is a bit confusing. If the children timeout, we switch to
14923 // showing the fallback children in place of the "primary" children.
14924 // However, we don't want to delete the primary children because then their
14925 // state will be lost (both the React state and the host state, e.g.
14926 // uncontrolled form inputs). Instead we keep them mounted and hide them.
14927 // Both the fallback children AND the primary children are rendered at the
14928 // same time. Once the primary children are un-suspended, we can delete
14929 // the fallback children — don't need to preserve their state.
14930 //
14931 // The two sets of children are siblings in the host environment, but
14932 // semantically, for purposes of reconciliation, they are two separate sets.
14933 // So we store them using two fragment fibers.
14934 //
14935 // However, we want to avoid allocating extra fibers for every placeholder.
14936 // They're only necessary when the children time out, because that's the
14937 // only time when both sets are mounted.
14938 //
14939 // So, the extra fragment fibers are only used if the children time out.
14940 // Otherwise, we render the primary children directly. This requires some
14941 // custom reconciliation logic to preserve the state of the primary
14942 // children. It's essentially a very basic form of re-parenting.
14943
14944 // `child` points to the child fiber. In the normal case, this is the first
14945 // fiber of the primary children set. In the timed-out case, it's a
14946 // a fragment fiber containing the primary children.
14947 var child = void 0;
14948 // `next` points to the next fiber React should render. In the normal case,
14949 // it's the same as `child`: the first fiber of the primary children set.
14950 // In the timed-out case, it's a fragment fiber containing the *fallback*
14951 // children -- we skip over the primary children entirely.
14952 var next = void 0;
14953 if (current$$1 === null) {
14954 // This is the initial mount. This branch is pretty simple because there's
14955 // no previous state that needs to be preserved.
14956 if (nextDidTimeout) {
14957 // Mount separate fragments for primary and fallback children.
14958 var nextFallbackChildren = nextProps.fallback;
14959 var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
14960
14961 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
14962 // Outside of concurrent mode, we commit the effects from the
14963 var progressedState = workInProgress.memoizedState;
14964 var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
14965 primaryChildFragment.child = progressedPrimaryChild;
14966 }
14967
14968 var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
14969 primaryChildFragment.sibling = fallbackChildFragment;
14970 child = primaryChildFragment;
14971 // Skip the primary children, and continue working on the
14972 // fallback children.
14973 next = fallbackChildFragment;
14974 child.return = next.return = workInProgress;
14975 } else {
14976 // Mount the primary children without an intermediate fragment fiber.
14977 var nextPrimaryChildren = nextProps.children;
14978 child = next = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
14979 }
14980 } else {
14981 // This is an update. This branch is more complicated because we need to
14982 // ensure the state of the primary children is preserved.
14983 var prevState = current$$1.memoizedState;
14984 var prevDidTimeout = prevState !== null;
14985 if (prevDidTimeout) {
14986 // The current tree already timed out. That means each child set is
14987 var currentPrimaryChildFragment = current$$1.child;
14988 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
14989 if (nextDidTimeout) {
14990 // Still timed out. Reuse the current primary children by cloning
14991 // its fragment. We're going to skip over these entirely.
14992 var _nextFallbackChildren = nextProps.fallback;
14993 var _primaryChildFragment = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
14994
14995 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
14996 // Outside of concurrent mode, we commit the effects from the
14997 var _progressedState = workInProgress.memoizedState;
14998 var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
14999 if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
15000 _primaryChildFragment.child = _progressedPrimaryChild;
15001 }
15002 }
15003
15004 // Because primaryChildFragment is a new fiber that we're inserting as the
15005 // parent of a new tree, we need to set its treeBaseDuration.
15006 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
15007 // treeBaseDuration is the sum of all the child tree base durations.
15008 var treeBaseDuration = 0;
15009 var hiddenChild = _primaryChildFragment.child;
15010 while (hiddenChild !== null) {
15011 treeBaseDuration += hiddenChild.treeBaseDuration;
15012 hiddenChild = hiddenChild.sibling;
15013 }
15014 _primaryChildFragment.treeBaseDuration = treeBaseDuration;
15015 }
15016
15017 // Clone the fallback child fragment, too. These we'll continue
15018 // working on.
15019 var _fallbackChildFragment = _primaryChildFragment.sibling = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren, currentFallbackChildFragment.expirationTime);
15020 child = _primaryChildFragment;
15021 _primaryChildFragment.childExpirationTime = NoWork;
15022 // Skip the primary children, and continue working on the
15023 // fallback children.
15024 next = _fallbackChildFragment;
15025 child.return = next.return = workInProgress;
15026 } else {
15027 // No longer suspended. Switch back to showing the primary children,
15028 // and remove the intermediate fragment fiber.
15029 var _nextPrimaryChildren = nextProps.children;
15030 var currentPrimaryChild = currentPrimaryChildFragment.child;
15031 var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime);
15032
15033 // If this render doesn't suspend, we need to delete the fallback
15034 // children. Wait until the complete phase, after we've confirmed the
15035 // fallback is no longer needed.
15036 // TODO: Would it be better to store the fallback fragment on
15037 // the stateNode?
15038
15039 // Continue rendering the children, like we normally do.
15040 child = next = primaryChild;
15041 }
15042 } else {
15043 // The current tree has not already timed out. That means the primary
15044 // children are not wrapped in a fragment fiber.
15045 var _currentPrimaryChild = current$$1.child;
15046 if (nextDidTimeout) {
15047 // Timed out. Wrap the children in a fragment fiber to keep them
15048 // separate from the fallback children.
15049 var _nextFallbackChildren2 = nextProps.fallback;
15050 var _primaryChildFragment2 = createFiberFromFragment(
15051 // It shouldn't matter what the pending props are because we aren't
15052 // going to render this fragment.
15053 null, mode, NoWork, null);
15054 _primaryChildFragment2.child = _currentPrimaryChild;
15055
15056 // Even though we're creating a new fiber, there are no new children,
15057 // because we're reusing an already mounted tree. So we don't need to
15058 // schedule a placement.
15059 // primaryChildFragment.effectTag |= Placement;
15060
15061 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
15062 // Outside of concurrent mode, we commit the effects from the
15063 var _progressedState2 = workInProgress.memoizedState;
15064 var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
15065 _primaryChildFragment2.child = _progressedPrimaryChild2;
15066 }
15067
15068 // Because primaryChildFragment is a new fiber that we're inserting as the
15069 // parent of a new tree, we need to set its treeBaseDuration.
15070 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
15071 // treeBaseDuration is the sum of all the child tree base durations.
15072 var _treeBaseDuration = 0;
15073 var _hiddenChild = _primaryChildFragment2.child;
15074 while (_hiddenChild !== null) {
15075 _treeBaseDuration += _hiddenChild.treeBaseDuration;
15076 _hiddenChild = _hiddenChild.sibling;
15077 }
15078 _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
15079 }
15080
15081 // Create a fragment from the fallback children, too.
15082 var _fallbackChildFragment2 = _primaryChildFragment2.sibling = createFiberFromFragment(_nextFallbackChildren2, mode, renderExpirationTime, null);
15083 _fallbackChildFragment2.effectTag |= Placement;
15084 child = _primaryChildFragment2;
15085 _primaryChildFragment2.childExpirationTime = NoWork;
15086 // Skip the primary children, and continue working on the
15087 // fallback children.
15088 next = _fallbackChildFragment2;
15089 child.return = next.return = workInProgress;
15090 } else {
15091 // Still haven't timed out. Continue rendering the children, like we
15092 // normally do.
15093 var _nextPrimaryChildren2 = nextProps.children;
15094 next = child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
15095 }
15096 }
15097 workInProgress.stateNode = current$$1.stateNode;
15098 }
15099
15100 workInProgress.memoizedState = nextState;
15101 workInProgress.child = child;
15102 return next;
15103}
15104
15105function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) {
15106 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
15107 var nextChildren = workInProgress.pendingProps;
15108 if (current$$1 === null) {
15109 // Portals are special because we don't append the children during mount
15110 // but at commit. Therefore we need to track insertions which the normal
15111 // flow doesn't do during mount. This doesn't happen at the root because
15112 // the root always starts with a "current" with a null child.
15113 // TODO: Consider unifying this with how the root works.
15114 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
15115 } else {
15116 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15117 }
15118 return workInProgress.child;
15119}
15120
15121function updateContextProvider(current$$1, workInProgress, renderExpirationTime) {
15122 var providerType = workInProgress.type;
15123 var context = providerType._context;
15124
15125 var newProps = workInProgress.pendingProps;
15126 var oldProps = workInProgress.memoizedProps;
15127
15128 var newValue = newProps.value;
15129
15130 {
15131 var providerPropTypes = workInProgress.type.propTypes;
15132
15133 if (providerPropTypes) {
15134 checkPropTypes_1(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
15135 }
15136 }
15137
15138 pushProvider(workInProgress, newValue);
15139
15140 if (oldProps !== null) {
15141 var oldValue = oldProps.value;
15142 var changedBits = calculateChangedBits(context, newValue, oldValue);
15143 if (changedBits === 0) {
15144 // No change. Bailout early if children are the same.
15145 if (oldProps.children === newProps.children && !hasContextChanged()) {
15146 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15147 }
15148 } else {
15149 // The context value changed. Search for matching consumers and schedule
15150 // them to update.
15151 propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
15152 }
15153 }
15154
15155 var newChildren = newProps.children;
15156 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
15157 return workInProgress.child;
15158}
15159
15160var hasWarnedAboutUsingContextAsConsumer = false;
15161
15162function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) {
15163 var context = workInProgress.type;
15164 // The logic below for Context differs depending on PROD or DEV mode. In
15165 // DEV mode, we create a separate object for Context.Consumer that acts
15166 // like a proxy to Context. This proxy object adds unnecessary code in PROD
15167 // so we use the old behaviour (Context.Consumer references Context) to
15168 // reduce size and overhead. The separate object references context via
15169 // a property called "_context", which also gives us the ability to check
15170 // in DEV mode if this property exists or not and warn if it does not.
15171 {
15172 if (context._context === undefined) {
15173 // This may be because it's a Context (rather than a Consumer).
15174 // Or it may be because it's older React where they're the same thing.
15175 // We only want to warn if we're sure it's a new React.
15176 if (context !== context.Consumer) {
15177 if (!hasWarnedAboutUsingContextAsConsumer) {
15178 hasWarnedAboutUsingContextAsConsumer = true;
15179 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?');
15180 }
15181 }
15182 } else {
15183 context = context._context;
15184 }
15185 }
15186 var newProps = workInProgress.pendingProps;
15187 var render = newProps.children;
15188
15189 {
15190 !(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;
15191 }
15192
15193 prepareToReadContext(workInProgress, renderExpirationTime);
15194 var newValue = readContext(context, newProps.unstable_observedBits);
15195 var newChildren = void 0;
15196 {
15197 ReactCurrentOwner$3.current = workInProgress;
15198 setCurrentPhase('render');
15199 newChildren = render(newValue);
15200 setCurrentPhase(null);
15201 }
15202
15203 // React DevTools reads this flag.
15204 workInProgress.effectTag |= PerformedWork;
15205 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
15206 return workInProgress.child;
15207}
15208
15209function markWorkInProgressReceivedUpdate() {
15210 didReceiveUpdate = true;
15211}
15212
15213function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) {
15214 cancelWorkTimer(workInProgress);
15215
15216 if (current$$1 !== null) {
15217 // Reuse previous context list
15218 workInProgress.contextDependencies = current$$1.contextDependencies;
15219 }
15220
15221 if (enableProfilerTimer) {
15222 // Don't update "base" render times for bailouts.
15223 stopProfilerTimerIfRunning(workInProgress);
15224 }
15225
15226 // Check if the children have any pending work.
15227 var childExpirationTime = workInProgress.childExpirationTime;
15228 if (childExpirationTime < renderExpirationTime) {
15229 // The children don't have any work either. We can skip them.
15230 // TODO: Once we add back resuming, we should check if the children are
15231 // a work-in-progress set. If so, we need to transfer their effects.
15232 return null;
15233 } else {
15234 // This fiber doesn't have work, but its subtree does. Clone the child
15235 // fibers and continue.
15236 cloneChildFibers(current$$1, workInProgress);
15237 return workInProgress.child;
15238 }
15239}
15240
15241function beginWork(current$$1, workInProgress, renderExpirationTime) {
15242 var updateExpirationTime = workInProgress.expirationTime;
15243
15244 if (current$$1 !== null) {
15245 var oldProps = current$$1.memoizedProps;
15246 var newProps = workInProgress.pendingProps;
15247
15248 if (oldProps !== newProps || hasContextChanged()) {
15249 // If props or context changed, mark the fiber as having performed work.
15250 // This may be unset if the props are determined to be equal later (memo).
15251 didReceiveUpdate = true;
15252 } else if (updateExpirationTime < renderExpirationTime) {
15253 didReceiveUpdate = false;
15254 // This fiber does not have any pending work. Bailout without entering
15255 // the begin phase. There's still some bookkeeping we that needs to be done
15256 // in this optimized path, mostly pushing stuff onto the stack.
15257 switch (workInProgress.tag) {
15258 case HostRoot:
15259 pushHostRootContext(workInProgress);
15260 resetHydrationState();
15261 break;
15262 case HostComponent:
15263 pushHostContext(workInProgress);
15264 break;
15265 case ClassComponent:
15266 {
15267 var Component = workInProgress.type;
15268 if (isContextProvider(Component)) {
15269 pushContextProvider(workInProgress);
15270 }
15271 break;
15272 }
15273 case HostPortal:
15274 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
15275 break;
15276 case ContextProvider:
15277 {
15278 var newValue = workInProgress.memoizedProps.value;
15279 pushProvider(workInProgress, newValue);
15280 break;
15281 }
15282 case Profiler:
15283 if (enableProfilerTimer) {
15284 workInProgress.effectTag |= Update;
15285 }
15286 break;
15287 case SuspenseComponent:
15288 {
15289 var state = workInProgress.memoizedState;
15290 var didTimeout = state !== null;
15291 if (didTimeout) {
15292 // If this boundary is currently timed out, we need to decide
15293 // whether to retry the primary children, or to skip over it and
15294 // go straight to the fallback. Check the priority of the primary
15295 var primaryChildFragment = workInProgress.child;
15296 var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
15297 if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
15298 // The primary children have pending work. Use the normal path
15299 // to attempt to render the primary children again.
15300 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
15301 } else {
15302 // The primary children do not have pending work with sufficient
15303 // priority. Bailout.
15304 var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15305 if (child !== null) {
15306 // The fallback children have pending work. Skip over the
15307 // primary children and work on the fallback.
15308 return child.sibling;
15309 } else {
15310 return null;
15311 }
15312 }
15313 }
15314 break;
15315 }
15316 }
15317 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15318 }
15319 } else {
15320 didReceiveUpdate = false;
15321 }
15322
15323 // Before entering the begin phase, clear the expiration time.
15324 workInProgress.expirationTime = NoWork;
15325
15326 switch (workInProgress.tag) {
15327 case IndeterminateComponent:
15328 {
15329 var elementType = workInProgress.elementType;
15330 return mountIndeterminateComponent(current$$1, workInProgress, elementType, renderExpirationTime);
15331 }
15332 case LazyComponent:
15333 {
15334 var _elementType = workInProgress.elementType;
15335 return mountLazyComponent(current$$1, workInProgress, _elementType, updateExpirationTime, renderExpirationTime);
15336 }
15337 case FunctionComponent:
15338 {
15339 var _Component = workInProgress.type;
15340 var unresolvedProps = workInProgress.pendingProps;
15341 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
15342 return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime);
15343 }
15344 case ClassComponent:
15345 {
15346 var _Component2 = workInProgress.type;
15347 var _unresolvedProps = workInProgress.pendingProps;
15348 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
15349 return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
15350 }
15351 case HostRoot:
15352 return updateHostRoot(current$$1, workInProgress, renderExpirationTime);
15353 case HostComponent:
15354 return updateHostComponent(current$$1, workInProgress, renderExpirationTime);
15355 case HostText:
15356 return updateHostText(current$$1, workInProgress);
15357 case SuspenseComponent:
15358 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
15359 case HostPortal:
15360 return updatePortalComponent(current$$1, workInProgress, renderExpirationTime);
15361 case ForwardRef:
15362 {
15363 var type = workInProgress.type;
15364 var _unresolvedProps2 = workInProgress.pendingProps;
15365 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
15366 return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime);
15367 }
15368 case Fragment:
15369 return updateFragment(current$$1, workInProgress, renderExpirationTime);
15370 case Mode:
15371 return updateMode(current$$1, workInProgress, renderExpirationTime);
15372 case Profiler:
15373 return updateProfiler(current$$1, workInProgress, renderExpirationTime);
15374 case ContextProvider:
15375 return updateContextProvider(current$$1, workInProgress, renderExpirationTime);
15376 case ContextConsumer:
15377 return updateContextConsumer(current$$1, workInProgress, renderExpirationTime);
15378 case MemoComponent:
15379 {
15380 var _type2 = workInProgress.type;
15381 var _unresolvedProps3 = workInProgress.pendingProps;
15382 // Resolve outer props first, then resolve inner props.
15383 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
15384 {
15385 if (workInProgress.type !== workInProgress.elementType) {
15386 var outerPropTypes = _type2.propTypes;
15387 if (outerPropTypes) {
15388 checkPropTypes_1(outerPropTypes, _resolvedProps3, // Resolved for outer only
15389 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
15390 }
15391 }
15392 }
15393 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
15394 return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
15395 }
15396 case SimpleMemoComponent:
15397 {
15398 return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
15399 }
15400 case IncompleteClassComponent:
15401 {
15402 var _Component3 = workInProgress.type;
15403 var _unresolvedProps4 = workInProgress.pendingProps;
15404 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
15405 return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
15406 }
15407 default:
15408 invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
15409 }
15410}
15411
15412var valueCursor = createCursor(null);
15413
15414var rendererSigil = void 0;
15415{
15416 // Use this to detect multiple renderers using the same context
15417 rendererSigil = {};
15418}
15419
15420var currentlyRenderingFiber = null;
15421var lastContextDependency = null;
15422var lastContextWithAllBitsObserved = null;
15423
15424var isDisallowedContextReadInDEV = false;
15425
15426function resetContextDependences() {
15427 // This is called right before React yields execution, to ensure `readContext`
15428 // cannot be called outside the render phase.
15429 currentlyRenderingFiber = null;
15430 lastContextDependency = null;
15431 lastContextWithAllBitsObserved = null;
15432 {
15433 isDisallowedContextReadInDEV = false;
15434 }
15435}
15436
15437function enterDisallowedContextReadInDEV() {
15438 {
15439 isDisallowedContextReadInDEV = true;
15440 }
15441}
15442
15443function exitDisallowedContextReadInDEV() {
15444 {
15445 isDisallowedContextReadInDEV = false;
15446 }
15447}
15448
15449function pushProvider(providerFiber, nextValue) {
15450 var context = providerFiber.type._context;
15451
15452 if (isPrimaryRenderer) {
15453 push(valueCursor, context._currentValue, providerFiber);
15454
15455 context._currentValue = nextValue;
15456 {
15457 !(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;
15458 context._currentRenderer = rendererSigil;
15459 }
15460 } else {
15461 push(valueCursor, context._currentValue2, providerFiber);
15462
15463 context._currentValue2 = nextValue;
15464 {
15465 !(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;
15466 context._currentRenderer2 = rendererSigil;
15467 }
15468 }
15469}
15470
15471function popProvider(providerFiber) {
15472 var currentValue = valueCursor.current;
15473
15474 pop(valueCursor, providerFiber);
15475
15476 var context = providerFiber.type._context;
15477 if (isPrimaryRenderer) {
15478 context._currentValue = currentValue;
15479 } else {
15480 context._currentValue2 = currentValue;
15481 }
15482}
15483
15484function calculateChangedBits(context, newValue, oldValue) {
15485 if (is(oldValue, newValue)) {
15486 // No change
15487 return 0;
15488 } else {
15489 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : maxSigned31BitInt;
15490
15491 {
15492 !((changedBits & maxSigned31BitInt) === changedBits) ? warning$1(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0;
15493 }
15494 return changedBits | 0;
15495 }
15496}
15497
15498function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
15499 var fiber = workInProgress.child;
15500 if (fiber !== null) {
15501 // Set the return pointer of the child to the work-in-progress fiber.
15502 fiber.return = workInProgress;
15503 }
15504 while (fiber !== null) {
15505 var nextFiber = void 0;
15506
15507 // Visit this fiber.
15508 var list = fiber.contextDependencies;
15509 if (list !== null) {
15510 nextFiber = fiber.child;
15511
15512 var dependency = list.first;
15513 while (dependency !== null) {
15514 // Check if the context matches.
15515 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
15516 // Match! Schedule an update on this fiber.
15517
15518 if (fiber.tag === ClassComponent) {
15519 // Schedule a force update on the work-in-progress.
15520 var update = createUpdate(renderExpirationTime);
15521 update.tag = ForceUpdate;
15522 // TODO: Because we don't have a work-in-progress, this will add the
15523 // update to the current fiber, too, which means it will persist even if
15524 // this render is thrown away. Since it's a race condition, not sure it's
15525 // worth fixing.
15526 enqueueUpdate(fiber, update);
15527 }
15528
15529 if (fiber.expirationTime < renderExpirationTime) {
15530 fiber.expirationTime = renderExpirationTime;
15531 }
15532 var alternate = fiber.alternate;
15533 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
15534 alternate.expirationTime = renderExpirationTime;
15535 }
15536 // Update the child expiration time of all the ancestors, including
15537 // the alternates.
15538 var node = fiber.return;
15539 while (node !== null) {
15540 alternate = node.alternate;
15541 if (node.childExpirationTime < renderExpirationTime) {
15542 node.childExpirationTime = renderExpirationTime;
15543 if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
15544 alternate.childExpirationTime = renderExpirationTime;
15545 }
15546 } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
15547 alternate.childExpirationTime = renderExpirationTime;
15548 } else {
15549 // Neither alternate was updated, which means the rest of the
15550 // ancestor path already has sufficient priority.
15551 break;
15552 }
15553 node = node.return;
15554 }
15555
15556 // Mark the expiration time on the list, too.
15557 if (list.expirationTime < renderExpirationTime) {
15558 list.expirationTime = renderExpirationTime;
15559 }
15560
15561 // Since we already found a match, we can stop traversing the
15562 // dependency list.
15563 break;
15564 }
15565 dependency = dependency.next;
15566 }
15567 } else if (fiber.tag === ContextProvider) {
15568 // Don't scan deeper if this is a matching provider
15569 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
15570 } else {
15571 // Traverse down.
15572 nextFiber = fiber.child;
15573 }
15574
15575 if (nextFiber !== null) {
15576 // Set the return pointer of the child to the work-in-progress fiber.
15577 nextFiber.return = fiber;
15578 } else {
15579 // No child. Traverse to next sibling.
15580 nextFiber = fiber;
15581 while (nextFiber !== null) {
15582 if (nextFiber === workInProgress) {
15583 // We're back to the root of this subtree. Exit.
15584 nextFiber = null;
15585 break;
15586 }
15587 var sibling = nextFiber.sibling;
15588 if (sibling !== null) {
15589 // Set the return pointer of the sibling to the work-in-progress fiber.
15590 sibling.return = nextFiber.return;
15591 nextFiber = sibling;
15592 break;
15593 }
15594 // No more siblings. Traverse up.
15595 nextFiber = nextFiber.return;
15596 }
15597 }
15598 fiber = nextFiber;
15599 }
15600}
15601
15602function prepareToReadContext(workInProgress, renderExpirationTime) {
15603 currentlyRenderingFiber = workInProgress;
15604 lastContextDependency = null;
15605 lastContextWithAllBitsObserved = null;
15606
15607 var currentDependencies = workInProgress.contextDependencies;
15608 if (currentDependencies !== null && currentDependencies.expirationTime >= renderExpirationTime) {
15609 // Context list has a pending update. Mark that this fiber performed work.
15610 markWorkInProgressReceivedUpdate();
15611 }
15612
15613 // Reset the work-in-progress list
15614 workInProgress.contextDependencies = null;
15615}
15616
15617function readContext(context, observedBits) {
15618 {
15619 // This warning would fire if you read context inside a Hook like useMemo.
15620 // Unlike the class check below, it's not enforced in production for perf.
15621 !!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;
15622 }
15623
15624 if (lastContextWithAllBitsObserved === context) {
15625 // Nothing to do. We already observe everything in this context.
15626 } else if (observedBits === false || observedBits === 0) {
15627 // Do not observe any updates.
15628 } else {
15629 var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types.
15630 if (typeof observedBits !== 'number' || observedBits === maxSigned31BitInt) {
15631 // Observe all updates.
15632 lastContextWithAllBitsObserved = context;
15633 resolvedObservedBits = maxSigned31BitInt;
15634 } else {
15635 resolvedObservedBits = observedBits;
15636 }
15637
15638 var contextItem = {
15639 context: context,
15640 observedBits: resolvedObservedBits,
15641 next: null
15642 };
15643
15644 if (lastContextDependency === null) {
15645 !(currentlyRenderingFiber !== null) ? invariant(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;
15646
15647 // This is the first dependency for this component. Create a new list.
15648 lastContextDependency = contextItem;
15649 currentlyRenderingFiber.contextDependencies = {
15650 first: contextItem,
15651 expirationTime: NoWork
15652 };
15653 } else {
15654 // Append a new context item.
15655 lastContextDependency = lastContextDependency.next = contextItem;
15656 }
15657 }
15658 return isPrimaryRenderer ? context._currentValue : context._currentValue2;
15659}
15660
15661// UpdateQueue is a linked list of prioritized updates.
15662//
15663// Like fibers, update queues come in pairs: a current queue, which represents
15664// the visible state of the screen, and a work-in-progress queue, which can be
15665// mutated and processed asynchronously before it is committed — a form of
15666// double buffering. If a work-in-progress render is discarded before finishing,
15667// we create a new work-in-progress by cloning the current queue.
15668//
15669// Both queues share a persistent, singly-linked list structure. To schedule an
15670// update, we append it to the end of both queues. Each queue maintains a
15671// pointer to first update in the persistent list that hasn't been processed.
15672// The work-in-progress pointer always has a position equal to or greater than
15673// the current queue, since we always work on that one. The current queue's
15674// pointer is only updated during the commit phase, when we swap in the
15675// work-in-progress.
15676//
15677// For example:
15678//
15679// Current pointer: A - B - C - D - E - F
15680// Work-in-progress pointer: D - E - F
15681// ^
15682// The work-in-progress queue has
15683// processed more updates than current.
15684//
15685// The reason we append to both queues is because otherwise we might drop
15686// updates without ever processing them. For example, if we only add updates to
15687// the work-in-progress queue, some updates could be lost whenever a work-in
15688// -progress render restarts by cloning from current. Similarly, if we only add
15689// updates to the current queue, the updates will be lost whenever an already
15690// in-progress queue commits and swaps with the current queue. However, by
15691// adding to both queues, we guarantee that the update will be part of the next
15692// work-in-progress. (And because the work-in-progress queue becomes the
15693// current queue once it commits, there's no danger of applying the same
15694// update twice.)
15695//
15696// Prioritization
15697// --------------
15698//
15699// Updates are not sorted by priority, but by insertion; new updates are always
15700// appended to the end of the list.
15701//
15702// The priority is still important, though. When processing the update queue
15703// during the render phase, only the updates with sufficient priority are
15704// included in the result. If we skip an update because it has insufficient
15705// priority, it remains in the queue to be processed later, during a lower
15706// priority render. Crucially, all updates subsequent to a skipped update also
15707// remain in the queue *regardless of their priority*. That means high priority
15708// updates are sometimes processed twice, at two separate priorities. We also
15709// keep track of a base state, that represents the state before the first
15710// update in the queue is applied.
15711//
15712// For example:
15713//
15714// Given a base state of '', and the following queue of updates
15715//
15716// A1 - B2 - C1 - D2
15717//
15718// where the number indicates the priority, and the update is applied to the
15719// previous state by appending a letter, React will process these updates as
15720// two separate renders, one per distinct priority level:
15721//
15722// First render, at priority 1:
15723// Base state: ''
15724// Updates: [A1, C1]
15725// Result state: 'AC'
15726//
15727// Second render, at priority 2:
15728// Base state: 'A' <- The base state does not include C1,
15729// because B2 was skipped.
15730// Updates: [B2, C1, D2] <- C1 was rebased on top of B2
15731// Result state: 'ABCD'
15732//
15733// Because we process updates in insertion order, and rebase high priority
15734// updates when preceding updates are skipped, the final result is deterministic
15735// regardless of priority. Intermediate state may vary according to system
15736// resources, but the final state is always the same.
15737
15738var UpdateState = 0;
15739var ReplaceState = 1;
15740var ForceUpdate = 2;
15741var CaptureUpdate = 3;
15742
15743// Global state that is reset at the beginning of calling `processUpdateQueue`.
15744// It should only be read right after calling `processUpdateQueue`, via
15745// `checkHasForceUpdateAfterProcessing`.
15746var hasForceUpdate = false;
15747
15748var didWarnUpdateInsideUpdate = void 0;
15749var currentlyProcessingQueue = void 0;
15750var resetCurrentlyProcessingQueue = void 0;
15751{
15752 didWarnUpdateInsideUpdate = false;
15753 currentlyProcessingQueue = null;
15754 resetCurrentlyProcessingQueue = function () {
15755 currentlyProcessingQueue = null;
15756 };
15757}
15758
15759function createUpdateQueue(baseState) {
15760 var queue = {
15761 baseState: baseState,
15762 firstUpdate: null,
15763 lastUpdate: null,
15764 firstCapturedUpdate: null,
15765 lastCapturedUpdate: null,
15766 firstEffect: null,
15767 lastEffect: null,
15768 firstCapturedEffect: null,
15769 lastCapturedEffect: null
15770 };
15771 return queue;
15772}
15773
15774function cloneUpdateQueue(currentQueue) {
15775 var queue = {
15776 baseState: currentQueue.baseState,
15777 firstUpdate: currentQueue.firstUpdate,
15778 lastUpdate: currentQueue.lastUpdate,
15779
15780 // TODO: With resuming, if we bail out and resuse the child tree, we should
15781 // keep these effects.
15782 firstCapturedUpdate: null,
15783 lastCapturedUpdate: null,
15784
15785 firstEffect: null,
15786 lastEffect: null,
15787
15788 firstCapturedEffect: null,
15789 lastCapturedEffect: null
15790 };
15791 return queue;
15792}
15793
15794function createUpdate(expirationTime) {
15795 return {
15796 expirationTime: expirationTime,
15797
15798 tag: UpdateState,
15799 payload: null,
15800 callback: null,
15801
15802 next: null,
15803 nextEffect: null
15804 };
15805}
15806
15807function appendUpdateToQueue(queue, update) {
15808 // Append the update to the end of the list.
15809 if (queue.lastUpdate === null) {
15810 // Queue is empty
15811 queue.firstUpdate = queue.lastUpdate = update;
15812 } else {
15813 queue.lastUpdate.next = update;
15814 queue.lastUpdate = update;
15815 }
15816}
15817
15818function enqueueUpdate(fiber, update) {
15819 // Update queues are created lazily.
15820 var alternate = fiber.alternate;
15821 var queue1 = void 0;
15822 var queue2 = void 0;
15823 if (alternate === null) {
15824 // There's only one fiber.
15825 queue1 = fiber.updateQueue;
15826 queue2 = null;
15827 if (queue1 === null) {
15828 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
15829 }
15830 } else {
15831 // There are two owners.
15832 queue1 = fiber.updateQueue;
15833 queue2 = alternate.updateQueue;
15834 if (queue1 === null) {
15835 if (queue2 === null) {
15836 // Neither fiber has an update queue. Create new ones.
15837 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
15838 queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
15839 } else {
15840 // Only one fiber has an update queue. Clone to create a new one.
15841 queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
15842 }
15843 } else {
15844 if (queue2 === null) {
15845 // Only one fiber has an update queue. Clone to create a new one.
15846 queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
15847 } else {
15848 // Both owners have an update queue.
15849 }
15850 }
15851 }
15852 if (queue2 === null || queue1 === queue2) {
15853 // There's only a single queue.
15854 appendUpdateToQueue(queue1, update);
15855 } else {
15856 // There are two queues. We need to append the update to both queues,
15857 // while accounting for the persistent structure of the list — we don't
15858 // want the same update to be added multiple times.
15859 if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
15860 // One of the queues is not empty. We must add the update to both queues.
15861 appendUpdateToQueue(queue1, update);
15862 appendUpdateToQueue(queue2, update);
15863 } else {
15864 // Both queues are non-empty. The last update is the same in both lists,
15865 // because of structural sharing. So, only append to one of the lists.
15866 appendUpdateToQueue(queue1, update);
15867 // But we still need to update the `lastUpdate` pointer of queue2.
15868 queue2.lastUpdate = update;
15869 }
15870 }
15871
15872 {
15873 if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
15874 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.');
15875 didWarnUpdateInsideUpdate = true;
15876 }
15877 }
15878}
15879
15880function enqueueCapturedUpdate(workInProgress, update) {
15881 // Captured updates go into a separate list, and only on the work-in-
15882 // progress queue.
15883 var workInProgressQueue = workInProgress.updateQueue;
15884 if (workInProgressQueue === null) {
15885 workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
15886 } else {
15887 // TODO: I put this here rather than createWorkInProgress so that we don't
15888 // clone the queue unnecessarily. There's probably a better way to
15889 // structure this.
15890 workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
15891 }
15892
15893 // Append the update to the end of the list.
15894 if (workInProgressQueue.lastCapturedUpdate === null) {
15895 // This is the first render phase update
15896 workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
15897 } else {
15898 workInProgressQueue.lastCapturedUpdate.next = update;
15899 workInProgressQueue.lastCapturedUpdate = update;
15900 }
15901}
15902
15903function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
15904 var current = workInProgress.alternate;
15905 if (current !== null) {
15906 // If the work-in-progress queue is equal to the current queue,
15907 // we need to clone it first.
15908 if (queue === current.updateQueue) {
15909 queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
15910 }
15911 }
15912 return queue;
15913}
15914
15915function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
15916 switch (update.tag) {
15917 case ReplaceState:
15918 {
15919 var _payload = update.payload;
15920 if (typeof _payload === 'function') {
15921 // Updater function
15922 {
15923 enterDisallowedContextReadInDEV();
15924 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
15925 _payload.call(instance, prevState, nextProps);
15926 }
15927 }
15928 var nextState = _payload.call(instance, prevState, nextProps);
15929 {
15930 exitDisallowedContextReadInDEV();
15931 }
15932 return nextState;
15933 }
15934 // State object
15935 return _payload;
15936 }
15937 case CaptureUpdate:
15938 {
15939 workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
15940 }
15941 // Intentional fallthrough
15942 case UpdateState:
15943 {
15944 var _payload2 = update.payload;
15945 var partialState = void 0;
15946 if (typeof _payload2 === 'function') {
15947 // Updater function
15948 {
15949 enterDisallowedContextReadInDEV();
15950 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
15951 _payload2.call(instance, prevState, nextProps);
15952 }
15953 }
15954 partialState = _payload2.call(instance, prevState, nextProps);
15955 {
15956 exitDisallowedContextReadInDEV();
15957 }
15958 } else {
15959 // Partial state object
15960 partialState = _payload2;
15961 }
15962 if (partialState === null || partialState === undefined) {
15963 // Null and undefined are treated as no-ops.
15964 return prevState;
15965 }
15966 // Merge the partial state and the previous state.
15967 return _assign({}, prevState, partialState);
15968 }
15969 case ForceUpdate:
15970 {
15971 hasForceUpdate = true;
15972 return prevState;
15973 }
15974 }
15975 return prevState;
15976}
15977
15978function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
15979 hasForceUpdate = false;
15980
15981 queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
15982
15983 {
15984 currentlyProcessingQueue = queue;
15985 }
15986
15987 // These values may change as we process the queue.
15988 var newBaseState = queue.baseState;
15989 var newFirstUpdate = null;
15990 var newExpirationTime = NoWork;
15991
15992 // Iterate through the list of updates to compute the result.
15993 var update = queue.firstUpdate;
15994 var resultState = newBaseState;
15995 while (update !== null) {
15996 var updateExpirationTime = update.expirationTime;
15997 if (updateExpirationTime < renderExpirationTime) {
15998 // This update does not have sufficient priority. Skip it.
15999 if (newFirstUpdate === null) {
16000 // This is the first skipped update. It will be the first update in
16001 // the new list.
16002 newFirstUpdate = update;
16003 // Since this is the first update that was skipped, the current result
16004 // is the new base state.
16005 newBaseState = resultState;
16006 }
16007 // Since this update will remain in the list, update the remaining
16008 // expiration time.
16009 if (newExpirationTime < updateExpirationTime) {
16010 newExpirationTime = updateExpirationTime;
16011 }
16012 } else {
16013 // This update does have sufficient priority. Process it and compute
16014 // a new result.
16015 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
16016 var _callback = update.callback;
16017 if (_callback !== null) {
16018 workInProgress.effectTag |= Callback;
16019 // Set this to null, in case it was mutated during an aborted render.
16020 update.nextEffect = null;
16021 if (queue.lastEffect === null) {
16022 queue.firstEffect = queue.lastEffect = update;
16023 } else {
16024 queue.lastEffect.nextEffect = update;
16025 queue.lastEffect = update;
16026 }
16027 }
16028 }
16029 // Continue to the next update.
16030 update = update.next;
16031 }
16032
16033 // Separately, iterate though the list of captured updates.
16034 var newFirstCapturedUpdate = null;
16035 update = queue.firstCapturedUpdate;
16036 while (update !== null) {
16037 var _updateExpirationTime = update.expirationTime;
16038 if (_updateExpirationTime < renderExpirationTime) {
16039 // This update does not have sufficient priority. Skip it.
16040 if (newFirstCapturedUpdate === null) {
16041 // This is the first skipped captured update. It will be the first
16042 // update in the new list.
16043 newFirstCapturedUpdate = update;
16044 // If this is the first update that was skipped, the current result is
16045 // the new base state.
16046 if (newFirstUpdate === null) {
16047 newBaseState = resultState;
16048 }
16049 }
16050 // Since this update will remain in the list, update the remaining
16051 // expiration time.
16052 if (newExpirationTime < _updateExpirationTime) {
16053 newExpirationTime = _updateExpirationTime;
16054 }
16055 } else {
16056 // This update does have sufficient priority. Process it and compute
16057 // a new result.
16058 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
16059 var _callback2 = update.callback;
16060 if (_callback2 !== null) {
16061 workInProgress.effectTag |= Callback;
16062 // Set this to null, in case it was mutated during an aborted render.
16063 update.nextEffect = null;
16064 if (queue.lastCapturedEffect === null) {
16065 queue.firstCapturedEffect = queue.lastCapturedEffect = update;
16066 } else {
16067 queue.lastCapturedEffect.nextEffect = update;
16068 queue.lastCapturedEffect = update;
16069 }
16070 }
16071 }
16072 update = update.next;
16073 }
16074
16075 if (newFirstUpdate === null) {
16076 queue.lastUpdate = null;
16077 }
16078 if (newFirstCapturedUpdate === null) {
16079 queue.lastCapturedUpdate = null;
16080 } else {
16081 workInProgress.effectTag |= Callback;
16082 }
16083 if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
16084 // We processed every update, without skipping. That means the new base
16085 // state is the same as the result state.
16086 newBaseState = resultState;
16087 }
16088
16089 queue.baseState = newBaseState;
16090 queue.firstUpdate = newFirstUpdate;
16091 queue.firstCapturedUpdate = newFirstCapturedUpdate;
16092
16093 // Set the remaining expiration time to be whatever is remaining in the queue.
16094 // This should be fine because the only two other things that contribute to
16095 // expiration time are props and context. We're already in the middle of the
16096 // begin phase by the time we start processing the queue, so we've already
16097 // dealt with the props. Context in components that specify
16098 // shouldComponentUpdate is tricky; but we'll have to account for
16099 // that regardless.
16100 workInProgress.expirationTime = newExpirationTime;
16101 workInProgress.memoizedState = resultState;
16102
16103 {
16104 currentlyProcessingQueue = null;
16105 }
16106}
16107
16108function callCallback(callback, context) {
16109 !(typeof callback === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', callback) : void 0;
16110 callback.call(context);
16111}
16112
16113function resetHasForceUpdateBeforeProcessing() {
16114 hasForceUpdate = false;
16115}
16116
16117function checkHasForceUpdateAfterProcessing() {
16118 return hasForceUpdate;
16119}
16120
16121function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
16122 // If the finished render included captured updates, and there are still
16123 // lower priority updates left over, we need to keep the captured updates
16124 // in the queue so that they are rebased and not dropped once we process the
16125 // queue again at the lower priority.
16126 if (finishedQueue.firstCapturedUpdate !== null) {
16127 // Join the captured update list to the end of the normal list.
16128 if (finishedQueue.lastUpdate !== null) {
16129 finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
16130 finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
16131 }
16132 // Clear the list of captured updates.
16133 finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
16134 }
16135
16136 // Commit the effects
16137 commitUpdateEffects(finishedQueue.firstEffect, instance);
16138 finishedQueue.firstEffect = finishedQueue.lastEffect = null;
16139
16140 commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
16141 finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
16142}
16143
16144function commitUpdateEffects(effect, instance) {
16145 while (effect !== null) {
16146 var _callback3 = effect.callback;
16147 if (_callback3 !== null) {
16148 effect.callback = null;
16149 callCallback(_callback3, instance);
16150 }
16151 effect = effect.nextEffect;
16152 }
16153}
16154
16155function createCapturedValue(value, source) {
16156 // If the value is an error, call this function immediately after it is thrown
16157 // so the stack is accurate.
16158 return {
16159 value: value,
16160 source: source,
16161 stack: getStackByFiberInDevAndProd(source)
16162 };
16163}
16164
16165function markUpdate(workInProgress) {
16166 // Tag the fiber with an update effect. This turns a Placement into
16167 // a PlacementAndUpdate.
16168 workInProgress.effectTag |= Update;
16169}
16170
16171function markRef$1(workInProgress) {
16172 workInProgress.effectTag |= Ref;
16173}
16174
16175var appendAllChildren = void 0;
16176var updateHostContainer = void 0;
16177var updateHostComponent$1 = void 0;
16178var updateHostText$1 = void 0;
16179if (supportsMutation) {
16180 // Mutation mode
16181
16182 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
16183 // We only have the top Fiber that was created but we need recurse down its
16184 // children to find all the terminal nodes.
16185 var node = workInProgress.child;
16186 while (node !== null) {
16187 if (node.tag === HostComponent || node.tag === HostText) {
16188 appendInitialChild(parent, node.stateNode);
16189 } else if (node.tag === HostPortal) {
16190 // If we have a portal child, then we don't want to traverse
16191 // down its children. Instead, we'll get insertions from each child in
16192 // the portal directly.
16193 } else if (node.child !== null) {
16194 node.child.return = node;
16195 node = node.child;
16196 continue;
16197 }
16198 if (node === workInProgress) {
16199 return;
16200 }
16201 while (node.sibling === null) {
16202 if (node.return === null || node.return === workInProgress) {
16203 return;
16204 }
16205 node = node.return;
16206 }
16207 node.sibling.return = node.return;
16208 node = node.sibling;
16209 }
16210 };
16211
16212 updateHostContainer = function (workInProgress) {
16213 // Noop
16214 };
16215 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
16216 // If we have an alternate, that means this is an update and we need to
16217 // schedule a side-effect to do the updates.
16218 var oldProps = current.memoizedProps;
16219 if (oldProps === newProps) {
16220 // In mutation mode, this is sufficient for a bailout because
16221 // we won't touch this node even if children changed.
16222 return;
16223 }
16224
16225 // If we get updated because one of our children updated, we don't
16226 // have newProps so we'll have to reuse them.
16227 // TODO: Split the update API as separate for the props vs. children.
16228 // Even better would be if children weren't special cased at all tho.
16229 var instance = workInProgress.stateNode;
16230 var currentHostContext = getHostContext();
16231 // TODO: Experiencing an error where oldProps is null. Suggests a host
16232 // component is hitting the resume path. Figure out why. Possibly
16233 // related to `hidden`.
16234 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
16235 // TODO: Type this specific to this type of component.
16236 workInProgress.updateQueue = updatePayload;
16237 // If the update payload indicates that there is a change or if there
16238 // is a new ref we mark this as an update. All the work is done in commitWork.
16239 if (updatePayload) {
16240 markUpdate(workInProgress);
16241 }
16242 };
16243 updateHostText$1 = function (current, workInProgress, oldText, newText) {
16244 // If the text differs, mark it as an update. All the work in done in commitWork.
16245 if (oldText !== newText) {
16246 markUpdate(workInProgress);
16247 }
16248 };
16249} else if (supportsPersistence) {
16250 // Persistent host tree mode
16251
16252 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
16253 // We only have the top Fiber that was created but we need recurse down its
16254 // children to find all the terminal nodes.
16255 var node = workInProgress.child;
16256 while (node !== null) {
16257 // eslint-disable-next-line no-labels
16258 branches: if (node.tag === HostComponent) {
16259 var instance = node.stateNode;
16260 if (needsVisibilityToggle) {
16261 var props = node.memoizedProps;
16262 var type = node.type;
16263 if (isHidden) {
16264 // This child is inside a timed out tree. Hide it.
16265 instance = cloneHiddenInstance(instance, type, props, node);
16266 } else {
16267 // This child was previously inside a timed out tree. If it was not
16268 // updated during this render, it may need to be unhidden. Clone
16269 // again to be sure.
16270 instance = cloneUnhiddenInstance(instance, type, props, node);
16271 }
16272 node.stateNode = instance;
16273 }
16274 appendInitialChild(parent, instance);
16275 } else if (node.tag === HostText) {
16276 var _instance = node.stateNode;
16277 if (needsVisibilityToggle) {
16278 var text = node.memoizedProps;
16279 var rootContainerInstance = getRootHostContainer();
16280 var currentHostContext = getHostContext();
16281 if (isHidden) {
16282 _instance = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16283 } else {
16284 _instance = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16285 }
16286 node.stateNode = _instance;
16287 }
16288 appendInitialChild(parent, _instance);
16289 } else if (node.tag === HostPortal) {
16290 // If we have a portal child, then we don't want to traverse
16291 // down its children. Instead, we'll get insertions from each child in
16292 // the portal directly.
16293 } else if (node.tag === SuspenseComponent) {
16294 var current = node.alternate;
16295 if (current !== null) {
16296 var oldState = current.memoizedState;
16297 var newState = node.memoizedState;
16298 var oldIsHidden = oldState !== null;
16299 var newIsHidden = newState !== null;
16300 if (oldIsHidden !== newIsHidden) {
16301 // The placeholder either just timed out or switched back to the normal
16302 // children after having previously timed out. Toggle the visibility of
16303 // the direct host children.
16304 var primaryChildParent = newIsHidden ? node.child : node;
16305 if (primaryChildParent !== null) {
16306 appendAllChildren(parent, primaryChildParent, true, newIsHidden);
16307 }
16308 // eslint-disable-next-line no-labels
16309 break branches;
16310 }
16311 }
16312 if (node.child !== null) {
16313 // Continue traversing like normal
16314 node.child.return = node;
16315 node = node.child;
16316 continue;
16317 }
16318 } else if (node.child !== null) {
16319 node.child.return = node;
16320 node = node.child;
16321 continue;
16322 }
16323 // $FlowFixMe This is correct but Flow is confused by the labeled break.
16324 node = node;
16325 if (node === workInProgress) {
16326 return;
16327 }
16328 while (node.sibling === null) {
16329 if (node.return === null || node.return === workInProgress) {
16330 return;
16331 }
16332 node = node.return;
16333 }
16334 node.sibling.return = node.return;
16335 node = node.sibling;
16336 }
16337 };
16338
16339 // An unfortunate fork of appendAllChildren because we have two different parent types.
16340 var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
16341 // We only have the top Fiber that was created but we need recurse down its
16342 // children to find all the terminal nodes.
16343 var node = workInProgress.child;
16344 while (node !== null) {
16345 // eslint-disable-next-line no-labels
16346 branches: if (node.tag === HostComponent) {
16347 var instance = node.stateNode;
16348 if (needsVisibilityToggle) {
16349 var props = node.memoizedProps;
16350 var type = node.type;
16351 if (isHidden) {
16352 // This child is inside a timed out tree. Hide it.
16353 instance = cloneHiddenInstance(instance, type, props, node);
16354 } else {
16355 // This child was previously inside a timed out tree. If it was not
16356 // updated during this render, it may need to be unhidden. Clone
16357 // again to be sure.
16358 instance = cloneUnhiddenInstance(instance, type, props, node);
16359 }
16360 node.stateNode = instance;
16361 }
16362 appendChildToContainerChildSet(containerChildSet, instance);
16363 } else if (node.tag === HostText) {
16364 var _instance2 = node.stateNode;
16365 if (needsVisibilityToggle) {
16366 var text = node.memoizedProps;
16367 var rootContainerInstance = getRootHostContainer();
16368 var currentHostContext = getHostContext();
16369 if (isHidden) {
16370 _instance2 = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16371 } else {
16372 _instance2 = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16373 }
16374 node.stateNode = _instance2;
16375 }
16376 appendChildToContainerChildSet(containerChildSet, _instance2);
16377 } else if (node.tag === HostPortal) {
16378 // If we have a portal child, then we don't want to traverse
16379 // down its children. Instead, we'll get insertions from each child in
16380 // the portal directly.
16381 } else if (node.tag === SuspenseComponent) {
16382 var current = node.alternate;
16383 if (current !== null) {
16384 var oldState = current.memoizedState;
16385 var newState = node.memoizedState;
16386 var oldIsHidden = oldState !== null;
16387 var newIsHidden = newState !== null;
16388 if (oldIsHidden !== newIsHidden) {
16389 // The placeholder either just timed out or switched back to the normal
16390 // children after having previously timed out. Toggle the visibility of
16391 // the direct host children.
16392 var primaryChildParent = newIsHidden ? node.child : node;
16393 if (primaryChildParent !== null) {
16394 appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
16395 }
16396 // eslint-disable-next-line no-labels
16397 break branches;
16398 }
16399 }
16400 if (node.child !== null) {
16401 // Continue traversing like normal
16402 node.child.return = node;
16403 node = node.child;
16404 continue;
16405 }
16406 } else if (node.child !== null) {
16407 node.child.return = node;
16408 node = node.child;
16409 continue;
16410 }
16411 // $FlowFixMe This is correct but Flow is confused by the labeled break.
16412 node = node;
16413 if (node === workInProgress) {
16414 return;
16415 }
16416 while (node.sibling === null) {
16417 if (node.return === null || node.return === workInProgress) {
16418 return;
16419 }
16420 node = node.return;
16421 }
16422 node.sibling.return = node.return;
16423 node = node.sibling;
16424 }
16425 };
16426 updateHostContainer = function (workInProgress) {
16427 var portalOrRoot = workInProgress.stateNode;
16428 var childrenUnchanged = workInProgress.firstEffect === null;
16429 if (childrenUnchanged) {
16430 // No changes, just reuse the existing instance.
16431 } else {
16432 var container = portalOrRoot.containerInfo;
16433 var newChildSet = createContainerChildSet(container);
16434 // If children might have changed, we have to add them all to the set.
16435 appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
16436 portalOrRoot.pendingChildren = newChildSet;
16437 // Schedule an update on the container to swap out the container.
16438 markUpdate(workInProgress);
16439 finalizeContainerChildren(container, newChildSet);
16440 }
16441 };
16442 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
16443 var currentInstance = current.stateNode;
16444 var oldProps = current.memoizedProps;
16445 // If there are no effects associated with this node, then none of our children had any updates.
16446 // This guarantees that we can reuse all of them.
16447 var childrenUnchanged = workInProgress.firstEffect === null;
16448 if (childrenUnchanged && oldProps === newProps) {
16449 // No changes, just reuse the existing instance.
16450 // Note that this might release a previous clone.
16451 workInProgress.stateNode = currentInstance;
16452 return;
16453 }
16454 var recyclableInstance = workInProgress.stateNode;
16455 var currentHostContext = getHostContext();
16456 var updatePayload = null;
16457 if (oldProps !== newProps) {
16458 updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
16459 }
16460 if (childrenUnchanged && updatePayload === null) {
16461 // No changes, just reuse the existing instance.
16462 // Note that this might release a previous clone.
16463 workInProgress.stateNode = currentInstance;
16464 return;
16465 }
16466 var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
16467 if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
16468 markUpdate(workInProgress);
16469 }
16470 workInProgress.stateNode = newInstance;
16471 if (childrenUnchanged) {
16472 // If there are no other effects in this tree, we need to flag this node as having one.
16473 // Even though we're not going to use it for anything.
16474 // Otherwise parents won't know that there are new children to propagate upwards.
16475 markUpdate(workInProgress);
16476 } else {
16477 // If children might have changed, we have to add them all to the set.
16478 appendAllChildren(newInstance, workInProgress, false, false);
16479 }
16480 };
16481 updateHostText$1 = function (current, workInProgress, oldText, newText) {
16482 if (oldText !== newText) {
16483 // If the text content differs, we'll create a new text instance for it.
16484 var rootContainerInstance = getRootHostContainer();
16485 var currentHostContext = getHostContext();
16486 workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress);
16487 // We'll have to mark it as having an effect, even though we won't use the effect for anything.
16488 // This lets the parents know that at least one of their children has changed.
16489 markUpdate(workInProgress);
16490 }
16491 };
16492} else {
16493 // No host operations
16494 updateHostContainer = function (workInProgress) {
16495 // Noop
16496 };
16497 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
16498 // Noop
16499 };
16500 updateHostText$1 = function (current, workInProgress, oldText, newText) {
16501 // Noop
16502 };
16503}
16504
16505function completeWork(current, workInProgress, renderExpirationTime) {
16506 var newProps = workInProgress.pendingProps;
16507
16508 switch (workInProgress.tag) {
16509 case IndeterminateComponent:
16510 break;
16511 case LazyComponent:
16512 break;
16513 case SimpleMemoComponent:
16514 case FunctionComponent:
16515 break;
16516 case ClassComponent:
16517 {
16518 var Component = workInProgress.type;
16519 if (isContextProvider(Component)) {
16520 popContext(workInProgress);
16521 }
16522 break;
16523 }
16524 case HostRoot:
16525 {
16526 popHostContainer(workInProgress);
16527 popTopLevelContextObject(workInProgress);
16528 var fiberRoot = workInProgress.stateNode;
16529 if (fiberRoot.pendingContext) {
16530 fiberRoot.context = fiberRoot.pendingContext;
16531 fiberRoot.pendingContext = null;
16532 }
16533 if (current === null || current.child === null) {
16534 // If we hydrated, pop so that we can delete any remaining children
16535 // that weren't hydrated.
16536 popHydrationState(workInProgress);
16537 // This resets the hacky state to fix isMounted before committing.
16538 // TODO: Delete this when we delete isMounted and findDOMNode.
16539 workInProgress.effectTag &= ~Placement;
16540 }
16541 updateHostContainer(workInProgress);
16542 break;
16543 }
16544 case HostComponent:
16545 {
16546 popHostContext(workInProgress);
16547 var rootContainerInstance = getRootHostContainer();
16548 var type = workInProgress.type;
16549 if (current !== null && workInProgress.stateNode != null) {
16550 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
16551
16552 if (current.ref !== workInProgress.ref) {
16553 markRef$1(workInProgress);
16554 }
16555 } else {
16556 if (!newProps) {
16557 !(workInProgress.stateNode !== null) ? invariant(false, 'We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.') : void 0;
16558 // This can happen when we abort work.
16559 break;
16560 }
16561
16562 var currentHostContext = getHostContext();
16563 // TODO: Move createInstance to beginWork and keep it on a context
16564 // "stack" as the parent. Then append children as we go in beginWork
16565 // or completeWork depending on we want to add then top->down or
16566 // bottom->up. Top->down is faster in IE11.
16567 var wasHydrated = popHydrationState(workInProgress);
16568 if (wasHydrated) {
16569 // TODO: Move this and createInstance step into the beginPhase
16570 // to consolidate.
16571 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
16572 // If changes to the hydrated node needs to be applied at the
16573 // commit-phase we mark this as such.
16574 markUpdate(workInProgress);
16575 }
16576 } else {
16577 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
16578
16579 appendAllChildren(instance, workInProgress, false, false);
16580
16581 // Certain renderers require commit-time effects for initial mount.
16582 // (eg DOM renderer supports auto-focus for certain elements).
16583 // Make sure such renderers get scheduled for later work.
16584 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
16585 markUpdate(workInProgress);
16586 }
16587 workInProgress.stateNode = instance;
16588 }
16589
16590 if (workInProgress.ref !== null) {
16591 // If there is a ref on a host node we need to schedule a callback
16592 markRef$1(workInProgress);
16593 }
16594 }
16595 break;
16596 }
16597 case HostText:
16598 {
16599 var newText = newProps;
16600 if (current && workInProgress.stateNode != null) {
16601 var oldText = current.memoizedProps;
16602 // If we have an alternate, that means this is an update and we need
16603 // to schedule a side-effect to do the updates.
16604 updateHostText$1(current, workInProgress, oldText, newText);
16605 } else {
16606 if (typeof newText !== 'string') {
16607 !(workInProgress.stateNode !== null) ? invariant(false, 'We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.') : void 0;
16608 // This can happen when we abort work.
16609 }
16610 var _rootContainerInstance = getRootHostContainer();
16611 var _currentHostContext = getHostContext();
16612 var _wasHydrated = popHydrationState(workInProgress);
16613 if (_wasHydrated) {
16614 if (prepareToHydrateHostTextInstance(workInProgress)) {
16615 markUpdate(workInProgress);
16616 }
16617 } else {
16618 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
16619 }
16620 }
16621 break;
16622 }
16623 case ForwardRef:
16624 break;
16625 case SuspenseComponent:
16626 {
16627 var nextState = workInProgress.memoizedState;
16628 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
16629 // Something suspended. Re-render with the fallback children.
16630 workInProgress.expirationTime = renderExpirationTime;
16631 // Do not reset the effect list.
16632 return workInProgress;
16633 }
16634
16635 var nextDidTimeout = nextState !== null;
16636 var prevDidTimeout = current !== null && current.memoizedState !== null;
16637
16638 if (current !== null && !nextDidTimeout && prevDidTimeout) {
16639 // We just switched from the fallback to the normal children. Delete
16640 // the fallback.
16641 // TODO: Would it be better to store the fallback fragment on
16642 var currentFallbackChild = current.child.sibling;
16643 if (currentFallbackChild !== null) {
16644 // Deletions go at the beginning of the return fiber's effect list
16645 var first = workInProgress.firstEffect;
16646 if (first !== null) {
16647 workInProgress.firstEffect = currentFallbackChild;
16648 currentFallbackChild.nextEffect = first;
16649 } else {
16650 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
16651 currentFallbackChild.nextEffect = null;
16652 }
16653 currentFallbackChild.effectTag = Deletion;
16654 }
16655 }
16656
16657 if (nextDidTimeout || prevDidTimeout) {
16658 // If the children are hidden, or if they were previous hidden, schedule
16659 // an effect to toggle their visibility. This is also used to attach a
16660 // retry listener to the promise.
16661 workInProgress.effectTag |= Update;
16662 }
16663 break;
16664 }
16665 case Fragment:
16666 break;
16667 case Mode:
16668 break;
16669 case Profiler:
16670 break;
16671 case HostPortal:
16672 popHostContainer(workInProgress);
16673 updateHostContainer(workInProgress);
16674 break;
16675 case ContextProvider:
16676 // Pop provider fiber
16677 popProvider(workInProgress);
16678 break;
16679 case ContextConsumer:
16680 break;
16681 case MemoComponent:
16682 break;
16683 case IncompleteClassComponent:
16684 {
16685 // Same as class component case. I put it down here so that the tags are
16686 // sequential to ensure this switch is compiled to a jump table.
16687 var _Component = workInProgress.type;
16688 if (isContextProvider(_Component)) {
16689 popContext(workInProgress);
16690 }
16691 break;
16692 }
16693 default:
16694 invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
16695 }
16696
16697 return null;
16698}
16699
16700function shouldCaptureSuspense(workInProgress) {
16701 // In order to capture, the Suspense component must have a fallback prop.
16702 if (workInProgress.memoizedProps.fallback === undefined) {
16703 return false;
16704 }
16705 // If it was the primary children that just suspended, capture and render the
16706 // fallback. Otherwise, don't capture and bubble to the next boundary.
16707 var nextState = workInProgress.memoizedState;
16708 return nextState === null;
16709}
16710
16711// This module is forked in different environments.
16712// By default, return `true` to log errors to the console.
16713// Forks can return `false` if this isn't desirable.
16714function showErrorDialog(capturedError) {
16715 return true;
16716}
16717
16718function logCapturedError(capturedError) {
16719 var logError = showErrorDialog(capturedError);
16720
16721 // Allow injected showErrorDialog() to prevent default console.error logging.
16722 // This enables renderers like ReactNative to better manage redbox behavior.
16723 if (logError === false) {
16724 return;
16725 }
16726
16727 var error = capturedError.error;
16728 {
16729 var componentName = capturedError.componentName,
16730 componentStack = capturedError.componentStack,
16731 errorBoundaryName = capturedError.errorBoundaryName,
16732 errorBoundaryFound = capturedError.errorBoundaryFound,
16733 willRetry = capturedError.willRetry;
16734
16735 // Browsers support silencing uncaught errors by calling
16736 // `preventDefault()` in window `error` handler.
16737 // We record this information as an expando on the error.
16738
16739 if (error != null && error._suppressLogging) {
16740 if (errorBoundaryFound && willRetry) {
16741 // The error is recoverable and was silenced.
16742 // Ignore it and don't print the stack addendum.
16743 // This is handy for testing error boundaries without noise.
16744 return;
16745 }
16746 // The error is fatal. Since the silencing might have
16747 // been accidental, we'll surface it anyway.
16748 // However, the browser would have silenced the original error
16749 // so we'll print it first, and then print the stack addendum.
16750 console.error(error);
16751 // For a more detailed description of this block, see:
16752 // https://github.com/facebook/react/pull/13384
16753 }
16754
16755 var componentNameMessage = componentName ? 'The above error occurred in the <' + componentName + '> component:' : 'The above error occurred in one of your React components:';
16756
16757 var errorBoundaryMessage = void 0;
16758 // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
16759 if (errorBoundaryFound && errorBoundaryName) {
16760 if (willRetry) {
16761 errorBoundaryMessage = 'React will try to recreate this component tree from scratch ' + ('using the error boundary you provided, ' + errorBoundaryName + '.');
16762 } else {
16763 errorBoundaryMessage = 'This error was initially handled by the error boundary ' + errorBoundaryName + '.\n' + 'Recreating the tree from scratch failed so React will unmount the tree.';
16764 }
16765 } else {
16766 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.';
16767 }
16768 var combinedMessage = '' + componentNameMessage + componentStack + '\n\n' + ('' + errorBoundaryMessage);
16769
16770 // In development, we provide our own message with just the component stack.
16771 // We don't include the original error message and JS stack because the browser
16772 // has already printed it. Even if the application swallows the error, it is still
16773 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
16774 console.error(combinedMessage);
16775 }
16776}
16777
16778var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
16779{
16780 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
16781}
16782
16783var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
16784
16785function logError(boundary, errorInfo) {
16786 var source = errorInfo.source;
16787 var stack = errorInfo.stack;
16788 if (stack === null && source !== null) {
16789 stack = getStackByFiberInDevAndProd(source);
16790 }
16791
16792 var capturedError = {
16793 componentName: source !== null ? getComponentName(source.type) : null,
16794 componentStack: stack !== null ? stack : '',
16795 error: errorInfo.value,
16796 errorBoundary: null,
16797 errorBoundaryName: null,
16798 errorBoundaryFound: false,
16799 willRetry: false
16800 };
16801
16802 if (boundary !== null && boundary.tag === ClassComponent) {
16803 capturedError.errorBoundary = boundary.stateNode;
16804 capturedError.errorBoundaryName = getComponentName(boundary.type);
16805 capturedError.errorBoundaryFound = true;
16806 capturedError.willRetry = true;
16807 }
16808
16809 try {
16810 logCapturedError(capturedError);
16811 } catch (e) {
16812 // This method must not throw, or React internal state will get messed up.
16813 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
16814 // we want to report this error outside of the normal stack as a last resort.
16815 // https://github.com/facebook/react/issues/13188
16816 setTimeout(function () {
16817 throw e;
16818 });
16819 }
16820}
16821
16822var callComponentWillUnmountWithTimer = function (current$$1, instance) {
16823 startPhaseTimer(current$$1, 'componentWillUnmount');
16824 instance.props = current$$1.memoizedProps;
16825 instance.state = current$$1.memoizedState;
16826 instance.componentWillUnmount();
16827 stopPhaseTimer();
16828};
16829
16830// Capture errors so they don't interrupt unmounting.
16831function safelyCallComponentWillUnmount(current$$1, instance) {
16832 {
16833 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
16834 if (hasCaughtError()) {
16835 var unmountError = clearCaughtError();
16836 captureCommitPhaseError(current$$1, unmountError);
16837 }
16838 }
16839}
16840
16841function safelyDetachRef(current$$1) {
16842 var ref = current$$1.ref;
16843 if (ref !== null) {
16844 if (typeof ref === 'function') {
16845 {
16846 invokeGuardedCallback(null, ref, null, null);
16847 if (hasCaughtError()) {
16848 var refError = clearCaughtError();
16849 captureCommitPhaseError(current$$1, refError);
16850 }
16851 }
16852 } else {
16853 ref.current = null;
16854 }
16855 }
16856}
16857
16858function safelyCallDestroy(current$$1, destroy) {
16859 {
16860 invokeGuardedCallback(null, destroy, null);
16861 if (hasCaughtError()) {
16862 var error = clearCaughtError();
16863 captureCommitPhaseError(current$$1, error);
16864 }
16865 }
16866}
16867
16868function commitBeforeMutationLifeCycles(current$$1, finishedWork) {
16869 switch (finishedWork.tag) {
16870 case FunctionComponent:
16871 case ForwardRef:
16872 case SimpleMemoComponent:
16873 {
16874 commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
16875 return;
16876 }
16877 case ClassComponent:
16878 {
16879 if (finishedWork.effectTag & Snapshot) {
16880 if (current$$1 !== null) {
16881 var prevProps = current$$1.memoizedProps;
16882 var prevState = current$$1.memoizedState;
16883 startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
16884 var instance = finishedWork.stateNode;
16885 // We could update instance props and state here,
16886 // but instead we rely on them being set during last render.
16887 // TODO: revisit this when we implement resuming.
16888 {
16889 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
16890 !(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;
16891 !(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;
16892 }
16893 }
16894 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
16895 {
16896 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
16897 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
16898 didWarnSet.add(finishedWork.type);
16899 warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
16900 }
16901 }
16902 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
16903 stopPhaseTimer();
16904 }
16905 }
16906 return;
16907 }
16908 case HostRoot:
16909 case HostComponent:
16910 case HostText:
16911 case HostPortal:
16912 case IncompleteClassComponent:
16913 // Nothing to do for these component types
16914 return;
16915 default:
16916 {
16917 invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
16918 }
16919 }
16920}
16921
16922function commitHookEffectList(unmountTag, mountTag, finishedWork) {
16923 var updateQueue = finishedWork.updateQueue;
16924 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
16925 if (lastEffect !== null) {
16926 var firstEffect = lastEffect.next;
16927 var effect = firstEffect;
16928 do {
16929 if ((effect.tag & unmountTag) !== NoEffect$1) {
16930 // Unmount
16931 var destroy = effect.destroy;
16932 effect.destroy = undefined;
16933 if (destroy !== undefined) {
16934 destroy();
16935 }
16936 }
16937 if ((effect.tag & mountTag) !== NoEffect$1) {
16938 // Mount
16939 var create = effect.create;
16940 effect.destroy = create();
16941
16942 {
16943 var _destroy = effect.destroy;
16944 if (_destroy !== undefined && typeof _destroy !== 'function') {
16945 var addendum = void 0;
16946 if (_destroy === null) {
16947 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
16948 } else if (typeof _destroy.then === 'function') {
16949 addendum = '\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, you may write an async function separately ' + 'and then call it from inside the effect:\n\n' + 'async function fetchComment(commentId) {\n' + ' // You can await here\n' + '}\n\n' + 'useEffect(() => {\n' + ' fetchComment(commentId);\n' + '}, [commentId]);\n\n' + 'In the future, React will provide a more idiomatic solution for data fetching ' + "that doesn't involve writing effects manually.";
16950 } else {
16951 addendum = ' You returned: ' + _destroy;
16952 }
16953 warningWithoutStack$1(false, 'An Effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
16954 }
16955 }
16956 }
16957 effect = effect.next;
16958 } while (effect !== firstEffect);
16959 }
16960}
16961
16962function commitPassiveHookEffects(finishedWork) {
16963 commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
16964 commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
16965}
16966
16967function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) {
16968 switch (finishedWork.tag) {
16969 case FunctionComponent:
16970 case ForwardRef:
16971 case SimpleMemoComponent:
16972 {
16973 commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
16974 break;
16975 }
16976 case ClassComponent:
16977 {
16978 var instance = finishedWork.stateNode;
16979 if (finishedWork.effectTag & Update) {
16980 if (current$$1 === null) {
16981 startPhaseTimer(finishedWork, 'componentDidMount');
16982 // We could update instance props and state here,
16983 // but instead we rely on them being set during last render.
16984 // TODO: revisit this when we implement resuming.
16985 {
16986 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
16987 !(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;
16988 !(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;
16989 }
16990 }
16991 instance.componentDidMount();
16992 stopPhaseTimer();
16993 } else {
16994 var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);
16995 var prevState = current$$1.memoizedState;
16996 startPhaseTimer(finishedWork, 'componentDidUpdate');
16997 // We could update instance props and state here,
16998 // but instead we rely on them being set during last render.
16999 // TODO: revisit this when we implement resuming.
17000 {
17001 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
17002 !(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;
17003 !(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;
17004 }
17005 }
17006 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
17007 stopPhaseTimer();
17008 }
17009 }
17010 var updateQueue = finishedWork.updateQueue;
17011 if (updateQueue !== null) {
17012 {
17013 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
17014 !(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;
17015 !(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;
17016 }
17017 }
17018 // We could update instance props and state here,
17019 // but instead we rely on them being set during last render.
17020 // TODO: revisit this when we implement resuming.
17021 commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
17022 }
17023 return;
17024 }
17025 case HostRoot:
17026 {
17027 var _updateQueue = finishedWork.updateQueue;
17028 if (_updateQueue !== null) {
17029 var _instance = null;
17030 if (finishedWork.child !== null) {
17031 switch (finishedWork.child.tag) {
17032 case HostComponent:
17033 _instance = getPublicInstance(finishedWork.child.stateNode);
17034 break;
17035 case ClassComponent:
17036 _instance = finishedWork.child.stateNode;
17037 break;
17038 }
17039 }
17040 commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
17041 }
17042 return;
17043 }
17044 case HostComponent:
17045 {
17046 var _instance2 = finishedWork.stateNode;
17047
17048 // Renderers may schedule work to be done after host components are mounted
17049 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
17050 // These effects should only be committed when components are first mounted,
17051 // aka when there is no current/alternate.
17052 if (current$$1 === null && finishedWork.effectTag & Update) {
17053 var type = finishedWork.type;
17054 var props = finishedWork.memoizedProps;
17055 commitMount(_instance2, type, props, finishedWork);
17056 }
17057
17058 return;
17059 }
17060 case HostText:
17061 {
17062 // We have no life-cycles associated with text.
17063 return;
17064 }
17065 case HostPortal:
17066 {
17067 // We have no life-cycles associated with portals.
17068 return;
17069 }
17070 case Profiler:
17071 {
17072 if (enableProfilerTimer) {
17073 var onRender = finishedWork.memoizedProps.onRender;
17074
17075 if (enableSchedulerTracing) {
17076 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
17077 } else {
17078 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
17079 }
17080 }
17081 return;
17082 }
17083 case SuspenseComponent:
17084 break;
17085 case IncompleteClassComponent:
17086 break;
17087 default:
17088 {
17089 invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
17090 }
17091 }
17092}
17093
17094function hideOrUnhideAllChildren(finishedWork, isHidden) {
17095 if (supportsMutation) {
17096 // We only have the top Fiber that was inserted but we need recurse down its
17097 var node = finishedWork;
17098 while (true) {
17099 if (node.tag === HostComponent) {
17100 var instance = node.stateNode;
17101 if (isHidden) {
17102 hideInstance(instance);
17103 } else {
17104 unhideInstance(node.stateNode, node.memoizedProps);
17105 }
17106 } else if (node.tag === HostText) {
17107 var _instance3 = node.stateNode;
17108 if (isHidden) {
17109 hideTextInstance(_instance3);
17110 } else {
17111 unhideTextInstance(_instance3, node.memoizedProps);
17112 }
17113 } else if (node.tag === SuspenseComponent && node.memoizedState !== null) {
17114 // Found a nested Suspense component that timed out. Skip over the
17115 var fallbackChildFragment = node.child.sibling;
17116 fallbackChildFragment.return = node;
17117 node = fallbackChildFragment;
17118 continue;
17119 } else if (node.child !== null) {
17120 node.child.return = node;
17121 node = node.child;
17122 continue;
17123 }
17124 if (node === finishedWork) {
17125 return;
17126 }
17127 while (node.sibling === null) {
17128 if (node.return === null || node.return === finishedWork) {
17129 return;
17130 }
17131 node = node.return;
17132 }
17133 node.sibling.return = node.return;
17134 node = node.sibling;
17135 }
17136 }
17137}
17138
17139function commitAttachRef(finishedWork) {
17140 var ref = finishedWork.ref;
17141 if (ref !== null) {
17142 var instance = finishedWork.stateNode;
17143 var instanceToUse = void 0;
17144 switch (finishedWork.tag) {
17145 case HostComponent:
17146 instanceToUse = getPublicInstance(instance);
17147 break;
17148 default:
17149 instanceToUse = instance;
17150 }
17151 if (typeof ref === 'function') {
17152 ref(instanceToUse);
17153 } else {
17154 {
17155 if (!ref.hasOwnProperty('current')) {
17156 warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
17157 }
17158 }
17159
17160 ref.current = instanceToUse;
17161 }
17162 }
17163}
17164
17165function commitDetachRef(current$$1) {
17166 var currentRef = current$$1.ref;
17167 if (currentRef !== null) {
17168 if (typeof currentRef === 'function') {
17169 currentRef(null);
17170 } else {
17171 currentRef.current = null;
17172 }
17173 }
17174}
17175
17176// User-originating errors (lifecycles and refs) should not interrupt
17177// deletion, so don't let them throw. Host-originating errors should
17178// interrupt deletion, so it's okay
17179function commitUnmount(current$$1) {
17180 onCommitUnmount(current$$1);
17181
17182 switch (current$$1.tag) {
17183 case FunctionComponent:
17184 case ForwardRef:
17185 case MemoComponent:
17186 case SimpleMemoComponent:
17187 {
17188 var updateQueue = current$$1.updateQueue;
17189 if (updateQueue !== null) {
17190 var lastEffect = updateQueue.lastEffect;
17191 if (lastEffect !== null) {
17192 var firstEffect = lastEffect.next;
17193 var effect = firstEffect;
17194 do {
17195 var destroy = effect.destroy;
17196 if (destroy !== undefined) {
17197 safelyCallDestroy(current$$1, destroy);
17198 }
17199 effect = effect.next;
17200 } while (effect !== firstEffect);
17201 }
17202 }
17203 break;
17204 }
17205 case ClassComponent:
17206 {
17207 safelyDetachRef(current$$1);
17208 var instance = current$$1.stateNode;
17209 if (typeof instance.componentWillUnmount === 'function') {
17210 safelyCallComponentWillUnmount(current$$1, instance);
17211 }
17212 return;
17213 }
17214 case HostComponent:
17215 {
17216 safelyDetachRef(current$$1);
17217 return;
17218 }
17219 case HostPortal:
17220 {
17221 // TODO: this is recursive.
17222 // We are also not using this parent because
17223 // the portal will get pushed immediately.
17224 if (supportsMutation) {
17225 unmountHostComponents(current$$1);
17226 } else if (supportsPersistence) {
17227 emptyPortalContainer(current$$1);
17228 }
17229 return;
17230 }
17231 }
17232}
17233
17234function commitNestedUnmounts(root) {
17235 // While we're inside a removed host node we don't want to call
17236 // removeChild on the inner nodes because they're removed by the top
17237 // call anyway. We also want to call componentWillUnmount on all
17238 // composites before this host node is removed from the tree. Therefore
17239 var node = root;
17240 while (true) {
17241 commitUnmount(node);
17242 // Visit children because they may contain more composite or host nodes.
17243 // Skip portals because commitUnmount() currently visits them recursively.
17244 if (node.child !== null && (
17245 // If we use mutation we drill down into portals using commitUnmount above.
17246 // If we don't use mutation we drill down into portals here instead.
17247 !supportsMutation || node.tag !== HostPortal)) {
17248 node.child.return = node;
17249 node = node.child;
17250 continue;
17251 }
17252 if (node === root) {
17253 return;
17254 }
17255 while (node.sibling === null) {
17256 if (node.return === null || node.return === root) {
17257 return;
17258 }
17259 node = node.return;
17260 }
17261 node.sibling.return = node.return;
17262 node = node.sibling;
17263 }
17264}
17265
17266function detachFiber(current$$1) {
17267 // Cut off the return pointers to disconnect it from the tree. Ideally, we
17268 // should clear the child pointer of the parent alternate to let this
17269 // get GC:ed but we don't know which for sure which parent is the current
17270 // one so we'll settle for GC:ing the subtree of this child. This child
17271 // itself will be GC:ed when the parent updates the next time.
17272 current$$1.return = null;
17273 current$$1.child = null;
17274 current$$1.memoizedState = null;
17275 current$$1.updateQueue = null;
17276 var alternate = current$$1.alternate;
17277 if (alternate !== null) {
17278 alternate.return = null;
17279 alternate.child = null;
17280 alternate.memoizedState = null;
17281 alternate.updateQueue = null;
17282 }
17283}
17284
17285function emptyPortalContainer(current$$1) {
17286 if (!supportsPersistence) {
17287 return;
17288 }
17289
17290 var portal = current$$1.stateNode;
17291 var containerInfo = portal.containerInfo;
17292
17293 var emptyChildSet = createContainerChildSet(containerInfo);
17294 replaceContainerChildren(containerInfo, emptyChildSet);
17295}
17296
17297function commitContainer(finishedWork) {
17298 if (!supportsPersistence) {
17299 return;
17300 }
17301
17302 switch (finishedWork.tag) {
17303 case ClassComponent:
17304 {
17305 return;
17306 }
17307 case HostComponent:
17308 {
17309 return;
17310 }
17311 case HostText:
17312 {
17313 return;
17314 }
17315 case HostRoot:
17316 case HostPortal:
17317 {
17318 var portalOrRoot = finishedWork.stateNode;
17319 var containerInfo = portalOrRoot.containerInfo,
17320 _pendingChildren = portalOrRoot.pendingChildren;
17321
17322 replaceContainerChildren(containerInfo, _pendingChildren);
17323 return;
17324 }
17325 default:
17326 {
17327 invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
17328 }
17329 }
17330}
17331
17332function getHostParentFiber(fiber) {
17333 var parent = fiber.return;
17334 while (parent !== null) {
17335 if (isHostParent(parent)) {
17336 return parent;
17337 }
17338 parent = parent.return;
17339 }
17340 invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.');
17341}
17342
17343function isHostParent(fiber) {
17344 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
17345}
17346
17347function getHostSibling(fiber) {
17348 // We're going to search forward into the tree until we find a sibling host
17349 // node. Unfortunately, if multiple insertions are done in a row we have to
17350 // search past them. This leads to exponential search for the next sibling.
17351 var node = fiber;
17352 siblings: while (true) {
17353 // If we didn't find anything, let's try the next sibling.
17354 while (node.sibling === null) {
17355 if (node.return === null || isHostParent(node.return)) {
17356 // If we pop out of the root or hit the parent the fiber we are the
17357 // last sibling.
17358 return null;
17359 }
17360 node = node.return;
17361 }
17362 node.sibling.return = node.return;
17363 node = node.sibling;
17364 while (node.tag !== HostComponent && node.tag !== HostText) {
17365 // If it is not host node and, we might have a host node inside it.
17366 // Try to search down until we find one.
17367 if (node.effectTag & Placement) {
17368 // If we don't have a child, try the siblings instead.
17369 continue siblings;
17370 }
17371 // If we don't have a child, try the siblings instead.
17372 // We also skip portals because they are not part of this host tree.
17373 if (node.child === null || node.tag === HostPortal) {
17374 continue siblings;
17375 } else {
17376 node.child.return = node;
17377 node = node.child;
17378 }
17379 }
17380 // Check if this host node is stable or about to be placed.
17381 if (!(node.effectTag & Placement)) {
17382 // Found it!
17383 return node.stateNode;
17384 }
17385 }
17386}
17387
17388function commitPlacement(finishedWork) {
17389 if (!supportsMutation) {
17390 return;
17391 }
17392
17393 // Recursively insert all host nodes into the parent.
17394 var parentFiber = getHostParentFiber(finishedWork);
17395
17396 // Note: these two variables *must* always be updated together.
17397 var parent = void 0;
17398 var isContainer = void 0;
17399
17400 switch (parentFiber.tag) {
17401 case HostComponent:
17402 parent = parentFiber.stateNode;
17403 isContainer = false;
17404 break;
17405 case HostRoot:
17406 parent = parentFiber.stateNode.containerInfo;
17407 isContainer = true;
17408 break;
17409 case HostPortal:
17410 parent = parentFiber.stateNode.containerInfo;
17411 isContainer = true;
17412 break;
17413 default:
17414 invariant(false, 'Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.');
17415 }
17416 if (parentFiber.effectTag & ContentReset) {
17417 // Reset the text content of the parent before doing any insertions
17418 resetTextContent(parent);
17419 // Clear ContentReset from the effect tag
17420 parentFiber.effectTag &= ~ContentReset;
17421 }
17422
17423 var before = getHostSibling(finishedWork);
17424 // We only have the top Fiber that was inserted but we need recurse down its
17425 // children to find all the terminal nodes.
17426 var node = finishedWork;
17427 while (true) {
17428 if (node.tag === HostComponent || node.tag === HostText) {
17429 if (before) {
17430 if (isContainer) {
17431 insertInContainerBefore(parent, node.stateNode, before);
17432 } else {
17433 insertBefore(parent, node.stateNode, before);
17434 }
17435 } else {
17436 if (isContainer) {
17437 appendChildToContainer(parent, node.stateNode);
17438 } else {
17439 appendChild(parent, node.stateNode);
17440 }
17441 }
17442 } else if (node.tag === HostPortal) {
17443 // If the insertion itself is a portal, then we don't want to traverse
17444 // down its children. Instead, we'll get insertions from each child in
17445 // the portal directly.
17446 } else if (node.child !== null) {
17447 node.child.return = node;
17448 node = node.child;
17449 continue;
17450 }
17451 if (node === finishedWork) {
17452 return;
17453 }
17454 while (node.sibling === null) {
17455 if (node.return === null || node.return === finishedWork) {
17456 return;
17457 }
17458 node = node.return;
17459 }
17460 node.sibling.return = node.return;
17461 node = node.sibling;
17462 }
17463}
17464
17465function unmountHostComponents(current$$1) {
17466 // We only have the top Fiber that was deleted but we need recurse down its
17467 var node = current$$1;
17468
17469 // Each iteration, currentParent is populated with node's host parent if not
17470 // currentParentIsValid.
17471 var currentParentIsValid = false;
17472
17473 // Note: these two variables *must* always be updated together.
17474 var currentParent = void 0;
17475 var currentParentIsContainer = void 0;
17476
17477 while (true) {
17478 if (!currentParentIsValid) {
17479 var parent = node.return;
17480 findParent: while (true) {
17481 !(parent !== null) ? invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.') : void 0;
17482 switch (parent.tag) {
17483 case HostComponent:
17484 currentParent = parent.stateNode;
17485 currentParentIsContainer = false;
17486 break findParent;
17487 case HostRoot:
17488 currentParent = parent.stateNode.containerInfo;
17489 currentParentIsContainer = true;
17490 break findParent;
17491 case HostPortal:
17492 currentParent = parent.stateNode.containerInfo;
17493 currentParentIsContainer = true;
17494 break findParent;
17495 }
17496 parent = parent.return;
17497 }
17498 currentParentIsValid = true;
17499 }
17500
17501 if (node.tag === HostComponent || node.tag === HostText) {
17502 commitNestedUnmounts(node);
17503 // After all the children have unmounted, it is now safe to remove the
17504 // node from the tree.
17505 if (currentParentIsContainer) {
17506 removeChildFromContainer(currentParent, node.stateNode);
17507 } else {
17508 removeChild(currentParent, node.stateNode);
17509 }
17510 // Don't visit children because we already visited them.
17511 } else if (node.tag === HostPortal) {
17512 // When we go into a portal, it becomes the parent to remove from.
17513 // We will reassign it back when we pop the portal on the way up.
17514 currentParent = node.stateNode.containerInfo;
17515 currentParentIsContainer = true;
17516 // Visit children because portals might contain host components.
17517 if (node.child !== null) {
17518 node.child.return = node;
17519 node = node.child;
17520 continue;
17521 }
17522 } else {
17523 commitUnmount(node);
17524 // Visit children because we may find more host components below.
17525 if (node.child !== null) {
17526 node.child.return = node;
17527 node = node.child;
17528 continue;
17529 }
17530 }
17531 if (node === current$$1) {
17532 return;
17533 }
17534 while (node.sibling === null) {
17535 if (node.return === null || node.return === current$$1) {
17536 return;
17537 }
17538 node = node.return;
17539 if (node.tag === HostPortal) {
17540 // When we go out of the portal, we need to restore the parent.
17541 // Since we don't keep a stack of them, we will search for it.
17542 currentParentIsValid = false;
17543 }
17544 }
17545 node.sibling.return = node.return;
17546 node = node.sibling;
17547 }
17548}
17549
17550function commitDeletion(current$$1) {
17551 if (supportsMutation) {
17552 // Recursively delete all host nodes from the parent.
17553 // Detach refs and call componentWillUnmount() on the whole subtree.
17554 unmountHostComponents(current$$1);
17555 } else {
17556 // Detach refs and call componentWillUnmount() on the whole subtree.
17557 commitNestedUnmounts(current$$1);
17558 }
17559 detachFiber(current$$1);
17560}
17561
17562function commitWork(current$$1, finishedWork) {
17563 if (!supportsMutation) {
17564 switch (finishedWork.tag) {
17565 case FunctionComponent:
17566 case ForwardRef:
17567 case MemoComponent:
17568 case SimpleMemoComponent:
17569 {
17570 // Note: We currently never use MountMutation, but useLayout uses
17571 // UnmountMutation.
17572 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
17573 return;
17574 }
17575 }
17576
17577 commitContainer(finishedWork);
17578 return;
17579 }
17580
17581 switch (finishedWork.tag) {
17582 case FunctionComponent:
17583 case ForwardRef:
17584 case MemoComponent:
17585 case SimpleMemoComponent:
17586 {
17587 // Note: We currently never use MountMutation, but useLayout uses
17588 // UnmountMutation.
17589 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
17590 return;
17591 }
17592 case ClassComponent:
17593 {
17594 return;
17595 }
17596 case HostComponent:
17597 {
17598 var instance = finishedWork.stateNode;
17599 if (instance != null) {
17600 // Commit the work prepared earlier.
17601 var newProps = finishedWork.memoizedProps;
17602 // For hydration we reuse the update path but we treat the oldProps
17603 // as the newProps. The updatePayload will contain the real change in
17604 // this case.
17605 var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps;
17606 var type = finishedWork.type;
17607 // TODO: Type the updateQueue to be specific to host components.
17608 var updatePayload = finishedWork.updateQueue;
17609 finishedWork.updateQueue = null;
17610 if (updatePayload !== null) {
17611 commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
17612 }
17613 }
17614 return;
17615 }
17616 case HostText:
17617 {
17618 !(finishedWork.stateNode !== null) ? invariant(false, 'This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.') : void 0;
17619 var textInstance = finishedWork.stateNode;
17620 var newText = finishedWork.memoizedProps;
17621 // For hydration we reuse the update path but we treat the oldProps
17622 // as the newProps. The updatePayload will contain the real change in
17623 // this case.
17624 var oldText = current$$1 !== null ? current$$1.memoizedProps : newText;
17625 commitTextUpdate(textInstance, oldText, newText);
17626 return;
17627 }
17628 case HostRoot:
17629 {
17630 return;
17631 }
17632 case Profiler:
17633 {
17634 return;
17635 }
17636 case SuspenseComponent:
17637 {
17638 var newState = finishedWork.memoizedState;
17639
17640 var newDidTimeout = void 0;
17641 var primaryChildParent = finishedWork;
17642 if (newState === null) {
17643 newDidTimeout = false;
17644 } else {
17645 newDidTimeout = true;
17646 primaryChildParent = finishedWork.child;
17647 if (newState.timedOutAt === NoWork) {
17648 // If the children had not already timed out, record the time.
17649 // This is used to compute the elapsed time during subsequent
17650 // attempts to render the children.
17651 newState.timedOutAt = requestCurrentTime();
17652 }
17653 }
17654
17655 if (primaryChildParent !== null) {
17656 hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
17657 }
17658
17659 // If this boundary just timed out, then it will have a set of thenables.
17660 // For each thenable, attach a listener so that when it resolves, React
17661 // attempts to re-render the boundary in the primary (pre-timeout) state.
17662 var thenables = finishedWork.updateQueue;
17663 if (thenables !== null) {
17664 finishedWork.updateQueue = null;
17665 var retryCache = finishedWork.stateNode;
17666 if (retryCache === null) {
17667 retryCache = finishedWork.stateNode = new PossiblyWeakSet();
17668 }
17669 thenables.forEach(function (thenable) {
17670 // Memoize using the boundary fiber to prevent redundant listeners.
17671 var retry = retryTimedOutBoundary.bind(null, finishedWork, thenable);
17672 if (enableSchedulerTracing) {
17673 retry = unstable_wrap(retry);
17674 }
17675 if (!retryCache.has(thenable)) {
17676 retryCache.add(thenable);
17677 thenable.then(retry, retry);
17678 }
17679 });
17680 }
17681
17682 return;
17683 }
17684 case IncompleteClassComponent:
17685 {
17686 return;
17687 }
17688 default:
17689 {
17690 invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
17691 }
17692 }
17693}
17694
17695function commitResetTextContent(current$$1) {
17696 if (!supportsMutation) {
17697 return;
17698 }
17699 resetTextContent(current$$1.stateNode);
17700}
17701
17702var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
17703
17704function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
17705 var update = createUpdate(expirationTime);
17706 // Unmount the root by rendering null.
17707 update.tag = CaptureUpdate;
17708 // Caution: React DevTools currently depends on this property
17709 // being called "element".
17710 update.payload = { element: null };
17711 var error = errorInfo.value;
17712 update.callback = function () {
17713 onUncaughtError(error);
17714 logError(fiber, errorInfo);
17715 };
17716 return update;
17717}
17718
17719function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
17720 var update = createUpdate(expirationTime);
17721 update.tag = CaptureUpdate;
17722 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
17723 if (typeof getDerivedStateFromError === 'function') {
17724 var error = errorInfo.value;
17725 update.payload = function () {
17726 return getDerivedStateFromError(error);
17727 };
17728 }
17729
17730 var inst = fiber.stateNode;
17731 if (inst !== null && typeof inst.componentDidCatch === 'function') {
17732 update.callback = function callback() {
17733 if (typeof getDerivedStateFromError !== 'function') {
17734 // To preserve the preexisting retry behavior of error boundaries,
17735 // we keep track of which ones already failed during this batch.
17736 // This gets reset before we yield back to the browser.
17737 // TODO: Warn in strict mode if getDerivedStateFromError is
17738 // not defined.
17739 markLegacyErrorBoundaryAsFailed(this);
17740 }
17741 var error = errorInfo.value;
17742 var stack = errorInfo.stack;
17743 logError(fiber, errorInfo);
17744 this.componentDidCatch(error, {
17745 componentStack: stack !== null ? stack : ''
17746 });
17747 {
17748 if (typeof getDerivedStateFromError !== 'function') {
17749 // If componentDidCatch is the only error boundary method defined,
17750 // then it needs to call setState to recover from errors.
17751 // If no state update is scheduled then the boundary will swallow the error.
17752 !(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;
17753 }
17754 }
17755 };
17756 }
17757 return update;
17758}
17759
17760function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
17761 // The source fiber did not complete.
17762 sourceFiber.effectTag |= Incomplete;
17763 // Its effect list is no longer valid.
17764 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
17765
17766 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
17767 // This is a thenable.
17768 var thenable = value;
17769
17770 // Find the earliest timeout threshold of all the placeholders in the
17771 // ancestor path. We could avoid this traversal by storing the thresholds on
17772 // the stack, but we choose not to because we only hit this path if we're
17773 // IO-bound (i.e. if something suspends). Whereas the stack is used even in
17774 // the non-IO- bound case.
17775 var _workInProgress = returnFiber;
17776 var earliestTimeoutMs = -1;
17777 var startTimeMs = -1;
17778 do {
17779 if (_workInProgress.tag === SuspenseComponent) {
17780 var current$$1 = _workInProgress.alternate;
17781 if (current$$1 !== null) {
17782 var currentState = current$$1.memoizedState;
17783 if (currentState !== null) {
17784 // Reached a boundary that already timed out. Do not search
17785 // any further.
17786 var timedOutAt = currentState.timedOutAt;
17787 startTimeMs = expirationTimeToMs(timedOutAt);
17788 // Do not search any further.
17789 break;
17790 }
17791 }
17792 var timeoutPropMs = _workInProgress.pendingProps.maxDuration;
17793 if (typeof timeoutPropMs === 'number') {
17794 if (timeoutPropMs <= 0) {
17795 earliestTimeoutMs = 0;
17796 } else if (earliestTimeoutMs === -1 || timeoutPropMs < earliestTimeoutMs) {
17797 earliestTimeoutMs = timeoutPropMs;
17798 }
17799 }
17800 }
17801 _workInProgress = _workInProgress.return;
17802 } while (_workInProgress !== null);
17803
17804 // Schedule the nearest Suspense to re-render the timed out view.
17805 _workInProgress = returnFiber;
17806 do {
17807 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress)) {
17808 // Found the nearest boundary.
17809
17810 // Stash the promise on the boundary fiber. If the boundary times out, we'll
17811 var thenables = _workInProgress.updateQueue;
17812 if (thenables === null) {
17813 var updateQueue = new Set();
17814 updateQueue.add(thenable);
17815 _workInProgress.updateQueue = updateQueue;
17816 } else {
17817 thenables.add(thenable);
17818 }
17819
17820 // If the boundary is outside of concurrent mode, we should *not*
17821 // suspend the commit. Pretend as if the suspended component rendered
17822 // null and keep rendering. In the commit phase, we'll schedule a
17823 // subsequent synchronous update to re-render the Suspense.
17824 //
17825 // Note: It doesn't matter whether the component that suspended was
17826 // inside a concurrent mode tree. If the Suspense is outside of it, we
17827 // should *not* suspend the commit.
17828 if ((_workInProgress.mode & ConcurrentMode) === NoEffect) {
17829 _workInProgress.effectTag |= DidCapture;
17830
17831 // We're going to commit this fiber even though it didn't complete.
17832 // But we shouldn't call any lifecycle methods or callbacks. Remove
17833 // all lifecycle effect tags.
17834 sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
17835
17836 if (sourceFiber.tag === ClassComponent) {
17837 var currentSourceFiber = sourceFiber.alternate;
17838 if (currentSourceFiber === null) {
17839 // This is a new mount. Change the tag so it's not mistaken for a
17840 // completed class component. For example, we should not call
17841 // componentWillUnmount if it is deleted.
17842 sourceFiber.tag = IncompleteClassComponent;
17843 } else {
17844 // When we try rendering again, we should not reuse the current fiber,
17845 // since it's known to be in an inconsistent state. Use a force updte to
17846 // prevent a bail out.
17847 var update = createUpdate(Sync);
17848 update.tag = ForceUpdate;
17849 enqueueUpdate(sourceFiber, update);
17850 }
17851 }
17852
17853 // The source fiber did not complete. Mark it with Sync priority to
17854 // indicate that it still has pending work.
17855 sourceFiber.expirationTime = Sync;
17856
17857 // Exit without suspending.
17858 return;
17859 }
17860
17861 // Confirmed that the boundary is in a concurrent mode tree. Continue
17862 // with the normal suspend path.
17863
17864 // Attach a listener to the promise to "ping" the root and retry. But
17865 // only if one does not already exist for the current render expiration
17866 // time (which acts like a "thread ID" here).
17867 var pingCache = root.pingCache;
17868 var threadIDs = void 0;
17869 if (pingCache === null) {
17870 pingCache = root.pingCache = new PossiblyWeakMap();
17871 threadIDs = new Set();
17872 pingCache.set(thenable, threadIDs);
17873 } else {
17874 threadIDs = pingCache.get(thenable);
17875 if (threadIDs === undefined) {
17876 threadIDs = new Set();
17877 pingCache.set(thenable, threadIDs);
17878 }
17879 }
17880 if (!threadIDs.has(renderExpirationTime)) {
17881 // Memoize using the thread ID to prevent redundant listeners.
17882 threadIDs.add(renderExpirationTime);
17883 var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);
17884 if (enableSchedulerTracing) {
17885 ping = unstable_wrap(ping);
17886 }
17887 thenable.then(ping, ping);
17888 }
17889
17890 var absoluteTimeoutMs = void 0;
17891 if (earliestTimeoutMs === -1) {
17892 // If no explicit threshold is given, default to an arbitrarily large
17893 // value. The actual size doesn't matter because the threshold for the
17894 // whole tree will be clamped to the expiration time.
17895 absoluteTimeoutMs = maxSigned31BitInt;
17896 } else {
17897 if (startTimeMs === -1) {
17898 // This suspend happened outside of any already timed-out
17899 // placeholders. We don't know exactly when the update was
17900 // scheduled, but we can infer an approximate start time from the
17901 // expiration time. First, find the earliest uncommitted expiration
17902 // time in the tree, including work that is suspended. Then subtract
17903 // the offset used to compute an async update's expiration time.
17904 // This will cause high priority (interactive) work to expire
17905 // earlier than necessary, but we can account for this by adjusting
17906 // for the Just Noticeable Difference.
17907 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, renderExpirationTime);
17908 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
17909 startTimeMs = earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
17910 }
17911 absoluteTimeoutMs = startTimeMs + earliestTimeoutMs;
17912 }
17913
17914 // Mark the earliest timeout in the suspended fiber's ancestor path.
17915 // After completing the root, we'll take the largest of all the
17916 // suspended fiber's timeouts and use it to compute a timeout for the
17917 // whole tree.
17918 renderDidSuspend(root, absoluteTimeoutMs, renderExpirationTime);
17919
17920 _workInProgress.effectTag |= ShouldCapture;
17921 _workInProgress.expirationTime = renderExpirationTime;
17922 return;
17923 }
17924 // This boundary already captured during this render. Continue to the next
17925 // boundary.
17926 _workInProgress = _workInProgress.return;
17927 } while (_workInProgress !== null);
17928 // No boundary was found. Fallthrough to error mode.
17929 // TODO: Use invariant so the message is stripped in prod?
17930 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));
17931 }
17932
17933 // We didn't find a boundary that could handle this type of exception. Start
17934 // over and traverse parent path again, this time treating the exception
17935 // as an error.
17936 renderDidError();
17937 value = createCapturedValue(value, sourceFiber);
17938 var workInProgress = returnFiber;
17939 do {
17940 switch (workInProgress.tag) {
17941 case HostRoot:
17942 {
17943 var _errorInfo = value;
17944 workInProgress.effectTag |= ShouldCapture;
17945 workInProgress.expirationTime = renderExpirationTime;
17946 var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
17947 enqueueCapturedUpdate(workInProgress, _update);
17948 return;
17949 }
17950 case ClassComponent:
17951 // Capture and retry
17952 var errorInfo = value;
17953 var ctor = workInProgress.type;
17954 var instance = workInProgress.stateNode;
17955 if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
17956 workInProgress.effectTag |= ShouldCapture;
17957 workInProgress.expirationTime = renderExpirationTime;
17958 // Schedule the error boundary to re-render using updated state
17959 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
17960 enqueueCapturedUpdate(workInProgress, _update2);
17961 return;
17962 }
17963 break;
17964 default:
17965 break;
17966 }
17967 workInProgress = workInProgress.return;
17968 } while (workInProgress !== null);
17969}
17970
17971function unwindWork(workInProgress, renderExpirationTime) {
17972 switch (workInProgress.tag) {
17973 case ClassComponent:
17974 {
17975 var Component = workInProgress.type;
17976 if (isContextProvider(Component)) {
17977 popContext(workInProgress);
17978 }
17979 var effectTag = workInProgress.effectTag;
17980 if (effectTag & ShouldCapture) {
17981 workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
17982 return workInProgress;
17983 }
17984 return null;
17985 }
17986 case HostRoot:
17987 {
17988 popHostContainer(workInProgress);
17989 popTopLevelContextObject(workInProgress);
17990 var _effectTag = workInProgress.effectTag;
17991 !((_effectTag & DidCapture) === NoEffect) ? invariant(false, 'The root failed to unmount after an error. This is likely a bug in React. Please file an issue.') : void 0;
17992 workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
17993 return workInProgress;
17994 }
17995 case HostComponent:
17996 {
17997 popHostContext(workInProgress);
17998 return null;
17999 }
18000 case SuspenseComponent:
18001 {
18002 var _effectTag2 = workInProgress.effectTag;
18003 if (_effectTag2 & ShouldCapture) {
18004 workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture;
18005 // Captured a suspense effect. Re-render the boundary.
18006 return workInProgress;
18007 }
18008 return null;
18009 }
18010 case HostPortal:
18011 popHostContainer(workInProgress);
18012 return null;
18013 case ContextProvider:
18014 popProvider(workInProgress);
18015 return null;
18016 default:
18017 return null;
18018 }
18019}
18020
18021function unwindInterruptedWork(interruptedWork) {
18022 switch (interruptedWork.tag) {
18023 case ClassComponent:
18024 {
18025 var childContextTypes = interruptedWork.type.childContextTypes;
18026 if (childContextTypes !== null && childContextTypes !== undefined) {
18027 popContext(interruptedWork);
18028 }
18029 break;
18030 }
18031 case HostRoot:
18032 {
18033 popHostContainer(interruptedWork);
18034 popTopLevelContextObject(interruptedWork);
18035 break;
18036 }
18037 case HostComponent:
18038 {
18039 popHostContext(interruptedWork);
18040 break;
18041 }
18042 case HostPortal:
18043 popHostContainer(interruptedWork);
18044 break;
18045 case ContextProvider:
18046 popProvider(interruptedWork);
18047 break;
18048 default:
18049 break;
18050 }
18051}
18052
18053var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
18054var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
18055
18056
18057var didWarnAboutStateTransition = void 0;
18058var didWarnSetStateChildContext = void 0;
18059var warnAboutUpdateOnUnmounted = void 0;
18060var warnAboutInvalidUpdates = void 0;
18061
18062if (enableSchedulerTracing) {
18063 // Provide explicit error message when production+profiling bundle of e.g. react-dom
18064 // is used with production (non-profiling) bundle of scheduler/tracing
18065 !(__interactionsRef != null && __interactionsRef.current != null) ? invariant(false, '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') : void 0;
18066}
18067
18068{
18069 didWarnAboutStateTransition = false;
18070 didWarnSetStateChildContext = false;
18071 var didWarnStateUpdateForUnmountedComponent = {};
18072
18073 warnAboutUpdateOnUnmounted = function (fiber, isClass) {
18074 // We show the whole stack but dedupe on the top component's name because
18075 // the problematic code almost always lies inside that component.
18076 var componentName = getComponentName(fiber.type) || 'ReactComponent';
18077 if (didWarnStateUpdateForUnmountedComponent[componentName]) {
18078 return;
18079 }
18080 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', isClass ? 'the componentWillUnmount method' : 'a useEffect cleanup function', getStackByFiberInDevAndProd(fiber));
18081 didWarnStateUpdateForUnmountedComponent[componentName] = true;
18082 };
18083
18084 warnAboutInvalidUpdates = function (instance) {
18085 switch (phase) {
18086 case 'getChildContext':
18087 if (didWarnSetStateChildContext) {
18088 return;
18089 }
18090 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
18091 didWarnSetStateChildContext = true;
18092 break;
18093 case 'render':
18094 if (didWarnAboutStateTransition) {
18095 return;
18096 }
18097 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.');
18098 didWarnAboutStateTransition = true;
18099 break;
18100 }
18101 };
18102}
18103
18104// Used to ensure computeUniqueAsyncExpiration is monotonically decreasing.
18105var lastUniqueAsyncExpiration = Sync - 1;
18106
18107// Represents the expiration time that incoming updates should use. (If this
18108// is NoWork, use the default strategy: async updates in async mode, sync
18109// updates in sync mode.)
18110var expirationContext = NoWork;
18111
18112var isWorking = false;
18113
18114// The next work in progress fiber that we're currently working on.
18115var nextUnitOfWork = null;
18116var nextRoot = null;
18117// The time at which we're currently rendering work.
18118var nextRenderExpirationTime = NoWork;
18119var nextLatestAbsoluteTimeoutMs = -1;
18120var nextRenderDidError = false;
18121
18122// The next fiber with an effect that we're currently committing.
18123var nextEffect = null;
18124
18125var isCommitting$1 = false;
18126var rootWithPendingPassiveEffects = null;
18127var passiveEffectCallbackHandle = null;
18128var passiveEffectCallback = null;
18129
18130var legacyErrorBoundariesThatAlreadyFailed = null;
18131
18132// Used for performance tracking.
18133var interruptedBy = null;
18134
18135var stashedWorkInProgressProperties = void 0;
18136var replayUnitOfWork = void 0;
18137var mayReplayFailedUnitOfWork = void 0;
18138var isReplayingFailedUnitOfWork = void 0;
18139var originalReplayError = void 0;
18140var rethrowOriginalError = void 0;
18141if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
18142 stashedWorkInProgressProperties = null;
18143 mayReplayFailedUnitOfWork = true;
18144 isReplayingFailedUnitOfWork = false;
18145 originalReplayError = null;
18146 replayUnitOfWork = function (failedUnitOfWork, thrownValue, isYieldy) {
18147 if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
18148 // Don't replay promises. Treat everything else like an error.
18149 // TODO: Need to figure out a different strategy if/when we add
18150 // support for catching other types.
18151 return;
18152 }
18153
18154 // Restore the original state of the work-in-progress
18155 if (stashedWorkInProgressProperties === null) {
18156 // This should never happen. Don't throw because this code is DEV-only.
18157 warningWithoutStack$1(false, 'Could not replay rendering after an error. This is likely a bug in React. ' + 'Please file an issue.');
18158 return;
18159 }
18160 assignFiberPropertiesInDEV(failedUnitOfWork, stashedWorkInProgressProperties);
18161
18162 switch (failedUnitOfWork.tag) {
18163 case HostRoot:
18164 popHostContainer(failedUnitOfWork);
18165 popTopLevelContextObject(failedUnitOfWork);
18166 break;
18167 case HostComponent:
18168 popHostContext(failedUnitOfWork);
18169 break;
18170 case ClassComponent:
18171 {
18172 var Component = failedUnitOfWork.type;
18173 if (isContextProvider(Component)) {
18174 popContext(failedUnitOfWork);
18175 }
18176 break;
18177 }
18178 case HostPortal:
18179 popHostContainer(failedUnitOfWork);
18180 break;
18181 case ContextProvider:
18182 popProvider(failedUnitOfWork);
18183 break;
18184 }
18185 // Replay the begin phase.
18186 isReplayingFailedUnitOfWork = true;
18187 originalReplayError = thrownValue;
18188 invokeGuardedCallback(null, workLoop, null, isYieldy);
18189 isReplayingFailedUnitOfWork = false;
18190 originalReplayError = null;
18191 if (hasCaughtError()) {
18192 var replayError = clearCaughtError();
18193 if (replayError != null && thrownValue != null) {
18194 try {
18195 // Reading the expando property is intentionally
18196 // inside `try` because it might be a getter or Proxy.
18197 if (replayError._suppressLogging) {
18198 // Also suppress logging for the original error.
18199 thrownValue._suppressLogging = true;
18200 }
18201 } catch (inner) {
18202 // Ignore.
18203 }
18204 }
18205 } else {
18206 // If the begin phase did not fail the second time, set this pointer
18207 // back to the original value.
18208 nextUnitOfWork = failedUnitOfWork;
18209 }
18210 };
18211 rethrowOriginalError = function () {
18212 throw originalReplayError;
18213 };
18214}
18215
18216function resetStack() {
18217 if (nextUnitOfWork !== null) {
18218 var interruptedWork = nextUnitOfWork.return;
18219 while (interruptedWork !== null) {
18220 unwindInterruptedWork(interruptedWork);
18221 interruptedWork = interruptedWork.return;
18222 }
18223 }
18224
18225 {
18226 ReactStrictModeWarnings.discardPendingWarnings();
18227 checkThatStackIsEmpty();
18228 }
18229
18230 nextRoot = null;
18231 nextRenderExpirationTime = NoWork;
18232 nextLatestAbsoluteTimeoutMs = -1;
18233 nextRenderDidError = false;
18234 nextUnitOfWork = null;
18235}
18236
18237function commitAllHostEffects() {
18238 while (nextEffect !== null) {
18239 {
18240 setCurrentFiber(nextEffect);
18241 }
18242 recordEffect();
18243
18244 var effectTag = nextEffect.effectTag;
18245
18246 if (effectTag & ContentReset) {
18247 commitResetTextContent(nextEffect);
18248 }
18249
18250 if (effectTag & Ref) {
18251 var current$$1 = nextEffect.alternate;
18252 if (current$$1 !== null) {
18253 commitDetachRef(current$$1);
18254 }
18255 }
18256
18257 // The following switch statement is only concerned about placement,
18258 // updates, and deletions. To avoid needing to add a case for every
18259 // possible bitmap value, we remove the secondary effects from the
18260 // effect tag and switch on that value.
18261 var primaryEffectTag = effectTag & (Placement | Update | Deletion);
18262 switch (primaryEffectTag) {
18263 case Placement:
18264 {
18265 commitPlacement(nextEffect);
18266 // Clear the "placement" from effect tag so that we know that this is inserted, before
18267 // any life-cycles like componentDidMount gets called.
18268 // TODO: findDOMNode doesn't rely on this any more but isMounted
18269 // does and isMounted is deprecated anyway so we should be able
18270 // to kill this.
18271 nextEffect.effectTag &= ~Placement;
18272 break;
18273 }
18274 case PlacementAndUpdate:
18275 {
18276 // Placement
18277 commitPlacement(nextEffect);
18278 // Clear the "placement" from effect tag so that we know that this is inserted, before
18279 // any life-cycles like componentDidMount gets called.
18280 nextEffect.effectTag &= ~Placement;
18281
18282 // Update
18283 var _current = nextEffect.alternate;
18284 commitWork(_current, nextEffect);
18285 break;
18286 }
18287 case Update:
18288 {
18289 var _current2 = nextEffect.alternate;
18290 commitWork(_current2, nextEffect);
18291 break;
18292 }
18293 case Deletion:
18294 {
18295 commitDeletion(nextEffect);
18296 break;
18297 }
18298 }
18299 nextEffect = nextEffect.nextEffect;
18300 }
18301
18302 {
18303 resetCurrentFiber();
18304 }
18305}
18306
18307function commitBeforeMutationLifecycles() {
18308 while (nextEffect !== null) {
18309 {
18310 setCurrentFiber(nextEffect);
18311 }
18312
18313 var effectTag = nextEffect.effectTag;
18314 if (effectTag & Snapshot) {
18315 recordEffect();
18316 var current$$1 = nextEffect.alternate;
18317 commitBeforeMutationLifeCycles(current$$1, nextEffect);
18318 }
18319
18320 nextEffect = nextEffect.nextEffect;
18321 }
18322
18323 {
18324 resetCurrentFiber();
18325 }
18326}
18327
18328function commitAllLifeCycles(finishedRoot, committedExpirationTime) {
18329 {
18330 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
18331 ReactStrictModeWarnings.flushLegacyContextWarning();
18332
18333 if (warnAboutDeprecatedLifecycles) {
18334 ReactStrictModeWarnings.flushPendingDeprecationWarnings();
18335 }
18336 }
18337 while (nextEffect !== null) {
18338 {
18339 setCurrentFiber(nextEffect);
18340 }
18341 var effectTag = nextEffect.effectTag;
18342
18343 if (effectTag & (Update | Callback)) {
18344 recordEffect();
18345 var current$$1 = nextEffect.alternate;
18346 commitLifeCycles(finishedRoot, current$$1, nextEffect, committedExpirationTime);
18347 }
18348
18349 if (effectTag & Ref) {
18350 recordEffect();
18351 commitAttachRef(nextEffect);
18352 }
18353
18354 if (effectTag & Passive) {
18355 rootWithPendingPassiveEffects = finishedRoot;
18356 }
18357
18358 nextEffect = nextEffect.nextEffect;
18359 }
18360 {
18361 resetCurrentFiber();
18362 }
18363}
18364
18365function commitPassiveEffects(root, firstEffect) {
18366 rootWithPendingPassiveEffects = null;
18367 passiveEffectCallbackHandle = null;
18368 passiveEffectCallback = null;
18369
18370 // Set this to true to prevent re-entrancy
18371 var previousIsRendering = isRendering;
18372 isRendering = true;
18373
18374 var effect = firstEffect;
18375 do {
18376 {
18377 setCurrentFiber(effect);
18378 }
18379
18380 if (effect.effectTag & Passive) {
18381 var didError = false;
18382 var error = void 0;
18383 {
18384 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
18385 if (hasCaughtError()) {
18386 didError = true;
18387 error = clearCaughtError();
18388 }
18389 }
18390 if (didError) {
18391 captureCommitPhaseError(effect, error);
18392 }
18393 }
18394 effect = effect.nextEffect;
18395 } while (effect !== null);
18396 {
18397 resetCurrentFiber();
18398 }
18399
18400 isRendering = previousIsRendering;
18401
18402 // Check if work was scheduled by one of the effects
18403 var rootExpirationTime = root.expirationTime;
18404 if (rootExpirationTime !== NoWork) {
18405 requestWork(root, rootExpirationTime);
18406 }
18407}
18408
18409function isAlreadyFailedLegacyErrorBoundary(instance) {
18410 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
18411}
18412
18413function markLegacyErrorBoundaryAsFailed(instance) {
18414 if (legacyErrorBoundariesThatAlreadyFailed === null) {
18415 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
18416 } else {
18417 legacyErrorBoundariesThatAlreadyFailed.add(instance);
18418 }
18419}
18420
18421function flushPassiveEffects() {
18422 if (passiveEffectCallbackHandle !== null) {
18423 cancelPassiveEffects(passiveEffectCallbackHandle);
18424 }
18425 if (passiveEffectCallback !== null) {
18426 // We call the scheduled callback instead of commitPassiveEffects directly
18427 // to ensure tracing works correctly.
18428 passiveEffectCallback();
18429 }
18430}
18431
18432function commitRoot(root, finishedWork) {
18433 isWorking = true;
18434 isCommitting$1 = true;
18435 startCommitTimer();
18436
18437 !(root.current !== finishedWork) ? invariant(false, 'Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue.') : void 0;
18438 var committedExpirationTime = root.pendingCommitExpirationTime;
18439 !(committedExpirationTime !== NoWork) ? invariant(false, 'Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.') : void 0;
18440 root.pendingCommitExpirationTime = NoWork;
18441
18442 // Update the pending priority levels to account for the work that we are
18443 // about to commit. This needs to happen before calling the lifecycles, since
18444 // they may schedule additional updates.
18445 var updateExpirationTimeBeforeCommit = finishedWork.expirationTime;
18446 var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime;
18447 var earliestRemainingTimeBeforeCommit = childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit ? childExpirationTimeBeforeCommit : updateExpirationTimeBeforeCommit;
18448 markCommittedPriorityLevels(root, earliestRemainingTimeBeforeCommit);
18449
18450 var prevInteractions = null;
18451 if (enableSchedulerTracing) {
18452 // Restore any pending interactions at this point,
18453 // So that cascading work triggered during the render phase will be accounted for.
18454 prevInteractions = __interactionsRef.current;
18455 __interactionsRef.current = root.memoizedInteractions;
18456 }
18457
18458 // Reset this to null before calling lifecycles
18459 ReactCurrentOwner$2.current = null;
18460
18461 var firstEffect = void 0;
18462 if (finishedWork.effectTag > PerformedWork) {
18463 // A fiber's effect list consists only of its children, not itself. So if
18464 // the root has an effect, we need to add it to the end of the list. The
18465 // resulting list is the set that would belong to the root's parent, if
18466 // it had one; that is, all the effects in the tree including the root.
18467 if (finishedWork.lastEffect !== null) {
18468 finishedWork.lastEffect.nextEffect = finishedWork;
18469 firstEffect = finishedWork.firstEffect;
18470 } else {
18471 firstEffect = finishedWork;
18472 }
18473 } else {
18474 // There is no effect on the root.
18475 firstEffect = finishedWork.firstEffect;
18476 }
18477
18478 prepareForCommit(root.containerInfo);
18479
18480 // Invoke instances of getSnapshotBeforeUpdate before mutation.
18481 nextEffect = firstEffect;
18482 startCommitSnapshotEffectsTimer();
18483 while (nextEffect !== null) {
18484 var didError = false;
18485 var error = void 0;
18486 {
18487 invokeGuardedCallback(null, commitBeforeMutationLifecycles, null);
18488 if (hasCaughtError()) {
18489 didError = true;
18490 error = clearCaughtError();
18491 }
18492 }
18493 if (didError) {
18494 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
18495 captureCommitPhaseError(nextEffect, error);
18496 // Clean-up
18497 if (nextEffect !== null) {
18498 nextEffect = nextEffect.nextEffect;
18499 }
18500 }
18501 }
18502 stopCommitSnapshotEffectsTimer();
18503
18504 if (enableProfilerTimer) {
18505 // Mark the current commit time to be shared by all Profilers in this batch.
18506 // This enables them to be grouped later.
18507 recordCommitTime();
18508 }
18509
18510 // Commit all the side-effects within a tree. We'll do this in two passes.
18511 // The first pass performs all the host insertions, updates, deletions and
18512 // ref unmounts.
18513 nextEffect = firstEffect;
18514 startCommitHostEffectsTimer();
18515 while (nextEffect !== null) {
18516 var _didError = false;
18517 var _error = void 0;
18518 {
18519 invokeGuardedCallback(null, commitAllHostEffects, null);
18520 if (hasCaughtError()) {
18521 _didError = true;
18522 _error = clearCaughtError();
18523 }
18524 }
18525 if (_didError) {
18526 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
18527 captureCommitPhaseError(nextEffect, _error);
18528 // Clean-up
18529 if (nextEffect !== null) {
18530 nextEffect = nextEffect.nextEffect;
18531 }
18532 }
18533 }
18534 stopCommitHostEffectsTimer();
18535
18536 resetAfterCommit(root.containerInfo);
18537
18538 // The work-in-progress tree is now the current tree. This must come after
18539 // the first pass of the commit phase, so that the previous tree is still
18540 // current during componentWillUnmount, but before the second pass, so that
18541 // the finished work is current during componentDidMount/Update.
18542 root.current = finishedWork;
18543
18544 // In the second pass we'll perform all life-cycles and ref callbacks.
18545 // Life-cycles happen as a separate pass so that all placements, updates,
18546 // and deletions in the entire tree have already been invoked.
18547 // This pass also triggers any renderer-specific initial effects.
18548 nextEffect = firstEffect;
18549 startCommitLifeCyclesTimer();
18550 while (nextEffect !== null) {
18551 var _didError2 = false;
18552 var _error2 = void 0;
18553 {
18554 invokeGuardedCallback(null, commitAllLifeCycles, null, root, committedExpirationTime);
18555 if (hasCaughtError()) {
18556 _didError2 = true;
18557 _error2 = clearCaughtError();
18558 }
18559 }
18560 if (_didError2) {
18561 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
18562 captureCommitPhaseError(nextEffect, _error2);
18563 if (nextEffect !== null) {
18564 nextEffect = nextEffect.nextEffect;
18565 }
18566 }
18567 }
18568
18569 if (firstEffect !== null && rootWithPendingPassiveEffects !== null) {
18570 // This commit included a passive effect. These do not need to fire until
18571 // after the next paint. Schedule an callback to fire them in an async
18572 // event. To ensure serial execution, the callback will be flushed early if
18573 // we enter rootWithPendingPassiveEffects commit phase before then.
18574 var callback = commitPassiveEffects.bind(null, root, firstEffect);
18575 if (enableSchedulerTracing) {
18576 // TODO: Avoid this extra callback by mutating the tracing ref directly,
18577 // like we do at the beginning of commitRoot. I've opted not to do that
18578 // here because that code is still in flux.
18579 callback = unstable_wrap(callback);
18580 }
18581 passiveEffectCallbackHandle = schedulePassiveEffects(callback);
18582 passiveEffectCallback = callback;
18583 }
18584
18585 isCommitting$1 = false;
18586 isWorking = false;
18587 stopCommitLifeCyclesTimer();
18588 stopCommitTimer();
18589 onCommitRoot(finishedWork.stateNode);
18590 if (true && ReactFiberInstrumentation_1.debugTool) {
18591 ReactFiberInstrumentation_1.debugTool.onCommitWork(finishedWork);
18592 }
18593
18594 var updateExpirationTimeAfterCommit = finishedWork.expirationTime;
18595 var childExpirationTimeAfterCommit = finishedWork.childExpirationTime;
18596 var earliestRemainingTimeAfterCommit = childExpirationTimeAfterCommit > updateExpirationTimeAfterCommit ? childExpirationTimeAfterCommit : updateExpirationTimeAfterCommit;
18597 if (earliestRemainingTimeAfterCommit === NoWork) {
18598 // If there's no remaining work, we can clear the set of already failed
18599 // error boundaries.
18600 legacyErrorBoundariesThatAlreadyFailed = null;
18601 }
18602 onCommit(root, earliestRemainingTimeAfterCommit);
18603
18604 if (enableSchedulerTracing) {
18605 __interactionsRef.current = prevInteractions;
18606
18607 var subscriber = void 0;
18608
18609 try {
18610 subscriber = __subscriberRef.current;
18611 if (subscriber !== null && root.memoizedInteractions.size > 0) {
18612 var threadID = computeThreadID(committedExpirationTime, root.interactionThreadID);
18613 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
18614 }
18615 } catch (error) {
18616 // It's not safe for commitRoot() to throw.
18617 // Store the error for now and we'll re-throw in finishRendering().
18618 if (!hasUnhandledError) {
18619 hasUnhandledError = true;
18620 unhandledError = error;
18621 }
18622 } finally {
18623 // Clear completed interactions from the pending Map.
18624 // Unless the render was suspended or cascading work was scheduled,
18625 // In which case– leave pending interactions until the subsequent render.
18626 var pendingInteractionMap = root.pendingInteractionMap;
18627 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
18628 // Only decrement the pending interaction count if we're done.
18629 // If there's still work at the current priority,
18630 // That indicates that we are waiting for suspense data.
18631 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
18632 pendingInteractionMap.delete(scheduledExpirationTime);
18633
18634 scheduledInteractions.forEach(function (interaction) {
18635 interaction.__count--;
18636
18637 if (subscriber !== null && interaction.__count === 0) {
18638 try {
18639 subscriber.onInteractionScheduledWorkCompleted(interaction);
18640 } catch (error) {
18641 // It's not safe for commitRoot() to throw.
18642 // Store the error for now and we'll re-throw in finishRendering().
18643 if (!hasUnhandledError) {
18644 hasUnhandledError = true;
18645 unhandledError = error;
18646 }
18647 }
18648 }
18649 });
18650 }
18651 });
18652 }
18653 }
18654}
18655
18656function resetChildExpirationTime(workInProgress, renderTime) {
18657 if (renderTime !== Never && workInProgress.childExpirationTime === Never) {
18658 // The children of this component are hidden. Don't bubble their
18659 // expiration times.
18660 return;
18661 }
18662
18663 var newChildExpirationTime = NoWork;
18664
18665 // Bubble up the earliest expiration time.
18666 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
18667 // We're in profiling mode.
18668 // Let's use this same traversal to update the render durations.
18669 var actualDuration = workInProgress.actualDuration;
18670 var treeBaseDuration = workInProgress.selfBaseDuration;
18671
18672 // When a fiber is cloned, its actualDuration is reset to 0.
18673 // This value will only be updated if work is done on the fiber (i.e. it doesn't bailout).
18674 // When work is done, it should bubble to the parent's actualDuration.
18675 // If the fiber has not been cloned though, (meaning no work was done),
18676 // Then this value will reflect the amount of time spent working on a previous render.
18677 // In that case it should not bubble.
18678 // We determine whether it was cloned by comparing the child pointer.
18679 var shouldBubbleActualDurations = workInProgress.alternate === null || workInProgress.child !== workInProgress.alternate.child;
18680
18681 var child = workInProgress.child;
18682 while (child !== null) {
18683 var childUpdateExpirationTime = child.expirationTime;
18684 var childChildExpirationTime = child.childExpirationTime;
18685 if (childUpdateExpirationTime > newChildExpirationTime) {
18686 newChildExpirationTime = childUpdateExpirationTime;
18687 }
18688 if (childChildExpirationTime > newChildExpirationTime) {
18689 newChildExpirationTime = childChildExpirationTime;
18690 }
18691 if (shouldBubbleActualDurations) {
18692 actualDuration += child.actualDuration;
18693 }
18694 treeBaseDuration += child.treeBaseDuration;
18695 child = child.sibling;
18696 }
18697 workInProgress.actualDuration = actualDuration;
18698 workInProgress.treeBaseDuration = treeBaseDuration;
18699 } else {
18700 var _child = workInProgress.child;
18701 while (_child !== null) {
18702 var _childUpdateExpirationTime = _child.expirationTime;
18703 var _childChildExpirationTime = _child.childExpirationTime;
18704 if (_childUpdateExpirationTime > newChildExpirationTime) {
18705 newChildExpirationTime = _childUpdateExpirationTime;
18706 }
18707 if (_childChildExpirationTime > newChildExpirationTime) {
18708 newChildExpirationTime = _childChildExpirationTime;
18709 }
18710 _child = _child.sibling;
18711 }
18712 }
18713
18714 workInProgress.childExpirationTime = newChildExpirationTime;
18715}
18716
18717function completeUnitOfWork(workInProgress) {
18718 // Attempt to complete the current unit of work, then move to the
18719 // next sibling. If there are no more siblings, return to the
18720 // parent fiber.
18721 while (true) {
18722 // The current, flushed, state of this fiber is the alternate.
18723 // Ideally nothing should rely on this, but relying on it here
18724 // means that we don't need an additional field on the work in
18725 // progress.
18726 var current$$1 = workInProgress.alternate;
18727 {
18728 setCurrentFiber(workInProgress);
18729 }
18730
18731 var returnFiber = workInProgress.return;
18732 var siblingFiber = workInProgress.sibling;
18733
18734 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
18735 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
18736 // Don't replay if it fails during completion phase.
18737 mayReplayFailedUnitOfWork = false;
18738 }
18739 // This fiber completed.
18740 // Remember we're completing this unit so we can find a boundary if it fails.
18741 nextUnitOfWork = workInProgress;
18742 if (enableProfilerTimer) {
18743 if (workInProgress.mode & ProfileMode) {
18744 startProfilerTimer(workInProgress);
18745 }
18746 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
18747 if (workInProgress.mode & ProfileMode) {
18748 // Update render duration assuming we didn't error.
18749 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
18750 }
18751 } else {
18752 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
18753 }
18754 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
18755 // We're out of completion phase so replaying is fine now.
18756 mayReplayFailedUnitOfWork = true;
18757 }
18758 stopWorkTimer(workInProgress);
18759 resetChildExpirationTime(workInProgress, nextRenderExpirationTime);
18760 {
18761 resetCurrentFiber();
18762 }
18763
18764 if (nextUnitOfWork !== null) {
18765 // Completing this fiber spawned new work. Work on that next.
18766 return nextUnitOfWork;
18767 }
18768
18769 if (returnFiber !== null &&
18770 // Do not append effects to parents if a sibling failed to complete
18771 (returnFiber.effectTag & Incomplete) === NoEffect) {
18772 // Append all the effects of the subtree and this fiber onto the effect
18773 // list of the parent. The completion order of the children affects the
18774 // side-effect order.
18775 if (returnFiber.firstEffect === null) {
18776 returnFiber.firstEffect = workInProgress.firstEffect;
18777 }
18778 if (workInProgress.lastEffect !== null) {
18779 if (returnFiber.lastEffect !== null) {
18780 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
18781 }
18782 returnFiber.lastEffect = workInProgress.lastEffect;
18783 }
18784
18785 // If this fiber had side-effects, we append it AFTER the children's
18786 // side-effects. We can perform certain side-effects earlier if
18787 // needed, by doing multiple passes over the effect list. We don't want
18788 // to schedule our own side-effect on our own list because if end up
18789 // reusing children we'll schedule this effect onto itself since we're
18790 // at the end.
18791 var effectTag = workInProgress.effectTag;
18792 // Skip both NoWork and PerformedWork tags when creating the effect list.
18793 // PerformedWork effect is read by React DevTools but shouldn't be committed.
18794 if (effectTag > PerformedWork) {
18795 if (returnFiber.lastEffect !== null) {
18796 returnFiber.lastEffect.nextEffect = workInProgress;
18797 } else {
18798 returnFiber.firstEffect = workInProgress;
18799 }
18800 returnFiber.lastEffect = workInProgress;
18801 }
18802 }
18803
18804 if (true && ReactFiberInstrumentation_1.debugTool) {
18805 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
18806 }
18807
18808 if (siblingFiber !== null) {
18809 // If there is more work to do in this returnFiber, do that next.
18810 return siblingFiber;
18811 } else if (returnFiber !== null) {
18812 // If there's no more work in this returnFiber. Complete the returnFiber.
18813 workInProgress = returnFiber;
18814 continue;
18815 } else {
18816 // We've reached the root.
18817 return null;
18818 }
18819 } else {
18820 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
18821 // Record the render duration for the fiber that errored.
18822 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
18823
18824 // Include the time spent working on failed children before continuing.
18825 var actualDuration = workInProgress.actualDuration;
18826 var child = workInProgress.child;
18827 while (child !== null) {
18828 actualDuration += child.actualDuration;
18829 child = child.sibling;
18830 }
18831 workInProgress.actualDuration = actualDuration;
18832 }
18833
18834 // This fiber did not complete because something threw. Pop values off
18835 // the stack without entering the complete phase. If this is a boundary,
18836 // capture values if possible.
18837 var next = unwindWork(workInProgress, nextRenderExpirationTime);
18838 // Because this fiber did not complete, don't reset its expiration time.
18839 if (workInProgress.effectTag & DidCapture) {
18840 // Restarting an error boundary
18841 stopFailedWorkTimer(workInProgress);
18842 } else {
18843 stopWorkTimer(workInProgress);
18844 }
18845
18846 {
18847 resetCurrentFiber();
18848 }
18849
18850 if (next !== null) {
18851 stopWorkTimer(workInProgress);
18852 if (true && ReactFiberInstrumentation_1.debugTool) {
18853 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
18854 }
18855
18856 // If completing this work spawned new work, do that next. We'll come
18857 // back here again.
18858 // Since we're restarting, remove anything that is not a host effect
18859 // from the effect tag.
18860 next.effectTag &= HostEffectMask;
18861 return next;
18862 }
18863
18864 if (returnFiber !== null) {
18865 // Mark the parent fiber as incomplete and clear its effect list.
18866 returnFiber.firstEffect = returnFiber.lastEffect = null;
18867 returnFiber.effectTag |= Incomplete;
18868 }
18869
18870 if (true && ReactFiberInstrumentation_1.debugTool) {
18871 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
18872 }
18873
18874 if (siblingFiber !== null) {
18875 // If there is more work to do in this returnFiber, do that next.
18876 return siblingFiber;
18877 } else if (returnFiber !== null) {
18878 // If there's no more work in this returnFiber. Complete the returnFiber.
18879 workInProgress = returnFiber;
18880 continue;
18881 } else {
18882 return null;
18883 }
18884 }
18885 }
18886
18887 // Without this explicit null return Flow complains of invalid return type
18888 // TODO Remove the above while(true) loop
18889 // eslint-disable-next-line no-unreachable
18890 return null;
18891}
18892
18893function performUnitOfWork(workInProgress) {
18894 // The current, flushed, state of this fiber is the alternate.
18895 // Ideally nothing should rely on this, but relying on it here
18896 // means that we don't need an additional field on the work in
18897 // progress.
18898 var current$$1 = workInProgress.alternate;
18899
18900 // See if beginning this work spawns more work.
18901 startWorkTimer(workInProgress);
18902 {
18903 setCurrentFiber(workInProgress);
18904 }
18905
18906 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
18907 stashedWorkInProgressProperties = assignFiberPropertiesInDEV(stashedWorkInProgressProperties, workInProgress);
18908 }
18909
18910 var next = void 0;
18911 if (enableProfilerTimer) {
18912 if (workInProgress.mode & ProfileMode) {
18913 startProfilerTimer(workInProgress);
18914 }
18915
18916 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
18917 workInProgress.memoizedProps = workInProgress.pendingProps;
18918
18919 if (workInProgress.mode & ProfileMode) {
18920 // Record the render duration assuming we didn't bailout (or error).
18921 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
18922 }
18923 } else {
18924 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
18925 workInProgress.memoizedProps = workInProgress.pendingProps;
18926 }
18927
18928 {
18929 resetCurrentFiber();
18930 if (isReplayingFailedUnitOfWork) {
18931 // Currently replaying a failed unit of work. This should be unreachable,
18932 // because the render phase is meant to be idempotent, and it should
18933 // have thrown again. Since it didn't, rethrow the original error, so
18934 // React's internal stack is not misaligned.
18935 rethrowOriginalError();
18936 }
18937 }
18938 if (true && ReactFiberInstrumentation_1.debugTool) {
18939 ReactFiberInstrumentation_1.debugTool.onBeginWork(workInProgress);
18940 }
18941
18942 if (next === null) {
18943 // If this doesn't spawn new work, complete the current work.
18944 next = completeUnitOfWork(workInProgress);
18945 }
18946
18947 ReactCurrentOwner$2.current = null;
18948
18949 return next;
18950}
18951
18952function workLoop(isYieldy) {
18953 if (!isYieldy) {
18954 // Flush work without yielding
18955 while (nextUnitOfWork !== null) {
18956 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
18957 }
18958 } else {
18959 // Flush asynchronous work until there's a higher priority event
18960 while (nextUnitOfWork !== null && !shouldYieldToRenderer()) {
18961 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
18962 }
18963 }
18964}
18965
18966function renderRoot(root, isYieldy) {
18967 !!isWorking ? invariant(false, 'renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;
18968
18969 flushPassiveEffects();
18970
18971 isWorking = true;
18972 var previousDispatcher = ReactCurrentDispatcher.current;
18973 ReactCurrentDispatcher.current = ContextOnlyDispatcher;
18974
18975 var expirationTime = root.nextExpirationTimeToWorkOn;
18976
18977 // Check if we're starting from a fresh stack, or if we're resuming from
18978 // previously yielded work.
18979 if (expirationTime !== nextRenderExpirationTime || root !== nextRoot || nextUnitOfWork === null) {
18980 // Reset the stack and start working from the root.
18981 resetStack();
18982 nextRoot = root;
18983 nextRenderExpirationTime = expirationTime;
18984 nextUnitOfWork = createWorkInProgress(nextRoot.current, null, nextRenderExpirationTime);
18985 root.pendingCommitExpirationTime = NoWork;
18986
18987 if (enableSchedulerTracing) {
18988 // Determine which interactions this batch of work currently includes,
18989 // So that we can accurately attribute time spent working on it,
18990 var interactions = new Set();
18991 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
18992 if (scheduledExpirationTime >= expirationTime) {
18993 scheduledInteractions.forEach(function (interaction) {
18994 return interactions.add(interaction);
18995 });
18996 }
18997 });
18998
18999 // Store the current set of interactions on the FiberRoot for a few reasons:
19000 // We can re-use it in hot functions like renderRoot() without having to recalculate it.
19001 // We will also use it in commitWork() to pass to any Profiler onRender() hooks.
19002 // This also provides DevTools with a way to access it when the onCommitRoot() hook is called.
19003 root.memoizedInteractions = interactions;
19004
19005 if (interactions.size > 0) {
19006 var subscriber = __subscriberRef.current;
19007 if (subscriber !== null) {
19008 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
19009 try {
19010 subscriber.onWorkStarted(interactions, threadID);
19011 } catch (error) {
19012 // Work thrown by an interaction tracing subscriber should be rethrown,
19013 // But only once it's safe (to avoid leaving the scheduler in an invalid state).
19014 // Store the error for now and we'll re-throw in finishRendering().
19015 if (!hasUnhandledError) {
19016 hasUnhandledError = true;
19017 unhandledError = error;
19018 }
19019 }
19020 }
19021 }
19022 }
19023 }
19024
19025 var prevInteractions = null;
19026 if (enableSchedulerTracing) {
19027 // We're about to start new traced work.
19028 // Restore pending interactions so cascading work triggered during the render phase will be accounted for.
19029 prevInteractions = __interactionsRef.current;
19030 __interactionsRef.current = root.memoizedInteractions;
19031 }
19032
19033 var didFatal = false;
19034
19035 startWorkLoopTimer(nextUnitOfWork);
19036
19037 do {
19038 try {
19039 workLoop(isYieldy);
19040 } catch (thrownValue) {
19041 resetContextDependences();
19042 resetHooks();
19043
19044 // Reset in case completion throws.
19045 // This is only used in DEV and when replaying is on.
19046 var mayReplay = void 0;
19047 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
19048 mayReplay = mayReplayFailedUnitOfWork;
19049 mayReplayFailedUnitOfWork = true;
19050 }
19051
19052 if (nextUnitOfWork === null) {
19053 // This is a fatal error.
19054 didFatal = true;
19055 onUncaughtError(thrownValue);
19056 } else {
19057 if (enableProfilerTimer && nextUnitOfWork.mode & ProfileMode) {
19058 // Record the time spent rendering before an error was thrown.
19059 // This avoids inaccurate Profiler durations in the case of a suspended render.
19060 stopProfilerTimerIfRunningAndRecordDelta(nextUnitOfWork, true);
19061 }
19062
19063 {
19064 // Reset global debug state
19065 // We assume this is defined in DEV
19066 resetCurrentlyProcessingQueue();
19067 }
19068
19069 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
19070 if (mayReplay) {
19071 var failedUnitOfWork = nextUnitOfWork;
19072 replayUnitOfWork(failedUnitOfWork, thrownValue, isYieldy);
19073 }
19074 }
19075
19076 // TODO: we already know this isn't true in some cases.
19077 // At least this shows a nicer error message until we figure out the cause.
19078 // https://github.com/facebook/react/issues/12449#issuecomment-386727431
19079 !(nextUnitOfWork !== null) ? invariant(false, 'Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it.') : void 0;
19080
19081 var sourceFiber = nextUnitOfWork;
19082 var returnFiber = sourceFiber.return;
19083 if (returnFiber === null) {
19084 // This is the root. The root could capture its own errors. However,
19085 // we don't know if it errors before or after we pushed the host
19086 // context. This information is needed to avoid a stack mismatch.
19087 // Because we're not sure, treat this as a fatal error. We could track
19088 // which phase it fails in, but doesn't seem worth it. At least
19089 // for now.
19090 didFatal = true;
19091 onUncaughtError(thrownValue);
19092 } else {
19093 throwException(root, returnFiber, sourceFiber, thrownValue, nextRenderExpirationTime);
19094 nextUnitOfWork = completeUnitOfWork(sourceFiber);
19095 continue;
19096 }
19097 }
19098 }
19099 break;
19100 } while (true);
19101
19102 if (enableSchedulerTracing) {
19103 // Traced work is done for now; restore the previous interactions.
19104 __interactionsRef.current = prevInteractions;
19105 }
19106
19107 // We're done performing work. Time to clean up.
19108 isWorking = false;
19109 ReactCurrentDispatcher.current = previousDispatcher;
19110 resetContextDependences();
19111 resetHooks();
19112
19113 // Yield back to main thread.
19114 if (didFatal) {
19115 var _didCompleteRoot = false;
19116 stopWorkLoopTimer(interruptedBy, _didCompleteRoot);
19117 interruptedBy = null;
19118 // There was a fatal error.
19119 {
19120 resetStackAfterFatalErrorInDev();
19121 }
19122 // `nextRoot` points to the in-progress root. A non-null value indicates
19123 // that we're in the middle of an async render. Set it to null to indicate
19124 // there's no more work to be done in the current batch.
19125 nextRoot = null;
19126 onFatal(root);
19127 return;
19128 }
19129
19130 if (nextUnitOfWork !== null) {
19131 // There's still remaining async work in this tree, but we ran out of time
19132 // in the current frame. Yield back to the renderer. Unless we're
19133 // interrupted by a higher priority update, we'll continue later from where
19134 // we left off.
19135 var _didCompleteRoot2 = false;
19136 stopWorkLoopTimer(interruptedBy, _didCompleteRoot2);
19137 interruptedBy = null;
19138 onYield(root);
19139 return;
19140 }
19141
19142 // We completed the whole tree.
19143 var didCompleteRoot = true;
19144 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
19145 var rootWorkInProgress = root.current.alternate;
19146 !(rootWorkInProgress !== null) ? invariant(false, 'Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue.') : void 0;
19147
19148 // `nextRoot` points to the in-progress root. A non-null value indicates
19149 // that we're in the middle of an async render. Set it to null to indicate
19150 // there's no more work to be done in the current batch.
19151 nextRoot = null;
19152 interruptedBy = null;
19153
19154 if (nextRenderDidError) {
19155 // There was an error
19156 if (hasLowerPriorityWork(root, expirationTime)) {
19157 // There's lower priority work. If so, it may have the effect of fixing
19158 // the exception that was just thrown. Exit without committing. This is
19159 // similar to a suspend, but without a timeout because we're not waiting
19160 // for a promise to resolve. React will restart at the lower
19161 // priority level.
19162 markSuspendedPriorityLevel(root, expirationTime);
19163 var suspendedExpirationTime = expirationTime;
19164 var rootExpirationTime = root.expirationTime;
19165 onSuspend(root, rootWorkInProgress, suspendedExpirationTime, rootExpirationTime, -1 // Indicates no timeout
19166 );
19167 return;
19168 } else if (
19169 // There's no lower priority work, but we're rendering asynchronously.
19170 // Synchronsouly attempt to render the same level one more time. This is
19171 // similar to a suspend, but without a timeout because we're not waiting
19172 // for a promise to resolve.
19173 !root.didError && isYieldy) {
19174 root.didError = true;
19175 var _suspendedExpirationTime = root.nextExpirationTimeToWorkOn = expirationTime;
19176 var _rootExpirationTime = root.expirationTime = Sync;
19177 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime, _rootExpirationTime, -1 // Indicates no timeout
19178 );
19179 return;
19180 }
19181 }
19182
19183 if (isYieldy && nextLatestAbsoluteTimeoutMs !== -1) {
19184 // The tree was suspended.
19185 var _suspendedExpirationTime2 = expirationTime;
19186 markSuspendedPriorityLevel(root, _suspendedExpirationTime2);
19187
19188 // Find the earliest uncommitted expiration time in the tree, including
19189 // work that is suspended. The timeout threshold cannot be longer than
19190 // the overall expiration.
19191 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, expirationTime);
19192 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
19193 if (earliestExpirationTimeMs < nextLatestAbsoluteTimeoutMs) {
19194 nextLatestAbsoluteTimeoutMs = earliestExpirationTimeMs;
19195 }
19196
19197 // Subtract the current time from the absolute timeout to get the number
19198 // of milliseconds until the timeout. In other words, convert an absolute
19199 // timestamp to a relative time. This is the value that is passed
19200 // to `setTimeout`.
19201 var currentTimeMs = expirationTimeToMs(requestCurrentTime());
19202 var msUntilTimeout = nextLatestAbsoluteTimeoutMs - currentTimeMs;
19203 msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout;
19204
19205 // TODO: Account for the Just Noticeable Difference
19206
19207 var _rootExpirationTime2 = root.expirationTime;
19208 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime2, _rootExpirationTime2, msUntilTimeout);
19209 return;
19210 }
19211
19212 // Ready to commit.
19213 onComplete(root, rootWorkInProgress, expirationTime);
19214}
19215
19216function captureCommitPhaseError(sourceFiber, value) {
19217 var expirationTime = Sync;
19218 var fiber = sourceFiber.return;
19219 while (fiber !== null) {
19220 switch (fiber.tag) {
19221 case ClassComponent:
19222 var ctor = fiber.type;
19223 var instance = fiber.stateNode;
19224 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
19225 var errorInfo = createCapturedValue(value, sourceFiber);
19226 var update = createClassErrorUpdate(fiber, errorInfo, expirationTime);
19227 enqueueUpdate(fiber, update);
19228 scheduleWork(fiber, expirationTime);
19229 return;
19230 }
19231 break;
19232 case HostRoot:
19233 {
19234 var _errorInfo = createCapturedValue(value, sourceFiber);
19235 var _update = createRootErrorUpdate(fiber, _errorInfo, expirationTime);
19236 enqueueUpdate(fiber, _update);
19237 scheduleWork(fiber, expirationTime);
19238 return;
19239 }
19240 }
19241 fiber = fiber.return;
19242 }
19243
19244 if (sourceFiber.tag === HostRoot) {
19245 // Error was thrown at the root. There is no parent, so the root
19246 // itself should capture it.
19247 var rootFiber = sourceFiber;
19248 var _errorInfo2 = createCapturedValue(value, rootFiber);
19249 var _update2 = createRootErrorUpdate(rootFiber, _errorInfo2, expirationTime);
19250 enqueueUpdate(rootFiber, _update2);
19251 scheduleWork(rootFiber, expirationTime);
19252 }
19253}
19254
19255function computeThreadID(expirationTime, interactionThreadID) {
19256 // Interaction threads are unique per root and expiration time.
19257 return expirationTime * 1000 + interactionThreadID;
19258}
19259
19260// Creates a unique async expiration time.
19261function computeUniqueAsyncExpiration() {
19262 var currentTime = requestCurrentTime();
19263 var result = computeAsyncExpiration(currentTime);
19264 if (result >= lastUniqueAsyncExpiration) {
19265 // Since we assume the current time monotonically increases, we only hit
19266 // this branch when computeUniqueAsyncExpiration is fired multiple times
19267 // within a 200ms window (or whatever the async bucket size is).
19268 result = lastUniqueAsyncExpiration - 1;
19269 }
19270 lastUniqueAsyncExpiration = result;
19271 return lastUniqueAsyncExpiration;
19272}
19273
19274function computeExpirationForFiber(currentTime, fiber) {
19275 var expirationTime = void 0;
19276 if (expirationContext !== NoWork) {
19277 // An explicit expiration context was set;
19278 expirationTime = expirationContext;
19279 } else if (isWorking) {
19280 if (isCommitting$1) {
19281 // Updates that occur during the commit phase should have sync priority
19282 // by default.
19283 expirationTime = Sync;
19284 } else {
19285 // Updates during the render phase should expire at the same time as
19286 // the work that is being rendered.
19287 expirationTime = nextRenderExpirationTime;
19288 }
19289 } else {
19290 // No explicit expiration context was set, and we're not currently
19291 // performing work. Calculate a new expiration time.
19292 if (fiber.mode & ConcurrentMode) {
19293 if (isBatchingInteractiveUpdates) {
19294 // This is an interactive update
19295 expirationTime = computeInteractiveExpiration(currentTime);
19296 } else {
19297 // This is an async update
19298 expirationTime = computeAsyncExpiration(currentTime);
19299 }
19300 // If we're in the middle of rendering a tree, do not update at the same
19301 // expiration time that is already rendering.
19302 if (nextRoot !== null && expirationTime === nextRenderExpirationTime) {
19303 expirationTime -= 1;
19304 }
19305 } else {
19306 // This is a sync update
19307 expirationTime = Sync;
19308 }
19309 }
19310 if (isBatchingInteractiveUpdates) {
19311 // This is an interactive update. Keep track of the lowest pending
19312 // interactive expiration time. This allows us to synchronously flush
19313 // all interactive updates when needed.
19314 if (lowestPriorityPendingInteractiveExpirationTime === NoWork || expirationTime < lowestPriorityPendingInteractiveExpirationTime) {
19315 lowestPriorityPendingInteractiveExpirationTime = expirationTime;
19316 }
19317 }
19318 return expirationTime;
19319}
19320
19321function renderDidSuspend(root, absoluteTimeoutMs, suspendedTime) {
19322 // Schedule the timeout.
19323 if (absoluteTimeoutMs >= 0 && nextLatestAbsoluteTimeoutMs < absoluteTimeoutMs) {
19324 nextLatestAbsoluteTimeoutMs = absoluteTimeoutMs;
19325 }
19326}
19327
19328function renderDidError() {
19329 nextRenderDidError = true;
19330}
19331
19332function pingSuspendedRoot(root, thenable, pingTime) {
19333 // A promise that previously suspended React from committing has resolved.
19334 // If React is still suspended, try again at the previous level (pingTime).
19335
19336 var pingCache = root.pingCache;
19337 if (pingCache !== null) {
19338 // The thenable resolved, so we no longer need to memoize, because it will
19339 // never be thrown again.
19340 pingCache.delete(thenable);
19341 }
19342
19343 if (nextRoot !== null && nextRenderExpirationTime === pingTime) {
19344 // Received a ping at the same priority level at which we're currently
19345 // rendering. Restart from the root.
19346 nextRoot = null;
19347 } else {
19348 // Confirm that the root is still suspended at this level. Otherwise exit.
19349 if (isPriorityLevelSuspended(root, pingTime)) {
19350 // Ping at the original level
19351 markPingedPriorityLevel(root, pingTime);
19352 var rootExpirationTime = root.expirationTime;
19353 if (rootExpirationTime !== NoWork) {
19354 requestWork(root, rootExpirationTime);
19355 }
19356 }
19357 }
19358}
19359
19360function retryTimedOutBoundary(boundaryFiber, thenable) {
19361 // The boundary fiber (a Suspense component) previously timed out and was
19362 // rendered in its fallback state. One of the promises that suspended it has
19363 // resolved, which means at least part of the tree was likely unblocked. Try
19364 var retryCache = boundaryFiber.stateNode;
19365 if (retryCache !== null) {
19366 // The thenable resolved, so we no longer need to memoize, because it will
19367 // never be thrown again.
19368 retryCache.delete(thenable);
19369 }
19370
19371 var currentTime = requestCurrentTime();
19372 var retryTime = computeExpirationForFiber(currentTime, boundaryFiber);
19373 var root = scheduleWorkToRoot(boundaryFiber, retryTime);
19374 if (root !== null) {
19375 markPendingPriorityLevel(root, retryTime);
19376 var rootExpirationTime = root.expirationTime;
19377 if (rootExpirationTime !== NoWork) {
19378 requestWork(root, rootExpirationTime);
19379 }
19380 }
19381}
19382
19383function scheduleWorkToRoot(fiber, expirationTime) {
19384 recordScheduleUpdate();
19385
19386 {
19387 if (fiber.tag === ClassComponent) {
19388 var instance = fiber.stateNode;
19389 warnAboutInvalidUpdates(instance);
19390 }
19391 }
19392
19393 // Update the source fiber's expiration time
19394 if (fiber.expirationTime < expirationTime) {
19395 fiber.expirationTime = expirationTime;
19396 }
19397 var alternate = fiber.alternate;
19398 if (alternate !== null && alternate.expirationTime < expirationTime) {
19399 alternate.expirationTime = expirationTime;
19400 }
19401 // Walk the parent path to the root and update the child expiration time.
19402 var node = fiber.return;
19403 var root = null;
19404 if (node === null && fiber.tag === HostRoot) {
19405 root = fiber.stateNode;
19406 } else {
19407 while (node !== null) {
19408 alternate = node.alternate;
19409 if (node.childExpirationTime < expirationTime) {
19410 node.childExpirationTime = expirationTime;
19411 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
19412 alternate.childExpirationTime = expirationTime;
19413 }
19414 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
19415 alternate.childExpirationTime = expirationTime;
19416 }
19417 if (node.return === null && node.tag === HostRoot) {
19418 root = node.stateNode;
19419 break;
19420 }
19421 node = node.return;
19422 }
19423 }
19424
19425 if (enableSchedulerTracing) {
19426 if (root !== null) {
19427 var interactions = __interactionsRef.current;
19428 if (interactions.size > 0) {
19429 var pendingInteractionMap = root.pendingInteractionMap;
19430 var pendingInteractions = pendingInteractionMap.get(expirationTime);
19431 if (pendingInteractions != null) {
19432 interactions.forEach(function (interaction) {
19433 if (!pendingInteractions.has(interaction)) {
19434 // Update the pending async work count for previously unscheduled interaction.
19435 interaction.__count++;
19436 }
19437
19438 pendingInteractions.add(interaction);
19439 });
19440 } else {
19441 pendingInteractionMap.set(expirationTime, new Set(interactions));
19442
19443 // Update the pending async work count for the current interactions.
19444 interactions.forEach(function (interaction) {
19445 interaction.__count++;
19446 });
19447 }
19448
19449 var subscriber = __subscriberRef.current;
19450 if (subscriber !== null) {
19451 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
19452 subscriber.onWorkScheduled(interactions, threadID);
19453 }
19454 }
19455 }
19456 }
19457 return root;
19458}
19459
19460function warnIfNotCurrentlyBatchingInDev(fiber) {
19461 {
19462 if (isRendering === false && isBatchingUpdates === false) {
19463 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', getComponentName(fiber.type));
19464 }
19465 }
19466}
19467
19468function scheduleWork(fiber, expirationTime) {
19469 var root = scheduleWorkToRoot(fiber, expirationTime);
19470 if (root === null) {
19471 {
19472 switch (fiber.tag) {
19473 case ClassComponent:
19474 warnAboutUpdateOnUnmounted(fiber, true);
19475 break;
19476 case FunctionComponent:
19477 case ForwardRef:
19478 case MemoComponent:
19479 case SimpleMemoComponent:
19480 warnAboutUpdateOnUnmounted(fiber, false);
19481 break;
19482 }
19483 }
19484 return;
19485 }
19486
19487 if (!isWorking && nextRenderExpirationTime !== NoWork && expirationTime > nextRenderExpirationTime) {
19488 // This is an interruption. (Used for performance tracking.)
19489 interruptedBy = fiber;
19490 resetStack();
19491 }
19492 markPendingPriorityLevel(root, expirationTime);
19493 if (
19494 // If we're in the render phase, we don't need to schedule this root
19495 // for an update, because we'll do it before we exit...
19496 !isWorking || isCommitting$1 ||
19497 // ...unless this is a different root than the one we're rendering.
19498 nextRoot !== root) {
19499 var rootExpirationTime = root.expirationTime;
19500 requestWork(root, rootExpirationTime);
19501 }
19502 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
19503 // Reset this back to zero so subsequent updates don't throw.
19504 nestedUpdateCount = 0;
19505 invariant(false, '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.');
19506 }
19507}
19508
19509function syncUpdates(fn, a, b, c, d) {
19510 var previousExpirationContext = expirationContext;
19511 expirationContext = Sync;
19512 try {
19513 return fn(a, b, c, d);
19514 } finally {
19515 expirationContext = previousExpirationContext;
19516 }
19517}
19518
19519// TODO: Everything below this is written as if it has been lifted to the
19520// renderers. I'll do this in a follow-up.
19521
19522// Linked-list of roots
19523var firstScheduledRoot = null;
19524var lastScheduledRoot = null;
19525
19526var callbackExpirationTime = NoWork;
19527var callbackID = void 0;
19528var isRendering = false;
19529var nextFlushedRoot = null;
19530var nextFlushedExpirationTime = NoWork;
19531var lowestPriorityPendingInteractiveExpirationTime = NoWork;
19532var hasUnhandledError = false;
19533var unhandledError = null;
19534
19535var isBatchingUpdates = false;
19536var isUnbatchingUpdates = false;
19537var isBatchingInteractiveUpdates = false;
19538
19539var completedBatches = null;
19540
19541var originalStartTimeMs = unstable_now();
19542var currentRendererTime = msToExpirationTime(originalStartTimeMs);
19543var currentSchedulerTime = currentRendererTime;
19544
19545// Use these to prevent an infinite loop of nested updates
19546var NESTED_UPDATE_LIMIT = 50;
19547var nestedUpdateCount = 0;
19548var lastCommittedRootDuringThisBatch = null;
19549
19550function recomputeCurrentRendererTime() {
19551 var currentTimeMs = unstable_now() - originalStartTimeMs;
19552 currentRendererTime = msToExpirationTime(currentTimeMs);
19553}
19554
19555function scheduleCallbackWithExpirationTime(root, expirationTime) {
19556 if (callbackExpirationTime !== NoWork) {
19557 // A callback is already scheduled. Check its expiration time (timeout).
19558 if (expirationTime < callbackExpirationTime) {
19559 // Existing callback has sufficient timeout. Exit.
19560 return;
19561 } else {
19562 if (callbackID !== null) {
19563 // Existing callback has insufficient timeout. Cancel and schedule a
19564 // new one.
19565 unstable_cancelCallback(callbackID);
19566 }
19567 }
19568 // The request callback timer is already running. Don't start a new one.
19569 } else {
19570 startRequestCallbackTimer();
19571 }
19572
19573 callbackExpirationTime = expirationTime;
19574 var currentMs = unstable_now() - originalStartTimeMs;
19575 var expirationTimeMs = expirationTimeToMs(expirationTime);
19576 var timeout = expirationTimeMs - currentMs;
19577 callbackID = unstable_scheduleCallback(performAsyncWork, { timeout: timeout });
19578}
19579
19580// For every call to renderRoot, one of onFatal, onComplete, onSuspend, and
19581// onYield is called upon exiting. We use these in lieu of returning a tuple.
19582// I've also chosen not to inline them into renderRoot because these will
19583// eventually be lifted into the renderer.
19584function onFatal(root) {
19585 root.finishedWork = null;
19586}
19587
19588function onComplete(root, finishedWork, expirationTime) {
19589 root.pendingCommitExpirationTime = expirationTime;
19590 root.finishedWork = finishedWork;
19591}
19592
19593function onSuspend(root, finishedWork, suspendedExpirationTime, rootExpirationTime, msUntilTimeout) {
19594 root.expirationTime = rootExpirationTime;
19595 if (msUntilTimeout === 0 && !shouldYieldToRenderer()) {
19596 // Don't wait an additional tick. Commit the tree immediately.
19597 root.pendingCommitExpirationTime = suspendedExpirationTime;
19598 root.finishedWork = finishedWork;
19599 } else if (msUntilTimeout > 0) {
19600 // Wait `msUntilTimeout` milliseconds before committing.
19601 root.timeoutHandle = scheduleTimeout(onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), msUntilTimeout);
19602 }
19603}
19604
19605function onYield(root) {
19606 root.finishedWork = null;
19607}
19608
19609function onTimeout(root, finishedWork, suspendedExpirationTime) {
19610 // The root timed out. Commit it.
19611 root.pendingCommitExpirationTime = suspendedExpirationTime;
19612 root.finishedWork = finishedWork;
19613 // Read the current time before entering the commit phase. We can be
19614 // certain this won't cause tearing related to batching of event updates
19615 // because we're at the top of a timer event.
19616 recomputeCurrentRendererTime();
19617 currentSchedulerTime = currentRendererTime;
19618 flushRoot(root, suspendedExpirationTime);
19619}
19620
19621function onCommit(root, expirationTime) {
19622 root.expirationTime = expirationTime;
19623 root.finishedWork = null;
19624}
19625
19626function requestCurrentTime() {
19627 // requestCurrentTime is called by the scheduler to compute an expiration
19628 // time.
19629 //
19630 // Expiration times are computed by adding to the current time (the start
19631 // time). However, if two updates are scheduled within the same event, we
19632 // should treat their start times as simultaneous, even if the actual clock
19633 // time has advanced between the first and second call.
19634
19635 // In other words, because expiration times determine how updates are batched,
19636 // we want all updates of like priority that occur within the same event to
19637 // receive the same expiration time. Otherwise we get tearing.
19638 //
19639 // We keep track of two separate times: the current "renderer" time and the
19640 // current "scheduler" time. The renderer time can be updated whenever; it
19641 // only exists to minimize the calls performance.now.
19642 //
19643 // But the scheduler time can only be updated if there's no pending work, or
19644 // if we know for certain that we're not in the middle of an event.
19645
19646 if (isRendering) {
19647 // We're already rendering. Return the most recently read time.
19648 return currentSchedulerTime;
19649 }
19650 // Check if there's pending work.
19651 findHighestPriorityRoot();
19652 if (nextFlushedExpirationTime === NoWork || nextFlushedExpirationTime === Never) {
19653 // If there's no pending work, or if the pending work is offscreen, we can
19654 // read the current time without risk of tearing.
19655 recomputeCurrentRendererTime();
19656 currentSchedulerTime = currentRendererTime;
19657 return currentSchedulerTime;
19658 }
19659 // There's already pending work. We might be in the middle of a browser
19660 // event. If we were to read the current time, it could cause multiple updates
19661 // within the same event to receive different expiration times, leading to
19662 // tearing. Return the last read time. During the next idle callback, the
19663 // time will be updated.
19664 return currentSchedulerTime;
19665}
19666
19667// requestWork is called by the scheduler whenever a root receives an update.
19668// It's up to the renderer to call renderRoot at some point in the future.
19669function requestWork(root, expirationTime) {
19670 addRootToSchedule(root, expirationTime);
19671 if (isRendering) {
19672 // Prevent reentrancy. Remaining work will be scheduled at the end of
19673 // the currently rendering batch.
19674 return;
19675 }
19676
19677 if (isBatchingUpdates) {
19678 // Flush work at the end of the batch.
19679 if (isUnbatchingUpdates) {
19680 // ...unless we're inside unbatchedUpdates, in which case we should
19681 // flush it now.
19682 nextFlushedRoot = root;
19683 nextFlushedExpirationTime = Sync;
19684 performWorkOnRoot(root, Sync, false);
19685 }
19686 return;
19687 }
19688
19689 // TODO: Get rid of Sync and use current time?
19690 if (expirationTime === Sync) {
19691 performSyncWork();
19692 } else {
19693 scheduleCallbackWithExpirationTime(root, expirationTime);
19694 }
19695}
19696
19697function addRootToSchedule(root, expirationTime) {
19698 // Add the root to the schedule.
19699 // Check if this root is already part of the schedule.
19700 if (root.nextScheduledRoot === null) {
19701 // This root is not already scheduled. Add it.
19702 root.expirationTime = expirationTime;
19703 if (lastScheduledRoot === null) {
19704 firstScheduledRoot = lastScheduledRoot = root;
19705 root.nextScheduledRoot = root;
19706 } else {
19707 lastScheduledRoot.nextScheduledRoot = root;
19708 lastScheduledRoot = root;
19709 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
19710 }
19711 } else {
19712 // This root is already scheduled, but its priority may have increased.
19713 var remainingExpirationTime = root.expirationTime;
19714 if (expirationTime > remainingExpirationTime) {
19715 // Update the priority.
19716 root.expirationTime = expirationTime;
19717 }
19718 }
19719}
19720
19721function findHighestPriorityRoot() {
19722 var highestPriorityWork = NoWork;
19723 var highestPriorityRoot = null;
19724 if (lastScheduledRoot !== null) {
19725 var previousScheduledRoot = lastScheduledRoot;
19726 var root = firstScheduledRoot;
19727 while (root !== null) {
19728 var remainingExpirationTime = root.expirationTime;
19729 if (remainingExpirationTime === NoWork) {
19730 // This root no longer has work. Remove it from the scheduler.
19731
19732 // TODO: This check is redudant, but Flow is confused by the branch
19733 // below where we set lastScheduledRoot to null, even though we break
19734 // from the loop right after.
19735 !(previousScheduledRoot !== null && lastScheduledRoot !== null) ? invariant(false, 'Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue.') : void 0;
19736 if (root === root.nextScheduledRoot) {
19737 // This is the only root in the list.
19738 root.nextScheduledRoot = null;
19739 firstScheduledRoot = lastScheduledRoot = null;
19740 break;
19741 } else if (root === firstScheduledRoot) {
19742 // This is the first root in the list.
19743 var next = root.nextScheduledRoot;
19744 firstScheduledRoot = next;
19745 lastScheduledRoot.nextScheduledRoot = next;
19746 root.nextScheduledRoot = null;
19747 } else if (root === lastScheduledRoot) {
19748 // This is the last root in the list.
19749 lastScheduledRoot = previousScheduledRoot;
19750 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
19751 root.nextScheduledRoot = null;
19752 break;
19753 } else {
19754 previousScheduledRoot.nextScheduledRoot = root.nextScheduledRoot;
19755 root.nextScheduledRoot = null;
19756 }
19757 root = previousScheduledRoot.nextScheduledRoot;
19758 } else {
19759 if (remainingExpirationTime > highestPriorityWork) {
19760 // Update the priority, if it's higher
19761 highestPriorityWork = remainingExpirationTime;
19762 highestPriorityRoot = root;
19763 }
19764 if (root === lastScheduledRoot) {
19765 break;
19766 }
19767 if (highestPriorityWork === Sync) {
19768 // Sync is highest priority by definition so
19769 // we can stop searching.
19770 break;
19771 }
19772 previousScheduledRoot = root;
19773 root = root.nextScheduledRoot;
19774 }
19775 }
19776 }
19777
19778 nextFlushedRoot = highestPriorityRoot;
19779 nextFlushedExpirationTime = highestPriorityWork;
19780}
19781
19782// TODO: This wrapper exists because many of the older tests (the ones that use
19783// flushDeferredPri) rely on the number of times `shouldYield` is called. We
19784// should get rid of it.
19785var didYield = false;
19786function shouldYieldToRenderer() {
19787 if (didYield) {
19788 return true;
19789 }
19790 if (unstable_shouldYield()) {
19791 didYield = true;
19792 return true;
19793 }
19794 return false;
19795}
19796
19797function performAsyncWork() {
19798 try {
19799 if (!shouldYieldToRenderer()) {
19800 // The callback timed out. That means at least one update has expired.
19801 // Iterate through the root schedule. If they contain expired work, set
19802 // the next render expiration time to the current time. This has the effect
19803 // of flushing all expired work in a single batch, instead of flushing each
19804 // level one at a time.
19805 if (firstScheduledRoot !== null) {
19806 recomputeCurrentRendererTime();
19807 var root = firstScheduledRoot;
19808 do {
19809 didExpireAtExpirationTime(root, currentRendererTime);
19810 // The root schedule is circular, so this is never null.
19811 root = root.nextScheduledRoot;
19812 } while (root !== firstScheduledRoot);
19813 }
19814 }
19815 performWork(NoWork, true);
19816 } finally {
19817 didYield = false;
19818 }
19819}
19820
19821function performSyncWork() {
19822 performWork(Sync, false);
19823}
19824
19825function performWork(minExpirationTime, isYieldy) {
19826 // Keep working on roots until there's no more work, or until there's a higher
19827 // priority event.
19828 findHighestPriorityRoot();
19829
19830 if (isYieldy) {
19831 recomputeCurrentRendererTime();
19832 currentSchedulerTime = currentRendererTime;
19833
19834 if (enableUserTimingAPI) {
19835 var didExpire = nextFlushedExpirationTime > currentRendererTime;
19836 var timeout = expirationTimeToMs(nextFlushedExpirationTime);
19837 stopRequestCallbackTimer(didExpire, timeout);
19838 }
19839
19840 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime && !(didYield && currentRendererTime > nextFlushedExpirationTime)) {
19841 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, currentRendererTime > nextFlushedExpirationTime);
19842 findHighestPriorityRoot();
19843 recomputeCurrentRendererTime();
19844 currentSchedulerTime = currentRendererTime;
19845 }
19846 } else {
19847 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime) {
19848 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false);
19849 findHighestPriorityRoot();
19850 }
19851 }
19852
19853 // We're done flushing work. Either we ran out of time in this callback,
19854 // or there's no more work left with sufficient priority.
19855
19856 // If we're inside a callback, set this to false since we just completed it.
19857 if (isYieldy) {
19858 callbackExpirationTime = NoWork;
19859 callbackID = null;
19860 }
19861 // If there's work left over, schedule a new callback.
19862 if (nextFlushedExpirationTime !== NoWork) {
19863 scheduleCallbackWithExpirationTime(nextFlushedRoot, nextFlushedExpirationTime);
19864 }
19865
19866 // Clean-up.
19867 finishRendering();
19868}
19869
19870function flushRoot(root, expirationTime) {
19871 !!isRendering ? invariant(false, 'work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.') : void 0;
19872 // Perform work on root as if the given expiration time is the current time.
19873 // This has the effect of synchronously flushing all work up to and
19874 // including the given time.
19875 nextFlushedRoot = root;
19876 nextFlushedExpirationTime = expirationTime;
19877 performWorkOnRoot(root, expirationTime, false);
19878 // Flush any sync work that was scheduled by lifecycles
19879 performSyncWork();
19880}
19881
19882function finishRendering() {
19883 nestedUpdateCount = 0;
19884 lastCommittedRootDuringThisBatch = null;
19885
19886 if (completedBatches !== null) {
19887 var batches = completedBatches;
19888 completedBatches = null;
19889 for (var i = 0; i < batches.length; i++) {
19890 var batch = batches[i];
19891 try {
19892 batch._onComplete();
19893 } catch (error) {
19894 if (!hasUnhandledError) {
19895 hasUnhandledError = true;
19896 unhandledError = error;
19897 }
19898 }
19899 }
19900 }
19901
19902 if (hasUnhandledError) {
19903 var error = unhandledError;
19904 unhandledError = null;
19905 hasUnhandledError = false;
19906 throw error;
19907 }
19908}
19909
19910function performWorkOnRoot(root, expirationTime, isYieldy) {
19911 !!isRendering ? invariant(false, 'performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;
19912
19913 isRendering = true;
19914
19915 // Check if this is async work or sync/expired work.
19916 if (!isYieldy) {
19917 // Flush work without yielding.
19918 // TODO: Non-yieldy work does not necessarily imply expired work. A renderer
19919 // may want to perform some work without yielding, but also without
19920 // requiring the root to complete (by triggering placeholders).
19921
19922 var finishedWork = root.finishedWork;
19923 if (finishedWork !== null) {
19924 // This root is already complete. We can commit it.
19925 completeRoot(root, finishedWork, expirationTime);
19926 } else {
19927 root.finishedWork = null;
19928 // If this root previously suspended, clear its existing timeout, since
19929 // we're about to try rendering again.
19930 var timeoutHandle = root.timeoutHandle;
19931 if (timeoutHandle !== noTimeout) {
19932 root.timeoutHandle = noTimeout;
19933 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
19934 cancelTimeout(timeoutHandle);
19935 }
19936 renderRoot(root, isYieldy);
19937 finishedWork = root.finishedWork;
19938 if (finishedWork !== null) {
19939 // We've completed the root. Commit it.
19940 completeRoot(root, finishedWork, expirationTime);
19941 }
19942 }
19943 } else {
19944 // Flush async work.
19945 var _finishedWork = root.finishedWork;
19946 if (_finishedWork !== null) {
19947 // This root is already complete. We can commit it.
19948 completeRoot(root, _finishedWork, expirationTime);
19949 } else {
19950 root.finishedWork = null;
19951 // If this root previously suspended, clear its existing timeout, since
19952 // we're about to try rendering again.
19953 var _timeoutHandle = root.timeoutHandle;
19954 if (_timeoutHandle !== noTimeout) {
19955 root.timeoutHandle = noTimeout;
19956 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
19957 cancelTimeout(_timeoutHandle);
19958 }
19959 renderRoot(root, isYieldy);
19960 _finishedWork = root.finishedWork;
19961 if (_finishedWork !== null) {
19962 // We've completed the root. Check the if we should yield one more time
19963 // before committing.
19964 if (!shouldYieldToRenderer()) {
19965 // Still time left. Commit the root.
19966 completeRoot(root, _finishedWork, expirationTime);
19967 } else {
19968 // There's no time left. Mark this root as complete. We'll come
19969 // back and commit it later.
19970 root.finishedWork = _finishedWork;
19971 }
19972 }
19973 }
19974 }
19975
19976 isRendering = false;
19977}
19978
19979function completeRoot(root, finishedWork, expirationTime) {
19980 // Check if there's a batch that matches this expiration time.
19981 var firstBatch = root.firstBatch;
19982 if (firstBatch !== null && firstBatch._expirationTime >= expirationTime) {
19983 if (completedBatches === null) {
19984 completedBatches = [firstBatch];
19985 } else {
19986 completedBatches.push(firstBatch);
19987 }
19988 if (firstBatch._defer) {
19989 // This root is blocked from committing by a batch. Unschedule it until
19990 // we receive another update.
19991 root.finishedWork = finishedWork;
19992 root.expirationTime = NoWork;
19993 return;
19994 }
19995 }
19996
19997 // Commit the root.
19998 root.finishedWork = null;
19999
20000 // Check if this is a nested update (a sync update scheduled during the
20001 // commit phase).
20002 if (root === lastCommittedRootDuringThisBatch) {
20003 // If the next root is the same as the previous root, this is a nested
20004 // update. To prevent an infinite loop, increment the nested update count.
20005 nestedUpdateCount++;
20006 } else {
20007 // Reset whenever we switch roots.
20008 lastCommittedRootDuringThisBatch = root;
20009 nestedUpdateCount = 0;
20010 }
20011 commitRoot(root, finishedWork);
20012}
20013
20014function onUncaughtError(error) {
20015 !(nextFlushedRoot !== null) ? invariant(false, 'Should be working on a root. This error is likely caused by a bug in React. Please file an issue.') : void 0;
20016 // Unschedule this root so we don't work on it again until there's
20017 // another update.
20018 nextFlushedRoot.expirationTime = NoWork;
20019 if (!hasUnhandledError) {
20020 hasUnhandledError = true;
20021 unhandledError = error;
20022 }
20023}
20024
20025// TODO: Batching should be implemented at the renderer level, not inside
20026// the reconciler.
20027function batchedUpdates$1(fn, a) {
20028 var previousIsBatchingUpdates = isBatchingUpdates;
20029 isBatchingUpdates = true;
20030 try {
20031 return fn(a);
20032 } finally {
20033 isBatchingUpdates = previousIsBatchingUpdates;
20034 if (!isBatchingUpdates && !isRendering) {
20035 performSyncWork();
20036 }
20037 }
20038}
20039
20040// TODO: Batching should be implemented at the renderer level, not inside
20041// the reconciler.
20042function unbatchedUpdates(fn, a) {
20043 if (isBatchingUpdates && !isUnbatchingUpdates) {
20044 isUnbatchingUpdates = true;
20045 try {
20046 return fn(a);
20047 } finally {
20048 isUnbatchingUpdates = false;
20049 }
20050 }
20051 return fn(a);
20052}
20053
20054// TODO: Batching should be implemented at the renderer level, not within
20055// the reconciler.
20056function flushSync(fn, a) {
20057 !!isRendering ? invariant(false, 'flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.') : void 0;
20058 var previousIsBatchingUpdates = isBatchingUpdates;
20059 isBatchingUpdates = true;
20060 try {
20061 return syncUpdates(fn, a);
20062 } finally {
20063 isBatchingUpdates = previousIsBatchingUpdates;
20064 performSyncWork();
20065 }
20066}
20067
20068function interactiveUpdates$1(fn, a, b) {
20069 if (isBatchingInteractiveUpdates) {
20070 return fn(a, b);
20071 }
20072 // If there are any pending interactive updates, synchronously flush them.
20073 // This needs to happen before we read any handlers, because the effect of
20074 // the previous event may influence which handlers are called during
20075 // this event.
20076 if (!isBatchingUpdates && !isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) {
20077 // Synchronously flush pending interactive updates.
20078 performWork(lowestPriorityPendingInteractiveExpirationTime, false);
20079 lowestPriorityPendingInteractiveExpirationTime = NoWork;
20080 }
20081 var previousIsBatchingInteractiveUpdates = isBatchingInteractiveUpdates;
20082 var previousIsBatchingUpdates = isBatchingUpdates;
20083 isBatchingInteractiveUpdates = true;
20084 isBatchingUpdates = true;
20085 try {
20086 return fn(a, b);
20087 } finally {
20088 isBatchingInteractiveUpdates = previousIsBatchingInteractiveUpdates;
20089 isBatchingUpdates = previousIsBatchingUpdates;
20090 if (!isBatchingUpdates && !isRendering) {
20091 performSyncWork();
20092 }
20093 }
20094}
20095
20096function flushInteractiveUpdates$1() {
20097 if (!isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) {
20098 // Synchronously flush pending interactive updates.
20099 performWork(lowestPriorityPendingInteractiveExpirationTime, false);
20100 lowestPriorityPendingInteractiveExpirationTime = NoWork;
20101 }
20102}
20103
20104function flushControlled(fn) {
20105 var previousIsBatchingUpdates = isBatchingUpdates;
20106 isBatchingUpdates = true;
20107 try {
20108 syncUpdates(fn);
20109 } finally {
20110 isBatchingUpdates = previousIsBatchingUpdates;
20111 if (!isBatchingUpdates && !isRendering) {
20112 performSyncWork();
20113 }
20114 }
20115}
20116
20117// 0 is PROD, 1 is DEV.
20118// Might add PROFILE later.
20119
20120
20121var didWarnAboutNestedUpdates = void 0;
20122var didWarnAboutFindNodeInStrictMode = void 0;
20123
20124{
20125 didWarnAboutNestedUpdates = false;
20126 didWarnAboutFindNodeInStrictMode = {};
20127}
20128
20129function getContextForSubtree(parentComponent) {
20130 if (!parentComponent) {
20131 return emptyContextObject;
20132 }
20133
20134 var fiber = get(parentComponent);
20135 var parentContext = findCurrentUnmaskedContext(fiber);
20136
20137 if (fiber.tag === ClassComponent) {
20138 var Component = fiber.type;
20139 if (isContextProvider(Component)) {
20140 return processChildContext(fiber, Component, parentContext);
20141 }
20142 }
20143
20144 return parentContext;
20145}
20146
20147function scheduleRootUpdate(current$$1, element, expirationTime, callback) {
20148 {
20149 if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) {
20150 didWarnAboutNestedUpdates = true;
20151 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');
20152 }
20153 }
20154
20155 var update = createUpdate(expirationTime);
20156 // Caution: React DevTools currently depends on this property
20157 // being called "element".
20158 update.payload = { element: element };
20159
20160 callback = callback === undefined ? null : callback;
20161 if (callback !== null) {
20162 !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
20163 update.callback = callback;
20164 }
20165
20166 flushPassiveEffects();
20167 enqueueUpdate(current$$1, update);
20168 scheduleWork(current$$1, expirationTime);
20169
20170 return expirationTime;
20171}
20172
20173function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback) {
20174 // TODO: If this is a nested container, this won't be the root.
20175 var current$$1 = container.current;
20176
20177 {
20178 if (ReactFiberInstrumentation_1.debugTool) {
20179 if (current$$1.alternate === null) {
20180 ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
20181 } else if (element === null) {
20182 ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
20183 } else {
20184 ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
20185 }
20186 }
20187 }
20188
20189 var context = getContextForSubtree(parentComponent);
20190 if (container.context === null) {
20191 container.context = context;
20192 } else {
20193 container.pendingContext = context;
20194 }
20195
20196 return scheduleRootUpdate(current$$1, element, expirationTime, callback);
20197}
20198
20199function findHostInstance(component) {
20200 var fiber = get(component);
20201 if (fiber === undefined) {
20202 if (typeof component.render === 'function') {
20203 invariant(false, 'Unable to find node on an unmounted component.');
20204 } else {
20205 invariant(false, 'Argument appears to not be a ReactComponent. Keys: %s', Object.keys(component));
20206 }
20207 }
20208 var hostFiber = findCurrentHostFiber(fiber);
20209 if (hostFiber === null) {
20210 return null;
20211 }
20212 return hostFiber.stateNode;
20213}
20214
20215function findHostInstanceWithWarning(component, methodName) {
20216 {
20217 var fiber = get(component);
20218 if (fiber === undefined) {
20219 if (typeof component.render === 'function') {
20220 invariant(false, 'Unable to find node on an unmounted component.');
20221 } else {
20222 invariant(false, 'Argument appears to not be a ReactComponent. Keys: %s', Object.keys(component));
20223 }
20224 }
20225 var hostFiber = findCurrentHostFiber(fiber);
20226 if (hostFiber === null) {
20227 return null;
20228 }
20229 if (hostFiber.mode & StrictMode) {
20230 var componentName = getComponentName(fiber.type) || 'Component';
20231 if (!didWarnAboutFindNodeInStrictMode[componentName]) {
20232 didWarnAboutFindNodeInStrictMode[componentName] = true;
20233 if (fiber.mode & StrictMode) {
20234 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.' + '\n%s' + '\n\nLearn more about using refs safely here:' + '\nhttps://fb.me/react-strict-mode-find-node', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));
20235 } else {
20236 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.' + '\n%s' + '\n\nLearn more about using refs safely here:' + '\nhttps://fb.me/react-strict-mode-find-node', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));
20237 }
20238 }
20239 }
20240 return hostFiber.stateNode;
20241 }
20242 return findHostInstance(component);
20243}
20244
20245function createContainer(containerInfo, isConcurrent, hydrate) {
20246 return createFiberRoot(containerInfo, isConcurrent, hydrate);
20247}
20248
20249function updateContainer(element, container, parentComponent, callback) {
20250 var current$$1 = container.current;
20251 var currentTime = requestCurrentTime();
20252 var expirationTime = computeExpirationForFiber(currentTime, current$$1);
20253 return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback);
20254}
20255
20256function getPublicRootInstance(container) {
20257 var containerFiber = container.current;
20258 if (!containerFiber.child) {
20259 return null;
20260 }
20261 switch (containerFiber.child.tag) {
20262 case HostComponent:
20263 return getPublicInstance(containerFiber.child.stateNode);
20264 default:
20265 return containerFiber.child.stateNode;
20266 }
20267}
20268
20269function findHostInstanceWithNoPortals(fiber) {
20270 var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
20271 if (hostFiber === null) {
20272 return null;
20273 }
20274 return hostFiber.stateNode;
20275}
20276
20277var overrideProps = null;
20278
20279{
20280 var copyWithSetImpl = function (obj, path, idx, value) {
20281 if (idx >= path.length) {
20282 return value;
20283 }
20284 var key = path[idx];
20285 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
20286 // $FlowFixMe number or string is fine here
20287 updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
20288 return updated;
20289 };
20290
20291 var copyWithSet = function (obj, path, value) {
20292 return copyWithSetImpl(obj, path, 0, value);
20293 };
20294
20295 // Support DevTools props for function components, forwardRef, memo, host components, etc.
20296 overrideProps = function (fiber, path, value) {
20297 flushPassiveEffects();
20298 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
20299 if (fiber.alternate) {
20300 fiber.alternate.pendingProps = fiber.pendingProps;
20301 }
20302 scheduleWork(fiber, Sync);
20303 };
20304}
20305
20306function injectIntoDevTools(devToolsConfig) {
20307 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
20308 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
20309
20310
20311 return injectInternals(_assign({}, devToolsConfig, {
20312 overrideProps: overrideProps,
20313 currentDispatcherRef: ReactCurrentDispatcher,
20314 findHostInstanceByFiber: function (fiber) {
20315 var hostFiber = findCurrentHostFiber(fiber);
20316 if (hostFiber === null) {
20317 return null;
20318 }
20319 return hostFiber.stateNode;
20320 },
20321 findFiberByHostInstance: function (instance) {
20322 if (!findFiberByHostInstance) {
20323 // Might not be implemented by the renderer.
20324 return null;
20325 }
20326 return findFiberByHostInstance(instance);
20327 }
20328 }));
20329}
20330
20331// This file intentionally does *not* have the Flow annotation.
20332// Don't add it. See `./inline-typed.js` for an explanation.
20333
20334function createPortal$1(children, containerInfo,
20335// TODO: figure out the API for cross-renderer implementation.
20336implementation) {
20337 var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
20338
20339 return {
20340 // This tag allow us to uniquely identify this as a React Portal
20341 $$typeof: REACT_PORTAL_TYPE,
20342 key: key == null ? null : '' + key,
20343 children: children,
20344 containerInfo: containerInfo,
20345 implementation: implementation
20346 };
20347}
20348
20349// TODO: this is special because it gets imported during build.
20350
20351var ReactVersion = '16.8.1';
20352
20353// TODO: This type is shared between the reconciler and ReactDOM, but will
20354// eventually be lifted out to the renderer.
20355
20356var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
20357
20358var topLevelUpdateWarnings = void 0;
20359var warnOnInvalidCallback = void 0;
20360var didWarnAboutUnstableCreatePortal = false;
20361
20362{
20363 if (typeof Map !== 'function' ||
20364 // $FlowIssue Flow incorrectly thinks Map has no prototype
20365 Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' ||
20366 // $FlowIssue Flow incorrectly thinks Set has no prototype
20367 Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
20368 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');
20369 }
20370
20371 topLevelUpdateWarnings = function (container) {
20372 if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
20373 var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
20374 if (hostInstance) {
20375 !(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;
20376 }
20377 }
20378
20379 var isRootRenderedBySomeReact = !!container._reactRootContainer;
20380 var rootEl = getReactRootElementInContainer(container);
20381 var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));
20382
20383 !(!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;
20384
20385 !(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;
20386 };
20387
20388 warnOnInvalidCallback = function (callback, callerName) {
20389 !(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;
20390 };
20391}
20392
20393setRestoreImplementation(restoreControlledState$1);
20394
20395function ReactBatch(root) {
20396 var expirationTime = computeUniqueAsyncExpiration();
20397 this._expirationTime = expirationTime;
20398 this._root = root;
20399 this._next = null;
20400 this._callbacks = null;
20401 this._didComplete = false;
20402 this._hasChildren = false;
20403 this._children = null;
20404 this._defer = true;
20405}
20406ReactBatch.prototype.render = function (children) {
20407 !this._defer ? invariant(false, 'batch.render: Cannot render a batch that already committed.') : void 0;
20408 this._hasChildren = true;
20409 this._children = children;
20410 var internalRoot = this._root._internalRoot;
20411 var expirationTime = this._expirationTime;
20412 var work = new ReactWork();
20413 updateContainerAtExpirationTime(children, internalRoot, null, expirationTime, work._onCommit);
20414 return work;
20415};
20416ReactBatch.prototype.then = function (onComplete) {
20417 if (this._didComplete) {
20418 onComplete();
20419 return;
20420 }
20421 var callbacks = this._callbacks;
20422 if (callbacks === null) {
20423 callbacks = this._callbacks = [];
20424 }
20425 callbacks.push(onComplete);
20426};
20427ReactBatch.prototype.commit = function () {
20428 var internalRoot = this._root._internalRoot;
20429 var firstBatch = internalRoot.firstBatch;
20430 !(this._defer && firstBatch !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0;
20431
20432 if (!this._hasChildren) {
20433 // This batch is empty. Return.
20434 this._next = null;
20435 this._defer = false;
20436 return;
20437 }
20438
20439 var expirationTime = this._expirationTime;
20440
20441 // Ensure this is the first batch in the list.
20442 if (firstBatch !== this) {
20443 // This batch is not the earliest batch. We need to move it to the front.
20444 // Update its expiration time to be the expiration time of the earliest
20445 // batch, so that we can flush it without flushing the other batches.
20446 if (this._hasChildren) {
20447 expirationTime = this._expirationTime = firstBatch._expirationTime;
20448 // Rendering this batch again ensures its children will be the final state
20449 // when we flush (updates are processed in insertion order: last
20450 // update wins).
20451 // TODO: This forces a restart. Should we print a warning?
20452 this.render(this._children);
20453 }
20454
20455 // Remove the batch from the list.
20456 var previous = null;
20457 var batch = firstBatch;
20458 while (batch !== this) {
20459 previous = batch;
20460 batch = batch._next;
20461 }
20462 !(previous !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0;
20463 previous._next = batch._next;
20464
20465 // Add it to the front.
20466 this._next = firstBatch;
20467 firstBatch = internalRoot.firstBatch = this;
20468 }
20469
20470 // Synchronously flush all the work up to this batch's expiration time.
20471 this._defer = false;
20472 flushRoot(internalRoot, expirationTime);
20473
20474 // Pop the batch from the list.
20475 var next = this._next;
20476 this._next = null;
20477 firstBatch = internalRoot.firstBatch = next;
20478
20479 // Append the next earliest batch's children to the update queue.
20480 if (firstBatch !== null && firstBatch._hasChildren) {
20481 firstBatch.render(firstBatch._children);
20482 }
20483};
20484ReactBatch.prototype._onComplete = function () {
20485 if (this._didComplete) {
20486 return;
20487 }
20488 this._didComplete = true;
20489 var callbacks = this._callbacks;
20490 if (callbacks === null) {
20491 return;
20492 }
20493 // TODO: Error handling.
20494 for (var i = 0; i < callbacks.length; i++) {
20495 var _callback = callbacks[i];
20496 _callback();
20497 }
20498};
20499
20500function ReactWork() {
20501 this._callbacks = null;
20502 this._didCommit = false;
20503 // TODO: Avoid need to bind by replacing callbacks in the update queue with
20504 // list of Work objects.
20505 this._onCommit = this._onCommit.bind(this);
20506}
20507ReactWork.prototype.then = function (onCommit) {
20508 if (this._didCommit) {
20509 onCommit();
20510 return;
20511 }
20512 var callbacks = this._callbacks;
20513 if (callbacks === null) {
20514 callbacks = this._callbacks = [];
20515 }
20516 callbacks.push(onCommit);
20517};
20518ReactWork.prototype._onCommit = function () {
20519 if (this._didCommit) {
20520 return;
20521 }
20522 this._didCommit = true;
20523 var callbacks = this._callbacks;
20524 if (callbacks === null) {
20525 return;
20526 }
20527 // TODO: Error handling.
20528 for (var i = 0; i < callbacks.length; i++) {
20529 var _callback2 = callbacks[i];
20530 !(typeof _callback2 === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', _callback2) : void 0;
20531 _callback2();
20532 }
20533};
20534
20535function ReactRoot(container, isConcurrent, hydrate) {
20536 var root = createContainer(container, isConcurrent, hydrate);
20537 this._internalRoot = root;
20538}
20539ReactRoot.prototype.render = function (children, callback) {
20540 var root = this._internalRoot;
20541 var work = new ReactWork();
20542 callback = callback === undefined ? null : callback;
20543 {
20544 warnOnInvalidCallback(callback, 'render');
20545 }
20546 if (callback !== null) {
20547 work.then(callback);
20548 }
20549 updateContainer(children, root, null, work._onCommit);
20550 return work;
20551};
20552ReactRoot.prototype.unmount = function (callback) {
20553 var root = this._internalRoot;
20554 var work = new ReactWork();
20555 callback = callback === undefined ? null : callback;
20556 {
20557 warnOnInvalidCallback(callback, 'render');
20558 }
20559 if (callback !== null) {
20560 work.then(callback);
20561 }
20562 updateContainer(null, root, null, work._onCommit);
20563 return work;
20564};
20565ReactRoot.prototype.legacy_renderSubtreeIntoContainer = function (parentComponent, children, callback) {
20566 var root = this._internalRoot;
20567 var work = new ReactWork();
20568 callback = callback === undefined ? null : callback;
20569 {
20570 warnOnInvalidCallback(callback, 'render');
20571 }
20572 if (callback !== null) {
20573 work.then(callback);
20574 }
20575 updateContainer(children, root, parentComponent, work._onCommit);
20576 return work;
20577};
20578ReactRoot.prototype.createBatch = function () {
20579 var batch = new ReactBatch(this);
20580 var expirationTime = batch._expirationTime;
20581
20582 var internalRoot = this._internalRoot;
20583 var firstBatch = internalRoot.firstBatch;
20584 if (firstBatch === null) {
20585 internalRoot.firstBatch = batch;
20586 batch._next = null;
20587 } else {
20588 // Insert sorted by expiration time then insertion order
20589 var insertAfter = null;
20590 var insertBefore = firstBatch;
20591 while (insertBefore !== null && insertBefore._expirationTime >= expirationTime) {
20592 insertAfter = insertBefore;
20593 insertBefore = insertBefore._next;
20594 }
20595 batch._next = insertBefore;
20596 if (insertAfter !== null) {
20597 insertAfter._next = batch;
20598 }
20599 }
20600
20601 return batch;
20602};
20603
20604/**
20605 * True if the supplied DOM node is a valid node element.
20606 *
20607 * @param {?DOMElement} node The candidate DOM node.
20608 * @return {boolean} True if the DOM is a valid DOM node.
20609 * @internal
20610 */
20611function isValidContainer(node) {
20612 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 '));
20613}
20614
20615function getReactRootElementInContainer(container) {
20616 if (!container) {
20617 return null;
20618 }
20619
20620 if (container.nodeType === DOCUMENT_NODE) {
20621 return container.documentElement;
20622 } else {
20623 return container.firstChild;
20624 }
20625}
20626
20627function shouldHydrateDueToLegacyHeuristic(container) {
20628 var rootElement = getReactRootElementInContainer(container);
20629 return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
20630}
20631
20632setBatchingImplementation(batchedUpdates$1, interactiveUpdates$1, flushInteractiveUpdates$1);
20633
20634var warnedAboutHydrateAPI = false;
20635
20636function legacyCreateRootFromDOMContainer(container, forceHydrate) {
20637 var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container);
20638 // First clear any existing content.
20639 if (!shouldHydrate) {
20640 var warned = false;
20641 var rootSibling = void 0;
20642 while (rootSibling = container.lastChild) {
20643 {
20644 if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
20645 warned = true;
20646 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.');
20647 }
20648 }
20649 container.removeChild(rootSibling);
20650 }
20651 }
20652 {
20653 if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
20654 warnedAboutHydrateAPI = true;
20655 lowPriorityWarning$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.');
20656 }
20657 }
20658 // Legacy roots are not async by default.
20659 var isConcurrent = false;
20660 return new ReactRoot(container, isConcurrent, shouldHydrate);
20661}
20662
20663function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
20664 {
20665 topLevelUpdateWarnings(container);
20666 }
20667
20668 // TODO: Without `any` type, Flow says "Property cannot be accessed on any
20669 // member of intersection type." Whyyyyyy.
20670 var root = container._reactRootContainer;
20671 if (!root) {
20672 // Initial mount
20673 root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
20674 if (typeof callback === 'function') {
20675 var originalCallback = callback;
20676 callback = function () {
20677 var instance = getPublicRootInstance(root._internalRoot);
20678 originalCallback.call(instance);
20679 };
20680 }
20681 // Initial mount should not be batched.
20682 unbatchedUpdates(function () {
20683 if (parentComponent != null) {
20684 root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
20685 } else {
20686 root.render(children, callback);
20687 }
20688 });
20689 } else {
20690 if (typeof callback === 'function') {
20691 var _originalCallback = callback;
20692 callback = function () {
20693 var instance = getPublicRootInstance(root._internalRoot);
20694 _originalCallback.call(instance);
20695 };
20696 }
20697 // Update
20698 if (parentComponent != null) {
20699 root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
20700 } else {
20701 root.render(children, callback);
20702 }
20703 }
20704 return getPublicRootInstance(root._internalRoot);
20705}
20706
20707function createPortal$$1(children, container) {
20708 var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
20709
20710 !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;
20711 // TODO: pass ReactDOM portal implementation as third argument
20712 return createPortal$1(children, container, null, key);
20713}
20714
20715var ReactDOM = {
20716 createPortal: createPortal$$1,
20717
20718 findDOMNode: function (componentOrElement) {
20719 {
20720 var owner = ReactCurrentOwner.current;
20721 if (owner !== null && owner.stateNode !== null) {
20722 var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
20723 !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;
20724 owner.stateNode._warnedAboutRefsInRender = true;
20725 }
20726 }
20727 if (componentOrElement == null) {
20728 return null;
20729 }
20730 if (componentOrElement.nodeType === ELEMENT_NODE) {
20731 return componentOrElement;
20732 }
20733 {
20734 return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
20735 }
20736 return findHostInstance(componentOrElement);
20737 },
20738 hydrate: function (element, container, callback) {
20739 !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;
20740 {
20741 !!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 root.render(element, {hydrate: true})?', enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot') : void 0;
20742 }
20743 // TODO: throw or warn if we couldn't hydrate?
20744 return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
20745 },
20746 render: function (element, container, callback) {
20747 !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;
20748 {
20749 !!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;
20750 }
20751 return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
20752 },
20753 unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) {
20754 !isValidContainer(containerNode) ? invariant(false, 'Target container is not a DOM element.') : void 0;
20755 !(parentComponent != null && has(parentComponent)) ? invariant(false, 'parentComponent must be a valid React Component') : void 0;
20756 return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
20757 },
20758 unmountComponentAtNode: function (container) {
20759 !isValidContainer(container) ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : void 0;
20760
20761 {
20762 !!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;
20763 }
20764
20765 if (container._reactRootContainer) {
20766 {
20767 var rootEl = getReactRootElementInContainer(container);
20768 var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);
20769 !!renderedByDifferentReact ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0;
20770 }
20771
20772 // Unmount should not be batched.
20773 unbatchedUpdates(function () {
20774 legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
20775 container._reactRootContainer = null;
20776 });
20777 });
20778 // If you call unmountComponentAtNode twice in quick succession, you'll
20779 // get `true` twice. That's probably fine?
20780 return true;
20781 } else {
20782 {
20783 var _rootEl = getReactRootElementInContainer(container);
20784 var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl));
20785
20786 // Check if the container itself is a React root node.
20787 var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;
20788
20789 !!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;
20790 }
20791
20792 return false;
20793 }
20794 },
20795
20796
20797 // Temporary alias since we already shipped React 16 RC with it.
20798 // TODO: remove in React 17.
20799 unstable_createPortal: function () {
20800 if (!didWarnAboutUnstableCreatePortal) {
20801 didWarnAboutUnstableCreatePortal = true;
20802 lowPriorityWarning$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.');
20803 }
20804 return createPortal$$1.apply(undefined, arguments);
20805 },
20806
20807
20808 unstable_batchedUpdates: batchedUpdates$1,
20809
20810 unstable_interactiveUpdates: interactiveUpdates$1,
20811
20812 flushSync: flushSync,
20813
20814 unstable_createRoot: createRoot,
20815 unstable_flushControlled: flushControlled,
20816
20817 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
20818 // Keep in sync with ReactDOMUnstableNativeDependencies.js
20819 // and ReactTestUtils.js. This is an array for better minification.
20820 Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injection.injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch]
20821 }
20822};
20823
20824function createRoot(container, options) {
20825 var functionName = enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot';
20826 !isValidContainer(container) ? invariant(false, '%s(...): Target container is not a DOM element.', functionName) : void 0;
20827 {
20828 !!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;
20829 container._reactHasBeenPassedToCreateRootDEV = true;
20830 }
20831 var hydrate = options != null && options.hydrate === true;
20832 return new ReactRoot(container, true, hydrate);
20833}
20834
20835if (enableStableConcurrentModeAPIs) {
20836 ReactDOM.createRoot = createRoot;
20837 ReactDOM.unstable_createRoot = undefined;
20838}
20839
20840var foundDevTools = injectIntoDevTools({
20841 findFiberByHostInstance: getClosestInstanceFromNode,
20842 bundleType: 1,
20843 version: ReactVersion,
20844 rendererPackageName: 'react-dom'
20845});
20846
20847{
20848 if (!foundDevTools && canUseDOM && window.top === window.self) {
20849 // If we're in Chrome or Firefox, provide a download link if not installed.
20850 if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
20851 var protocol = window.location.protocol;
20852 // Don't warn in exotic cases like chrome-extension://.
20853 if (/^(https?|file):$/.test(protocol)) {
20854 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');
20855 }
20856 }
20857 }
20858}
20859
20860
20861
20862var ReactDOM$2 = Object.freeze({
20863 default: ReactDOM
20864});
20865
20866var ReactDOM$3 = ( ReactDOM$2 && ReactDOM ) || ReactDOM$2;
20867
20868// TODO: decide on the top-level export form.
20869// This is hacky but makes it work with both Rollup and Jest.
20870var reactDom = ReactDOM$3.default || ReactDOM$3;
20871
20872return reactDom;
20873
20874})));