UNPKG

791 kBJavaScriptView Raw
1/** @license React v16.8.5
2 * react-dom-unstable-fire.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.ReactFire = 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 // unintuitive, 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;
839var DehydratedSuspenseComponent = 18;
840
841var randomKey = Math.random().toString(36).slice(2);
842var internalInstanceKey = '__reactInternalInstance$' + randomKey;
843var internalEventHandlersKey = '__reactEventHandlers$' + randomKey;
844
845function precacheFiberNode(hostInst, node) {
846 node[internalInstanceKey] = hostInst;
847}
848
849/**
850 * Given a DOM node, return the closest ReactDOMComponent or
851 * ReactDOMTextComponent instance ancestor.
852 */
853function getClosestInstanceFromNode(node) {
854 if (node[internalInstanceKey]) {
855 return node[internalInstanceKey];
856 }
857
858 while (!node[internalInstanceKey]) {
859 if (node.parentNode) {
860 node = node.parentNode;
861 } else {
862 // Top of the tree. This node must not be part of a React tree (or is
863 // unmounted, potentially).
864 return null;
865 }
866 }
867
868 var inst = node[internalInstanceKey];
869 if (inst.tag === HostComponent || inst.tag === HostText) {
870 // In Fiber, this will always be the deepest root.
871 return inst;
872 }
873
874 return null;
875}
876
877/**
878 * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
879 * instance, or null if the node was not rendered by this React.
880 */
881function getInstanceFromNode$1(node) {
882 var inst = node[internalInstanceKey];
883 if (inst) {
884 if (inst.tag === HostComponent || inst.tag === HostText) {
885 return inst;
886 } else {
887 return null;
888 }
889 }
890 return null;
891}
892
893/**
894 * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
895 * DOM node.
896 */
897function getNodeFromInstance$1(inst) {
898 if (inst.tag === HostComponent || inst.tag === HostText) {
899 // In Fiber this, is just the state node right now. We assume it will be
900 // a host component or host text.
901 return inst.stateNode;
902 }
903
904 // Without this first invariant, passing a non-DOM-component triggers the next
905 // invariant for a missing parent, which is super confusing.
906 invariant(false, 'getNodeFromInstance: Invalid argument.');
907}
908
909function getFiberCurrentPropsFromNode$1(node) {
910 return node[internalEventHandlersKey] || null;
911}
912
913function updateFiberProps(node, props) {
914 node[internalEventHandlersKey] = props;
915}
916
917function getParent(inst) {
918 do {
919 inst = inst.return;
920 // TODO: If this is a HostRoot we might want to bail out.
921 // That is depending on if we want nested subtrees (layers) to bubble
922 // events to their parent. We could also go through parentNode on the
923 // host node but that wouldn't work for React Native and doesn't let us
924 // do the portal feature.
925 } while (inst && inst.tag !== HostComponent);
926 if (inst) {
927 return inst;
928 }
929 return null;
930}
931
932/**
933 * Return the lowest common ancestor of A and B, or null if they are in
934 * different trees.
935 */
936function getLowestCommonAncestor(instA, instB) {
937 var depthA = 0;
938 for (var tempA = instA; tempA; tempA = getParent(tempA)) {
939 depthA++;
940 }
941 var depthB = 0;
942 for (var tempB = instB; tempB; tempB = getParent(tempB)) {
943 depthB++;
944 }
945
946 // If A is deeper, crawl up.
947 while (depthA - depthB > 0) {
948 instA = getParent(instA);
949 depthA--;
950 }
951
952 // If B is deeper, crawl up.
953 while (depthB - depthA > 0) {
954 instB = getParent(instB);
955 depthB--;
956 }
957
958 // Walk in lockstep until we find a match.
959 var depth = depthA;
960 while (depth--) {
961 if (instA === instB || instA === instB.alternate) {
962 return instA;
963 }
964 instA = getParent(instA);
965 instB = getParent(instB);
966 }
967 return null;
968}
969
970/**
971 * Return if A is an ancestor of B.
972 */
973
974
975/**
976 * Return the parent instance of the passed-in instance.
977 */
978
979
980/**
981 * Simulates the traversal of a two-phase, capture/bubble event dispatch.
982 */
983function traverseTwoPhase(inst, fn, arg) {
984 var path = [];
985 while (inst) {
986 path.push(inst);
987 inst = getParent(inst);
988 }
989 var i = void 0;
990 for (i = path.length; i-- > 0;) {
991 fn(path[i], 'captured', arg);
992 }
993 for (i = 0; i < path.length; i++) {
994 fn(path[i], 'bubbled', arg);
995 }
996}
997
998/**
999 * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
1000 * should would receive a `mouseEnter` or `mouseLeave` event.
1001 *
1002 * Does not invoke the callback on the nearest common ancestor because nothing
1003 * "entered" or "left" that element.
1004 */
1005function traverseEnterLeave(from, to, fn, argFrom, argTo) {
1006 var common = from && to ? getLowestCommonAncestor(from, to) : null;
1007 var pathFrom = [];
1008 while (true) {
1009 if (!from) {
1010 break;
1011 }
1012 if (from === common) {
1013 break;
1014 }
1015 var alternate = from.alternate;
1016 if (alternate !== null && alternate === common) {
1017 break;
1018 }
1019 pathFrom.push(from);
1020 from = getParent(from);
1021 }
1022 var pathTo = [];
1023 while (true) {
1024 if (!to) {
1025 break;
1026 }
1027 if (to === common) {
1028 break;
1029 }
1030 var _alternate = to.alternate;
1031 if (_alternate !== null && _alternate === common) {
1032 break;
1033 }
1034 pathTo.push(to);
1035 to = getParent(to);
1036 }
1037 for (var i = 0; i < pathFrom.length; i++) {
1038 fn(pathFrom[i], 'bubbled', argFrom);
1039 }
1040 for (var _i = pathTo.length; _i-- > 0;) {
1041 fn(pathTo[_i], 'captured', argTo);
1042 }
1043}
1044
1045/**
1046 * Some event types have a notion of different registration names for different
1047 * "phases" of propagation. This finds listeners by a given phase.
1048 */
1049function listenerAtPhase(inst, event, propagationPhase) {
1050 var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
1051 return getListener(inst, registrationName);
1052}
1053
1054/**
1055 * A small set of propagation patterns, each of which will accept a small amount
1056 * of information, and generate a set of "dispatch ready event objects" - which
1057 * are sets of events that have already been annotated with a set of dispatched
1058 * listener functions/ids. The API is designed this way to discourage these
1059 * propagation strategies from actually executing the dispatches, since we
1060 * always want to collect the entire set of dispatches before executing even a
1061 * single one.
1062 */
1063
1064/**
1065 * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
1066 * here, allows us to not have to bind or create functions for each event.
1067 * Mutating the event's members allows us to not have to create a wrapping
1068 * "dispatch" object that pairs the event with the listener.
1069 */
1070function accumulateDirectionalDispatches(inst, phase, event) {
1071 {
1072 !inst ? warningWithoutStack$1(false, 'Dispatching inst must not be null') : void 0;
1073 }
1074 var listener = listenerAtPhase(inst, event, phase);
1075 if (listener) {
1076 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
1077 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
1078 }
1079}
1080
1081/**
1082 * Collect dispatches (must be entirely collected before dispatching - see unit
1083 * tests). Lazily allocate the array to conserve memory. We must loop through
1084 * each event and perform the traversal for each one. We cannot perform a
1085 * single traversal for the entire collection of events because each event may
1086 * have a different target.
1087 */
1088function accumulateTwoPhaseDispatchesSingle(event) {
1089 if (event && event.dispatchConfig.phasedRegistrationNames) {
1090 traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
1091 }
1092}
1093
1094/**
1095 * Accumulates without regard to direction, does not look for phased
1096 * registration names. Same as `accumulateDirectDispatchesSingle` but without
1097 * requiring that the `dispatchMarker` be the same as the dispatched ID.
1098 */
1099function accumulateDispatches(inst, ignoredDirection, event) {
1100 if (inst && event && event.dispatchConfig.registrationName) {
1101 var registrationName = event.dispatchConfig.registrationName;
1102 var listener = getListener(inst, registrationName);
1103 if (listener) {
1104 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
1105 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
1106 }
1107 }
1108}
1109
1110/**
1111 * Accumulates dispatches on an `SyntheticEvent`, but only for the
1112 * `dispatchMarker`.
1113 * @param {SyntheticEvent} event
1114 */
1115function accumulateDirectDispatchesSingle(event) {
1116 if (event && event.dispatchConfig.registrationName) {
1117 accumulateDispatches(event._targetInst, null, event);
1118 }
1119}
1120
1121function accumulateTwoPhaseDispatches(events) {
1122 forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
1123}
1124
1125
1126
1127function accumulateEnterLeaveDispatches(leave, enter, from, to) {
1128 traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
1129}
1130
1131function accumulateDirectDispatches(events) {
1132 forEachAccumulated(events, accumulateDirectDispatchesSingle);
1133}
1134
1135var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
1136
1137// Do not uses the below two methods directly!
1138// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.
1139// (It is the only module that is allowed to access these methods.)
1140
1141function unsafeCastStringToDOMTopLevelType(topLevelType) {
1142 return topLevelType;
1143}
1144
1145function unsafeCastDOMTopLevelTypeToString(topLevelType) {
1146 return topLevelType;
1147}
1148
1149/**
1150 * Generate a mapping of standard vendor prefixes using the defined style property and event name.
1151 *
1152 * @param {string} styleProp
1153 * @param {string} eventName
1154 * @returns {object}
1155 */
1156function makePrefixMap(styleProp, eventName) {
1157 var prefixes = {};
1158
1159 prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
1160 prefixes['Webkit' + styleProp] = 'webkit' + eventName;
1161 prefixes['Moz' + styleProp] = 'moz' + eventName;
1162
1163 return prefixes;
1164}
1165
1166/**
1167 * A list of event names to a configurable list of vendor prefixes.
1168 */
1169var vendorPrefixes = {
1170 animationend: makePrefixMap('Animation', 'AnimationEnd'),
1171 animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
1172 animationstart: makePrefixMap('Animation', 'AnimationStart'),
1173 transitionend: makePrefixMap('Transition', 'TransitionEnd')
1174};
1175
1176/**
1177 * Event names that have already been detected and prefixed (if applicable).
1178 */
1179var prefixedEventNames = {};
1180
1181/**
1182 * Element to check for prefixes on.
1183 */
1184var style = {};
1185
1186/**
1187 * Bootstrap if a DOM exists.
1188 */
1189if (canUseDOM) {
1190 style = document.createElement('div').style;
1191
1192 // On some platforms, in particular some releases of Android 4.x,
1193 // the un-prefixed "animation" and "transition" properties are defined on the
1194 // style object but the events that fire will still be prefixed, so we need
1195 // to check if the un-prefixed events are usable, and if not remove them from the map.
1196 if (!('AnimationEvent' in window)) {
1197 delete vendorPrefixes.animationend.animation;
1198 delete vendorPrefixes.animationiteration.animation;
1199 delete vendorPrefixes.animationstart.animation;
1200 }
1201
1202 // Same as above
1203 if (!('TransitionEvent' in window)) {
1204 delete vendorPrefixes.transitionend.transition;
1205 }
1206}
1207
1208/**
1209 * Attempts to determine the correct vendor prefixed event name.
1210 *
1211 * @param {string} eventName
1212 * @returns {string}
1213 */
1214function getVendorPrefixedEventName(eventName) {
1215 if (prefixedEventNames[eventName]) {
1216 return prefixedEventNames[eventName];
1217 } else if (!vendorPrefixes[eventName]) {
1218 return eventName;
1219 }
1220
1221 var prefixMap = vendorPrefixes[eventName];
1222
1223 for (var styleProp in prefixMap) {
1224 if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
1225 return prefixedEventNames[eventName] = prefixMap[styleProp];
1226 }
1227 }
1228
1229 return eventName;
1230}
1231
1232/**
1233 * To identify top level events in ReactDOM, we use constants defined by this
1234 * module. This is the only module that uses the unsafe* methods to express
1235 * that the constants actually correspond to the browser event names. This lets
1236 * us save some bundle size by avoiding a top level type -> event name map.
1237 * The rest of ReactDOM code should import top level types from this file.
1238 */
1239var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
1240var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
1241var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));
1242var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
1243var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
1244var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
1245var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
1246var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
1247var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
1248var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
1249var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
1250var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
1251var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');
1252var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');
1253var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
1254var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
1255var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
1256var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
1257var TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick');
1258var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
1259var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
1260var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
1261var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
1262var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
1263var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
1264var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
1265var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
1266var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
1267var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
1268var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
1269var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
1270var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
1271var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
1272var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture');
1273var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
1274var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid');
1275var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
1276var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
1277var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
1278var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
1279var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
1280var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
1281var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
1282var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture');
1283var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
1284var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
1285var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
1286var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
1287var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
1288var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
1289var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
1290var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
1291var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
1292var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel');
1293var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown');
1294
1295
1296var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove');
1297var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout');
1298var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover');
1299var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup');
1300var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
1301var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
1302var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset');
1303var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
1304var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
1305var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
1306var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
1307var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
1308var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit');
1309var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
1310var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
1311var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
1312var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
1313var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
1314var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
1315var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
1316var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
1317var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
1318var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
1319var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
1320var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel');
1321
1322// List of events that need to be individually attached to media elements.
1323// Note that events in this list will *not* be listened to at the top level
1324// unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.
1325var 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];
1326
1327function getRawEventName(topLevelType) {
1328 return unsafeCastDOMTopLevelTypeToString(topLevelType);
1329}
1330
1331/**
1332 * These variables store information about text content of a target node,
1333 * allowing comparison of content before and after a given event.
1334 *
1335 * Identify the node where selection currently begins, then observe
1336 * both its text content and its current position in the DOM. Since the
1337 * browser may natively replace the target node during composition, we can
1338 * use its position to find its replacement.
1339 *
1340 *
1341 */
1342
1343var root = null;
1344var startText = null;
1345var fallbackText = null;
1346
1347function initialize(nativeEventTarget) {
1348 root = nativeEventTarget;
1349 startText = getText();
1350 return true;
1351}
1352
1353function reset() {
1354 root = null;
1355 startText = null;
1356 fallbackText = null;
1357}
1358
1359function getData() {
1360 if (fallbackText) {
1361 return fallbackText;
1362 }
1363
1364 var start = void 0;
1365 var startValue = startText;
1366 var startLength = startValue.length;
1367 var end = void 0;
1368 var endValue = getText();
1369 var endLength = endValue.length;
1370
1371 for (start = 0; start < startLength; start++) {
1372 if (startValue[start] !== endValue[start]) {
1373 break;
1374 }
1375 }
1376
1377 var minEnd = startLength - start;
1378 for (end = 1; end <= minEnd; end++) {
1379 if (startValue[startLength - end] !== endValue[endLength - end]) {
1380 break;
1381 }
1382 }
1383
1384 var sliceTail = end > 1 ? 1 - end : undefined;
1385 fallbackText = endValue.slice(start, sliceTail);
1386 return fallbackText;
1387}
1388
1389function getText() {
1390 if ('value' in root) {
1391 return root.value;
1392 }
1393 return root.textContent;
1394}
1395
1396var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1397
1398var _assign = ReactInternals.assign;
1399
1400/* eslint valid-typeof: 0 */
1401
1402var EVENT_POOL_SIZE = 10;
1403
1404/**
1405 * @interface Event
1406 * @see http://www.w3.org/TR/DOM-Level-3-Events/
1407 */
1408var EventInterface = {
1409 type: null,
1410 target: null,
1411 // currentTarget is set when dispatching; no use in copying it here
1412 currentTarget: function () {
1413 return null;
1414 },
1415 eventPhase: null,
1416 bubbles: null,
1417 cancelable: null,
1418 timeStamp: function (event) {
1419 return event.timeStamp || Date.now();
1420 },
1421 defaultPrevented: null,
1422 isTrusted: null
1423};
1424
1425function functionThatReturnsTrue() {
1426 return true;
1427}
1428
1429function functionThatReturnsFalse() {
1430 return false;
1431}
1432
1433/**
1434 * Synthetic events are dispatched by event plugins, typically in response to a
1435 * top-level event delegation handler.
1436 *
1437 * These systems should generally use pooling to reduce the frequency of garbage
1438 * collection. The system should check `isPersistent` to determine whether the
1439 * event should be released into the pool after being dispatched. Users that
1440 * need a persisted event should invoke `persist`.
1441 *
1442 * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
1443 * normalizing browser quirks. Subclasses do not necessarily have to implement a
1444 * DOM interface; custom application-specific events can also subclass this.
1445 *
1446 * @param {object} dispatchConfig Configuration used to dispatch this event.
1447 * @param {*} targetInst Marker identifying the event target.
1448 * @param {object} nativeEvent Native browser event.
1449 * @param {DOMEventTarget} nativeEventTarget Target node.
1450 */
1451function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
1452 {
1453 // these have a getter/setter for warnings
1454 delete this.nativeEvent;
1455 delete this.preventDefault;
1456 delete this.stopPropagation;
1457 delete this.isDefaultPrevented;
1458 delete this.isPropagationStopped;
1459 }
1460
1461 this.dispatchConfig = dispatchConfig;
1462 this._targetInst = targetInst;
1463 this.nativeEvent = nativeEvent;
1464
1465 var Interface = this.constructor.Interface;
1466 for (var propName in Interface) {
1467 if (!Interface.hasOwnProperty(propName)) {
1468 continue;
1469 }
1470 {
1471 delete this[propName]; // this has a getter/setter for warnings
1472 }
1473 var normalize = Interface[propName];
1474 if (normalize) {
1475 this[propName] = normalize(nativeEvent);
1476 } else {
1477 if (propName === 'target') {
1478 this.target = nativeEventTarget;
1479 } else {
1480 this[propName] = nativeEvent[propName];
1481 }
1482 }
1483 }
1484
1485 var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
1486 if (defaultPrevented) {
1487 this.isDefaultPrevented = functionThatReturnsTrue;
1488 } else {
1489 this.isDefaultPrevented = functionThatReturnsFalse;
1490 }
1491 this.isPropagationStopped = functionThatReturnsFalse;
1492 return this;
1493}
1494
1495_assign(SyntheticEvent.prototype, {
1496 preventDefault: function () {
1497 this.defaultPrevented = true;
1498 var event = this.nativeEvent;
1499 if (!event) {
1500 return;
1501 }
1502
1503 if (event.preventDefault) {
1504 event.preventDefault();
1505 } else if (typeof event.returnValue !== 'unknown') {
1506 event.returnValue = false;
1507 }
1508 this.isDefaultPrevented = functionThatReturnsTrue;
1509 },
1510
1511 stopPropagation: function () {
1512 var event = this.nativeEvent;
1513 if (!event) {
1514 return;
1515 }
1516
1517 if (event.stopPropagation) {
1518 event.stopPropagation();
1519 } else if (typeof event.cancelBubble !== 'unknown') {
1520 // The ChangeEventPlugin registers a "propertychange" event for
1521 // IE. This event does not support bubbling or cancelling, and
1522 // any references to cancelBubble throw "Member not found". A
1523 // typeof check of "unknown" circumvents this issue (and is also
1524 // IE specific).
1525 event.cancelBubble = true;
1526 }
1527
1528 this.isPropagationStopped = functionThatReturnsTrue;
1529 },
1530
1531 /**
1532 * We release all dispatched `SyntheticEvent`s after each event loop, adding
1533 * them back into the pool. This allows a way to hold onto a reference that
1534 * won't be added back into the pool.
1535 */
1536 persist: function () {
1537 this.isPersistent = functionThatReturnsTrue;
1538 },
1539
1540 /**
1541 * Checks if this event should be released back into the pool.
1542 *
1543 * @return {boolean} True if this should not be released, false otherwise.
1544 */
1545 isPersistent: functionThatReturnsFalse,
1546
1547 /**
1548 * `PooledClass` looks for `destructor` on each instance it releases.
1549 */
1550 destructor: function () {
1551 var Interface = this.constructor.Interface;
1552 for (var propName in Interface) {
1553 {
1554 Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
1555 }
1556 }
1557 this.dispatchConfig = null;
1558 this._targetInst = null;
1559 this.nativeEvent = null;
1560 this.isDefaultPrevented = functionThatReturnsFalse;
1561 this.isPropagationStopped = functionThatReturnsFalse;
1562 this._dispatchListeners = null;
1563 this._dispatchInstances = null;
1564 {
1565 Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
1566 Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
1567 Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
1568 Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
1569 Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
1570 }
1571 }
1572});
1573
1574SyntheticEvent.Interface = EventInterface;
1575
1576/**
1577 * Helper to reduce boilerplate when creating subclasses.
1578 */
1579SyntheticEvent.extend = function (Interface) {
1580 var Super = this;
1581
1582 var E = function () {};
1583 E.prototype = Super.prototype;
1584 var prototype = new E();
1585
1586 function Class() {
1587 return Super.apply(this, arguments);
1588 }
1589 _assign(prototype, Class.prototype);
1590 Class.prototype = prototype;
1591 Class.prototype.constructor = Class;
1592
1593 Class.Interface = _assign({}, Super.Interface, Interface);
1594 Class.extend = Super.extend;
1595 addEventPoolingTo(Class);
1596
1597 return Class;
1598};
1599
1600addEventPoolingTo(SyntheticEvent);
1601
1602/**
1603 * Helper to nullify syntheticEvent instance properties when destructing
1604 *
1605 * @param {String} propName
1606 * @param {?object} getVal
1607 * @return {object} defineProperty object
1608 */
1609function getPooledWarningPropertyDefinition(propName, getVal) {
1610 var isFunction = typeof getVal === 'function';
1611 return {
1612 configurable: true,
1613 set: set,
1614 get: get
1615 };
1616
1617 function set(val) {
1618 var action = isFunction ? 'setting the method' : 'setting the property';
1619 warn(action, 'This is effectively a no-op');
1620 return val;
1621 }
1622
1623 function get() {
1624 var action = isFunction ? 'accessing the method' : 'accessing the property';
1625 var result = isFunction ? 'This is a no-op function' : 'This is set to null';
1626 warn(action, result);
1627 return getVal;
1628 }
1629
1630 function warn(action, result) {
1631 var warningCondition = false;
1632 !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;
1633 }
1634}
1635
1636function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
1637 var EventConstructor = this;
1638 if (EventConstructor.eventPool.length) {
1639 var instance = EventConstructor.eventPool.pop();
1640 EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
1641 return instance;
1642 }
1643 return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
1644}
1645
1646function releasePooledEvent(event) {
1647 var EventConstructor = this;
1648 !(event instanceof EventConstructor) ? invariant(false, 'Trying to release an event instance into a pool of a different type.') : void 0;
1649 event.destructor();
1650 if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
1651 EventConstructor.eventPool.push(event);
1652 }
1653}
1654
1655function addEventPoolingTo(EventConstructor) {
1656 EventConstructor.eventPool = [];
1657 EventConstructor.getPooled = getPooledEvent;
1658 EventConstructor.release = releasePooledEvent;
1659}
1660
1661/**
1662 * @interface Event
1663 * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
1664 */
1665var SyntheticCompositionEvent = SyntheticEvent.extend({
1666 data: null
1667});
1668
1669/**
1670 * @interface Event
1671 * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
1672 * /#events-inputevents
1673 */
1674var SyntheticInputEvent = SyntheticEvent.extend({
1675 data: null
1676});
1677
1678var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
1679var START_KEYCODE = 229;
1680
1681var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
1682
1683var documentMode = null;
1684if (canUseDOM && 'documentMode' in document) {
1685 documentMode = document.documentMode;
1686}
1687
1688// Webkit offers a very useful `textInput` event that can be used to
1689// directly represent `beforeInput`. The IE `textinput` event is not as
1690// useful, so we don't use it.
1691var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode;
1692
1693// In IE9+, we have access to composition events, but the data supplied
1694// by the native compositionend event may be incorrect. Japanese ideographic
1695// spaces, for instance (\u3000) are not recorded correctly.
1696var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
1697
1698var SPACEBAR_CODE = 32;
1699var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
1700
1701// Events and their corresponding property names.
1702var eventTypes = {
1703 beforeInput: {
1704 phasedRegistrationNames: {
1705 bubbled: 'onBeforeInput',
1706 captured: 'onBeforeInputCapture'
1707 },
1708 dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]
1709 },
1710 compositionEnd: {
1711 phasedRegistrationNames: {
1712 bubbled: 'onCompositionEnd',
1713 captured: 'onCompositionEndCapture'
1714 },
1715 dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
1716 },
1717 compositionStart: {
1718 phasedRegistrationNames: {
1719 bubbled: 'onCompositionStart',
1720 captured: 'onCompositionStartCapture'
1721 },
1722 dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
1723 },
1724 compositionUpdate: {
1725 phasedRegistrationNames: {
1726 bubbled: 'onCompositionUpdate',
1727 captured: 'onCompositionUpdateCapture'
1728 },
1729 dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
1730 }
1731};
1732
1733// Track whether we've ever handled a keypress on the space key.
1734var hasSpaceKeypress = false;
1735
1736/**
1737 * Return whether a native keypress event is assumed to be a command.
1738 * This is required because Firefox fires `keypress` events for key commands
1739 * (cut, copy, select-all, etc.) even though no character is inserted.
1740 */
1741function isKeypressCommand(nativeEvent) {
1742 return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
1743 // ctrlKey && altKey is equivalent to AltGr, and is not a command.
1744 !(nativeEvent.ctrlKey && nativeEvent.altKey);
1745}
1746
1747/**
1748 * Translate native top level events into event types.
1749 *
1750 * @param {string} topLevelType
1751 * @return {object}
1752 */
1753function getCompositionEventType(topLevelType) {
1754 switch (topLevelType) {
1755 case TOP_COMPOSITION_START:
1756 return eventTypes.compositionStart;
1757 case TOP_COMPOSITION_END:
1758 return eventTypes.compositionEnd;
1759 case TOP_COMPOSITION_UPDATE:
1760 return eventTypes.compositionUpdate;
1761 }
1762}
1763
1764/**
1765 * Does our fallback best-guess model think this event signifies that
1766 * composition has begun?
1767 *
1768 * @param {string} topLevelType
1769 * @param {object} nativeEvent
1770 * @return {boolean}
1771 */
1772function isFallbackCompositionStart(topLevelType, nativeEvent) {
1773 return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;
1774}
1775
1776/**
1777 * Does our fallback mode think that this event is the end of composition?
1778 *
1779 * @param {string} topLevelType
1780 * @param {object} nativeEvent
1781 * @return {boolean}
1782 */
1783function isFallbackCompositionEnd(topLevelType, nativeEvent) {
1784 switch (topLevelType) {
1785 case TOP_KEY_UP:
1786 // Command keys insert or clear IME input.
1787 return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
1788 case TOP_KEY_DOWN:
1789 // Expect IME keyCode on each keydown. If we get any other
1790 // code we must have exited earlier.
1791 return nativeEvent.keyCode !== START_KEYCODE;
1792 case TOP_KEY_PRESS:
1793 case TOP_MOUSE_DOWN:
1794 case TOP_BLUR:
1795 // Events are not possible without cancelling IME.
1796 return true;
1797 default:
1798 return false;
1799 }
1800}
1801
1802/**
1803 * Google Input Tools provides composition data via a CustomEvent,
1804 * with the `data` property populated in the `detail` object. If this
1805 * is available on the event object, use it. If not, this is a plain
1806 * composition event and we have nothing special to extract.
1807 *
1808 * @param {object} nativeEvent
1809 * @return {?string}
1810 */
1811function getDataFromCustomEvent(nativeEvent) {
1812 var detail = nativeEvent.detail;
1813 if (typeof detail === 'object' && 'data' in detail) {
1814 return detail.data;
1815 }
1816 return null;
1817}
1818
1819/**
1820 * Check if a composition event was triggered by Korean IME.
1821 * Our fallback mode does not work well with IE's Korean IME,
1822 * so just use native composition events when Korean IME is used.
1823 * Although CompositionEvent.locale property is deprecated,
1824 * it is available in IE, where our fallback mode is enabled.
1825 *
1826 * @param {object} nativeEvent
1827 * @return {boolean}
1828 */
1829function isUsingKoreanIME(nativeEvent) {
1830 return nativeEvent.locale === 'ko';
1831}
1832
1833// Track the current IME composition status, if any.
1834var isComposing = false;
1835
1836/**
1837 * @return {?object} A SyntheticCompositionEvent.
1838 */
1839function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
1840 var eventType = void 0;
1841 var fallbackData = void 0;
1842
1843 if (canUseCompositionEvent) {
1844 eventType = getCompositionEventType(topLevelType);
1845 } else if (!isComposing) {
1846 if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
1847 eventType = eventTypes.compositionStart;
1848 }
1849 } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
1850 eventType = eventTypes.compositionEnd;
1851 }
1852
1853 if (!eventType) {
1854 return null;
1855 }
1856
1857 if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
1858 // The current composition is stored statically and must not be
1859 // overwritten while composition continues.
1860 if (!isComposing && eventType === eventTypes.compositionStart) {
1861 isComposing = initialize(nativeEventTarget);
1862 } else if (eventType === eventTypes.compositionEnd) {
1863 if (isComposing) {
1864 fallbackData = getData();
1865 }
1866 }
1867 }
1868
1869 var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
1870
1871 if (fallbackData) {
1872 // Inject data generated from fallback path into the synthetic event.
1873 // This matches the property of native CompositionEventInterface.
1874 event.data = fallbackData;
1875 } else {
1876 var customData = getDataFromCustomEvent(nativeEvent);
1877 if (customData !== null) {
1878 event.data = customData;
1879 }
1880 }
1881
1882 accumulateTwoPhaseDispatches(event);
1883 return event;
1884}
1885
1886/**
1887 * @param {TopLevelType} topLevelType Number from `TopLevelType`.
1888 * @param {object} nativeEvent Native browser event.
1889 * @return {?string} The string corresponding to this `beforeInput` event.
1890 */
1891function getNativeBeforeInputChars(topLevelType, nativeEvent) {
1892 switch (topLevelType) {
1893 case TOP_COMPOSITION_END:
1894 return getDataFromCustomEvent(nativeEvent);
1895 case TOP_KEY_PRESS:
1896 /**
1897 * If native `textInput` events are available, our goal is to make
1898 * use of them. However, there is a special case: the spacebar key.
1899 * In Webkit, preventing default on a spacebar `textInput` event
1900 * cancels character insertion, but it *also* causes the browser
1901 * to fall back to its default spacebar behavior of scrolling the
1902 * page.
1903 *
1904 * Tracking at:
1905 * https://code.google.com/p/chromium/issues/detail?id=355103
1906 *
1907 * To avoid this issue, use the keypress event as if no `textInput`
1908 * event is available.
1909 */
1910 var which = nativeEvent.which;
1911 if (which !== SPACEBAR_CODE) {
1912 return null;
1913 }
1914
1915 hasSpaceKeypress = true;
1916 return SPACEBAR_CHAR;
1917
1918 case TOP_TEXT_INPUT:
1919 // Record the characters to be added to the DOM.
1920 var chars = nativeEvent.data;
1921
1922 // If it's a spacebar character, assume that we have already handled
1923 // it at the keypress level and bail immediately. Android Chrome
1924 // doesn't give us keycodes, so we need to ignore it.
1925 if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
1926 return null;
1927 }
1928
1929 return chars;
1930
1931 default:
1932 // For other native event types, do nothing.
1933 return null;
1934 }
1935}
1936
1937/**
1938 * For browsers that do not provide the `textInput` event, extract the
1939 * appropriate string to use for SyntheticInputEvent.
1940 *
1941 * @param {number} topLevelType Number from `TopLevelEventTypes`.
1942 * @param {object} nativeEvent Native browser event.
1943 * @return {?string} The fallback string for this `beforeInput` event.
1944 */
1945function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
1946 // If we are currently composing (IME) and using a fallback to do so,
1947 // try to extract the composed characters from the fallback object.
1948 // If composition event is available, we extract a string only at
1949 // compositionevent, otherwise extract it at fallback events.
1950 if (isComposing) {
1951 if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {
1952 var chars = getData();
1953 reset();
1954 isComposing = false;
1955 return chars;
1956 }
1957 return null;
1958 }
1959
1960 switch (topLevelType) {
1961 case TOP_PASTE:
1962 // If a paste event occurs after a keypress, throw out the input
1963 // chars. Paste events should not lead to BeforeInput events.
1964 return null;
1965 case TOP_KEY_PRESS:
1966 /**
1967 * As of v27, Firefox may fire keypress events even when no character
1968 * will be inserted. A few possibilities:
1969 *
1970 * - `which` is `0`. Arrow keys, Esc key, etc.
1971 *
1972 * - `which` is the pressed key code, but no char is available.
1973 * Ex: 'AltGr + d` in Polish. There is no modified character for
1974 * this key combination and no character is inserted into the
1975 * document, but FF fires the keypress for char code `100` anyway.
1976 * No `input` event will occur.
1977 *
1978 * - `which` is the pressed key code, but a command combination is
1979 * being used. Ex: `Cmd+C`. No character is inserted, and no
1980 * `input` event will occur.
1981 */
1982 if (!isKeypressCommand(nativeEvent)) {
1983 // IE fires the `keypress` event when a user types an emoji via
1984 // Touch keyboard of Windows. In such a case, the `char` property
1985 // holds an emoji character like `\uD83D\uDE0A`. Because its length
1986 // is 2, the property `which` does not represent an emoji correctly.
1987 // In such a case, we directly return the `char` property instead of
1988 // using `which`.
1989 if (nativeEvent.char && nativeEvent.char.length > 1) {
1990 return nativeEvent.char;
1991 } else if (nativeEvent.which) {
1992 return String.fromCharCode(nativeEvent.which);
1993 }
1994 }
1995 return null;
1996 case TOP_COMPOSITION_END:
1997 return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
1998 default:
1999 return null;
2000 }
2001}
2002
2003/**
2004 * Extract a SyntheticInputEvent for `beforeInput`, based on either native
2005 * `textInput` or fallback behavior.
2006 *
2007 * @return {?object} A SyntheticInputEvent.
2008 */
2009function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
2010 var chars = void 0;
2011
2012 if (canUseTextInputEvent) {
2013 chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
2014 } else {
2015 chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
2016 }
2017
2018 // If no characters are being inserted, no BeforeInput event should
2019 // be fired.
2020 if (!chars) {
2021 return null;
2022 }
2023
2024 var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);
2025
2026 event.data = chars;
2027 accumulateTwoPhaseDispatches(event);
2028 return event;
2029}
2030
2031/**
2032 * Create an `onBeforeInput` event to match
2033 * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
2034 *
2035 * This event plugin is based on the native `textInput` event
2036 * available in Chrome, Safari, Opera, and IE. This event fires after
2037 * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
2038 *
2039 * `beforeInput` is spec'd but not implemented in any browsers, and
2040 * the `input` event does not provide any useful information about what has
2041 * actually been added, contrary to the spec. Thus, `textInput` is the best
2042 * available event to identify the characters that have actually been inserted
2043 * into the target node.
2044 *
2045 * This plugin is also responsible for emitting `composition` events, thus
2046 * allowing us to share composition fallback code for both `beforeInput` and
2047 * `composition` event types.
2048 */
2049var BeforeInputEventPlugin = {
2050 eventTypes: eventTypes,
2051
2052 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
2053 var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
2054
2055 var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
2056
2057 if (composition === null) {
2058 return beforeInput;
2059 }
2060
2061 if (beforeInput === null) {
2062 return composition;
2063 }
2064
2065 return [composition, beforeInput];
2066 }
2067};
2068
2069// Use to restore controlled state after a change event has fired.
2070
2071var restoreImpl = null;
2072var restoreTarget = null;
2073var restoreQueue = null;
2074
2075function restoreStateOfTarget(target) {
2076 // We perform this translation at the end of the event loop so that we
2077 // always receive the correct fiber here
2078 var internalInstance = getInstanceFromNode(target);
2079 if (!internalInstance) {
2080 // Unmounted
2081 return;
2082 }
2083 !(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;
2084 var props = getFiberCurrentPropsFromNode(internalInstance.stateNode);
2085 restoreImpl(internalInstance.stateNode, internalInstance.type, props);
2086}
2087
2088function setRestoreImplementation(impl) {
2089 restoreImpl = impl;
2090}
2091
2092function enqueueStateRestore(target) {
2093 if (restoreTarget) {
2094 if (restoreQueue) {
2095 restoreQueue.push(target);
2096 } else {
2097 restoreQueue = [target];
2098 }
2099 } else {
2100 restoreTarget = target;
2101 }
2102}
2103
2104function needsStateRestore() {
2105 return restoreTarget !== null || restoreQueue !== null;
2106}
2107
2108function restoreStateIfNeeded() {
2109 if (!restoreTarget) {
2110 return;
2111 }
2112 var target = restoreTarget;
2113 var queuedTargets = restoreQueue;
2114 restoreTarget = null;
2115 restoreQueue = null;
2116
2117 restoreStateOfTarget(target);
2118 if (queuedTargets) {
2119 for (var i = 0; i < queuedTargets.length; i++) {
2120 restoreStateOfTarget(queuedTargets[i]);
2121 }
2122 }
2123}
2124
2125// Used as a way to call batchedUpdates when we don't have a reference to
2126// the renderer. Such as when we're dispatching events or if third party
2127// libraries need to call batchedUpdates. Eventually, this API will go away when
2128// everything is batched by default. We'll then have a similar API to opt-out of
2129// scheduled work and instead do synchronous work.
2130
2131// Defaults
2132var _batchedUpdatesImpl = function (fn, bookkeeping) {
2133 return fn(bookkeeping);
2134};
2135var _interactiveUpdatesImpl = function (fn, a, b) {
2136 return fn(a, b);
2137};
2138var _flushInteractiveUpdatesImpl = function () {};
2139
2140var isBatching = false;
2141function batchedUpdates(fn, bookkeeping) {
2142 if (isBatching) {
2143 // If we are currently inside another batch, we need to wait until it
2144 // fully completes before restoring state.
2145 return fn(bookkeeping);
2146 }
2147 isBatching = true;
2148 try {
2149 return _batchedUpdatesImpl(fn, bookkeeping);
2150 } finally {
2151 // Here we wait until all updates have propagated, which is important
2152 // when using controlled components within layers:
2153 // https://github.com/facebook/react/issues/1698
2154 // Then we restore state of any controlled component.
2155 isBatching = false;
2156 var controlledComponentsHavePendingUpdates = needsStateRestore();
2157 if (controlledComponentsHavePendingUpdates) {
2158 // If a controlled event was fired, we may need to restore the state of
2159 // the DOM node back to the controlled value. This is necessary when React
2160 // bails out of the update without touching the DOM.
2161 _flushInteractiveUpdatesImpl();
2162 restoreStateIfNeeded();
2163 }
2164 }
2165}
2166
2167function interactiveUpdates(fn, a, b) {
2168 return _interactiveUpdatesImpl(fn, a, b);
2169}
2170
2171
2172
2173function setBatchingImplementation(batchedUpdatesImpl, interactiveUpdatesImpl, flushInteractiveUpdatesImpl) {
2174 _batchedUpdatesImpl = batchedUpdatesImpl;
2175 _interactiveUpdatesImpl = interactiveUpdatesImpl;
2176 _flushInteractiveUpdatesImpl = flushInteractiveUpdatesImpl;
2177}
2178
2179/**
2180 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
2181 */
2182var supportedInputTypes = {
2183 color: true,
2184 date: true,
2185 datetime: true,
2186 'datetime-local': true,
2187 email: true,
2188 month: true,
2189 number: true,
2190 password: true,
2191 range: true,
2192 search: true,
2193 tel: true,
2194 text: true,
2195 time: true,
2196 url: true,
2197 week: true
2198};
2199
2200function isTextInputElement(elem) {
2201 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
2202
2203 if (nodeName === 'input') {
2204 return !!supportedInputTypes[elem.type];
2205 }
2206
2207 if (nodeName === 'textarea') {
2208 return true;
2209 }
2210
2211 return false;
2212}
2213
2214/**
2215 * HTML nodeType values that represent the type of the node
2216 */
2217
2218var ELEMENT_NODE = 1;
2219var TEXT_NODE = 3;
2220var COMMENT_NODE = 8;
2221var DOCUMENT_NODE = 9;
2222var DOCUMENT_FRAGMENT_NODE = 11;
2223
2224/**
2225 * Gets the target node from a native browser event by accounting for
2226 * inconsistencies in browser DOM APIs.
2227 *
2228 * @param {object} nativeEvent Native browser event.
2229 * @return {DOMEventTarget} Target node.
2230 */
2231function getEventTarget(nativeEvent) {
2232 // Fallback to nativeEvent.srcElement for IE9
2233 // https://github.com/facebook/react/issues/12506
2234 var target = nativeEvent.target || nativeEvent.srcElement || window;
2235
2236 // Normalize SVG <use> element events #4963
2237 if (target.correspondingUseElement) {
2238 target = target.correspondingUseElement;
2239 }
2240
2241 // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
2242 // @see http://www.quirksmode.org/js/events_properties.html
2243 return target.nodeType === TEXT_NODE ? target.parentNode : target;
2244}
2245
2246/**
2247 * Checks if an event is supported in the current execution environment.
2248 *
2249 * NOTE: This will not work correctly for non-generic events such as `change`,
2250 * `reset`, `load`, `error`, and `select`.
2251 *
2252 * Borrows from Modernizr.
2253 *
2254 * @param {string} eventNameSuffix Event name, e.g. "click".
2255 * @return {boolean} True if the event is supported.
2256 * @internal
2257 * @license Modernizr 3.0.0pre (Custom Build) | MIT
2258 */
2259function isEventSupported(eventNameSuffix) {
2260 if (!canUseDOM) {
2261 return false;
2262 }
2263
2264 var eventName = 'on' + eventNameSuffix;
2265 var isSupported = eventName in document;
2266
2267 if (!isSupported) {
2268 var element = document.createElement('div');
2269 element.setAttribute(eventName, 'return;');
2270 isSupported = typeof element[eventName] === 'function';
2271 }
2272
2273 return isSupported;
2274}
2275
2276function isCheckable(elem) {
2277 var type = elem.type;
2278 var nodeName = elem.nodeName;
2279 return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
2280}
2281
2282function getTracker(node) {
2283 return node._valueTracker;
2284}
2285
2286function detachTracker(node) {
2287 node._valueTracker = null;
2288}
2289
2290function getValueFromNode(node) {
2291 var value = '';
2292 if (!node) {
2293 return value;
2294 }
2295
2296 if (isCheckable(node)) {
2297 value = node.checked ? 'true' : 'false';
2298 } else {
2299 value = node.value;
2300 }
2301
2302 return value;
2303}
2304
2305function trackValueOnNode(node) {
2306 var valueField = isCheckable(node) ? 'checked' : 'value';
2307 var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
2308
2309 var currentValue = '' + node[valueField];
2310
2311 // if someone has already defined a value or Safari, then bail
2312 // and don't track value will cause over reporting of changes,
2313 // but it's better then a hard failure
2314 // (needed for certain tests that spyOn input values and Safari)
2315 if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
2316 return;
2317 }
2318 var get = descriptor.get,
2319 set = descriptor.set;
2320
2321 Object.defineProperty(node, valueField, {
2322 configurable: true,
2323 get: function () {
2324 return get.call(this);
2325 },
2326 set: function (value) {
2327 currentValue = '' + value;
2328 set.call(this, value);
2329 }
2330 });
2331 // We could've passed this the first time
2332 // but it triggers a bug in IE11 and Edge 14/15.
2333 // Calling defineProperty() again should be equivalent.
2334 // https://github.com/facebook/react/issues/11768
2335 Object.defineProperty(node, valueField, {
2336 enumerable: descriptor.enumerable
2337 });
2338
2339 var tracker = {
2340 getValue: function () {
2341 return currentValue;
2342 },
2343 setValue: function (value) {
2344 currentValue = '' + value;
2345 },
2346 stopTracking: function () {
2347 detachTracker(node);
2348 delete node[valueField];
2349 }
2350 };
2351 return tracker;
2352}
2353
2354function track(node) {
2355 if (getTracker(node)) {
2356 return;
2357 }
2358
2359 // TODO: Once it's just Fiber we can move this to node._wrapperState
2360 node._valueTracker = trackValueOnNode(node);
2361}
2362
2363function updateValueIfChanged(node) {
2364 if (!node) {
2365 return false;
2366 }
2367
2368 var tracker = getTracker(node);
2369 // if there is no tracker at this point it's unlikely
2370 // that trying again will succeed
2371 if (!tracker) {
2372 return true;
2373 }
2374
2375 var lastValue = tracker.getValue();
2376 var nextValue = getValueFromNode(node);
2377 if (nextValue !== lastValue) {
2378 tracker.setValue(nextValue);
2379 return true;
2380 }
2381 return false;
2382}
2383
2384var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
2385
2386// Prevent newer renderers from RTE when used with older react package versions.
2387// Current owner and dispatcher used to share the same ref,
2388// but PR #14548 split them out to better support the react-debug-tools package.
2389if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
2390 ReactSharedInternals.ReactCurrentDispatcher = {
2391 current: null
2392 };
2393}
2394
2395var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
2396
2397var describeComponentFrame = function (name, source, ownerName) {
2398 var sourceInfo = '';
2399 if (source) {
2400 var path = source.fileName;
2401 var fileName = path.replace(BEFORE_SLASH_RE, '');
2402 {
2403 // In DEV, include code for a common special case:
2404 // prefer "folder/index.js" instead of just "index.js".
2405 if (/^index\./.test(fileName)) {
2406 var match = path.match(BEFORE_SLASH_RE);
2407 if (match) {
2408 var pathBeforeSlash = match[1];
2409 if (pathBeforeSlash) {
2410 var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
2411 fileName = folderName + '/' + fileName;
2412 }
2413 }
2414 }
2415 }
2416 sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
2417 } else if (ownerName) {
2418 sourceInfo = ' (created by ' + ownerName + ')';
2419 }
2420 return '\n in ' + (name || 'Unknown') + sourceInfo;
2421};
2422
2423// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
2424// nor polyfill, then a plain number is used for performance.
2425var hasSymbol = typeof Symbol === 'function' && Symbol.for;
2426
2427var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
2428var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
2429var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
2430var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
2431var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
2432var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
2433var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
2434
2435var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
2436var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
2437var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
2438var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
2439var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
2440
2441var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
2442var FAUX_ITERATOR_SYMBOL = '@@iterator';
2443
2444function getIteratorFn(maybeIterable) {
2445 if (maybeIterable === null || typeof maybeIterable !== 'object') {
2446 return null;
2447 }
2448 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
2449 if (typeof maybeIterator === 'function') {
2450 return maybeIterator;
2451 }
2452 return null;
2453}
2454
2455var Pending = 0;
2456var Resolved = 1;
2457var Rejected = 2;
2458
2459function refineResolvedLazyComponent(lazyComponent) {
2460 return lazyComponent._status === Resolved ? lazyComponent._result : null;
2461}
2462
2463function getWrappedName(outerType, innerType, wrapperName) {
2464 var functionName = innerType.displayName || innerType.name || '';
2465 return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName);
2466}
2467
2468function getComponentName(type) {
2469 if (type == null) {
2470 // Host root, text node or just invalid type.
2471 return null;
2472 }
2473 {
2474 if (typeof type.tag === 'number') {
2475 warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
2476 }
2477 }
2478 if (typeof type === 'function') {
2479 return type.displayName || type.name || null;
2480 }
2481 if (typeof type === 'string') {
2482 return type;
2483 }
2484 switch (type) {
2485 case REACT_CONCURRENT_MODE_TYPE:
2486 return 'ConcurrentMode';
2487 case REACT_FRAGMENT_TYPE:
2488 return 'Fragment';
2489 case REACT_PORTAL_TYPE:
2490 return 'Portal';
2491 case REACT_PROFILER_TYPE:
2492 return 'Profiler';
2493 case REACT_STRICT_MODE_TYPE:
2494 return 'StrictMode';
2495 case REACT_SUSPENSE_TYPE:
2496 return 'Suspense';
2497 }
2498 if (typeof type === 'object') {
2499 switch (type.$$typeof) {
2500 case REACT_CONTEXT_TYPE:
2501 return 'Context.Consumer';
2502 case REACT_PROVIDER_TYPE:
2503 return 'Context.Provider';
2504 case REACT_FORWARD_REF_TYPE:
2505 return getWrappedName(type, type.render, 'ForwardRef');
2506 case REACT_MEMO_TYPE:
2507 return getComponentName(type.type);
2508 case REACT_LAZY_TYPE:
2509 {
2510 var thenable = type;
2511 var resolvedThenable = refineResolvedLazyComponent(thenable);
2512 if (resolvedThenable) {
2513 return getComponentName(resolvedThenable);
2514 }
2515 }
2516 }
2517 }
2518 return null;
2519}
2520
2521var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
2522
2523function describeFiber(fiber) {
2524 switch (fiber.tag) {
2525 case HostRoot:
2526 case HostPortal:
2527 case HostText:
2528 case Fragment:
2529 case ContextProvider:
2530 case ContextConsumer:
2531 return '';
2532 default:
2533 var owner = fiber._debugOwner;
2534 var source = fiber._debugSource;
2535 var name = getComponentName(fiber.type);
2536 var ownerName = null;
2537 if (owner) {
2538 ownerName = getComponentName(owner.type);
2539 }
2540 return describeComponentFrame(name, source, ownerName);
2541 }
2542}
2543
2544function getStackByFiberInDevAndProd(workInProgress) {
2545 var info = '';
2546 var node = workInProgress;
2547 do {
2548 info += describeFiber(node);
2549 node = node.return;
2550 } while (node);
2551 return info;
2552}
2553
2554var current = null;
2555var phase = null;
2556
2557function getCurrentFiberOwnerNameInDevOrNull() {
2558 {
2559 if (current === null) {
2560 return null;
2561 }
2562 var owner = current._debugOwner;
2563 if (owner !== null && typeof owner !== 'undefined') {
2564 return getComponentName(owner.type);
2565 }
2566 }
2567 return null;
2568}
2569
2570function getCurrentFiberStackInDev() {
2571 {
2572 if (current === null) {
2573 return '';
2574 }
2575 // Safe because if current fiber exists, we are reconciling,
2576 // and it is guaranteed to be the work-in-progress version.
2577 return getStackByFiberInDevAndProd(current);
2578 }
2579 return '';
2580}
2581
2582function resetCurrentFiber() {
2583 {
2584 ReactDebugCurrentFrame.getCurrentStack = null;
2585 current = null;
2586 phase = null;
2587 }
2588}
2589
2590function setCurrentFiber(fiber) {
2591 {
2592 ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev;
2593 current = fiber;
2594 phase = null;
2595 }
2596}
2597
2598function setCurrentPhase(lifeCyclePhase) {
2599 {
2600 phase = lifeCyclePhase;
2601 }
2602}
2603
2604/**
2605 * Similar to invariant but only logs a warning if the condition is not met.
2606 * This can be used to log issues in development environments in critical
2607 * paths. Removing the logging code for production environments will keep the
2608 * same logic and follow the same code paths.
2609 */
2610
2611var warning = warningWithoutStack$1;
2612
2613{
2614 warning = function (condition, format) {
2615 if (condition) {
2616 return;
2617 }
2618 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
2619 var stack = ReactDebugCurrentFrame.getStackAddendum();
2620 // eslint-disable-next-line react-internal/warning-and-invariant-args
2621
2622 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
2623 args[_key - 2] = arguments[_key];
2624 }
2625
2626 warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack]));
2627 };
2628}
2629
2630var warning$1 = warning;
2631
2632// A reserved attribute.
2633// It is handled by React separately and shouldn't be written to the DOM.
2634var RESERVED = 0;
2635
2636// A simple string attribute.
2637// Attributes that aren't in the whitelist are presumed to have this type.
2638var STRING = 1;
2639
2640// A string attribute that accepts booleans in React. In HTML, these are called
2641// "enumerated" attributes with "true" and "false" as possible values.
2642// When true, it should be set to a "true" string.
2643// When false, it should be set to a "false" string.
2644var BOOLEANISH_STRING = 2;
2645
2646// A real boolean attribute.
2647// When true, it should be present (set either to an empty string or its name).
2648// When false, it should be omitted.
2649var BOOLEAN = 3;
2650
2651// An attribute that can be used as a flag as well as with a value.
2652// When true, it should be present (set either to an empty string or its name).
2653// When false, it should be omitted.
2654// For any other value, should be present with that value.
2655var OVERLOADED_BOOLEAN = 4;
2656
2657// An attribute that must be numeric or parse as a numeric.
2658// When falsy, it should be removed.
2659var NUMERIC = 5;
2660
2661// An attribute that must be positive numeric or parse as a positive numeric.
2662// When falsy, it should be removed.
2663var POSITIVE_NUMERIC = 6;
2664
2665/* eslint-disable max-len */
2666var 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';
2667/* eslint-enable max-len */
2668var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040';
2669
2670
2671var ROOT_ATTRIBUTE_NAME = 'data-reactroot';
2672var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
2673
2674var hasOwnProperty = Object.prototype.hasOwnProperty;
2675var illegalAttributeNameCache = {};
2676var validatedAttributeNameCache = {};
2677
2678function isAttributeNameSafe(attributeName) {
2679 if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
2680 return true;
2681 }
2682 if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
2683 return false;
2684 }
2685 if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
2686 validatedAttributeNameCache[attributeName] = true;
2687 return true;
2688 }
2689 illegalAttributeNameCache[attributeName] = true;
2690 {
2691 warning$1(false, 'Invalid attribute name: `%s`', attributeName);
2692 }
2693 return false;
2694}
2695
2696function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
2697 if (propertyInfo !== null) {
2698 return propertyInfo.type === RESERVED;
2699 }
2700 if (isCustomComponentTag) {
2701 return false;
2702 }
2703 if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
2704 return true;
2705 }
2706 return false;
2707}
2708
2709function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
2710 if (propertyInfo !== null && propertyInfo.type === RESERVED) {
2711 return false;
2712 }
2713 switch (typeof value) {
2714 case 'function':
2715 // $FlowIssue symbol is perfectly valid here
2716 case 'symbol':
2717 // eslint-disable-line
2718 return true;
2719 case 'boolean':
2720 {
2721 if (isCustomComponentTag) {
2722 return false;
2723 }
2724 if (propertyInfo !== null) {
2725 return !propertyInfo.acceptsBooleans;
2726 } else {
2727 var prefix = name.toLowerCase().slice(0, 5);
2728 return prefix !== 'data-' && prefix !== 'aria-';
2729 }
2730 }
2731 default:
2732 return false;
2733 }
2734}
2735
2736function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
2737 if (value === null || typeof value === 'undefined') {
2738 return true;
2739 }
2740 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
2741 return true;
2742 }
2743 if (isCustomComponentTag) {
2744 return false;
2745 }
2746 if (propertyInfo !== null) {
2747 switch (propertyInfo.type) {
2748 case BOOLEAN:
2749 return !value;
2750 case OVERLOADED_BOOLEAN:
2751 return value === false;
2752 case NUMERIC:
2753 return isNaN(value);
2754 case POSITIVE_NUMERIC:
2755 return isNaN(value) || value < 1;
2756 }
2757 }
2758 return false;
2759}
2760
2761function getPropertyInfo(name) {
2762 return properties.hasOwnProperty(name) ? properties[name] : null;
2763}
2764
2765function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace) {
2766 this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
2767 this.attributeName = attributeName;
2768 this.attributeNamespace = attributeNamespace;
2769 this.mustUseProperty = mustUseProperty;
2770 this.propertyName = name;
2771 this.type = type;
2772}
2773
2774// When adding attributes to this list, be sure to also add them to
2775// the `possibleStandardNames` module to ensure casing and incorrect
2776// name warnings.
2777var properties = {};
2778
2779// These props are reserved by React. They shouldn't be written to the DOM.
2780['children', 'dangerouslySetInnerHTML',
2781// TODO: This prevents the assignment of defaultValue to regular
2782// elements (not just inputs). Now that ReactDOMInput assigns to the
2783// defaultValue property -- do we need this?
2784'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'].forEach(function (name) {
2785 properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
2786 name, // attributeName
2787 null);
2788} // attributeNamespace
2789);
2790
2791// A few React string attributes have a different name.
2792// This is a mapping from React prop names to the attribute names.
2793[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
2794 var name = _ref[0],
2795 attributeName = _ref[1];
2796
2797 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2798 attributeName, // attributeName
2799 null);
2800} // attributeNamespace
2801);
2802
2803// These are "enumerated" HTML attributes that accept "true" and "false".
2804// In React, we let users pass `true` and `false` even though technically
2805// these aren't boolean attributes (they are coerced to strings).
2806['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
2807 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2808 name.toLowerCase(), // attributeName
2809 null);
2810} // attributeNamespace
2811);
2812
2813// These are "enumerated" SVG attributes that accept "true" and "false".
2814// In React, we let users pass `true` and `false` even though technically
2815// these aren't boolean attributes (they are coerced to strings).
2816// Since these are SVG attributes, their attribute names are case-sensitive.
2817['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
2818 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2819 name, // attributeName
2820 null);
2821} // attributeNamespace
2822);
2823
2824// These are HTML boolean attributes.
2825['allowFullScreen', 'async',
2826// Note: there is a special case that prevents it from being written to the DOM
2827// on the client side because the browsers are inconsistent. Instead we call focus().
2828'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless',
2829// Microdata
2830'itemScope'].forEach(function (name) {
2831 properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
2832 name.toLowerCase(), // attributeName
2833 null);
2834} // attributeNamespace
2835);
2836
2837// These are the few React props that we set as DOM properties
2838// rather than attributes. These are all booleans.
2839['checked',
2840// Note: `option.selected` is not updated if `select.multiple` is
2841// disabled with `removeAttribute`. We have special logic for handling this.
2842'multiple', 'muted', 'selected'].forEach(function (name) {
2843 properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
2844 name, // attributeName
2845 null);
2846} // attributeNamespace
2847);
2848
2849// These are HTML attributes that are "overloaded booleans": they behave like
2850// booleans, but can also accept a string value.
2851['capture', 'download'].forEach(function (name) {
2852 properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
2853 name, // attributeName
2854 null);
2855} // attributeNamespace
2856);
2857
2858// These are HTML attributes that must be positive numbers.
2859['cols', 'rows', 'size', 'span'].forEach(function (name) {
2860 properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
2861 name, // attributeName
2862 null);
2863} // attributeNamespace
2864);
2865
2866// These are HTML attributes that must be numbers.
2867['rowSpan', 'start'].forEach(function (name) {
2868 properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
2869 name.toLowerCase(), // attributeName
2870 null);
2871} // attributeNamespace
2872);
2873
2874var CAMELIZE = /[\-\:]([a-z])/g;
2875var capitalize = function (token) {
2876 return token[1].toUpperCase();
2877};
2878
2879// This is a list of all SVG attributes that need special casing, namespacing,
2880// or boolean value assignment. Regular attributes that just accept strings
2881// and have the same names are omitted, just like in the HTML whitelist.
2882// Some of these attributes can be hard to find. This list was created by
2883// scrapping the MDN documentation.
2884['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) {
2885 var name = attributeName.replace(CAMELIZE, capitalize);
2886 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2887 attributeName, null);
2888} // attributeNamespace
2889);
2890
2891// String SVG attributes with the xlink namespace.
2892['xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type'].forEach(function (attributeName) {
2893 var name = attributeName.replace(CAMELIZE, capitalize);
2894 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2895 attributeName, 'http://www.w3.org/1999/xlink');
2896});
2897
2898// String SVG attributes with the xml namespace.
2899['xml:base', 'xml:lang', 'xml:space'].forEach(function (attributeName) {
2900 var name = attributeName.replace(CAMELIZE, capitalize);
2901 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2902 attributeName, 'http://www.w3.org/XML/1998/namespace');
2903});
2904
2905// These attribute exists both in HTML and SVG.
2906// The attribute name is case-sensitive in SVG so we can't just use
2907// the React name like we do for attributes that exist only in HTML.
2908['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
2909 properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
2910 attributeName.toLowerCase(), // attributeName
2911 null);
2912} // attributeNamespace
2913);
2914
2915/**
2916 * Get the value for a property on a node. Only used in DEV for SSR validation.
2917 * The "expected" argument is used as a hint of what the expected value is.
2918 * Some properties have multiple equivalent values.
2919 */
2920function getValueForProperty(node, name, expected, propertyInfo) {
2921 {
2922 if (propertyInfo.mustUseProperty) {
2923 var propertyName = propertyInfo.propertyName;
2924
2925 return node[propertyName];
2926 } else {
2927 var attributeName = propertyInfo.attributeName;
2928
2929 var stringValue = null;
2930
2931 if (propertyInfo.type === OVERLOADED_BOOLEAN) {
2932 if (node.hasAttribute(attributeName)) {
2933 var value = node.getAttribute(attributeName);
2934 if (value === '') {
2935 return true;
2936 }
2937 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2938 return value;
2939 }
2940 if (value === '' + expected) {
2941 return expected;
2942 }
2943 return value;
2944 }
2945 } else if (node.hasAttribute(attributeName)) {
2946 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2947 // We had an attribute but shouldn't have had one, so read it
2948 // for the error message.
2949 return node.getAttribute(attributeName);
2950 }
2951 if (propertyInfo.type === BOOLEAN) {
2952 // If this was a boolean, it doesn't matter what the value is
2953 // the fact that we have it is the same as the expected.
2954 return expected;
2955 }
2956 // Even if this property uses a namespace we use getAttribute
2957 // because we assume its namespaced name is the same as our config.
2958 // To use getAttributeNS we need the local name which we don't have
2959 // in our config atm.
2960 stringValue = node.getAttribute(attributeName);
2961 }
2962
2963 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2964 return stringValue === null ? expected : stringValue;
2965 } else if (stringValue === '' + expected) {
2966 return expected;
2967 } else {
2968 return stringValue;
2969 }
2970 }
2971 }
2972}
2973
2974/**
2975 * Get the value for a attribute on a node. Only used in DEV for SSR validation.
2976 * The third argument is used as a hint of what the expected value is. Some
2977 * attributes have multiple equivalent values.
2978 */
2979function getValueForAttribute(node, name, expected) {
2980 {
2981 if (!isAttributeNameSafe(name)) {
2982 return;
2983 }
2984 if (!node.hasAttribute(name)) {
2985 return expected === undefined ? undefined : null;
2986 }
2987 var value = node.getAttribute(name);
2988 if (value === '' + expected) {
2989 return expected;
2990 }
2991 return value;
2992 }
2993}
2994
2995/**
2996 * Sets the value for a property on a node.
2997 *
2998 * @param {DOMElement} node
2999 * @param {string} name
3000 * @param {*} value
3001 */
3002function setValueForProperty(node, name, value, isCustomComponentTag) {
3003 var propertyInfo = getPropertyInfo(name);
3004 if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
3005 return;
3006 }
3007 if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
3008 value = null;
3009 }
3010 // If the prop isn't in the special list, treat it as a simple attribute.
3011 if (isCustomComponentTag || propertyInfo === null) {
3012 if (isAttributeNameSafe(name)) {
3013 var _attributeName = name;
3014 if (value === null) {
3015 node.removeAttribute(_attributeName);
3016 } else {
3017 node.setAttribute(_attributeName, '' + value);
3018 }
3019 }
3020 return;
3021 }
3022 var mustUseProperty = propertyInfo.mustUseProperty;
3023
3024 if (mustUseProperty) {
3025 var propertyName = propertyInfo.propertyName;
3026
3027 if (value === null) {
3028 var type = propertyInfo.type;
3029
3030 node[propertyName] = type === BOOLEAN ? false : '';
3031 } else {
3032 // Contrary to `setAttribute`, object properties are properly
3033 // `toString`ed by IE8/9.
3034 node[propertyName] = value;
3035 }
3036 return;
3037 }
3038 // The rest are treated as attributes with special cases.
3039 var attributeName = propertyInfo.attributeName,
3040 attributeNamespace = propertyInfo.attributeNamespace;
3041
3042 if (value === null) {
3043 node.removeAttribute(attributeName);
3044 } else {
3045 var _type = propertyInfo.type;
3046
3047 var attributeValue = void 0;
3048 if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
3049 attributeValue = '';
3050 } else {
3051 // `setAttribute` with objects becomes only `[object]` in IE8/9,
3052 // ('' + value) makes it output the correct toString()-value.
3053 attributeValue = '' + value;
3054 }
3055 if (attributeNamespace) {
3056 node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
3057 } else {
3058 node.setAttribute(attributeName, attributeValue);
3059 }
3060 }
3061}
3062
3063// Flow does not allow string concatenation of most non-string types. To work
3064// around this limitation, we use an opaque type that can only be obtained by
3065// passing the value through getToStringValue first.
3066function toString(value) {
3067 return '' + value;
3068}
3069
3070function getToStringValue(value) {
3071 switch (typeof value) {
3072 case 'boolean':
3073 case 'number':
3074 case 'object':
3075 case 'string':
3076 case 'undefined':
3077 return value;
3078 default:
3079 // function, symbol are assigned as empty strings
3080 return '';
3081 }
3082}
3083
3084/**
3085 * Copyright (c) 2013-present, Facebook, Inc.
3086 *
3087 * This source code is licensed under the MIT license found in the
3088 * LICENSE file in the root directory of this source tree.
3089 */
3090
3091
3092
3093var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
3094
3095var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
3096
3097/**
3098 * Copyright (c) 2013-present, Facebook, Inc.
3099 *
3100 * This source code is licensed under the MIT license found in the
3101 * LICENSE file in the root directory of this source tree.
3102 */
3103
3104
3105
3106var printWarning = function() {};
3107
3108{
3109 var ReactPropTypesSecret = ReactPropTypesSecret_1;
3110 var loggedTypeFailures = {};
3111
3112 printWarning = function(text) {
3113 var message = 'Warning: ' + text;
3114 if (typeof console !== 'undefined') {
3115 console.error(message);
3116 }
3117 try {
3118 // --- Welcome to debugging React ---
3119 // This error was thrown as a convenience so that you can use this stack
3120 // to find the callsite that caused this warning to fire.
3121 throw new Error(message);
3122 } catch (x) {}
3123 };
3124}
3125
3126/**
3127 * Assert that the values match with the type specs.
3128 * Error messages are memorized and will only be shown once.
3129 *
3130 * @param {object} typeSpecs Map of name to a ReactPropType
3131 * @param {object} values Runtime values that need to be type-checked
3132 * @param {string} location e.g. "prop", "context", "child context"
3133 * @param {string} componentName Name of the component for error messages.
3134 * @param {?Function} getStack Returns the component stack.
3135 * @private
3136 */
3137function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
3138 {
3139 for (var typeSpecName in typeSpecs) {
3140 if (typeSpecs.hasOwnProperty(typeSpecName)) {
3141 var error;
3142 // Prop type validation may throw. In case they do, we don't want to
3143 // fail the render phase where it didn't fail before. So we log it.
3144 // After these have been cleaned up, we'll let them throw.
3145 try {
3146 // This is intentionally an invariant that gets caught. It's the same
3147 // behavior as without this statement except with a better message.
3148 if (typeof typeSpecs[typeSpecName] !== 'function') {
3149 var err = Error(
3150 (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
3151 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
3152 );
3153 err.name = 'Invariant Violation';
3154 throw err;
3155 }
3156 error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
3157 } catch (ex) {
3158 error = ex;
3159 }
3160 if (error && !(error instanceof Error)) {
3161 printWarning(
3162 (componentName || 'React class') + ': type specification of ' +
3163 location + ' `' + typeSpecName + '` is invalid; the type checker ' +
3164 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
3165 'You may have forgotten to pass an argument to the type checker ' +
3166 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
3167 'shape all require an argument).'
3168 );
3169
3170 }
3171 if (error instanceof Error && !(error.message in loggedTypeFailures)) {
3172 // Only monitor this failure once because there tends to be a lot of the
3173 // same error.
3174 loggedTypeFailures[error.message] = true;
3175
3176 var stack = getStack ? getStack() : '';
3177
3178 printWarning(
3179 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
3180 );
3181 }
3182 }
3183 }
3184 }
3185}
3186
3187var checkPropTypes_1 = checkPropTypes;
3188
3189var ReactDebugCurrentFrame$1 = null;
3190
3191var ReactControlledValuePropTypes = {
3192 checkPropTypes: null
3193};
3194
3195{
3196 ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
3197
3198 var hasReadOnlyValue = {
3199 button: true,
3200 checkbox: true,
3201 image: true,
3202 hidden: true,
3203 radio: true,
3204 reset: true,
3205 submit: true
3206 };
3207
3208 var propTypes = {
3209 value: function (props, propName, componentName) {
3210 if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null) {
3211 return null;
3212 }
3213 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`.');
3214 },
3215 checked: function (props, propName, componentName) {
3216 if (props.onChange || props.readOnly || props.disabled || props[propName] == null) {
3217 return null;
3218 }
3219 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`.');
3220 }
3221 };
3222
3223 /**
3224 * Provide a linked `value` attribute for controlled forms. You should not use
3225 * this outside of the ReactDOM controlled form components.
3226 */
3227 ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) {
3228 checkPropTypes_1(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$1.getStackAddendum);
3229 };
3230}
3231
3232var enableUserTimingAPI = true;
3233
3234// Helps identify side effects in begin-phase lifecycle hooks and setState reducers:
3235var debugRenderPhaseSideEffects = false;
3236
3237// In some cases, StrictMode should also double-render lifecycles.
3238// This can be confusing for tests though,
3239// And it can be bad for performance in production.
3240// This feature flag can be used to control the behavior:
3241var debugRenderPhaseSideEffectsForStrictMode = true;
3242
3243// To preserve the "Pause on caught exceptions" behavior of the debugger, we
3244// replay the begin phase of a failed component inside invokeGuardedCallback.
3245var replayFailedUnitOfWorkWithInvokeGuardedCallback = true;
3246
3247// Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:
3248var warnAboutDeprecatedLifecycles = false;
3249
3250// Gather advanced timing metrics for Profiler subtrees.
3251var enableProfilerTimer = true;
3252
3253// Trace which interactions trigger each commit.
3254var enableSchedulerTracing = true;
3255
3256// Only used in www builds.
3257var enableSuspenseServerRenderer = false; // TODO: true? Here it might just be false.
3258
3259// Only used in www builds.
3260
3261
3262// Only used in www builds.
3263
3264
3265// React Fire: prevent the value and checked attributes from syncing
3266// with their related DOM properties
3267var disableInputAttributeSyncing = false;
3268
3269// These APIs will no longer be "unstable" in the upcoming 16.7 release,
3270// Control this behavior with a flag to support 16.6 minor releases in the meanwhile.
3271var enableStableConcurrentModeAPIs = false;
3272
3273var warnAboutShorthandPropertyCollision = false;
3274
3275// TODO: direct imports like some-package/src/* are bad. Fix me.
3276var didWarnValueDefaultValue = false;
3277var didWarnCheckedDefaultChecked = false;
3278var didWarnControlledToUncontrolled = false;
3279var didWarnUncontrolledToControlled = false;
3280
3281function isControlled(props) {
3282 var usesChecked = props.type === 'checkbox' || props.type === 'radio';
3283 return usesChecked ? props.checked != null : props.value != null;
3284}
3285
3286/**
3287 * Implements an <input> host component that allows setting these optional
3288 * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
3289 *
3290 * If `checked` or `value` are not supplied (or null/undefined), user actions
3291 * that affect the checked state or value will trigger updates to the element.
3292 *
3293 * If they are supplied (and not null/undefined), the rendered element will not
3294 * trigger updates to the element. Instead, the props must change in order for
3295 * the rendered element to be updated.
3296 *
3297 * The rendered element will be initialized as unchecked (or `defaultChecked`)
3298 * with an empty value (or `defaultValue`).
3299 *
3300 * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
3301 */
3302
3303function getHostProps(element, props) {
3304 var node = element;
3305 var checked = props.checked;
3306
3307 var hostProps = _assign({}, props, {
3308 defaultChecked: undefined,
3309 defaultValue: undefined,
3310 value: undefined,
3311 checked: checked != null ? checked : node._wrapperState.initialChecked
3312 });
3313
3314 return hostProps;
3315}
3316
3317function initWrapperState(element, props) {
3318 {
3319 ReactControlledValuePropTypes.checkPropTypes('input', props);
3320
3321 if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
3322 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);
3323 didWarnCheckedDefaultChecked = true;
3324 }
3325 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
3326 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);
3327 didWarnValueDefaultValue = true;
3328 }
3329 }
3330
3331 var node = element;
3332 var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
3333
3334 node._wrapperState = {
3335 initialChecked: props.checked != null ? props.checked : props.defaultChecked,
3336 initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
3337 controlled: isControlled(props)
3338 };
3339}
3340
3341function updateChecked(element, props) {
3342 var node = element;
3343 var checked = props.checked;
3344 if (checked != null) {
3345 setValueForProperty(node, 'checked', checked, false);
3346 }
3347}
3348
3349function updateWrapper(element, props) {
3350 var node = element;
3351 {
3352 var _controlled = isControlled(props);
3353
3354 if (!node._wrapperState.controlled && _controlled && !didWarnUncontrolledToControlled) {
3355 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);
3356 didWarnUncontrolledToControlled = true;
3357 }
3358 if (node._wrapperState.controlled && !_controlled && !didWarnControlledToUncontrolled) {
3359 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);
3360 didWarnControlledToUncontrolled = true;
3361 }
3362 }
3363
3364 updateChecked(element, props);
3365
3366 var value = getToStringValue(props.value);
3367 var type = props.type;
3368
3369 if (value != null) {
3370 if (type === 'number') {
3371 if (value === 0 && node.value === '' ||
3372 // We explicitly want to coerce to number here if possible.
3373 // eslint-disable-next-line
3374 node.value != value) {
3375 node.value = toString(value);
3376 }
3377 } else if (node.value !== toString(value)) {
3378 node.value = toString(value);
3379 }
3380 } else if (type === 'submit' || type === 'reset') {
3381 // Submit/reset inputs need the attribute removed completely to avoid
3382 // blank-text buttons.
3383 node.removeAttribute('value');
3384 return;
3385 }
3386
3387 if (disableInputAttributeSyncing) {
3388 // When not syncing the value attribute, React only assigns a new value
3389 // whenever the defaultValue React prop has changed. When not present,
3390 // React does nothing
3391 if (props.hasOwnProperty('defaultValue')) {
3392 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
3393 }
3394 } else {
3395 // When syncing the value attribute, the value comes from a cascade of
3396 // properties:
3397 // 1. The value React property
3398 // 2. The defaultValue React property
3399 // 3. Otherwise there should be no change
3400 if (props.hasOwnProperty('value')) {
3401 setDefaultValue(node, props.type, value);
3402 } else if (props.hasOwnProperty('defaultValue')) {
3403 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
3404 }
3405 }
3406
3407 if (disableInputAttributeSyncing) {
3408 // When not syncing the checked attribute, the attribute is directly
3409 // controllable from the defaultValue React property. It needs to be
3410 // updated as new props come in.
3411 if (props.defaultChecked == null) {
3412 node.removeAttribute('checked');
3413 } else {
3414 node.defaultChecked = !!props.defaultChecked;
3415 }
3416 } else {
3417 // When syncing the checked attribute, it only changes when it needs
3418 // to be removed, such as transitioning from a checkbox into a text input
3419 if (props.checked == null && props.defaultChecked != null) {
3420 node.defaultChecked = !!props.defaultChecked;
3421 }
3422 }
3423}
3424
3425function postMountWrapper(element, props, isHydrating) {
3426 var node = element;
3427
3428 // Do not assign value if it is already set. This prevents user text input
3429 // from being lost during SSR hydration.
3430 if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
3431 var type = props.type;
3432 var isButton = type === 'submit' || type === 'reset';
3433
3434 // Avoid setting value attribute on submit/reset inputs as it overrides the
3435 // default value provided by the browser. See: #12872
3436 if (isButton && (props.value === undefined || props.value === null)) {
3437 return;
3438 }
3439
3440 var _initialValue = toString(node._wrapperState.initialValue);
3441
3442 // Do not assign value if it is already set. This prevents user text input
3443 // from being lost during SSR hydration.
3444 if (!isHydrating) {
3445 if (disableInputAttributeSyncing) {
3446 var value = getToStringValue(props.value);
3447
3448 // When not syncing the value attribute, the value property points
3449 // directly to the React prop. Only assign it if it exists.
3450 if (value != null) {
3451 // Always assign on buttons so that it is possible to assign an
3452 // empty string to clear button text.
3453 //
3454 // Otherwise, do not re-assign the value property if is empty. This
3455 // potentially avoids a DOM write and prevents Firefox (~60.0.1) from
3456 // prematurely marking required inputs as invalid. Equality is compared
3457 // to the current value in case the browser provided value is not an
3458 // empty string.
3459 if (isButton || value !== node.value) {
3460 node.value = toString(value);
3461 }
3462 }
3463 } else {
3464 // When syncing the value attribute, the value property should use
3465 // the wrapperState._initialValue property. This uses:
3466 //
3467 // 1. The value React property when present
3468 // 2. The defaultValue React property when present
3469 // 3. An empty string
3470 if (_initialValue !== node.value) {
3471 node.value = _initialValue;
3472 }
3473 }
3474 }
3475
3476 if (disableInputAttributeSyncing) {
3477 // When not syncing the value attribute, assign the value attribute
3478 // directly from the defaultValue React property (when present)
3479 var defaultValue = getToStringValue(props.defaultValue);
3480 if (defaultValue != null) {
3481 node.defaultValue = toString(defaultValue);
3482 }
3483 } else {
3484 // Otherwise, the value attribute is synchronized to the property,
3485 // so we assign defaultValue to the same thing as the value property
3486 // assignment step above.
3487 node.defaultValue = _initialValue;
3488 }
3489 }
3490
3491 // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
3492 // this is needed to work around a chrome bug where setting defaultChecked
3493 // will sometimes influence the value of checked (even after detachment).
3494 // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
3495 // We need to temporarily unset name to avoid disrupting radio button groups.
3496 var name = node.name;
3497 if (name !== '') {
3498 node.name = '';
3499 }
3500
3501 if (disableInputAttributeSyncing) {
3502 // When not syncing the checked attribute, the checked property
3503 // never gets assigned. It must be manually set. We don't want
3504 // to do this when hydrating so that existing user input isn't
3505 // modified
3506 if (!isHydrating) {
3507 updateChecked(element, props);
3508 }
3509
3510 // Only assign the checked attribute if it is defined. This saves
3511 // a DOM write when controlling the checked attribute isn't needed
3512 // (text inputs, submit/reset)
3513 if (props.hasOwnProperty('defaultChecked')) {
3514 node.defaultChecked = !node.defaultChecked;
3515 node.defaultChecked = !!props.defaultChecked;
3516 }
3517 } else {
3518 // When syncing the checked attribute, both the checked property and
3519 // attribute are assigned at the same time using defaultChecked. This uses:
3520 //
3521 // 1. The checked React property when present
3522 // 2. The defaultChecked React property when present
3523 // 3. Otherwise, false
3524 node.defaultChecked = !node.defaultChecked;
3525 node.defaultChecked = !!node._wrapperState.initialChecked;
3526 }
3527
3528 if (name !== '') {
3529 node.name = name;
3530 }
3531}
3532
3533function restoreControlledState(element, props) {
3534 var node = element;
3535 updateWrapper(node, props);
3536 updateNamedCousins(node, props);
3537}
3538
3539function updateNamedCousins(rootNode, props) {
3540 var name = props.name;
3541 if (props.type === 'radio' && name != null) {
3542 var queryRoot = rootNode;
3543
3544 while (queryRoot.parentNode) {
3545 queryRoot = queryRoot.parentNode;
3546 }
3547
3548 // If `rootNode.form` was non-null, then we could try `form.elements`,
3549 // but that sometimes behaves strangely in IE8. We could also try using
3550 // `form.getElementsByName`, but that will only return direct children
3551 // and won't include inputs that use the HTML5 `form=` attribute. Since
3552 // the input might not even be in a form. It might not even be in the
3553 // document. Let's just use the local `querySelectorAll` to ensure we don't
3554 // miss anything.
3555 var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
3556
3557 for (var i = 0; i < group.length; i++) {
3558 var otherNode = group[i];
3559 if (otherNode === rootNode || otherNode.form !== rootNode.form) {
3560 continue;
3561 }
3562 // This will throw if radio buttons rendered by different copies of React
3563 // and the same name are rendered into the same form (same as #1939).
3564 // That's probably okay; we don't support it just as we don't support
3565 // mixing React radio buttons with non-React ones.
3566 var otherProps = getFiberCurrentPropsFromNode$1(otherNode);
3567 !otherProps ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : void 0;
3568
3569 // We need update the tracked value on the named cousin since the value
3570 // was changed but the input saw no event or value set
3571 updateValueIfChanged(otherNode);
3572
3573 // If this is a controlled radio button group, forcing the input that
3574 // was previously checked to update will cause it to be come re-checked
3575 // as appropriate.
3576 updateWrapper(otherNode, otherProps);
3577 }
3578 }
3579}
3580
3581// In Chrome, assigning defaultValue to certain input types triggers input validation.
3582// For number inputs, the display value loses trailing decimal points. For email inputs,
3583// Chrome raises "The specified value <x> is not a valid email address".
3584//
3585// Here we check to see if the defaultValue has actually changed, avoiding these problems
3586// when the user is inputting text
3587//
3588// https://github.com/facebook/react/issues/7253
3589function setDefaultValue(node, type, value) {
3590 if (
3591 // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
3592 type !== 'number' || node.ownerDocument.activeElement !== node) {
3593 if (value == null) {
3594 node.defaultValue = toString(node._wrapperState.initialValue);
3595 } else if (node.defaultValue !== toString(value)) {
3596 node.defaultValue = toString(value);
3597 }
3598 }
3599}
3600
3601var eventTypes$1 = {
3602 change: {
3603 phasedRegistrationNames: {
3604 bubbled: 'onChange',
3605 captured: 'onChangeCapture'
3606 },
3607 dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE]
3608 }
3609};
3610
3611function createAndAccumulateChangeEvent(inst, nativeEvent, target) {
3612 var event = SyntheticEvent.getPooled(eventTypes$1.change, inst, nativeEvent, target);
3613 event.type = 'change';
3614 // Flag this event loop as needing state restore.
3615 enqueueStateRestore(target);
3616 accumulateTwoPhaseDispatches(event);
3617 return event;
3618}
3619/**
3620 * For IE shims
3621 */
3622var activeElement = null;
3623var activeElementInst = null;
3624
3625/**
3626 * SECTION: handle `change` event
3627 */
3628function shouldUseChangeEvent(elem) {
3629 var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
3630 return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
3631}
3632
3633function manualDispatchChangeEvent(nativeEvent) {
3634 var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent));
3635
3636 // If change and propertychange bubbled, we'd just bind to it like all the
3637 // other events and have it go through ReactBrowserEventEmitter. Since it
3638 // doesn't, we manually listen for the events and so we have to enqueue and
3639 // process the abstract event manually.
3640 //
3641 // Batching is necessary here in order to ensure that all event handlers run
3642 // before the next rerender (including event handlers attached to ancestor
3643 // elements instead of directly on the input). Without this, controlled
3644 // components don't work properly in conjunction with event bubbling because
3645 // the component is rerendered and the value reverted before all the event
3646 // handlers can run. See https://github.com/facebook/react/issues/708.
3647 batchedUpdates(runEventInBatch, event);
3648}
3649
3650function runEventInBatch(event) {
3651 runEventsInBatch(event);
3652}
3653
3654function getInstIfValueChanged(targetInst) {
3655 var targetNode = getNodeFromInstance$1(targetInst);
3656 if (updateValueIfChanged(targetNode)) {
3657 return targetInst;
3658 }
3659}
3660
3661function getTargetInstForChangeEvent(topLevelType, targetInst) {
3662 if (topLevelType === TOP_CHANGE) {
3663 return targetInst;
3664 }
3665}
3666
3667/**
3668 * SECTION: handle `input` event
3669 */
3670var isInputEventSupported = false;
3671if (canUseDOM) {
3672 // IE9 claims to support the input event but fails to trigger it when
3673 // deleting text, so we ignore its input events.
3674 isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
3675}
3676
3677/**
3678 * (For IE <=9) Starts tracking propertychange events on the passed-in element
3679 * and override the value property so that we can distinguish user events from
3680 * value changes in JS.
3681 */
3682function startWatchingForValueChange(target, targetInst) {
3683 activeElement = target;
3684 activeElementInst = targetInst;
3685 activeElement.attachEvent('onpropertychange', handlePropertyChange);
3686}
3687
3688/**
3689 * (For IE <=9) Removes the event listeners from the currently-tracked element,
3690 * if any exists.
3691 */
3692function stopWatchingForValueChange() {
3693 if (!activeElement) {
3694 return;
3695 }
3696 activeElement.detachEvent('onpropertychange', handlePropertyChange);
3697 activeElement = null;
3698 activeElementInst = null;
3699}
3700
3701/**
3702 * (For IE <=9) Handles a propertychange event, sending a `change` event if
3703 * the value of the active element has changed.
3704 */
3705function handlePropertyChange(nativeEvent) {
3706 if (nativeEvent.propertyName !== 'value') {
3707 return;
3708 }
3709 if (getInstIfValueChanged(activeElementInst)) {
3710 manualDispatchChangeEvent(nativeEvent);
3711 }
3712}
3713
3714function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
3715 if (topLevelType === TOP_FOCUS) {
3716 // In IE9, propertychange fires for most input events but is buggy and
3717 // doesn't fire when text is deleted, but conveniently, selectionchange
3718 // appears to fire in all of the remaining cases so we catch those and
3719 // forward the event if the value has changed
3720 // In either case, we don't want to call the event handler if the value
3721 // is changed from JS so we redefine a setter for `.value` that updates
3722 // our activeElementValue variable, allowing us to ignore those changes
3723 //
3724 // stopWatching() should be a noop here but we call it just in case we
3725 // missed a blur event somehow.
3726 stopWatchingForValueChange();
3727 startWatchingForValueChange(target, targetInst);
3728 } else if (topLevelType === TOP_BLUR) {
3729 stopWatchingForValueChange();
3730 }
3731}
3732
3733// For IE8 and IE9.
3734function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {
3735 if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {
3736 // On the selectionchange event, the target is just document which isn't
3737 // helpful for us so just check activeElement instead.
3738 //
3739 // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
3740 // propertychange on the first input event after setting `value` from a
3741 // script and fires only keydown, keypress, keyup. Catching keyup usually
3742 // gets it and catching keydown lets us fire an event for the first
3743 // keystroke if user does a key repeat (it'll be a little delayed: right
3744 // before the second keystroke). Other input methods (e.g., paste) seem to
3745 // fire selectionchange normally.
3746 return getInstIfValueChanged(activeElementInst);
3747 }
3748}
3749
3750/**
3751 * SECTION: handle `click` event
3752 */
3753function shouldUseClickEvent(elem) {
3754 // Use the `click` event to detect changes to checkbox and radio inputs.
3755 // This approach works across all browsers, whereas `change` does not fire
3756 // until `blur` in IE8.
3757 var nodeName = elem.nodeName;
3758 return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
3759}
3760
3761function getTargetInstForClickEvent(topLevelType, targetInst) {
3762 if (topLevelType === TOP_CLICK) {
3763 return getInstIfValueChanged(targetInst);
3764 }
3765}
3766
3767function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {
3768 if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) {
3769 return getInstIfValueChanged(targetInst);
3770 }
3771}
3772
3773function handleControlledInputBlur(node) {
3774 var state = node._wrapperState;
3775
3776 if (!state || !state.controlled || node.type !== 'number') {
3777 return;
3778 }
3779
3780 if (!disableInputAttributeSyncing) {
3781 // If controlled, assign the value attribute to the current value on blur
3782 setDefaultValue(node, 'number', node.value);
3783 }
3784}
3785
3786/**
3787 * This plugin creates an `onChange` event that normalizes change events
3788 * across form elements. This event fires at a time when it's possible to
3789 * change the element's value without seeing a flicker.
3790 *
3791 * Supported elements are:
3792 * - input (see `isTextInputElement`)
3793 * - textarea
3794 * - select
3795 */
3796var ChangeEventPlugin = {
3797 eventTypes: eventTypes$1,
3798
3799 _isInputEventSupported: isInputEventSupported,
3800
3801 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
3802 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
3803
3804 var getTargetInstFunc = void 0,
3805 handleEventFunc = void 0;
3806 if (shouldUseChangeEvent(targetNode)) {
3807 getTargetInstFunc = getTargetInstForChangeEvent;
3808 } else if (isTextInputElement(targetNode)) {
3809 if (isInputEventSupported) {
3810 getTargetInstFunc = getTargetInstForInputOrChangeEvent;
3811 } else {
3812 getTargetInstFunc = getTargetInstForInputEventPolyfill;
3813 handleEventFunc = handleEventsForInputEventPolyfill;
3814 }
3815 } else if (shouldUseClickEvent(targetNode)) {
3816 getTargetInstFunc = getTargetInstForClickEvent;
3817 }
3818
3819 if (getTargetInstFunc) {
3820 var inst = getTargetInstFunc(topLevelType, targetInst);
3821 if (inst) {
3822 var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget);
3823 return event;
3824 }
3825 }
3826
3827 if (handleEventFunc) {
3828 handleEventFunc(topLevelType, targetNode, targetInst);
3829 }
3830
3831 // When blurring, set the value attribute for number inputs
3832 if (topLevelType === TOP_BLUR) {
3833 handleControlledInputBlur(targetNode);
3834 }
3835 }
3836};
3837
3838/**
3839 * Module that is injectable into `EventPluginHub`, that specifies a
3840 * deterministic ordering of `EventPlugin`s. A convenient way to reason about
3841 * plugins, without having to package every one of them. This is better than
3842 * having plugins be ordered in the same order that they are injected because
3843 * that ordering would be influenced by the packaging order.
3844 * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
3845 * preventing default on events is convenient in `SimpleEventPlugin` handlers.
3846 */
3847var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];
3848
3849var SyntheticUIEvent = SyntheticEvent.extend({
3850 view: null,
3851 detail: null
3852});
3853
3854var modifierKeyToProp = {
3855 Alt: 'altKey',
3856 Control: 'ctrlKey',
3857 Meta: 'metaKey',
3858 Shift: 'shiftKey'
3859};
3860
3861// Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
3862// getModifierState. If getModifierState is not supported, we map it to a set of
3863// modifier keys exposed by the event. In this case, Lock-keys are not supported.
3864/**
3865 * Translation from modifier key to the associated property in the event.
3866 * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
3867 */
3868
3869function modifierStateGetter(keyArg) {
3870 var syntheticEvent = this;
3871 var nativeEvent = syntheticEvent.nativeEvent;
3872 if (nativeEvent.getModifierState) {
3873 return nativeEvent.getModifierState(keyArg);
3874 }
3875 var keyProp = modifierKeyToProp[keyArg];
3876 return keyProp ? !!nativeEvent[keyProp] : false;
3877}
3878
3879function getEventModifierState(nativeEvent) {
3880 return modifierStateGetter;
3881}
3882
3883var previousScreenX = 0;
3884var previousScreenY = 0;
3885// Use flags to signal movementX/Y has already been set
3886var isMovementXSet = false;
3887var isMovementYSet = false;
3888
3889/**
3890 * @interface MouseEvent
3891 * @see http://www.w3.org/TR/DOM-Level-3-Events/
3892 */
3893var SyntheticMouseEvent = SyntheticUIEvent.extend({
3894 screenX: null,
3895 screenY: null,
3896 clientX: null,
3897 clientY: null,
3898 pageX: null,
3899 pageY: null,
3900 ctrlKey: null,
3901 shiftKey: null,
3902 altKey: null,
3903 metaKey: null,
3904 getModifierState: getEventModifierState,
3905 button: null,
3906 buttons: null,
3907 relatedTarget: function (event) {
3908 return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
3909 },
3910 movementX: function (event) {
3911 if ('movementX' in event) {
3912 return event.movementX;
3913 }
3914
3915 var screenX = previousScreenX;
3916 previousScreenX = event.screenX;
3917
3918 if (!isMovementXSet) {
3919 isMovementXSet = true;
3920 return 0;
3921 }
3922
3923 return event.type === 'mousemove' ? event.screenX - screenX : 0;
3924 },
3925 movementY: function (event) {
3926 if ('movementY' in event) {
3927 return event.movementY;
3928 }
3929
3930 var screenY = previousScreenY;
3931 previousScreenY = event.screenY;
3932
3933 if (!isMovementYSet) {
3934 isMovementYSet = true;
3935 return 0;
3936 }
3937
3938 return event.type === 'mousemove' ? event.screenY - screenY : 0;
3939 }
3940});
3941
3942/**
3943 * @interface PointerEvent
3944 * @see http://www.w3.org/TR/pointerevents/
3945 */
3946var SyntheticPointerEvent = SyntheticMouseEvent.extend({
3947 pointerId: null,
3948 width: null,
3949 height: null,
3950 pressure: null,
3951 tangentialPressure: null,
3952 tiltX: null,
3953 tiltY: null,
3954 twist: null,
3955 pointerType: null,
3956 isPrimary: null
3957});
3958
3959var eventTypes$2 = {
3960 mouseEnter: {
3961 registrationName: 'onMouseEnter',
3962 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
3963 },
3964 mouseLeave: {
3965 registrationName: 'onMouseLeave',
3966 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
3967 },
3968 pointerEnter: {
3969 registrationName: 'onPointerEnter',
3970 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
3971 },
3972 pointerLeave: {
3973 registrationName: 'onPointerLeave',
3974 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
3975 }
3976};
3977
3978var EnterLeaveEventPlugin = {
3979 eventTypes: eventTypes$2,
3980
3981 /**
3982 * For almost every interaction we care about, there will be both a top-level
3983 * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
3984 * we do not extract duplicate events. However, moving the mouse into the
3985 * browser from outside will not fire a `mouseout` event. In this case, we use
3986 * the `mouseover` top-level event.
3987 */
3988 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
3989 var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
3990 var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;
3991
3992 if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
3993 return null;
3994 }
3995
3996 if (!isOutEvent && !isOverEvent) {
3997 // Must not be a mouse or pointer in or out - ignoring.
3998 return null;
3999 }
4000
4001 var win = void 0;
4002 if (nativeEventTarget.window === nativeEventTarget) {
4003 // `nativeEventTarget` is probably a window object.
4004 win = nativeEventTarget;
4005 } else {
4006 // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
4007 var doc = nativeEventTarget.ownerDocument;
4008 if (doc) {
4009 win = doc.defaultView || doc.parentWindow;
4010 } else {
4011 win = window;
4012 }
4013 }
4014
4015 var from = void 0;
4016 var to = void 0;
4017 if (isOutEvent) {
4018 from = targetInst;
4019 var related = nativeEvent.relatedTarget || nativeEvent.toElement;
4020 to = related ? getClosestInstanceFromNode(related) : null;
4021 } else {
4022 // Moving to a node from outside the window.
4023 from = null;
4024 to = targetInst;
4025 }
4026
4027 if (from === to) {
4028 // Nothing pertains to our managed components.
4029 return null;
4030 }
4031
4032 var eventInterface = void 0,
4033 leaveEventType = void 0,
4034 enterEventType = void 0,
4035 eventTypePrefix = void 0;
4036
4037 if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
4038 eventInterface = SyntheticMouseEvent;
4039 leaveEventType = eventTypes$2.mouseLeave;
4040 enterEventType = eventTypes$2.mouseEnter;
4041 eventTypePrefix = 'mouse';
4042 } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {
4043 eventInterface = SyntheticPointerEvent;
4044 leaveEventType = eventTypes$2.pointerLeave;
4045 enterEventType = eventTypes$2.pointerEnter;
4046 eventTypePrefix = 'pointer';
4047 }
4048
4049 var fromNode = from == null ? win : getNodeFromInstance$1(from);
4050 var toNode = to == null ? win : getNodeFromInstance$1(to);
4051
4052 var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);
4053 leave.type = eventTypePrefix + 'leave';
4054 leave.target = fromNode;
4055 leave.relatedTarget = toNode;
4056
4057 var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);
4058 enter.type = eventTypePrefix + 'enter';
4059 enter.target = toNode;
4060 enter.relatedTarget = fromNode;
4061
4062 accumulateEnterLeaveDispatches(leave, enter, from, to);
4063
4064 return [leave, enter];
4065 }
4066};
4067
4068/**
4069 * inlined Object.is polyfill to avoid requiring consumers ship their own
4070 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
4071 */
4072function is(x, y) {
4073 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
4074 ;
4075}
4076
4077var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
4078
4079/**
4080 * Performs equality by iterating through keys on an object and returning false
4081 * when any key has values which are not strictly equal between the arguments.
4082 * Returns true when the values of all keys are strictly equal.
4083 */
4084function shallowEqual(objA, objB) {
4085 if (is(objA, objB)) {
4086 return true;
4087 }
4088
4089 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
4090 return false;
4091 }
4092
4093 var keysA = Object.keys(objA);
4094 var keysB = Object.keys(objB);
4095
4096 if (keysA.length !== keysB.length) {
4097 return false;
4098 }
4099
4100 // Test for A's keys different from B.
4101 for (var i = 0; i < keysA.length; i++) {
4102 if (!hasOwnProperty$1.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
4103 return false;
4104 }
4105 }
4106
4107 return true;
4108}
4109
4110/**
4111 * `ReactInstanceMap` maintains a mapping from a public facing stateful
4112 * instance (key) and the internal representation (value). This allows public
4113 * methods to accept the user facing instance as an argument and map them back
4114 * to internal methods.
4115 *
4116 * Note that this module is currently shared and assumed to be stateless.
4117 * If this becomes an actual Map, that will break.
4118 */
4119
4120/**
4121 * This API should be called `delete` but we'd have to make sure to always
4122 * transform these to strings for IE support. When this transform is fully
4123 * supported we can rename it.
4124 */
4125
4126
4127function get(key) {
4128 return key._reactInternalFiber;
4129}
4130
4131function has(key) {
4132 return key._reactInternalFiber !== undefined;
4133}
4134
4135function set(key, value) {
4136 key._reactInternalFiber = value;
4137}
4138
4139// Don't change these two values. They're used by React Dev Tools.
4140var NoEffect = /* */0;
4141var PerformedWork = /* */1;
4142
4143// You can change the rest (and add more).
4144var Placement = /* */2;
4145var Update = /* */4;
4146var PlacementAndUpdate = /* */6;
4147var Deletion = /* */8;
4148var ContentReset = /* */16;
4149var Callback = /* */32;
4150var DidCapture = /* */64;
4151var Ref = /* */128;
4152var Snapshot = /* */256;
4153var Passive = /* */512;
4154
4155// Passive & Update & Callback & Ref & Snapshot
4156var LifecycleEffectMask = /* */932;
4157
4158// Union of all host effects
4159var HostEffectMask = /* */1023;
4160
4161var Incomplete = /* */1024;
4162var ShouldCapture = /* */2048;
4163
4164var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
4165
4166var MOUNTING = 1;
4167var MOUNTED = 2;
4168var UNMOUNTED = 3;
4169
4170function isFiberMountedImpl(fiber) {
4171 var node = fiber;
4172 if (!fiber.alternate) {
4173 // If there is no alternate, this might be a new tree that isn't inserted
4174 // yet. If it is, then it will have a pending insertion effect on it.
4175 if ((node.effectTag & Placement) !== NoEffect) {
4176 return MOUNTING;
4177 }
4178 while (node.return) {
4179 node = node.return;
4180 if ((node.effectTag & Placement) !== NoEffect) {
4181 return MOUNTING;
4182 }
4183 }
4184 } else {
4185 while (node.return) {
4186 node = node.return;
4187 }
4188 }
4189 if (node.tag === HostRoot) {
4190 // TODO: Check if this was a nested HostRoot when used with
4191 // renderContainerIntoSubtree.
4192 return MOUNTED;
4193 }
4194 // If we didn't hit the root, that means that we're in an disconnected tree
4195 // that has been unmounted.
4196 return UNMOUNTED;
4197}
4198
4199function isFiberMounted(fiber) {
4200 return isFiberMountedImpl(fiber) === MOUNTED;
4201}
4202
4203function isMounted(component) {
4204 {
4205 var owner = ReactCurrentOwner$1.current;
4206 if (owner !== null && owner.tag === ClassComponent) {
4207 var ownerFiber = owner;
4208 var instance = ownerFiber.stateNode;
4209 !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;
4210 instance._warnedAboutRefsInRender = true;
4211 }
4212 }
4213
4214 var fiber = get(component);
4215 if (!fiber) {
4216 return false;
4217 }
4218 return isFiberMountedImpl(fiber) === MOUNTED;
4219}
4220
4221function assertIsMounted(fiber) {
4222 !(isFiberMountedImpl(fiber) === MOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
4223}
4224
4225function findCurrentFiberUsingSlowPath(fiber) {
4226 var alternate = fiber.alternate;
4227 if (!alternate) {
4228 // If there is no alternate, then we only need to check if it is mounted.
4229 var state = isFiberMountedImpl(fiber);
4230 !(state !== UNMOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
4231 if (state === MOUNTING) {
4232 return null;
4233 }
4234 return fiber;
4235 }
4236 // If we have two possible branches, we'll walk backwards up to the root
4237 // to see what path the root points to. On the way we may hit one of the
4238 // special cases and we'll deal with them.
4239 var a = fiber;
4240 var b = alternate;
4241 while (true) {
4242 var parentA = a.return;
4243 var parentB = parentA ? parentA.alternate : null;
4244 if (!parentA || !parentB) {
4245 // We're at the root.
4246 break;
4247 }
4248
4249 // If both copies of the parent fiber point to the same child, we can
4250 // assume that the child is current. This happens when we bailout on low
4251 // priority: the bailed out fiber's child reuses the current child.
4252 if (parentA.child === parentB.child) {
4253 var child = parentA.child;
4254 while (child) {
4255 if (child === a) {
4256 // We've determined that A is the current branch.
4257 assertIsMounted(parentA);
4258 return fiber;
4259 }
4260 if (child === b) {
4261 // We've determined that B is the current branch.
4262 assertIsMounted(parentA);
4263 return alternate;
4264 }
4265 child = child.sibling;
4266 }
4267 // We should never have an alternate for any mounting node. So the only
4268 // way this could possibly happen is if this was unmounted, if at all.
4269 invariant(false, 'Unable to find node on an unmounted component.');
4270 }
4271
4272 if (a.return !== b.return) {
4273 // The return pointer of A and the return pointer of B point to different
4274 // fibers. We assume that return pointers never criss-cross, so A must
4275 // belong to the child set of A.return, and B must belong to the child
4276 // set of B.return.
4277 a = parentA;
4278 b = parentB;
4279 } else {
4280 // The return pointers point to the same fiber. We'll have to use the
4281 // default, slow path: scan the child sets of each parent alternate to see
4282 // which child belongs to which set.
4283 //
4284 // Search parent A's child set
4285 var didFindChild = false;
4286 var _child = parentA.child;
4287 while (_child) {
4288 if (_child === a) {
4289 didFindChild = true;
4290 a = parentA;
4291 b = parentB;
4292 break;
4293 }
4294 if (_child === b) {
4295 didFindChild = true;
4296 b = parentA;
4297 a = parentB;
4298 break;
4299 }
4300 _child = _child.sibling;
4301 }
4302 if (!didFindChild) {
4303 // Search parent B's child set
4304 _child = parentB.child;
4305 while (_child) {
4306 if (_child === a) {
4307 didFindChild = true;
4308 a = parentB;
4309 b = parentA;
4310 break;
4311 }
4312 if (_child === b) {
4313 didFindChild = true;
4314 b = parentB;
4315 a = parentA;
4316 break;
4317 }
4318 _child = _child.sibling;
4319 }
4320 !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;
4321 }
4322 }
4323
4324 !(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;
4325 }
4326 // If the root is not a host container, we're in a disconnected tree. I.e.
4327 // unmounted.
4328 !(a.tag === HostRoot) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
4329 if (a.stateNode.current === a) {
4330 // We've determined that A is the current branch.
4331 return fiber;
4332 }
4333 // Otherwise B has to be current branch.
4334 return alternate;
4335}
4336
4337function findCurrentHostFiber(parent) {
4338 var currentParent = findCurrentFiberUsingSlowPath(parent);
4339 if (!currentParent) {
4340 return null;
4341 }
4342
4343 // Next we'll drill down this component to find the first HostComponent/Text.
4344 var node = currentParent;
4345 while (true) {
4346 if (node.tag === HostComponent || node.tag === HostText) {
4347 return node;
4348 } else if (node.child) {
4349 node.child.return = node;
4350 node = node.child;
4351 continue;
4352 }
4353 if (node === currentParent) {
4354 return null;
4355 }
4356 while (!node.sibling) {
4357 if (!node.return || node.return === currentParent) {
4358 return null;
4359 }
4360 node = node.return;
4361 }
4362 node.sibling.return = node.return;
4363 node = node.sibling;
4364 }
4365 // Flow needs the return null here, but ESLint complains about it.
4366 // eslint-disable-next-line no-unreachable
4367 return null;
4368}
4369
4370function findCurrentHostFiberWithNoPortals(parent) {
4371 var currentParent = findCurrentFiberUsingSlowPath(parent);
4372 if (!currentParent) {
4373 return null;
4374 }
4375
4376 // Next we'll drill down this component to find the first HostComponent/Text.
4377 var node = currentParent;
4378 while (true) {
4379 if (node.tag === HostComponent || node.tag === HostText) {
4380 return node;
4381 } else if (node.child && node.tag !== HostPortal) {
4382 node.child.return = node;
4383 node = node.child;
4384 continue;
4385 }
4386 if (node === currentParent) {
4387 return null;
4388 }
4389 while (!node.sibling) {
4390 if (!node.return || node.return === currentParent) {
4391 return null;
4392 }
4393 node = node.return;
4394 }
4395 node.sibling.return = node.return;
4396 node = node.sibling;
4397 }
4398 // Flow needs the return null here, but ESLint complains about it.
4399 // eslint-disable-next-line no-unreachable
4400 return null;
4401}
4402
4403function addEventBubbleListener(element, eventType, listener) {
4404 element.addEventListener(eventType, listener, false);
4405}
4406
4407function addEventCaptureListener(element, eventType, listener) {
4408 element.addEventListener(eventType, listener, true);
4409}
4410
4411/**
4412 * @interface Event
4413 * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
4414 * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
4415 */
4416var SyntheticAnimationEvent = SyntheticEvent.extend({
4417 animationName: null,
4418 elapsedTime: null,
4419 pseudoElement: null
4420});
4421
4422/**
4423 * @interface Event
4424 * @see http://www.w3.org/TR/clipboard-apis/
4425 */
4426var SyntheticClipboardEvent = SyntheticEvent.extend({
4427 clipboardData: function (event) {
4428 return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
4429 }
4430});
4431
4432/**
4433 * @interface FocusEvent
4434 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4435 */
4436var SyntheticFocusEvent = SyntheticUIEvent.extend({
4437 relatedTarget: null
4438});
4439
4440/**
4441 * `charCode` represents the actual "character code" and is safe to use with
4442 * `String.fromCharCode`. As such, only keys that correspond to printable
4443 * characters produce a valid `charCode`, the only exception to this is Enter.
4444 * The Tab-key is considered non-printable and does not have a `charCode`,
4445 * presumably because it does not produce a tab-character in browsers.
4446 *
4447 * @param {object} nativeEvent Native browser event.
4448 * @return {number} Normalized `charCode` property.
4449 */
4450function getEventCharCode(nativeEvent) {
4451 var charCode = void 0;
4452 var keyCode = nativeEvent.keyCode;
4453
4454 if ('charCode' in nativeEvent) {
4455 charCode = nativeEvent.charCode;
4456
4457 // FF does not set `charCode` for the Enter-key, check against `keyCode`.
4458 if (charCode === 0 && keyCode === 13) {
4459 charCode = 13;
4460 }
4461 } else {
4462 // IE8 does not implement `charCode`, but `keyCode` has the correct value.
4463 charCode = keyCode;
4464 }
4465
4466 // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
4467 // report Enter as charCode 10 when ctrl is pressed.
4468 if (charCode === 10) {
4469 charCode = 13;
4470 }
4471
4472 // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
4473 // Must not discard the (non-)printable Enter-key.
4474 if (charCode >= 32 || charCode === 13) {
4475 return charCode;
4476 }
4477
4478 return 0;
4479}
4480
4481/**
4482 * Normalization of deprecated HTML5 `key` values
4483 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
4484 */
4485var normalizeKey = {
4486 Esc: 'Escape',
4487 Spacebar: ' ',
4488 Left: 'ArrowLeft',
4489 Up: 'ArrowUp',
4490 Right: 'ArrowRight',
4491 Down: 'ArrowDown',
4492 Del: 'Delete',
4493 Win: 'OS',
4494 Menu: 'ContextMenu',
4495 Apps: 'ContextMenu',
4496 Scroll: 'ScrollLock',
4497 MozPrintableKey: 'Unidentified'
4498};
4499
4500/**
4501 * Translation from legacy `keyCode` to HTML5 `key`
4502 * Only special keys supported, all others depend on keyboard layout or browser
4503 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
4504 */
4505var translateToKey = {
4506 '8': 'Backspace',
4507 '9': 'Tab',
4508 '12': 'Clear',
4509 '13': 'Enter',
4510 '16': 'Shift',
4511 '17': 'Control',
4512 '18': 'Alt',
4513 '19': 'Pause',
4514 '20': 'CapsLock',
4515 '27': 'Escape',
4516 '32': ' ',
4517 '33': 'PageUp',
4518 '34': 'PageDown',
4519 '35': 'End',
4520 '36': 'Home',
4521 '37': 'ArrowLeft',
4522 '38': 'ArrowUp',
4523 '39': 'ArrowRight',
4524 '40': 'ArrowDown',
4525 '45': 'Insert',
4526 '46': 'Delete',
4527 '112': 'F1',
4528 '113': 'F2',
4529 '114': 'F3',
4530 '115': 'F4',
4531 '116': 'F5',
4532 '117': 'F6',
4533 '118': 'F7',
4534 '119': 'F8',
4535 '120': 'F9',
4536 '121': 'F10',
4537 '122': 'F11',
4538 '123': 'F12',
4539 '144': 'NumLock',
4540 '145': 'ScrollLock',
4541 '224': 'Meta'
4542};
4543
4544/**
4545 * @param {object} nativeEvent Native browser event.
4546 * @return {string} Normalized `key` property.
4547 */
4548function getEventKey(nativeEvent) {
4549 if (nativeEvent.key) {
4550 // Normalize inconsistent values reported by browsers due to
4551 // implementations of a working draft specification.
4552
4553 // FireFox implements `key` but returns `MozPrintableKey` for all
4554 // printable characters (normalized to `Unidentified`), ignore it.
4555 var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
4556 if (key !== 'Unidentified') {
4557 return key;
4558 }
4559 }
4560
4561 // Browser does not implement `key`, polyfill as much of it as we can.
4562 if (nativeEvent.type === 'keypress') {
4563 var charCode = getEventCharCode(nativeEvent);
4564
4565 // The enter-key is technically both printable and non-printable and can
4566 // thus be captured by `keypress`, no other non-printable key should.
4567 return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
4568 }
4569 if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
4570 // While user keyboard layout determines the actual meaning of each
4571 // `keyCode` value, almost all function keys have a universal value.
4572 return translateToKey[nativeEvent.keyCode] || 'Unidentified';
4573 }
4574 return '';
4575}
4576
4577/**
4578 * @interface KeyboardEvent
4579 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4580 */
4581var SyntheticKeyboardEvent = SyntheticUIEvent.extend({
4582 key: getEventKey,
4583 location: null,
4584 ctrlKey: null,
4585 shiftKey: null,
4586 altKey: null,
4587 metaKey: null,
4588 repeat: null,
4589 locale: null,
4590 getModifierState: getEventModifierState,
4591 // Legacy Interface
4592 charCode: function (event) {
4593 // `charCode` is the result of a KeyPress event and represents the value of
4594 // the actual printable character.
4595
4596 // KeyPress is deprecated, but its replacement is not yet final and not
4597 // implemented in any major browser. Only KeyPress has charCode.
4598 if (event.type === 'keypress') {
4599 return getEventCharCode(event);
4600 }
4601 return 0;
4602 },
4603 keyCode: function (event) {
4604 // `keyCode` is the result of a KeyDown/Up event and represents the value of
4605 // physical keyboard key.
4606
4607 // The actual meaning of the value depends on the users' keyboard layout
4608 // which cannot be detected. Assuming that it is a US keyboard layout
4609 // provides a surprisingly accurate mapping for US and European users.
4610 // Due to this, it is left to the user to implement at this time.
4611 if (event.type === 'keydown' || event.type === 'keyup') {
4612 return event.keyCode;
4613 }
4614 return 0;
4615 },
4616 which: function (event) {
4617 // `which` is an alias for either `keyCode` or `charCode` depending on the
4618 // type of the event.
4619 if (event.type === 'keypress') {
4620 return getEventCharCode(event);
4621 }
4622 if (event.type === 'keydown' || event.type === 'keyup') {
4623 return event.keyCode;
4624 }
4625 return 0;
4626 }
4627});
4628
4629/**
4630 * @interface DragEvent
4631 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4632 */
4633var SyntheticDragEvent = SyntheticMouseEvent.extend({
4634 dataTransfer: null
4635});
4636
4637/**
4638 * @interface TouchEvent
4639 * @see http://www.w3.org/TR/touch-events/
4640 */
4641var SyntheticTouchEvent = SyntheticUIEvent.extend({
4642 touches: null,
4643 targetTouches: null,
4644 changedTouches: null,
4645 altKey: null,
4646 metaKey: null,
4647 ctrlKey: null,
4648 shiftKey: null,
4649 getModifierState: getEventModifierState
4650});
4651
4652/**
4653 * @interface Event
4654 * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
4655 * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
4656 */
4657var SyntheticTransitionEvent = SyntheticEvent.extend({
4658 propertyName: null,
4659 elapsedTime: null,
4660 pseudoElement: null
4661});
4662
4663/**
4664 * @interface WheelEvent
4665 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4666 */
4667var SyntheticWheelEvent = SyntheticMouseEvent.extend({
4668 deltaX: function (event) {
4669 return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
4670 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
4671 },
4672 deltaY: function (event) {
4673 return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
4674 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
4675 'wheelDelta' in event ? -event.wheelDelta : 0;
4676 },
4677
4678 deltaZ: null,
4679
4680 // Browsers without "deltaMode" is reporting in raw wheel delta where one
4681 // notch on the scroll is always +/- 120, roughly equivalent to pixels.
4682 // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
4683 // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
4684 deltaMode: null
4685});
4686
4687/**
4688 * Turns
4689 * ['abort', ...]
4690 * into
4691 * eventTypes = {
4692 * 'abort': {
4693 * phasedRegistrationNames: {
4694 * bubbled: 'onAbort',
4695 * captured: 'onAbortCapture',
4696 * },
4697 * dependencies: [TOP_ABORT],
4698 * },
4699 * ...
4700 * };
4701 * topLevelEventsToDispatchConfig = new Map([
4702 * [TOP_ABORT, { sameConfig }],
4703 * ]);
4704 */
4705
4706var 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']];
4707var 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']];
4708
4709var eventTypes$4 = {};
4710var topLevelEventsToDispatchConfig = {};
4711
4712function addEventTypeNameToConfig(_ref, isInteractive) {
4713 var topEvent = _ref[0],
4714 event = _ref[1];
4715
4716 var capitalizedEvent = event[0].toUpperCase() + event.slice(1);
4717 var onEvent = 'on' + capitalizedEvent;
4718
4719 var type = {
4720 phasedRegistrationNames: {
4721 bubbled: onEvent,
4722 captured: onEvent + 'Capture'
4723 },
4724 dependencies: [topEvent],
4725 isInteractive: isInteractive
4726 };
4727 eventTypes$4[event] = type;
4728 topLevelEventsToDispatchConfig[topEvent] = type;
4729}
4730
4731interactiveEventTypeNames.forEach(function (eventTuple) {
4732 addEventTypeNameToConfig(eventTuple, true);
4733});
4734nonInteractiveEventTypeNames.forEach(function (eventTuple) {
4735 addEventTypeNameToConfig(eventTuple, false);
4736});
4737
4738// Only used in DEV for exhaustiveness validation.
4739var 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];
4740
4741var SimpleEventPlugin = {
4742 eventTypes: eventTypes$4,
4743
4744 isInteractiveTopLevelEventType: function (topLevelType) {
4745 var config = topLevelEventsToDispatchConfig[topLevelType];
4746 return config !== undefined && config.isInteractive === true;
4747 },
4748
4749
4750 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
4751 var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
4752 if (!dispatchConfig) {
4753 return null;
4754 }
4755 var EventConstructor = void 0;
4756 switch (topLevelType) {
4757 case TOP_KEY_PRESS:
4758 // Firefox creates a keypress event for function keys too. This removes
4759 // the unwanted keypress events. Enter is however both printable and
4760 // non-printable. One would expect Tab to be as well (but it isn't).
4761 if (getEventCharCode(nativeEvent) === 0) {
4762 return null;
4763 }
4764 /* falls through */
4765 case TOP_KEY_DOWN:
4766 case TOP_KEY_UP:
4767 EventConstructor = SyntheticKeyboardEvent;
4768 break;
4769 case TOP_BLUR:
4770 case TOP_FOCUS:
4771 EventConstructor = SyntheticFocusEvent;
4772 break;
4773 case TOP_CLICK:
4774 // Firefox creates a click event on right mouse clicks. This removes the
4775 // unwanted click events.
4776 if (nativeEvent.button === 2) {
4777 return null;
4778 }
4779 /* falls through */
4780 case TOP_AUX_CLICK:
4781 case TOP_DOUBLE_CLICK:
4782 case TOP_MOUSE_DOWN:
4783 case TOP_MOUSE_MOVE:
4784 case TOP_MOUSE_UP:
4785 // TODO: Disabled elements should not respond to mouse events
4786 /* falls through */
4787 case TOP_MOUSE_OUT:
4788 case TOP_MOUSE_OVER:
4789 case TOP_CONTEXT_MENU:
4790 EventConstructor = SyntheticMouseEvent;
4791 break;
4792 case TOP_DRAG:
4793 case TOP_DRAG_END:
4794 case TOP_DRAG_ENTER:
4795 case TOP_DRAG_EXIT:
4796 case TOP_DRAG_LEAVE:
4797 case TOP_DRAG_OVER:
4798 case TOP_DRAG_START:
4799 case TOP_DROP:
4800 EventConstructor = SyntheticDragEvent;
4801 break;
4802 case TOP_TOUCH_CANCEL:
4803 case TOP_TOUCH_END:
4804 case TOP_TOUCH_MOVE:
4805 case TOP_TOUCH_START:
4806 EventConstructor = SyntheticTouchEvent;
4807 break;
4808 case TOP_ANIMATION_END:
4809 case TOP_ANIMATION_ITERATION:
4810 case TOP_ANIMATION_START:
4811 EventConstructor = SyntheticAnimationEvent;
4812 break;
4813 case TOP_TRANSITION_END:
4814 EventConstructor = SyntheticTransitionEvent;
4815 break;
4816 case TOP_SCROLL:
4817 EventConstructor = SyntheticUIEvent;
4818 break;
4819 case TOP_WHEEL:
4820 EventConstructor = SyntheticWheelEvent;
4821 break;
4822 case TOP_COPY:
4823 case TOP_CUT:
4824 case TOP_PASTE:
4825 EventConstructor = SyntheticClipboardEvent;
4826 break;
4827 case TOP_GOT_POINTER_CAPTURE:
4828 case TOP_LOST_POINTER_CAPTURE:
4829 case TOP_POINTER_CANCEL:
4830 case TOP_POINTER_DOWN:
4831 case TOP_POINTER_MOVE:
4832 case TOP_POINTER_OUT:
4833 case TOP_POINTER_OVER:
4834 case TOP_POINTER_UP:
4835 EventConstructor = SyntheticPointerEvent;
4836 break;
4837 default:
4838 {
4839 if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {
4840 warningWithoutStack$1(false, 'SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType);
4841 }
4842 }
4843 // HTML Events
4844 // @see http://www.w3.org/TR/html5/index.html#events-0
4845 EventConstructor = SyntheticEvent;
4846 break;
4847 }
4848 var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
4849 accumulateTwoPhaseDispatches(event);
4850 return event;
4851 }
4852};
4853
4854var isInteractiveTopLevelEventType = SimpleEventPlugin.isInteractiveTopLevelEventType;
4855
4856
4857var CALLBACK_BOOKKEEPING_POOL_SIZE = 10;
4858var callbackBookkeepingPool = [];
4859
4860/**
4861 * Find the deepest React component completely containing the root of the
4862 * passed-in instance (for use when entire React trees are nested within each
4863 * other). If React trees are not nested, returns null.
4864 */
4865function findRootContainerNode(inst) {
4866 // TODO: It may be a good idea to cache this to prevent unnecessary DOM
4867 // traversal, but caching is difficult to do correctly without using a
4868 // mutation observer to listen for all DOM changes.
4869 while (inst.return) {
4870 inst = inst.return;
4871 }
4872 if (inst.tag !== HostRoot) {
4873 // This can happen if we're in a detached tree.
4874 return null;
4875 }
4876 return inst.stateNode.containerInfo;
4877}
4878
4879// Used to store ancestor hierarchy in top level callback
4880function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst) {
4881 if (callbackBookkeepingPool.length) {
4882 var instance = callbackBookkeepingPool.pop();
4883 instance.topLevelType = topLevelType;
4884 instance.nativeEvent = nativeEvent;
4885 instance.targetInst = targetInst;
4886 return instance;
4887 }
4888 return {
4889 topLevelType: topLevelType,
4890 nativeEvent: nativeEvent,
4891 targetInst: targetInst,
4892 ancestors: []
4893 };
4894}
4895
4896function releaseTopLevelCallbackBookKeeping(instance) {
4897 instance.topLevelType = null;
4898 instance.nativeEvent = null;
4899 instance.targetInst = null;
4900 instance.ancestors.length = 0;
4901 if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) {
4902 callbackBookkeepingPool.push(instance);
4903 }
4904}
4905
4906function handleTopLevel(bookKeeping) {
4907 var targetInst = bookKeeping.targetInst;
4908
4909 // Loop through the hierarchy, in case there's any nested components.
4910 // It's important that we build the array of ancestors before calling any
4911 // event handlers, because event handlers can modify the DOM, leading to
4912 // inconsistencies with ReactMount's node cache. See #1105.
4913 var ancestor = targetInst;
4914 do {
4915 if (!ancestor) {
4916 bookKeeping.ancestors.push(ancestor);
4917 break;
4918 }
4919 var root = findRootContainerNode(ancestor);
4920 if (!root) {
4921 break;
4922 }
4923 bookKeeping.ancestors.push(ancestor);
4924 ancestor = getClosestInstanceFromNode(root);
4925 } while (ancestor);
4926
4927 for (var i = 0; i < bookKeeping.ancestors.length; i++) {
4928 targetInst = bookKeeping.ancestors[i];
4929 runExtractedEventsInBatch(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
4930 }
4931}
4932
4933// TODO: can we stop exporting these?
4934var _enabled = true;
4935
4936function setEnabled(enabled) {
4937 _enabled = !!enabled;
4938}
4939
4940function isEnabled() {
4941 return _enabled;
4942}
4943
4944/**
4945 * Traps top-level events by using event bubbling.
4946 *
4947 * @param {number} topLevelType Number from `TopLevelEventTypes`.
4948 * @param {object} element Element on which to attach listener.
4949 * @return {?object} An object with a remove function which will forcefully
4950 * remove the listener.
4951 * @internal
4952 */
4953function trapBubbledEvent(topLevelType, element) {
4954 if (!element) {
4955 return null;
4956 }
4957 var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent;
4958
4959 addEventBubbleListener(element, getRawEventName(topLevelType),
4960 // Check if interactive and wrap in interactiveUpdates
4961 dispatch.bind(null, topLevelType));
4962}
4963
4964/**
4965 * Traps a top-level event by using event capturing.
4966 *
4967 * @param {number} topLevelType Number from `TopLevelEventTypes`.
4968 * @param {object} element Element on which to attach listener.
4969 * @return {?object} An object with a remove function which will forcefully
4970 * remove the listener.
4971 * @internal
4972 */
4973function trapCapturedEvent(topLevelType, element) {
4974 if (!element) {
4975 return null;
4976 }
4977 var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent;
4978
4979 addEventCaptureListener(element, getRawEventName(topLevelType),
4980 // Check if interactive and wrap in interactiveUpdates
4981 dispatch.bind(null, topLevelType));
4982}
4983
4984function dispatchInteractiveEvent(topLevelType, nativeEvent) {
4985 interactiveUpdates(dispatchEvent, topLevelType, nativeEvent);
4986}
4987
4988function dispatchEvent(topLevelType, nativeEvent) {
4989 if (!_enabled) {
4990 return;
4991 }
4992
4993 var nativeEventTarget = getEventTarget(nativeEvent);
4994 var targetInst = getClosestInstanceFromNode(nativeEventTarget);
4995 if (targetInst !== null && typeof targetInst.tag === 'number' && !isFiberMounted(targetInst)) {
4996 // If we get an event (ex: img onload) before committing that
4997 // component's mount, ignore it for now (that is, treat it as if it was an
4998 // event on a non-React tree). We might also consider queueing events and
4999 // dispatching them after the mount.
5000 targetInst = null;
5001 }
5002
5003 var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst);
5004
5005 try {
5006 // Event queue being processed in the same cycle allows
5007 // `preventDefault`.
5008 batchedUpdates(handleTopLevel, bookKeeping);
5009 } finally {
5010 releaseTopLevelCallbackBookKeeping(bookKeeping);
5011 }
5012}
5013
5014/**
5015 * Summary of `ReactBrowserEventEmitter` event handling:
5016 *
5017 * - Top-level delegation is used to trap most native browser events. This
5018 * may only occur in the main thread and is the responsibility of
5019 * ReactDOMEventListener, which is injected and can therefore support
5020 * pluggable event sources. This is the only work that occurs in the main
5021 * thread.
5022 *
5023 * - We normalize and de-duplicate events to account for browser quirks. This
5024 * may be done in the worker thread.
5025 *
5026 * - Forward these native events (with the associated top-level type used to
5027 * trap it) to `EventPluginHub`, which in turn will ask plugins if they want
5028 * to extract any synthetic events.
5029 *
5030 * - The `EventPluginHub` will then process each event by annotating them with
5031 * "dispatches", a sequence of listeners and IDs that care about that event.
5032 *
5033 * - The `EventPluginHub` then dispatches the events.
5034 *
5035 * Overview of React and the event system:
5036 *
5037 * +------------+ .
5038 * | DOM | .
5039 * +------------+ .
5040 * | .
5041 * v .
5042 * +------------+ .
5043 * | ReactEvent | .
5044 * | Listener | .
5045 * +------------+ . +-----------+
5046 * | . +--------+|SimpleEvent|
5047 * | . | |Plugin |
5048 * +-----|------+ . v +-----------+
5049 * | | | . +--------------+ +------------+
5050 * | +-----------.--->|EventPluginHub| | Event |
5051 * | | . | | +-----------+ | Propagators|
5052 * | ReactEvent | . | | |TapEvent | |------------|
5053 * | Emitter | . | |<---+|Plugin | |other plugin|
5054 * | | . | | +-----------+ | utilities |
5055 * | +-----------.--->| | +------------+
5056 * | | | . +--------------+
5057 * +-----|------+ . ^ +-----------+
5058 * | . | |Enter/Leave|
5059 * + . +-------+|Plugin |
5060 * +-------------+ . +-----------+
5061 * | application | .
5062 * |-------------| .
5063 * | | .
5064 * | | .
5065 * +-------------+ .
5066 * .
5067 * React Core . General Purpose Event Plugin System
5068 */
5069
5070var alreadyListeningTo = {};
5071var reactTopListenersCounter = 0;
5072
5073/**
5074 * To ensure no conflicts with other potential React instances on the page
5075 */
5076var topListenersIDKey = '_reactListenersID' + ('' + Math.random()).slice(2);
5077
5078function getListeningForDocument(mountAt) {
5079 // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
5080 // directly.
5081 if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) {
5082 mountAt[topListenersIDKey] = reactTopListenersCounter++;
5083 alreadyListeningTo[mountAt[topListenersIDKey]] = {};
5084 }
5085 return alreadyListeningTo[mountAt[topListenersIDKey]];
5086}
5087
5088/**
5089 * We listen for bubbled touch events on the document object.
5090 *
5091 * Firefox v8.01 (and possibly others) exhibited strange behavior when
5092 * mounting `onmousemove` events at some node that was not the document
5093 * element. The symptoms were that if your mouse is not moving over something
5094 * contained within that mount point (for example on the background) the
5095 * top-level listeners for `onmousemove` won't be called. However, if you
5096 * register the `mousemove` on the document object, then it will of course
5097 * catch all `mousemove`s. This along with iOS quirks, justifies restricting
5098 * top-level listeners to the document object only, at least for these
5099 * movement types of events and possibly all events.
5100 *
5101 * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
5102 *
5103 * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
5104 * they bubble to document.
5105 *
5106 * @param {string} registrationName Name of listener (e.g. `onClick`).
5107 * @param {object} mountAt Container where to mount the listener
5108 */
5109function listenTo(registrationName, mountAt) {
5110 var isListening = getListeningForDocument(mountAt);
5111 var dependencies = registrationNameDependencies[registrationName];
5112
5113 for (var i = 0; i < dependencies.length; i++) {
5114 var dependency = dependencies[i];
5115 if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
5116 switch (dependency) {
5117 case TOP_SCROLL:
5118 trapCapturedEvent(TOP_SCROLL, mountAt);
5119 break;
5120 case TOP_FOCUS:
5121 case TOP_BLUR:
5122 trapCapturedEvent(TOP_FOCUS, mountAt);
5123 trapCapturedEvent(TOP_BLUR, mountAt);
5124 // We set the flag for a single dependency later in this function,
5125 // but this ensures we mark both as attached rather than just one.
5126 isListening[TOP_BLUR] = true;
5127 isListening[TOP_FOCUS] = true;
5128 break;
5129 case TOP_CANCEL:
5130 case TOP_CLOSE:
5131 if (isEventSupported(getRawEventName(dependency))) {
5132 trapCapturedEvent(dependency, mountAt);
5133 }
5134 break;
5135 case TOP_INVALID:
5136 case TOP_SUBMIT:
5137 case TOP_RESET:
5138 // We listen to them on the target DOM elements.
5139 // Some of them bubble so we don't want them to fire twice.
5140 break;
5141 default:
5142 // By default, listen on the top level to all non-media events.
5143 // Media events don't bubble so adding the listener wouldn't do anything.
5144 var isMediaEvent = mediaEventTypes.indexOf(dependency) !== -1;
5145 if (!isMediaEvent) {
5146 trapBubbledEvent(dependency, mountAt);
5147 }
5148 break;
5149 }
5150 isListening[dependency] = true;
5151 }
5152 }
5153}
5154
5155function isListeningToAllDependencies(registrationName, mountAt) {
5156 var isListening = getListeningForDocument(mountAt);
5157 var dependencies = registrationNameDependencies[registrationName];
5158 for (var i = 0; i < dependencies.length; i++) {
5159 var dependency = dependencies[i];
5160 if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
5161 return false;
5162 }
5163 }
5164 return true;
5165}
5166
5167function getActiveElement(doc) {
5168 doc = doc || (typeof document !== 'undefined' ? document : undefined);
5169 if (typeof doc === 'undefined') {
5170 return null;
5171 }
5172 try {
5173 return doc.activeElement || doc.body;
5174 } catch (e) {
5175 return doc.body;
5176 }
5177}
5178
5179/**
5180 * Given any node return the first leaf node without children.
5181 *
5182 * @param {DOMElement|DOMTextNode} node
5183 * @return {DOMElement|DOMTextNode}
5184 */
5185function getLeafNode(node) {
5186 while (node && node.firstChild) {
5187 node = node.firstChild;
5188 }
5189 return node;
5190}
5191
5192/**
5193 * Get the next sibling within a container. This will walk up the
5194 * DOM if a node's siblings have been exhausted.
5195 *
5196 * @param {DOMElement|DOMTextNode} node
5197 * @return {?DOMElement|DOMTextNode}
5198 */
5199function getSiblingNode(node) {
5200 while (node) {
5201 if (node.nextSibling) {
5202 return node.nextSibling;
5203 }
5204 node = node.parentNode;
5205 }
5206}
5207
5208/**
5209 * Get object describing the nodes which contain characters at offset.
5210 *
5211 * @param {DOMElement|DOMTextNode} root
5212 * @param {number} offset
5213 * @return {?object}
5214 */
5215function getNodeForCharacterOffset(root, offset) {
5216 var node = getLeafNode(root);
5217 var nodeStart = 0;
5218 var nodeEnd = 0;
5219
5220 while (node) {
5221 if (node.nodeType === TEXT_NODE) {
5222 nodeEnd = nodeStart + node.textContent.length;
5223
5224 if (nodeStart <= offset && nodeEnd >= offset) {
5225 return {
5226 node: node,
5227 offset: offset - nodeStart
5228 };
5229 }
5230
5231 nodeStart = nodeEnd;
5232 }
5233
5234 node = getLeafNode(getSiblingNode(node));
5235 }
5236}
5237
5238/**
5239 * @param {DOMElement} outerNode
5240 * @return {?object}
5241 */
5242function getOffsets(outerNode) {
5243 var ownerDocument = outerNode.ownerDocument;
5244
5245 var win = ownerDocument && ownerDocument.defaultView || window;
5246 var selection = win.getSelection && win.getSelection();
5247
5248 if (!selection || selection.rangeCount === 0) {
5249 return null;
5250 }
5251
5252 var anchorNode = selection.anchorNode,
5253 anchorOffset = selection.anchorOffset,
5254 focusNode = selection.focusNode,
5255 focusOffset = selection.focusOffset;
5256
5257 // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
5258 // up/down buttons on an <input type="number">. Anonymous divs do not seem to
5259 // expose properties, triggering a "Permission denied error" if any of its
5260 // properties are accessed. The only seemingly possible way to avoid erroring
5261 // is to access a property that typically works for non-anonymous divs and
5262 // catch any error that may otherwise arise. See
5263 // https://bugzilla.mozilla.org/show_bug.cgi?id=208427
5264
5265 try {
5266 /* eslint-disable no-unused-expressions */
5267 anchorNode.nodeType;
5268 focusNode.nodeType;
5269 /* eslint-enable no-unused-expressions */
5270 } catch (e) {
5271 return null;
5272 }
5273
5274 return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
5275}
5276
5277/**
5278 * Returns {start, end} where `start` is the character/codepoint index of
5279 * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
5280 * `end` is the index of (focusNode, focusOffset).
5281 *
5282 * Returns null if you pass in garbage input but we should probably just crash.
5283 *
5284 * Exported only for testing.
5285 */
5286function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
5287 var length = 0;
5288 var start = -1;
5289 var end = -1;
5290 var indexWithinAnchor = 0;
5291 var indexWithinFocus = 0;
5292 var node = outerNode;
5293 var parentNode = null;
5294
5295 outer: while (true) {
5296 var next = null;
5297
5298 while (true) {
5299 if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
5300 start = length + anchorOffset;
5301 }
5302 if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
5303 end = length + focusOffset;
5304 }
5305
5306 if (node.nodeType === TEXT_NODE) {
5307 length += node.nodeValue.length;
5308 }
5309
5310 if ((next = node.firstChild) === null) {
5311 break;
5312 }
5313 // Moving from `node` to its first child `next`.
5314 parentNode = node;
5315 node = next;
5316 }
5317
5318 while (true) {
5319 if (node === outerNode) {
5320 // If `outerNode` has children, this is always the second time visiting
5321 // it. If it has no children, this is still the first loop, and the only
5322 // valid selection is anchorNode and focusNode both equal to this node
5323 // and both offsets 0, in which case we will have handled above.
5324 break outer;
5325 }
5326 if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
5327 start = length;
5328 }
5329 if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
5330 end = length;
5331 }
5332 if ((next = node.nextSibling) !== null) {
5333 break;
5334 }
5335 node = parentNode;
5336 parentNode = node.parentNode;
5337 }
5338
5339 // Moving from `node` to its next sibling `next`.
5340 node = next;
5341 }
5342
5343 if (start === -1 || end === -1) {
5344 // This should never happen. (Would happen if the anchor/focus nodes aren't
5345 // actually inside the passed-in node.)
5346 return null;
5347 }
5348
5349 return {
5350 start: start,
5351 end: end
5352 };
5353}
5354
5355/**
5356 * In modern non-IE browsers, we can support both forward and backward
5357 * selections.
5358 *
5359 * Note: IE10+ supports the Selection object, but it does not support
5360 * the `extend` method, which means that even in modern IE, it's not possible
5361 * to programmatically create a backward selection. Thus, for all IE
5362 * versions, we use the old IE API to create our selections.
5363 *
5364 * @param {DOMElement|DOMTextNode} node
5365 * @param {object} offsets
5366 */
5367function setOffsets(node, offsets) {
5368 var doc = node.ownerDocument || document;
5369 var win = doc && doc.defaultView || window;
5370
5371 // Edge fails with "Object expected" in some scenarios.
5372 // (For instance: TinyMCE editor used in a list component that supports pasting to add more,
5373 // fails when pasting 100+ items)
5374 if (!win.getSelection) {
5375 return;
5376 }
5377
5378 var selection = win.getSelection();
5379 var length = node.textContent.length;
5380 var start = Math.min(offsets.start, length);
5381 var end = offsets.end === undefined ? start : Math.min(offsets.end, length);
5382
5383 // IE 11 uses modern selection, but doesn't support the extend method.
5384 // Flip backward selections, so we can set with a single range.
5385 if (!selection.extend && start > end) {
5386 var temp = end;
5387 end = start;
5388 start = temp;
5389 }
5390
5391 var startMarker = getNodeForCharacterOffset(node, start);
5392 var endMarker = getNodeForCharacterOffset(node, end);
5393
5394 if (startMarker && endMarker) {
5395 if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
5396 return;
5397 }
5398 var range = doc.createRange();
5399 range.setStart(startMarker.node, startMarker.offset);
5400 selection.removeAllRanges();
5401
5402 if (start > end) {
5403 selection.addRange(range);
5404 selection.extend(endMarker.node, endMarker.offset);
5405 } else {
5406 range.setEnd(endMarker.node, endMarker.offset);
5407 selection.addRange(range);
5408 }
5409 }
5410}
5411
5412function isTextNode(node) {
5413 return node && node.nodeType === TEXT_NODE;
5414}
5415
5416function containsNode(outerNode, innerNode) {
5417 if (!outerNode || !innerNode) {
5418 return false;
5419 } else if (outerNode === innerNode) {
5420 return true;
5421 } else if (isTextNode(outerNode)) {
5422 return false;
5423 } else if (isTextNode(innerNode)) {
5424 return containsNode(outerNode, innerNode.parentNode);
5425 } else if ('contains' in outerNode) {
5426 return outerNode.contains(innerNode);
5427 } else if (outerNode.compareDocumentPosition) {
5428 return !!(outerNode.compareDocumentPosition(innerNode) & 16);
5429 } else {
5430 return false;
5431 }
5432}
5433
5434function isInDocument(node) {
5435 return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
5436}
5437
5438function getActiveElementDeep() {
5439 var win = window;
5440 var element = getActiveElement();
5441 while (element instanceof win.HTMLIFrameElement) {
5442 // Accessing the contentDocument of a HTMLIframeElement can cause the browser
5443 // to throw, e.g. if it has a cross-origin src attribute
5444 try {
5445 win = element.contentDocument.defaultView;
5446 } catch (e) {
5447 return element;
5448 }
5449 element = getActiveElement(win.document);
5450 }
5451 return element;
5452}
5453
5454/**
5455 * @ReactInputSelection: React input selection module. Based on Selection.js,
5456 * but modified to be suitable for react and has a couple of bug fixes (doesn't
5457 * assume buttons have range selections allowed).
5458 * Input selection module for React.
5459 */
5460
5461/**
5462 * @hasSelectionCapabilities: we get the element types that support selection
5463 * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
5464 * and `selectionEnd` rows.
5465 */
5466function hasSelectionCapabilities(elem) {
5467 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
5468 return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
5469}
5470
5471function getSelectionInformation() {
5472 var focusedElem = getActiveElementDeep();
5473 return {
5474 focusedElem: focusedElem,
5475 selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection$1(focusedElem) : null
5476 };
5477}
5478
5479/**
5480 * @restoreSelection: If any selection information was potentially lost,
5481 * restore it. This is useful when performing operations that could remove dom
5482 * nodes and place them back in, resulting in focus being lost.
5483 */
5484function restoreSelection(priorSelectionInformation) {
5485 var curFocusedElem = getActiveElementDeep();
5486 var priorFocusedElem = priorSelectionInformation.focusedElem;
5487 var priorSelectionRange = priorSelectionInformation.selectionRange;
5488 if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
5489 if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
5490 setSelection(priorFocusedElem, priorSelectionRange);
5491 }
5492
5493 // Focusing a node can change the scroll position, which is undesirable
5494 var ancestors = [];
5495 var ancestor = priorFocusedElem;
5496 while (ancestor = ancestor.parentNode) {
5497 if (ancestor.nodeType === ELEMENT_NODE) {
5498 ancestors.push({
5499 element: ancestor,
5500 left: ancestor.scrollLeft,
5501 top: ancestor.scrollTop
5502 });
5503 }
5504 }
5505
5506 if (typeof priorFocusedElem.focus === 'function') {
5507 priorFocusedElem.focus();
5508 }
5509
5510 for (var i = 0; i < ancestors.length; i++) {
5511 var info = ancestors[i];
5512 info.element.scrollLeft = info.left;
5513 info.element.scrollTop = info.top;
5514 }
5515 }
5516}
5517
5518/**
5519 * @getSelection: Gets the selection bounds of a focused textarea, input or
5520 * contentEditable node.
5521 * -@input: Look up selection bounds of this input
5522 * -@return {start: selectionStart, end: selectionEnd}
5523 */
5524function getSelection$1(input) {
5525 var selection = void 0;
5526
5527 if ('selectionStart' in input) {
5528 // Modern browser with input or textarea.
5529 selection = {
5530 start: input.selectionStart,
5531 end: input.selectionEnd
5532 };
5533 } else {
5534 // Content editable or old IE textarea.
5535 selection = getOffsets(input);
5536 }
5537
5538 return selection || { start: 0, end: 0 };
5539}
5540
5541/**
5542 * @setSelection: Sets the selection bounds of a textarea or input and focuses
5543 * the input.
5544 * -@input Set selection bounds of this input or textarea
5545 * -@offsets Object of same form that is returned from get*
5546 */
5547function setSelection(input, offsets) {
5548 var start = offsets.start,
5549 end = offsets.end;
5550
5551 if (end === undefined) {
5552 end = start;
5553 }
5554
5555 if ('selectionStart' in input) {
5556 input.selectionStart = start;
5557 input.selectionEnd = Math.min(end, input.value.length);
5558 } else {
5559 setOffsets(input, offsets);
5560 }
5561}
5562
5563var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;
5564
5565var eventTypes$3 = {
5566 select: {
5567 phasedRegistrationNames: {
5568 bubbled: 'onSelect',
5569 captured: 'onSelectCapture'
5570 },
5571 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]
5572 }
5573};
5574
5575var activeElement$1 = null;
5576var activeElementInst$1 = null;
5577var lastSelection = null;
5578var mouseDown = false;
5579
5580/**
5581 * Get an object which is a unique representation of the current selection.
5582 *
5583 * The return value will not be consistent across nodes or browsers, but
5584 * two identical selections on the same node will return identical objects.
5585 *
5586 * @param {DOMElement} node
5587 * @return {object}
5588 */
5589function getSelection(node) {
5590 if ('selectionStart' in node && hasSelectionCapabilities(node)) {
5591 return {
5592 start: node.selectionStart,
5593 end: node.selectionEnd
5594 };
5595 } else {
5596 var win = node.ownerDocument && node.ownerDocument.defaultView || window;
5597 var selection = win.getSelection();
5598 return {
5599 anchorNode: selection.anchorNode,
5600 anchorOffset: selection.anchorOffset,
5601 focusNode: selection.focusNode,
5602 focusOffset: selection.focusOffset
5603 };
5604 }
5605}
5606
5607/**
5608 * Get document associated with the event target.
5609 *
5610 * @param {object} nativeEventTarget
5611 * @return {Document}
5612 */
5613function getEventTargetDocument(eventTarget) {
5614 return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
5615}
5616
5617/**
5618 * Poll selection to see whether it's changed.
5619 *
5620 * @param {object} nativeEvent
5621 * @param {object} nativeEventTarget
5622 * @return {?SyntheticEvent}
5623 */
5624function constructSelectEvent(nativeEvent, nativeEventTarget) {
5625 // Ensure we have the right element, and that the user is not dragging a
5626 // selection (this matches native `select` event behavior). In HTML5, select
5627 // fires only on input and textarea thus if there's no focused element we
5628 // won't dispatch.
5629 var doc = getEventTargetDocument(nativeEventTarget);
5630
5631 if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
5632 return null;
5633 }
5634
5635 // Only fire when selection has actually changed.
5636 var currentSelection = getSelection(activeElement$1);
5637 if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
5638 lastSelection = currentSelection;
5639
5640 var syntheticEvent = SyntheticEvent.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget);
5641
5642 syntheticEvent.type = 'select';
5643 syntheticEvent.target = activeElement$1;
5644
5645 accumulateTwoPhaseDispatches(syntheticEvent);
5646
5647 return syntheticEvent;
5648 }
5649
5650 return null;
5651}
5652
5653/**
5654 * This plugin creates an `onSelect` event that normalizes select events
5655 * across form elements.
5656 *
5657 * Supported elements are:
5658 * - input (see `isTextInputElement`)
5659 * - textarea
5660 * - contentEditable
5661 *
5662 * This differs from native browser implementations in the following ways:
5663 * - Fires on contentEditable fields as well as inputs.
5664 * - Fires for collapsed selection.
5665 * - Fires after user input.
5666 */
5667var SelectEventPlugin = {
5668 eventTypes: eventTypes$3,
5669
5670 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
5671 var doc = getEventTargetDocument(nativeEventTarget);
5672 // Track whether all listeners exists for this plugin. If none exist, we do
5673 // not extract events. See #3639.
5674 if (!doc || !isListeningToAllDependencies('onSelect', doc)) {
5675 return null;
5676 }
5677
5678 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
5679
5680 switch (topLevelType) {
5681 // Track the input node that has focus.
5682 case TOP_FOCUS:
5683 if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
5684 activeElement$1 = targetNode;
5685 activeElementInst$1 = targetInst;
5686 lastSelection = null;
5687 }
5688 break;
5689 case TOP_BLUR:
5690 activeElement$1 = null;
5691 activeElementInst$1 = null;
5692 lastSelection = null;
5693 break;
5694 // Don't fire the event while the user is dragging. This matches the
5695 // semantics of the native select event.
5696 case TOP_MOUSE_DOWN:
5697 mouseDown = true;
5698 break;
5699 case TOP_CONTEXT_MENU:
5700 case TOP_MOUSE_UP:
5701 case TOP_DRAG_END:
5702 mouseDown = false;
5703 return constructSelectEvent(nativeEvent, nativeEventTarget);
5704 // Chrome and IE fire non-standard event when selection is changed (and
5705 // sometimes when it hasn't). IE's event fires out of order with respect
5706 // to key and input events on deletion, so we discard it.
5707 //
5708 // Firefox doesn't support selectionchange, so check selection status
5709 // after each key entry. The selection changes after keydown and before
5710 // keyup, but we check on keydown as well in the case of holding down a
5711 // key, when multiple keydown events are fired but only one keyup is.
5712 // This is also our approach for IE handling, for the reason above.
5713 case TOP_SELECTION_CHANGE:
5714 if (skipSelectionChangeEvent) {
5715 break;
5716 }
5717 // falls through
5718 case TOP_KEY_DOWN:
5719 case TOP_KEY_UP:
5720 return constructSelectEvent(nativeEvent, nativeEventTarget);
5721 }
5722
5723 return null;
5724 }
5725};
5726
5727/**
5728 * Inject modules for resolving DOM hierarchy and plugin ordering.
5729 */
5730injection.injectEventPluginOrder(DOMEventPluginOrder);
5731setComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);
5732
5733/**
5734 * Some important event plugins included by default (without having to require
5735 * them).
5736 */
5737injection.injectEventPluginsByName({
5738 SimpleEventPlugin: SimpleEventPlugin,
5739 EnterLeaveEventPlugin: EnterLeaveEventPlugin,
5740 ChangeEventPlugin: ChangeEventPlugin,
5741 SelectEventPlugin: SelectEventPlugin,
5742 BeforeInputEventPlugin: BeforeInputEventPlugin
5743});
5744
5745var didWarnSelectedSetOnOption = false;
5746var didWarnInvalidChild = false;
5747
5748function flattenChildren(children) {
5749 var content = '';
5750
5751 // Flatten children. We'll warn if they are invalid
5752 // during validateProps() which runs for hydration too.
5753 // Note that this would throw on non-element objects.
5754 // Elements are stringified (which is normally irrelevant
5755 // but matters for <fbt>).
5756 React.Children.forEach(children, function (child) {
5757 if (child == null) {
5758 return;
5759 }
5760 content += child;
5761 // Note: we don't warn about invalid children here.
5762 // Instead, this is done separately below so that
5763 // it happens during the hydration codepath too.
5764 });
5765
5766 return content;
5767}
5768
5769/**
5770 * Implements an <option> host component that warns when `selected` is set.
5771 */
5772
5773function validateProps(element, props) {
5774 {
5775 // This mirrors the codepath above, but runs for hydration too.
5776 // Warn about invalid children here so that client and hydration are consistent.
5777 // TODO: this seems like it could cause a DEV-only throw for hydration
5778 // if children contains a non-element object. We should try to avoid that.
5779 if (typeof props.children === 'object' && props.children !== null) {
5780 React.Children.forEach(props.children, function (child) {
5781 if (child == null) {
5782 return;
5783 }
5784 if (typeof child === 'string' || typeof child === 'number') {
5785 return;
5786 }
5787 if (typeof child.type !== 'string') {
5788 return;
5789 }
5790 if (!didWarnInvalidChild) {
5791 didWarnInvalidChild = true;
5792 warning$1(false, 'Only strings and numbers are supported as <option> children.');
5793 }
5794 });
5795 }
5796
5797 // TODO: Remove support for `selected` in <option>.
5798 if (props.selected != null && !didWarnSelectedSetOnOption) {
5799 warning$1(false, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
5800 didWarnSelectedSetOnOption = true;
5801 }
5802 }
5803}
5804
5805function postMountWrapper$1(element, props) {
5806 // value="" should make a value attribute (#6219)
5807 if (props.value != null) {
5808 element.setAttribute('value', toString(getToStringValue(props.value)));
5809 }
5810}
5811
5812function getHostProps$1(element, props) {
5813 var hostProps = _assign({ children: undefined }, props);
5814 var content = flattenChildren(props.children);
5815
5816 if (content) {
5817 hostProps.children = content;
5818 }
5819
5820 return hostProps;
5821}
5822
5823// TODO: direct imports like some-package/src/* are bad. Fix me.
5824var didWarnValueDefaultValue$1 = void 0;
5825
5826{
5827 didWarnValueDefaultValue$1 = false;
5828}
5829
5830function getDeclarationErrorAddendum() {
5831 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
5832 if (ownerName) {
5833 return '\n\nCheck the render method of `' + ownerName + '`.';
5834 }
5835 return '';
5836}
5837
5838var valuePropNames = ['value', 'defaultValue'];
5839
5840/**
5841 * Validation function for `value` and `defaultValue`.
5842 */
5843function checkSelectPropTypes(props) {
5844 ReactControlledValuePropTypes.checkPropTypes('select', props);
5845
5846 for (var i = 0; i < valuePropNames.length; i++) {
5847 var propName = valuePropNames[i];
5848 if (props[propName] == null) {
5849 continue;
5850 }
5851 var isArray = Array.isArray(props[propName]);
5852 if (props.multiple && !isArray) {
5853 warning$1(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
5854 } else if (!props.multiple && isArray) {
5855 warning$1(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
5856 }
5857 }
5858}
5859
5860function updateOptions(node, multiple, propValue, setDefaultSelected) {
5861 var options = node.options;
5862
5863 if (multiple) {
5864 var selectedValues = propValue;
5865 var selectedValue = {};
5866 for (var i = 0; i < selectedValues.length; i++) {
5867 // Prefix to avoid chaos with special keys.
5868 selectedValue['$' + selectedValues[i]] = true;
5869 }
5870 for (var _i = 0; _i < options.length; _i++) {
5871 var selected = selectedValue.hasOwnProperty('$' + options[_i].value);
5872 if (options[_i].selected !== selected) {
5873 options[_i].selected = selected;
5874 }
5875 if (selected && setDefaultSelected) {
5876 options[_i].defaultSelected = true;
5877 }
5878 }
5879 } else {
5880 // Do not set `select.value` as exact behavior isn't consistent across all
5881 // browsers for all cases.
5882 var _selectedValue = toString(getToStringValue(propValue));
5883 var defaultSelected = null;
5884 for (var _i2 = 0; _i2 < options.length; _i2++) {
5885 if (options[_i2].value === _selectedValue) {
5886 options[_i2].selected = true;
5887 if (setDefaultSelected) {
5888 options[_i2].defaultSelected = true;
5889 }
5890 return;
5891 }
5892 if (defaultSelected === null && !options[_i2].disabled) {
5893 defaultSelected = options[_i2];
5894 }
5895 }
5896 if (defaultSelected !== null) {
5897 defaultSelected.selected = true;
5898 }
5899 }
5900}
5901
5902/**
5903 * Implements a <select> host component that allows optionally setting the
5904 * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
5905 * stringable. If `multiple` is true, the prop must be an array of stringables.
5906 *
5907 * If `value` is not supplied (or null/undefined), user actions that change the
5908 * selected option will trigger updates to the rendered options.
5909 *
5910 * If it is supplied (and not null/undefined), the rendered options will not
5911 * update in response to user actions. Instead, the `value` prop must change in
5912 * order for the rendered options to update.
5913 *
5914 * If `defaultValue` is provided, any options with the supplied values will be
5915 * selected.
5916 */
5917
5918function getHostProps$2(element, props) {
5919 return _assign({}, props, {
5920 value: undefined
5921 });
5922}
5923
5924function initWrapperState$1(element, props) {
5925 var node = element;
5926 {
5927 checkSelectPropTypes(props);
5928 }
5929
5930 node._wrapperState = {
5931 wasMultiple: !!props.multiple
5932 };
5933
5934 {
5935 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
5936 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');
5937 didWarnValueDefaultValue$1 = true;
5938 }
5939 }
5940}
5941
5942function postMountWrapper$2(element, props) {
5943 var node = element;
5944 node.multiple = !!props.multiple;
5945 var value = props.value;
5946 if (value != null) {
5947 updateOptions(node, !!props.multiple, value, false);
5948 } else if (props.defaultValue != null) {
5949 updateOptions(node, !!props.multiple, props.defaultValue, true);
5950 }
5951}
5952
5953function postUpdateWrapper(element, props) {
5954 var node = element;
5955 var wasMultiple = node._wrapperState.wasMultiple;
5956 node._wrapperState.wasMultiple = !!props.multiple;
5957
5958 var value = props.value;
5959 if (value != null) {
5960 updateOptions(node, !!props.multiple, value, false);
5961 } else if (wasMultiple !== !!props.multiple) {
5962 // For simplicity, reapply `defaultValue` if `multiple` is toggled.
5963 if (props.defaultValue != null) {
5964 updateOptions(node, !!props.multiple, props.defaultValue, true);
5965 } else {
5966 // Revert the select back to its default unselected state.
5967 updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
5968 }
5969 }
5970}
5971
5972function restoreControlledState$2(element, props) {
5973 var node = element;
5974 var value = props.value;
5975
5976 if (value != null) {
5977 updateOptions(node, !!props.multiple, value, false);
5978 }
5979}
5980
5981var didWarnValDefaultVal = false;
5982
5983/**
5984 * Implements a <textarea> host component that allows setting `value`, and
5985 * `defaultValue`. This differs from the traditional DOM API because value is
5986 * usually set as PCDATA children.
5987 *
5988 * If `value` is not supplied (or null/undefined), user actions that affect the
5989 * value will trigger updates to the element.
5990 *
5991 * If `value` is supplied (and not null/undefined), the rendered element will
5992 * not trigger updates to the element. Instead, the `value` prop must change in
5993 * order for the rendered element to be updated.
5994 *
5995 * The rendered element will be initialized with an empty value, the prop
5996 * `defaultValue` if specified, or the children content (deprecated).
5997 */
5998
5999function getHostProps$3(element, props) {
6000 var node = element;
6001 !(props.dangerouslySetInnerHTML == null) ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : void 0;
6002
6003 // Always set children to the same thing. In IE9, the selection range will
6004 // get reset if `textContent` is mutated. We could add a check in setTextContent
6005 // to only set the value if/when the value differs from the node value (which would
6006 // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
6007 // solution. The value can be a boolean or object so that's why it's forced
6008 // to be a string.
6009 var hostProps = _assign({}, props, {
6010 value: undefined,
6011 defaultValue: undefined,
6012 children: toString(node._wrapperState.initialValue)
6013 });
6014
6015 return hostProps;
6016}
6017
6018function initWrapperState$2(element, props) {
6019 var node = element;
6020 {
6021 ReactControlledValuePropTypes.checkPropTypes('textarea', props);
6022 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
6023 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');
6024 didWarnValDefaultVal = true;
6025 }
6026 }
6027
6028 var initialValue = props.value;
6029
6030 // Only bother fetching default value if we're going to use it
6031 if (initialValue == null) {
6032 var defaultValue = props.defaultValue;
6033 // TODO (yungsters): Remove support for children content in <textarea>.
6034 var children = props.children;
6035 if (children != null) {
6036 {
6037 warning$1(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
6038 }
6039 !(defaultValue == null) ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : void 0;
6040 if (Array.isArray(children)) {
6041 !(children.length <= 1) ? invariant(false, '<textarea> can only have at most one child.') : void 0;
6042 children = children[0];
6043 }
6044
6045 defaultValue = children;
6046 }
6047 if (defaultValue == null) {
6048 defaultValue = '';
6049 }
6050 initialValue = defaultValue;
6051 }
6052
6053 node._wrapperState = {
6054 initialValue: getToStringValue(initialValue)
6055 };
6056}
6057
6058function updateWrapper$1(element, props) {
6059 var node = element;
6060 var value = getToStringValue(props.value);
6061 var defaultValue = getToStringValue(props.defaultValue);
6062 if (value != null) {
6063 // Cast `value` to a string to ensure the value is set correctly. While
6064 // browsers typically do this as necessary, jsdom doesn't.
6065 var newValue = toString(value);
6066 // To avoid side effects (such as losing text selection), only set value if changed
6067 if (newValue !== node.value) {
6068 node.value = newValue;
6069 }
6070 if (props.defaultValue == null && node.defaultValue !== newValue) {
6071 node.defaultValue = newValue;
6072 }
6073 }
6074 if (defaultValue != null) {
6075 node.defaultValue = toString(defaultValue);
6076 }
6077}
6078
6079function postMountWrapper$3(element, props) {
6080 var node = element;
6081 // This is in postMount because we need access to the DOM node, which is not
6082 // available until after the component has mounted.
6083 var textContent = node.textContent;
6084
6085 // Only set node.value if textContent is equal to the expected
6086 // initial value. In IE10/IE11 there is a bug where the placeholder attribute
6087 // will populate textContent as well.
6088 // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
6089 if (textContent === node._wrapperState.initialValue) {
6090 node.value = textContent;
6091 }
6092}
6093
6094function restoreControlledState$3(element, props) {
6095 // DOM component is still mounted; update
6096 updateWrapper$1(element, props);
6097}
6098
6099var HTML_NAMESPACE$1 = 'http://www.w3.org/1999/xhtml';
6100var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
6101var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
6102
6103var Namespaces = {
6104 html: HTML_NAMESPACE$1,
6105 mathml: MATH_NAMESPACE,
6106 svg: SVG_NAMESPACE
6107};
6108
6109// Assumes there is no parent namespace.
6110function getIntrinsicNamespace(type) {
6111 switch (type) {
6112 case 'svg':
6113 return SVG_NAMESPACE;
6114 case 'math':
6115 return MATH_NAMESPACE;
6116 default:
6117 return HTML_NAMESPACE$1;
6118 }
6119}
6120
6121function getChildNamespace(parentNamespace, type) {
6122 if (parentNamespace == null || parentNamespace === HTML_NAMESPACE$1) {
6123 // No (or default) parent namespace: potential entry point.
6124 return getIntrinsicNamespace(type);
6125 }
6126 if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
6127 // We're leaving SVG.
6128 return HTML_NAMESPACE$1;
6129 }
6130 // By default, pass namespace below.
6131 return parentNamespace;
6132}
6133
6134/* globals MSApp */
6135
6136/**
6137 * Create a function which has 'unsafe' privileges (required by windows8 apps)
6138 */
6139var createMicrosoftUnsafeLocalFunction = function (func) {
6140 if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
6141 return function (arg0, arg1, arg2, arg3) {
6142 MSApp.execUnsafeLocalFunction(function () {
6143 return func(arg0, arg1, arg2, arg3);
6144 });
6145 };
6146 } else {
6147 return func;
6148 }
6149};
6150
6151// SVG temp container for IE lacking innerHTML
6152var reusableSVGContainer = void 0;
6153
6154/**
6155 * Set the innerHTML property of a node
6156 *
6157 * @param {DOMElement} node
6158 * @param {string} html
6159 * @internal
6160 */
6161var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
6162 // IE does not have innerHTML for SVG nodes, so instead we inject the
6163 // new markup in a temp node and then move the child nodes across into
6164 // the target node
6165
6166 if (node.namespaceURI === Namespaces.svg && !('innerHTML' in node)) {
6167 reusableSVGContainer = reusableSVGContainer || document.createElement('div');
6168 reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
6169 var svgNode = reusableSVGContainer.firstChild;
6170 while (node.firstChild) {
6171 node.removeChild(node.firstChild);
6172 }
6173 while (svgNode.firstChild) {
6174 node.appendChild(svgNode.firstChild);
6175 }
6176 } else {
6177 node.innerHTML = html;
6178 }
6179});
6180
6181/**
6182 * Set the textContent property of a node. For text updates, it's faster
6183 * to set the `nodeValue` of the Text node directly instead of using
6184 * `.textContent` which will remove the existing node and create a new one.
6185 *
6186 * @param {DOMElement} node
6187 * @param {string} text
6188 * @internal
6189 */
6190var setTextContent = function (node, text) {
6191 if (text) {
6192 var firstChild = node.firstChild;
6193
6194 if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
6195 firstChild.nodeValue = text;
6196 return;
6197 }
6198 }
6199 node.textContent = text;
6200};
6201
6202// List derived from Gecko source code:
6203// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
6204var shorthandToLonghand = {
6205 animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
6206 background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
6207 backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
6208 border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6209 borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
6210 borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
6211 borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
6212 borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
6213 borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
6214 borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
6215 borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
6216 borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
6217 borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
6218 borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
6219 borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
6220 borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6221 borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
6222 columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
6223 columns: ['columnCount', 'columnWidth'],
6224 flex: ['flexBasis', 'flexGrow', 'flexShrink'],
6225 flexFlow: ['flexDirection', 'flexWrap'],
6226 font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
6227 fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
6228 gap: ['columnGap', 'rowGap'],
6229 grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6230 gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
6231 gridColumn: ['gridColumnEnd', 'gridColumnStart'],
6232 gridColumnGap: ['columnGap'],
6233 gridGap: ['columnGap', 'rowGap'],
6234 gridRow: ['gridRowEnd', 'gridRowStart'],
6235 gridRowGap: ['rowGap'],
6236 gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6237 listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
6238 margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
6239 marker: ['markerEnd', 'markerMid', 'markerStart'],
6240 mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
6241 maskPosition: ['maskPositionX', 'maskPositionY'],
6242 outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
6243 overflow: ['overflowX', 'overflowY'],
6244 padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
6245 placeContent: ['alignContent', 'justifyContent'],
6246 placeItems: ['alignItems', 'justifyItems'],
6247 placeSelf: ['alignSelf', 'justifySelf'],
6248 textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
6249 textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
6250 transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
6251 wordWrap: ['overflowWrap']
6252};
6253
6254/**
6255 * CSS properties which accept numbers but are not in units of "px".
6256 */
6257var isUnitlessNumber = {
6258 animationIterationCount: true,
6259 borderImageOutset: true,
6260 borderImageSlice: true,
6261 borderImageWidth: true,
6262 boxFlex: true,
6263 boxFlexGroup: true,
6264 boxOrdinalGroup: true,
6265 columnCount: true,
6266 columns: true,
6267 flex: true,
6268 flexGrow: true,
6269 flexPositive: true,
6270 flexShrink: true,
6271 flexNegative: true,
6272 flexOrder: true,
6273 gridArea: true,
6274 gridRow: true,
6275 gridRowEnd: true,
6276 gridRowSpan: true,
6277 gridRowStart: true,
6278 gridColumn: true,
6279 gridColumnEnd: true,
6280 gridColumnSpan: true,
6281 gridColumnStart: true,
6282 fontWeight: true,
6283 lineClamp: true,
6284 lineHeight: true,
6285 opacity: true,
6286 order: true,
6287 orphans: true,
6288 tabSize: true,
6289 widows: true,
6290 zIndex: true,
6291 zoom: true,
6292
6293 // SVG-related properties
6294 fillOpacity: true,
6295 floodOpacity: true,
6296 stopOpacity: true,
6297 strokeDasharray: true,
6298 strokeDashoffset: true,
6299 strokeMiterlimit: true,
6300 strokeOpacity: true,
6301 strokeWidth: true
6302};
6303
6304/**
6305 * @param {string} prefix vendor-specific prefix, eg: Webkit
6306 * @param {string} key style name, eg: transitionDuration
6307 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
6308 * WebkitTransitionDuration
6309 */
6310function prefixKey(prefix, key) {
6311 return prefix + key.charAt(0).toUpperCase() + key.substring(1);
6312}
6313
6314/**
6315 * Support style names that may come passed in prefixed by adding permutations
6316 * of vendor prefixes.
6317 */
6318var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
6319
6320// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
6321// infinite loop, because it iterates over the newly added props too.
6322Object.keys(isUnitlessNumber).forEach(function (prop) {
6323 prefixes.forEach(function (prefix) {
6324 isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
6325 });
6326});
6327
6328/**
6329 * Convert a value into the proper css writable value. The style name `name`
6330 * should be logical (no hyphens), as specified
6331 * in `CSSProperty.isUnitlessNumber`.
6332 *
6333 * @param {string} name CSS property name such as `topMargin`.
6334 * @param {*} value CSS property value such as `10px`.
6335 * @return {string} Normalized style value with dimensions applied.
6336 */
6337function dangerousStyleValue(name, value, isCustomProperty) {
6338 // Note that we've removed escapeTextForBrowser() calls here since the
6339 // whole string will be escaped when the attribute is injected into
6340 // the markup. If you provide unsafe user data here they can inject
6341 // arbitrary CSS which may be problematic (I couldn't repro this):
6342 // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
6343 // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
6344 // This is not an XSS hole but instead a potential CSS injection issue
6345 // which has lead to a greater discussion about how we're going to
6346 // trust URLs moving forward. See #2115901
6347
6348 var isEmpty = value == null || typeof value === 'boolean' || value === '';
6349 if (isEmpty) {
6350 return '';
6351 }
6352
6353 if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
6354 return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
6355 }
6356
6357 return ('' + value).trim();
6358}
6359
6360var uppercasePattern = /([A-Z])/g;
6361var msPattern = /^ms-/;
6362
6363/**
6364 * Hyphenates a camelcased CSS property name, for example:
6365 *
6366 * > hyphenateStyleName('backgroundColor')
6367 * < "background-color"
6368 * > hyphenateStyleName('MozTransition')
6369 * < "-moz-transition"
6370 * > hyphenateStyleName('msTransition')
6371 * < "-ms-transition"
6372 *
6373 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
6374 * is converted to `-ms-`.
6375 */
6376function hyphenateStyleName(name) {
6377 return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
6378}
6379
6380var warnValidStyle = function () {};
6381
6382{
6383 // 'msTransform' is correct, but the other prefixes should be capitalized
6384 var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
6385 var msPattern$1 = /^-ms-/;
6386 var hyphenPattern = /-(.)/g;
6387
6388 // style values shouldn't contain a semicolon
6389 var badStyleValueWithSemicolonPattern = /;\s*$/;
6390
6391 var warnedStyleNames = {};
6392 var warnedStyleValues = {};
6393 var warnedForNaNValue = false;
6394 var warnedForInfinityValue = false;
6395
6396 var camelize = function (string) {
6397 return string.replace(hyphenPattern, function (_, character) {
6398 return character.toUpperCase();
6399 });
6400 };
6401
6402 var warnHyphenatedStyleName = function (name) {
6403 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6404 return;
6405 }
6406
6407 warnedStyleNames[name] = true;
6408 warning$1(false, 'Unsupported style property %s. Did you mean %s?', name,
6409 // As Andi Smith suggests
6410 // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
6411 // is converted to lowercase `ms`.
6412 camelize(name.replace(msPattern$1, 'ms-')));
6413 };
6414
6415 var warnBadVendoredStyleName = function (name) {
6416 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6417 return;
6418 }
6419
6420 warnedStyleNames[name] = true;
6421 warning$1(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
6422 };
6423
6424 var warnStyleValueWithSemicolon = function (name, value) {
6425 if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
6426 return;
6427 }
6428
6429 warnedStyleValues[value] = true;
6430 warning$1(false, "Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
6431 };
6432
6433 var warnStyleValueIsNaN = function (name, value) {
6434 if (warnedForNaNValue) {
6435 return;
6436 }
6437
6438 warnedForNaNValue = true;
6439 warning$1(false, '`NaN` is an invalid value for the `%s` css style property.', name);
6440 };
6441
6442 var warnStyleValueIsInfinity = function (name, value) {
6443 if (warnedForInfinityValue) {
6444 return;
6445 }
6446
6447 warnedForInfinityValue = true;
6448 warning$1(false, '`Infinity` is an invalid value for the `%s` css style property.', name);
6449 };
6450
6451 warnValidStyle = function (name, value) {
6452 if (name.indexOf('-') > -1) {
6453 warnHyphenatedStyleName(name);
6454 } else if (badVendoredStyleNamePattern.test(name)) {
6455 warnBadVendoredStyleName(name);
6456 } else if (badStyleValueWithSemicolonPattern.test(value)) {
6457 warnStyleValueWithSemicolon(name, value);
6458 }
6459
6460 if (typeof value === 'number') {
6461 if (isNaN(value)) {
6462 warnStyleValueIsNaN(name, value);
6463 } else if (!isFinite(value)) {
6464 warnStyleValueIsInfinity(name, value);
6465 }
6466 }
6467 };
6468}
6469
6470var warnValidStyle$1 = warnValidStyle;
6471
6472/**
6473 * Operations for dealing with CSS properties.
6474 */
6475
6476/**
6477 * This creates a string that is expected to be equivalent to the style
6478 * attribute generated by server-side rendering. It by-passes warnings and
6479 * security checks so it's not safe to use this value for anything other than
6480 * comparison. It is only used in DEV for SSR validation.
6481 */
6482function createDangerousStringForStyles(styles) {
6483 {
6484 var serialized = '';
6485 var delimiter = '';
6486 for (var styleName in styles) {
6487 if (!styles.hasOwnProperty(styleName)) {
6488 continue;
6489 }
6490 var styleValue = styles[styleName];
6491 if (styleValue != null) {
6492 var isCustomProperty = styleName.indexOf('--') === 0;
6493 serialized += delimiter + hyphenateStyleName(styleName) + ':';
6494 serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
6495
6496 delimiter = ';';
6497 }
6498 }
6499 return serialized || null;
6500 }
6501}
6502
6503/**
6504 * Sets the value for multiple styles on a node. If a value is specified as
6505 * '' (empty string), the corresponding style property will be unset.
6506 *
6507 * @param {DOMElement} node
6508 * @param {object} styles
6509 */
6510function setValueForStyles(node, styles) {
6511 var style = node.style;
6512 for (var styleName in styles) {
6513 if (!styles.hasOwnProperty(styleName)) {
6514 continue;
6515 }
6516 var isCustomProperty = styleName.indexOf('--') === 0;
6517 {
6518 if (!isCustomProperty) {
6519 warnValidStyle$1(styleName, styles[styleName]);
6520 }
6521 }
6522 var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
6523 if (styleName === 'float') {
6524 styleName = 'cssFloat';
6525 }
6526 if (isCustomProperty) {
6527 style.setProperty(styleName, styleValue);
6528 } else {
6529 style[styleName] = styleValue;
6530 }
6531 }
6532}
6533
6534function isValueEmpty(value) {
6535 return value == null || typeof value === 'boolean' || value === '';
6536}
6537
6538/**
6539 * Given {color: 'red', overflow: 'hidden'} returns {
6540 * color: 'color',
6541 * overflowX: 'overflow',
6542 * overflowY: 'overflow',
6543 * }. This can be read as "the overflowY property was set by the overflow
6544 * shorthand". That is, the values are the property that each was derived from.
6545 */
6546function expandShorthandMap(styles) {
6547 var expanded = {};
6548 for (var key in styles) {
6549 var longhands = shorthandToLonghand[key] || [key];
6550 for (var i = 0; i < longhands.length; i++) {
6551 expanded[longhands[i]] = key;
6552 }
6553 }
6554 return expanded;
6555}
6556
6557/**
6558 * When mixing shorthand and longhand property names, we warn during updates if
6559 * we expect an incorrect result to occur. In particular, we warn for:
6560 *
6561 * Updating a shorthand property (longhand gets overwritten):
6562 * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
6563 * becomes .style.font = 'baz'
6564 * Removing a shorthand property (longhand gets lost too):
6565 * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
6566 * becomes .style.font = ''
6567 * Removing a longhand property (should revert to shorthand; doesn't):
6568 * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
6569 * becomes .style.fontVariant = ''
6570 */
6571function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
6572 if (!warnAboutShorthandPropertyCollision) {
6573 return;
6574 }
6575
6576 if (!nextStyles) {
6577 return;
6578 }
6579
6580 var expandedUpdates = expandShorthandMap(styleUpdates);
6581 var expandedStyles = expandShorthandMap(nextStyles);
6582 var warnedAbout = {};
6583 for (var key in expandedUpdates) {
6584 var originalKey = expandedUpdates[key];
6585 var correctOriginalKey = expandedStyles[key];
6586 if (correctOriginalKey && originalKey !== correctOriginalKey) {
6587 var warningKey = originalKey + ',' + correctOriginalKey;
6588 if (warnedAbout[warningKey]) {
6589 continue;
6590 }
6591 warnedAbout[warningKey] = true;
6592 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);
6593 }
6594 }
6595}
6596
6597// For HTML, certain tags should omit their close tag. We keep a whitelist for
6598// those special-case tags.
6599
6600var omittedCloseTags = {
6601 area: true,
6602 base: true,
6603 br: true,
6604 col: true,
6605 embed: true,
6606 hr: true,
6607 img: true,
6608 input: true,
6609 keygen: true,
6610 link: true,
6611 meta: true,
6612 param: true,
6613 source: true,
6614 track: true,
6615 wbr: true
6616 // NOTE: menuitem's close tag should be omitted, but that causes problems.
6617};
6618
6619// For HTML, certain tags cannot have children. This has the same purpose as
6620// `omittedCloseTags` except that `menuitem` should still have its closing tag.
6621
6622var voidElementTags = _assign({
6623 menuitem: true
6624}, omittedCloseTags);
6625
6626// TODO: We can remove this if we add invariantWithStack()
6627// or add stack by default to invariants where possible.
6628var HTML$1 = '__html';
6629
6630var ReactDebugCurrentFrame$2 = null;
6631{
6632 ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame;
6633}
6634
6635function assertValidProps(tag, props) {
6636 if (!props) {
6637 return;
6638 }
6639 // Note the use of `==` which checks for null or undefined.
6640 if (voidElementTags[tag]) {
6641 !(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;
6642 }
6643 if (props.dangerouslySetInnerHTML != null) {
6644 !(props.children == null) ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : void 0;
6645 !(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;
6646 }
6647 {
6648 !(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;
6649 }
6650 !(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;
6651}
6652
6653function isCustomComponent(tagName, props) {
6654 if (tagName.indexOf('-') === -1) {
6655 return typeof props.is === 'string';
6656 }
6657 switch (tagName) {
6658 // These are reserved SVG and MathML elements.
6659 // We don't mind this whitelist too much because we expect it to never grow.
6660 // The alternative is to track the namespace in a few places which is convoluted.
6661 // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
6662 case 'annotation-xml':
6663 case 'color-profile':
6664 case 'font-face':
6665 case 'font-face-src':
6666 case 'font-face-uri':
6667 case 'font-face-format':
6668 case 'font-face-name':
6669 case 'missing-glyph':
6670 return false;
6671 default:
6672 return true;
6673 }
6674}
6675
6676// When adding attributes to the HTML or SVG whitelist, be sure to
6677// also add them to this module to ensure casing and incorrect name
6678// warnings.
6679var possibleStandardNames = {
6680 // HTML
6681 accept: 'accept',
6682 acceptcharset: 'acceptCharset',
6683 'accept-charset': 'acceptCharset',
6684 accesskey: 'accessKey',
6685 action: 'action',
6686 allowfullscreen: 'allowFullScreen',
6687 alt: 'alt',
6688 as: 'as',
6689 async: 'async',
6690 autocapitalize: 'autoCapitalize',
6691 autocomplete: 'autoComplete',
6692 autocorrect: 'autoCorrect',
6693 autofocus: 'autoFocus',
6694 autoplay: 'autoPlay',
6695 autosave: 'autoSave',
6696 capture: 'capture',
6697 cellpadding: 'cellPadding',
6698 cellspacing: 'cellSpacing',
6699 challenge: 'challenge',
6700 charset: 'charSet',
6701 checked: 'checked',
6702 children: 'children',
6703 cite: 'cite',
6704 class: 'className',
6705 classid: 'classID',
6706 classname: 'className',
6707 cols: 'cols',
6708 colspan: 'colSpan',
6709 content: 'content',
6710 contenteditable: 'contentEditable',
6711 contextmenu: 'contextMenu',
6712 controls: 'controls',
6713 controlslist: 'controlsList',
6714 coords: 'coords',
6715 crossorigin: 'crossOrigin',
6716 dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
6717 data: 'data',
6718 datetime: 'dateTime',
6719 default: 'default',
6720 defaultchecked: 'defaultChecked',
6721 defaultvalue: 'defaultValue',
6722 defer: 'defer',
6723 dir: 'dir',
6724 disabled: 'disabled',
6725 download: 'download',
6726 draggable: 'draggable',
6727 enctype: 'encType',
6728 for: 'htmlFor',
6729 form: 'form',
6730 formmethod: 'formMethod',
6731 formaction: 'formAction',
6732 formenctype: 'formEncType',
6733 formnovalidate: 'formNoValidate',
6734 formtarget: 'formTarget',
6735 frameborder: 'frameBorder',
6736 headers: 'headers',
6737 height: 'height',
6738 hidden: 'hidden',
6739 high: 'high',
6740 href: 'href',
6741 hreflang: 'hrefLang',
6742 htmlfor: 'htmlFor',
6743 httpequiv: 'httpEquiv',
6744 'http-equiv': 'httpEquiv',
6745 icon: 'icon',
6746 id: 'id',
6747 innerhtml: 'innerHTML',
6748 inputmode: 'inputMode',
6749 integrity: 'integrity',
6750 is: 'is',
6751 itemid: 'itemID',
6752 itemprop: 'itemProp',
6753 itemref: 'itemRef',
6754 itemscope: 'itemScope',
6755 itemtype: 'itemType',
6756 keyparams: 'keyParams',
6757 keytype: 'keyType',
6758 kind: 'kind',
6759 label: 'label',
6760 lang: 'lang',
6761 list: 'list',
6762 loop: 'loop',
6763 low: 'low',
6764 manifest: 'manifest',
6765 marginwidth: 'marginWidth',
6766 marginheight: 'marginHeight',
6767 max: 'max',
6768 maxlength: 'maxLength',
6769 media: 'media',
6770 mediagroup: 'mediaGroup',
6771 method: 'method',
6772 min: 'min',
6773 minlength: 'minLength',
6774 multiple: 'multiple',
6775 muted: 'muted',
6776 name: 'name',
6777 nomodule: 'noModule',
6778 nonce: 'nonce',
6779 novalidate: 'noValidate',
6780 open: 'open',
6781 optimum: 'optimum',
6782 pattern: 'pattern',
6783 placeholder: 'placeholder',
6784 playsinline: 'playsInline',
6785 poster: 'poster',
6786 preload: 'preload',
6787 profile: 'profile',
6788 radiogroup: 'radioGroup',
6789 readonly: 'readOnly',
6790 referrerpolicy: 'referrerPolicy',
6791 rel: 'rel',
6792 required: 'required',
6793 reversed: 'reversed',
6794 role: 'role',
6795 rows: 'rows',
6796 rowspan: 'rowSpan',
6797 sandbox: 'sandbox',
6798 scope: 'scope',
6799 scoped: 'scoped',
6800 scrolling: 'scrolling',
6801 seamless: 'seamless',
6802 selected: 'selected',
6803 shape: 'shape',
6804 size: 'size',
6805 sizes: 'sizes',
6806 span: 'span',
6807 spellcheck: 'spellCheck',
6808 src: 'src',
6809 srcdoc: 'srcDoc',
6810 srclang: 'srcLang',
6811 srcset: 'srcSet',
6812 start: 'start',
6813 step: 'step',
6814 style: 'style',
6815 summary: 'summary',
6816 tabindex: 'tabIndex',
6817 target: 'target',
6818 title: 'title',
6819 type: 'type',
6820 usemap: 'useMap',
6821 value: 'value',
6822 width: 'width',
6823 wmode: 'wmode',
6824 wrap: 'wrap',
6825
6826 // SVG
6827 about: 'about',
6828 accentheight: 'accentHeight',
6829 'accent-height': 'accentHeight',
6830 accumulate: 'accumulate',
6831 additive: 'additive',
6832 alignmentbaseline: 'alignmentBaseline',
6833 'alignment-baseline': 'alignmentBaseline',
6834 allowreorder: 'allowReorder',
6835 alphabetic: 'alphabetic',
6836 amplitude: 'amplitude',
6837 arabicform: 'arabicForm',
6838 'arabic-form': 'arabicForm',
6839 ascent: 'ascent',
6840 attributename: 'attributeName',
6841 attributetype: 'attributeType',
6842 autoreverse: 'autoReverse',
6843 azimuth: 'azimuth',
6844 basefrequency: 'baseFrequency',
6845 baselineshift: 'baselineShift',
6846 'baseline-shift': 'baselineShift',
6847 baseprofile: 'baseProfile',
6848 bbox: 'bbox',
6849 begin: 'begin',
6850 bias: 'bias',
6851 by: 'by',
6852 calcmode: 'calcMode',
6853 capheight: 'capHeight',
6854 'cap-height': 'capHeight',
6855 clip: 'clip',
6856 clippath: 'clipPath',
6857 'clip-path': 'clipPath',
6858 clippathunits: 'clipPathUnits',
6859 cliprule: 'clipRule',
6860 'clip-rule': 'clipRule',
6861 color: 'color',
6862 colorinterpolation: 'colorInterpolation',
6863 'color-interpolation': 'colorInterpolation',
6864 colorinterpolationfilters: 'colorInterpolationFilters',
6865 'color-interpolation-filters': 'colorInterpolationFilters',
6866 colorprofile: 'colorProfile',
6867 'color-profile': 'colorProfile',
6868 colorrendering: 'colorRendering',
6869 'color-rendering': 'colorRendering',
6870 contentscripttype: 'contentScriptType',
6871 contentstyletype: 'contentStyleType',
6872 cursor: 'cursor',
6873 cx: 'cx',
6874 cy: 'cy',
6875 d: 'd',
6876 datatype: 'datatype',
6877 decelerate: 'decelerate',
6878 descent: 'descent',
6879 diffuseconstant: 'diffuseConstant',
6880 direction: 'direction',
6881 display: 'display',
6882 divisor: 'divisor',
6883 dominantbaseline: 'dominantBaseline',
6884 'dominant-baseline': 'dominantBaseline',
6885 dur: 'dur',
6886 dx: 'dx',
6887 dy: 'dy',
6888 edgemode: 'edgeMode',
6889 elevation: 'elevation',
6890 enablebackground: 'enableBackground',
6891 'enable-background': 'enableBackground',
6892 end: 'end',
6893 exponent: 'exponent',
6894 externalresourcesrequired: 'externalResourcesRequired',
6895 fill: 'fill',
6896 fillopacity: 'fillOpacity',
6897 'fill-opacity': 'fillOpacity',
6898 fillrule: 'fillRule',
6899 'fill-rule': 'fillRule',
6900 filter: 'filter',
6901 filterres: 'filterRes',
6902 filterunits: 'filterUnits',
6903 floodopacity: 'floodOpacity',
6904 'flood-opacity': 'floodOpacity',
6905 floodcolor: 'floodColor',
6906 'flood-color': 'floodColor',
6907 focusable: 'focusable',
6908 fontfamily: 'fontFamily',
6909 'font-family': 'fontFamily',
6910 fontsize: 'fontSize',
6911 'font-size': 'fontSize',
6912 fontsizeadjust: 'fontSizeAdjust',
6913 'font-size-adjust': 'fontSizeAdjust',
6914 fontstretch: 'fontStretch',
6915 'font-stretch': 'fontStretch',
6916 fontstyle: 'fontStyle',
6917 'font-style': 'fontStyle',
6918 fontvariant: 'fontVariant',
6919 'font-variant': 'fontVariant',
6920 fontweight: 'fontWeight',
6921 'font-weight': 'fontWeight',
6922 format: 'format',
6923 from: 'from',
6924 fx: 'fx',
6925 fy: 'fy',
6926 g1: 'g1',
6927 g2: 'g2',
6928 glyphname: 'glyphName',
6929 'glyph-name': 'glyphName',
6930 glyphorientationhorizontal: 'glyphOrientationHorizontal',
6931 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
6932 glyphorientationvertical: 'glyphOrientationVertical',
6933 'glyph-orientation-vertical': 'glyphOrientationVertical',
6934 glyphref: 'glyphRef',
6935 gradienttransform: 'gradientTransform',
6936 gradientunits: 'gradientUnits',
6937 hanging: 'hanging',
6938 horizadvx: 'horizAdvX',
6939 'horiz-adv-x': 'horizAdvX',
6940 horizoriginx: 'horizOriginX',
6941 'horiz-origin-x': 'horizOriginX',
6942 ideographic: 'ideographic',
6943 imagerendering: 'imageRendering',
6944 'image-rendering': 'imageRendering',
6945 in2: 'in2',
6946 in: 'in',
6947 inlist: 'inlist',
6948 intercept: 'intercept',
6949 k1: 'k1',
6950 k2: 'k2',
6951 k3: 'k3',
6952 k4: 'k4',
6953 k: 'k',
6954 kernelmatrix: 'kernelMatrix',
6955 kernelunitlength: 'kernelUnitLength',
6956 kerning: 'kerning',
6957 keypoints: 'keyPoints',
6958 keysplines: 'keySplines',
6959 keytimes: 'keyTimes',
6960 lengthadjust: 'lengthAdjust',
6961 letterspacing: 'letterSpacing',
6962 'letter-spacing': 'letterSpacing',
6963 lightingcolor: 'lightingColor',
6964 'lighting-color': 'lightingColor',
6965 limitingconeangle: 'limitingConeAngle',
6966 local: 'local',
6967 markerend: 'markerEnd',
6968 'marker-end': 'markerEnd',
6969 markerheight: 'markerHeight',
6970 markermid: 'markerMid',
6971 'marker-mid': 'markerMid',
6972 markerstart: 'markerStart',
6973 'marker-start': 'markerStart',
6974 markerunits: 'markerUnits',
6975 markerwidth: 'markerWidth',
6976 mask: 'mask',
6977 maskcontentunits: 'maskContentUnits',
6978 maskunits: 'maskUnits',
6979 mathematical: 'mathematical',
6980 mode: 'mode',
6981 numoctaves: 'numOctaves',
6982 offset: 'offset',
6983 opacity: 'opacity',
6984 operator: 'operator',
6985 order: 'order',
6986 orient: 'orient',
6987 orientation: 'orientation',
6988 origin: 'origin',
6989 overflow: 'overflow',
6990 overlineposition: 'overlinePosition',
6991 'overline-position': 'overlinePosition',
6992 overlinethickness: 'overlineThickness',
6993 'overline-thickness': 'overlineThickness',
6994 paintorder: 'paintOrder',
6995 'paint-order': 'paintOrder',
6996 panose1: 'panose1',
6997 'panose-1': 'panose1',
6998 pathlength: 'pathLength',
6999 patterncontentunits: 'patternContentUnits',
7000 patterntransform: 'patternTransform',
7001 patternunits: 'patternUnits',
7002 pointerevents: 'pointerEvents',
7003 'pointer-events': 'pointerEvents',
7004 points: 'points',
7005 pointsatx: 'pointsAtX',
7006 pointsaty: 'pointsAtY',
7007 pointsatz: 'pointsAtZ',
7008 prefix: 'prefix',
7009 preservealpha: 'preserveAlpha',
7010 preserveaspectratio: 'preserveAspectRatio',
7011 primitiveunits: 'primitiveUnits',
7012 property: 'property',
7013 r: 'r',
7014 radius: 'radius',
7015 refx: 'refX',
7016 refy: 'refY',
7017 renderingintent: 'renderingIntent',
7018 'rendering-intent': 'renderingIntent',
7019 repeatcount: 'repeatCount',
7020 repeatdur: 'repeatDur',
7021 requiredextensions: 'requiredExtensions',
7022 requiredfeatures: 'requiredFeatures',
7023 resource: 'resource',
7024 restart: 'restart',
7025 result: 'result',
7026 results: 'results',
7027 rotate: 'rotate',
7028 rx: 'rx',
7029 ry: 'ry',
7030 scale: 'scale',
7031 security: 'security',
7032 seed: 'seed',
7033 shaperendering: 'shapeRendering',
7034 'shape-rendering': 'shapeRendering',
7035 slope: 'slope',
7036 spacing: 'spacing',
7037 specularconstant: 'specularConstant',
7038 specularexponent: 'specularExponent',
7039 speed: 'speed',
7040 spreadmethod: 'spreadMethod',
7041 startoffset: 'startOffset',
7042 stddeviation: 'stdDeviation',
7043 stemh: 'stemh',
7044 stemv: 'stemv',
7045 stitchtiles: 'stitchTiles',
7046 stopcolor: 'stopColor',
7047 'stop-color': 'stopColor',
7048 stopopacity: 'stopOpacity',
7049 'stop-opacity': 'stopOpacity',
7050 strikethroughposition: 'strikethroughPosition',
7051 'strikethrough-position': 'strikethroughPosition',
7052 strikethroughthickness: 'strikethroughThickness',
7053 'strikethrough-thickness': 'strikethroughThickness',
7054 string: 'string',
7055 stroke: 'stroke',
7056 strokedasharray: 'strokeDasharray',
7057 'stroke-dasharray': 'strokeDasharray',
7058 strokedashoffset: 'strokeDashoffset',
7059 'stroke-dashoffset': 'strokeDashoffset',
7060 strokelinecap: 'strokeLinecap',
7061 'stroke-linecap': 'strokeLinecap',
7062 strokelinejoin: 'strokeLinejoin',
7063 'stroke-linejoin': 'strokeLinejoin',
7064 strokemiterlimit: 'strokeMiterlimit',
7065 'stroke-miterlimit': 'strokeMiterlimit',
7066 strokewidth: 'strokeWidth',
7067 'stroke-width': 'strokeWidth',
7068 strokeopacity: 'strokeOpacity',
7069 'stroke-opacity': 'strokeOpacity',
7070 suppresscontenteditablewarning: 'suppressContentEditableWarning',
7071 suppresshydrationwarning: 'suppressHydrationWarning',
7072 surfacescale: 'surfaceScale',
7073 systemlanguage: 'systemLanguage',
7074 tablevalues: 'tableValues',
7075 targetx: 'targetX',
7076 targety: 'targetY',
7077 textanchor: 'textAnchor',
7078 'text-anchor': 'textAnchor',
7079 textdecoration: 'textDecoration',
7080 'text-decoration': 'textDecoration',
7081 textlength: 'textLength',
7082 textrendering: 'textRendering',
7083 'text-rendering': 'textRendering',
7084 to: 'to',
7085 transform: 'transform',
7086 typeof: 'typeof',
7087 u1: 'u1',
7088 u2: 'u2',
7089 underlineposition: 'underlinePosition',
7090 'underline-position': 'underlinePosition',
7091 underlinethickness: 'underlineThickness',
7092 'underline-thickness': 'underlineThickness',
7093 unicode: 'unicode',
7094 unicodebidi: 'unicodeBidi',
7095 'unicode-bidi': 'unicodeBidi',
7096 unicoderange: 'unicodeRange',
7097 'unicode-range': 'unicodeRange',
7098 unitsperem: 'unitsPerEm',
7099 'units-per-em': 'unitsPerEm',
7100 unselectable: 'unselectable',
7101 valphabetic: 'vAlphabetic',
7102 'v-alphabetic': 'vAlphabetic',
7103 values: 'values',
7104 vectoreffect: 'vectorEffect',
7105 'vector-effect': 'vectorEffect',
7106 version: 'version',
7107 vertadvy: 'vertAdvY',
7108 'vert-adv-y': 'vertAdvY',
7109 vertoriginx: 'vertOriginX',
7110 'vert-origin-x': 'vertOriginX',
7111 vertoriginy: 'vertOriginY',
7112 'vert-origin-y': 'vertOriginY',
7113 vhanging: 'vHanging',
7114 'v-hanging': 'vHanging',
7115 videographic: 'vIdeographic',
7116 'v-ideographic': 'vIdeographic',
7117 viewbox: 'viewBox',
7118 viewtarget: 'viewTarget',
7119 visibility: 'visibility',
7120 vmathematical: 'vMathematical',
7121 'v-mathematical': 'vMathematical',
7122 vocab: 'vocab',
7123 widths: 'widths',
7124 wordspacing: 'wordSpacing',
7125 'word-spacing': 'wordSpacing',
7126 writingmode: 'writingMode',
7127 'writing-mode': 'writingMode',
7128 x1: 'x1',
7129 x2: 'x2',
7130 x: 'x',
7131 xchannelselector: 'xChannelSelector',
7132 xheight: 'xHeight',
7133 'x-height': 'xHeight',
7134 xlinkactuate: 'xlinkActuate',
7135 'xlink:actuate': 'xlinkActuate',
7136 xlinkarcrole: 'xlinkArcrole',
7137 'xlink:arcrole': 'xlinkArcrole',
7138 xlinkhref: 'xlinkHref',
7139 'xlink:href': 'xlinkHref',
7140 xlinkrole: 'xlinkRole',
7141 'xlink:role': 'xlinkRole',
7142 xlinkshow: 'xlinkShow',
7143 'xlink:show': 'xlinkShow',
7144 xlinktitle: 'xlinkTitle',
7145 'xlink:title': 'xlinkTitle',
7146 xlinktype: 'xlinkType',
7147 'xlink:type': 'xlinkType',
7148 xmlbase: 'xmlBase',
7149 'xml:base': 'xmlBase',
7150 xmllang: 'xmlLang',
7151 'xml:lang': 'xmlLang',
7152 xmlns: 'xmlns',
7153 'xml:space': 'xmlSpace',
7154 xmlnsxlink: 'xmlnsXlink',
7155 'xmlns:xlink': 'xmlnsXlink',
7156 xmlspace: 'xmlSpace',
7157 y1: 'y1',
7158 y2: 'y2',
7159 y: 'y',
7160 ychannelselector: 'yChannelSelector',
7161 z: 'z',
7162 zoomandpan: 'zoomAndPan'
7163};
7164
7165var ariaProperties = {
7166 'aria-current': 0, // state
7167 'aria-details': 0,
7168 'aria-disabled': 0, // state
7169 'aria-hidden': 0, // state
7170 'aria-invalid': 0, // state
7171 'aria-keyshortcuts': 0,
7172 'aria-label': 0,
7173 'aria-roledescription': 0,
7174 // Widget Attributes
7175 'aria-autocomplete': 0,
7176 'aria-checked': 0,
7177 'aria-expanded': 0,
7178 'aria-haspopup': 0,
7179 'aria-level': 0,
7180 'aria-modal': 0,
7181 'aria-multiline': 0,
7182 'aria-multiselectable': 0,
7183 'aria-orientation': 0,
7184 'aria-placeholder': 0,
7185 'aria-pressed': 0,
7186 'aria-readonly': 0,
7187 'aria-required': 0,
7188 'aria-selected': 0,
7189 'aria-sort': 0,
7190 'aria-valuemax': 0,
7191 'aria-valuemin': 0,
7192 'aria-valuenow': 0,
7193 'aria-valuetext': 0,
7194 // Live Region Attributes
7195 'aria-atomic': 0,
7196 'aria-busy': 0,
7197 'aria-live': 0,
7198 'aria-relevant': 0,
7199 // Drag-and-Drop Attributes
7200 'aria-dropeffect': 0,
7201 'aria-grabbed': 0,
7202 // Relationship Attributes
7203 'aria-activedescendant': 0,
7204 'aria-colcount': 0,
7205 'aria-colindex': 0,
7206 'aria-colspan': 0,
7207 'aria-controls': 0,
7208 'aria-describedby': 0,
7209 'aria-errormessage': 0,
7210 'aria-flowto': 0,
7211 'aria-labelledby': 0,
7212 'aria-owns': 0,
7213 'aria-posinset': 0,
7214 'aria-rowcount': 0,
7215 'aria-rowindex': 0,
7216 'aria-rowspan': 0,
7217 'aria-setsize': 0
7218};
7219
7220var warnedProperties = {};
7221var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7222var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7223
7224var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
7225
7226function validateProperty(tagName, name) {
7227 if (hasOwnProperty$2.call(warnedProperties, name) && warnedProperties[name]) {
7228 return true;
7229 }
7230
7231 if (rARIACamel.test(name)) {
7232 var ariaName = 'aria-' + name.slice(4).toLowerCase();
7233 var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null;
7234
7235 // If this is an aria-* attribute, but is not listed in the known DOM
7236 // DOM properties, then it is an invalid aria-* attribute.
7237 if (correctName == null) {
7238 warning$1(false, 'Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
7239 warnedProperties[name] = true;
7240 return true;
7241 }
7242 // aria-* attributes should be lowercase; suggest the lowercase version.
7243 if (name !== correctName) {
7244 warning$1(false, 'Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
7245 warnedProperties[name] = true;
7246 return true;
7247 }
7248 }
7249
7250 if (rARIA.test(name)) {
7251 var lowerCasedName = name.toLowerCase();
7252 var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null;
7253
7254 // If this is an aria-* attribute, but is not listed in the known DOM
7255 // DOM properties, then it is an invalid aria-* attribute.
7256 if (standardName == null) {
7257 warnedProperties[name] = true;
7258 return false;
7259 }
7260 // aria-* attributes should be lowercase; suggest the lowercase version.
7261 if (name !== standardName) {
7262 warning$1(false, 'Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
7263 warnedProperties[name] = true;
7264 return true;
7265 }
7266 }
7267
7268 return true;
7269}
7270
7271function warnInvalidARIAProps(type, props) {
7272 var invalidProps = [];
7273
7274 for (var key in props) {
7275 var isValid = validateProperty(type, key);
7276 if (!isValid) {
7277 invalidProps.push(key);
7278 }
7279 }
7280
7281 var unknownPropString = invalidProps.map(function (prop) {
7282 return '`' + prop + '`';
7283 }).join(', ');
7284
7285 if (invalidProps.length === 1) {
7286 warning$1(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7287 } else if (invalidProps.length > 1) {
7288 warning$1(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7289 }
7290}
7291
7292function validateProperties(type, props) {
7293 if (isCustomComponent(type, props)) {
7294 return;
7295 }
7296 warnInvalidARIAProps(type, props);
7297}
7298
7299var didWarnValueNull = false;
7300
7301function validateProperties$1(type, props) {
7302 if (type !== 'input' && type !== 'textarea' && type !== 'select') {
7303 return;
7304 }
7305
7306 if (props != null && props.value === null && !didWarnValueNull) {
7307 didWarnValueNull = true;
7308 if (type === 'select' && props.multiple) {
7309 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);
7310 } else {
7311 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);
7312 }
7313 }
7314}
7315
7316var validateProperty$1 = function () {};
7317
7318{
7319 var warnedProperties$1 = {};
7320 var _hasOwnProperty = Object.prototype.hasOwnProperty;
7321 var EVENT_NAME_REGEX = /^on./;
7322 var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
7323 var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7324 var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7325
7326 validateProperty$1 = function (tagName, name, value, canUseEventSystem) {
7327 if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
7328 return true;
7329 }
7330
7331 var lowerCasedName = name.toLowerCase();
7332 if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
7333 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.');
7334 warnedProperties$1[name] = true;
7335 return true;
7336 }
7337
7338 // We can't rely on the event system being injected on the server.
7339 if (canUseEventSystem) {
7340 if (registrationNameModules.hasOwnProperty(name)) {
7341 return true;
7342 }
7343 var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
7344 if (registrationName != null) {
7345 warning$1(false, 'Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
7346 warnedProperties$1[name] = true;
7347 return true;
7348 }
7349 if (EVENT_NAME_REGEX.test(name)) {
7350 warning$1(false, 'Unknown event handler property `%s`. It will be ignored.', name);
7351 warnedProperties$1[name] = true;
7352 return true;
7353 }
7354 } else if (EVENT_NAME_REGEX.test(name)) {
7355 // If no event plugins have been injected, we are in a server environment.
7356 // So we can't tell if the event name is correct for sure, but we can filter
7357 // out known bad ones like `onclick`. We can't suggest a specific replacement though.
7358 if (INVALID_EVENT_NAME_REGEX.test(name)) {
7359 warning$1(false, 'Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
7360 }
7361 warnedProperties$1[name] = true;
7362 return true;
7363 }
7364
7365 // Let the ARIA attribute hook validate ARIA attributes
7366 if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
7367 return true;
7368 }
7369
7370 if (lowerCasedName === 'innerhtml') {
7371 warning$1(false, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
7372 warnedProperties$1[name] = true;
7373 return true;
7374 }
7375
7376 if (lowerCasedName === 'aria') {
7377 warning$1(false, 'The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
7378 warnedProperties$1[name] = true;
7379 return true;
7380 }
7381
7382 if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
7383 warning$1(false, 'Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
7384 warnedProperties$1[name] = true;
7385 return true;
7386 }
7387
7388 if (typeof value === 'number' && isNaN(value)) {
7389 warning$1(false, 'Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
7390 warnedProperties$1[name] = true;
7391 return true;
7392 }
7393
7394 var propertyInfo = getPropertyInfo(name);
7395 var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED;
7396
7397 // Known attributes should match the casing specified in the property config.
7398 if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
7399 var standardName = possibleStandardNames[lowerCasedName];
7400 if (standardName !== name) {
7401 warning$1(false, 'Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
7402 warnedProperties$1[name] = true;
7403 return true;
7404 }
7405 } else if (!isReserved && name !== lowerCasedName) {
7406 // Unknown attributes should have lowercase casing since that's how they
7407 // will be cased anyway with server rendering.
7408 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);
7409 warnedProperties$1[name] = true;
7410 return true;
7411 }
7412
7413 if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7414 if (value) {
7415 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);
7416 } else {
7417 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);
7418 }
7419 warnedProperties$1[name] = true;
7420 return true;
7421 }
7422
7423 // Now that we've validated casing, do not validate
7424 // data types for reserved props
7425 if (isReserved) {
7426 return true;
7427 }
7428
7429 // Warn when a known attribute is a bad type
7430 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7431 warnedProperties$1[name] = true;
7432 return false;
7433 }
7434
7435 // Warn when passing the strings 'false' or 'true' into a boolean prop
7436 if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
7437 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);
7438 warnedProperties$1[name] = true;
7439 return true;
7440 }
7441
7442 return true;
7443 };
7444}
7445
7446var warnUnknownProperties = function (type, props, canUseEventSystem) {
7447 var unknownProps = [];
7448 for (var key in props) {
7449 var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);
7450 if (!isValid) {
7451 unknownProps.push(key);
7452 }
7453 }
7454
7455 var unknownPropString = unknownProps.map(function (prop) {
7456 return '`' + prop + '`';
7457 }).join(', ');
7458 if (unknownProps.length === 1) {
7459 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);
7460 } else if (unknownProps.length > 1) {
7461 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);
7462 }
7463};
7464
7465function validateProperties$2(type, props, canUseEventSystem) {
7466 if (isCustomComponent(type, props)) {
7467 return;
7468 }
7469 warnUnknownProperties(type, props, canUseEventSystem);
7470}
7471
7472// TODO: direct imports like some-package/src/* are bad. Fix me.
7473var didWarnInvalidHydration = false;
7474var didWarnShadyDOM = false;
7475
7476var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
7477var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
7478var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
7479var AUTOFOCUS = 'autoFocus';
7480var CHILDREN = 'children';
7481var STYLE$1 = 'style';
7482var HTML = '__html';
7483
7484var HTML_NAMESPACE = Namespaces.html;
7485
7486
7487var warnedUnknownTags = void 0;
7488var suppressHydrationWarning = void 0;
7489
7490var validatePropertiesInDevelopment = void 0;
7491var warnForTextDifference = void 0;
7492var warnForPropDifference = void 0;
7493var warnForExtraAttributes = void 0;
7494var warnForInvalidEventListener = void 0;
7495var canDiffStyleForHydrationWarning = void 0;
7496
7497var normalizeMarkupForTextOrAttribute = void 0;
7498var normalizeHTML = void 0;
7499
7500{
7501 warnedUnknownTags = {
7502 // Chrome is the only major browser not shipping <time>. But as of July
7503 // 2017 it intends to ship it due to widespread usage. We intentionally
7504 // *don't* warn for <time> even if it's unrecognized by Chrome because
7505 // it soon will be, and many apps have been using it anyway.
7506 time: true,
7507 // There are working polyfills for <dialog>. Let people use it.
7508 dialog: true,
7509 // Electron ships a custom <webview> tag to display external web content in
7510 // an isolated frame and process.
7511 // This tag is not present in non Electron environments such as JSDom which
7512 // is often used for testing purposes.
7513 // @see https://electronjs.org/docs/api/webview-tag
7514 webview: true
7515 };
7516
7517 validatePropertiesInDevelopment = function (type, props) {
7518 validateProperties(type, props);
7519 validateProperties$1(type, props);
7520 validateProperties$2(type, props, /* canUseEventSystem */true);
7521 };
7522
7523 // IE 11 parses & normalizes the style attribute as opposed to other
7524 // browsers. It adds spaces and sorts the properties in some
7525 // non-alphabetical order. Handling that would require sorting CSS
7526 // properties in the client & server versions or applying
7527 // `expectedStyle` to a temporary DOM node to read its `style` attribute
7528 // normalized. Since it only affects IE, we're skipping style warnings
7529 // in that browser completely in favor of doing all that work.
7530 // See https://github.com/facebook/react/issues/11807
7531 canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode;
7532
7533 // HTML parsing normalizes CR and CRLF to LF.
7534 // It also can turn \u0000 into \uFFFD inside attributes.
7535 // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
7536 // If we have a mismatch, it might be caused by that.
7537 // We will still patch up in this case but not fire the warning.
7538 var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
7539 var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
7540
7541 normalizeMarkupForTextOrAttribute = function (markup) {
7542 var markupString = typeof markup === 'string' ? markup : '' + markup;
7543 return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
7544 };
7545
7546 warnForTextDifference = function (serverText, clientText) {
7547 if (didWarnInvalidHydration) {
7548 return;
7549 }
7550 var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
7551 var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
7552 if (normalizedServerText === normalizedClientText) {
7553 return;
7554 }
7555 didWarnInvalidHydration = true;
7556 warningWithoutStack$1(false, 'Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
7557 };
7558
7559 warnForPropDifference = function (propName, serverValue, clientValue) {
7560 if (didWarnInvalidHydration) {
7561 return;
7562 }
7563 var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
7564 var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
7565 if (normalizedServerValue === normalizedClientValue) {
7566 return;
7567 }
7568 didWarnInvalidHydration = true;
7569 warningWithoutStack$1(false, 'Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
7570 };
7571
7572 warnForExtraAttributes = function (attributeNames) {
7573 if (didWarnInvalidHydration) {
7574 return;
7575 }
7576 didWarnInvalidHydration = true;
7577 var names = [];
7578 attributeNames.forEach(function (name) {
7579 names.push(name);
7580 });
7581 warningWithoutStack$1(false, 'Extra attributes from the server: %s', names);
7582 };
7583
7584 warnForInvalidEventListener = function (registrationName, listener) {
7585 if (listener === false) {
7586 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);
7587 } else {
7588 warning$1(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
7589 }
7590 };
7591
7592 // Parse the HTML and read it back to normalize the HTML string so that it
7593 // can be used for comparison.
7594 normalizeHTML = function (parent, html) {
7595 // We could have created a separate document here to avoid
7596 // re-initializing custom elements if they exist. But this breaks
7597 // how <noscript> is being handled. So we use the same document.
7598 // See the discussion in https://github.com/facebook/react/pull/11157.
7599 var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
7600 testElement.innerHTML = html;
7601 return testElement.innerHTML;
7602 };
7603}
7604
7605function ensureListeningTo(rootContainerElement, registrationName) {
7606 var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;
7607 var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;
7608 listenTo(registrationName, doc);
7609}
7610
7611function getOwnerDocumentFromRootContainer(rootContainerElement) {
7612 return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
7613}
7614
7615function noop() {}
7616
7617function trapClickOnNonInteractiveElement(node) {
7618 // Mobile Safari does not fire properly bubble click events on
7619 // non-interactive elements, which means delegated click listeners do not
7620 // fire. The workaround for this bug involves attaching an empty click
7621 // listener on the target node.
7622 // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
7623 // Just set it using the onclick property so that we don't have to manage any
7624 // bookkeeping for it. Not sure if we need to clear it when the listener is
7625 // removed.
7626 // TODO: Only do this for the relevant Safaris maybe?
7627 node.onclick = noop;
7628}
7629
7630function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
7631 for (var propKey in nextProps) {
7632 if (!nextProps.hasOwnProperty(propKey)) {
7633 continue;
7634 }
7635 var nextProp = nextProps[propKey];
7636 if (propKey === STYLE$1) {
7637 {
7638 if (nextProp) {
7639 // Freeze the next style object so that we can assume it won't be
7640 // mutated. We have already warned for this in the past.
7641 Object.freeze(nextProp);
7642 }
7643 }
7644 // Relies on `updateStylesByID` not mutating `styleUpdates`.
7645 setValueForStyles(domElement, nextProp);
7646 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7647 var nextHtml = nextProp ? nextProp[HTML] : undefined;
7648 if (nextHtml != null) {
7649 setInnerHTML(domElement, nextHtml);
7650 }
7651 } else if (propKey === CHILDREN) {
7652 if (typeof nextProp === 'string') {
7653 // Avoid setting initial textContent when the text is empty. In IE11 setting
7654 // textContent on a <textarea> will cause the placeholder to not
7655 // show within the <textarea> until it has been focused and blurred again.
7656 // https://github.com/facebook/react/issues/6731#issuecomment-254874553
7657 var canSetTextContent = tag !== 'textarea' || nextProp !== '';
7658 if (canSetTextContent) {
7659 setTextContent(domElement, nextProp);
7660 }
7661 } else if (typeof nextProp === 'number') {
7662 setTextContent(domElement, '' + nextProp);
7663 }
7664 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
7665 // Noop
7666 } else if (propKey === AUTOFOCUS) {
7667 // We polyfill it separately on the client during commit.
7668 // We could have excluded it in the property list instead of
7669 // adding a special case here, but then it wouldn't be emitted
7670 // on server rendering (but we *do* want to emit it in SSR).
7671 } else if (registrationNameModules.hasOwnProperty(propKey)) {
7672 if (nextProp != null) {
7673 if (true && typeof nextProp !== 'function') {
7674 warnForInvalidEventListener(propKey, nextProp);
7675 }
7676 ensureListeningTo(rootContainerElement, propKey);
7677 }
7678 } else if (nextProp != null) {
7679 setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
7680 }
7681 }
7682}
7683
7684function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
7685 // TODO: Handle wasCustomComponentTag
7686 for (var i = 0; i < updatePayload.length; i += 2) {
7687 var propKey = updatePayload[i];
7688 var propValue = updatePayload[i + 1];
7689 if (propKey === STYLE$1) {
7690 setValueForStyles(domElement, propValue);
7691 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7692 setInnerHTML(domElement, propValue);
7693 } else if (propKey === CHILDREN) {
7694 setTextContent(domElement, propValue);
7695 } else {
7696 setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
7697 }
7698 }
7699}
7700
7701function createElement(type, props, rootContainerElement, parentNamespace) {
7702 var isCustomComponentTag = void 0;
7703
7704 // We create tags in the namespace of their parent container, except HTML
7705 // tags get no namespace.
7706 var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
7707 var domElement = void 0;
7708 var namespaceURI = parentNamespace;
7709 if (namespaceURI === HTML_NAMESPACE) {
7710 namespaceURI = getIntrinsicNamespace(type);
7711 }
7712 if (namespaceURI === HTML_NAMESPACE) {
7713 {
7714 isCustomComponentTag = isCustomComponent(type, props);
7715 // Should this check be gated by parent namespace? Not sure we want to
7716 // allow <SVG> or <mATH>.
7717 !(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;
7718 }
7719
7720 if (type === 'script') {
7721 // Create the script via .innerHTML so its "parser-inserted" flag is
7722 // set to true and it does not execute
7723 var div = ownerDocument.createElement('div');
7724 div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
7725 // This is guaranteed to yield a script element.
7726 var firstChild = div.firstChild;
7727 domElement = div.removeChild(firstChild);
7728 } else if (typeof props.is === 'string') {
7729 // $FlowIssue `createElement` should be updated for Web Components
7730 domElement = ownerDocument.createElement(type, { is: props.is });
7731 } else {
7732 // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
7733 // See discussion in https://github.com/facebook/react/pull/6896
7734 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
7735 domElement = ownerDocument.createElement(type);
7736 // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
7737 // attributes on `select`s needs to be added before `option`s are inserted.
7738 // This prevents:
7739 // - a bug where the `select` does not scroll to the correct option because singular
7740 // `select` elements automatically pick the first item #13222
7741 // - a bug where the `select` set the first item as selected despite the `size` attribute #14239
7742 // See https://github.com/facebook/react/issues/13222
7743 // and https://github.com/facebook/react/issues/14239
7744 if (type === 'select') {
7745 var node = domElement;
7746 if (props.multiple) {
7747 node.multiple = true;
7748 } else if (props.size) {
7749 // Setting a size greater than 1 causes a select to behave like `multiple=true`, where
7750 // it is possible that no option is selected.
7751 //
7752 // This is only necessary when a select in "single selection mode".
7753 node.size = props.size;
7754 }
7755 }
7756 }
7757 } else {
7758 domElement = ownerDocument.createElementNS(namespaceURI, type);
7759 }
7760
7761 {
7762 if (namespaceURI === HTML_NAMESPACE) {
7763 if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {
7764 warnedUnknownTags[type] = true;
7765 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);
7766 }
7767 }
7768 }
7769
7770 return domElement;
7771}
7772
7773function createTextNode(text, rootContainerElement) {
7774 return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
7775}
7776
7777function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
7778 var isCustomComponentTag = isCustomComponent(tag, rawProps);
7779 {
7780 validatePropertiesInDevelopment(tag, rawProps);
7781 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
7782 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
7783 didWarnShadyDOM = true;
7784 }
7785 }
7786
7787 // TODO: Make sure that we check isMounted before firing any of these events.
7788 var props = void 0;
7789 switch (tag) {
7790 case 'iframe':
7791 case 'object':
7792 trapBubbledEvent(TOP_LOAD, domElement);
7793 props = rawProps;
7794 break;
7795 case 'video':
7796 case 'audio':
7797 // Create listener for each media event
7798 for (var i = 0; i < mediaEventTypes.length; i++) {
7799 trapBubbledEvent(mediaEventTypes[i], domElement);
7800 }
7801 props = rawProps;
7802 break;
7803 case 'source':
7804 trapBubbledEvent(TOP_ERROR, domElement);
7805 props = rawProps;
7806 break;
7807 case 'img':
7808 case 'image':
7809 case 'link':
7810 trapBubbledEvent(TOP_ERROR, domElement);
7811 trapBubbledEvent(TOP_LOAD, domElement);
7812 props = rawProps;
7813 break;
7814 case 'form':
7815 trapBubbledEvent(TOP_RESET, domElement);
7816 trapBubbledEvent(TOP_SUBMIT, domElement);
7817 props = rawProps;
7818 break;
7819 case 'details':
7820 trapBubbledEvent(TOP_TOGGLE, domElement);
7821 props = rawProps;
7822 break;
7823 case 'input':
7824 initWrapperState(domElement, rawProps);
7825 props = getHostProps(domElement, rawProps);
7826 trapBubbledEvent(TOP_INVALID, domElement);
7827 // For controlled components we always need to ensure we're listening
7828 // to onChange. Even if there is no listener.
7829 ensureListeningTo(rootContainerElement, 'onChange');
7830 break;
7831 case 'option':
7832 validateProps(domElement, rawProps);
7833 props = getHostProps$1(domElement, rawProps);
7834 break;
7835 case 'select':
7836 initWrapperState$1(domElement, rawProps);
7837 props = getHostProps$2(domElement, rawProps);
7838 trapBubbledEvent(TOP_INVALID, domElement);
7839 // For controlled components we always need to ensure we're listening
7840 // to onChange. Even if there is no listener.
7841 ensureListeningTo(rootContainerElement, 'onChange');
7842 break;
7843 case 'textarea':
7844 initWrapperState$2(domElement, rawProps);
7845 props = getHostProps$3(domElement, rawProps);
7846 trapBubbledEvent(TOP_INVALID, domElement);
7847 // For controlled components we always need to ensure we're listening
7848 // to onChange. Even if there is no listener.
7849 ensureListeningTo(rootContainerElement, 'onChange');
7850 break;
7851 default:
7852 props = rawProps;
7853 }
7854
7855 assertValidProps(tag, props);
7856
7857 setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
7858
7859 switch (tag) {
7860 case 'input':
7861 // TODO: Make sure we check if this is still unmounted or do any clean
7862 // up necessary since we never stop tracking anymore.
7863 track(domElement);
7864 postMountWrapper(domElement, rawProps, false);
7865 break;
7866 case 'textarea':
7867 // TODO: Make sure we check if this is still unmounted or do any clean
7868 // up necessary since we never stop tracking anymore.
7869 track(domElement);
7870 postMountWrapper$3(domElement, rawProps);
7871 break;
7872 case 'option':
7873 postMountWrapper$1(domElement, rawProps);
7874 break;
7875 case 'select':
7876 postMountWrapper$2(domElement, rawProps);
7877 break;
7878 default:
7879 if (typeof props.onClick === 'function') {
7880 // TODO: This cast may not be sound for SVG, MathML or custom elements.
7881 trapClickOnNonInteractiveElement(domElement);
7882 }
7883 break;
7884 }
7885}
7886
7887// Calculate the diff between the two objects.
7888function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
7889 {
7890 validatePropertiesInDevelopment(tag, nextRawProps);
7891 }
7892
7893 var updatePayload = null;
7894
7895 var lastProps = void 0;
7896 var nextProps = void 0;
7897 switch (tag) {
7898 case 'input':
7899 lastProps = getHostProps(domElement, lastRawProps);
7900 nextProps = getHostProps(domElement, nextRawProps);
7901 updatePayload = [];
7902 break;
7903 case 'option':
7904 lastProps = getHostProps$1(domElement, lastRawProps);
7905 nextProps = getHostProps$1(domElement, nextRawProps);
7906 updatePayload = [];
7907 break;
7908 case 'select':
7909 lastProps = getHostProps$2(domElement, lastRawProps);
7910 nextProps = getHostProps$2(domElement, nextRawProps);
7911 updatePayload = [];
7912 break;
7913 case 'textarea':
7914 lastProps = getHostProps$3(domElement, lastRawProps);
7915 nextProps = getHostProps$3(domElement, nextRawProps);
7916 updatePayload = [];
7917 break;
7918 default:
7919 lastProps = lastRawProps;
7920 nextProps = nextRawProps;
7921 if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
7922 // TODO: This cast may not be sound for SVG, MathML or custom elements.
7923 trapClickOnNonInteractiveElement(domElement);
7924 }
7925 break;
7926 }
7927
7928 assertValidProps(tag, nextProps);
7929
7930 var propKey = void 0;
7931 var styleName = void 0;
7932 var styleUpdates = null;
7933 for (propKey in lastProps) {
7934 if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
7935 continue;
7936 }
7937 if (propKey === STYLE$1) {
7938 var lastStyle = lastProps[propKey];
7939 for (styleName in lastStyle) {
7940 if (lastStyle.hasOwnProperty(styleName)) {
7941 if (!styleUpdates) {
7942 styleUpdates = {};
7943 }
7944 styleUpdates[styleName] = '';
7945 }
7946 }
7947 } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) {
7948 // Noop. This is handled by the clear text mechanism.
7949 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
7950 // Noop
7951 } else if (propKey === AUTOFOCUS) {
7952 // Noop. It doesn't work on updates anyway.
7953 } else if (registrationNameModules.hasOwnProperty(propKey)) {
7954 // This is a special case. If any listener updates we need to ensure
7955 // that the "current" fiber pointer gets updated so we need a commit
7956 // to update this element.
7957 if (!updatePayload) {
7958 updatePayload = [];
7959 }
7960 } else {
7961 // For all other deleted properties we add it to the queue. We use
7962 // the whitelist in the commit phase instead.
7963 (updatePayload = updatePayload || []).push(propKey, null);
7964 }
7965 }
7966 for (propKey in nextProps) {
7967 var nextProp = nextProps[propKey];
7968 var lastProp = lastProps != null ? lastProps[propKey] : undefined;
7969 if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
7970 continue;
7971 }
7972 if (propKey === STYLE$1) {
7973 {
7974 if (nextProp) {
7975 // Freeze the next style object so that we can assume it won't be
7976 // mutated. We have already warned for this in the past.
7977 Object.freeze(nextProp);
7978 }
7979 }
7980 if (lastProp) {
7981 // Unset styles on `lastProp` but not on `nextProp`.
7982 for (styleName in lastProp) {
7983 if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
7984 if (!styleUpdates) {
7985 styleUpdates = {};
7986 }
7987 styleUpdates[styleName] = '';
7988 }
7989 }
7990 // Update styles that changed since `lastProp`.
7991 for (styleName in nextProp) {
7992 if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
7993 if (!styleUpdates) {
7994 styleUpdates = {};
7995 }
7996 styleUpdates[styleName] = nextProp[styleName];
7997 }
7998 }
7999 } else {
8000 // Relies on `updateStylesByID` not mutating `styleUpdates`.
8001 if (!styleUpdates) {
8002 if (!updatePayload) {
8003 updatePayload = [];
8004 }
8005 updatePayload.push(propKey, styleUpdates);
8006 }
8007 styleUpdates = nextProp;
8008 }
8009 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8010 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8011 var lastHtml = lastProp ? lastProp[HTML] : undefined;
8012 if (nextHtml != null) {
8013 if (lastHtml !== nextHtml) {
8014 (updatePayload = updatePayload || []).push(propKey, '' + nextHtml);
8015 }
8016 } else {
8017 // TODO: It might be too late to clear this if we have children
8018 // inserted already.
8019 }
8020 } else if (propKey === CHILDREN) {
8021 if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {
8022 (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
8023 }
8024 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
8025 // Noop
8026 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8027 if (nextProp != null) {
8028 // We eagerly listen to this even though we haven't committed yet.
8029 if (true && typeof nextProp !== 'function') {
8030 warnForInvalidEventListener(propKey, nextProp);
8031 }
8032 ensureListeningTo(rootContainerElement, propKey);
8033 }
8034 if (!updatePayload && lastProp !== nextProp) {
8035 // This is a special case. If any listener updates we need to ensure
8036 // that the "current" props pointer gets updated so we need a commit
8037 // to update this element.
8038 updatePayload = [];
8039 }
8040 } else {
8041 // For any other property we always add it to the queue and then we
8042 // filter it out using the whitelist during the commit.
8043 (updatePayload = updatePayload || []).push(propKey, nextProp);
8044 }
8045 }
8046 if (styleUpdates) {
8047 {
8048 validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE$1]);
8049 }
8050 (updatePayload = updatePayload || []).push(STYLE$1, styleUpdates);
8051 }
8052 return updatePayload;
8053}
8054
8055// Apply the diff.
8056function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
8057 // Update checked *before* name.
8058 // In the middle of an update, it is possible to have multiple checked.
8059 // When a checked radio tries to change name, browser makes another radio's checked false.
8060 if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
8061 updateChecked(domElement, nextRawProps);
8062 }
8063
8064 var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
8065 var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
8066 // Apply the diff.
8067 updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag);
8068
8069 // TODO: Ensure that an update gets scheduled if any of the special props
8070 // changed.
8071 switch (tag) {
8072 case 'input':
8073 // Update the wrapper around inputs *after* updating props. This has to
8074 // happen after `updateDOMProperties`. Otherwise HTML5 input validations
8075 // raise warnings and prevent the new value from being assigned.
8076 updateWrapper(domElement, nextRawProps);
8077 break;
8078 case 'textarea':
8079 updateWrapper$1(domElement, nextRawProps);
8080 break;
8081 case 'select':
8082 // <select> value update needs to occur after <option> children
8083 // reconciliation
8084 postUpdateWrapper(domElement, nextRawProps);
8085 break;
8086 }
8087}
8088
8089function getPossibleStandardName(propName) {
8090 {
8091 var lowerCasedName = propName.toLowerCase();
8092 if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
8093 return null;
8094 }
8095 return possibleStandardNames[lowerCasedName] || null;
8096 }
8097 return null;
8098}
8099
8100function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {
8101 var isCustomComponentTag = void 0;
8102 var extraAttributeNames = void 0;
8103
8104 {
8105 suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING$1] === true;
8106 isCustomComponentTag = isCustomComponent(tag, rawProps);
8107 validatePropertiesInDevelopment(tag, rawProps);
8108 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
8109 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
8110 didWarnShadyDOM = true;
8111 }
8112 }
8113
8114 // TODO: Make sure that we check isMounted before firing any of these events.
8115 switch (tag) {
8116 case 'iframe':
8117 case 'object':
8118 trapBubbledEvent(TOP_LOAD, domElement);
8119 break;
8120 case 'video':
8121 case 'audio':
8122 // Create listener for each media event
8123 for (var i = 0; i < mediaEventTypes.length; i++) {
8124 trapBubbledEvent(mediaEventTypes[i], domElement);
8125 }
8126 break;
8127 case 'source':
8128 trapBubbledEvent(TOP_ERROR, domElement);
8129 break;
8130 case 'img':
8131 case 'image':
8132 case 'link':
8133 trapBubbledEvent(TOP_ERROR, domElement);
8134 trapBubbledEvent(TOP_LOAD, domElement);
8135 break;
8136 case 'form':
8137 trapBubbledEvent(TOP_RESET, domElement);
8138 trapBubbledEvent(TOP_SUBMIT, domElement);
8139 break;
8140 case 'details':
8141 trapBubbledEvent(TOP_TOGGLE, domElement);
8142 break;
8143 case 'input':
8144 initWrapperState(domElement, rawProps);
8145 trapBubbledEvent(TOP_INVALID, domElement);
8146 // For controlled components we always need to ensure we're listening
8147 // to onChange. Even if there is no listener.
8148 ensureListeningTo(rootContainerElement, 'onChange');
8149 break;
8150 case 'option':
8151 validateProps(domElement, rawProps);
8152 break;
8153 case 'select':
8154 initWrapperState$1(domElement, rawProps);
8155 trapBubbledEvent(TOP_INVALID, domElement);
8156 // For controlled components we always need to ensure we're listening
8157 // to onChange. Even if there is no listener.
8158 ensureListeningTo(rootContainerElement, 'onChange');
8159 break;
8160 case 'textarea':
8161 initWrapperState$2(domElement, rawProps);
8162 trapBubbledEvent(TOP_INVALID, domElement);
8163 // For controlled components we always need to ensure we're listening
8164 // to onChange. Even if there is no listener.
8165 ensureListeningTo(rootContainerElement, 'onChange');
8166 break;
8167 }
8168
8169 assertValidProps(tag, rawProps);
8170
8171 {
8172 extraAttributeNames = new Set();
8173 var attributes = domElement.attributes;
8174 for (var _i = 0; _i < attributes.length; _i++) {
8175 var name = attributes[_i].name.toLowerCase();
8176 switch (name) {
8177 // Built-in SSR attribute is whitelisted
8178 case 'data-reactroot':
8179 break;
8180 // Controlled attributes are not validated
8181 // TODO: Only ignore them on controlled tags.
8182 case 'value':
8183 break;
8184 case 'checked':
8185 break;
8186 case 'selected':
8187 break;
8188 default:
8189 // Intentionally use the original name.
8190 // See discussion in https://github.com/facebook/react/pull/10676.
8191 extraAttributeNames.add(attributes[_i].name);
8192 }
8193 }
8194 }
8195
8196 var updatePayload = null;
8197 for (var propKey in rawProps) {
8198 if (!rawProps.hasOwnProperty(propKey)) {
8199 continue;
8200 }
8201 var nextProp = rawProps[propKey];
8202 if (propKey === CHILDREN) {
8203 // For text content children we compare against textContent. This
8204 // might match additional HTML that is hidden when we read it using
8205 // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
8206 // satisfies our requirement. Our requirement is not to produce perfect
8207 // HTML and attributes. Ideally we should preserve structure but it's
8208 // ok not to if the visible content is still enough to indicate what
8209 // even listeners these nodes might be wired up to.
8210 // TODO: Warn if there is more than a single textNode as a child.
8211 // TODO: Should we use domElement.firstChild.nodeValue to compare?
8212 if (typeof nextProp === 'string') {
8213 if (domElement.textContent !== nextProp) {
8214 if (true && !suppressHydrationWarning) {
8215 warnForTextDifference(domElement.textContent, nextProp);
8216 }
8217 updatePayload = [CHILDREN, nextProp];
8218 }
8219 } else if (typeof nextProp === 'number') {
8220 if (domElement.textContent !== '' + nextProp) {
8221 if (true && !suppressHydrationWarning) {
8222 warnForTextDifference(domElement.textContent, nextProp);
8223 }
8224 updatePayload = [CHILDREN, '' + nextProp];
8225 }
8226 }
8227 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8228 if (nextProp != null) {
8229 if (true && typeof nextProp !== 'function') {
8230 warnForInvalidEventListener(propKey, nextProp);
8231 }
8232 ensureListeningTo(rootContainerElement, propKey);
8233 }
8234 } else if (true &&
8235 // Convince Flow we've calculated it (it's DEV-only in this method.)
8236 typeof isCustomComponentTag === 'boolean') {
8237 // Validate that the properties correspond to their expected values.
8238 var serverValue = void 0;
8239 var propertyInfo = getPropertyInfo(propKey);
8240 if (suppressHydrationWarning) {
8241 // Don't bother comparing. We're ignoring all these warnings.
8242 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1 ||
8243 // Controlled attributes are not validated
8244 // TODO: Only ignore them on controlled tags.
8245 propKey === 'value' || propKey === 'checked' || propKey === 'selected') {
8246 // Noop
8247 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8248 var serverHTML = domElement.innerHTML;
8249 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8250 var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : '');
8251 if (expectedHTML !== serverHTML) {
8252 warnForPropDifference(propKey, serverHTML, expectedHTML);
8253 }
8254 } else if (propKey === STYLE$1) {
8255 // $FlowFixMe - Should be inferred as not undefined.
8256 extraAttributeNames.delete(propKey);
8257
8258 if (canDiffStyleForHydrationWarning) {
8259 var expectedStyle = createDangerousStringForStyles(nextProp);
8260 serverValue = domElement.getAttribute('style');
8261 if (expectedStyle !== serverValue) {
8262 warnForPropDifference(propKey, serverValue, expectedStyle);
8263 }
8264 }
8265 } else if (isCustomComponentTag) {
8266 // $FlowFixMe - Should be inferred as not undefined.
8267 extraAttributeNames.delete(propKey.toLowerCase());
8268 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8269
8270 if (nextProp !== serverValue) {
8271 warnForPropDifference(propKey, serverValue, nextProp);
8272 }
8273 } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
8274 var isMismatchDueToBadCasing = false;
8275 if (propertyInfo !== null) {
8276 // $FlowFixMe - Should be inferred as not undefined.
8277 extraAttributeNames.delete(propertyInfo.attributeName);
8278 serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
8279 } else {
8280 var ownNamespace = parentNamespace;
8281 if (ownNamespace === HTML_NAMESPACE) {
8282 ownNamespace = getIntrinsicNamespace(tag);
8283 }
8284 if (ownNamespace === HTML_NAMESPACE) {
8285 // $FlowFixMe - Should be inferred as not undefined.
8286 extraAttributeNames.delete(propKey.toLowerCase());
8287 } else {
8288 var standardName = getPossibleStandardName(propKey);
8289 if (standardName !== null && standardName !== propKey) {
8290 // If an SVG prop is supplied with bad casing, it will
8291 // be successfully parsed from HTML, but will produce a mismatch
8292 // (and would be incorrectly rendered on the client).
8293 // However, we already warn about bad casing elsewhere.
8294 // So we'll skip the misleading extra mismatch warning in this case.
8295 isMismatchDueToBadCasing = true;
8296 // $FlowFixMe - Should be inferred as not undefined.
8297 extraAttributeNames.delete(standardName);
8298 }
8299 // $FlowFixMe - Should be inferred as not undefined.
8300 extraAttributeNames.delete(propKey);
8301 }
8302 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8303 }
8304
8305 if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
8306 warnForPropDifference(propKey, serverValue, nextProp);
8307 }
8308 }
8309 }
8310 }
8311
8312 {
8313 // $FlowFixMe - Should be inferred as not undefined.
8314 if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
8315 // $FlowFixMe - Should be inferred as not undefined.
8316 warnForExtraAttributes(extraAttributeNames);
8317 }
8318 }
8319
8320 switch (tag) {
8321 case 'input':
8322 // TODO: Make sure we check if this is still unmounted or do any clean
8323 // up necessary since we never stop tracking anymore.
8324 track(domElement);
8325 postMountWrapper(domElement, rawProps, true);
8326 break;
8327 case 'textarea':
8328 // TODO: Make sure we check if this is still unmounted or do any clean
8329 // up necessary since we never stop tracking anymore.
8330 track(domElement);
8331 postMountWrapper$3(domElement, rawProps);
8332 break;
8333 case 'select':
8334 case 'option':
8335 // For input and textarea we current always set the value property at
8336 // post mount to force it to diverge from attributes. However, for
8337 // option and select we don't quite do the same thing and select
8338 // is not resilient to the DOM state changing so we don't do that here.
8339 // TODO: Consider not doing this for input and textarea.
8340 break;
8341 default:
8342 if (typeof rawProps.onClick === 'function') {
8343 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8344 trapClickOnNonInteractiveElement(domElement);
8345 }
8346 break;
8347 }
8348
8349 return updatePayload;
8350}
8351
8352function diffHydratedText(textNode, text) {
8353 var isDifferent = textNode.nodeValue !== text;
8354 return isDifferent;
8355}
8356
8357function warnForUnmatchedText(textNode, text) {
8358 {
8359 warnForTextDifference(textNode.nodeValue, text);
8360 }
8361}
8362
8363function warnForDeletedHydratableElement(parentNode, child) {
8364 {
8365 if (didWarnInvalidHydration) {
8366 return;
8367 }
8368 didWarnInvalidHydration = true;
8369 warningWithoutStack$1(false, 'Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
8370 }
8371}
8372
8373function warnForDeletedHydratableText(parentNode, child) {
8374 {
8375 if (didWarnInvalidHydration) {
8376 return;
8377 }
8378 didWarnInvalidHydration = true;
8379 warningWithoutStack$1(false, 'Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
8380 }
8381}
8382
8383function warnForInsertedHydratedElement(parentNode, tag, props) {
8384 {
8385 if (didWarnInvalidHydration) {
8386 return;
8387 }
8388 didWarnInvalidHydration = true;
8389 warningWithoutStack$1(false, 'Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
8390 }
8391}
8392
8393function warnForInsertedHydratedText(parentNode, text) {
8394 {
8395 if (text === '') {
8396 // We expect to insert empty text nodes since they're not represented in
8397 // the HTML.
8398 // TODO: Remove this special case if we can just avoid inserting empty
8399 // text nodes.
8400 return;
8401 }
8402 if (didWarnInvalidHydration) {
8403 return;
8404 }
8405 didWarnInvalidHydration = true;
8406 warningWithoutStack$1(false, 'Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
8407 }
8408}
8409
8410function restoreControlledState$1(domElement, tag, props) {
8411 switch (tag) {
8412 case 'input':
8413 restoreControlledState(domElement, props);
8414 return;
8415 case 'textarea':
8416 restoreControlledState$3(domElement, props);
8417 return;
8418 case 'select':
8419 restoreControlledState$2(domElement, props);
8420 return;
8421 }
8422}
8423
8424// TODO: direct imports like some-package/src/* are bad. Fix me.
8425var validateDOMNesting = function () {};
8426var updatedAncestorInfo = function () {};
8427
8428{
8429 // This validation code was written based on the HTML5 parsing spec:
8430 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
8431 //
8432 // Note: this does not catch all invalid nesting, nor does it try to (as it's
8433 // not clear what practical benefit doing so provides); instead, we warn only
8434 // for cases where the parser will give a parse tree differing from what React
8435 // intended. For example, <b><div></div></b> is invalid but we don't warn
8436 // because it still parses correctly; we do warn for other cases like nested
8437 // <p> tags where the beginning of the second element implicitly closes the
8438 // first, causing a confusing mess.
8439
8440 // https://html.spec.whatwg.org/multipage/syntax.html#special
8441 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'];
8442
8443 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
8444 var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template',
8445
8446 // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
8447 // TODO: Distinguish by namespace here -- for <title>, including it here
8448 // errs on the side of fewer warnings
8449 'foreignObject', 'desc', 'title'];
8450
8451 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
8452 var buttonScopeTags = inScopeTags.concat(['button']);
8453
8454 // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
8455 var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
8456
8457 var emptyAncestorInfo = {
8458 current: null,
8459
8460 formTag: null,
8461 aTagInScope: null,
8462 buttonTagInScope: null,
8463 nobrTagInScope: null,
8464 pTagInButtonScope: null,
8465
8466 listItemTagAutoclosing: null,
8467 dlItemTagAutoclosing: null
8468 };
8469
8470 updatedAncestorInfo = function (oldInfo, tag) {
8471 var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
8472 var info = { tag: tag };
8473
8474 if (inScopeTags.indexOf(tag) !== -1) {
8475 ancestorInfo.aTagInScope = null;
8476 ancestorInfo.buttonTagInScope = null;
8477 ancestorInfo.nobrTagInScope = null;
8478 }
8479 if (buttonScopeTags.indexOf(tag) !== -1) {
8480 ancestorInfo.pTagInButtonScope = null;
8481 }
8482
8483 // See rules for 'li', 'dd', 'dt' start tags in
8484 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
8485 if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
8486 ancestorInfo.listItemTagAutoclosing = null;
8487 ancestorInfo.dlItemTagAutoclosing = null;
8488 }
8489
8490 ancestorInfo.current = info;
8491
8492 if (tag === 'form') {
8493 ancestorInfo.formTag = info;
8494 }
8495 if (tag === 'a') {
8496 ancestorInfo.aTagInScope = info;
8497 }
8498 if (tag === 'button') {
8499 ancestorInfo.buttonTagInScope = info;
8500 }
8501 if (tag === 'nobr') {
8502 ancestorInfo.nobrTagInScope = info;
8503 }
8504 if (tag === 'p') {
8505 ancestorInfo.pTagInButtonScope = info;
8506 }
8507 if (tag === 'li') {
8508 ancestorInfo.listItemTagAutoclosing = info;
8509 }
8510 if (tag === 'dd' || tag === 'dt') {
8511 ancestorInfo.dlItemTagAutoclosing = info;
8512 }
8513
8514 return ancestorInfo;
8515 };
8516
8517 /**
8518 * Returns whether
8519 */
8520 var isTagValidWithParent = function (tag, parentTag) {
8521 // First, let's check if we're in an unusual parsing mode...
8522 switch (parentTag) {
8523 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
8524 case 'select':
8525 return tag === 'option' || tag === 'optgroup' || tag === '#text';
8526 case 'optgroup':
8527 return tag === 'option' || tag === '#text';
8528 // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
8529 // but
8530 case 'option':
8531 return tag === '#text';
8532 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
8533 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
8534 // No special behavior since these rules fall back to "in body" mode for
8535 // all except special table nodes which cause bad parsing behavior anyway.
8536
8537 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
8538 case 'tr':
8539 return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
8540 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
8541 case 'tbody':
8542 case 'thead':
8543 case 'tfoot':
8544 return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
8545 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
8546 case 'colgroup':
8547 return tag === 'col' || tag === 'template';
8548 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
8549 case 'table':
8550 return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
8551 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
8552 case 'head':
8553 return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
8554 // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
8555 case 'html':
8556 return tag === 'head' || tag === 'body';
8557 case '#document':
8558 return tag === 'html';
8559 }
8560
8561 // Probably in the "in body" parsing mode, so we outlaw only tag combos
8562 // where the parsing rules cause implicit opens or closes to be added.
8563 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
8564 switch (tag) {
8565 case 'h1':
8566 case 'h2':
8567 case 'h3':
8568 case 'h4':
8569 case 'h5':
8570 case 'h6':
8571 return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
8572
8573 case 'rp':
8574 case 'rt':
8575 return impliedEndTags.indexOf(parentTag) === -1;
8576
8577 case 'body':
8578 case 'caption':
8579 case 'col':
8580 case 'colgroup':
8581 case 'frame':
8582 case 'head':
8583 case 'html':
8584 case 'tbody':
8585 case 'td':
8586 case 'tfoot':
8587 case 'th':
8588 case 'thead':
8589 case 'tr':
8590 // These tags are only valid with a few parents that have special child
8591 // parsing rules -- if we're down here, then none of those matched and
8592 // so we allow it only if we don't know what the parent is, as all other
8593 // cases are invalid.
8594 return parentTag == null;
8595 }
8596
8597 return true;
8598 };
8599
8600 /**
8601 * Returns whether
8602 */
8603 var findInvalidAncestorForTag = function (tag, ancestorInfo) {
8604 switch (tag) {
8605 case 'address':
8606 case 'article':
8607 case 'aside':
8608 case 'blockquote':
8609 case 'center':
8610 case 'details':
8611 case 'dialog':
8612 case 'dir':
8613 case 'div':
8614 case 'dl':
8615 case 'fieldset':
8616 case 'figcaption':
8617 case 'figure':
8618 case 'footer':
8619 case 'header':
8620 case 'hgroup':
8621 case 'main':
8622 case 'menu':
8623 case 'nav':
8624 case 'ol':
8625 case 'p':
8626 case 'section':
8627 case 'summary':
8628 case 'ul':
8629 case 'pre':
8630 case 'listing':
8631 case 'table':
8632 case 'hr':
8633 case 'xmp':
8634 case 'h1':
8635 case 'h2':
8636 case 'h3':
8637 case 'h4':
8638 case 'h5':
8639 case 'h6':
8640 return ancestorInfo.pTagInButtonScope;
8641
8642 case 'form':
8643 return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
8644
8645 case 'li':
8646 return ancestorInfo.listItemTagAutoclosing;
8647
8648 case 'dd':
8649 case 'dt':
8650 return ancestorInfo.dlItemTagAutoclosing;
8651
8652 case 'button':
8653 return ancestorInfo.buttonTagInScope;
8654
8655 case 'a':
8656 // Spec says something about storing a list of markers, but it sounds
8657 // equivalent to this check.
8658 return ancestorInfo.aTagInScope;
8659
8660 case 'nobr':
8661 return ancestorInfo.nobrTagInScope;
8662 }
8663
8664 return null;
8665 };
8666
8667 var didWarn = {};
8668
8669 validateDOMNesting = function (childTag, childText, ancestorInfo) {
8670 ancestorInfo = ancestorInfo || emptyAncestorInfo;
8671 var parentInfo = ancestorInfo.current;
8672 var parentTag = parentInfo && parentInfo.tag;
8673
8674 if (childText != null) {
8675 !(childTag == null) ? warningWithoutStack$1(false, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0;
8676 childTag = '#text';
8677 }
8678
8679 var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
8680 var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
8681 var invalidParentOrAncestor = invalidParent || invalidAncestor;
8682 if (!invalidParentOrAncestor) {
8683 return;
8684 }
8685
8686 var ancestorTag = invalidParentOrAncestor.tag;
8687 var addendum = getCurrentFiberStackInDev();
8688
8689 var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;
8690 if (didWarn[warnKey]) {
8691 return;
8692 }
8693 didWarn[warnKey] = true;
8694
8695 var tagDisplayName = childTag;
8696 var whitespaceInfo = '';
8697 if (childTag === '#text') {
8698 if (/\S/.test(childText)) {
8699 tagDisplayName = 'Text nodes';
8700 } else {
8701 tagDisplayName = 'Whitespace text nodes';
8702 whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
8703 }
8704 } else {
8705 tagDisplayName = '<' + childTag + '>';
8706 }
8707
8708 if (invalidParent) {
8709 var info = '';
8710 if (ancestorTag === 'table' && childTag === 'tr') {
8711 info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.';
8712 }
8713 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info, addendum);
8714 } else {
8715 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.%s', tagDisplayName, ancestorTag, addendum);
8716 }
8717 };
8718}
8719
8720var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
8721
8722var _ReactInternals$Sched = ReactInternals$1.Scheduler;
8723var unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback;
8724var unstable_now = _ReactInternals$Sched.unstable_now;
8725var unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback;
8726var unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield;
8727var unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode;
8728var unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority;
8729var unstable_next = _ReactInternals$Sched.unstable_next;
8730var unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution;
8731var unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution;
8732var unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel;
8733var unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority;
8734var unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority;
8735var unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority;
8736var unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority;
8737var unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority;
8738
8739// Renderers that don't support persistence
8740// can re-export everything from this module.
8741
8742function shim() {
8743 invariant(false, 'The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.');
8744}
8745
8746// Persistence (when unsupported)
8747var supportsPersistence = false;
8748var cloneInstance = shim;
8749var createContainerChildSet = shim;
8750var appendChildToContainerChildSet = shim;
8751var finalizeContainerChildren = shim;
8752var replaceContainerChildren = shim;
8753var cloneHiddenInstance = shim;
8754var cloneUnhiddenInstance = shim;
8755var createHiddenTextInstance = shim;
8756
8757var SUPPRESS_HYDRATION_WARNING = void 0;
8758{
8759 SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
8760}
8761
8762var SUSPENSE_START_DATA = '$';
8763var SUSPENSE_END_DATA = '/$';
8764
8765var STYLE = 'style';
8766
8767var eventsEnabled = null;
8768var selectionInformation = null;
8769
8770function shouldAutoFocusHostComponent(type, props) {
8771 switch (type) {
8772 case 'button':
8773 case 'input':
8774 case 'select':
8775 case 'textarea':
8776 return !!props.autoFocus;
8777 }
8778 return false;
8779}
8780
8781function getRootHostContext(rootContainerInstance) {
8782 var type = void 0;
8783 var namespace = void 0;
8784 var nodeType = rootContainerInstance.nodeType;
8785 switch (nodeType) {
8786 case DOCUMENT_NODE:
8787 case DOCUMENT_FRAGMENT_NODE:
8788 {
8789 type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
8790 var root = rootContainerInstance.documentElement;
8791 namespace = root ? root.namespaceURI : getChildNamespace(null, '');
8792 break;
8793 }
8794 default:
8795 {
8796 var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
8797 var ownNamespace = container.namespaceURI || null;
8798 type = container.tagName;
8799 namespace = getChildNamespace(ownNamespace, type);
8800 break;
8801 }
8802 }
8803 {
8804 var validatedTag = type.toLowerCase();
8805 var _ancestorInfo = updatedAncestorInfo(null, validatedTag);
8806 return { namespace: namespace, ancestorInfo: _ancestorInfo };
8807 }
8808 return namespace;
8809}
8810
8811function getChildHostContext(parentHostContext, type, rootContainerInstance) {
8812 {
8813 var parentHostContextDev = parentHostContext;
8814 var _namespace = getChildNamespace(parentHostContextDev.namespace, type);
8815 var _ancestorInfo2 = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
8816 return { namespace: _namespace, ancestorInfo: _ancestorInfo2 };
8817 }
8818 var parentNamespace = parentHostContext;
8819 return getChildNamespace(parentNamespace, type);
8820}
8821
8822function getPublicInstance(instance) {
8823 return instance;
8824}
8825
8826function prepareForCommit(containerInfo) {
8827 eventsEnabled = isEnabled();
8828 selectionInformation = getSelectionInformation();
8829 setEnabled(false);
8830}
8831
8832function resetAfterCommit(containerInfo) {
8833 restoreSelection(selectionInformation);
8834 selectionInformation = null;
8835 setEnabled(eventsEnabled);
8836 eventsEnabled = null;
8837}
8838
8839function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
8840 var parentNamespace = void 0;
8841 {
8842 // TODO: take namespace into account when validating.
8843 var hostContextDev = hostContext;
8844 validateDOMNesting(type, null, hostContextDev.ancestorInfo);
8845 if (typeof props.children === 'string' || typeof props.children === 'number') {
8846 var string = '' + props.children;
8847 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
8848 validateDOMNesting(null, string, ownAncestorInfo);
8849 }
8850 parentNamespace = hostContextDev.namespace;
8851 }
8852 var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
8853 precacheFiberNode(internalInstanceHandle, domElement);
8854 updateFiberProps(domElement, props);
8855 return domElement;
8856}
8857
8858function appendInitialChild(parentInstance, child) {
8859 parentInstance.appendChild(child);
8860}
8861
8862function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
8863 setInitialProperties(domElement, type, props, rootContainerInstance);
8864 return shouldAutoFocusHostComponent(type, props);
8865}
8866
8867function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
8868 {
8869 var hostContextDev = hostContext;
8870 if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
8871 var string = '' + newProps.children;
8872 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
8873 validateDOMNesting(null, string, ownAncestorInfo);
8874 }
8875 }
8876 return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);
8877}
8878
8879function shouldSetTextContent(type, props) {
8880 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;
8881}
8882
8883function shouldDeprioritizeSubtree(type, props) {
8884 return !!props.hidden;
8885}
8886
8887function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
8888 {
8889 var hostContextDev = hostContext;
8890 validateDOMNesting(null, text, hostContextDev.ancestorInfo);
8891 }
8892 var textNode = createTextNode(text, rootContainerInstance);
8893 precacheFiberNode(internalInstanceHandle, textNode);
8894 return textNode;
8895}
8896
8897var isPrimaryRenderer = true;
8898// This initialization code may run even on server environments
8899// if a component just imports ReactDOM (e.g. for findDOMNode).
8900// Some environments might not have setTimeout or clearTimeout.
8901var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
8902var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
8903var noTimeout = -1;
8904var schedulePassiveEffects = unstable_scheduleCallback;
8905var cancelPassiveEffects = unstable_cancelCallback;
8906
8907// -------------------
8908// Mutation
8909// -------------------
8910
8911var supportsMutation = true;
8912
8913function commitMount(domElement, type, newProps, internalInstanceHandle) {
8914 // Despite the naming that might imply otherwise, this method only
8915 // fires if there is an `Update` effect scheduled during mounting.
8916 // This happens if `finalizeInitialChildren` returns `true` (which it
8917 // does to implement the `autoFocus` attribute on the client). But
8918 // there are also other cases when this might happen (such as patching
8919 // up text content during hydration mismatch). So we'll check this again.
8920 if (shouldAutoFocusHostComponent(type, newProps)) {
8921 domElement.focus();
8922 }
8923}
8924
8925function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
8926 // Update the props handle so that we know which props are the ones with
8927 // with current event handlers.
8928 updateFiberProps(domElement, newProps);
8929 // Apply the diff to the DOM node.
8930 updateProperties(domElement, updatePayload, type, oldProps, newProps);
8931}
8932
8933function resetTextContent(domElement) {
8934 setTextContent(domElement, '');
8935}
8936
8937function commitTextUpdate(textInstance, oldText, newText) {
8938 textInstance.nodeValue = newText;
8939}
8940
8941function appendChild(parentInstance, child) {
8942 parentInstance.appendChild(child);
8943}
8944
8945function appendChildToContainer(container, child) {
8946 var parentNode = void 0;
8947 if (container.nodeType === COMMENT_NODE) {
8948 parentNode = container.parentNode;
8949 parentNode.insertBefore(child, container);
8950 } else {
8951 parentNode = container;
8952 parentNode.appendChild(child);
8953 }
8954 // This container might be used for a portal.
8955 // If something inside a portal is clicked, that click should bubble
8956 // through the React tree. However, on Mobile Safari the click would
8957 // never bubble through the *DOM* tree unless an ancestor with onclick
8958 // event exists. So we wouldn't see it and dispatch it.
8959 // This is why we ensure that non React root containers have inline onclick
8960 // defined.
8961 // https://github.com/facebook/react/issues/11918
8962 var reactRootContainer = container._reactRootContainer;
8963 if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
8964 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8965 trapClickOnNonInteractiveElement(parentNode);
8966 }
8967}
8968
8969function insertBefore(parentInstance, child, beforeChild) {
8970 parentInstance.insertBefore(child, beforeChild);
8971}
8972
8973function insertInContainerBefore(container, child, beforeChild) {
8974 if (container.nodeType === COMMENT_NODE) {
8975 container.parentNode.insertBefore(child, beforeChild);
8976 } else {
8977 container.insertBefore(child, beforeChild);
8978 }
8979}
8980
8981function removeChild(parentInstance, child) {
8982 parentInstance.removeChild(child);
8983}
8984
8985function removeChildFromContainer(container, child) {
8986 if (container.nodeType === COMMENT_NODE) {
8987 container.parentNode.removeChild(child);
8988 } else {
8989 container.removeChild(child);
8990 }
8991}
8992
8993function clearSuspenseBoundary(parentInstance, suspenseInstance) {
8994 var node = suspenseInstance;
8995 // Delete all nodes within this suspense boundary.
8996 // There might be nested nodes so we need to keep track of how
8997 // deep we are and only break out when we're back on top.
8998 var depth = 0;
8999 do {
9000 var nextNode = node.nextSibling;
9001 parentInstance.removeChild(node);
9002 if (nextNode && nextNode.nodeType === COMMENT_NODE) {
9003 var data = nextNode.data;
9004 if (data === SUSPENSE_END_DATA) {
9005 if (depth === 0) {
9006 parentInstance.removeChild(nextNode);
9007 return;
9008 } else {
9009 depth--;
9010 }
9011 } else if (data === SUSPENSE_START_DATA) {
9012 depth++;
9013 }
9014 }
9015 node = nextNode;
9016 } while (node);
9017 // TODO: Warn, we didn't find the end comment boundary.
9018}
9019
9020function clearSuspenseBoundaryFromContainer(container, suspenseInstance) {
9021 if (container.nodeType === COMMENT_NODE) {
9022 clearSuspenseBoundary(container.parentNode, suspenseInstance);
9023 } else if (container.nodeType === ELEMENT_NODE) {
9024 clearSuspenseBoundary(container, suspenseInstance);
9025 } else {
9026 // Document nodes should never contain suspense boundaries.
9027 }
9028}
9029
9030function hideInstance(instance) {
9031 // TODO: Does this work for all element types? What about MathML? Should we
9032 // pass host context to this method?
9033 instance = instance;
9034 instance.style.display = 'none';
9035}
9036
9037function hideTextInstance(textInstance) {
9038 textInstance.nodeValue = '';
9039}
9040
9041function unhideInstance(instance, props) {
9042 instance = instance;
9043 var styleProp = props[STYLE];
9044 var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
9045 instance.style.display = dangerousStyleValue('display', display);
9046}
9047
9048function unhideTextInstance(textInstance, text) {
9049 textInstance.nodeValue = text;
9050}
9051
9052// -------------------
9053// Hydration
9054// -------------------
9055
9056var supportsHydration = true;
9057
9058function canHydrateInstance(instance, type, props) {
9059 if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
9060 return null;
9061 }
9062 // This has now been refined to an element node.
9063 return instance;
9064}
9065
9066function canHydrateTextInstance(instance, text) {
9067 if (text === '' || instance.nodeType !== TEXT_NODE) {
9068 // Empty strings are not parsed by HTML so there won't be a correct match here.
9069 return null;
9070 }
9071 // This has now been refined to a text node.
9072 return instance;
9073}
9074
9075function canHydrateSuspenseInstance(instance) {
9076 if (instance.nodeType !== COMMENT_NODE) {
9077 // Empty strings are not parsed by HTML so there won't be a correct match here.
9078 return null;
9079 }
9080 // This has now been refined to a suspense node.
9081 return instance;
9082}
9083
9084function getNextHydratableSibling(instance) {
9085 var node = instance.nextSibling;
9086 // Skip non-hydratable nodes.
9087 while (node && node.nodeType !== ELEMENT_NODE && node.nodeType !== TEXT_NODE && (!enableSuspenseServerRenderer || node.nodeType !== COMMENT_NODE || node.data !== SUSPENSE_START_DATA)) {
9088 node = node.nextSibling;
9089 }
9090 return node;
9091}
9092
9093function getFirstHydratableChild(parentInstance) {
9094 var next = parentInstance.firstChild;
9095 // Skip non-hydratable nodes.
9096 while (next && next.nodeType !== ELEMENT_NODE && next.nodeType !== TEXT_NODE && (!enableSuspenseServerRenderer || next.nodeType !== COMMENT_NODE || next.data !== SUSPENSE_START_DATA)) {
9097 next = next.nextSibling;
9098 }
9099 return next;
9100}
9101
9102function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
9103 precacheFiberNode(internalInstanceHandle, instance);
9104 // TODO: Possibly defer this until the commit phase where all the events
9105 // get attached.
9106 updateFiberProps(instance, props);
9107 var parentNamespace = void 0;
9108 {
9109 var hostContextDev = hostContext;
9110 parentNamespace = hostContextDev.namespace;
9111 }
9112 return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);
9113}
9114
9115function hydrateTextInstance(textInstance, text, internalInstanceHandle) {
9116 precacheFiberNode(internalInstanceHandle, textInstance);
9117 return diffHydratedText(textInstance, text);
9118}
9119
9120function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
9121 var node = suspenseInstance.nextSibling;
9122 // Skip past all nodes within this suspense boundary.
9123 // There might be nested nodes so we need to keep track of how
9124 // deep we are and only break out when we're back on top.
9125 var depth = 0;
9126 while (node) {
9127 if (node.nodeType === COMMENT_NODE) {
9128 var data = node.data;
9129 if (data === SUSPENSE_END_DATA) {
9130 if (depth === 0) {
9131 return getNextHydratableSibling(node);
9132 } else {
9133 depth--;
9134 }
9135 } else if (data === SUSPENSE_START_DATA) {
9136 depth++;
9137 }
9138 }
9139 node = node.nextSibling;
9140 }
9141 // TODO: Warn, we didn't find the end comment boundary.
9142 return null;
9143}
9144
9145function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {
9146 {
9147 warnForUnmatchedText(textInstance, text);
9148 }
9149}
9150
9151function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {
9152 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9153 warnForUnmatchedText(textInstance, text);
9154 }
9155}
9156
9157function didNotHydrateContainerInstance(parentContainer, instance) {
9158 {
9159 if (instance.nodeType === ELEMENT_NODE) {
9160 warnForDeletedHydratableElement(parentContainer, instance);
9161 } else if (instance.nodeType === COMMENT_NODE) {
9162 // TODO: warnForDeletedHydratableSuspenseBoundary
9163 } else {
9164 warnForDeletedHydratableText(parentContainer, instance);
9165 }
9166 }
9167}
9168
9169function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {
9170 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9171 if (instance.nodeType === ELEMENT_NODE) {
9172 warnForDeletedHydratableElement(parentInstance, instance);
9173 } else if (instance.nodeType === COMMENT_NODE) {
9174 // TODO: warnForDeletedHydratableSuspenseBoundary
9175 } else {
9176 warnForDeletedHydratableText(parentInstance, instance);
9177 }
9178 }
9179}
9180
9181function didNotFindHydratableContainerInstance(parentContainer, type, props) {
9182 {
9183 warnForInsertedHydratedElement(parentContainer, type, props);
9184 }
9185}
9186
9187function didNotFindHydratableContainerTextInstance(parentContainer, text) {
9188 {
9189 warnForInsertedHydratedText(parentContainer, text);
9190 }
9191}
9192
9193
9194
9195function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {
9196 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9197 warnForInsertedHydratedElement(parentInstance, type, props);
9198 }
9199}
9200
9201function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {
9202 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9203 warnForInsertedHydratedText(parentInstance, text);
9204 }
9205}
9206
9207function didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance) {
9208 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9209 // TODO: warnForInsertedHydratedSuspense(parentInstance);
9210 }
9211}
9212
9213// This is just to get the setup running.
9214// TODO: real implementation.
9215// console.log('Hello from Fire host config.');
9216
9217// Prefix measurements so that it's possible to filter them.
9218// Longer prefixes are hard to read in DevTools.
9219var reactEmoji = '\u269B';
9220var warningEmoji = '\u26D4';
9221var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function';
9222
9223// Keep track of current fiber so that we know the path to unwind on pause.
9224// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
9225var currentFiber = null;
9226// If we're in the middle of user code, which fiber and method is it?
9227// Reusing `currentFiber` would be confusing for this because user code fiber
9228// can change during commit phase too, but we don't need to unwind it (since
9229// lifecycles in the commit phase don't resemble a tree).
9230var currentPhase = null;
9231var currentPhaseFiber = null;
9232// Did lifecycle hook schedule an update? This is often a performance problem,
9233// so we will keep track of it, and include it in the report.
9234// Track commits caused by cascading updates.
9235var isCommitting = false;
9236var hasScheduledUpdateInCurrentCommit = false;
9237var hasScheduledUpdateInCurrentPhase = false;
9238var commitCountInCurrentWorkLoop = 0;
9239var effectCountInCurrentCommit = 0;
9240var isWaitingForCallback = false;
9241// During commits, we only show a measurement once per method name
9242// to avoid stretch the commit phase with measurement overhead.
9243var labelsInCurrentCommit = new Set();
9244
9245var formatMarkName = function (markName) {
9246 return reactEmoji + ' ' + markName;
9247};
9248
9249var formatLabel = function (label, warning) {
9250 var prefix = warning ? warningEmoji + ' ' : reactEmoji + ' ';
9251 var suffix = warning ? ' Warning: ' + warning : '';
9252 return '' + prefix + label + suffix;
9253};
9254
9255var beginMark = function (markName) {
9256 performance.mark(formatMarkName(markName));
9257};
9258
9259var clearMark = function (markName) {
9260 performance.clearMarks(formatMarkName(markName));
9261};
9262
9263var endMark = function (label, markName, warning) {
9264 var formattedMarkName = formatMarkName(markName);
9265 var formattedLabel = formatLabel(label, warning);
9266 try {
9267 performance.measure(formattedLabel, formattedMarkName);
9268 } catch (err) {}
9269 // If previous mark was missing for some reason, this will throw.
9270 // This could only happen if React crashed in an unexpected place earlier.
9271 // Don't pile on with more errors.
9272
9273 // Clear marks immediately to avoid growing buffer.
9274 performance.clearMarks(formattedMarkName);
9275 performance.clearMeasures(formattedLabel);
9276};
9277
9278var getFiberMarkName = function (label, debugID) {
9279 return label + ' (#' + debugID + ')';
9280};
9281
9282var getFiberLabel = function (componentName, isMounted, phase) {
9283 if (phase === null) {
9284 // These are composite component total time measurements.
9285 return componentName + ' [' + (isMounted ? 'update' : 'mount') + ']';
9286 } else {
9287 // Composite component methods.
9288 return componentName + '.' + phase;
9289 }
9290};
9291
9292var beginFiberMark = function (fiber, phase) {
9293 var componentName = getComponentName(fiber.type) || 'Unknown';
9294 var debugID = fiber._debugID;
9295 var isMounted = fiber.alternate !== null;
9296 var label = getFiberLabel(componentName, isMounted, phase);
9297
9298 if (isCommitting && labelsInCurrentCommit.has(label)) {
9299 // During the commit phase, we don't show duplicate labels because
9300 // there is a fixed overhead for every measurement, and we don't
9301 // want to stretch the commit phase beyond necessary.
9302 return false;
9303 }
9304 labelsInCurrentCommit.add(label);
9305
9306 var markName = getFiberMarkName(label, debugID);
9307 beginMark(markName);
9308 return true;
9309};
9310
9311var clearFiberMark = function (fiber, phase) {
9312 var componentName = getComponentName(fiber.type) || 'Unknown';
9313 var debugID = fiber._debugID;
9314 var isMounted = fiber.alternate !== null;
9315 var label = getFiberLabel(componentName, isMounted, phase);
9316 var markName = getFiberMarkName(label, debugID);
9317 clearMark(markName);
9318};
9319
9320var endFiberMark = function (fiber, phase, warning) {
9321 var componentName = getComponentName(fiber.type) || 'Unknown';
9322 var debugID = fiber._debugID;
9323 var isMounted = fiber.alternate !== null;
9324 var label = getFiberLabel(componentName, isMounted, phase);
9325 var markName = getFiberMarkName(label, debugID);
9326 endMark(label, markName, warning);
9327};
9328
9329var shouldIgnoreFiber = function (fiber) {
9330 // Host components should be skipped in the timeline.
9331 // We could check typeof fiber.type, but does this work with RN?
9332 switch (fiber.tag) {
9333 case HostRoot:
9334 case HostComponent:
9335 case HostText:
9336 case HostPortal:
9337 case Fragment:
9338 case ContextProvider:
9339 case ContextConsumer:
9340 case Mode:
9341 return true;
9342 default:
9343 return false;
9344 }
9345};
9346
9347var clearPendingPhaseMeasurement = function () {
9348 if (currentPhase !== null && currentPhaseFiber !== null) {
9349 clearFiberMark(currentPhaseFiber, currentPhase);
9350 }
9351 currentPhaseFiber = null;
9352 currentPhase = null;
9353 hasScheduledUpdateInCurrentPhase = false;
9354};
9355
9356var pauseTimers = function () {
9357 // Stops all currently active measurements so that they can be resumed
9358 // if we continue in a later deferred loop from the same unit of work.
9359 var fiber = currentFiber;
9360 while (fiber) {
9361 if (fiber._debugIsCurrentlyTiming) {
9362 endFiberMark(fiber, null, null);
9363 }
9364 fiber = fiber.return;
9365 }
9366};
9367
9368var resumeTimersRecursively = function (fiber) {
9369 if (fiber.return !== null) {
9370 resumeTimersRecursively(fiber.return);
9371 }
9372 if (fiber._debugIsCurrentlyTiming) {
9373 beginFiberMark(fiber, null);
9374 }
9375};
9376
9377var resumeTimers = function () {
9378 // Resumes all measurements that were active during the last deferred loop.
9379 if (currentFiber !== null) {
9380 resumeTimersRecursively(currentFiber);
9381 }
9382};
9383
9384function recordEffect() {
9385 if (enableUserTimingAPI) {
9386 effectCountInCurrentCommit++;
9387 }
9388}
9389
9390function recordScheduleUpdate() {
9391 if (enableUserTimingAPI) {
9392 if (isCommitting) {
9393 hasScheduledUpdateInCurrentCommit = true;
9394 }
9395 if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
9396 hasScheduledUpdateInCurrentPhase = true;
9397 }
9398 }
9399}
9400
9401function startRequestCallbackTimer() {
9402 if (enableUserTimingAPI) {
9403 if (supportsUserTiming && !isWaitingForCallback) {
9404 isWaitingForCallback = true;
9405 beginMark('(Waiting for async callback...)');
9406 }
9407 }
9408}
9409
9410function stopRequestCallbackTimer(didExpire, expirationTime) {
9411 if (enableUserTimingAPI) {
9412 if (supportsUserTiming) {
9413 isWaitingForCallback = false;
9414 var warning = didExpire ? 'React was blocked by main thread' : null;
9415 endMark('(Waiting for async callback... will force flush in ' + expirationTime + ' ms)', '(Waiting for async callback...)', warning);
9416 }
9417 }
9418}
9419
9420function startWorkTimer(fiber) {
9421 if (enableUserTimingAPI) {
9422 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9423 return;
9424 }
9425 // If we pause, this is the fiber to unwind from.
9426 currentFiber = fiber;
9427 if (!beginFiberMark(fiber, null)) {
9428 return;
9429 }
9430 fiber._debugIsCurrentlyTiming = true;
9431 }
9432}
9433
9434function cancelWorkTimer(fiber) {
9435 if (enableUserTimingAPI) {
9436 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9437 return;
9438 }
9439 // Remember we shouldn't complete measurement for this fiber.
9440 // Otherwise flamechart will be deep even for small updates.
9441 fiber._debugIsCurrentlyTiming = false;
9442 clearFiberMark(fiber, null);
9443 }
9444}
9445
9446function stopWorkTimer(fiber) {
9447 if (enableUserTimingAPI) {
9448 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9449 return;
9450 }
9451 // If we pause, its parent is the fiber to unwind from.
9452 currentFiber = fiber.return;
9453 if (!fiber._debugIsCurrentlyTiming) {
9454 return;
9455 }
9456 fiber._debugIsCurrentlyTiming = false;
9457 endFiberMark(fiber, null, null);
9458 }
9459}
9460
9461function stopFailedWorkTimer(fiber) {
9462 if (enableUserTimingAPI) {
9463 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9464 return;
9465 }
9466 // If we pause, its parent is the fiber to unwind from.
9467 currentFiber = fiber.return;
9468 if (!fiber._debugIsCurrentlyTiming) {
9469 return;
9470 }
9471 fiber._debugIsCurrentlyTiming = false;
9472 var warning = fiber.tag === SuspenseComponent || fiber.tag === DehydratedSuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
9473 endFiberMark(fiber, null, warning);
9474 }
9475}
9476
9477function startPhaseTimer(fiber, phase) {
9478 if (enableUserTimingAPI) {
9479 if (!supportsUserTiming) {
9480 return;
9481 }
9482 clearPendingPhaseMeasurement();
9483 if (!beginFiberMark(fiber, phase)) {
9484 return;
9485 }
9486 currentPhaseFiber = fiber;
9487 currentPhase = phase;
9488 }
9489}
9490
9491function stopPhaseTimer() {
9492 if (enableUserTimingAPI) {
9493 if (!supportsUserTiming) {
9494 return;
9495 }
9496 if (currentPhase !== null && currentPhaseFiber !== null) {
9497 var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
9498 endFiberMark(currentPhaseFiber, currentPhase, warning);
9499 }
9500 currentPhase = null;
9501 currentPhaseFiber = null;
9502 }
9503}
9504
9505function startWorkLoopTimer(nextUnitOfWork) {
9506 if (enableUserTimingAPI) {
9507 currentFiber = nextUnitOfWork;
9508 if (!supportsUserTiming) {
9509 return;
9510 }
9511 commitCountInCurrentWorkLoop = 0;
9512 // This is top level call.
9513 // Any other measurements are performed within.
9514 beginMark('(React Tree Reconciliation)');
9515 // Resume any measurements that were in progress during the last loop.
9516 resumeTimers();
9517 }
9518}
9519
9520function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
9521 if (enableUserTimingAPI) {
9522 if (!supportsUserTiming) {
9523 return;
9524 }
9525 var warning = null;
9526 if (interruptedBy !== null) {
9527 if (interruptedBy.tag === HostRoot) {
9528 warning = 'A top-level update interrupted the previous render';
9529 } else {
9530 var componentName = getComponentName(interruptedBy.type) || 'Unknown';
9531 warning = 'An update to ' + componentName + ' interrupted the previous render';
9532 }
9533 } else if (commitCountInCurrentWorkLoop > 1) {
9534 warning = 'There were cascading updates';
9535 }
9536 commitCountInCurrentWorkLoop = 0;
9537 var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)';
9538 // Pause any measurements until the next loop.
9539 pauseTimers();
9540 endMark(label, '(React Tree Reconciliation)', warning);
9541 }
9542}
9543
9544function startCommitTimer() {
9545 if (enableUserTimingAPI) {
9546 if (!supportsUserTiming) {
9547 return;
9548 }
9549 isCommitting = true;
9550 hasScheduledUpdateInCurrentCommit = false;
9551 labelsInCurrentCommit.clear();
9552 beginMark('(Committing Changes)');
9553 }
9554}
9555
9556function stopCommitTimer() {
9557 if (enableUserTimingAPI) {
9558 if (!supportsUserTiming) {
9559 return;
9560 }
9561
9562 var warning = null;
9563 if (hasScheduledUpdateInCurrentCommit) {
9564 warning = 'Lifecycle hook scheduled a cascading update';
9565 } else if (commitCountInCurrentWorkLoop > 0) {
9566 warning = 'Caused by a cascading update in earlier commit';
9567 }
9568 hasScheduledUpdateInCurrentCommit = false;
9569 commitCountInCurrentWorkLoop++;
9570 isCommitting = false;
9571 labelsInCurrentCommit.clear();
9572
9573 endMark('(Committing Changes)', '(Committing Changes)', warning);
9574 }
9575}
9576
9577function startCommitSnapshotEffectsTimer() {
9578 if (enableUserTimingAPI) {
9579 if (!supportsUserTiming) {
9580 return;
9581 }
9582 effectCountInCurrentCommit = 0;
9583 beginMark('(Committing Snapshot Effects)');
9584 }
9585}
9586
9587function stopCommitSnapshotEffectsTimer() {
9588 if (enableUserTimingAPI) {
9589 if (!supportsUserTiming) {
9590 return;
9591 }
9592 var count = effectCountInCurrentCommit;
9593 effectCountInCurrentCommit = 0;
9594 endMark('(Committing Snapshot Effects: ' + count + ' Total)', '(Committing Snapshot Effects)', null);
9595 }
9596}
9597
9598function startCommitHostEffectsTimer() {
9599 if (enableUserTimingAPI) {
9600 if (!supportsUserTiming) {
9601 return;
9602 }
9603 effectCountInCurrentCommit = 0;
9604 beginMark('(Committing Host Effects)');
9605 }
9606}
9607
9608function stopCommitHostEffectsTimer() {
9609 if (enableUserTimingAPI) {
9610 if (!supportsUserTiming) {
9611 return;
9612 }
9613 var count = effectCountInCurrentCommit;
9614 effectCountInCurrentCommit = 0;
9615 endMark('(Committing Host Effects: ' + count + ' Total)', '(Committing Host Effects)', null);
9616 }
9617}
9618
9619function startCommitLifeCyclesTimer() {
9620 if (enableUserTimingAPI) {
9621 if (!supportsUserTiming) {
9622 return;
9623 }
9624 effectCountInCurrentCommit = 0;
9625 beginMark('(Calling Lifecycle Methods)');
9626 }
9627}
9628
9629function stopCommitLifeCyclesTimer() {
9630 if (enableUserTimingAPI) {
9631 if (!supportsUserTiming) {
9632 return;
9633 }
9634 var count = effectCountInCurrentCommit;
9635 effectCountInCurrentCommit = 0;
9636 endMark('(Calling Lifecycle Methods: ' + count + ' Total)', '(Calling Lifecycle Methods)', null);
9637 }
9638}
9639
9640var valueStack = [];
9641
9642var fiberStack = void 0;
9643
9644{
9645 fiberStack = [];
9646}
9647
9648var index = -1;
9649
9650function createCursor(defaultValue) {
9651 return {
9652 current: defaultValue
9653 };
9654}
9655
9656function pop(cursor, fiber) {
9657 if (index < 0) {
9658 {
9659 warningWithoutStack$1(false, 'Unexpected pop.');
9660 }
9661 return;
9662 }
9663
9664 {
9665 if (fiber !== fiberStack[index]) {
9666 warningWithoutStack$1(false, 'Unexpected Fiber popped.');
9667 }
9668 }
9669
9670 cursor.current = valueStack[index];
9671
9672 valueStack[index] = null;
9673
9674 {
9675 fiberStack[index] = null;
9676 }
9677
9678 index--;
9679}
9680
9681function push(cursor, value, fiber) {
9682 index++;
9683
9684 valueStack[index] = cursor.current;
9685
9686 {
9687 fiberStack[index] = fiber;
9688 }
9689
9690 cursor.current = value;
9691}
9692
9693function checkThatStackIsEmpty() {
9694 {
9695 if (index !== -1) {
9696 warningWithoutStack$1(false, 'Expected an empty stack. Something was not reset properly.');
9697 }
9698 }
9699}
9700
9701function resetStackAfterFatalErrorInDev() {
9702 {
9703 index = -1;
9704 valueStack.length = 0;
9705 fiberStack.length = 0;
9706 }
9707}
9708
9709var warnedAboutMissingGetChildContext = void 0;
9710
9711{
9712 warnedAboutMissingGetChildContext = {};
9713}
9714
9715var emptyContextObject = {};
9716{
9717 Object.freeze(emptyContextObject);
9718}
9719
9720// A cursor to the current merged context object on the stack.
9721var contextStackCursor = createCursor(emptyContextObject);
9722// A cursor to a boolean indicating whether the context has changed.
9723var didPerformWorkStackCursor = createCursor(false);
9724// Keep track of the previous context object that was on the stack.
9725// We use this to get access to the parent context after we have already
9726// pushed the next context provider, and now need to merge their contexts.
9727var previousContext = emptyContextObject;
9728
9729function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
9730 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
9731 // If the fiber is a context provider itself, when we read its context
9732 // we may have already pushed its own child context on the stack. A context
9733 // provider should not "see" its own child context. Therefore we read the
9734 // previous (parent) context instead for a context provider.
9735 return previousContext;
9736 }
9737 return contextStackCursor.current;
9738}
9739
9740function cacheContext(workInProgress, unmaskedContext, maskedContext) {
9741 var instance = workInProgress.stateNode;
9742 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
9743 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
9744}
9745
9746function getMaskedContext(workInProgress, unmaskedContext) {
9747 var type = workInProgress.type;
9748 var contextTypes = type.contextTypes;
9749 if (!contextTypes) {
9750 return emptyContextObject;
9751 }
9752
9753 // Avoid recreating masked context unless unmasked context has changed.
9754 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
9755 // This may trigger infinite loops if componentWillReceiveProps calls setState.
9756 var instance = workInProgress.stateNode;
9757 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
9758 return instance.__reactInternalMemoizedMaskedChildContext;
9759 }
9760
9761 var context = {};
9762 for (var key in contextTypes) {
9763 context[key] = unmaskedContext[key];
9764 }
9765
9766 {
9767 var name = getComponentName(type) || 'Unknown';
9768 checkPropTypes_1(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
9769 }
9770
9771 // Cache unmasked context so we can avoid recreating masked context unless necessary.
9772 // Context is created before the class component is instantiated so check for instance.
9773 if (instance) {
9774 cacheContext(workInProgress, unmaskedContext, context);
9775 }
9776
9777 return context;
9778}
9779
9780function hasContextChanged() {
9781 return didPerformWorkStackCursor.current;
9782}
9783
9784function isContextProvider(type) {
9785 var childContextTypes = type.childContextTypes;
9786 return childContextTypes !== null && childContextTypes !== undefined;
9787}
9788
9789function popContext(fiber) {
9790 pop(didPerformWorkStackCursor, fiber);
9791 pop(contextStackCursor, fiber);
9792}
9793
9794function popTopLevelContextObject(fiber) {
9795 pop(didPerformWorkStackCursor, fiber);
9796 pop(contextStackCursor, fiber);
9797}
9798
9799function pushTopLevelContextObject(fiber, context, didChange) {
9800 !(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;
9801
9802 push(contextStackCursor, context, fiber);
9803 push(didPerformWorkStackCursor, didChange, fiber);
9804}
9805
9806function processChildContext(fiber, type, parentContext) {
9807 var instance = fiber.stateNode;
9808 var childContextTypes = type.childContextTypes;
9809
9810 // TODO (bvaughn) Replace this behavior with an invariant() in the future.
9811 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
9812 if (typeof instance.getChildContext !== 'function') {
9813 {
9814 var componentName = getComponentName(type) || 'Unknown';
9815
9816 if (!warnedAboutMissingGetChildContext[componentName]) {
9817 warnedAboutMissingGetChildContext[componentName] = true;
9818 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);
9819 }
9820 }
9821 return parentContext;
9822 }
9823
9824 var childContext = void 0;
9825 {
9826 setCurrentPhase('getChildContext');
9827 }
9828 startPhaseTimer(fiber, 'getChildContext');
9829 childContext = instance.getChildContext();
9830 stopPhaseTimer();
9831 {
9832 setCurrentPhase(null);
9833 }
9834 for (var contextKey in childContext) {
9835 !(contextKey in childContextTypes) ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName(type) || 'Unknown', contextKey) : void 0;
9836 }
9837 {
9838 var name = getComponentName(type) || 'Unknown';
9839 checkPropTypes_1(childContextTypes, childContext, 'child context', name,
9840 // In practice, there is one case in which we won't get a stack. It's when
9841 // somebody calls unstable_renderSubtreeIntoContainer() and we process
9842 // context from the parent component instance. The stack will be missing
9843 // because it's outside of the reconciliation, and so the pointer has not
9844 // been set. This is rare and doesn't matter. We'll also remove that API.
9845 getCurrentFiberStackInDev);
9846 }
9847
9848 return _assign({}, parentContext, childContext);
9849}
9850
9851function pushContextProvider(workInProgress) {
9852 var instance = workInProgress.stateNode;
9853 // We push the context as early as possible to ensure stack integrity.
9854 // If the instance does not exist yet, we will push null at first,
9855 // and replace it on the stack later when invalidating the context.
9856 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject;
9857
9858 // Remember the parent context so we can merge with it later.
9859 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
9860 previousContext = contextStackCursor.current;
9861 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
9862 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
9863
9864 return true;
9865}
9866
9867function invalidateContextProvider(workInProgress, type, didChange) {
9868 var instance = workInProgress.stateNode;
9869 !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;
9870
9871 if (didChange) {
9872 // Merge parent and own context.
9873 // Skip this if we're not updating due to sCU.
9874 // This avoids unnecessarily recomputing memoized values.
9875 var mergedContext = processChildContext(workInProgress, type, previousContext);
9876 instance.__reactInternalMemoizedMergedChildContext = mergedContext;
9877
9878 // Replace the old (or empty) context with the new one.
9879 // It is important to unwind the context in the reverse order.
9880 pop(didPerformWorkStackCursor, workInProgress);
9881 pop(contextStackCursor, workInProgress);
9882 // Now push the new context and mark that it has changed.
9883 push(contextStackCursor, mergedContext, workInProgress);
9884 push(didPerformWorkStackCursor, didChange, workInProgress);
9885 } else {
9886 pop(didPerformWorkStackCursor, workInProgress);
9887 push(didPerformWorkStackCursor, didChange, workInProgress);
9888 }
9889}
9890
9891function findCurrentUnmaskedContext(fiber) {
9892 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
9893 // makes sense elsewhere
9894 !(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;
9895
9896 var node = fiber;
9897 do {
9898 switch (node.tag) {
9899 case HostRoot:
9900 return node.stateNode.context;
9901 case ClassComponent:
9902 {
9903 var Component = node.type;
9904 if (isContextProvider(Component)) {
9905 return node.stateNode.__reactInternalMemoizedMergedChildContext;
9906 }
9907 break;
9908 }
9909 }
9910 node = node.return;
9911 } while (node !== null);
9912 invariant(false, 'Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.');
9913}
9914
9915var onCommitFiberRoot = null;
9916var onCommitFiberUnmount = null;
9917var hasLoggedError = false;
9918
9919function catchErrors(fn) {
9920 return function (arg) {
9921 try {
9922 return fn(arg);
9923 } catch (err) {
9924 if (true && !hasLoggedError) {
9925 hasLoggedError = true;
9926 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
9927 }
9928 }
9929 };
9930}
9931
9932var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
9933
9934function injectInternals(internals) {
9935 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
9936 // No DevTools
9937 return false;
9938 }
9939 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
9940 if (hook.isDisabled) {
9941 // This isn't a real property on the hook, but it can be set to opt out
9942 // of DevTools integration and associated warnings and logs.
9943 // https://github.com/facebook/react/issues/3877
9944 return true;
9945 }
9946 if (!hook.supportsFiber) {
9947 {
9948 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');
9949 }
9950 // DevTools exists, even though it doesn't support Fiber.
9951 return true;
9952 }
9953 try {
9954 var rendererID = hook.inject(internals);
9955 // We have successfully injected, so now it is safe to set up hooks.
9956 onCommitFiberRoot = catchErrors(function (root) {
9957 return hook.onCommitFiberRoot(rendererID, root);
9958 });
9959 onCommitFiberUnmount = catchErrors(function (fiber) {
9960 return hook.onCommitFiberUnmount(rendererID, fiber);
9961 });
9962 } catch (err) {
9963 // Catch all errors because it is unsafe to throw during initialization.
9964 {
9965 warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
9966 }
9967 }
9968 // DevTools exists
9969 return true;
9970}
9971
9972function onCommitRoot(root) {
9973 if (typeof onCommitFiberRoot === 'function') {
9974 onCommitFiberRoot(root);
9975 }
9976}
9977
9978function onCommitUnmount(fiber) {
9979 if (typeof onCommitFiberUnmount === 'function') {
9980 onCommitFiberUnmount(fiber);
9981 }
9982}
9983
9984// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
9985// Math.pow(2, 30) - 1
9986// 0b111111111111111111111111111111
9987var maxSigned31BitInt = 1073741823;
9988
9989var NoWork = 0;
9990var Never = 1;
9991var Sync = maxSigned31BitInt;
9992
9993var UNIT_SIZE = 10;
9994var MAGIC_NUMBER_OFFSET = maxSigned31BitInt - 1;
9995
9996// 1 unit of expiration time represents 10ms.
9997function msToExpirationTime(ms) {
9998 // Always add an offset so that we don't clash with the magic number for NoWork.
9999 return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
10000}
10001
10002function expirationTimeToMs(expirationTime) {
10003 return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
10004}
10005
10006function ceiling(num, precision) {
10007 return ((num / precision | 0) + 1) * precision;
10008}
10009
10010function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
10011 return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
10012}
10013
10014var LOW_PRIORITY_EXPIRATION = 5000;
10015var LOW_PRIORITY_BATCH_SIZE = 250;
10016
10017function computeAsyncExpiration(currentTime) {
10018 return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
10019}
10020
10021// We intentionally set a higher expiration time for interactive updates in
10022// dev than in production.
10023//
10024// If the main thread is being blocked so long that you hit the expiration,
10025// it's a problem that could be solved with better scheduling.
10026//
10027// People will be more likely to notice this and fix it with the long
10028// expiration time in development.
10029//
10030// In production we opt for better UX at the risk of masking scheduling
10031// problems, by expiring fast.
10032var HIGH_PRIORITY_EXPIRATION = 500;
10033var HIGH_PRIORITY_BATCH_SIZE = 100;
10034
10035function computeInteractiveExpiration(currentTime) {
10036 return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
10037}
10038
10039var NoContext = 0;
10040var ConcurrentMode = 1;
10041var StrictMode = 2;
10042var ProfileMode = 4;
10043
10044var hasBadMapPolyfill = void 0;
10045
10046{
10047 hasBadMapPolyfill = false;
10048 try {
10049 var nonExtensibleObject = Object.preventExtensions({});
10050 var testMap = new Map([[nonExtensibleObject, null]]);
10051 var testSet = new Set([nonExtensibleObject]);
10052 // This is necessary for Rollup to not consider these unused.
10053 // https://github.com/rollup/rollup/issues/1771
10054 // TODO: we can remove these if Rollup fixes the bug.
10055 testMap.set(0, 0);
10056 testSet.add(0);
10057 } catch (e) {
10058 // TODO: Consider warning about bad polyfills
10059 hasBadMapPolyfill = true;
10060 }
10061}
10062
10063// A Fiber is work on a Component that needs to be done or was done. There can
10064// be more than one per component.
10065
10066
10067var debugCounter = void 0;
10068
10069{
10070 debugCounter = 1;
10071}
10072
10073function FiberNode(tag, pendingProps, key, mode) {
10074 // Instance
10075 this.tag = tag;
10076 this.key = key;
10077 this.elementType = null;
10078 this.type = null;
10079 this.stateNode = null;
10080
10081 // Fiber
10082 this.return = null;
10083 this.child = null;
10084 this.sibling = null;
10085 this.index = 0;
10086
10087 this.ref = null;
10088
10089 this.pendingProps = pendingProps;
10090 this.memoizedProps = null;
10091 this.updateQueue = null;
10092 this.memoizedState = null;
10093 this.contextDependencies = null;
10094
10095 this.mode = mode;
10096
10097 // Effects
10098 this.effectTag = NoEffect;
10099 this.nextEffect = null;
10100
10101 this.firstEffect = null;
10102 this.lastEffect = null;
10103
10104 this.expirationTime = NoWork;
10105 this.childExpirationTime = NoWork;
10106
10107 this.alternate = null;
10108
10109 if (enableProfilerTimer) {
10110 // Note: The following is done to avoid a v8 performance cliff.
10111 //
10112 // Initializing the fields below to smis and later updating them with
10113 // double values will cause Fibers to end up having separate shapes.
10114 // This behavior/bug has something to do with Object.preventExtension().
10115 // Fortunately this only impacts DEV builds.
10116 // Unfortunately it makes React unusably slow for some applications.
10117 // To work around this, initialize the fields below with doubles.
10118 //
10119 // Learn more about this here:
10120 // https://github.com/facebook/react/issues/14365
10121 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
10122 this.actualDuration = Number.NaN;
10123 this.actualStartTime = Number.NaN;
10124 this.selfBaseDuration = Number.NaN;
10125 this.treeBaseDuration = Number.NaN;
10126
10127 // It's okay to replace the initial doubles with smis after initialization.
10128 // This won't trigger the performance cliff mentioned above,
10129 // and it simplifies other profiler code (including DevTools).
10130 this.actualDuration = 0;
10131 this.actualStartTime = -1;
10132 this.selfBaseDuration = 0;
10133 this.treeBaseDuration = 0;
10134 }
10135
10136 {
10137 this._debugID = debugCounter++;
10138 this._debugSource = null;
10139 this._debugOwner = null;
10140 this._debugIsCurrentlyTiming = false;
10141 this._debugHookTypes = null;
10142 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
10143 Object.preventExtensions(this);
10144 }
10145 }
10146}
10147
10148// This is a constructor function, rather than a POJO constructor, still
10149// please ensure we do the following:
10150// 1) Nobody should add any instance methods on this. Instance methods can be
10151// more difficult to predict when they get optimized and they are almost
10152// never inlined properly in static compilers.
10153// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
10154// always know when it is a fiber.
10155// 3) We might want to experiment with using numeric keys since they are easier
10156// to optimize in a non-JIT environment.
10157// 4) We can easily go from a constructor to a createFiber object literal if that
10158// is faster.
10159// 5) It should be easy to port this to a C struct and keep a C implementation
10160// compatible.
10161var createFiber = function (tag, pendingProps, key, mode) {
10162 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
10163 return new FiberNode(tag, pendingProps, key, mode);
10164};
10165
10166function shouldConstruct(Component) {
10167 var prototype = Component.prototype;
10168 return !!(prototype && prototype.isReactComponent);
10169}
10170
10171function isSimpleFunctionComponent(type) {
10172 return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
10173}
10174
10175function resolveLazyComponentTag(Component) {
10176 if (typeof Component === 'function') {
10177 return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
10178 } else if (Component !== undefined && Component !== null) {
10179 var $$typeof = Component.$$typeof;
10180 if ($$typeof === REACT_FORWARD_REF_TYPE) {
10181 return ForwardRef;
10182 }
10183 if ($$typeof === REACT_MEMO_TYPE) {
10184 return MemoComponent;
10185 }
10186 }
10187 return IndeterminateComponent;
10188}
10189
10190// This is used to create an alternate fiber to do work on.
10191function createWorkInProgress(current, pendingProps, expirationTime) {
10192 var workInProgress = current.alternate;
10193 if (workInProgress === null) {
10194 // We use a double buffering pooling technique because we know that we'll
10195 // only ever need at most two versions of a tree. We pool the "other" unused
10196 // node that we're free to reuse. This is lazily created to avoid allocating
10197 // extra objects for things that are never updated. It also allow us to
10198 // reclaim the extra memory if needed.
10199 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
10200 workInProgress.elementType = current.elementType;
10201 workInProgress.type = current.type;
10202 workInProgress.stateNode = current.stateNode;
10203
10204 {
10205 // DEV-only fields
10206 workInProgress._debugID = current._debugID;
10207 workInProgress._debugSource = current._debugSource;
10208 workInProgress._debugOwner = current._debugOwner;
10209 workInProgress._debugHookTypes = current._debugHookTypes;
10210 }
10211
10212 workInProgress.alternate = current;
10213 current.alternate = workInProgress;
10214 } else {
10215 workInProgress.pendingProps = pendingProps;
10216
10217 // We already have an alternate.
10218 // Reset the effect tag.
10219 workInProgress.effectTag = NoEffect;
10220
10221 // The effect list is no longer valid.
10222 workInProgress.nextEffect = null;
10223 workInProgress.firstEffect = null;
10224 workInProgress.lastEffect = null;
10225
10226 if (enableProfilerTimer) {
10227 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
10228 // This prevents time from endlessly accumulating in new commits.
10229 // This has the downside of resetting values for different priority renders,
10230 // But works for yielding (the common case) and should support resuming.
10231 workInProgress.actualDuration = 0;
10232 workInProgress.actualStartTime = -1;
10233 }
10234 }
10235
10236 workInProgress.childExpirationTime = current.childExpirationTime;
10237 workInProgress.expirationTime = current.expirationTime;
10238
10239 workInProgress.child = current.child;
10240 workInProgress.memoizedProps = current.memoizedProps;
10241 workInProgress.memoizedState = current.memoizedState;
10242 workInProgress.updateQueue = current.updateQueue;
10243 workInProgress.contextDependencies = current.contextDependencies;
10244
10245 // These will be overridden during the parent's reconciliation
10246 workInProgress.sibling = current.sibling;
10247 workInProgress.index = current.index;
10248 workInProgress.ref = current.ref;
10249
10250 if (enableProfilerTimer) {
10251 workInProgress.selfBaseDuration = current.selfBaseDuration;
10252 workInProgress.treeBaseDuration = current.treeBaseDuration;
10253 }
10254
10255 return workInProgress;
10256}
10257
10258function createHostRootFiber(isConcurrent) {
10259 var mode = isConcurrent ? ConcurrentMode | StrictMode : NoContext;
10260
10261 if (enableProfilerTimer && isDevToolsPresent) {
10262 // Always collect profile timings when DevTools are present.
10263 // This enables DevTools to start capturing timing at any point–
10264 // Without some nodes in the tree having empty base times.
10265 mode |= ProfileMode;
10266 }
10267
10268 return createFiber(HostRoot, null, null, mode);
10269}
10270
10271function createFiberFromTypeAndProps(type, // React$ElementType
10272key, pendingProps, owner, mode, expirationTime) {
10273 var fiber = void 0;
10274
10275 var fiberTag = IndeterminateComponent;
10276 // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
10277 var resolvedType = type;
10278 if (typeof type === 'function') {
10279 if (shouldConstruct(type)) {
10280 fiberTag = ClassComponent;
10281 }
10282 } else if (typeof type === 'string') {
10283 fiberTag = HostComponent;
10284 } else {
10285 getTag: switch (type) {
10286 case REACT_FRAGMENT_TYPE:
10287 return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
10288 case REACT_CONCURRENT_MODE_TYPE:
10289 return createFiberFromMode(pendingProps, mode | ConcurrentMode | StrictMode, expirationTime, key);
10290 case REACT_STRICT_MODE_TYPE:
10291 return createFiberFromMode(pendingProps, mode | StrictMode, expirationTime, key);
10292 case REACT_PROFILER_TYPE:
10293 return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
10294 case REACT_SUSPENSE_TYPE:
10295 return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
10296 default:
10297 {
10298 if (typeof type === 'object' && type !== null) {
10299 switch (type.$$typeof) {
10300 case REACT_PROVIDER_TYPE:
10301 fiberTag = ContextProvider;
10302 break getTag;
10303 case REACT_CONTEXT_TYPE:
10304 // This is a consumer
10305 fiberTag = ContextConsumer;
10306 break getTag;
10307 case REACT_FORWARD_REF_TYPE:
10308 fiberTag = ForwardRef;
10309 break getTag;
10310 case REACT_MEMO_TYPE:
10311 fiberTag = MemoComponent;
10312 break getTag;
10313 case REACT_LAZY_TYPE:
10314 fiberTag = LazyComponent;
10315 resolvedType = null;
10316 break getTag;
10317 }
10318 }
10319 var info = '';
10320 {
10321 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
10322 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.';
10323 }
10324 var ownerName = owner ? getComponentName(owner.type) : null;
10325 if (ownerName) {
10326 info += '\n\nCheck the render method of `' + ownerName + '`.';
10327 }
10328 }
10329 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);
10330 }
10331 }
10332 }
10333
10334 fiber = createFiber(fiberTag, pendingProps, key, mode);
10335 fiber.elementType = type;
10336 fiber.type = resolvedType;
10337 fiber.expirationTime = expirationTime;
10338
10339 return fiber;
10340}
10341
10342function createFiberFromElement(element, mode, expirationTime) {
10343 var owner = null;
10344 {
10345 owner = element._owner;
10346 }
10347 var type = element.type;
10348 var key = element.key;
10349 var pendingProps = element.props;
10350 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
10351 {
10352 fiber._debugSource = element._source;
10353 fiber._debugOwner = element._owner;
10354 }
10355 return fiber;
10356}
10357
10358function createFiberFromFragment(elements, mode, expirationTime, key) {
10359 var fiber = createFiber(Fragment, elements, key, mode);
10360 fiber.expirationTime = expirationTime;
10361 return fiber;
10362}
10363
10364function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
10365 {
10366 if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
10367 warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
10368 }
10369 }
10370
10371 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
10372 // TODO: The Profiler fiber shouldn't have a type. It has a tag.
10373 fiber.elementType = REACT_PROFILER_TYPE;
10374 fiber.type = REACT_PROFILER_TYPE;
10375 fiber.expirationTime = expirationTime;
10376
10377 return fiber;
10378}
10379
10380function createFiberFromMode(pendingProps, mode, expirationTime, key) {
10381 var fiber = createFiber(Mode, pendingProps, key, mode);
10382
10383 // TODO: The Mode fiber shouldn't have a type. It has a tag.
10384 var type = (mode & ConcurrentMode) === NoContext ? REACT_STRICT_MODE_TYPE : REACT_CONCURRENT_MODE_TYPE;
10385 fiber.elementType = type;
10386 fiber.type = type;
10387
10388 fiber.expirationTime = expirationTime;
10389 return fiber;
10390}
10391
10392function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
10393 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
10394
10395 // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
10396 var type = REACT_SUSPENSE_TYPE;
10397 fiber.elementType = type;
10398 fiber.type = type;
10399
10400 fiber.expirationTime = expirationTime;
10401 return fiber;
10402}
10403
10404function createFiberFromText(content, mode, expirationTime) {
10405 var fiber = createFiber(HostText, content, null, mode);
10406 fiber.expirationTime = expirationTime;
10407 return fiber;
10408}
10409
10410function createFiberFromHostInstanceForDeletion() {
10411 var fiber = createFiber(HostComponent, null, null, NoContext);
10412 // TODO: These should not need a type.
10413 fiber.elementType = 'DELETED';
10414 fiber.type = 'DELETED';
10415 return fiber;
10416}
10417
10418function createFiberFromPortal(portal, mode, expirationTime) {
10419 var pendingProps = portal.children !== null ? portal.children : [];
10420 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
10421 fiber.expirationTime = expirationTime;
10422 fiber.stateNode = {
10423 containerInfo: portal.containerInfo,
10424 pendingChildren: null, // Used by persistent updates
10425 implementation: portal.implementation
10426 };
10427 return fiber;
10428}
10429
10430// Used for stashing WIP properties to replay failed work in DEV.
10431function assignFiberPropertiesInDEV(target, source) {
10432 if (target === null) {
10433 // This Fiber's initial properties will always be overwritten.
10434 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
10435 target = createFiber(IndeterminateComponent, null, null, NoContext);
10436 }
10437
10438 // This is intentionally written as a list of all properties.
10439 // We tried to use Object.assign() instead but this is called in
10440 // the hottest path, and Object.assign() was too slow:
10441 // https://github.com/facebook/react/issues/12502
10442 // This code is DEV-only so size is not a concern.
10443
10444 target.tag = source.tag;
10445 target.key = source.key;
10446 target.elementType = source.elementType;
10447 target.type = source.type;
10448 target.stateNode = source.stateNode;
10449 target.return = source.return;
10450 target.child = source.child;
10451 target.sibling = source.sibling;
10452 target.index = source.index;
10453 target.ref = source.ref;
10454 target.pendingProps = source.pendingProps;
10455 target.memoizedProps = source.memoizedProps;
10456 target.updateQueue = source.updateQueue;
10457 target.memoizedState = source.memoizedState;
10458 target.contextDependencies = source.contextDependencies;
10459 target.mode = source.mode;
10460 target.effectTag = source.effectTag;
10461 target.nextEffect = source.nextEffect;
10462 target.firstEffect = source.firstEffect;
10463 target.lastEffect = source.lastEffect;
10464 target.expirationTime = source.expirationTime;
10465 target.childExpirationTime = source.childExpirationTime;
10466 target.alternate = source.alternate;
10467 if (enableProfilerTimer) {
10468 target.actualDuration = source.actualDuration;
10469 target.actualStartTime = source.actualStartTime;
10470 target.selfBaseDuration = source.selfBaseDuration;
10471 target.treeBaseDuration = source.treeBaseDuration;
10472 }
10473 target._debugID = source._debugID;
10474 target._debugSource = source._debugSource;
10475 target._debugOwner = source._debugOwner;
10476 target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
10477 target._debugHookTypes = source._debugHookTypes;
10478 return target;
10479}
10480
10481var ReactInternals$2 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
10482
10483var _ReactInternals$Sched$1 = ReactInternals$2.SchedulerTracing;
10484var __interactionsRef = _ReactInternals$Sched$1.__interactionsRef;
10485var __subscriberRef = _ReactInternals$Sched$1.__subscriberRef;
10486var unstable_clear = _ReactInternals$Sched$1.unstable_clear;
10487var unstable_getCurrent = _ReactInternals$Sched$1.unstable_getCurrent;
10488var unstable_getThreadID = _ReactInternals$Sched$1.unstable_getThreadID;
10489var unstable_subscribe = _ReactInternals$Sched$1.unstable_subscribe;
10490var unstable_trace = _ReactInternals$Sched$1.unstable_trace;
10491var unstable_unsubscribe = _ReactInternals$Sched$1.unstable_unsubscribe;
10492var unstable_wrap = _ReactInternals$Sched$1.unstable_wrap;
10493
10494// TODO: This should be lifted into the renderer.
10495
10496
10497// The following attributes are only used by interaction tracing builds.
10498// They enable interactions to be associated with their async work,
10499// And expose interaction metadata to the React DevTools Profiler plugin.
10500// Note that these attributes are only defined when the enableSchedulerTracing flag is enabled.
10501
10502
10503// Exported FiberRoot type includes all properties,
10504// To avoid requiring potentially error-prone :any casts throughout the project.
10505// Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true).
10506// The types are defined separately within this file to ensure they stay in sync.
10507// (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.)
10508
10509
10510function createFiberRoot(containerInfo, isConcurrent, hydrate) {
10511 // Cyclic construction. This cheats the type system right now because
10512 // stateNode is any.
10513 var uninitializedFiber = createHostRootFiber(isConcurrent);
10514
10515 var root = void 0;
10516 if (enableSchedulerTracing) {
10517 root = {
10518 current: uninitializedFiber,
10519 containerInfo: containerInfo,
10520 pendingChildren: null,
10521
10522 earliestPendingTime: NoWork,
10523 latestPendingTime: NoWork,
10524 earliestSuspendedTime: NoWork,
10525 latestSuspendedTime: NoWork,
10526 latestPingedTime: NoWork,
10527
10528 pingCache: null,
10529
10530 didError: false,
10531
10532 pendingCommitExpirationTime: NoWork,
10533 finishedWork: null,
10534 timeoutHandle: noTimeout,
10535 context: null,
10536 pendingContext: null,
10537 hydrate: hydrate,
10538 nextExpirationTimeToWorkOn: NoWork,
10539 expirationTime: NoWork,
10540 firstBatch: null,
10541 nextScheduledRoot: null,
10542
10543 interactionThreadID: unstable_getThreadID(),
10544 memoizedInteractions: new Set(),
10545 pendingInteractionMap: new Map()
10546 };
10547 } else {
10548 root = {
10549 current: uninitializedFiber,
10550 containerInfo: containerInfo,
10551 pendingChildren: null,
10552
10553 pingCache: null,
10554
10555 earliestPendingTime: NoWork,
10556 latestPendingTime: NoWork,
10557 earliestSuspendedTime: NoWork,
10558 latestSuspendedTime: NoWork,
10559 latestPingedTime: NoWork,
10560
10561 didError: false,
10562
10563 pendingCommitExpirationTime: NoWork,
10564 finishedWork: null,
10565 timeoutHandle: noTimeout,
10566 context: null,
10567 pendingContext: null,
10568 hydrate: hydrate,
10569 nextExpirationTimeToWorkOn: NoWork,
10570 expirationTime: NoWork,
10571 firstBatch: null,
10572 nextScheduledRoot: null
10573 };
10574 }
10575
10576 uninitializedFiber.stateNode = root;
10577
10578 // The reason for the way the Flow types are structured in this file,
10579 // Is to avoid needing :any casts everywhere interaction tracing fields are used.
10580 // Unfortunately that requires an :any cast for non-interaction tracing capable builds.
10581 // $FlowFixMe Remove this :any cast and replace it with something better.
10582 return root;
10583}
10584
10585/**
10586 * Forked from fbjs/warning:
10587 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
10588 *
10589 * Only change is we use console.warn instead of console.error,
10590 * and do nothing when 'console' is not supported.
10591 * This really simplifies the code.
10592 * ---
10593 * Similar to invariant but only logs a warning if the condition is not met.
10594 * This can be used to log issues in development environments in critical
10595 * paths. Removing the logging code for production environments will keep the
10596 * same logic and follow the same code paths.
10597 */
10598
10599var lowPriorityWarning = function () {};
10600
10601{
10602 var printWarning$1 = function (format) {
10603 for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
10604 args[_key - 1] = arguments[_key];
10605 }
10606
10607 var argIndex = 0;
10608 var message = 'Warning: ' + format.replace(/%s/g, function () {
10609 return args[argIndex++];
10610 });
10611 if (typeof console !== 'undefined') {
10612 console.warn(message);
10613 }
10614 try {
10615 // --- Welcome to debugging React ---
10616 // This error was thrown as a convenience so that you can use this stack
10617 // to find the callsite that caused this warning to fire.
10618 throw new Error(message);
10619 } catch (x) {}
10620 };
10621
10622 lowPriorityWarning = function (condition, format) {
10623 if (format === undefined) {
10624 throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
10625 }
10626 if (!condition) {
10627 for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
10628 args[_key2 - 2] = arguments[_key2];
10629 }
10630
10631 printWarning$1.apply(undefined, [format].concat(args));
10632 }
10633 };
10634}
10635
10636var lowPriorityWarning$1 = lowPriorityWarning;
10637
10638var ReactStrictModeWarnings = {
10639 discardPendingWarnings: function () {},
10640 flushPendingDeprecationWarnings: function () {},
10641 flushPendingUnsafeLifecycleWarnings: function () {},
10642 recordDeprecationWarnings: function (fiber, instance) {},
10643 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
10644 recordLegacyContextWarning: function (fiber, instance) {},
10645 flushLegacyContextWarning: function () {}
10646};
10647
10648{
10649 var LIFECYCLE_SUGGESTIONS = {
10650 UNSAFE_componentWillMount: 'componentDidMount',
10651 UNSAFE_componentWillReceiveProps: 'static getDerivedStateFromProps',
10652 UNSAFE_componentWillUpdate: 'componentDidUpdate'
10653 };
10654
10655 var pendingComponentWillMountWarnings = [];
10656 var pendingComponentWillReceivePropsWarnings = [];
10657 var pendingComponentWillUpdateWarnings = [];
10658 var pendingUnsafeLifecycleWarnings = new Map();
10659 var pendingLegacyContextWarning = new Map();
10660
10661 // Tracks components we have already warned about.
10662 var didWarnAboutDeprecatedLifecycles = new Set();
10663 var didWarnAboutUnsafeLifecycles = new Set();
10664 var didWarnAboutLegacyContext = new Set();
10665
10666 var setToSortedString = function (set) {
10667 var array = [];
10668 set.forEach(function (value) {
10669 array.push(value);
10670 });
10671 return array.sort().join(', ');
10672 };
10673
10674 ReactStrictModeWarnings.discardPendingWarnings = function () {
10675 pendingComponentWillMountWarnings = [];
10676 pendingComponentWillReceivePropsWarnings = [];
10677 pendingComponentWillUpdateWarnings = [];
10678 pendingUnsafeLifecycleWarnings = new Map();
10679 pendingLegacyContextWarning = new Map();
10680 };
10681
10682 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
10683 pendingUnsafeLifecycleWarnings.forEach(function (lifecycleWarningsMap, strictRoot) {
10684 var lifecyclesWarningMessages = [];
10685
10686 Object.keys(lifecycleWarningsMap).forEach(function (lifecycle) {
10687 var lifecycleWarnings = lifecycleWarningsMap[lifecycle];
10688 if (lifecycleWarnings.length > 0) {
10689 var componentNames = new Set();
10690 lifecycleWarnings.forEach(function (fiber) {
10691 componentNames.add(getComponentName(fiber.type) || 'Component');
10692 didWarnAboutUnsafeLifecycles.add(fiber.type);
10693 });
10694
10695 var formatted = lifecycle.replace('UNSAFE_', '');
10696 var suggestion = LIFECYCLE_SUGGESTIONS[lifecycle];
10697 var sortedComponentNames = setToSortedString(componentNames);
10698
10699 lifecyclesWarningMessages.push(formatted + ': Please update the following components to use ' + (suggestion + ' instead: ' + sortedComponentNames));
10700 }
10701 });
10702
10703 if (lifecyclesWarningMessages.length > 0) {
10704 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
10705
10706 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'));
10707 }
10708 });
10709
10710 pendingUnsafeLifecycleWarnings = new Map();
10711 };
10712
10713 var findStrictRoot = function (fiber) {
10714 var maybeStrictRoot = null;
10715
10716 var node = fiber;
10717 while (node !== null) {
10718 if (node.mode & StrictMode) {
10719 maybeStrictRoot = node;
10720 }
10721 node = node.return;
10722 }
10723
10724 return maybeStrictRoot;
10725 };
10726
10727 ReactStrictModeWarnings.flushPendingDeprecationWarnings = function () {
10728 if (pendingComponentWillMountWarnings.length > 0) {
10729 var uniqueNames = new Set();
10730 pendingComponentWillMountWarnings.forEach(function (fiber) {
10731 uniqueNames.add(getComponentName(fiber.type) || 'Component');
10732 didWarnAboutDeprecatedLifecycles.add(fiber.type);
10733 });
10734
10735 var sortedNames = setToSortedString(uniqueNames);
10736
10737 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);
10738
10739 pendingComponentWillMountWarnings = [];
10740 }
10741
10742 if (pendingComponentWillReceivePropsWarnings.length > 0) {
10743 var _uniqueNames = new Set();
10744 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
10745 _uniqueNames.add(getComponentName(fiber.type) || 'Component');
10746 didWarnAboutDeprecatedLifecycles.add(fiber.type);
10747 });
10748
10749 var _sortedNames = setToSortedString(_uniqueNames);
10750
10751 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);
10752
10753 pendingComponentWillReceivePropsWarnings = [];
10754 }
10755
10756 if (pendingComponentWillUpdateWarnings.length > 0) {
10757 var _uniqueNames2 = new Set();
10758 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
10759 _uniqueNames2.add(getComponentName(fiber.type) || 'Component');
10760 didWarnAboutDeprecatedLifecycles.add(fiber.type);
10761 });
10762
10763 var _sortedNames2 = setToSortedString(_uniqueNames2);
10764
10765 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);
10766
10767 pendingComponentWillUpdateWarnings = [];
10768 }
10769 };
10770
10771 ReactStrictModeWarnings.recordDeprecationWarnings = function (fiber, instance) {
10772 // Dedup strategy: Warn once per component.
10773 if (didWarnAboutDeprecatedLifecycles.has(fiber.type)) {
10774 return;
10775 }
10776
10777 // Don't warn about react-lifecycles-compat polyfilled components.
10778 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
10779 pendingComponentWillMountWarnings.push(fiber);
10780 }
10781 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
10782 pendingComponentWillReceivePropsWarnings.push(fiber);
10783 }
10784 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
10785 pendingComponentWillUpdateWarnings.push(fiber);
10786 }
10787 };
10788
10789 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
10790 var strictRoot = findStrictRoot(fiber);
10791 if (strictRoot === null) {
10792 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.');
10793 return;
10794 }
10795
10796 // Dedup strategy: Warn once per component.
10797 // This is difficult to track any other way since component names
10798 // are often vague and are likely to collide between 3rd party libraries.
10799 // An expand property is probably okay to use here since it's DEV-only,
10800 // and will only be set in the event of serious warnings.
10801 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
10802 return;
10803 }
10804
10805 var warningsForRoot = void 0;
10806 if (!pendingUnsafeLifecycleWarnings.has(strictRoot)) {
10807 warningsForRoot = {
10808 UNSAFE_componentWillMount: [],
10809 UNSAFE_componentWillReceiveProps: [],
10810 UNSAFE_componentWillUpdate: []
10811 };
10812
10813 pendingUnsafeLifecycleWarnings.set(strictRoot, warningsForRoot);
10814 } else {
10815 warningsForRoot = pendingUnsafeLifecycleWarnings.get(strictRoot);
10816 }
10817
10818 var unsafeLifecycles = [];
10819 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillMount === 'function') {
10820 unsafeLifecycles.push('UNSAFE_componentWillMount');
10821 }
10822 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
10823 unsafeLifecycles.push('UNSAFE_componentWillReceiveProps');
10824 }
10825 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillUpdate === 'function') {
10826 unsafeLifecycles.push('UNSAFE_componentWillUpdate');
10827 }
10828
10829 if (unsafeLifecycles.length > 0) {
10830 unsafeLifecycles.forEach(function (lifecycle) {
10831 warningsForRoot[lifecycle].push(fiber);
10832 });
10833 }
10834 };
10835
10836 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
10837 var strictRoot = findStrictRoot(fiber);
10838 if (strictRoot === null) {
10839 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.');
10840 return;
10841 }
10842
10843 // Dedup strategy: Warn once per component.
10844 if (didWarnAboutLegacyContext.has(fiber.type)) {
10845 return;
10846 }
10847
10848 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
10849
10850 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
10851 if (warningsForRoot === undefined) {
10852 warningsForRoot = [];
10853 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
10854 }
10855 warningsForRoot.push(fiber);
10856 }
10857 };
10858
10859 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
10860 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
10861 var uniqueNames = new Set();
10862 fiberArray.forEach(function (fiber) {
10863 uniqueNames.add(getComponentName(fiber.type) || 'Component');
10864 didWarnAboutLegacyContext.add(fiber.type);
10865 });
10866
10867 var sortedNames = setToSortedString(uniqueNames);
10868 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
10869
10870 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);
10871 });
10872 };
10873}
10874
10875// This lets us hook into Fiber to debug what it's doing.
10876// See https://github.com/facebook/react/pull/8033.
10877// This is not part of the public API, not even for React DevTools.
10878// You may only inject a debugTool if you work on React Fiber itself.
10879var ReactFiberInstrumentation = {
10880 debugTool: null
10881};
10882
10883var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
10884
10885// TODO: Offscreen updates should never suspend. However, a promise that
10886// suspended inside an offscreen subtree should be able to ping at the priority
10887// of the outer render.
10888
10889function markPendingPriorityLevel(root, expirationTime) {
10890 // If there's a gap between completing a failed root and retrying it,
10891 // additional updates may be scheduled. Clear `didError`, in case the update
10892 // is sufficient to fix the error.
10893 root.didError = false;
10894
10895 // Update the latest and earliest pending times
10896 var earliestPendingTime = root.earliestPendingTime;
10897 if (earliestPendingTime === NoWork) {
10898 // No other pending updates.
10899 root.earliestPendingTime = root.latestPendingTime = expirationTime;
10900 } else {
10901 if (earliestPendingTime < expirationTime) {
10902 // This is the earliest pending update.
10903 root.earliestPendingTime = expirationTime;
10904 } else {
10905 var latestPendingTime = root.latestPendingTime;
10906 if (latestPendingTime > expirationTime) {
10907 // This is the latest pending update
10908 root.latestPendingTime = expirationTime;
10909 }
10910 }
10911 }
10912 findNextExpirationTimeToWorkOn(expirationTime, root);
10913}
10914
10915function markCommittedPriorityLevels(root, earliestRemainingTime) {
10916 root.didError = false;
10917
10918 if (earliestRemainingTime === NoWork) {
10919 // Fast path. There's no remaining work. Clear everything.
10920 root.earliestPendingTime = NoWork;
10921 root.latestPendingTime = NoWork;
10922 root.earliestSuspendedTime = NoWork;
10923 root.latestSuspendedTime = NoWork;
10924 root.latestPingedTime = NoWork;
10925 findNextExpirationTimeToWorkOn(NoWork, root);
10926 return;
10927 }
10928
10929 if (earliestRemainingTime < root.latestPingedTime) {
10930 root.latestPingedTime = NoWork;
10931 }
10932
10933 // Let's see if the previous latest known pending level was just flushed.
10934 var latestPendingTime = root.latestPendingTime;
10935 if (latestPendingTime !== NoWork) {
10936 if (latestPendingTime > earliestRemainingTime) {
10937 // We've flushed all the known pending levels.
10938 root.earliestPendingTime = root.latestPendingTime = NoWork;
10939 } else {
10940 var earliestPendingTime = root.earliestPendingTime;
10941 if (earliestPendingTime > earliestRemainingTime) {
10942 // We've flushed the earliest known pending level. Set this to the
10943 // latest pending time.
10944 root.earliestPendingTime = root.latestPendingTime;
10945 }
10946 }
10947 }
10948
10949 // Now let's handle the earliest remaining level in the whole tree. We need to
10950 // decide whether to treat it as a pending level or as suspended. Check
10951 // it falls within the range of known suspended levels.
10952
10953 var earliestSuspendedTime = root.earliestSuspendedTime;
10954 if (earliestSuspendedTime === NoWork) {
10955 // There's no suspended work. Treat the earliest remaining level as a
10956 // pending level.
10957 markPendingPriorityLevel(root, earliestRemainingTime);
10958 findNextExpirationTimeToWorkOn(NoWork, root);
10959 return;
10960 }
10961
10962 var latestSuspendedTime = root.latestSuspendedTime;
10963 if (earliestRemainingTime < latestSuspendedTime) {
10964 // The earliest remaining level is later than all the suspended work. That
10965 // means we've flushed all the suspended work.
10966 root.earliestSuspendedTime = NoWork;
10967 root.latestSuspendedTime = NoWork;
10968 root.latestPingedTime = NoWork;
10969
10970 // There's no suspended work. Treat the earliest remaining level as a
10971 // pending level.
10972 markPendingPriorityLevel(root, earliestRemainingTime);
10973 findNextExpirationTimeToWorkOn(NoWork, root);
10974 return;
10975 }
10976
10977 if (earliestRemainingTime > earliestSuspendedTime) {
10978 // The earliest remaining time is earlier than all the suspended work.
10979 // Treat it as a pending update.
10980 markPendingPriorityLevel(root, earliestRemainingTime);
10981 findNextExpirationTimeToWorkOn(NoWork, root);
10982 return;
10983 }
10984
10985 // The earliest remaining time falls within the range of known suspended
10986 // levels. We should treat this as suspended work.
10987 findNextExpirationTimeToWorkOn(NoWork, root);
10988}
10989
10990function hasLowerPriorityWork(root, erroredExpirationTime) {
10991 var latestPendingTime = root.latestPendingTime;
10992 var latestSuspendedTime = root.latestSuspendedTime;
10993 var latestPingedTime = root.latestPingedTime;
10994 return latestPendingTime !== NoWork && latestPendingTime < erroredExpirationTime || latestSuspendedTime !== NoWork && latestSuspendedTime < erroredExpirationTime || latestPingedTime !== NoWork && latestPingedTime < erroredExpirationTime;
10995}
10996
10997function isPriorityLevelSuspended(root, expirationTime) {
10998 var earliestSuspendedTime = root.earliestSuspendedTime;
10999 var latestSuspendedTime = root.latestSuspendedTime;
11000 return earliestSuspendedTime !== NoWork && expirationTime <= earliestSuspendedTime && expirationTime >= latestSuspendedTime;
11001}
11002
11003function markSuspendedPriorityLevel(root, suspendedTime) {
11004 root.didError = false;
11005 clearPing(root, suspendedTime);
11006
11007 // First, check the known pending levels and update them if needed.
11008 var earliestPendingTime = root.earliestPendingTime;
11009 var latestPendingTime = root.latestPendingTime;
11010 if (earliestPendingTime === suspendedTime) {
11011 if (latestPendingTime === suspendedTime) {
11012 // Both known pending levels were suspended. Clear them.
11013 root.earliestPendingTime = root.latestPendingTime = NoWork;
11014 } else {
11015 // The earliest pending level was suspended. Clear by setting it to the
11016 // latest pending level.
11017 root.earliestPendingTime = latestPendingTime;
11018 }
11019 } else if (latestPendingTime === suspendedTime) {
11020 // The latest pending level was suspended. Clear by setting it to the
11021 // latest pending level.
11022 root.latestPendingTime = earliestPendingTime;
11023 }
11024
11025 // Finally, update the known suspended levels.
11026 var earliestSuspendedTime = root.earliestSuspendedTime;
11027 var latestSuspendedTime = root.latestSuspendedTime;
11028 if (earliestSuspendedTime === NoWork) {
11029 // No other suspended levels.
11030 root.earliestSuspendedTime = root.latestSuspendedTime = suspendedTime;
11031 } else {
11032 if (earliestSuspendedTime < suspendedTime) {
11033 // This is the earliest suspended level.
11034 root.earliestSuspendedTime = suspendedTime;
11035 } else if (latestSuspendedTime > suspendedTime) {
11036 // This is the latest suspended level
11037 root.latestSuspendedTime = suspendedTime;
11038 }
11039 }
11040
11041 findNextExpirationTimeToWorkOn(suspendedTime, root);
11042}
11043
11044function markPingedPriorityLevel(root, pingedTime) {
11045 root.didError = false;
11046
11047 // TODO: When we add back resuming, we need to ensure the progressed work
11048 // is thrown out and not reused during the restarted render. One way to
11049 // invalidate the progressed work is to restart at expirationTime + 1.
11050 var latestPingedTime = root.latestPingedTime;
11051 if (latestPingedTime === NoWork || latestPingedTime > pingedTime) {
11052 root.latestPingedTime = pingedTime;
11053 }
11054 findNextExpirationTimeToWorkOn(pingedTime, root);
11055}
11056
11057function clearPing(root, completedTime) {
11058 var latestPingedTime = root.latestPingedTime;
11059 if (latestPingedTime >= completedTime) {
11060 root.latestPingedTime = NoWork;
11061 }
11062}
11063
11064function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) {
11065 var earliestExpirationTime = renderExpirationTime;
11066
11067 var earliestPendingTime = root.earliestPendingTime;
11068 var earliestSuspendedTime = root.earliestSuspendedTime;
11069 if (earliestPendingTime > earliestExpirationTime) {
11070 earliestExpirationTime = earliestPendingTime;
11071 }
11072 if (earliestSuspendedTime > earliestExpirationTime) {
11073 earliestExpirationTime = earliestSuspendedTime;
11074 }
11075 return earliestExpirationTime;
11076}
11077
11078function didExpireAtExpirationTime(root, currentTime) {
11079 var expirationTime = root.expirationTime;
11080 if (expirationTime !== NoWork && currentTime <= expirationTime) {
11081 // The root has expired. Flush all work up to the current time.
11082 root.nextExpirationTimeToWorkOn = currentTime;
11083 }
11084}
11085
11086function findNextExpirationTimeToWorkOn(completedExpirationTime, root) {
11087 var earliestSuspendedTime = root.earliestSuspendedTime;
11088 var latestSuspendedTime = root.latestSuspendedTime;
11089 var earliestPendingTime = root.earliestPendingTime;
11090 var latestPingedTime = root.latestPingedTime;
11091
11092 // Work on the earliest pending time. Failing that, work on the latest
11093 // pinged time.
11094 var nextExpirationTimeToWorkOn = earliestPendingTime !== NoWork ? earliestPendingTime : latestPingedTime;
11095
11096 // If there is no pending or pinged work, check if there's suspended work
11097 // that's lower priority than what we just completed.
11098 if (nextExpirationTimeToWorkOn === NoWork && (completedExpirationTime === NoWork || latestSuspendedTime < completedExpirationTime)) {
11099 // The lowest priority suspended work is the work most likely to be
11100 // committed next. Let's start rendering it again, so that if it times out,
11101 // it's ready to commit.
11102 nextExpirationTimeToWorkOn = latestSuspendedTime;
11103 }
11104
11105 var expirationTime = nextExpirationTimeToWorkOn;
11106 if (expirationTime !== NoWork && earliestSuspendedTime > expirationTime) {
11107 // Expire using the earliest known expiration time.
11108 expirationTime = earliestSuspendedTime;
11109 }
11110
11111 root.nextExpirationTimeToWorkOn = nextExpirationTimeToWorkOn;
11112 root.expirationTime = expirationTime;
11113}
11114
11115function resolveDefaultProps(Component, baseProps) {
11116 if (Component && Component.defaultProps) {
11117 // Resolve default props. Taken from ReactElement
11118 var props = _assign({}, baseProps);
11119 var defaultProps = Component.defaultProps;
11120 for (var propName in defaultProps) {
11121 if (props[propName] === undefined) {
11122 props[propName] = defaultProps[propName];
11123 }
11124 }
11125 return props;
11126 }
11127 return baseProps;
11128}
11129
11130function readLazyComponentType(lazyComponent) {
11131 var status = lazyComponent._status;
11132 var result = lazyComponent._result;
11133 switch (status) {
11134 case Resolved:
11135 {
11136 var Component = result;
11137 return Component;
11138 }
11139 case Rejected:
11140 {
11141 var error = result;
11142 throw error;
11143 }
11144 case Pending:
11145 {
11146 var thenable = result;
11147 throw thenable;
11148 }
11149 default:
11150 {
11151 lazyComponent._status = Pending;
11152 var ctor = lazyComponent._ctor;
11153 var _thenable = ctor();
11154 _thenable.then(function (moduleObject) {
11155 if (lazyComponent._status === Pending) {
11156 var defaultExport = moduleObject.default;
11157 {
11158 if (defaultExport === undefined) {
11159 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);
11160 }
11161 }
11162 lazyComponent._status = Resolved;
11163 lazyComponent._result = defaultExport;
11164 }
11165 }, function (error) {
11166 if (lazyComponent._status === Pending) {
11167 lazyComponent._status = Rejected;
11168 lazyComponent._result = error;
11169 }
11170 });
11171 // Handle synchronous thenables.
11172 switch (lazyComponent._status) {
11173 case Resolved:
11174 return lazyComponent._result;
11175 case Rejected:
11176 throw lazyComponent._result;
11177 }
11178 lazyComponent._result = _thenable;
11179 throw _thenable;
11180 }
11181 }
11182}
11183
11184var fakeInternalInstance = {};
11185var isArray$1 = Array.isArray;
11186
11187// React.Component uses a shared frozen object by default.
11188// We'll use it to determine whether we need to initialize legacy refs.
11189var emptyRefsObject = new React.Component().refs;
11190
11191var didWarnAboutStateAssignmentForComponent = void 0;
11192var didWarnAboutUninitializedState = void 0;
11193var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0;
11194var didWarnAboutLegacyLifecyclesAndDerivedState = void 0;
11195var didWarnAboutUndefinedDerivedState = void 0;
11196var warnOnUndefinedDerivedState = void 0;
11197var warnOnInvalidCallback$1 = void 0;
11198var didWarnAboutDirectlyAssigningPropsToState = void 0;
11199var didWarnAboutContextTypeAndContextTypes = void 0;
11200var didWarnAboutInvalidateContextType = void 0;
11201
11202{
11203 didWarnAboutStateAssignmentForComponent = new Set();
11204 didWarnAboutUninitializedState = new Set();
11205 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
11206 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
11207 didWarnAboutDirectlyAssigningPropsToState = new Set();
11208 didWarnAboutUndefinedDerivedState = new Set();
11209 didWarnAboutContextTypeAndContextTypes = new Set();
11210 didWarnAboutInvalidateContextType = new Set();
11211
11212 var didWarnOnInvalidCallback = new Set();
11213
11214 warnOnInvalidCallback$1 = function (callback, callerName) {
11215 if (callback === null || typeof callback === 'function') {
11216 return;
11217 }
11218 var key = callerName + '_' + callback;
11219 if (!didWarnOnInvalidCallback.has(key)) {
11220 didWarnOnInvalidCallback.add(key);
11221 warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
11222 }
11223 };
11224
11225 warnOnUndefinedDerivedState = function (type, partialState) {
11226 if (partialState === undefined) {
11227 var componentName = getComponentName(type) || 'Component';
11228 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
11229 didWarnAboutUndefinedDerivedState.add(componentName);
11230 warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
11231 }
11232 }
11233 };
11234
11235 // This is so gross but it's at least non-critical and can be removed if
11236 // it causes problems. This is meant to give a nicer error message for
11237 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
11238 // ...)) which otherwise throws a "_processChildContext is not a function"
11239 // exception.
11240 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
11241 enumerable: false,
11242 value: function () {
11243 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).');
11244 }
11245 });
11246 Object.freeze(fakeInternalInstance);
11247}
11248
11249function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
11250 var prevState = workInProgress.memoizedState;
11251
11252 {
11253 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
11254 // Invoke the function an extra time to help detect side-effects.
11255 getDerivedStateFromProps(nextProps, prevState);
11256 }
11257 }
11258
11259 var partialState = getDerivedStateFromProps(nextProps, prevState);
11260
11261 {
11262 warnOnUndefinedDerivedState(ctor, partialState);
11263 }
11264 // Merge the partial state and the previous state.
11265 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
11266 workInProgress.memoizedState = memoizedState;
11267
11268 // Once the update queue is empty, persist the derived state onto the
11269 // base state.
11270 var updateQueue = workInProgress.updateQueue;
11271 if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
11272 updateQueue.baseState = memoizedState;
11273 }
11274}
11275
11276var classComponentUpdater = {
11277 isMounted: isMounted,
11278 enqueueSetState: function (inst, payload, callback) {
11279 var fiber = get(inst);
11280 var currentTime = requestCurrentTime();
11281 var expirationTime = computeExpirationForFiber(currentTime, fiber);
11282
11283 var update = createUpdate(expirationTime);
11284 update.payload = payload;
11285 if (callback !== undefined && callback !== null) {
11286 {
11287 warnOnInvalidCallback$1(callback, 'setState');
11288 }
11289 update.callback = callback;
11290 }
11291
11292 flushPassiveEffects();
11293 enqueueUpdate(fiber, update);
11294 scheduleWork(fiber, expirationTime);
11295 },
11296 enqueueReplaceState: function (inst, payload, callback) {
11297 var fiber = get(inst);
11298 var currentTime = requestCurrentTime();
11299 var expirationTime = computeExpirationForFiber(currentTime, fiber);
11300
11301 var update = createUpdate(expirationTime);
11302 update.tag = ReplaceState;
11303 update.payload = payload;
11304
11305 if (callback !== undefined && callback !== null) {
11306 {
11307 warnOnInvalidCallback$1(callback, 'replaceState');
11308 }
11309 update.callback = callback;
11310 }
11311
11312 flushPassiveEffects();
11313 enqueueUpdate(fiber, update);
11314 scheduleWork(fiber, expirationTime);
11315 },
11316 enqueueForceUpdate: function (inst, callback) {
11317 var fiber = get(inst);
11318 var currentTime = requestCurrentTime();
11319 var expirationTime = computeExpirationForFiber(currentTime, fiber);
11320
11321 var update = createUpdate(expirationTime);
11322 update.tag = ForceUpdate;
11323
11324 if (callback !== undefined && callback !== null) {
11325 {
11326 warnOnInvalidCallback$1(callback, 'forceUpdate');
11327 }
11328 update.callback = callback;
11329 }
11330
11331 flushPassiveEffects();
11332 enqueueUpdate(fiber, update);
11333 scheduleWork(fiber, expirationTime);
11334 }
11335};
11336
11337function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
11338 var instance = workInProgress.stateNode;
11339 if (typeof instance.shouldComponentUpdate === 'function') {
11340 startPhaseTimer(workInProgress, 'shouldComponentUpdate');
11341 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
11342 stopPhaseTimer();
11343
11344 {
11345 !(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;
11346 }
11347
11348 return shouldUpdate;
11349 }
11350
11351 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
11352 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
11353 }
11354
11355 return true;
11356}
11357
11358function checkClassInstance(workInProgress, ctor, newProps) {
11359 var instance = workInProgress.stateNode;
11360 {
11361 var name = getComponentName(ctor) || 'Component';
11362 var renderPresent = instance.render;
11363
11364 if (!renderPresent) {
11365 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
11366 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
11367 } else {
11368 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
11369 }
11370 }
11371
11372 var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
11373 !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;
11374 var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
11375 !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;
11376 var noInstancePropTypes = !instance.propTypes;
11377 !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
11378 var noInstanceContextType = !instance.contextType;
11379 !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0;
11380 var noInstanceContextTypes = !instance.contextTypes;
11381 !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
11382
11383 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
11384 didWarnAboutContextTypeAndContextTypes.add(ctor);
11385 warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
11386 }
11387
11388 var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
11389 !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;
11390 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
11391 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');
11392 }
11393 var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
11394 !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
11395 var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
11396 !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;
11397 var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
11398 !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
11399 var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
11400 !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
11401 var hasMutatedProps = instance.props !== newProps;
11402 !(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;
11403 var noInstanceDefaultProps = !instance.defaultProps;
11404 !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;
11405
11406 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
11407 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
11408 warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
11409 }
11410
11411 var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
11412 !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;
11413 var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function';
11414 !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;
11415 var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function';
11416 !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;
11417 var _state = instance.state;
11418 if (_state && (typeof _state !== 'object' || isArray$1(_state))) {
11419 warningWithoutStack$1(false, '%s.state: must be set to an object or null', name);
11420 }
11421 if (typeof instance.getChildContext === 'function') {
11422 !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
11423 }
11424 }
11425}
11426
11427function adoptClassInstance(workInProgress, instance) {
11428 instance.updater = classComponentUpdater;
11429 workInProgress.stateNode = instance;
11430 // The instance needs access to the fiber so that it can schedule updates
11431 set(instance, workInProgress);
11432 {
11433 instance._reactInternalInstance = fakeInternalInstance;
11434 }
11435}
11436
11437function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) {
11438 var isLegacyContextConsumer = false;
11439 var unmaskedContext = emptyContextObject;
11440 var context = null;
11441 var contextType = ctor.contextType;
11442 if (typeof contextType === 'object' && contextType !== null) {
11443 {
11444 if (contextType.$$typeof !== REACT_CONTEXT_TYPE && !didWarnAboutInvalidateContextType.has(ctor)) {
11445 didWarnAboutInvalidateContextType.add(ctor);
11446 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');
11447 }
11448 }
11449
11450 context = readContext(contextType);
11451 } else {
11452 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11453 var contextTypes = ctor.contextTypes;
11454 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
11455 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
11456 }
11457
11458 // Instantiate twice to help detect side-effects.
11459 {
11460 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
11461 new ctor(props, context); // eslint-disable-line no-new
11462 }
11463 }
11464
11465 var instance = new ctor(props, context);
11466 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
11467 adoptClassInstance(workInProgress, instance);
11468
11469 {
11470 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
11471 var componentName = getComponentName(ctor) || 'Component';
11472 if (!didWarnAboutUninitializedState.has(componentName)) {
11473 didWarnAboutUninitializedState.add(componentName);
11474 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);
11475 }
11476 }
11477
11478 // If new component APIs are defined, "unsafe" lifecycles won't be called.
11479 // Warn about these lifecycles if they are present.
11480 // Don't warn about react-lifecycles-compat polyfilled methods though.
11481 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
11482 var foundWillMountName = null;
11483 var foundWillReceivePropsName = null;
11484 var foundWillUpdateName = null;
11485 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
11486 foundWillMountName = 'componentWillMount';
11487 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
11488 foundWillMountName = 'UNSAFE_componentWillMount';
11489 }
11490 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
11491 foundWillReceivePropsName = 'componentWillReceiveProps';
11492 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
11493 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
11494 }
11495 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
11496 foundWillUpdateName = 'componentWillUpdate';
11497 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
11498 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
11499 }
11500 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
11501 var _componentName = getComponentName(ctor) || 'Component';
11502 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
11503 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
11504 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
11505 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 : '');
11506 }
11507 }
11508 }
11509 }
11510
11511 // Cache unmasked context so we can avoid recreating masked context unless necessary.
11512 // ReactFiberContext usually updates this cache but can't for newly-created instances.
11513 if (isLegacyContextConsumer) {
11514 cacheContext(workInProgress, unmaskedContext, context);
11515 }
11516
11517 return instance;
11518}
11519
11520function callComponentWillMount(workInProgress, instance) {
11521 startPhaseTimer(workInProgress, 'componentWillMount');
11522 var oldState = instance.state;
11523
11524 if (typeof instance.componentWillMount === 'function') {
11525 instance.componentWillMount();
11526 }
11527 if (typeof instance.UNSAFE_componentWillMount === 'function') {
11528 instance.UNSAFE_componentWillMount();
11529 }
11530
11531 stopPhaseTimer();
11532
11533 if (oldState !== instance.state) {
11534 {
11535 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');
11536 }
11537 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
11538 }
11539}
11540
11541function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
11542 var oldState = instance.state;
11543 startPhaseTimer(workInProgress, 'componentWillReceiveProps');
11544 if (typeof instance.componentWillReceiveProps === 'function') {
11545 instance.componentWillReceiveProps(newProps, nextContext);
11546 }
11547 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
11548 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
11549 }
11550 stopPhaseTimer();
11551
11552 if (instance.state !== oldState) {
11553 {
11554 var componentName = getComponentName(workInProgress.type) || 'Component';
11555 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
11556 didWarnAboutStateAssignmentForComponent.add(componentName);
11557 warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
11558 }
11559 }
11560 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
11561 }
11562}
11563
11564// Invokes the mount life-cycles on a previously never rendered instance.
11565function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
11566 {
11567 checkClassInstance(workInProgress, ctor, newProps);
11568 }
11569
11570 var instance = workInProgress.stateNode;
11571 instance.props = newProps;
11572 instance.state = workInProgress.memoizedState;
11573 instance.refs = emptyRefsObject;
11574
11575 var contextType = ctor.contextType;
11576 if (typeof contextType === 'object' && contextType !== null) {
11577 instance.context = readContext(contextType);
11578 } else {
11579 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11580 instance.context = getMaskedContext(workInProgress, unmaskedContext);
11581 }
11582
11583 {
11584 if (instance.state === newProps) {
11585 var componentName = getComponentName(ctor) || 'Component';
11586 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
11587 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
11588 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);
11589 }
11590 }
11591
11592 if (workInProgress.mode & StrictMode) {
11593 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
11594
11595 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
11596 }
11597
11598 if (warnAboutDeprecatedLifecycles) {
11599 ReactStrictModeWarnings.recordDeprecationWarnings(workInProgress, instance);
11600 }
11601 }
11602
11603 var updateQueue = workInProgress.updateQueue;
11604 if (updateQueue !== null) {
11605 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11606 instance.state = workInProgress.memoizedState;
11607 }
11608
11609 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
11610 if (typeof getDerivedStateFromProps === 'function') {
11611 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
11612 instance.state = workInProgress.memoizedState;
11613 }
11614
11615 // In order to support react-lifecycles-compat polyfilled components,
11616 // Unsafe lifecycles should not be invoked for components using the new APIs.
11617 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
11618 callComponentWillMount(workInProgress, instance);
11619 // If we had additional state updates during this life-cycle, let's
11620 // process them now.
11621 updateQueue = workInProgress.updateQueue;
11622 if (updateQueue !== null) {
11623 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11624 instance.state = workInProgress.memoizedState;
11625 }
11626 }
11627
11628 if (typeof instance.componentDidMount === 'function') {
11629 workInProgress.effectTag |= Update;
11630 }
11631}
11632
11633function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
11634 var instance = workInProgress.stateNode;
11635
11636 var oldProps = workInProgress.memoizedProps;
11637 instance.props = oldProps;
11638
11639 var oldContext = instance.context;
11640 var contextType = ctor.contextType;
11641 var nextContext = void 0;
11642 if (typeof contextType === 'object' && contextType !== null) {
11643 nextContext = readContext(contextType);
11644 } else {
11645 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11646 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
11647 }
11648
11649 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
11650 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
11651
11652 // Note: During these life-cycles, instance.props/instance.state are what
11653 // ever the previously attempted to render - not the "current". However,
11654 // during componentDidUpdate we pass the "current" props.
11655
11656 // In order to support react-lifecycles-compat polyfilled components,
11657 // Unsafe lifecycles should not be invoked for components using the new APIs.
11658 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
11659 if (oldProps !== newProps || oldContext !== nextContext) {
11660 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
11661 }
11662 }
11663
11664 resetHasForceUpdateBeforeProcessing();
11665
11666 var oldState = workInProgress.memoizedState;
11667 var newState = instance.state = oldState;
11668 var updateQueue = workInProgress.updateQueue;
11669 if (updateQueue !== null) {
11670 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11671 newState = workInProgress.memoizedState;
11672 }
11673 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
11674 // If an update was already in progress, we should schedule an Update
11675 // effect even though we're bailing out, so that cWU/cDU are called.
11676 if (typeof instance.componentDidMount === 'function') {
11677 workInProgress.effectTag |= Update;
11678 }
11679 return false;
11680 }
11681
11682 if (typeof getDerivedStateFromProps === 'function') {
11683 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
11684 newState = workInProgress.memoizedState;
11685 }
11686
11687 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
11688
11689 if (shouldUpdate) {
11690 // In order to support react-lifecycles-compat polyfilled components,
11691 // Unsafe lifecycles should not be invoked for components using the new APIs.
11692 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
11693 startPhaseTimer(workInProgress, 'componentWillMount');
11694 if (typeof instance.componentWillMount === 'function') {
11695 instance.componentWillMount();
11696 }
11697 if (typeof instance.UNSAFE_componentWillMount === 'function') {
11698 instance.UNSAFE_componentWillMount();
11699 }
11700 stopPhaseTimer();
11701 }
11702 if (typeof instance.componentDidMount === 'function') {
11703 workInProgress.effectTag |= Update;
11704 }
11705 } else {
11706 // If an update was already in progress, we should schedule an Update
11707 // effect even though we're bailing out, so that cWU/cDU are called.
11708 if (typeof instance.componentDidMount === 'function') {
11709 workInProgress.effectTag |= Update;
11710 }
11711
11712 // If shouldComponentUpdate returned false, we should still update the
11713 // memoized state to indicate that this work can be reused.
11714 workInProgress.memoizedProps = newProps;
11715 workInProgress.memoizedState = newState;
11716 }
11717
11718 // Update the existing instance's state, props, and context pointers even
11719 // if shouldComponentUpdate returns false.
11720 instance.props = newProps;
11721 instance.state = newState;
11722 instance.context = nextContext;
11723
11724 return shouldUpdate;
11725}
11726
11727// Invokes the update life-cycles and returns false if it shouldn't rerender.
11728function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
11729 var instance = workInProgress.stateNode;
11730
11731 var oldProps = workInProgress.memoizedProps;
11732 instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
11733
11734 var oldContext = instance.context;
11735 var contextType = ctor.contextType;
11736 var nextContext = void 0;
11737 if (typeof contextType === 'object' && contextType !== null) {
11738 nextContext = readContext(contextType);
11739 } else {
11740 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11741 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
11742 }
11743
11744 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
11745 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
11746
11747 // Note: During these life-cycles, instance.props/instance.state are what
11748 // ever the previously attempted to render - not the "current". However,
11749 // during componentDidUpdate we pass the "current" props.
11750
11751 // In order to support react-lifecycles-compat polyfilled components,
11752 // Unsafe lifecycles should not be invoked for components using the new APIs.
11753 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
11754 if (oldProps !== newProps || oldContext !== nextContext) {
11755 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
11756 }
11757 }
11758
11759 resetHasForceUpdateBeforeProcessing();
11760
11761 var oldState = workInProgress.memoizedState;
11762 var newState = instance.state = oldState;
11763 var updateQueue = workInProgress.updateQueue;
11764 if (updateQueue !== null) {
11765 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11766 newState = workInProgress.memoizedState;
11767 }
11768
11769 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
11770 // If an update was already in progress, we should schedule an Update
11771 // effect even though we're bailing out, so that cWU/cDU are called.
11772 if (typeof instance.componentDidUpdate === 'function') {
11773 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11774 workInProgress.effectTag |= Update;
11775 }
11776 }
11777 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
11778 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11779 workInProgress.effectTag |= Snapshot;
11780 }
11781 }
11782 return false;
11783 }
11784
11785 if (typeof getDerivedStateFromProps === 'function') {
11786 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
11787 newState = workInProgress.memoizedState;
11788 }
11789
11790 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
11791
11792 if (shouldUpdate) {
11793 // In order to support react-lifecycles-compat polyfilled components,
11794 // Unsafe lifecycles should not be invoked for components using the new APIs.
11795 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
11796 startPhaseTimer(workInProgress, 'componentWillUpdate');
11797 if (typeof instance.componentWillUpdate === 'function') {
11798 instance.componentWillUpdate(newProps, newState, nextContext);
11799 }
11800 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
11801 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
11802 }
11803 stopPhaseTimer();
11804 }
11805 if (typeof instance.componentDidUpdate === 'function') {
11806 workInProgress.effectTag |= Update;
11807 }
11808 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
11809 workInProgress.effectTag |= Snapshot;
11810 }
11811 } else {
11812 // If an update was already in progress, we should schedule an Update
11813 // effect even though we're bailing out, so that cWU/cDU are called.
11814 if (typeof instance.componentDidUpdate === 'function') {
11815 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11816 workInProgress.effectTag |= Update;
11817 }
11818 }
11819 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
11820 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11821 workInProgress.effectTag |= Snapshot;
11822 }
11823 }
11824
11825 // If shouldComponentUpdate returned false, we should still update the
11826 // memoized props/state to indicate that this work can be reused.
11827 workInProgress.memoizedProps = newProps;
11828 workInProgress.memoizedState = newState;
11829 }
11830
11831 // Update the existing instance's state, props, and context pointers even
11832 // if shouldComponentUpdate returns false.
11833 instance.props = newProps;
11834 instance.state = newState;
11835 instance.context = nextContext;
11836
11837 return shouldUpdate;
11838}
11839
11840var didWarnAboutMaps = void 0;
11841var didWarnAboutGenerators = void 0;
11842var didWarnAboutStringRefInStrictMode = void 0;
11843var ownerHasKeyUseWarning = void 0;
11844var ownerHasFunctionTypeWarning = void 0;
11845var warnForMissingKey = function (child) {};
11846
11847{
11848 didWarnAboutMaps = false;
11849 didWarnAboutGenerators = false;
11850 didWarnAboutStringRefInStrictMode = {};
11851
11852 /**
11853 * Warn if there's no key explicitly set on dynamic arrays of children or
11854 * object keys are not valid. This allows us to keep track of children between
11855 * updates.
11856 */
11857 ownerHasKeyUseWarning = {};
11858 ownerHasFunctionTypeWarning = {};
11859
11860 warnForMissingKey = function (child) {
11861 if (child === null || typeof child !== 'object') {
11862 return;
11863 }
11864 if (!child._store || child._store.validated || child.key != null) {
11865 return;
11866 }
11867 !(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;
11868 child._store.validated = true;
11869
11870 var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
11871 if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
11872 return;
11873 }
11874 ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
11875
11876 warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
11877 };
11878}
11879
11880var isArray = Array.isArray;
11881
11882function coerceRef(returnFiber, current$$1, element) {
11883 var mixedRef = element.ref;
11884 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
11885 {
11886 if (returnFiber.mode & StrictMode) {
11887 var componentName = getComponentName(returnFiber.type) || 'Component';
11888 if (!didWarnAboutStringRefInStrictMode[componentName]) {
11889 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));
11890 didWarnAboutStringRefInStrictMode[componentName] = true;
11891 }
11892 }
11893 }
11894
11895 if (element._owner) {
11896 var owner = element._owner;
11897 var inst = void 0;
11898 if (owner) {
11899 var ownerFiber = owner;
11900 !(ownerFiber.tag === ClassComponent) ? invariant(false, 'Function components cannot have refs. Did you mean to use React.forwardRef()?') : void 0;
11901 inst = ownerFiber.stateNode;
11902 }
11903 !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;
11904 var stringRef = '' + mixedRef;
11905 // Check if previous string ref matches new string ref
11906 if (current$$1 !== null && current$$1.ref !== null && typeof current$$1.ref === 'function' && current$$1.ref._stringRef === stringRef) {
11907 return current$$1.ref;
11908 }
11909 var ref = function (value) {
11910 var refs = inst.refs;
11911 if (refs === emptyRefsObject) {
11912 // This is a lazy pooled frozen object, so we need to initialize.
11913 refs = inst.refs = {};
11914 }
11915 if (value === null) {
11916 delete refs[stringRef];
11917 } else {
11918 refs[stringRef] = value;
11919 }
11920 };
11921 ref._stringRef = stringRef;
11922 return ref;
11923 } else {
11924 !(typeof mixedRef === 'string') ? invariant(false, 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.') : void 0;
11925 !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;
11926 }
11927 }
11928 return mixedRef;
11929}
11930
11931function throwOnInvalidObjectType(returnFiber, newChild) {
11932 if (returnFiber.type !== 'textarea') {
11933 var addendum = '';
11934 {
11935 addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
11936 }
11937 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);
11938 }
11939}
11940
11941function warnOnFunctionType() {
11942 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();
11943
11944 if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
11945 return;
11946 }
11947 ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
11948
11949 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.');
11950}
11951
11952// This wrapper function exists because I expect to clone the code in each path
11953// to be able to optimize each path individually by branching early. This needs
11954// a compiler or we can do it manually. Helpers that don't need this branching
11955// live outside of this function.
11956function ChildReconciler(shouldTrackSideEffects) {
11957 function deleteChild(returnFiber, childToDelete) {
11958 if (!shouldTrackSideEffects) {
11959 // Noop.
11960 return;
11961 }
11962 // Deletions are added in reversed order so we add it to the front.
11963 // At this point, the return fiber's effect list is empty except for
11964 // deletions, so we can just append the deletion to the list. The remaining
11965 // effects aren't added until the complete phase. Once we implement
11966 // resuming, this may not be true.
11967 var last = returnFiber.lastEffect;
11968 if (last !== null) {
11969 last.nextEffect = childToDelete;
11970 returnFiber.lastEffect = childToDelete;
11971 } else {
11972 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
11973 }
11974 childToDelete.nextEffect = null;
11975 childToDelete.effectTag = Deletion;
11976 }
11977
11978 function deleteRemainingChildren(returnFiber, currentFirstChild) {
11979 if (!shouldTrackSideEffects) {
11980 // Noop.
11981 return null;
11982 }
11983
11984 // TODO: For the shouldClone case, this could be micro-optimized a bit by
11985 // assuming that after the first child we've already added everything.
11986 var childToDelete = currentFirstChild;
11987 while (childToDelete !== null) {
11988 deleteChild(returnFiber, childToDelete);
11989 childToDelete = childToDelete.sibling;
11990 }
11991 return null;
11992 }
11993
11994 function mapRemainingChildren(returnFiber, currentFirstChild) {
11995 // Add the remaining children to a temporary map so that we can find them by
11996 // keys quickly. Implicit (null) keys get added to this set with their index
11997 var existingChildren = new Map();
11998
11999 var existingChild = currentFirstChild;
12000 while (existingChild !== null) {
12001 if (existingChild.key !== null) {
12002 existingChildren.set(existingChild.key, existingChild);
12003 } else {
12004 existingChildren.set(existingChild.index, existingChild);
12005 }
12006 existingChild = existingChild.sibling;
12007 }
12008 return existingChildren;
12009 }
12010
12011 function useFiber(fiber, pendingProps, expirationTime) {
12012 // We currently set sibling to null and index to 0 here because it is easy
12013 // to forget to do before returning it. E.g. for the single child case.
12014 var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
12015 clone.index = 0;
12016 clone.sibling = null;
12017 return clone;
12018 }
12019
12020 function placeChild(newFiber, lastPlacedIndex, newIndex) {
12021 newFiber.index = newIndex;
12022 if (!shouldTrackSideEffects) {
12023 // Noop.
12024 return lastPlacedIndex;
12025 }
12026 var current$$1 = newFiber.alternate;
12027 if (current$$1 !== null) {
12028 var oldIndex = current$$1.index;
12029 if (oldIndex < lastPlacedIndex) {
12030 // This is a move.
12031 newFiber.effectTag = Placement;
12032 return lastPlacedIndex;
12033 } else {
12034 // This item can stay in place.
12035 return oldIndex;
12036 }
12037 } else {
12038 // This is an insertion.
12039 newFiber.effectTag = Placement;
12040 return lastPlacedIndex;
12041 }
12042 }
12043
12044 function placeSingleChild(newFiber) {
12045 // This is simpler for the single child case. We only need to do a
12046 // placement for inserting new children.
12047 if (shouldTrackSideEffects && newFiber.alternate === null) {
12048 newFiber.effectTag = Placement;
12049 }
12050 return newFiber;
12051 }
12052
12053 function updateTextNode(returnFiber, current$$1, textContent, expirationTime) {
12054 if (current$$1 === null || current$$1.tag !== HostText) {
12055 // Insert
12056 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
12057 created.return = returnFiber;
12058 return created;
12059 } else {
12060 // Update
12061 var existing = useFiber(current$$1, textContent, expirationTime);
12062 existing.return = returnFiber;
12063 return existing;
12064 }
12065 }
12066
12067 function updateElement(returnFiber, current$$1, element, expirationTime) {
12068 if (current$$1 !== null && current$$1.elementType === element.type) {
12069 // Move based on index
12070 var existing = useFiber(current$$1, element.props, expirationTime);
12071 existing.ref = coerceRef(returnFiber, current$$1, element);
12072 existing.return = returnFiber;
12073 {
12074 existing._debugSource = element._source;
12075 existing._debugOwner = element._owner;
12076 }
12077 return existing;
12078 } else {
12079 // Insert
12080 var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
12081 created.ref = coerceRef(returnFiber, current$$1, element);
12082 created.return = returnFiber;
12083 return created;
12084 }
12085 }
12086
12087 function updatePortal(returnFiber, current$$1, portal, expirationTime) {
12088 if (current$$1 === null || current$$1.tag !== HostPortal || current$$1.stateNode.containerInfo !== portal.containerInfo || current$$1.stateNode.implementation !== portal.implementation) {
12089 // Insert
12090 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
12091 created.return = returnFiber;
12092 return created;
12093 } else {
12094 // Update
12095 var existing = useFiber(current$$1, portal.children || [], expirationTime);
12096 existing.return = returnFiber;
12097 return existing;
12098 }
12099 }
12100
12101 function updateFragment(returnFiber, current$$1, fragment, expirationTime, key) {
12102 if (current$$1 === null || current$$1.tag !== Fragment) {
12103 // Insert
12104 var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
12105 created.return = returnFiber;
12106 return created;
12107 } else {
12108 // Update
12109 var existing = useFiber(current$$1, fragment, expirationTime);
12110 existing.return = returnFiber;
12111 return existing;
12112 }
12113 }
12114
12115 function createChild(returnFiber, newChild, expirationTime) {
12116 if (typeof newChild === 'string' || typeof newChild === 'number') {
12117 // Text nodes don't have keys. If the previous node is implicitly keyed
12118 // we can continue to replace it without aborting even if it is not a text
12119 // node.
12120 var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
12121 created.return = returnFiber;
12122 return created;
12123 }
12124
12125 if (typeof newChild === 'object' && newChild !== null) {
12126 switch (newChild.$$typeof) {
12127 case REACT_ELEMENT_TYPE:
12128 {
12129 var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
12130 _created.ref = coerceRef(returnFiber, null, newChild);
12131 _created.return = returnFiber;
12132 return _created;
12133 }
12134 case REACT_PORTAL_TYPE:
12135 {
12136 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
12137 _created2.return = returnFiber;
12138 return _created2;
12139 }
12140 }
12141
12142 if (isArray(newChild) || getIteratorFn(newChild)) {
12143 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
12144 _created3.return = returnFiber;
12145 return _created3;
12146 }
12147
12148 throwOnInvalidObjectType(returnFiber, newChild);
12149 }
12150
12151 {
12152 if (typeof newChild === 'function') {
12153 warnOnFunctionType();
12154 }
12155 }
12156
12157 return null;
12158 }
12159
12160 function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
12161 // Update the fiber if the keys match, otherwise return null.
12162
12163 var key = oldFiber !== null ? oldFiber.key : null;
12164
12165 if (typeof newChild === 'string' || typeof newChild === 'number') {
12166 // Text nodes don't have keys. If the previous node is implicitly keyed
12167 // we can continue to replace it without aborting even if it is not a text
12168 // node.
12169 if (key !== null) {
12170 return null;
12171 }
12172 return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
12173 }
12174
12175 if (typeof newChild === 'object' && newChild !== null) {
12176 switch (newChild.$$typeof) {
12177 case REACT_ELEMENT_TYPE:
12178 {
12179 if (newChild.key === key) {
12180 if (newChild.type === REACT_FRAGMENT_TYPE) {
12181 return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
12182 }
12183 return updateElement(returnFiber, oldFiber, newChild, expirationTime);
12184 } else {
12185 return null;
12186 }
12187 }
12188 case REACT_PORTAL_TYPE:
12189 {
12190 if (newChild.key === key) {
12191 return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
12192 } else {
12193 return null;
12194 }
12195 }
12196 }
12197
12198 if (isArray(newChild) || getIteratorFn(newChild)) {
12199 if (key !== null) {
12200 return null;
12201 }
12202
12203 return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
12204 }
12205
12206 throwOnInvalidObjectType(returnFiber, newChild);
12207 }
12208
12209 {
12210 if (typeof newChild === 'function') {
12211 warnOnFunctionType();
12212 }
12213 }
12214
12215 return null;
12216 }
12217
12218 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
12219 if (typeof newChild === 'string' || typeof newChild === 'number') {
12220 // Text nodes don't have keys, so we neither have to check the old nor
12221 // new node for the key. If both are text nodes, they match.
12222 var matchedFiber = existingChildren.get(newIdx) || null;
12223 return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
12224 }
12225
12226 if (typeof newChild === 'object' && newChild !== null) {
12227 switch (newChild.$$typeof) {
12228 case REACT_ELEMENT_TYPE:
12229 {
12230 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
12231 if (newChild.type === REACT_FRAGMENT_TYPE) {
12232 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
12233 }
12234 return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
12235 }
12236 case REACT_PORTAL_TYPE:
12237 {
12238 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
12239 return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
12240 }
12241 }
12242
12243 if (isArray(newChild) || getIteratorFn(newChild)) {
12244 var _matchedFiber3 = existingChildren.get(newIdx) || null;
12245 return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
12246 }
12247
12248 throwOnInvalidObjectType(returnFiber, newChild);
12249 }
12250
12251 {
12252 if (typeof newChild === 'function') {
12253 warnOnFunctionType();
12254 }
12255 }
12256
12257 return null;
12258 }
12259
12260 /**
12261 * Warns if there is a duplicate or missing key
12262 */
12263 function warnOnInvalidKey(child, knownKeys) {
12264 {
12265 if (typeof child !== 'object' || child === null) {
12266 return knownKeys;
12267 }
12268 switch (child.$$typeof) {
12269 case REACT_ELEMENT_TYPE:
12270 case REACT_PORTAL_TYPE:
12271 warnForMissingKey(child);
12272 var key = child.key;
12273 if (typeof key !== 'string') {
12274 break;
12275 }
12276 if (knownKeys === null) {
12277 knownKeys = new Set();
12278 knownKeys.add(key);
12279 break;
12280 }
12281 if (!knownKeys.has(key)) {
12282 knownKeys.add(key);
12283 break;
12284 }
12285 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);
12286 break;
12287 default:
12288 break;
12289 }
12290 }
12291 return knownKeys;
12292 }
12293
12294 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
12295 // This algorithm can't optimize by searching from both ends since we
12296 // don't have backpointers on fibers. I'm trying to see how far we can get
12297 // with that model. If it ends up not being worth the tradeoffs, we can
12298 // add it later.
12299
12300 // Even with a two ended optimization, we'd want to optimize for the case
12301 // where there are few changes and brute force the comparison instead of
12302 // going for the Map. It'd like to explore hitting that path first in
12303 // forward-only mode and only go for the Map once we notice that we need
12304 // lots of look ahead. This doesn't handle reversal as well as two ended
12305 // search but that's unusual. Besides, for the two ended optimization to
12306 // work on Iterables, we'd need to copy the whole set.
12307
12308 // In this first iteration, we'll just live with hitting the bad case
12309 // (adding everything to a Map) in for every insert/move.
12310
12311 // If you change this code, also update reconcileChildrenIterator() which
12312 // uses the same algorithm.
12313
12314 {
12315 // First, validate keys.
12316 var knownKeys = null;
12317 for (var i = 0; i < newChildren.length; i++) {
12318 var child = newChildren[i];
12319 knownKeys = warnOnInvalidKey(child, knownKeys);
12320 }
12321 }
12322
12323 var resultingFirstChild = null;
12324 var previousNewFiber = null;
12325
12326 var oldFiber = currentFirstChild;
12327 var lastPlacedIndex = 0;
12328 var newIdx = 0;
12329 var nextOldFiber = null;
12330 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
12331 if (oldFiber.index > newIdx) {
12332 nextOldFiber = oldFiber;
12333 oldFiber = null;
12334 } else {
12335 nextOldFiber = oldFiber.sibling;
12336 }
12337 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
12338 if (newFiber === null) {
12339 // TODO: This breaks on empty slots like null children. That's
12340 // unfortunate because it triggers the slow path all the time. We need
12341 // a better way to communicate whether this was a miss or null,
12342 // boolean, undefined, etc.
12343 if (oldFiber === null) {
12344 oldFiber = nextOldFiber;
12345 }
12346 break;
12347 }
12348 if (shouldTrackSideEffects) {
12349 if (oldFiber && newFiber.alternate === null) {
12350 // We matched the slot, but we didn't reuse the existing fiber, so we
12351 // need to delete the existing child.
12352 deleteChild(returnFiber, oldFiber);
12353 }
12354 }
12355 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
12356 if (previousNewFiber === null) {
12357 // TODO: Move out of the loop. This only happens for the first run.
12358 resultingFirstChild = newFiber;
12359 } else {
12360 // TODO: Defer siblings if we're not at the right index for this slot.
12361 // I.e. if we had null values before, then we want to defer this
12362 // for each null value. However, we also don't want to call updateSlot
12363 // with the previous one.
12364 previousNewFiber.sibling = newFiber;
12365 }
12366 previousNewFiber = newFiber;
12367 oldFiber = nextOldFiber;
12368 }
12369
12370 if (newIdx === newChildren.length) {
12371 // We've reached the end of the new children. We can delete the rest.
12372 deleteRemainingChildren(returnFiber, oldFiber);
12373 return resultingFirstChild;
12374 }
12375
12376 if (oldFiber === null) {
12377 // If we don't have any more existing children we can choose a fast path
12378 // since the rest will all be insertions.
12379 for (; newIdx < newChildren.length; newIdx++) {
12380 var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
12381 if (!_newFiber) {
12382 continue;
12383 }
12384 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
12385 if (previousNewFiber === null) {
12386 // TODO: Move out of the loop. This only happens for the first run.
12387 resultingFirstChild = _newFiber;
12388 } else {
12389 previousNewFiber.sibling = _newFiber;
12390 }
12391 previousNewFiber = _newFiber;
12392 }
12393 return resultingFirstChild;
12394 }
12395
12396 // Add all children to a key map for quick lookups.
12397 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
12398
12399 // Keep scanning and use the map to restore deleted items as moves.
12400 for (; newIdx < newChildren.length; newIdx++) {
12401 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
12402 if (_newFiber2) {
12403 if (shouldTrackSideEffects) {
12404 if (_newFiber2.alternate !== null) {
12405 // The new fiber is a work in progress, but if there exists a
12406 // current, that means that we reused the fiber. We need to delete
12407 // it from the child list so that we don't add it to the deletion
12408 // list.
12409 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
12410 }
12411 }
12412 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
12413 if (previousNewFiber === null) {
12414 resultingFirstChild = _newFiber2;
12415 } else {
12416 previousNewFiber.sibling = _newFiber2;
12417 }
12418 previousNewFiber = _newFiber2;
12419 }
12420 }
12421
12422 if (shouldTrackSideEffects) {
12423 // Any existing children that weren't consumed above were deleted. We need
12424 // to add them to the deletion list.
12425 existingChildren.forEach(function (child) {
12426 return deleteChild(returnFiber, child);
12427 });
12428 }
12429
12430 return resultingFirstChild;
12431 }
12432
12433 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
12434 // This is the same implementation as reconcileChildrenArray(),
12435 // but using the iterator instead.
12436
12437 var iteratorFn = getIteratorFn(newChildrenIterable);
12438 !(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;
12439
12440 {
12441 // We don't support rendering Generators because it's a mutation.
12442 // See https://github.com/facebook/react/issues/12995
12443 if (typeof Symbol === 'function' &&
12444 // $FlowFixMe Flow doesn't know about toStringTag
12445 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
12446 !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;
12447 didWarnAboutGenerators = true;
12448 }
12449
12450 // Warn about using Maps as children
12451 if (newChildrenIterable.entries === iteratorFn) {
12452 !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;
12453 didWarnAboutMaps = true;
12454 }
12455
12456 // First, validate keys.
12457 // We'll get a different iterator later for the main pass.
12458 var _newChildren = iteratorFn.call(newChildrenIterable);
12459 if (_newChildren) {
12460 var knownKeys = null;
12461 var _step = _newChildren.next();
12462 for (; !_step.done; _step = _newChildren.next()) {
12463 var child = _step.value;
12464 knownKeys = warnOnInvalidKey(child, knownKeys);
12465 }
12466 }
12467 }
12468
12469 var newChildren = iteratorFn.call(newChildrenIterable);
12470 !(newChildren != null) ? invariant(false, 'An iterable object provided no iterator.') : void 0;
12471
12472 var resultingFirstChild = null;
12473 var previousNewFiber = null;
12474
12475 var oldFiber = currentFirstChild;
12476 var lastPlacedIndex = 0;
12477 var newIdx = 0;
12478 var nextOldFiber = null;
12479
12480 var step = newChildren.next();
12481 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
12482 if (oldFiber.index > newIdx) {
12483 nextOldFiber = oldFiber;
12484 oldFiber = null;
12485 } else {
12486 nextOldFiber = oldFiber.sibling;
12487 }
12488 var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
12489 if (newFiber === null) {
12490 // TODO: This breaks on empty slots like null children. That's
12491 // unfortunate because it triggers the slow path all the time. We need
12492 // a better way to communicate whether this was a miss or null,
12493 // boolean, undefined, etc.
12494 if (!oldFiber) {
12495 oldFiber = nextOldFiber;
12496 }
12497 break;
12498 }
12499 if (shouldTrackSideEffects) {
12500 if (oldFiber && newFiber.alternate === null) {
12501 // We matched the slot, but we didn't reuse the existing fiber, so we
12502 // need to delete the existing child.
12503 deleteChild(returnFiber, oldFiber);
12504 }
12505 }
12506 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
12507 if (previousNewFiber === null) {
12508 // TODO: Move out of the loop. This only happens for the first run.
12509 resultingFirstChild = newFiber;
12510 } else {
12511 // TODO: Defer siblings if we're not at the right index for this slot.
12512 // I.e. if we had null values before, then we want to defer this
12513 // for each null value. However, we also don't want to call updateSlot
12514 // with the previous one.
12515 previousNewFiber.sibling = newFiber;
12516 }
12517 previousNewFiber = newFiber;
12518 oldFiber = nextOldFiber;
12519 }
12520
12521 if (step.done) {
12522 // We've reached the end of the new children. We can delete the rest.
12523 deleteRemainingChildren(returnFiber, oldFiber);
12524 return resultingFirstChild;
12525 }
12526
12527 if (oldFiber === null) {
12528 // If we don't have any more existing children we can choose a fast path
12529 // since the rest will all be insertions.
12530 for (; !step.done; newIdx++, step = newChildren.next()) {
12531 var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
12532 if (_newFiber3 === null) {
12533 continue;
12534 }
12535 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
12536 if (previousNewFiber === null) {
12537 // TODO: Move out of the loop. This only happens for the first run.
12538 resultingFirstChild = _newFiber3;
12539 } else {
12540 previousNewFiber.sibling = _newFiber3;
12541 }
12542 previousNewFiber = _newFiber3;
12543 }
12544 return resultingFirstChild;
12545 }
12546
12547 // Add all children to a key map for quick lookups.
12548 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
12549
12550 // Keep scanning and use the map to restore deleted items as moves.
12551 for (; !step.done; newIdx++, step = newChildren.next()) {
12552 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
12553 if (_newFiber4 !== null) {
12554 if (shouldTrackSideEffects) {
12555 if (_newFiber4.alternate !== null) {
12556 // The new fiber is a work in progress, but if there exists a
12557 // current, that means that we reused the fiber. We need to delete
12558 // it from the child list so that we don't add it to the deletion
12559 // list.
12560 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
12561 }
12562 }
12563 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
12564 if (previousNewFiber === null) {
12565 resultingFirstChild = _newFiber4;
12566 } else {
12567 previousNewFiber.sibling = _newFiber4;
12568 }
12569 previousNewFiber = _newFiber4;
12570 }
12571 }
12572
12573 if (shouldTrackSideEffects) {
12574 // Any existing children that weren't consumed above were deleted. We need
12575 // to add them to the deletion list.
12576 existingChildren.forEach(function (child) {
12577 return deleteChild(returnFiber, child);
12578 });
12579 }
12580
12581 return resultingFirstChild;
12582 }
12583
12584 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
12585 // There's no need to check for keys on text nodes since we don't have a
12586 // way to define them.
12587 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
12588 // We already have an existing node so let's just update it and delete
12589 // the rest.
12590 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
12591 var existing = useFiber(currentFirstChild, textContent, expirationTime);
12592 existing.return = returnFiber;
12593 return existing;
12594 }
12595 // The existing first child is not a text node so we need to create one
12596 // and delete the existing ones.
12597 deleteRemainingChildren(returnFiber, currentFirstChild);
12598 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
12599 created.return = returnFiber;
12600 return created;
12601 }
12602
12603 function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
12604 var key = element.key;
12605 var child = currentFirstChild;
12606 while (child !== null) {
12607 // TODO: If key === null and child.key === null, then this only applies to
12608 // the first item in the list.
12609 if (child.key === key) {
12610 if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.elementType === element.type) {
12611 deleteRemainingChildren(returnFiber, child.sibling);
12612 var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
12613 existing.ref = coerceRef(returnFiber, child, element);
12614 existing.return = returnFiber;
12615 {
12616 existing._debugSource = element._source;
12617 existing._debugOwner = element._owner;
12618 }
12619 return existing;
12620 } else {
12621 deleteRemainingChildren(returnFiber, child);
12622 break;
12623 }
12624 } else {
12625 deleteChild(returnFiber, child);
12626 }
12627 child = child.sibling;
12628 }
12629
12630 if (element.type === REACT_FRAGMENT_TYPE) {
12631 var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
12632 created.return = returnFiber;
12633 return created;
12634 } else {
12635 var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
12636 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
12637 _created4.return = returnFiber;
12638 return _created4;
12639 }
12640 }
12641
12642 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
12643 var key = portal.key;
12644 var child = currentFirstChild;
12645 while (child !== null) {
12646 // TODO: If key === null and child.key === null, then this only applies to
12647 // the first item in the list.
12648 if (child.key === key) {
12649 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
12650 deleteRemainingChildren(returnFiber, child.sibling);
12651 var existing = useFiber(child, portal.children || [], expirationTime);
12652 existing.return = returnFiber;
12653 return existing;
12654 } else {
12655 deleteRemainingChildren(returnFiber, child);
12656 break;
12657 }
12658 } else {
12659 deleteChild(returnFiber, child);
12660 }
12661 child = child.sibling;
12662 }
12663
12664 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
12665 created.return = returnFiber;
12666 return created;
12667 }
12668
12669 // This API will tag the children with the side-effect of the reconciliation
12670 // itself. They will be added to the side-effect list as we pass through the
12671 // children and the parent.
12672 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
12673 // This function is not recursive.
12674 // If the top level item is an array, we treat it as a set of children,
12675 // not as a fragment. Nested arrays on the other hand will be treated as
12676 // fragment nodes. Recursion happens at the normal flow.
12677
12678 // Handle top level unkeyed fragments as if they were arrays.
12679 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
12680 // We treat the ambiguous cases above the same.
12681 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
12682 if (isUnkeyedTopLevelFragment) {
12683 newChild = newChild.props.children;
12684 }
12685
12686 // Handle object types
12687 var isObject = typeof newChild === 'object' && newChild !== null;
12688
12689 if (isObject) {
12690 switch (newChild.$$typeof) {
12691 case REACT_ELEMENT_TYPE:
12692 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
12693 case REACT_PORTAL_TYPE:
12694 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
12695 }
12696 }
12697
12698 if (typeof newChild === 'string' || typeof newChild === 'number') {
12699 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
12700 }
12701
12702 if (isArray(newChild)) {
12703 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
12704 }
12705
12706 if (getIteratorFn(newChild)) {
12707 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
12708 }
12709
12710 if (isObject) {
12711 throwOnInvalidObjectType(returnFiber, newChild);
12712 }
12713
12714 {
12715 if (typeof newChild === 'function') {
12716 warnOnFunctionType();
12717 }
12718 }
12719 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
12720 // If the new child is undefined, and the return fiber is a composite
12721 // component, throw an error. If Fiber return types are disabled,
12722 // we already threw above.
12723 switch (returnFiber.tag) {
12724 case ClassComponent:
12725 {
12726 {
12727 var instance = returnFiber.stateNode;
12728 if (instance.render._isMockFunction) {
12729 // We allow auto-mocks to proceed as if they're returning null.
12730 break;
12731 }
12732 }
12733 }
12734 // Intentionally fall through to the next case, which handles both
12735 // functions and classes
12736 // eslint-disable-next-lined no-fallthrough
12737 case FunctionComponent:
12738 {
12739 var Component = returnFiber.type;
12740 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');
12741 }
12742 }
12743 }
12744
12745 // Remaining cases are all treated as empty.
12746 return deleteRemainingChildren(returnFiber, currentFirstChild);
12747 }
12748
12749 return reconcileChildFibers;
12750}
12751
12752var reconcileChildFibers = ChildReconciler(true);
12753var mountChildFibers = ChildReconciler(false);
12754
12755function cloneChildFibers(current$$1, workInProgress) {
12756 !(current$$1 === null || workInProgress.child === current$$1.child) ? invariant(false, 'Resuming work not yet implemented.') : void 0;
12757
12758 if (workInProgress.child === null) {
12759 return;
12760 }
12761
12762 var currentChild = workInProgress.child;
12763 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
12764 workInProgress.child = newChild;
12765
12766 newChild.return = workInProgress;
12767 while (currentChild.sibling !== null) {
12768 currentChild = currentChild.sibling;
12769 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
12770 newChild.return = workInProgress;
12771 }
12772 newChild.sibling = null;
12773}
12774
12775var NO_CONTEXT = {};
12776
12777var contextStackCursor$1 = createCursor(NO_CONTEXT);
12778var contextFiberStackCursor = createCursor(NO_CONTEXT);
12779var rootInstanceStackCursor = createCursor(NO_CONTEXT);
12780
12781function requiredContext(c) {
12782 !(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;
12783 return c;
12784}
12785
12786function getRootHostContainer() {
12787 var rootInstance = requiredContext(rootInstanceStackCursor.current);
12788 return rootInstance;
12789}
12790
12791function pushHostContainer(fiber, nextRootInstance) {
12792 // Push current root instance onto the stack;
12793 // This allows us to reset root when portals are popped.
12794 push(rootInstanceStackCursor, nextRootInstance, fiber);
12795 // Track the context and the Fiber that provided it.
12796 // This enables us to pop only Fibers that provide unique contexts.
12797 push(contextFiberStackCursor, fiber, fiber);
12798
12799 // Finally, we need to push the host context to the stack.
12800 // However, we can't just call getRootHostContext() and push it because
12801 // we'd have a different number of entries on the stack depending on
12802 // whether getRootHostContext() throws somewhere in renderer code or not.
12803 // So we push an empty value first. This lets us safely unwind on errors.
12804 push(contextStackCursor$1, NO_CONTEXT, fiber);
12805 var nextRootContext = getRootHostContext(nextRootInstance);
12806 // Now that we know this function doesn't throw, replace it.
12807 pop(contextStackCursor$1, fiber);
12808 push(contextStackCursor$1, nextRootContext, fiber);
12809}
12810
12811function popHostContainer(fiber) {
12812 pop(contextStackCursor$1, fiber);
12813 pop(contextFiberStackCursor, fiber);
12814 pop(rootInstanceStackCursor, fiber);
12815}
12816
12817function getHostContext() {
12818 var context = requiredContext(contextStackCursor$1.current);
12819 return context;
12820}
12821
12822function pushHostContext(fiber) {
12823 var rootInstance = requiredContext(rootInstanceStackCursor.current);
12824 var context = requiredContext(contextStackCursor$1.current);
12825 var nextContext = getChildHostContext(context, fiber.type, rootInstance);
12826
12827 // Don't push this Fiber's context unless it's unique.
12828 if (context === nextContext) {
12829 return;
12830 }
12831
12832 // Track the context and the Fiber that provided it.
12833 // This enables us to pop only Fibers that provide unique contexts.
12834 push(contextFiberStackCursor, fiber, fiber);
12835 push(contextStackCursor$1, nextContext, fiber);
12836}
12837
12838function popHostContext(fiber) {
12839 // Do not pop unless this Fiber provided the current context.
12840 // pushHostContext() only pushes Fibers that provide unique contexts.
12841 if (contextFiberStackCursor.current !== fiber) {
12842 return;
12843 }
12844
12845 pop(contextStackCursor$1, fiber);
12846 pop(contextFiberStackCursor, fiber);
12847}
12848
12849var NoEffect$1 = /* */0;
12850var UnmountSnapshot = /* */2;
12851var UnmountMutation = /* */4;
12852var MountMutation = /* */8;
12853var UnmountLayout = /* */16;
12854var MountLayout = /* */32;
12855var MountPassive = /* */64;
12856var UnmountPassive = /* */128;
12857
12858var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
12859
12860
12861var didWarnAboutMismatchedHooksForComponent = void 0;
12862{
12863 didWarnAboutMismatchedHooksForComponent = new Set();
12864}
12865
12866// These are set right before calling the component.
12867var renderExpirationTime = NoWork;
12868// The work-in-progress fiber. I've named it differently to distinguish it from
12869// the work-in-progress hook.
12870var currentlyRenderingFiber$1 = null;
12871
12872// Hooks are stored as a linked list on the fiber's memoizedState field. The
12873// current hook list is the list that belongs to the current fiber. The
12874// work-in-progress hook list is a new list that will be added to the
12875// work-in-progress fiber.
12876var currentHook = null;
12877var nextCurrentHook = null;
12878var firstWorkInProgressHook = null;
12879var workInProgressHook = null;
12880var nextWorkInProgressHook = null;
12881
12882var remainingExpirationTime = NoWork;
12883var componentUpdateQueue = null;
12884var sideEffectTag = 0;
12885
12886// Updates scheduled during render will trigger an immediate re-render at the
12887// end of the current pass. We can't store these updates on the normal queue,
12888// because if the work is aborted, they should be discarded. Because this is
12889// a relatively rare case, we also don't want to add an additional field to
12890// either the hook or queue object types. So we store them in a lazily create
12891// map of queue -> render-phase updates, which are discarded once the component
12892// completes without re-rendering.
12893
12894// Whether an update was scheduled during the currently executing render pass.
12895var didScheduleRenderPhaseUpdate = false;
12896// Lazily created map of render-phase updates
12897var renderPhaseUpdates = null;
12898// Counter to prevent infinite loops.
12899var numberOfReRenders = 0;
12900var RE_RENDER_LIMIT = 25;
12901
12902// In DEV, this is the name of the currently executing primitive hook
12903var currentHookNameInDev = null;
12904
12905// In DEV, this list ensures that hooks are called in the same order between renders.
12906// The list stores the order of hooks used during the initial render (mount).
12907// Subsequent renders (updates) reference this list.
12908var hookTypesDev = null;
12909var hookTypesUpdateIndexDev = -1;
12910
12911function mountHookTypesDev() {
12912 {
12913 var hookName = currentHookNameInDev;
12914
12915 if (hookTypesDev === null) {
12916 hookTypesDev = [hookName];
12917 } else {
12918 hookTypesDev.push(hookName);
12919 }
12920 }
12921}
12922
12923function updateHookTypesDev() {
12924 {
12925 var hookName = currentHookNameInDev;
12926
12927 if (hookTypesDev !== null) {
12928 hookTypesUpdateIndexDev++;
12929 if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
12930 warnOnHookMismatchInDev(hookName);
12931 }
12932 }
12933 }
12934}
12935
12936function warnOnHookMismatchInDev(currentHookName) {
12937 {
12938 var componentName = getComponentName(currentlyRenderingFiber$1.type);
12939 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
12940 didWarnAboutMismatchedHooksForComponent.add(componentName);
12941
12942 if (hookTypesDev !== null) {
12943 var table = '';
12944
12945 var secondColumnStart = 30;
12946
12947 for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
12948 var oldHookName = hookTypesDev[i];
12949 var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
12950
12951 var row = i + 1 + '. ' + oldHookName;
12952
12953 // Extra space so second column lines up
12954 // lol @ IE not supporting String#repeat
12955 while (row.length < secondColumnStart) {
12956 row += ' ';
12957 }
12958
12959 row += newHookName + '\n';
12960
12961 table += row;
12962 }
12963
12964 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);
12965 }
12966 }
12967 }
12968}
12969
12970function throwInvalidHookError() {
12971 invariant(false, 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.');
12972}
12973
12974function areHookInputsEqual(nextDeps, prevDeps) {
12975 if (prevDeps === null) {
12976 {
12977 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);
12978 }
12979 return false;
12980 }
12981
12982 {
12983 // Don't bother comparing lengths in prod because these arrays should be
12984 // passed inline.
12985 if (nextDeps.length !== prevDeps.length) {
12986 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(', ') + ']');
12987 }
12988 }
12989 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
12990 if (is(nextDeps[i], prevDeps[i])) {
12991 continue;
12992 }
12993 return false;
12994 }
12995 return true;
12996}
12997
12998function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) {
12999 renderExpirationTime = nextRenderExpirationTime;
13000 currentlyRenderingFiber$1 = workInProgress;
13001 nextCurrentHook = current !== null ? current.memoizedState : null;
13002
13003 {
13004 hookTypesDev = current !== null ? current._debugHookTypes : null;
13005 hookTypesUpdateIndexDev = -1;
13006 }
13007
13008 // The following should have already been reset
13009 // currentHook = null;
13010 // workInProgressHook = null;
13011
13012 // remainingExpirationTime = NoWork;
13013 // componentUpdateQueue = null;
13014
13015 // didScheduleRenderPhaseUpdate = false;
13016 // renderPhaseUpdates = null;
13017 // numberOfReRenders = 0;
13018 // sideEffectTag = 0;
13019
13020 // TODO Warn if no hooks are used at all during mount, then some are used during update.
13021 // Currently we will identify the update render as a mount because nextCurrentHook === null.
13022 // This is tricky because it's valid for certain types of components (e.g. React.lazy)
13023
13024 // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used.
13025 // Non-stateful hooks (e.g. context) don't get added to memoizedState,
13026 // so nextCurrentHook would be null during updates and mounts.
13027 {
13028 if (nextCurrentHook !== null) {
13029 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
13030 } else if (hookTypesDev !== null) {
13031 // This dispatcher handles an edge case where a component is updating,
13032 // but no stateful hooks have been used.
13033 // We want to match the production code behavior (which will use HooksDispatcherOnMount),
13034 // but with the extra DEV validation to ensure hooks ordering hasn't changed.
13035 // This dispatcher does that.
13036 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
13037 } else {
13038 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
13039 }
13040 }
13041
13042 var children = Component(props, refOrContext);
13043
13044 if (didScheduleRenderPhaseUpdate) {
13045 do {
13046 didScheduleRenderPhaseUpdate = false;
13047 numberOfReRenders += 1;
13048
13049 // Start over from the beginning of the list
13050 nextCurrentHook = current !== null ? current.memoizedState : null;
13051 nextWorkInProgressHook = firstWorkInProgressHook;
13052
13053 currentHook = null;
13054 workInProgressHook = null;
13055 componentUpdateQueue = null;
13056
13057 {
13058 // Also validate hook order for cascading updates.
13059 hookTypesUpdateIndexDev = -1;
13060 }
13061
13062 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
13063
13064 children = Component(props, refOrContext);
13065 } while (didScheduleRenderPhaseUpdate);
13066
13067 renderPhaseUpdates = null;
13068 numberOfReRenders = 0;
13069 }
13070
13071 // We can assume the previous dispatcher is always this one, since we set it
13072 // at the beginning of the render phase and there's no re-entrancy.
13073 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
13074
13075 var renderedWork = currentlyRenderingFiber$1;
13076
13077 renderedWork.memoizedState = firstWorkInProgressHook;
13078 renderedWork.expirationTime = remainingExpirationTime;
13079 renderedWork.updateQueue = componentUpdateQueue;
13080 renderedWork.effectTag |= sideEffectTag;
13081
13082 {
13083 renderedWork._debugHookTypes = hookTypesDev;
13084 }
13085
13086 // This check uses currentHook so that it works the same in DEV and prod bundles.
13087 // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
13088 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
13089
13090 renderExpirationTime = NoWork;
13091 currentlyRenderingFiber$1 = null;
13092
13093 currentHook = null;
13094 nextCurrentHook = null;
13095 firstWorkInProgressHook = null;
13096 workInProgressHook = null;
13097 nextWorkInProgressHook = null;
13098
13099 {
13100 currentHookNameInDev = null;
13101 hookTypesDev = null;
13102 hookTypesUpdateIndexDev = -1;
13103 }
13104
13105 remainingExpirationTime = NoWork;
13106 componentUpdateQueue = null;
13107 sideEffectTag = 0;
13108
13109 // These were reset above
13110 // didScheduleRenderPhaseUpdate = false;
13111 // renderPhaseUpdates = null;
13112 // numberOfReRenders = 0;
13113
13114 !!didRenderTooFewHooks ? invariant(false, 'Rendered fewer hooks than expected. This may be caused by an accidental early return statement.') : void 0;
13115
13116 return children;
13117}
13118
13119function bailoutHooks(current, workInProgress, expirationTime) {
13120 workInProgress.updateQueue = current.updateQueue;
13121 workInProgress.effectTag &= ~(Passive | Update);
13122 if (current.expirationTime <= expirationTime) {
13123 current.expirationTime = NoWork;
13124 }
13125}
13126
13127function resetHooks() {
13128 // We can assume the previous dispatcher is always this one, since we set it
13129 // at the beginning of the render phase and there's no re-entrancy.
13130 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
13131
13132 // This is used to reset the state of this module when a component throws.
13133 // It's also called inside mountIndeterminateComponent if we determine the
13134 // component is a module-style component.
13135 renderExpirationTime = NoWork;
13136 currentlyRenderingFiber$1 = null;
13137
13138 currentHook = null;
13139 nextCurrentHook = null;
13140 firstWorkInProgressHook = null;
13141 workInProgressHook = null;
13142 nextWorkInProgressHook = null;
13143
13144 {
13145 hookTypesDev = null;
13146 hookTypesUpdateIndexDev = -1;
13147
13148 currentHookNameInDev = null;
13149 }
13150
13151 remainingExpirationTime = NoWork;
13152 componentUpdateQueue = null;
13153 sideEffectTag = 0;
13154
13155 didScheduleRenderPhaseUpdate = false;
13156 renderPhaseUpdates = null;
13157 numberOfReRenders = 0;
13158}
13159
13160function mountWorkInProgressHook() {
13161 var hook = {
13162 memoizedState: null,
13163
13164 baseState: null,
13165 queue: null,
13166 baseUpdate: null,
13167
13168 next: null
13169 };
13170
13171 if (workInProgressHook === null) {
13172 // This is the first hook in the list
13173 firstWorkInProgressHook = workInProgressHook = hook;
13174 } else {
13175 // Append to the end of the list
13176 workInProgressHook = workInProgressHook.next = hook;
13177 }
13178 return workInProgressHook;
13179}
13180
13181function updateWorkInProgressHook() {
13182 // This function is used both for updates and for re-renders triggered by a
13183 // render phase update. It assumes there is either a current hook we can
13184 // clone, or a work-in-progress hook from a previous render pass that we can
13185 // use as a base. When we reach the end of the base list, we must switch to
13186 // the dispatcher used for mounts.
13187 if (nextWorkInProgressHook !== null) {
13188 // There's already a work-in-progress. Reuse it.
13189 workInProgressHook = nextWorkInProgressHook;
13190 nextWorkInProgressHook = workInProgressHook.next;
13191
13192 currentHook = nextCurrentHook;
13193 nextCurrentHook = currentHook !== null ? currentHook.next : null;
13194 } else {
13195 // Clone from the current hook.
13196 !(nextCurrentHook !== null) ? invariant(false, 'Rendered more hooks than during the previous render.') : void 0;
13197 currentHook = nextCurrentHook;
13198
13199 var newHook = {
13200 memoizedState: currentHook.memoizedState,
13201
13202 baseState: currentHook.baseState,
13203 queue: currentHook.queue,
13204 baseUpdate: currentHook.baseUpdate,
13205
13206 next: null
13207 };
13208
13209 if (workInProgressHook === null) {
13210 // This is the first hook in the list.
13211 workInProgressHook = firstWorkInProgressHook = newHook;
13212 } else {
13213 // Append to the end of the list.
13214 workInProgressHook = workInProgressHook.next = newHook;
13215 }
13216 nextCurrentHook = currentHook.next;
13217 }
13218 return workInProgressHook;
13219}
13220
13221function createFunctionComponentUpdateQueue() {
13222 return {
13223 lastEffect: null
13224 };
13225}
13226
13227function basicStateReducer(state, action) {
13228 return typeof action === 'function' ? action(state) : action;
13229}
13230
13231function mountReducer(reducer, initialArg, init) {
13232 var hook = mountWorkInProgressHook();
13233 var initialState = void 0;
13234 if (init !== undefined) {
13235 initialState = init(initialArg);
13236 } else {
13237 initialState = initialArg;
13238 }
13239 hook.memoizedState = hook.baseState = initialState;
13240 var queue = hook.queue = {
13241 last: null,
13242 dispatch: null,
13243 eagerReducer: reducer,
13244 eagerState: initialState
13245 };
13246 var dispatch = queue.dispatch = dispatchAction.bind(null,
13247 // Flow doesn't know this is non-null, but we do.
13248 currentlyRenderingFiber$1, queue);
13249 return [hook.memoizedState, dispatch];
13250}
13251
13252function updateReducer(reducer, initialArg, init) {
13253 var hook = updateWorkInProgressHook();
13254 var queue = hook.queue;
13255 !(queue !== null) ? invariant(false, 'Should have a queue. This is likely a bug in React. Please file an issue.') : void 0;
13256
13257 if (numberOfReRenders > 0) {
13258 // This is a re-render. Apply the new render phase updates to the previous
13259 var _dispatch = queue.dispatch;
13260 if (renderPhaseUpdates !== null) {
13261 // Render phase updates are stored in a map of queue -> linked list
13262 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
13263 if (firstRenderPhaseUpdate !== undefined) {
13264 renderPhaseUpdates.delete(queue);
13265 var newState = hook.memoizedState;
13266 var update = firstRenderPhaseUpdate;
13267 do {
13268 // Process this render phase update. We don't have to check the
13269 // priority because it will always be the same as the current
13270 // render's.
13271 var _action = update.action;
13272 newState = reducer(newState, _action);
13273 update = update.next;
13274 } while (update !== null);
13275
13276 // Mark that the fiber performed work, but only if the new state is
13277 // different from the current state.
13278 if (!is(newState, hook.memoizedState)) {
13279 markWorkInProgressReceivedUpdate();
13280 }
13281
13282 hook.memoizedState = newState;
13283 // Don't persist the state accumlated from the render phase updates to
13284 // the base state unless the queue is empty.
13285 // TODO: Not sure if this is the desired semantics, but it's what we
13286 // do for gDSFP. I can't remember why.
13287 if (hook.baseUpdate === queue.last) {
13288 hook.baseState = newState;
13289 }
13290
13291 queue.eagerReducer = reducer;
13292 queue.eagerState = newState;
13293
13294 return [newState, _dispatch];
13295 }
13296 }
13297 return [hook.memoizedState, _dispatch];
13298 }
13299
13300 // The last update in the entire queue
13301 var last = queue.last;
13302 // The last update that is part of the base state.
13303 var baseUpdate = hook.baseUpdate;
13304 var baseState = hook.baseState;
13305
13306 // Find the first unprocessed update.
13307 var first = void 0;
13308 if (baseUpdate !== null) {
13309 if (last !== null) {
13310 // For the first update, the queue is a circular linked list where
13311 // `queue.last.next = queue.first`. Once the first update commits, and
13312 // the `baseUpdate` is no longer empty, we can unravel the list.
13313 last.next = null;
13314 }
13315 first = baseUpdate.next;
13316 } else {
13317 first = last !== null ? last.next : null;
13318 }
13319 if (first !== null) {
13320 var _newState = baseState;
13321 var newBaseState = null;
13322 var newBaseUpdate = null;
13323 var prevUpdate = baseUpdate;
13324 var _update = first;
13325 var didSkip = false;
13326 do {
13327 var updateExpirationTime = _update.expirationTime;
13328 if (updateExpirationTime < renderExpirationTime) {
13329 // Priority is insufficient. Skip this update. If this is the first
13330 // skipped update, the previous update/state is the new base
13331 // update/state.
13332 if (!didSkip) {
13333 didSkip = true;
13334 newBaseUpdate = prevUpdate;
13335 newBaseState = _newState;
13336 }
13337 // Update the remaining priority in the queue.
13338 if (updateExpirationTime > remainingExpirationTime) {
13339 remainingExpirationTime = updateExpirationTime;
13340 }
13341 } else {
13342 // Process this update.
13343 if (_update.eagerReducer === reducer) {
13344 // If this update was processed eagerly, and its reducer matches the
13345 // current reducer, we can use the eagerly computed state.
13346 _newState = _update.eagerState;
13347 } else {
13348 var _action2 = _update.action;
13349 _newState = reducer(_newState, _action2);
13350 }
13351 }
13352 prevUpdate = _update;
13353 _update = _update.next;
13354 } while (_update !== null && _update !== first);
13355
13356 if (!didSkip) {
13357 newBaseUpdate = prevUpdate;
13358 newBaseState = _newState;
13359 }
13360
13361 // Mark that the fiber performed work, but only if the new state is
13362 // different from the current state.
13363 if (!is(_newState, hook.memoizedState)) {
13364 markWorkInProgressReceivedUpdate();
13365 }
13366
13367 hook.memoizedState = _newState;
13368 hook.baseUpdate = newBaseUpdate;
13369 hook.baseState = newBaseState;
13370
13371 queue.eagerReducer = reducer;
13372 queue.eagerState = _newState;
13373 }
13374
13375 var dispatch = queue.dispatch;
13376 return [hook.memoizedState, dispatch];
13377}
13378
13379function mountState(initialState) {
13380 var hook = mountWorkInProgressHook();
13381 if (typeof initialState === 'function') {
13382 initialState = initialState();
13383 }
13384 hook.memoizedState = hook.baseState = initialState;
13385 var queue = hook.queue = {
13386 last: null,
13387 dispatch: null,
13388 eagerReducer: basicStateReducer,
13389 eagerState: initialState
13390 };
13391 var dispatch = queue.dispatch = dispatchAction.bind(null,
13392 // Flow doesn't know this is non-null, but we do.
13393 currentlyRenderingFiber$1, queue);
13394 return [hook.memoizedState, dispatch];
13395}
13396
13397function updateState(initialState) {
13398 return updateReducer(basicStateReducer, initialState);
13399}
13400
13401function pushEffect(tag, create, destroy, deps) {
13402 var effect = {
13403 tag: tag,
13404 create: create,
13405 destroy: destroy,
13406 deps: deps,
13407 // Circular
13408 next: null
13409 };
13410 if (componentUpdateQueue === null) {
13411 componentUpdateQueue = createFunctionComponentUpdateQueue();
13412 componentUpdateQueue.lastEffect = effect.next = effect;
13413 } else {
13414 var _lastEffect = componentUpdateQueue.lastEffect;
13415 if (_lastEffect === null) {
13416 componentUpdateQueue.lastEffect = effect.next = effect;
13417 } else {
13418 var firstEffect = _lastEffect.next;
13419 _lastEffect.next = effect;
13420 effect.next = firstEffect;
13421 componentUpdateQueue.lastEffect = effect;
13422 }
13423 }
13424 return effect;
13425}
13426
13427function mountRef(initialValue) {
13428 var hook = mountWorkInProgressHook();
13429 var ref = { current: initialValue };
13430 {
13431 Object.seal(ref);
13432 }
13433 hook.memoizedState = ref;
13434 return ref;
13435}
13436
13437function updateRef(initialValue) {
13438 var hook = updateWorkInProgressHook();
13439 return hook.memoizedState;
13440}
13441
13442function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
13443 var hook = mountWorkInProgressHook();
13444 var nextDeps = deps === undefined ? null : deps;
13445 sideEffectTag |= fiberEffectTag;
13446 hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps);
13447}
13448
13449function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
13450 var hook = updateWorkInProgressHook();
13451 var nextDeps = deps === undefined ? null : deps;
13452 var destroy = undefined;
13453
13454 if (currentHook !== null) {
13455 var prevEffect = currentHook.memoizedState;
13456 destroy = prevEffect.destroy;
13457 if (nextDeps !== null) {
13458 var prevDeps = prevEffect.deps;
13459 if (areHookInputsEqual(nextDeps, prevDeps)) {
13460 pushEffect(NoEffect$1, create, destroy, nextDeps);
13461 return;
13462 }
13463 }
13464 }
13465
13466 sideEffectTag |= fiberEffectTag;
13467 hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps);
13468}
13469
13470function mountEffect(create, deps) {
13471 return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
13472}
13473
13474function updateEffect(create, deps) {
13475 return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
13476}
13477
13478function mountLayoutEffect(create, deps) {
13479 return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
13480}
13481
13482function updateLayoutEffect(create, deps) {
13483 return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
13484}
13485
13486function imperativeHandleEffect(create, ref) {
13487 if (typeof ref === 'function') {
13488 var refCallback = ref;
13489 var _inst = create();
13490 refCallback(_inst);
13491 return function () {
13492 refCallback(null);
13493 };
13494 } else if (ref !== null && ref !== undefined) {
13495 var refObject = ref;
13496 {
13497 !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;
13498 }
13499 var _inst2 = create();
13500 refObject.current = _inst2;
13501 return function () {
13502 refObject.current = null;
13503 };
13504 }
13505}
13506
13507function mountImperativeHandle(ref, create, deps) {
13508 {
13509 !(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;
13510 }
13511
13512 // TODO: If deps are provided, should we skip comparing the ref itself?
13513 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
13514
13515 return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
13516}
13517
13518function updateImperativeHandle(ref, create, deps) {
13519 {
13520 !(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;
13521 }
13522
13523 // TODO: If deps are provided, should we skip comparing the ref itself?
13524 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
13525
13526 return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
13527}
13528
13529function mountDebugValue(value, formatterFn) {
13530 // This hook is normally a no-op.
13531 // The react-debug-hooks package injects its own implementation
13532 // so that e.g. DevTools can display custom hook values.
13533}
13534
13535var updateDebugValue = mountDebugValue;
13536
13537function mountCallback(callback, deps) {
13538 var hook = mountWorkInProgressHook();
13539 var nextDeps = deps === undefined ? null : deps;
13540 hook.memoizedState = [callback, nextDeps];
13541 return callback;
13542}
13543
13544function updateCallback(callback, deps) {
13545 var hook = updateWorkInProgressHook();
13546 var nextDeps = deps === undefined ? null : deps;
13547 var prevState = hook.memoizedState;
13548 if (prevState !== null) {
13549 if (nextDeps !== null) {
13550 var prevDeps = prevState[1];
13551 if (areHookInputsEqual(nextDeps, prevDeps)) {
13552 return prevState[0];
13553 }
13554 }
13555 }
13556 hook.memoizedState = [callback, nextDeps];
13557 return callback;
13558}
13559
13560function mountMemo(nextCreate, deps) {
13561 var hook = mountWorkInProgressHook();
13562 var nextDeps = deps === undefined ? null : deps;
13563 var nextValue = nextCreate();
13564 hook.memoizedState = [nextValue, nextDeps];
13565 return nextValue;
13566}
13567
13568function updateMemo(nextCreate, deps) {
13569 var hook = updateWorkInProgressHook();
13570 var nextDeps = deps === undefined ? null : deps;
13571 var prevState = hook.memoizedState;
13572 if (prevState !== null) {
13573 // Assume these are defined. If they're not, areHookInputsEqual will warn.
13574 if (nextDeps !== null) {
13575 var prevDeps = prevState[1];
13576 if (areHookInputsEqual(nextDeps, prevDeps)) {
13577 return prevState[0];
13578 }
13579 }
13580 }
13581 var nextValue = nextCreate();
13582 hook.memoizedState = [nextValue, nextDeps];
13583 return nextValue;
13584}
13585
13586// in a test-like environment, we want to warn if dispatchAction()
13587// is called outside of a batchedUpdates/TestUtils.act(...) call.
13588var shouldWarnForUnbatchedSetState = false;
13589
13590{
13591 // jest isn't a 'global', it's just exposed to tests via a wrapped function
13592 // further, this isn't a test file, so flow doesn't recognize the symbol. So...
13593 // $FlowExpectedError - because requirements don't give a damn about your type sigs.
13594 if ('undefined' !== typeof jest) {
13595 shouldWarnForUnbatchedSetState = true;
13596 }
13597}
13598
13599function dispatchAction(fiber, queue, action) {
13600 !(numberOfReRenders < RE_RENDER_LIMIT) ? invariant(false, 'Too many re-renders. React limits the number of renders to prevent an infinite loop.') : void 0;
13601
13602 {
13603 !(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;
13604 }
13605
13606 var alternate = fiber.alternate;
13607 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
13608 // This is a render phase update. Stash it in a lazily-created map of
13609 // queue -> linked list of updates. After this render pass, we'll restart
13610 // and apply the stashed updates on top of the work-in-progress hook.
13611 didScheduleRenderPhaseUpdate = true;
13612 var update = {
13613 expirationTime: renderExpirationTime,
13614 action: action,
13615 eagerReducer: null,
13616 eagerState: null,
13617 next: null
13618 };
13619 if (renderPhaseUpdates === null) {
13620 renderPhaseUpdates = new Map();
13621 }
13622 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
13623 if (firstRenderPhaseUpdate === undefined) {
13624 renderPhaseUpdates.set(queue, update);
13625 } else {
13626 // Append the update to the end of the list.
13627 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
13628 while (lastRenderPhaseUpdate.next !== null) {
13629 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
13630 }
13631 lastRenderPhaseUpdate.next = update;
13632 }
13633 } else {
13634 flushPassiveEffects();
13635
13636 var currentTime = requestCurrentTime();
13637 var _expirationTime = computeExpirationForFiber(currentTime, fiber);
13638
13639 var _update2 = {
13640 expirationTime: _expirationTime,
13641 action: action,
13642 eagerReducer: null,
13643 eagerState: null,
13644 next: null
13645 };
13646
13647 // Append the update to the end of the list.
13648 var _last = queue.last;
13649 if (_last === null) {
13650 // This is the first update. Create a circular list.
13651 _update2.next = _update2;
13652 } else {
13653 var first = _last.next;
13654 if (first !== null) {
13655 // Still circular.
13656 _update2.next = first;
13657 }
13658 _last.next = _update2;
13659 }
13660 queue.last = _update2;
13661
13662 if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
13663 // The queue is currently empty, which means we can eagerly compute the
13664 // next state before entering the render phase. If the new state is the
13665 // same as the current state, we may be able to bail out entirely.
13666 var _eagerReducer = queue.eagerReducer;
13667 if (_eagerReducer !== null) {
13668 var prevDispatcher = void 0;
13669 {
13670 prevDispatcher = ReactCurrentDispatcher$1.current;
13671 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13672 }
13673 try {
13674 var currentState = queue.eagerState;
13675 var _eagerState = _eagerReducer(currentState, action);
13676 // Stash the eagerly computed state, and the reducer used to compute
13677 // it, on the update object. If the reducer hasn't changed by the
13678 // time we enter the render phase, then the eager state can be used
13679 // without calling the reducer again.
13680 _update2.eagerReducer = _eagerReducer;
13681 _update2.eagerState = _eagerState;
13682 if (is(_eagerState, currentState)) {
13683 // Fast path. We can bail out without scheduling React to re-render.
13684 // It's still possible that we'll need to rebase this update later,
13685 // if the component re-renders for a different reason and by that
13686 // time the reducer has changed.
13687 return;
13688 }
13689 } catch (error) {
13690 // Suppress the error. It will throw again in the render phase.
13691 } finally {
13692 {
13693 ReactCurrentDispatcher$1.current = prevDispatcher;
13694 }
13695 }
13696 }
13697 }
13698 {
13699 if (shouldWarnForUnbatchedSetState === true) {
13700 warnIfNotCurrentlyBatchingInDev(fiber);
13701 }
13702 }
13703 scheduleWork(fiber, _expirationTime);
13704 }
13705}
13706
13707var ContextOnlyDispatcher = {
13708 readContext: readContext,
13709
13710 useCallback: throwInvalidHookError,
13711 useContext: throwInvalidHookError,
13712 useEffect: throwInvalidHookError,
13713 useImperativeHandle: throwInvalidHookError,
13714 useLayoutEffect: throwInvalidHookError,
13715 useMemo: throwInvalidHookError,
13716 useReducer: throwInvalidHookError,
13717 useRef: throwInvalidHookError,
13718 useState: throwInvalidHookError,
13719 useDebugValue: throwInvalidHookError
13720};
13721
13722var HooksDispatcherOnMountInDEV = null;
13723var HooksDispatcherOnMountWithHookTypesInDEV = null;
13724var HooksDispatcherOnUpdateInDEV = null;
13725var InvalidNestedHooksDispatcherOnMountInDEV = null;
13726var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
13727
13728{
13729 var warnInvalidContextAccess = function () {
13730 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().');
13731 };
13732
13733 var warnInvalidHookAccess = function () {
13734 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');
13735 };
13736
13737 HooksDispatcherOnMountInDEV = {
13738 readContext: function (context, observedBits) {
13739 return readContext(context, observedBits);
13740 },
13741 useCallback: function (callback, deps) {
13742 currentHookNameInDev = 'useCallback';
13743 mountHookTypesDev();
13744 return mountCallback(callback, deps);
13745 },
13746 useContext: function (context, observedBits) {
13747 currentHookNameInDev = 'useContext';
13748 mountHookTypesDev();
13749 return readContext(context, observedBits);
13750 },
13751 useEffect: function (create, deps) {
13752 currentHookNameInDev = 'useEffect';
13753 mountHookTypesDev();
13754 return mountEffect(create, deps);
13755 },
13756 useImperativeHandle: function (ref, create, deps) {
13757 currentHookNameInDev = 'useImperativeHandle';
13758 mountHookTypesDev();
13759 return mountImperativeHandle(ref, create, deps);
13760 },
13761 useLayoutEffect: function (create, deps) {
13762 currentHookNameInDev = 'useLayoutEffect';
13763 mountHookTypesDev();
13764 return mountLayoutEffect(create, deps);
13765 },
13766 useMemo: function (create, deps) {
13767 currentHookNameInDev = 'useMemo';
13768 mountHookTypesDev();
13769 var prevDispatcher = ReactCurrentDispatcher$1.current;
13770 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13771 try {
13772 return mountMemo(create, deps);
13773 } finally {
13774 ReactCurrentDispatcher$1.current = prevDispatcher;
13775 }
13776 },
13777 useReducer: function (reducer, initialArg, init) {
13778 currentHookNameInDev = 'useReducer';
13779 mountHookTypesDev();
13780 var prevDispatcher = ReactCurrentDispatcher$1.current;
13781 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13782 try {
13783 return mountReducer(reducer, initialArg, init);
13784 } finally {
13785 ReactCurrentDispatcher$1.current = prevDispatcher;
13786 }
13787 },
13788 useRef: function (initialValue) {
13789 currentHookNameInDev = 'useRef';
13790 mountHookTypesDev();
13791 return mountRef(initialValue);
13792 },
13793 useState: function (initialState) {
13794 currentHookNameInDev = 'useState';
13795 mountHookTypesDev();
13796 var prevDispatcher = ReactCurrentDispatcher$1.current;
13797 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13798 try {
13799 return mountState(initialState);
13800 } finally {
13801 ReactCurrentDispatcher$1.current = prevDispatcher;
13802 }
13803 },
13804 useDebugValue: function (value, formatterFn) {
13805 currentHookNameInDev = 'useDebugValue';
13806 mountHookTypesDev();
13807 return mountDebugValue(value, formatterFn);
13808 }
13809 };
13810
13811 HooksDispatcherOnMountWithHookTypesInDEV = {
13812 readContext: function (context, observedBits) {
13813 return readContext(context, observedBits);
13814 },
13815 useCallback: function (callback, deps) {
13816 currentHookNameInDev = 'useCallback';
13817 updateHookTypesDev();
13818 return mountCallback(callback, deps);
13819 },
13820 useContext: function (context, observedBits) {
13821 currentHookNameInDev = 'useContext';
13822 updateHookTypesDev();
13823 return readContext(context, observedBits);
13824 },
13825 useEffect: function (create, deps) {
13826 currentHookNameInDev = 'useEffect';
13827 updateHookTypesDev();
13828 return mountEffect(create, deps);
13829 },
13830 useImperativeHandle: function (ref, create, deps) {
13831 currentHookNameInDev = 'useImperativeHandle';
13832 updateHookTypesDev();
13833 return mountImperativeHandle(ref, create, deps);
13834 },
13835 useLayoutEffect: function (create, deps) {
13836 currentHookNameInDev = 'useLayoutEffect';
13837 updateHookTypesDev();
13838 return mountLayoutEffect(create, deps);
13839 },
13840 useMemo: function (create, deps) {
13841 currentHookNameInDev = 'useMemo';
13842 updateHookTypesDev();
13843 var prevDispatcher = ReactCurrentDispatcher$1.current;
13844 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13845 try {
13846 return mountMemo(create, deps);
13847 } finally {
13848 ReactCurrentDispatcher$1.current = prevDispatcher;
13849 }
13850 },
13851 useReducer: function (reducer, initialArg, init) {
13852 currentHookNameInDev = 'useReducer';
13853 updateHookTypesDev();
13854 var prevDispatcher = ReactCurrentDispatcher$1.current;
13855 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13856 try {
13857 return mountReducer(reducer, initialArg, init);
13858 } finally {
13859 ReactCurrentDispatcher$1.current = prevDispatcher;
13860 }
13861 },
13862 useRef: function (initialValue) {
13863 currentHookNameInDev = 'useRef';
13864 updateHookTypesDev();
13865 return mountRef(initialValue);
13866 },
13867 useState: function (initialState) {
13868 currentHookNameInDev = 'useState';
13869 updateHookTypesDev();
13870 var prevDispatcher = ReactCurrentDispatcher$1.current;
13871 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13872 try {
13873 return mountState(initialState);
13874 } finally {
13875 ReactCurrentDispatcher$1.current = prevDispatcher;
13876 }
13877 },
13878 useDebugValue: function (value, formatterFn) {
13879 currentHookNameInDev = 'useDebugValue';
13880 updateHookTypesDev();
13881 return mountDebugValue(value, formatterFn);
13882 }
13883 };
13884
13885 HooksDispatcherOnUpdateInDEV = {
13886 readContext: function (context, observedBits) {
13887 return readContext(context, observedBits);
13888 },
13889 useCallback: function (callback, deps) {
13890 currentHookNameInDev = 'useCallback';
13891 updateHookTypesDev();
13892 return updateCallback(callback, deps);
13893 },
13894 useContext: function (context, observedBits) {
13895 currentHookNameInDev = 'useContext';
13896 updateHookTypesDev();
13897 return readContext(context, observedBits);
13898 },
13899 useEffect: function (create, deps) {
13900 currentHookNameInDev = 'useEffect';
13901 updateHookTypesDev();
13902 return updateEffect(create, deps);
13903 },
13904 useImperativeHandle: function (ref, create, deps) {
13905 currentHookNameInDev = 'useImperativeHandle';
13906 updateHookTypesDev();
13907 return updateImperativeHandle(ref, create, deps);
13908 },
13909 useLayoutEffect: function (create, deps) {
13910 currentHookNameInDev = 'useLayoutEffect';
13911 updateHookTypesDev();
13912 return updateLayoutEffect(create, deps);
13913 },
13914 useMemo: function (create, deps) {
13915 currentHookNameInDev = 'useMemo';
13916 updateHookTypesDev();
13917 var prevDispatcher = ReactCurrentDispatcher$1.current;
13918 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13919 try {
13920 return updateMemo(create, deps);
13921 } finally {
13922 ReactCurrentDispatcher$1.current = prevDispatcher;
13923 }
13924 },
13925 useReducer: function (reducer, initialArg, init) {
13926 currentHookNameInDev = 'useReducer';
13927 updateHookTypesDev();
13928 var prevDispatcher = ReactCurrentDispatcher$1.current;
13929 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13930 try {
13931 return updateReducer(reducer, initialArg, init);
13932 } finally {
13933 ReactCurrentDispatcher$1.current = prevDispatcher;
13934 }
13935 },
13936 useRef: function (initialValue) {
13937 currentHookNameInDev = 'useRef';
13938 updateHookTypesDev();
13939 return updateRef(initialValue);
13940 },
13941 useState: function (initialState) {
13942 currentHookNameInDev = 'useState';
13943 updateHookTypesDev();
13944 var prevDispatcher = ReactCurrentDispatcher$1.current;
13945 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13946 try {
13947 return updateState(initialState);
13948 } finally {
13949 ReactCurrentDispatcher$1.current = prevDispatcher;
13950 }
13951 },
13952 useDebugValue: function (value, formatterFn) {
13953 currentHookNameInDev = 'useDebugValue';
13954 updateHookTypesDev();
13955 return updateDebugValue(value, formatterFn);
13956 }
13957 };
13958
13959 InvalidNestedHooksDispatcherOnMountInDEV = {
13960 readContext: function (context, observedBits) {
13961 warnInvalidContextAccess();
13962 return readContext(context, observedBits);
13963 },
13964 useCallback: function (callback, deps) {
13965 currentHookNameInDev = 'useCallback';
13966 warnInvalidHookAccess();
13967 mountHookTypesDev();
13968 return mountCallback(callback, deps);
13969 },
13970 useContext: function (context, observedBits) {
13971 currentHookNameInDev = 'useContext';
13972 warnInvalidHookAccess();
13973 mountHookTypesDev();
13974 return readContext(context, observedBits);
13975 },
13976 useEffect: function (create, deps) {
13977 currentHookNameInDev = 'useEffect';
13978 warnInvalidHookAccess();
13979 mountHookTypesDev();
13980 return mountEffect(create, deps);
13981 },
13982 useImperativeHandle: function (ref, create, deps) {
13983 currentHookNameInDev = 'useImperativeHandle';
13984 warnInvalidHookAccess();
13985 mountHookTypesDev();
13986 return mountImperativeHandle(ref, create, deps);
13987 },
13988 useLayoutEffect: function (create, deps) {
13989 currentHookNameInDev = 'useLayoutEffect';
13990 warnInvalidHookAccess();
13991 mountHookTypesDev();
13992 return mountLayoutEffect(create, deps);
13993 },
13994 useMemo: function (create, deps) {
13995 currentHookNameInDev = 'useMemo';
13996 warnInvalidHookAccess();
13997 mountHookTypesDev();
13998 var prevDispatcher = ReactCurrentDispatcher$1.current;
13999 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14000 try {
14001 return mountMemo(create, deps);
14002 } finally {
14003 ReactCurrentDispatcher$1.current = prevDispatcher;
14004 }
14005 },
14006 useReducer: function (reducer, initialArg, init) {
14007 currentHookNameInDev = 'useReducer';
14008 warnInvalidHookAccess();
14009 mountHookTypesDev();
14010 var prevDispatcher = ReactCurrentDispatcher$1.current;
14011 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14012 try {
14013 return mountReducer(reducer, initialArg, init);
14014 } finally {
14015 ReactCurrentDispatcher$1.current = prevDispatcher;
14016 }
14017 },
14018 useRef: function (initialValue) {
14019 currentHookNameInDev = 'useRef';
14020 warnInvalidHookAccess();
14021 mountHookTypesDev();
14022 return mountRef(initialValue);
14023 },
14024 useState: function (initialState) {
14025 currentHookNameInDev = 'useState';
14026 warnInvalidHookAccess();
14027 mountHookTypesDev();
14028 var prevDispatcher = ReactCurrentDispatcher$1.current;
14029 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14030 try {
14031 return mountState(initialState);
14032 } finally {
14033 ReactCurrentDispatcher$1.current = prevDispatcher;
14034 }
14035 },
14036 useDebugValue: function (value, formatterFn) {
14037 currentHookNameInDev = 'useDebugValue';
14038 warnInvalidHookAccess();
14039 mountHookTypesDev();
14040 return mountDebugValue(value, formatterFn);
14041 }
14042 };
14043
14044 InvalidNestedHooksDispatcherOnUpdateInDEV = {
14045 readContext: function (context, observedBits) {
14046 warnInvalidContextAccess();
14047 return readContext(context, observedBits);
14048 },
14049 useCallback: function (callback, deps) {
14050 currentHookNameInDev = 'useCallback';
14051 warnInvalidHookAccess();
14052 updateHookTypesDev();
14053 return updateCallback(callback, deps);
14054 },
14055 useContext: function (context, observedBits) {
14056 currentHookNameInDev = 'useContext';
14057 warnInvalidHookAccess();
14058 updateHookTypesDev();
14059 return readContext(context, observedBits);
14060 },
14061 useEffect: function (create, deps) {
14062 currentHookNameInDev = 'useEffect';
14063 warnInvalidHookAccess();
14064 updateHookTypesDev();
14065 return updateEffect(create, deps);
14066 },
14067 useImperativeHandle: function (ref, create, deps) {
14068 currentHookNameInDev = 'useImperativeHandle';
14069 warnInvalidHookAccess();
14070 updateHookTypesDev();
14071 return updateImperativeHandle(ref, create, deps);
14072 },
14073 useLayoutEffect: function (create, deps) {
14074 currentHookNameInDev = 'useLayoutEffect';
14075 warnInvalidHookAccess();
14076 updateHookTypesDev();
14077 return updateLayoutEffect(create, deps);
14078 },
14079 useMemo: function (create, deps) {
14080 currentHookNameInDev = 'useMemo';
14081 warnInvalidHookAccess();
14082 updateHookTypesDev();
14083 var prevDispatcher = ReactCurrentDispatcher$1.current;
14084 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
14085 try {
14086 return updateMemo(create, deps);
14087 } finally {
14088 ReactCurrentDispatcher$1.current = prevDispatcher;
14089 }
14090 },
14091 useReducer: function (reducer, initialArg, init) {
14092 currentHookNameInDev = 'useReducer';
14093 warnInvalidHookAccess();
14094 updateHookTypesDev();
14095 var prevDispatcher = ReactCurrentDispatcher$1.current;
14096 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
14097 try {
14098 return updateReducer(reducer, initialArg, init);
14099 } finally {
14100 ReactCurrentDispatcher$1.current = prevDispatcher;
14101 }
14102 },
14103 useRef: function (initialValue) {
14104 currentHookNameInDev = 'useRef';
14105 warnInvalidHookAccess();
14106 updateHookTypesDev();
14107 return updateRef(initialValue);
14108 },
14109 useState: function (initialState) {
14110 currentHookNameInDev = 'useState';
14111 warnInvalidHookAccess();
14112 updateHookTypesDev();
14113 var prevDispatcher = ReactCurrentDispatcher$1.current;
14114 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
14115 try {
14116 return updateState(initialState);
14117 } finally {
14118 ReactCurrentDispatcher$1.current = prevDispatcher;
14119 }
14120 },
14121 useDebugValue: function (value, formatterFn) {
14122 currentHookNameInDev = 'useDebugValue';
14123 warnInvalidHookAccess();
14124 updateHookTypesDev();
14125 return updateDebugValue(value, formatterFn);
14126 }
14127 };
14128}
14129
14130var commitTime = 0;
14131var profilerStartTime = -1;
14132
14133function getCommitTime() {
14134 return commitTime;
14135}
14136
14137function recordCommitTime() {
14138 if (!enableProfilerTimer) {
14139 return;
14140 }
14141 commitTime = unstable_now();
14142}
14143
14144function startProfilerTimer(fiber) {
14145 if (!enableProfilerTimer) {
14146 return;
14147 }
14148
14149 profilerStartTime = unstable_now();
14150
14151 if (fiber.actualStartTime < 0) {
14152 fiber.actualStartTime = unstable_now();
14153 }
14154}
14155
14156function stopProfilerTimerIfRunning(fiber) {
14157 if (!enableProfilerTimer) {
14158 return;
14159 }
14160 profilerStartTime = -1;
14161}
14162
14163function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
14164 if (!enableProfilerTimer) {
14165 return;
14166 }
14167
14168 if (profilerStartTime >= 0) {
14169 var elapsedTime = unstable_now() - profilerStartTime;
14170 fiber.actualDuration += elapsedTime;
14171 if (overrideBaseTime) {
14172 fiber.selfBaseDuration = elapsedTime;
14173 }
14174 profilerStartTime = -1;
14175 }
14176}
14177
14178// The deepest Fiber on the stack involved in a hydration context.
14179// This may have been an insertion or a hydration.
14180var hydrationParentFiber = null;
14181var nextHydratableInstance = null;
14182var isHydrating = false;
14183
14184function enterHydrationState(fiber) {
14185 if (!supportsHydration) {
14186 return false;
14187 }
14188
14189 var parentInstance = fiber.stateNode.containerInfo;
14190 nextHydratableInstance = getFirstHydratableChild(parentInstance);
14191 hydrationParentFiber = fiber;
14192 isHydrating = true;
14193 return true;
14194}
14195
14196function reenterHydrationStateFromDehydratedSuspenseInstance(fiber) {
14197 if (!supportsHydration) {
14198 return false;
14199 }
14200
14201 var suspenseInstance = fiber.stateNode;
14202 nextHydratableInstance = getNextHydratableSibling(suspenseInstance);
14203 popToNextHostParent(fiber);
14204 isHydrating = true;
14205 return true;
14206}
14207
14208function deleteHydratableInstance(returnFiber, instance) {
14209 {
14210 switch (returnFiber.tag) {
14211 case HostRoot:
14212 didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
14213 break;
14214 case HostComponent:
14215 didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
14216 break;
14217 }
14218 }
14219
14220 var childToDelete = createFiberFromHostInstanceForDeletion();
14221 childToDelete.stateNode = instance;
14222 childToDelete.return = returnFiber;
14223 childToDelete.effectTag = Deletion;
14224
14225 // This might seem like it belongs on progressedFirstDeletion. However,
14226 // these children are not part of the reconciliation list of children.
14227 // Even if we abort and rereconcile the children, that will try to hydrate
14228 // again and the nodes are still in the host tree so these will be
14229 // recreated.
14230 if (returnFiber.lastEffect !== null) {
14231 returnFiber.lastEffect.nextEffect = childToDelete;
14232 returnFiber.lastEffect = childToDelete;
14233 } else {
14234 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
14235 }
14236}
14237
14238function insertNonHydratedInstance(returnFiber, fiber) {
14239 fiber.effectTag |= Placement;
14240 {
14241 switch (returnFiber.tag) {
14242 case HostRoot:
14243 {
14244 var parentContainer = returnFiber.stateNode.containerInfo;
14245 switch (fiber.tag) {
14246 case HostComponent:
14247 var type = fiber.type;
14248 var props = fiber.pendingProps;
14249 didNotFindHydratableContainerInstance(parentContainer, type, props);
14250 break;
14251 case HostText:
14252 var text = fiber.pendingProps;
14253 didNotFindHydratableContainerTextInstance(parentContainer, text);
14254 break;
14255 case SuspenseComponent:
14256
14257 break;
14258 }
14259 break;
14260 }
14261 case HostComponent:
14262 {
14263 var parentType = returnFiber.type;
14264 var parentProps = returnFiber.memoizedProps;
14265 var parentInstance = returnFiber.stateNode;
14266 switch (fiber.tag) {
14267 case HostComponent:
14268 var _type = fiber.type;
14269 var _props = fiber.pendingProps;
14270 didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
14271 break;
14272 case HostText:
14273 var _text = fiber.pendingProps;
14274 didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
14275 break;
14276 case SuspenseComponent:
14277 didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance);
14278 break;
14279 }
14280 break;
14281 }
14282 default:
14283 return;
14284 }
14285 }
14286}
14287
14288function tryHydrate(fiber, nextInstance) {
14289 switch (fiber.tag) {
14290 case HostComponent:
14291 {
14292 var type = fiber.type;
14293 var props = fiber.pendingProps;
14294 var instance = canHydrateInstance(nextInstance, type, props);
14295 if (instance !== null) {
14296 fiber.stateNode = instance;
14297 return true;
14298 }
14299 return false;
14300 }
14301 case HostText:
14302 {
14303 var text = fiber.pendingProps;
14304 var textInstance = canHydrateTextInstance(nextInstance, text);
14305 if (textInstance !== null) {
14306 fiber.stateNode = textInstance;
14307 return true;
14308 }
14309 return false;
14310 }
14311 case SuspenseComponent:
14312 {
14313 if (enableSuspenseServerRenderer) {
14314 var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
14315 if (suspenseInstance !== null) {
14316 // Downgrade the tag to a dehydrated component until we've hydrated it.
14317 fiber.tag = DehydratedSuspenseComponent;
14318 fiber.stateNode = suspenseInstance;
14319 return true;
14320 }
14321 }
14322 return false;
14323 }
14324 default:
14325 return false;
14326 }
14327}
14328
14329function tryToClaimNextHydratableInstance(fiber) {
14330 if (!isHydrating) {
14331 return;
14332 }
14333 var nextInstance = nextHydratableInstance;
14334 if (!nextInstance) {
14335 // Nothing to hydrate. Make it an insertion.
14336 insertNonHydratedInstance(hydrationParentFiber, fiber);
14337 isHydrating = false;
14338 hydrationParentFiber = fiber;
14339 return;
14340 }
14341 var firstAttemptedInstance = nextInstance;
14342 if (!tryHydrate(fiber, nextInstance)) {
14343 // If we can't hydrate this instance let's try the next one.
14344 // We use this as a heuristic. It's based on intuition and not data so it
14345 // might be flawed or unnecessary.
14346 nextInstance = getNextHydratableSibling(firstAttemptedInstance);
14347 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
14348 // Nothing to hydrate. Make it an insertion.
14349 insertNonHydratedInstance(hydrationParentFiber, fiber);
14350 isHydrating = false;
14351 hydrationParentFiber = fiber;
14352 return;
14353 }
14354 // We matched the next one, we'll now assume that the first one was
14355 // superfluous and we'll delete it. Since we can't eagerly delete it
14356 // we'll have to schedule a deletion. To do that, this node needs a dummy
14357 // fiber associated with it.
14358 deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
14359 }
14360 hydrationParentFiber = fiber;
14361 nextHydratableInstance = getFirstHydratableChild(nextInstance);
14362}
14363
14364function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
14365 if (!supportsHydration) {
14366 invariant(false, 'Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
14367 }
14368
14369 var instance = fiber.stateNode;
14370 var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber);
14371 // TODO: Type this specific to this type of component.
14372 fiber.updateQueue = updatePayload;
14373 // If the update payload indicates that there is a change or if there
14374 // is a new ref we mark this as an update.
14375 if (updatePayload !== null) {
14376 return true;
14377 }
14378 return false;
14379}
14380
14381function prepareToHydrateHostTextInstance(fiber) {
14382 if (!supportsHydration) {
14383 invariant(false, 'Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
14384 }
14385
14386 var textInstance = fiber.stateNode;
14387 var textContent = fiber.memoizedProps;
14388 var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
14389 {
14390 if (shouldUpdate) {
14391 // We assume that prepareToHydrateHostTextInstance is called in a context where the
14392 // hydration parent is the parent host component of this host text.
14393 var returnFiber = hydrationParentFiber;
14394 if (returnFiber !== null) {
14395 switch (returnFiber.tag) {
14396 case HostRoot:
14397 {
14398 var parentContainer = returnFiber.stateNode.containerInfo;
14399 didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
14400 break;
14401 }
14402 case HostComponent:
14403 {
14404 var parentType = returnFiber.type;
14405 var parentProps = returnFiber.memoizedProps;
14406 var parentInstance = returnFiber.stateNode;
14407 didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
14408 break;
14409 }
14410 }
14411 }
14412 }
14413 }
14414 return shouldUpdate;
14415}
14416
14417function skipPastDehydratedSuspenseInstance(fiber) {
14418 if (!supportsHydration) {
14419 invariant(false, 'Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
14420 }
14421 var suspenseInstance = fiber.stateNode;
14422 !suspenseInstance ? invariant(false, 'Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.') : void 0;
14423 nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
14424}
14425
14426function popToNextHostParent(fiber) {
14427 var parent = fiber.return;
14428 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== DehydratedSuspenseComponent) {
14429 parent = parent.return;
14430 }
14431 hydrationParentFiber = parent;
14432}
14433
14434function popHydrationState(fiber) {
14435 if (!supportsHydration) {
14436 return false;
14437 }
14438 if (fiber !== hydrationParentFiber) {
14439 // We're deeper than the current hydration context, inside an inserted
14440 // tree.
14441 return false;
14442 }
14443 if (!isHydrating) {
14444 // If we're not currently hydrating but we're in a hydration context, then
14445 // we were an insertion and now need to pop up reenter hydration of our
14446 // siblings.
14447 popToNextHostParent(fiber);
14448 isHydrating = true;
14449 return false;
14450 }
14451
14452 var type = fiber.type;
14453
14454 // If we have any remaining hydratable nodes, we need to delete them now.
14455 // We only do this deeper than head and body since they tend to have random
14456 // other nodes in them. We also ignore components with pure text content in
14457 // side of them.
14458 // TODO: Better heuristic.
14459 if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
14460 var nextInstance = nextHydratableInstance;
14461 while (nextInstance) {
14462 deleteHydratableInstance(fiber, nextInstance);
14463 nextInstance = getNextHydratableSibling(nextInstance);
14464 }
14465 }
14466
14467 popToNextHostParent(fiber);
14468 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
14469 return true;
14470}
14471
14472function resetHydrationState() {
14473 if (!supportsHydration) {
14474 return;
14475 }
14476
14477 hydrationParentFiber = null;
14478 nextHydratableInstance = null;
14479 isHydrating = false;
14480}
14481
14482var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
14483
14484var didReceiveUpdate = false;
14485
14486var didWarnAboutBadClass = void 0;
14487var didWarnAboutContextTypeOnFunctionComponent = void 0;
14488var didWarnAboutGetDerivedStateOnFunctionComponent = void 0;
14489var didWarnAboutFunctionRefs = void 0;
14490var didWarnAboutReassigningProps = void 0;
14491
14492{
14493 didWarnAboutBadClass = {};
14494 didWarnAboutContextTypeOnFunctionComponent = {};
14495 didWarnAboutGetDerivedStateOnFunctionComponent = {};
14496 didWarnAboutFunctionRefs = {};
14497 didWarnAboutReassigningProps = false;
14498}
14499
14500function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) {
14501 if (current$$1 === null) {
14502 // If this is a fresh new component that hasn't been rendered yet, we
14503 // won't update its child set by applying minimal side-effects. Instead,
14504 // we will add them all to the child before it gets rendered. That means
14505 // we can optimize this reconciliation pass by not tracking side-effects.
14506 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
14507 } else {
14508 // If the current child is the same as the work in progress, it means that
14509 // we haven't yet started any work on these children. Therefore, we use
14510 // the clone algorithm to create a copy of all the current children.
14511
14512 // If we had any progressed work already, that is invalid at this point so
14513 // let's throw it out.
14514 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime);
14515 }
14516}
14517
14518function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) {
14519 // This function is fork of reconcileChildren. It's used in cases where we
14520 // want to reconcile without matching against the existing set. This has the
14521 // effect of all current children being unmounted; even if the type and key
14522 // are the same, the old child is unmounted and a new child is created.
14523 //
14524 // To do this, we're going to go through the reconcile algorithm twice. In
14525 // the first pass, we schedule a deletion for all the current children by
14526 // passing null.
14527 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime);
14528 // In the second pass, we mount the new children. The trick here is that we
14529 // pass null in place of where we usually pass the current child set. This has
14530 // the effect of remounting all children regardless of whether their their
14531 // identity matches.
14532 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
14533}
14534
14535function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
14536 // TODO: current can be non-null here even if the component
14537 // hasn't yet mounted. This happens after the first render suspends.
14538 // We'll need to figure out if this is fine or can cause issues.
14539
14540 {
14541 if (workInProgress.type !== workInProgress.elementType) {
14542 // Lazy component props can't be validated in createElement
14543 // because they're only guaranteed to be resolved here.
14544 var innerPropTypes = Component.propTypes;
14545 if (innerPropTypes) {
14546 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
14547 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14548 }
14549 }
14550 }
14551
14552 var render = Component.render;
14553 var ref = workInProgress.ref;
14554
14555 // The rest is a fork of updateFunctionComponent
14556 var nextChildren = void 0;
14557 prepareToReadContext(workInProgress, renderExpirationTime);
14558 {
14559 ReactCurrentOwner$3.current = workInProgress;
14560 setCurrentPhase('render');
14561 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
14562 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14563 // Only double-render components with Hooks
14564 if (workInProgress.memoizedState !== null) {
14565 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
14566 }
14567 }
14568 setCurrentPhase(null);
14569 }
14570
14571 if (current$$1 !== null && !didReceiveUpdate) {
14572 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
14573 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14574 }
14575
14576 // React DevTools reads this flag.
14577 workInProgress.effectTag |= PerformedWork;
14578 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14579 return workInProgress.child;
14580}
14581
14582function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
14583 if (current$$1 === null) {
14584 var type = Component.type;
14585 if (isSimpleFunctionComponent(type) && Component.compare === null &&
14586 // SimpleMemoComponent codepath doesn't resolve outer props either.
14587 Component.defaultProps === undefined) {
14588 // If this is a plain function component without default props,
14589 // and with only the default shallow comparison, we upgrade it
14590 // to a SimpleMemoComponent to allow fast path updates.
14591 workInProgress.tag = SimpleMemoComponent;
14592 workInProgress.type = type;
14593 {
14594 validateFunctionComponentInDev(workInProgress, type);
14595 }
14596 return updateSimpleMemoComponent(current$$1, workInProgress, type, nextProps, updateExpirationTime, renderExpirationTime);
14597 }
14598 {
14599 var innerPropTypes = type.propTypes;
14600 if (innerPropTypes) {
14601 // Inner memo component props aren't currently validated in createElement.
14602 // We could move it there, but we'd still need this for lazy code path.
14603 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
14604 'prop', getComponentName(type), getCurrentFiberStackInDev);
14605 }
14606 }
14607 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
14608 child.ref = workInProgress.ref;
14609 child.return = workInProgress;
14610 workInProgress.child = child;
14611 return child;
14612 }
14613 {
14614 var _type = Component.type;
14615 var _innerPropTypes = _type.propTypes;
14616 if (_innerPropTypes) {
14617 // Inner memo component props aren't currently validated in createElement.
14618 // We could move it there, but we'd still need this for lazy code path.
14619 checkPropTypes_1(_innerPropTypes, nextProps, // Resolved props
14620 'prop', getComponentName(_type), getCurrentFiberStackInDev);
14621 }
14622 }
14623 var currentChild = current$$1.child; // This is always exactly one child
14624 if (updateExpirationTime < renderExpirationTime) {
14625 // This will be the props with resolved defaultProps,
14626 // unlike current.memoizedProps which will be the unresolved ones.
14627 var prevProps = currentChild.memoizedProps;
14628 // Default to shallow comparison
14629 var compare = Component.compare;
14630 compare = compare !== null ? compare : shallowEqual;
14631 if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
14632 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14633 }
14634 }
14635 // React DevTools reads this flag.
14636 workInProgress.effectTag |= PerformedWork;
14637 var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
14638 newChild.ref = workInProgress.ref;
14639 newChild.return = workInProgress;
14640 workInProgress.child = newChild;
14641 return newChild;
14642}
14643
14644function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
14645 // TODO: current can be non-null here even if the component
14646 // hasn't yet mounted. This happens when the inner render suspends.
14647 // We'll need to figure out if this is fine or can cause issues.
14648
14649 {
14650 if (workInProgress.type !== workInProgress.elementType) {
14651 // Lazy component props can't be validated in createElement
14652 // because they're only guaranteed to be resolved here.
14653 var outerMemoType = workInProgress.elementType;
14654 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
14655 // We warn when you define propTypes on lazy()
14656 // so let's just skip over it to find memo() outer wrapper.
14657 // Inner props for memo are validated later.
14658 outerMemoType = refineResolvedLazyComponent(outerMemoType);
14659 }
14660 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
14661 if (outerPropTypes) {
14662 checkPropTypes_1(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
14663 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
14664 }
14665 // Inner propTypes will be validated in the function component path.
14666 }
14667 }
14668 if (current$$1 !== null) {
14669 var prevProps = current$$1.memoizedProps;
14670 if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
14671 didReceiveUpdate = false;
14672 if (updateExpirationTime < renderExpirationTime) {
14673 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14674 }
14675 }
14676 }
14677 return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
14678}
14679
14680function updateFragment(current$$1, workInProgress, renderExpirationTime) {
14681 var nextChildren = workInProgress.pendingProps;
14682 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14683 return workInProgress.child;
14684}
14685
14686function updateMode(current$$1, workInProgress, renderExpirationTime) {
14687 var nextChildren = workInProgress.pendingProps.children;
14688 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14689 return workInProgress.child;
14690}
14691
14692function updateProfiler(current$$1, workInProgress, renderExpirationTime) {
14693 if (enableProfilerTimer) {
14694 workInProgress.effectTag |= Update;
14695 }
14696 var nextProps = workInProgress.pendingProps;
14697 var nextChildren = nextProps.children;
14698 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14699 return workInProgress.child;
14700}
14701
14702function markRef(current$$1, workInProgress) {
14703 var ref = workInProgress.ref;
14704 if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) {
14705 // Schedule a Ref effect
14706 workInProgress.effectTag |= Ref;
14707 }
14708}
14709
14710function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
14711 {
14712 if (workInProgress.type !== workInProgress.elementType) {
14713 // Lazy component props can't be validated in createElement
14714 // because they're only guaranteed to be resolved here.
14715 var innerPropTypes = Component.propTypes;
14716 if (innerPropTypes) {
14717 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
14718 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14719 }
14720 }
14721 }
14722
14723 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
14724 var context = getMaskedContext(workInProgress, unmaskedContext);
14725
14726 var nextChildren = void 0;
14727 prepareToReadContext(workInProgress, renderExpirationTime);
14728 {
14729 ReactCurrentOwner$3.current = workInProgress;
14730 setCurrentPhase('render');
14731 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
14732 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14733 // Only double-render components with Hooks
14734 if (workInProgress.memoizedState !== null) {
14735 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
14736 }
14737 }
14738 setCurrentPhase(null);
14739 }
14740
14741 if (current$$1 !== null && !didReceiveUpdate) {
14742 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
14743 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14744 }
14745
14746 // React DevTools reads this flag.
14747 workInProgress.effectTag |= PerformedWork;
14748 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14749 return workInProgress.child;
14750}
14751
14752function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
14753 {
14754 if (workInProgress.type !== workInProgress.elementType) {
14755 // Lazy component props can't be validated in createElement
14756 // because they're only guaranteed to be resolved here.
14757 var innerPropTypes = Component.propTypes;
14758 if (innerPropTypes) {
14759 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
14760 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14761 }
14762 }
14763 }
14764
14765 // Push context providers early to prevent context stack mismatches.
14766 // During mounting we don't know the child context yet as the instance doesn't exist.
14767 // We will invalidate the child context in finishClassComponent() right after rendering.
14768 var hasContext = void 0;
14769 if (isContextProvider(Component)) {
14770 hasContext = true;
14771 pushContextProvider(workInProgress);
14772 } else {
14773 hasContext = false;
14774 }
14775 prepareToReadContext(workInProgress, renderExpirationTime);
14776
14777 var instance = workInProgress.stateNode;
14778 var shouldUpdate = void 0;
14779 if (instance === null) {
14780 if (current$$1 !== null) {
14781 // An class component without an instance only mounts if it suspended
14782 // inside a non- concurrent tree, in an inconsistent state. We want to
14783 // tree it like a new mount, even though an empty version of it already
14784 // committed. Disconnect the alternate pointers.
14785 current$$1.alternate = null;
14786 workInProgress.alternate = null;
14787 // Since this is conceptually a new fiber, schedule a Placement effect
14788 workInProgress.effectTag |= Placement;
14789 }
14790 // In the initial pass we might need to construct the instance.
14791 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14792 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14793 shouldUpdate = true;
14794 } else if (current$$1 === null) {
14795 // In a resume, we'll already have an instance we can reuse.
14796 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14797 } else {
14798 shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
14799 }
14800 var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
14801 {
14802 var inst = workInProgress.stateNode;
14803 if (inst.props !== nextProps) {
14804 !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;
14805 didWarnAboutReassigningProps = true;
14806 }
14807 }
14808 return nextUnitOfWork;
14809}
14810
14811function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
14812 // Refs should update even if shouldComponentUpdate returns false
14813 markRef(current$$1, workInProgress);
14814
14815 var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
14816
14817 if (!shouldUpdate && !didCaptureError) {
14818 // Context providers should defer to sCU for rendering
14819 if (hasContext) {
14820 invalidateContextProvider(workInProgress, Component, false);
14821 }
14822
14823 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14824 }
14825
14826 var instance = workInProgress.stateNode;
14827
14828 // Rerender
14829 ReactCurrentOwner$3.current = workInProgress;
14830 var nextChildren = void 0;
14831 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
14832 // If we captured an error, but getDerivedStateFrom catch is not defined,
14833 // unmount all the children. componentDidCatch will schedule an update to
14834 // re-render a fallback. This is temporary until we migrate everyone to
14835 // the new API.
14836 // TODO: Warn in a future release.
14837 nextChildren = null;
14838
14839 if (enableProfilerTimer) {
14840 stopProfilerTimerIfRunning(workInProgress);
14841 }
14842 } else {
14843 {
14844 setCurrentPhase('render');
14845 nextChildren = instance.render();
14846 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14847 instance.render();
14848 }
14849 setCurrentPhase(null);
14850 }
14851 }
14852
14853 // React DevTools reads this flag.
14854 workInProgress.effectTag |= PerformedWork;
14855 if (current$$1 !== null && didCaptureError) {
14856 // If we're recovering from an error, reconcile without reusing any of
14857 // the existing children. Conceptually, the normal children and the children
14858 // that are shown on error are two different sets, so we shouldn't reuse
14859 // normal children even if their identities match.
14860 forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime);
14861 } else {
14862 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14863 }
14864
14865 // Memoize state using the values we just used to render.
14866 // TODO: Restructure so we never read values from the instance.
14867 workInProgress.memoizedState = instance.state;
14868
14869 // The context might have changed so we need to recalculate it.
14870 if (hasContext) {
14871 invalidateContextProvider(workInProgress, Component, true);
14872 }
14873
14874 return workInProgress.child;
14875}
14876
14877function pushHostRootContext(workInProgress) {
14878 var root = workInProgress.stateNode;
14879 if (root.pendingContext) {
14880 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
14881 } else if (root.context) {
14882 // Should always be set
14883 pushTopLevelContextObject(workInProgress, root.context, false);
14884 }
14885 pushHostContainer(workInProgress, root.containerInfo);
14886}
14887
14888function updateHostRoot(current$$1, workInProgress, renderExpirationTime) {
14889 pushHostRootContext(workInProgress);
14890 var updateQueue = workInProgress.updateQueue;
14891 !(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;
14892 var nextProps = workInProgress.pendingProps;
14893 var prevState = workInProgress.memoizedState;
14894 var prevChildren = prevState !== null ? prevState.element : null;
14895 processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
14896 var nextState = workInProgress.memoizedState;
14897 // Caution: React DevTools currently depends on this property
14898 // being called "element".
14899 var nextChildren = nextState.element;
14900 if (nextChildren === prevChildren) {
14901 // If the state is the same as before, that's a bailout because we had
14902 // no work that expires at this time.
14903 resetHydrationState();
14904 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14905 }
14906 var root = workInProgress.stateNode;
14907 if ((current$$1 === null || current$$1.child === null) && root.hydrate && enterHydrationState(workInProgress)) {
14908 // If we don't have any current children this might be the first pass.
14909 // We always try to hydrate. If this isn't a hydration pass there won't
14910 // be any children to hydrate which is effectively the same thing as
14911 // not hydrating.
14912
14913 // This is a bit of a hack. We track the host root as a placement to
14914 // know that we're currently in a mounting state. That way isMounted
14915 // works as expected. We must reset this before committing.
14916 // TODO: Delete this when we delete isMounted and findDOMNode.
14917 workInProgress.effectTag |= Placement;
14918
14919 // Ensure that children mount into this root without tracking
14920 // side-effects. This ensures that we don't store Placement effects on
14921 // nodes that will be hydrated.
14922 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
14923 } else {
14924 // Otherwise reset hydration state in case we aborted and resumed another
14925 // root.
14926 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14927 resetHydrationState();
14928 }
14929 return workInProgress.child;
14930}
14931
14932function updateHostComponent(current$$1, workInProgress, renderExpirationTime) {
14933 pushHostContext(workInProgress);
14934
14935 if (current$$1 === null) {
14936 tryToClaimNextHydratableInstance(workInProgress);
14937 }
14938
14939 var type = workInProgress.type;
14940 var nextProps = workInProgress.pendingProps;
14941 var prevProps = current$$1 !== null ? current$$1.memoizedProps : null;
14942
14943 var nextChildren = nextProps.children;
14944 var isDirectTextChild = shouldSetTextContent(type, nextProps);
14945
14946 if (isDirectTextChild) {
14947 // We special case a direct text child of a host node. This is a common
14948 // case. We won't handle it as a reified child. We will instead handle
14949 // this in the host environment that also have access to this prop. That
14950 // avoids allocating another HostText fiber and traversing it.
14951 nextChildren = null;
14952 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
14953 // If we're switching from a direct text child to a normal child, or to
14954 // empty, we need to schedule the text content to be reset.
14955 workInProgress.effectTag |= ContentReset;
14956 }
14957
14958 markRef(current$$1, workInProgress);
14959
14960 // Check the host config to see if the children are offscreen/hidden.
14961 if (renderExpirationTime !== Never && workInProgress.mode & ConcurrentMode && shouldDeprioritizeSubtree(type, nextProps)) {
14962 // Schedule this fiber to re-render at offscreen priority. Then bailout.
14963 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
14964 return null;
14965 }
14966
14967 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14968 return workInProgress.child;
14969}
14970
14971function updateHostText(current$$1, workInProgress) {
14972 if (current$$1 === null) {
14973 tryToClaimNextHydratableInstance(workInProgress);
14974 }
14975 // Nothing to do here. This is terminal. We'll do the completion step
14976 // immediately after.
14977 return null;
14978}
14979
14980function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
14981 if (_current !== null) {
14982 // An lazy component only mounts if it suspended inside a non-
14983 // concurrent tree, in an inconsistent state. We want to treat it like
14984 // a new mount, even though an empty version of it already committed.
14985 // Disconnect the alternate pointers.
14986 _current.alternate = null;
14987 workInProgress.alternate = null;
14988 // Since this is conceptually a new fiber, schedule a Placement effect
14989 workInProgress.effectTag |= Placement;
14990 }
14991
14992 var props = workInProgress.pendingProps;
14993 // We can't start a User Timing measurement with correct label yet.
14994 // Cancel and resume right after we know the tag.
14995 cancelWorkTimer(workInProgress);
14996 var Component = readLazyComponentType(elementType);
14997 // Store the unwrapped component in the type.
14998 workInProgress.type = Component;
14999 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
15000 startWorkTimer(workInProgress);
15001 var resolvedProps = resolveDefaultProps(Component, props);
15002 var child = void 0;
15003 switch (resolvedTag) {
15004 case FunctionComponent:
15005 {
15006 {
15007 validateFunctionComponentInDev(workInProgress, Component);
15008 }
15009 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
15010 break;
15011 }
15012 case ClassComponent:
15013 {
15014 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
15015 break;
15016 }
15017 case ForwardRef:
15018 {
15019 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
15020 break;
15021 }
15022 case MemoComponent:
15023 {
15024 {
15025 if (workInProgress.type !== workInProgress.elementType) {
15026 var outerPropTypes = Component.propTypes;
15027 if (outerPropTypes) {
15028 checkPropTypes_1(outerPropTypes, resolvedProps, // Resolved for outer only
15029 'prop', getComponentName(Component), getCurrentFiberStackInDev);
15030 }
15031 }
15032 }
15033 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
15034 updateExpirationTime, renderExpirationTime);
15035 break;
15036 }
15037 default:
15038 {
15039 var hint = '';
15040 {
15041 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
15042 hint = ' Did you wrap a component in React.lazy() more than once?';
15043 }
15044 }
15045 // This message intentionally doesn't mention ForwardRef or MemoComponent
15046 // because the fact that it's a separate type of work is an
15047 // implementation detail.
15048 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);
15049 }
15050 }
15051 return child;
15052}
15053
15054function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
15055 if (_current !== null) {
15056 // An incomplete component only mounts if it suspended inside a non-
15057 // concurrent tree, in an inconsistent state. We want to treat it like
15058 // a new mount, even though an empty version of it already committed.
15059 // Disconnect the alternate pointers.
15060 _current.alternate = null;
15061 workInProgress.alternate = null;
15062 // Since this is conceptually a new fiber, schedule a Placement effect
15063 workInProgress.effectTag |= Placement;
15064 }
15065
15066 // Promote the fiber to a class and try rendering again.
15067 workInProgress.tag = ClassComponent;
15068
15069 // The rest of this function is a fork of `updateClassComponent`
15070
15071 // Push context providers early to prevent context stack mismatches.
15072 // During mounting we don't know the child context yet as the instance doesn't exist.
15073 // We will invalidate the child context in finishClassComponent() right after rendering.
15074 var hasContext = void 0;
15075 if (isContextProvider(Component)) {
15076 hasContext = true;
15077 pushContextProvider(workInProgress);
15078 } else {
15079 hasContext = false;
15080 }
15081 prepareToReadContext(workInProgress, renderExpirationTime);
15082
15083 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
15084 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
15085
15086 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
15087}
15088
15089function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
15090 if (_current !== null) {
15091 // An indeterminate component only mounts if it suspended inside a non-
15092 // concurrent tree, in an inconsistent state. We want to treat it like
15093 // a new mount, even though an empty version of it already committed.
15094 // Disconnect the alternate pointers.
15095 _current.alternate = null;
15096 workInProgress.alternate = null;
15097 // Since this is conceptually a new fiber, schedule a Placement effect
15098 workInProgress.effectTag |= Placement;
15099 }
15100
15101 var props = workInProgress.pendingProps;
15102 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
15103 var context = getMaskedContext(workInProgress, unmaskedContext);
15104
15105 prepareToReadContext(workInProgress, renderExpirationTime);
15106
15107 var value = void 0;
15108
15109 {
15110 if (Component.prototype && typeof Component.prototype.render === 'function') {
15111 var componentName = getComponentName(Component) || 'Unknown';
15112
15113 if (!didWarnAboutBadClass[componentName]) {
15114 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);
15115 didWarnAboutBadClass[componentName] = true;
15116 }
15117 }
15118
15119 if (workInProgress.mode & StrictMode) {
15120 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
15121 }
15122
15123 ReactCurrentOwner$3.current = workInProgress;
15124 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
15125 }
15126 // React DevTools reads this flag.
15127 workInProgress.effectTag |= PerformedWork;
15128
15129 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
15130 // Proceed under the assumption that this is a class instance
15131 workInProgress.tag = ClassComponent;
15132
15133 // Throw out any hooks that were used.
15134 resetHooks();
15135
15136 // Push context providers early to prevent context stack mismatches.
15137 // During mounting we don't know the child context yet as the instance doesn't exist.
15138 // We will invalidate the child context in finishClassComponent() right after rendering.
15139 var hasContext = false;
15140 if (isContextProvider(Component)) {
15141 hasContext = true;
15142 pushContextProvider(workInProgress);
15143 } else {
15144 hasContext = false;
15145 }
15146
15147 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
15148
15149 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
15150 if (typeof getDerivedStateFromProps === 'function') {
15151 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
15152 }
15153
15154 adoptClassInstance(workInProgress, value);
15155 mountClassInstance(workInProgress, Component, props, renderExpirationTime);
15156 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
15157 } else {
15158 // Proceed under the assumption that this is a function component
15159 workInProgress.tag = FunctionComponent;
15160 {
15161 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
15162 // Only double-render components with Hooks
15163 if (workInProgress.memoizedState !== null) {
15164 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
15165 }
15166 }
15167 }
15168 reconcileChildren(null, workInProgress, value, renderExpirationTime);
15169 {
15170 validateFunctionComponentInDev(workInProgress, Component);
15171 }
15172 return workInProgress.child;
15173 }
15174}
15175
15176function validateFunctionComponentInDev(workInProgress, Component) {
15177 if (Component) {
15178 !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
15179 }
15180 if (workInProgress.ref !== null) {
15181 var info = '';
15182 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
15183 if (ownerName) {
15184 info += '\n\nCheck the render method of `' + ownerName + '`.';
15185 }
15186
15187 var warningKey = ownerName || workInProgress._debugID || '';
15188 var debugSource = workInProgress._debugSource;
15189 if (debugSource) {
15190 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
15191 }
15192 if (!didWarnAboutFunctionRefs[warningKey]) {
15193 didWarnAboutFunctionRefs[warningKey] = true;
15194 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);
15195 }
15196 }
15197
15198 if (typeof Component.getDerivedStateFromProps === 'function') {
15199 var componentName = getComponentName(Component) || 'Unknown';
15200
15201 if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) {
15202 warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', componentName);
15203 didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true;
15204 }
15205 }
15206
15207 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
15208 var _componentName = getComponentName(Component) || 'Unknown';
15209
15210 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName]) {
15211 warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName);
15212 didWarnAboutContextTypeOnFunctionComponent[_componentName] = true;
15213 }
15214 }
15215}
15216
15217function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
15218 var mode = workInProgress.mode;
15219 var nextProps = workInProgress.pendingProps;
15220
15221 // We should attempt to render the primary children unless this boundary
15222 // already suspended during this render (`alreadyCaptured` is true).
15223 var nextState = workInProgress.memoizedState;
15224
15225 var nextDidTimeout = void 0;
15226 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
15227 // This is the first attempt.
15228 nextState = null;
15229 nextDidTimeout = false;
15230 } else {
15231 // Something in this boundary's subtree already suspended. Switch to
15232 // rendering the fallback children.
15233 nextState = {
15234 timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork
15235 };
15236 nextDidTimeout = true;
15237 workInProgress.effectTag &= ~DidCapture;
15238 }
15239
15240 // This next part is a bit confusing. If the children timeout, we switch to
15241 // showing the fallback children in place of the "primary" children.
15242 // However, we don't want to delete the primary children because then their
15243 // state will be lost (both the React state and the host state, e.g.
15244 // uncontrolled form inputs). Instead we keep them mounted and hide them.
15245 // Both the fallback children AND the primary children are rendered at the
15246 // same time. Once the primary children are un-suspended, we can delete
15247 // the fallback children — don't need to preserve their state.
15248 //
15249 // The two sets of children are siblings in the host environment, but
15250 // semantically, for purposes of reconciliation, they are two separate sets.
15251 // So we store them using two fragment fibers.
15252 //
15253 // However, we want to avoid allocating extra fibers for every placeholder.
15254 // They're only necessary when the children time out, because that's the
15255 // only time when both sets are mounted.
15256 //
15257 // So, the extra fragment fibers are only used if the children time out.
15258 // Otherwise, we render the primary children directly. This requires some
15259 // custom reconciliation logic to preserve the state of the primary
15260 // children. It's essentially a very basic form of re-parenting.
15261
15262 // `child` points to the child fiber. In the normal case, this is the first
15263 // fiber of the primary children set. In the timed-out case, it's a
15264 // a fragment fiber containing the primary children.
15265 var child = void 0;
15266 // `next` points to the next fiber React should render. In the normal case,
15267 // it's the same as `child`: the first fiber of the primary children set.
15268 // In the timed-out case, it's a fragment fiber containing the *fallback*
15269 // children -- we skip over the primary children entirely.
15270 var next = void 0;
15271 if (current$$1 === null) {
15272 if (enableSuspenseServerRenderer) {
15273 // If we're currently hydrating, try to hydrate this boundary.
15274 // But only if this has a fallback.
15275 if (nextProps.fallback !== undefined) {
15276 tryToClaimNextHydratableInstance(workInProgress);
15277 // This could've changed the tag if this was a dehydrated suspense component.
15278 if (workInProgress.tag === DehydratedSuspenseComponent) {
15279 return updateDehydratedSuspenseComponent(null, workInProgress, renderExpirationTime);
15280 }
15281 }
15282 }
15283
15284 // This is the initial mount. This branch is pretty simple because there's
15285 // no previous state that needs to be preserved.
15286 if (nextDidTimeout) {
15287 // Mount separate fragments for primary and fallback children.
15288 var nextFallbackChildren = nextProps.fallback;
15289 var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
15290
15291 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
15292 // Outside of concurrent mode, we commit the effects from the
15293 var progressedState = workInProgress.memoizedState;
15294 var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
15295 primaryChildFragment.child = progressedPrimaryChild;
15296 }
15297
15298 var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
15299 primaryChildFragment.sibling = fallbackChildFragment;
15300 child = primaryChildFragment;
15301 // Skip the primary children, and continue working on the
15302 // fallback children.
15303 next = fallbackChildFragment;
15304 child.return = next.return = workInProgress;
15305 } else {
15306 // Mount the primary children without an intermediate fragment fiber.
15307 var nextPrimaryChildren = nextProps.children;
15308 child = next = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
15309 }
15310 } else {
15311 // This is an update. This branch is more complicated because we need to
15312 // ensure the state of the primary children is preserved.
15313 var prevState = current$$1.memoizedState;
15314 var prevDidTimeout = prevState !== null;
15315 if (prevDidTimeout) {
15316 // The current tree already timed out. That means each child set is
15317 var currentPrimaryChildFragment = current$$1.child;
15318 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
15319 if (nextDidTimeout) {
15320 // Still timed out. Reuse the current primary children by cloning
15321 // its fragment. We're going to skip over these entirely.
15322 var _nextFallbackChildren = nextProps.fallback;
15323 var _primaryChildFragment = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
15324
15325 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
15326 // Outside of concurrent mode, we commit the effects from the
15327 var _progressedState = workInProgress.memoizedState;
15328 var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
15329 if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
15330 _primaryChildFragment.child = _progressedPrimaryChild;
15331 }
15332 }
15333
15334 // Because primaryChildFragment is a new fiber that we're inserting as the
15335 // parent of a new tree, we need to set its treeBaseDuration.
15336 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
15337 // treeBaseDuration is the sum of all the child tree base durations.
15338 var treeBaseDuration = 0;
15339 var hiddenChild = _primaryChildFragment.child;
15340 while (hiddenChild !== null) {
15341 treeBaseDuration += hiddenChild.treeBaseDuration;
15342 hiddenChild = hiddenChild.sibling;
15343 }
15344 _primaryChildFragment.treeBaseDuration = treeBaseDuration;
15345 }
15346
15347 // Clone the fallback child fragment, too. These we'll continue
15348 // working on.
15349 var _fallbackChildFragment = _primaryChildFragment.sibling = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren, currentFallbackChildFragment.expirationTime);
15350 child = _primaryChildFragment;
15351 _primaryChildFragment.childExpirationTime = NoWork;
15352 // Skip the primary children, and continue working on the
15353 // fallback children.
15354 next = _fallbackChildFragment;
15355 child.return = next.return = workInProgress;
15356 } else {
15357 // No longer suspended. Switch back to showing the primary children,
15358 // and remove the intermediate fragment fiber.
15359 var _nextPrimaryChildren = nextProps.children;
15360 var currentPrimaryChild = currentPrimaryChildFragment.child;
15361 var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime);
15362
15363 // If this render doesn't suspend, we need to delete the fallback
15364 // children. Wait until the complete phase, after we've confirmed the
15365 // fallback is no longer needed.
15366 // TODO: Would it be better to store the fallback fragment on
15367 // the stateNode?
15368
15369 // Continue rendering the children, like we normally do.
15370 child = next = primaryChild;
15371 }
15372 } else {
15373 // The current tree has not already timed out. That means the primary
15374 // children are not wrapped in a fragment fiber.
15375 var _currentPrimaryChild = current$$1.child;
15376 if (nextDidTimeout) {
15377 // Timed out. Wrap the children in a fragment fiber to keep them
15378 // separate from the fallback children.
15379 var _nextFallbackChildren2 = nextProps.fallback;
15380 var _primaryChildFragment2 = createFiberFromFragment(
15381 // It shouldn't matter what the pending props are because we aren't
15382 // going to render this fragment.
15383 null, mode, NoWork, null);
15384 _primaryChildFragment2.child = _currentPrimaryChild;
15385
15386 // Even though we're creating a new fiber, there are no new children,
15387 // because we're reusing an already mounted tree. So we don't need to
15388 // schedule a placement.
15389 // primaryChildFragment.effectTag |= Placement;
15390
15391 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
15392 // Outside of concurrent mode, we commit the effects from the
15393 var _progressedState2 = workInProgress.memoizedState;
15394 var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
15395 _primaryChildFragment2.child = _progressedPrimaryChild2;
15396 }
15397
15398 // Because primaryChildFragment is a new fiber that we're inserting as the
15399 // parent of a new tree, we need to set its treeBaseDuration.
15400 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
15401 // treeBaseDuration is the sum of all the child tree base durations.
15402 var _treeBaseDuration = 0;
15403 var _hiddenChild = _primaryChildFragment2.child;
15404 while (_hiddenChild !== null) {
15405 _treeBaseDuration += _hiddenChild.treeBaseDuration;
15406 _hiddenChild = _hiddenChild.sibling;
15407 }
15408 _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
15409 }
15410
15411 // Create a fragment from the fallback children, too.
15412 var _fallbackChildFragment2 = _primaryChildFragment2.sibling = createFiberFromFragment(_nextFallbackChildren2, mode, renderExpirationTime, null);
15413 _fallbackChildFragment2.effectTag |= Placement;
15414 child = _primaryChildFragment2;
15415 _primaryChildFragment2.childExpirationTime = NoWork;
15416 // Skip the primary children, and continue working on the
15417 // fallback children.
15418 next = _fallbackChildFragment2;
15419 child.return = next.return = workInProgress;
15420 } else {
15421 // Still haven't timed out. Continue rendering the children, like we
15422 // normally do.
15423 var _nextPrimaryChildren2 = nextProps.children;
15424 next = child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
15425 }
15426 }
15427 workInProgress.stateNode = current$$1.stateNode;
15428 }
15429
15430 workInProgress.memoizedState = nextState;
15431 workInProgress.child = child;
15432 return next;
15433}
15434
15435function updateDehydratedSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
15436 if (current$$1 === null) {
15437 // During the first pass, we'll bail out and not drill into the children.
15438 // Instead, we'll leave the content in place and try to hydrate it later.
15439 workInProgress.expirationTime = Never;
15440 return null;
15441 }
15442 // We use childExpirationTime to indicate that a child might depend on context, so if
15443 // any context has changed, we need to treat is as if the input might have changed.
15444 var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime;
15445 if (didReceiveUpdate || hasContextChanged$$1) {
15446 // This boundary has changed since the first render. This means that we are now unable to
15447 // hydrate it. We might still be able to hydrate it using an earlier expiration time but
15448 // during this render we can't. Instead, we're going to delete the whole subtree and
15449 // instead inject a new real Suspense boundary to take its place, which may render content
15450 // or fallback. The real Suspense boundary will suspend for a while so we have some time
15451 // to ensure it can produce real content, but all state and pending events will be lost.
15452
15453 // Detach from the current dehydrated boundary.
15454 current$$1.alternate = null;
15455 workInProgress.alternate = null;
15456
15457 // Insert a deletion in the effect list.
15458 var returnFiber = workInProgress.return;
15459 !(returnFiber !== null) ? invariant(false, 'Suspense boundaries are never on the root. This is probably a bug in React.') : void 0;
15460 var last = returnFiber.lastEffect;
15461 if (last !== null) {
15462 last.nextEffect = current$$1;
15463 returnFiber.lastEffect = current$$1;
15464 } else {
15465 returnFiber.firstEffect = returnFiber.lastEffect = current$$1;
15466 }
15467 current$$1.nextEffect = null;
15468 current$$1.effectTag = Deletion;
15469
15470 // Upgrade this work in progress to a real Suspense component.
15471 workInProgress.tag = SuspenseComponent;
15472 workInProgress.stateNode = null;
15473 workInProgress.memoizedState = null;
15474 // This is now an insertion.
15475 workInProgress.effectTag |= Placement;
15476 // Retry as a real Suspense component.
15477 return updateSuspenseComponent(null, workInProgress, renderExpirationTime);
15478 }
15479 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
15480 // This is the first attempt.
15481 reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress);
15482 var nextProps = workInProgress.pendingProps;
15483 var nextChildren = nextProps.children;
15484 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
15485 return workInProgress.child;
15486 } else {
15487 // Something suspended. Leave the existing children in place.
15488 // TODO: In non-concurrent mode, should we commit the nodes we have hydrated so far?
15489 workInProgress.child = null;
15490 return null;
15491 }
15492}
15493
15494function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) {
15495 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
15496 var nextChildren = workInProgress.pendingProps;
15497 if (current$$1 === null) {
15498 // Portals are special because we don't append the children during mount
15499 // but at commit. Therefore we need to track insertions which the normal
15500 // flow doesn't do during mount. This doesn't happen at the root because
15501 // the root always starts with a "current" with a null child.
15502 // TODO: Consider unifying this with how the root works.
15503 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
15504 } else {
15505 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15506 }
15507 return workInProgress.child;
15508}
15509
15510function updateContextProvider(current$$1, workInProgress, renderExpirationTime) {
15511 var providerType = workInProgress.type;
15512 var context = providerType._context;
15513
15514 var newProps = workInProgress.pendingProps;
15515 var oldProps = workInProgress.memoizedProps;
15516
15517 var newValue = newProps.value;
15518
15519 {
15520 var providerPropTypes = workInProgress.type.propTypes;
15521
15522 if (providerPropTypes) {
15523 checkPropTypes_1(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
15524 }
15525 }
15526
15527 pushProvider(workInProgress, newValue);
15528
15529 if (oldProps !== null) {
15530 var oldValue = oldProps.value;
15531 var changedBits = calculateChangedBits(context, newValue, oldValue);
15532 if (changedBits === 0) {
15533 // No change. Bailout early if children are the same.
15534 if (oldProps.children === newProps.children && !hasContextChanged()) {
15535 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15536 }
15537 } else {
15538 // The context value changed. Search for matching consumers and schedule
15539 // them to update.
15540 propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
15541 }
15542 }
15543
15544 var newChildren = newProps.children;
15545 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
15546 return workInProgress.child;
15547}
15548
15549var hasWarnedAboutUsingContextAsConsumer = false;
15550
15551function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) {
15552 var context = workInProgress.type;
15553 // The logic below for Context differs depending on PROD or DEV mode. In
15554 // DEV mode, we create a separate object for Context.Consumer that acts
15555 // like a proxy to Context. This proxy object adds unnecessary code in PROD
15556 // so we use the old behaviour (Context.Consumer references Context) to
15557 // reduce size and overhead. The separate object references context via
15558 // a property called "_context", which also gives us the ability to check
15559 // in DEV mode if this property exists or not and warn if it does not.
15560 {
15561 if (context._context === undefined) {
15562 // This may be because it's a Context (rather than a Consumer).
15563 // Or it may be because it's older React where they're the same thing.
15564 // We only want to warn if we're sure it's a new React.
15565 if (context !== context.Consumer) {
15566 if (!hasWarnedAboutUsingContextAsConsumer) {
15567 hasWarnedAboutUsingContextAsConsumer = true;
15568 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?');
15569 }
15570 }
15571 } else {
15572 context = context._context;
15573 }
15574 }
15575 var newProps = workInProgress.pendingProps;
15576 var render = newProps.children;
15577
15578 {
15579 !(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;
15580 }
15581
15582 prepareToReadContext(workInProgress, renderExpirationTime);
15583 var newValue = readContext(context, newProps.unstable_observedBits);
15584 var newChildren = void 0;
15585 {
15586 ReactCurrentOwner$3.current = workInProgress;
15587 setCurrentPhase('render');
15588 newChildren = render(newValue);
15589 setCurrentPhase(null);
15590 }
15591
15592 // React DevTools reads this flag.
15593 workInProgress.effectTag |= PerformedWork;
15594 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
15595 return workInProgress.child;
15596}
15597
15598function markWorkInProgressReceivedUpdate() {
15599 didReceiveUpdate = true;
15600}
15601
15602function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) {
15603 cancelWorkTimer(workInProgress);
15604
15605 if (current$$1 !== null) {
15606 // Reuse previous context list
15607 workInProgress.contextDependencies = current$$1.contextDependencies;
15608 }
15609
15610 if (enableProfilerTimer) {
15611 // Don't update "base" render times for bailouts.
15612 stopProfilerTimerIfRunning(workInProgress);
15613 }
15614
15615 // Check if the children have any pending work.
15616 var childExpirationTime = workInProgress.childExpirationTime;
15617 if (childExpirationTime < renderExpirationTime) {
15618 // The children don't have any work either. We can skip them.
15619 // TODO: Once we add back resuming, we should check if the children are
15620 // a work-in-progress set. If so, we need to transfer their effects.
15621 return null;
15622 } else {
15623 // This fiber doesn't have work, but its subtree does. Clone the child
15624 // fibers and continue.
15625 cloneChildFibers(current$$1, workInProgress);
15626 return workInProgress.child;
15627 }
15628}
15629
15630function beginWork(current$$1, workInProgress, renderExpirationTime) {
15631 var updateExpirationTime = workInProgress.expirationTime;
15632
15633 if (current$$1 !== null) {
15634 var oldProps = current$$1.memoizedProps;
15635 var newProps = workInProgress.pendingProps;
15636
15637 if (oldProps !== newProps || hasContextChanged()) {
15638 // If props or context changed, mark the fiber as having performed work.
15639 // This may be unset if the props are determined to be equal later (memo).
15640 didReceiveUpdate = true;
15641 } else if (updateExpirationTime < renderExpirationTime) {
15642 didReceiveUpdate = false;
15643 // This fiber does not have any pending work. Bailout without entering
15644 // the begin phase. There's still some bookkeeping we that needs to be done
15645 // in this optimized path, mostly pushing stuff onto the stack.
15646 switch (workInProgress.tag) {
15647 case HostRoot:
15648 pushHostRootContext(workInProgress);
15649 resetHydrationState();
15650 break;
15651 case HostComponent:
15652 pushHostContext(workInProgress);
15653 break;
15654 case ClassComponent:
15655 {
15656 var Component = workInProgress.type;
15657 if (isContextProvider(Component)) {
15658 pushContextProvider(workInProgress);
15659 }
15660 break;
15661 }
15662 case HostPortal:
15663 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
15664 break;
15665 case ContextProvider:
15666 {
15667 var newValue = workInProgress.memoizedProps.value;
15668 pushProvider(workInProgress, newValue);
15669 break;
15670 }
15671 case Profiler:
15672 if (enableProfilerTimer) {
15673 workInProgress.effectTag |= Update;
15674 }
15675 break;
15676 case SuspenseComponent:
15677 {
15678 var state = workInProgress.memoizedState;
15679 var didTimeout = state !== null;
15680 if (didTimeout) {
15681 // If this boundary is currently timed out, we need to decide
15682 // whether to retry the primary children, or to skip over it and
15683 // go straight to the fallback. Check the priority of the primary
15684 var primaryChildFragment = workInProgress.child;
15685 var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
15686 if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
15687 // The primary children have pending work. Use the normal path
15688 // to attempt to render the primary children again.
15689 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
15690 } else {
15691 // The primary children do not have pending work with sufficient
15692 // priority. Bailout.
15693 var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15694 if (child !== null) {
15695 // The fallback children have pending work. Skip over the
15696 // primary children and work on the fallback.
15697 return child.sibling;
15698 } else {
15699 return null;
15700 }
15701 }
15702 }
15703 break;
15704 }
15705 case DehydratedSuspenseComponent:
15706 {
15707 if (enableSuspenseServerRenderer) {
15708 // We know that this component will suspend again because if it has
15709 // been unsuspended it has committed as a regular Suspense component.
15710 // If it needs to be retried, it should have work scheduled on it.
15711 workInProgress.effectTag |= DidCapture;
15712 break;
15713 }
15714 }
15715 }
15716 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15717 }
15718 } else {
15719 didReceiveUpdate = false;
15720 }
15721
15722 // Before entering the begin phase, clear the expiration time.
15723 workInProgress.expirationTime = NoWork;
15724
15725 switch (workInProgress.tag) {
15726 case IndeterminateComponent:
15727 {
15728 var elementType = workInProgress.elementType;
15729 return mountIndeterminateComponent(current$$1, workInProgress, elementType, renderExpirationTime);
15730 }
15731 case LazyComponent:
15732 {
15733 var _elementType = workInProgress.elementType;
15734 return mountLazyComponent(current$$1, workInProgress, _elementType, updateExpirationTime, renderExpirationTime);
15735 }
15736 case FunctionComponent:
15737 {
15738 var _Component = workInProgress.type;
15739 var unresolvedProps = workInProgress.pendingProps;
15740 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
15741 return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime);
15742 }
15743 case ClassComponent:
15744 {
15745 var _Component2 = workInProgress.type;
15746 var _unresolvedProps = workInProgress.pendingProps;
15747 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
15748 return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
15749 }
15750 case HostRoot:
15751 return updateHostRoot(current$$1, workInProgress, renderExpirationTime);
15752 case HostComponent:
15753 return updateHostComponent(current$$1, workInProgress, renderExpirationTime);
15754 case HostText:
15755 return updateHostText(current$$1, workInProgress);
15756 case SuspenseComponent:
15757 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
15758 case HostPortal:
15759 return updatePortalComponent(current$$1, workInProgress, renderExpirationTime);
15760 case ForwardRef:
15761 {
15762 var type = workInProgress.type;
15763 var _unresolvedProps2 = workInProgress.pendingProps;
15764 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
15765 return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime);
15766 }
15767 case Fragment:
15768 return updateFragment(current$$1, workInProgress, renderExpirationTime);
15769 case Mode:
15770 return updateMode(current$$1, workInProgress, renderExpirationTime);
15771 case Profiler:
15772 return updateProfiler(current$$1, workInProgress, renderExpirationTime);
15773 case ContextProvider:
15774 return updateContextProvider(current$$1, workInProgress, renderExpirationTime);
15775 case ContextConsumer:
15776 return updateContextConsumer(current$$1, workInProgress, renderExpirationTime);
15777 case MemoComponent:
15778 {
15779 var _type2 = workInProgress.type;
15780 var _unresolvedProps3 = workInProgress.pendingProps;
15781 // Resolve outer props first, then resolve inner props.
15782 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
15783 {
15784 if (workInProgress.type !== workInProgress.elementType) {
15785 var outerPropTypes = _type2.propTypes;
15786 if (outerPropTypes) {
15787 checkPropTypes_1(outerPropTypes, _resolvedProps3, // Resolved for outer only
15788 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
15789 }
15790 }
15791 }
15792 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
15793 return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
15794 }
15795 case SimpleMemoComponent:
15796 {
15797 return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
15798 }
15799 case IncompleteClassComponent:
15800 {
15801 var _Component3 = workInProgress.type;
15802 var _unresolvedProps4 = workInProgress.pendingProps;
15803 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
15804 return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
15805 }
15806 case DehydratedSuspenseComponent:
15807 {
15808 if (enableSuspenseServerRenderer) {
15809 return updateDehydratedSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
15810 }
15811 break;
15812 }
15813 }
15814 invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
15815}
15816
15817var valueCursor = createCursor(null);
15818
15819var rendererSigil = void 0;
15820{
15821 // Use this to detect multiple renderers using the same context
15822 rendererSigil = {};
15823}
15824
15825var currentlyRenderingFiber = null;
15826var lastContextDependency = null;
15827var lastContextWithAllBitsObserved = null;
15828
15829var isDisallowedContextReadInDEV = false;
15830
15831function resetContextDependences() {
15832 // This is called right before React yields execution, to ensure `readContext`
15833 // cannot be called outside the render phase.
15834 currentlyRenderingFiber = null;
15835 lastContextDependency = null;
15836 lastContextWithAllBitsObserved = null;
15837 {
15838 isDisallowedContextReadInDEV = false;
15839 }
15840}
15841
15842function enterDisallowedContextReadInDEV() {
15843 {
15844 isDisallowedContextReadInDEV = true;
15845 }
15846}
15847
15848function exitDisallowedContextReadInDEV() {
15849 {
15850 isDisallowedContextReadInDEV = false;
15851 }
15852}
15853
15854function pushProvider(providerFiber, nextValue) {
15855 var context = providerFiber.type._context;
15856
15857 if (isPrimaryRenderer) {
15858 push(valueCursor, context._currentValue, providerFiber);
15859
15860 context._currentValue = nextValue;
15861 {
15862 !(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;
15863 context._currentRenderer = rendererSigil;
15864 }
15865 } else {
15866 push(valueCursor, context._currentValue2, providerFiber);
15867
15868 context._currentValue2 = nextValue;
15869 {
15870 !(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;
15871 context._currentRenderer2 = rendererSigil;
15872 }
15873 }
15874}
15875
15876function popProvider(providerFiber) {
15877 var currentValue = valueCursor.current;
15878
15879 pop(valueCursor, providerFiber);
15880
15881 var context = providerFiber.type._context;
15882 if (isPrimaryRenderer) {
15883 context._currentValue = currentValue;
15884 } else {
15885 context._currentValue2 = currentValue;
15886 }
15887}
15888
15889function calculateChangedBits(context, newValue, oldValue) {
15890 if (is(oldValue, newValue)) {
15891 // No change
15892 return 0;
15893 } else {
15894 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : maxSigned31BitInt;
15895
15896 {
15897 !((changedBits & maxSigned31BitInt) === changedBits) ? warning$1(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0;
15898 }
15899 return changedBits | 0;
15900 }
15901}
15902
15903function scheduleWorkOnParentPath(parent, renderExpirationTime) {
15904 // Update the child expiration time of all the ancestors, including
15905 // the alternates.
15906 var node = parent;
15907 while (node !== null) {
15908 var alternate = node.alternate;
15909 if (node.childExpirationTime < renderExpirationTime) {
15910 node.childExpirationTime = renderExpirationTime;
15911 if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
15912 alternate.childExpirationTime = renderExpirationTime;
15913 }
15914 } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
15915 alternate.childExpirationTime = renderExpirationTime;
15916 } else {
15917 // Neither alternate was updated, which means the rest of the
15918 // ancestor path already has sufficient priority.
15919 break;
15920 }
15921 node = node.return;
15922 }
15923}
15924
15925function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
15926 var fiber = workInProgress.child;
15927 if (fiber !== null) {
15928 // Set the return pointer of the child to the work-in-progress fiber.
15929 fiber.return = workInProgress;
15930 }
15931 while (fiber !== null) {
15932 var nextFiber = void 0;
15933
15934 // Visit this fiber.
15935 var list = fiber.contextDependencies;
15936 if (list !== null) {
15937 nextFiber = fiber.child;
15938
15939 var dependency = list.first;
15940 while (dependency !== null) {
15941 // Check if the context matches.
15942 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
15943 // Match! Schedule an update on this fiber.
15944
15945 if (fiber.tag === ClassComponent) {
15946 // Schedule a force update on the work-in-progress.
15947 var update = createUpdate(renderExpirationTime);
15948 update.tag = ForceUpdate;
15949 // TODO: Because we don't have a work-in-progress, this will add the
15950 // update to the current fiber, too, which means it will persist even if
15951 // this render is thrown away. Since it's a race condition, not sure it's
15952 // worth fixing.
15953 enqueueUpdate(fiber, update);
15954 }
15955
15956 if (fiber.expirationTime < renderExpirationTime) {
15957 fiber.expirationTime = renderExpirationTime;
15958 }
15959 var alternate = fiber.alternate;
15960 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
15961 alternate.expirationTime = renderExpirationTime;
15962 }
15963
15964 scheduleWorkOnParentPath(fiber.return, renderExpirationTime);
15965
15966 // Mark the expiration time on the list, too.
15967 if (list.expirationTime < renderExpirationTime) {
15968 list.expirationTime = renderExpirationTime;
15969 }
15970
15971 // Since we already found a match, we can stop traversing the
15972 // dependency list.
15973 break;
15974 }
15975 dependency = dependency.next;
15976 }
15977 } else if (fiber.tag === ContextProvider) {
15978 // Don't scan deeper if this is a matching provider
15979 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
15980 } else if (enableSuspenseServerRenderer && fiber.tag === DehydratedSuspenseComponent) {
15981 // If a dehydrated suspense component is in this subtree, we don't know
15982 // if it will have any context consumers in it. The best we can do is
15983 // mark it as having updates on its children.
15984 if (fiber.expirationTime < renderExpirationTime) {
15985 fiber.expirationTime = renderExpirationTime;
15986 }
15987 var _alternate = fiber.alternate;
15988 if (_alternate !== null && _alternate.expirationTime < renderExpirationTime) {
15989 _alternate.expirationTime = renderExpirationTime;
15990 }
15991 // This is intentionally passing this fiber as the parent
15992 // because we want to schedule this fiber as having work
15993 // on its children. We'll use the childExpirationTime on
15994 // this fiber to indicate that a context has changed.
15995 scheduleWorkOnParentPath(fiber, renderExpirationTime);
15996 nextFiber = fiber.sibling;
15997 } else {
15998 // Traverse down.
15999 nextFiber = fiber.child;
16000 }
16001
16002 if (nextFiber !== null) {
16003 // Set the return pointer of the child to the work-in-progress fiber.
16004 nextFiber.return = fiber;
16005 } else {
16006 // No child. Traverse to next sibling.
16007 nextFiber = fiber;
16008 while (nextFiber !== null) {
16009 if (nextFiber === workInProgress) {
16010 // We're back to the root of this subtree. Exit.
16011 nextFiber = null;
16012 break;
16013 }
16014 var sibling = nextFiber.sibling;
16015 if (sibling !== null) {
16016 // Set the return pointer of the sibling to the work-in-progress fiber.
16017 sibling.return = nextFiber.return;
16018 nextFiber = sibling;
16019 break;
16020 }
16021 // No more siblings. Traverse up.
16022 nextFiber = nextFiber.return;
16023 }
16024 }
16025 fiber = nextFiber;
16026 }
16027}
16028
16029function prepareToReadContext(workInProgress, renderExpirationTime) {
16030 currentlyRenderingFiber = workInProgress;
16031 lastContextDependency = null;
16032 lastContextWithAllBitsObserved = null;
16033
16034 var currentDependencies = workInProgress.contextDependencies;
16035 if (currentDependencies !== null && currentDependencies.expirationTime >= renderExpirationTime) {
16036 // Context list has a pending update. Mark that this fiber performed work.
16037 markWorkInProgressReceivedUpdate();
16038 }
16039
16040 // Reset the work-in-progress list
16041 workInProgress.contextDependencies = null;
16042}
16043
16044function readContext(context, observedBits) {
16045 {
16046 // This warning would fire if you read context inside a Hook like useMemo.
16047 // Unlike the class check below, it's not enforced in production for perf.
16048 !!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;
16049 }
16050
16051 if (lastContextWithAllBitsObserved === context) {
16052 // Nothing to do. We already observe everything in this context.
16053 } else if (observedBits === false || observedBits === 0) {
16054 // Do not observe any updates.
16055 } else {
16056 var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types.
16057 if (typeof observedBits !== 'number' || observedBits === maxSigned31BitInt) {
16058 // Observe all updates.
16059 lastContextWithAllBitsObserved = context;
16060 resolvedObservedBits = maxSigned31BitInt;
16061 } else {
16062 resolvedObservedBits = observedBits;
16063 }
16064
16065 var contextItem = {
16066 context: context,
16067 observedBits: resolvedObservedBits,
16068 next: null
16069 };
16070
16071 if (lastContextDependency === null) {
16072 !(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;
16073
16074 // This is the first dependency for this component. Create a new list.
16075 lastContextDependency = contextItem;
16076 currentlyRenderingFiber.contextDependencies = {
16077 first: contextItem,
16078 expirationTime: NoWork
16079 };
16080 } else {
16081 // Append a new context item.
16082 lastContextDependency = lastContextDependency.next = contextItem;
16083 }
16084 }
16085 return isPrimaryRenderer ? context._currentValue : context._currentValue2;
16086}
16087
16088// UpdateQueue is a linked list of prioritized updates.
16089//
16090// Like fibers, update queues come in pairs: a current queue, which represents
16091// the visible state of the screen, and a work-in-progress queue, which can be
16092// mutated and processed asynchronously before it is committed — a form of
16093// double buffering. If a work-in-progress render is discarded before finishing,
16094// we create a new work-in-progress by cloning the current queue.
16095//
16096// Both queues share a persistent, singly-linked list structure. To schedule an
16097// update, we append it to the end of both queues. Each queue maintains a
16098// pointer to first update in the persistent list that hasn't been processed.
16099// The work-in-progress pointer always has a position equal to or greater than
16100// the current queue, since we always work on that one. The current queue's
16101// pointer is only updated during the commit phase, when we swap in the
16102// work-in-progress.
16103//
16104// For example:
16105//
16106// Current pointer: A - B - C - D - E - F
16107// Work-in-progress pointer: D - E - F
16108// ^
16109// The work-in-progress queue has
16110// processed more updates than current.
16111//
16112// The reason we append to both queues is because otherwise we might drop
16113// updates without ever processing them. For example, if we only add updates to
16114// the work-in-progress queue, some updates could be lost whenever a work-in
16115// -progress render restarts by cloning from current. Similarly, if we only add
16116// updates to the current queue, the updates will be lost whenever an already
16117// in-progress queue commits and swaps with the current queue. However, by
16118// adding to both queues, we guarantee that the update will be part of the next
16119// work-in-progress. (And because the work-in-progress queue becomes the
16120// current queue once it commits, there's no danger of applying the same
16121// update twice.)
16122//
16123// Prioritization
16124// --------------
16125//
16126// Updates are not sorted by priority, but by insertion; new updates are always
16127// appended to the end of the list.
16128//
16129// The priority is still important, though. When processing the update queue
16130// during the render phase, only the updates with sufficient priority are
16131// included in the result. If we skip an update because it has insufficient
16132// priority, it remains in the queue to be processed later, during a lower
16133// priority render. Crucially, all updates subsequent to a skipped update also
16134// remain in the queue *regardless of their priority*. That means high priority
16135// updates are sometimes processed twice, at two separate priorities. We also
16136// keep track of a base state, that represents the state before the first
16137// update in the queue is applied.
16138//
16139// For example:
16140//
16141// Given a base state of '', and the following queue of updates
16142//
16143// A1 - B2 - C1 - D2
16144//
16145// where the number indicates the priority, and the update is applied to the
16146// previous state by appending a letter, React will process these updates as
16147// two separate renders, one per distinct priority level:
16148//
16149// First render, at priority 1:
16150// Base state: ''
16151// Updates: [A1, C1]
16152// Result state: 'AC'
16153//
16154// Second render, at priority 2:
16155// Base state: 'A' <- The base state does not include C1,
16156// because B2 was skipped.
16157// Updates: [B2, C1, D2] <- C1 was rebased on top of B2
16158// Result state: 'ABCD'
16159//
16160// Because we process updates in insertion order, and rebase high priority
16161// updates when preceding updates are skipped, the final result is deterministic
16162// regardless of priority. Intermediate state may vary according to system
16163// resources, but the final state is always the same.
16164
16165var UpdateState = 0;
16166var ReplaceState = 1;
16167var ForceUpdate = 2;
16168var CaptureUpdate = 3;
16169
16170// Global state that is reset at the beginning of calling `processUpdateQueue`.
16171// It should only be read right after calling `processUpdateQueue`, via
16172// `checkHasForceUpdateAfterProcessing`.
16173var hasForceUpdate = false;
16174
16175var didWarnUpdateInsideUpdate = void 0;
16176var currentlyProcessingQueue = void 0;
16177var resetCurrentlyProcessingQueue = void 0;
16178{
16179 didWarnUpdateInsideUpdate = false;
16180 currentlyProcessingQueue = null;
16181 resetCurrentlyProcessingQueue = function () {
16182 currentlyProcessingQueue = null;
16183 };
16184}
16185
16186function createUpdateQueue(baseState) {
16187 var queue = {
16188 baseState: baseState,
16189 firstUpdate: null,
16190 lastUpdate: null,
16191 firstCapturedUpdate: null,
16192 lastCapturedUpdate: null,
16193 firstEffect: null,
16194 lastEffect: null,
16195 firstCapturedEffect: null,
16196 lastCapturedEffect: null
16197 };
16198 return queue;
16199}
16200
16201function cloneUpdateQueue(currentQueue) {
16202 var queue = {
16203 baseState: currentQueue.baseState,
16204 firstUpdate: currentQueue.firstUpdate,
16205 lastUpdate: currentQueue.lastUpdate,
16206
16207 // TODO: With resuming, if we bail out and resuse the child tree, we should
16208 // keep these effects.
16209 firstCapturedUpdate: null,
16210 lastCapturedUpdate: null,
16211
16212 firstEffect: null,
16213 lastEffect: null,
16214
16215 firstCapturedEffect: null,
16216 lastCapturedEffect: null
16217 };
16218 return queue;
16219}
16220
16221function createUpdate(expirationTime) {
16222 return {
16223 expirationTime: expirationTime,
16224
16225 tag: UpdateState,
16226 payload: null,
16227 callback: null,
16228
16229 next: null,
16230 nextEffect: null
16231 };
16232}
16233
16234function appendUpdateToQueue(queue, update) {
16235 // Append the update to the end of the list.
16236 if (queue.lastUpdate === null) {
16237 // Queue is empty
16238 queue.firstUpdate = queue.lastUpdate = update;
16239 } else {
16240 queue.lastUpdate.next = update;
16241 queue.lastUpdate = update;
16242 }
16243}
16244
16245function enqueueUpdate(fiber, update) {
16246 // Update queues are created lazily.
16247 var alternate = fiber.alternate;
16248 var queue1 = void 0;
16249 var queue2 = void 0;
16250 if (alternate === null) {
16251 // There's only one fiber.
16252 queue1 = fiber.updateQueue;
16253 queue2 = null;
16254 if (queue1 === null) {
16255 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
16256 }
16257 } else {
16258 // There are two owners.
16259 queue1 = fiber.updateQueue;
16260 queue2 = alternate.updateQueue;
16261 if (queue1 === null) {
16262 if (queue2 === null) {
16263 // Neither fiber has an update queue. Create new ones.
16264 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
16265 queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
16266 } else {
16267 // Only one fiber has an update queue. Clone to create a new one.
16268 queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
16269 }
16270 } else {
16271 if (queue2 === null) {
16272 // Only one fiber has an update queue. Clone to create a new one.
16273 queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
16274 } else {
16275 // Both owners have an update queue.
16276 }
16277 }
16278 }
16279 if (queue2 === null || queue1 === queue2) {
16280 // There's only a single queue.
16281 appendUpdateToQueue(queue1, update);
16282 } else {
16283 // There are two queues. We need to append the update to both queues,
16284 // while accounting for the persistent structure of the list — we don't
16285 // want the same update to be added multiple times.
16286 if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
16287 // One of the queues is not empty. We must add the update to both queues.
16288 appendUpdateToQueue(queue1, update);
16289 appendUpdateToQueue(queue2, update);
16290 } else {
16291 // Both queues are non-empty. The last update is the same in both lists,
16292 // because of structural sharing. So, only append to one of the lists.
16293 appendUpdateToQueue(queue1, update);
16294 // But we still need to update the `lastUpdate` pointer of queue2.
16295 queue2.lastUpdate = update;
16296 }
16297 }
16298
16299 {
16300 if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
16301 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.');
16302 didWarnUpdateInsideUpdate = true;
16303 }
16304 }
16305}
16306
16307function enqueueCapturedUpdate(workInProgress, update) {
16308 // Captured updates go into a separate list, and only on the work-in-
16309 // progress queue.
16310 var workInProgressQueue = workInProgress.updateQueue;
16311 if (workInProgressQueue === null) {
16312 workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
16313 } else {
16314 // TODO: I put this here rather than createWorkInProgress so that we don't
16315 // clone the queue unnecessarily. There's probably a better way to
16316 // structure this.
16317 workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
16318 }
16319
16320 // Append the update to the end of the list.
16321 if (workInProgressQueue.lastCapturedUpdate === null) {
16322 // This is the first render phase update
16323 workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
16324 } else {
16325 workInProgressQueue.lastCapturedUpdate.next = update;
16326 workInProgressQueue.lastCapturedUpdate = update;
16327 }
16328}
16329
16330function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
16331 var current = workInProgress.alternate;
16332 if (current !== null) {
16333 // If the work-in-progress queue is equal to the current queue,
16334 // we need to clone it first.
16335 if (queue === current.updateQueue) {
16336 queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
16337 }
16338 }
16339 return queue;
16340}
16341
16342function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
16343 switch (update.tag) {
16344 case ReplaceState:
16345 {
16346 var _payload = update.payload;
16347 if (typeof _payload === 'function') {
16348 // Updater function
16349 {
16350 enterDisallowedContextReadInDEV();
16351 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
16352 _payload.call(instance, prevState, nextProps);
16353 }
16354 }
16355 var nextState = _payload.call(instance, prevState, nextProps);
16356 {
16357 exitDisallowedContextReadInDEV();
16358 }
16359 return nextState;
16360 }
16361 // State object
16362 return _payload;
16363 }
16364 case CaptureUpdate:
16365 {
16366 workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
16367 }
16368 // Intentional fallthrough
16369 case UpdateState:
16370 {
16371 var _payload2 = update.payload;
16372 var partialState = void 0;
16373 if (typeof _payload2 === 'function') {
16374 // Updater function
16375 {
16376 enterDisallowedContextReadInDEV();
16377 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
16378 _payload2.call(instance, prevState, nextProps);
16379 }
16380 }
16381 partialState = _payload2.call(instance, prevState, nextProps);
16382 {
16383 exitDisallowedContextReadInDEV();
16384 }
16385 } else {
16386 // Partial state object
16387 partialState = _payload2;
16388 }
16389 if (partialState === null || partialState === undefined) {
16390 // Null and undefined are treated as no-ops.
16391 return prevState;
16392 }
16393 // Merge the partial state and the previous state.
16394 return _assign({}, prevState, partialState);
16395 }
16396 case ForceUpdate:
16397 {
16398 hasForceUpdate = true;
16399 return prevState;
16400 }
16401 }
16402 return prevState;
16403}
16404
16405function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
16406 hasForceUpdate = false;
16407
16408 queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
16409
16410 {
16411 currentlyProcessingQueue = queue;
16412 }
16413
16414 // These values may change as we process the queue.
16415 var newBaseState = queue.baseState;
16416 var newFirstUpdate = null;
16417 var newExpirationTime = NoWork;
16418
16419 // Iterate through the list of updates to compute the result.
16420 var update = queue.firstUpdate;
16421 var resultState = newBaseState;
16422 while (update !== null) {
16423 var updateExpirationTime = update.expirationTime;
16424 if (updateExpirationTime < renderExpirationTime) {
16425 // This update does not have sufficient priority. Skip it.
16426 if (newFirstUpdate === null) {
16427 // This is the first skipped update. It will be the first update in
16428 // the new list.
16429 newFirstUpdate = update;
16430 // Since this is the first update that was skipped, the current result
16431 // is the new base state.
16432 newBaseState = resultState;
16433 }
16434 // Since this update will remain in the list, update the remaining
16435 // expiration time.
16436 if (newExpirationTime < updateExpirationTime) {
16437 newExpirationTime = updateExpirationTime;
16438 }
16439 } else {
16440 // This update does have sufficient priority. Process it and compute
16441 // a new result.
16442 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
16443 var _callback = update.callback;
16444 if (_callback !== null) {
16445 workInProgress.effectTag |= Callback;
16446 // Set this to null, in case it was mutated during an aborted render.
16447 update.nextEffect = null;
16448 if (queue.lastEffect === null) {
16449 queue.firstEffect = queue.lastEffect = update;
16450 } else {
16451 queue.lastEffect.nextEffect = update;
16452 queue.lastEffect = update;
16453 }
16454 }
16455 }
16456 // Continue to the next update.
16457 update = update.next;
16458 }
16459
16460 // Separately, iterate though the list of captured updates.
16461 var newFirstCapturedUpdate = null;
16462 update = queue.firstCapturedUpdate;
16463 while (update !== null) {
16464 var _updateExpirationTime = update.expirationTime;
16465 if (_updateExpirationTime < renderExpirationTime) {
16466 // This update does not have sufficient priority. Skip it.
16467 if (newFirstCapturedUpdate === null) {
16468 // This is the first skipped captured update. It will be the first
16469 // update in the new list.
16470 newFirstCapturedUpdate = update;
16471 // If this is the first update that was skipped, the current result is
16472 // the new base state.
16473 if (newFirstUpdate === null) {
16474 newBaseState = resultState;
16475 }
16476 }
16477 // Since this update will remain in the list, update the remaining
16478 // expiration time.
16479 if (newExpirationTime < _updateExpirationTime) {
16480 newExpirationTime = _updateExpirationTime;
16481 }
16482 } else {
16483 // This update does have sufficient priority. Process it and compute
16484 // a new result.
16485 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
16486 var _callback2 = update.callback;
16487 if (_callback2 !== null) {
16488 workInProgress.effectTag |= Callback;
16489 // Set this to null, in case it was mutated during an aborted render.
16490 update.nextEffect = null;
16491 if (queue.lastCapturedEffect === null) {
16492 queue.firstCapturedEffect = queue.lastCapturedEffect = update;
16493 } else {
16494 queue.lastCapturedEffect.nextEffect = update;
16495 queue.lastCapturedEffect = update;
16496 }
16497 }
16498 }
16499 update = update.next;
16500 }
16501
16502 if (newFirstUpdate === null) {
16503 queue.lastUpdate = null;
16504 }
16505 if (newFirstCapturedUpdate === null) {
16506 queue.lastCapturedUpdate = null;
16507 } else {
16508 workInProgress.effectTag |= Callback;
16509 }
16510 if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
16511 // We processed every update, without skipping. That means the new base
16512 // state is the same as the result state.
16513 newBaseState = resultState;
16514 }
16515
16516 queue.baseState = newBaseState;
16517 queue.firstUpdate = newFirstUpdate;
16518 queue.firstCapturedUpdate = newFirstCapturedUpdate;
16519
16520 // Set the remaining expiration time to be whatever is remaining in the queue.
16521 // This should be fine because the only two other things that contribute to
16522 // expiration time are props and context. We're already in the middle of the
16523 // begin phase by the time we start processing the queue, so we've already
16524 // dealt with the props. Context in components that specify
16525 // shouldComponentUpdate is tricky; but we'll have to account for
16526 // that regardless.
16527 workInProgress.expirationTime = newExpirationTime;
16528 workInProgress.memoizedState = resultState;
16529
16530 {
16531 currentlyProcessingQueue = null;
16532 }
16533}
16534
16535function callCallback(callback, context) {
16536 !(typeof callback === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', callback) : void 0;
16537 callback.call(context);
16538}
16539
16540function resetHasForceUpdateBeforeProcessing() {
16541 hasForceUpdate = false;
16542}
16543
16544function checkHasForceUpdateAfterProcessing() {
16545 return hasForceUpdate;
16546}
16547
16548function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
16549 // If the finished render included captured updates, and there are still
16550 // lower priority updates left over, we need to keep the captured updates
16551 // in the queue so that they are rebased and not dropped once we process the
16552 // queue again at the lower priority.
16553 if (finishedQueue.firstCapturedUpdate !== null) {
16554 // Join the captured update list to the end of the normal list.
16555 if (finishedQueue.lastUpdate !== null) {
16556 finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
16557 finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
16558 }
16559 // Clear the list of captured updates.
16560 finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
16561 }
16562
16563 // Commit the effects
16564 commitUpdateEffects(finishedQueue.firstEffect, instance);
16565 finishedQueue.firstEffect = finishedQueue.lastEffect = null;
16566
16567 commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
16568 finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
16569}
16570
16571function commitUpdateEffects(effect, instance) {
16572 while (effect !== null) {
16573 var _callback3 = effect.callback;
16574 if (_callback3 !== null) {
16575 effect.callback = null;
16576 callCallback(_callback3, instance);
16577 }
16578 effect = effect.nextEffect;
16579 }
16580}
16581
16582function createCapturedValue(value, source) {
16583 // If the value is an error, call this function immediately after it is thrown
16584 // so the stack is accurate.
16585 return {
16586 value: value,
16587 source: source,
16588 stack: getStackByFiberInDevAndProd(source)
16589 };
16590}
16591
16592function markUpdate(workInProgress) {
16593 // Tag the fiber with an update effect. This turns a Placement into
16594 // a PlacementAndUpdate.
16595 workInProgress.effectTag |= Update;
16596}
16597
16598function markRef$1(workInProgress) {
16599 workInProgress.effectTag |= Ref;
16600}
16601
16602var appendAllChildren = void 0;
16603var updateHostContainer = void 0;
16604var updateHostComponent$1 = void 0;
16605var updateHostText$1 = void 0;
16606if (supportsMutation) {
16607 // Mutation mode
16608
16609 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
16610 // We only have the top Fiber that was created but we need recurse down its
16611 // children to find all the terminal nodes.
16612 var node = workInProgress.child;
16613 while (node !== null) {
16614 if (node.tag === HostComponent || node.tag === HostText) {
16615 appendInitialChild(parent, node.stateNode);
16616 } else if (node.tag === HostPortal) {
16617 // If we have a portal child, then we don't want to traverse
16618 // down its children. Instead, we'll get insertions from each child in
16619 // the portal directly.
16620 } else if (node.child !== null) {
16621 node.child.return = node;
16622 node = node.child;
16623 continue;
16624 }
16625 if (node === workInProgress) {
16626 return;
16627 }
16628 while (node.sibling === null) {
16629 if (node.return === null || node.return === workInProgress) {
16630 return;
16631 }
16632 node = node.return;
16633 }
16634 node.sibling.return = node.return;
16635 node = node.sibling;
16636 }
16637 };
16638
16639 updateHostContainer = function (workInProgress) {
16640 // Noop
16641 };
16642 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
16643 // If we have an alternate, that means this is an update and we need to
16644 // schedule a side-effect to do the updates.
16645 var oldProps = current.memoizedProps;
16646 if (oldProps === newProps) {
16647 // In mutation mode, this is sufficient for a bailout because
16648 // we won't touch this node even if children changed.
16649 return;
16650 }
16651
16652 // If we get updated because one of our children updated, we don't
16653 // have newProps so we'll have to reuse them.
16654 // TODO: Split the update API as separate for the props vs. children.
16655 // Even better would be if children weren't special cased at all tho.
16656 var instance = workInProgress.stateNode;
16657 var currentHostContext = getHostContext();
16658 // TODO: Experiencing an error where oldProps is null. Suggests a host
16659 // component is hitting the resume path. Figure out why. Possibly
16660 // related to `hidden`.
16661 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
16662 // TODO: Type this specific to this type of component.
16663 workInProgress.updateQueue = updatePayload;
16664 // If the update payload indicates that there is a change or if there
16665 // is a new ref we mark this as an update. All the work is done in commitWork.
16666 if (updatePayload) {
16667 markUpdate(workInProgress);
16668 }
16669 };
16670 updateHostText$1 = function (current, workInProgress, oldText, newText) {
16671 // If the text differs, mark it as an update. All the work in done in commitWork.
16672 if (oldText !== newText) {
16673 markUpdate(workInProgress);
16674 }
16675 };
16676} else if (supportsPersistence) {
16677 // Persistent host tree mode
16678
16679 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
16680 // We only have the top Fiber that was created but we need recurse down its
16681 // children to find all the terminal nodes.
16682 var node = workInProgress.child;
16683 while (node !== null) {
16684 // eslint-disable-next-line no-labels
16685 branches: if (node.tag === HostComponent) {
16686 var instance = node.stateNode;
16687 if (needsVisibilityToggle) {
16688 var props = node.memoizedProps;
16689 var type = node.type;
16690 if (isHidden) {
16691 // This child is inside a timed out tree. Hide it.
16692 instance = cloneHiddenInstance(instance, type, props, node);
16693 } else {
16694 // This child was previously inside a timed out tree. If it was not
16695 // updated during this render, it may need to be unhidden. Clone
16696 // again to be sure.
16697 instance = cloneUnhiddenInstance(instance, type, props, node);
16698 }
16699 node.stateNode = instance;
16700 }
16701 appendInitialChild(parent, instance);
16702 } else if (node.tag === HostText) {
16703 var _instance = node.stateNode;
16704 if (needsVisibilityToggle) {
16705 var text = node.memoizedProps;
16706 var rootContainerInstance = getRootHostContainer();
16707 var currentHostContext = getHostContext();
16708 if (isHidden) {
16709 _instance = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16710 } else {
16711 _instance = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16712 }
16713 node.stateNode = _instance;
16714 }
16715 appendInitialChild(parent, _instance);
16716 } else if (node.tag === HostPortal) {
16717 // If we have a portal child, then we don't want to traverse
16718 // down its children. Instead, we'll get insertions from each child in
16719 // the portal directly.
16720 } else if (node.tag === SuspenseComponent) {
16721 var current = node.alternate;
16722 if (current !== null) {
16723 var oldState = current.memoizedState;
16724 var newState = node.memoizedState;
16725 var oldIsHidden = oldState !== null;
16726 var newIsHidden = newState !== null;
16727 if (oldIsHidden !== newIsHidden) {
16728 // The placeholder either just timed out or switched back to the normal
16729 // children after having previously timed out. Toggle the visibility of
16730 // the direct host children.
16731 var primaryChildParent = newIsHidden ? node.child : node;
16732 if (primaryChildParent !== null) {
16733 appendAllChildren(parent, primaryChildParent, true, newIsHidden);
16734 }
16735 // eslint-disable-next-line no-labels
16736 break branches;
16737 }
16738 }
16739 if (node.child !== null) {
16740 // Continue traversing like normal
16741 node.child.return = node;
16742 node = node.child;
16743 continue;
16744 }
16745 } else if (node.child !== null) {
16746 node.child.return = node;
16747 node = node.child;
16748 continue;
16749 }
16750 // $FlowFixMe This is correct but Flow is confused by the labeled break.
16751 node = node;
16752 if (node === workInProgress) {
16753 return;
16754 }
16755 while (node.sibling === null) {
16756 if (node.return === null || node.return === workInProgress) {
16757 return;
16758 }
16759 node = node.return;
16760 }
16761 node.sibling.return = node.return;
16762 node = node.sibling;
16763 }
16764 };
16765
16766 // An unfortunate fork of appendAllChildren because we have two different parent types.
16767 var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
16768 // We only have the top Fiber that was created but we need recurse down its
16769 // children to find all the terminal nodes.
16770 var node = workInProgress.child;
16771 while (node !== null) {
16772 // eslint-disable-next-line no-labels
16773 branches: if (node.tag === HostComponent) {
16774 var instance = node.stateNode;
16775 if (needsVisibilityToggle) {
16776 var props = node.memoizedProps;
16777 var type = node.type;
16778 if (isHidden) {
16779 // This child is inside a timed out tree. Hide it.
16780 instance = cloneHiddenInstance(instance, type, props, node);
16781 } else {
16782 // This child was previously inside a timed out tree. If it was not
16783 // updated during this render, it may need to be unhidden. Clone
16784 // again to be sure.
16785 instance = cloneUnhiddenInstance(instance, type, props, node);
16786 }
16787 node.stateNode = instance;
16788 }
16789 appendChildToContainerChildSet(containerChildSet, instance);
16790 } else if (node.tag === HostText) {
16791 var _instance2 = node.stateNode;
16792 if (needsVisibilityToggle) {
16793 var text = node.memoizedProps;
16794 var rootContainerInstance = getRootHostContainer();
16795 var currentHostContext = getHostContext();
16796 if (isHidden) {
16797 _instance2 = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16798 } else {
16799 _instance2 = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16800 }
16801 node.stateNode = _instance2;
16802 }
16803 appendChildToContainerChildSet(containerChildSet, _instance2);
16804 } else if (node.tag === HostPortal) {
16805 // If we have a portal child, then we don't want to traverse
16806 // down its children. Instead, we'll get insertions from each child in
16807 // the portal directly.
16808 } else if (node.tag === SuspenseComponent) {
16809 var current = node.alternate;
16810 if (current !== null) {
16811 var oldState = current.memoizedState;
16812 var newState = node.memoizedState;
16813 var oldIsHidden = oldState !== null;
16814 var newIsHidden = newState !== null;
16815 if (oldIsHidden !== newIsHidden) {
16816 // The placeholder either just timed out or switched back to the normal
16817 // children after having previously timed out. Toggle the visibility of
16818 // the direct host children.
16819 var primaryChildParent = newIsHidden ? node.child : node;
16820 if (primaryChildParent !== null) {
16821 appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
16822 }
16823 // eslint-disable-next-line no-labels
16824 break branches;
16825 }
16826 }
16827 if (node.child !== null) {
16828 // Continue traversing like normal
16829 node.child.return = node;
16830 node = node.child;
16831 continue;
16832 }
16833 } else if (node.child !== null) {
16834 node.child.return = node;
16835 node = node.child;
16836 continue;
16837 }
16838 // $FlowFixMe This is correct but Flow is confused by the labeled break.
16839 node = node;
16840 if (node === workInProgress) {
16841 return;
16842 }
16843 while (node.sibling === null) {
16844 if (node.return === null || node.return === workInProgress) {
16845 return;
16846 }
16847 node = node.return;
16848 }
16849 node.sibling.return = node.return;
16850 node = node.sibling;
16851 }
16852 };
16853 updateHostContainer = function (workInProgress) {
16854 var portalOrRoot = workInProgress.stateNode;
16855 var childrenUnchanged = workInProgress.firstEffect === null;
16856 if (childrenUnchanged) {
16857 // No changes, just reuse the existing instance.
16858 } else {
16859 var container = portalOrRoot.containerInfo;
16860 var newChildSet = createContainerChildSet(container);
16861 // If children might have changed, we have to add them all to the set.
16862 appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
16863 portalOrRoot.pendingChildren = newChildSet;
16864 // Schedule an update on the container to swap out the container.
16865 markUpdate(workInProgress);
16866 finalizeContainerChildren(container, newChildSet);
16867 }
16868 };
16869 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
16870 var currentInstance = current.stateNode;
16871 var oldProps = current.memoizedProps;
16872 // If there are no effects associated with this node, then none of our children had any updates.
16873 // This guarantees that we can reuse all of them.
16874 var childrenUnchanged = workInProgress.firstEffect === null;
16875 if (childrenUnchanged && oldProps === newProps) {
16876 // No changes, just reuse the existing instance.
16877 // Note that this might release a previous clone.
16878 workInProgress.stateNode = currentInstance;
16879 return;
16880 }
16881 var recyclableInstance = workInProgress.stateNode;
16882 var currentHostContext = getHostContext();
16883 var updatePayload = null;
16884 if (oldProps !== newProps) {
16885 updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
16886 }
16887 if (childrenUnchanged && updatePayload === null) {
16888 // No changes, just reuse the existing instance.
16889 // Note that this might release a previous clone.
16890 workInProgress.stateNode = currentInstance;
16891 return;
16892 }
16893 var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
16894 if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
16895 markUpdate(workInProgress);
16896 }
16897 workInProgress.stateNode = newInstance;
16898 if (childrenUnchanged) {
16899 // If there are no other effects in this tree, we need to flag this node as having one.
16900 // Even though we're not going to use it for anything.
16901 // Otherwise parents won't know that there are new children to propagate upwards.
16902 markUpdate(workInProgress);
16903 } else {
16904 // If children might have changed, we have to add them all to the set.
16905 appendAllChildren(newInstance, workInProgress, false, false);
16906 }
16907 };
16908 updateHostText$1 = function (current, workInProgress, oldText, newText) {
16909 if (oldText !== newText) {
16910 // If the text content differs, we'll create a new text instance for it.
16911 var rootContainerInstance = getRootHostContainer();
16912 var currentHostContext = getHostContext();
16913 workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress);
16914 // We'll have to mark it as having an effect, even though we won't use the effect for anything.
16915 // This lets the parents know that at least one of their children has changed.
16916 markUpdate(workInProgress);
16917 }
16918 };
16919} else {
16920 // No host operations
16921 updateHostContainer = function (workInProgress) {
16922 // Noop
16923 };
16924 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
16925 // Noop
16926 };
16927 updateHostText$1 = function (current, workInProgress, oldText, newText) {
16928 // Noop
16929 };
16930}
16931
16932function completeWork(current, workInProgress, renderExpirationTime) {
16933 var newProps = workInProgress.pendingProps;
16934
16935 switch (workInProgress.tag) {
16936 case IndeterminateComponent:
16937 break;
16938 case LazyComponent:
16939 break;
16940 case SimpleMemoComponent:
16941 case FunctionComponent:
16942 break;
16943 case ClassComponent:
16944 {
16945 var Component = workInProgress.type;
16946 if (isContextProvider(Component)) {
16947 popContext(workInProgress);
16948 }
16949 break;
16950 }
16951 case HostRoot:
16952 {
16953 popHostContainer(workInProgress);
16954 popTopLevelContextObject(workInProgress);
16955 var fiberRoot = workInProgress.stateNode;
16956 if (fiberRoot.pendingContext) {
16957 fiberRoot.context = fiberRoot.pendingContext;
16958 fiberRoot.pendingContext = null;
16959 }
16960 if (current === null || current.child === null) {
16961 // If we hydrated, pop so that we can delete any remaining children
16962 // that weren't hydrated.
16963 popHydrationState(workInProgress);
16964 // This resets the hacky state to fix isMounted before committing.
16965 // TODO: Delete this when we delete isMounted and findDOMNode.
16966 workInProgress.effectTag &= ~Placement;
16967 }
16968 updateHostContainer(workInProgress);
16969 break;
16970 }
16971 case HostComponent:
16972 {
16973 popHostContext(workInProgress);
16974 var rootContainerInstance = getRootHostContainer();
16975 var type = workInProgress.type;
16976 if (current !== null && workInProgress.stateNode != null) {
16977 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
16978
16979 if (current.ref !== workInProgress.ref) {
16980 markRef$1(workInProgress);
16981 }
16982 } else {
16983 if (!newProps) {
16984 !(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;
16985 // This can happen when we abort work.
16986 break;
16987 }
16988
16989 var currentHostContext = getHostContext();
16990 // TODO: Move createInstance to beginWork and keep it on a context
16991 // "stack" as the parent. Then append children as we go in beginWork
16992 // or completeWork depending on we want to add then top->down or
16993 // bottom->up. Top->down is faster in IE11.
16994 var wasHydrated = popHydrationState(workInProgress);
16995 if (wasHydrated) {
16996 // TODO: Move this and createInstance step into the beginPhase
16997 // to consolidate.
16998 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
16999 // If changes to the hydrated node needs to be applied at the
17000 // commit-phase we mark this as such.
17001 markUpdate(workInProgress);
17002 }
17003 } else {
17004 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
17005
17006 appendAllChildren(instance, workInProgress, false, false);
17007
17008 // Certain renderers require commit-time effects for initial mount.
17009 // (eg DOM renderer supports auto-focus for certain elements).
17010 // Make sure such renderers get scheduled for later work.
17011 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
17012 markUpdate(workInProgress);
17013 }
17014 workInProgress.stateNode = instance;
17015 }
17016
17017 if (workInProgress.ref !== null) {
17018 // If there is a ref on a host node we need to schedule a callback
17019 markRef$1(workInProgress);
17020 }
17021 }
17022 break;
17023 }
17024 case HostText:
17025 {
17026 var newText = newProps;
17027 if (current && workInProgress.stateNode != null) {
17028 var oldText = current.memoizedProps;
17029 // If we have an alternate, that means this is an update and we need
17030 // to schedule a side-effect to do the updates.
17031 updateHostText$1(current, workInProgress, oldText, newText);
17032 } else {
17033 if (typeof newText !== 'string') {
17034 !(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;
17035 // This can happen when we abort work.
17036 }
17037 var _rootContainerInstance = getRootHostContainer();
17038 var _currentHostContext = getHostContext();
17039 var _wasHydrated = popHydrationState(workInProgress);
17040 if (_wasHydrated) {
17041 if (prepareToHydrateHostTextInstance(workInProgress)) {
17042 markUpdate(workInProgress);
17043 }
17044 } else {
17045 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
17046 }
17047 }
17048 break;
17049 }
17050 case ForwardRef:
17051 break;
17052 case SuspenseComponent:
17053 {
17054 var nextState = workInProgress.memoizedState;
17055 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
17056 // Something suspended. Re-render with the fallback children.
17057 workInProgress.expirationTime = renderExpirationTime;
17058 // Do not reset the effect list.
17059 return workInProgress;
17060 }
17061
17062 var nextDidTimeout = nextState !== null;
17063 var prevDidTimeout = current !== null && current.memoizedState !== null;
17064
17065 if (current !== null && !nextDidTimeout && prevDidTimeout) {
17066 // We just switched from the fallback to the normal children. Delete
17067 // the fallback.
17068 // TODO: Would it be better to store the fallback fragment on
17069 var currentFallbackChild = current.child.sibling;
17070 if (currentFallbackChild !== null) {
17071 // Deletions go at the beginning of the return fiber's effect list
17072 var first = workInProgress.firstEffect;
17073 if (first !== null) {
17074 workInProgress.firstEffect = currentFallbackChild;
17075 currentFallbackChild.nextEffect = first;
17076 } else {
17077 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
17078 currentFallbackChild.nextEffect = null;
17079 }
17080 currentFallbackChild.effectTag = Deletion;
17081 }
17082 }
17083
17084 if (nextDidTimeout || prevDidTimeout) {
17085 // If the children are hidden, or if they were previous hidden, schedule
17086 // an effect to toggle their visibility. This is also used to attach a
17087 // retry listener to the promise.
17088 workInProgress.effectTag |= Update;
17089 }
17090 break;
17091 }
17092 case Fragment:
17093 break;
17094 case Mode:
17095 break;
17096 case Profiler:
17097 break;
17098 case HostPortal:
17099 popHostContainer(workInProgress);
17100 updateHostContainer(workInProgress);
17101 break;
17102 case ContextProvider:
17103 // Pop provider fiber
17104 popProvider(workInProgress);
17105 break;
17106 case ContextConsumer:
17107 break;
17108 case MemoComponent:
17109 break;
17110 case IncompleteClassComponent:
17111 {
17112 // Same as class component case. I put it down here so that the tags are
17113 // sequential to ensure this switch is compiled to a jump table.
17114 var _Component = workInProgress.type;
17115 if (isContextProvider(_Component)) {
17116 popContext(workInProgress);
17117 }
17118 break;
17119 }
17120 case DehydratedSuspenseComponent:
17121 {
17122 if (enableSuspenseServerRenderer) {
17123 if (current === null) {
17124 var _wasHydrated2 = popHydrationState(workInProgress);
17125 !_wasHydrated2 ? invariant(false, 'A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React.') : void 0;
17126 skipPastDehydratedSuspenseInstance(workInProgress);
17127 } else if ((workInProgress.effectTag & DidCapture) === NoEffect) {
17128 // This boundary did not suspend so it's now hydrated.
17129 // To handle any future suspense cases, we're going to now upgrade it
17130 // to a Suspense component. We detach it from the existing current fiber.
17131 current.alternate = null;
17132 workInProgress.alternate = null;
17133 workInProgress.tag = SuspenseComponent;
17134 workInProgress.memoizedState = null;
17135 workInProgress.stateNode = null;
17136 }
17137 }
17138 break;
17139 }
17140 default:
17141 invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
17142 }
17143
17144 return null;
17145}
17146
17147function shouldCaptureSuspense(workInProgress) {
17148 // In order to capture, the Suspense component must have a fallback prop.
17149 if (workInProgress.memoizedProps.fallback === undefined) {
17150 return false;
17151 }
17152 // If it was the primary children that just suspended, capture and render the
17153 // fallback. Otherwise, don't capture and bubble to the next boundary.
17154 var nextState = workInProgress.memoizedState;
17155 return nextState === null;
17156}
17157
17158// This module is forked in different environments.
17159// By default, return `true` to log errors to the console.
17160// Forks can return `false` if this isn't desirable.
17161function showErrorDialog(capturedError) {
17162 return true;
17163}
17164
17165function logCapturedError(capturedError) {
17166 var logError = showErrorDialog(capturedError);
17167
17168 // Allow injected showErrorDialog() to prevent default console.error logging.
17169 // This enables renderers like ReactNative to better manage redbox behavior.
17170 if (logError === false) {
17171 return;
17172 }
17173
17174 var error = capturedError.error;
17175 {
17176 var componentName = capturedError.componentName,
17177 componentStack = capturedError.componentStack,
17178 errorBoundaryName = capturedError.errorBoundaryName,
17179 errorBoundaryFound = capturedError.errorBoundaryFound,
17180 willRetry = capturedError.willRetry;
17181
17182 // Browsers support silencing uncaught errors by calling
17183 // `preventDefault()` in window `error` handler.
17184 // We record this information as an expando on the error.
17185
17186 if (error != null && error._suppressLogging) {
17187 if (errorBoundaryFound && willRetry) {
17188 // The error is recoverable and was silenced.
17189 // Ignore it and don't print the stack addendum.
17190 // This is handy for testing error boundaries without noise.
17191 return;
17192 }
17193 // The error is fatal. Since the silencing might have
17194 // been accidental, we'll surface it anyway.
17195 // However, the browser would have silenced the original error
17196 // so we'll print it first, and then print the stack addendum.
17197 console.error(error);
17198 // For a more detailed description of this block, see:
17199 // https://github.com/facebook/react/pull/13384
17200 }
17201
17202 var componentNameMessage = componentName ? 'The above error occurred in the <' + componentName + '> component:' : 'The above error occurred in one of your React components:';
17203
17204 var errorBoundaryMessage = void 0;
17205 // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
17206 if (errorBoundaryFound && errorBoundaryName) {
17207 if (willRetry) {
17208 errorBoundaryMessage = 'React will try to recreate this component tree from scratch ' + ('using the error boundary you provided, ' + errorBoundaryName + '.');
17209 } else {
17210 errorBoundaryMessage = 'This error was initially handled by the error boundary ' + errorBoundaryName + '.\n' + 'Recreating the tree from scratch failed so React will unmount the tree.';
17211 }
17212 } else {
17213 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.';
17214 }
17215 var combinedMessage = '' + componentNameMessage + componentStack + '\n\n' + ('' + errorBoundaryMessage);
17216
17217 // In development, we provide our own message with just the component stack.
17218 // We don't include the original error message and JS stack because the browser
17219 // has already printed it. Even if the application swallows the error, it is still
17220 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
17221 console.error(combinedMessage);
17222 }
17223}
17224
17225var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
17226{
17227 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
17228}
17229
17230var PossiblyWeakSet$1 = typeof WeakSet === 'function' ? WeakSet : Set;
17231
17232function logError(boundary, errorInfo) {
17233 var source = errorInfo.source;
17234 var stack = errorInfo.stack;
17235 if (stack === null && source !== null) {
17236 stack = getStackByFiberInDevAndProd(source);
17237 }
17238
17239 var capturedError = {
17240 componentName: source !== null ? getComponentName(source.type) : null,
17241 componentStack: stack !== null ? stack : '',
17242 error: errorInfo.value,
17243 errorBoundary: null,
17244 errorBoundaryName: null,
17245 errorBoundaryFound: false,
17246 willRetry: false
17247 };
17248
17249 if (boundary !== null && boundary.tag === ClassComponent) {
17250 capturedError.errorBoundary = boundary.stateNode;
17251 capturedError.errorBoundaryName = getComponentName(boundary.type);
17252 capturedError.errorBoundaryFound = true;
17253 capturedError.willRetry = true;
17254 }
17255
17256 try {
17257 logCapturedError(capturedError);
17258 } catch (e) {
17259 // This method must not throw, or React internal state will get messed up.
17260 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
17261 // we want to report this error outside of the normal stack as a last resort.
17262 // https://github.com/facebook/react/issues/13188
17263 setTimeout(function () {
17264 throw e;
17265 });
17266 }
17267}
17268
17269var callComponentWillUnmountWithTimer = function (current$$1, instance) {
17270 startPhaseTimer(current$$1, 'componentWillUnmount');
17271 instance.props = current$$1.memoizedProps;
17272 instance.state = current$$1.memoizedState;
17273 instance.componentWillUnmount();
17274 stopPhaseTimer();
17275};
17276
17277// Capture errors so they don't interrupt unmounting.
17278function safelyCallComponentWillUnmount(current$$1, instance) {
17279 {
17280 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
17281 if (hasCaughtError()) {
17282 var unmountError = clearCaughtError();
17283 captureCommitPhaseError(current$$1, unmountError);
17284 }
17285 }
17286}
17287
17288function safelyDetachRef(current$$1) {
17289 var ref = current$$1.ref;
17290 if (ref !== null) {
17291 if (typeof ref === 'function') {
17292 {
17293 invokeGuardedCallback(null, ref, null, null);
17294 if (hasCaughtError()) {
17295 var refError = clearCaughtError();
17296 captureCommitPhaseError(current$$1, refError);
17297 }
17298 }
17299 } else {
17300 ref.current = null;
17301 }
17302 }
17303}
17304
17305function safelyCallDestroy(current$$1, destroy) {
17306 {
17307 invokeGuardedCallback(null, destroy, null);
17308 if (hasCaughtError()) {
17309 var error = clearCaughtError();
17310 captureCommitPhaseError(current$$1, error);
17311 }
17312 }
17313}
17314
17315function commitBeforeMutationLifeCycles(current$$1, finishedWork) {
17316 switch (finishedWork.tag) {
17317 case FunctionComponent:
17318 case ForwardRef:
17319 case SimpleMemoComponent:
17320 {
17321 commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
17322 return;
17323 }
17324 case ClassComponent:
17325 {
17326 if (finishedWork.effectTag & Snapshot) {
17327 if (current$$1 !== null) {
17328 var prevProps = current$$1.memoizedProps;
17329 var prevState = current$$1.memoizedState;
17330 startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
17331 var instance = finishedWork.stateNode;
17332 // We could update instance props and state here,
17333 // but instead we rely on them being set during last render.
17334 // TODO: revisit this when we implement resuming.
17335 {
17336 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
17337 !(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;
17338 !(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;
17339 }
17340 }
17341 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
17342 {
17343 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
17344 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
17345 didWarnSet.add(finishedWork.type);
17346 warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
17347 }
17348 }
17349 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
17350 stopPhaseTimer();
17351 }
17352 }
17353 return;
17354 }
17355 case HostRoot:
17356 case HostComponent:
17357 case HostText:
17358 case HostPortal:
17359 case IncompleteClassComponent:
17360 // Nothing to do for these component types
17361 return;
17362 default:
17363 {
17364 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.');
17365 }
17366 }
17367}
17368
17369function commitHookEffectList(unmountTag, mountTag, finishedWork) {
17370 var updateQueue = finishedWork.updateQueue;
17371 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
17372 if (lastEffect !== null) {
17373 var firstEffect = lastEffect.next;
17374 var effect = firstEffect;
17375 do {
17376 if ((effect.tag & unmountTag) !== NoEffect$1) {
17377 // Unmount
17378 var destroy = effect.destroy;
17379 effect.destroy = undefined;
17380 if (destroy !== undefined) {
17381 destroy();
17382 }
17383 }
17384 if ((effect.tag & mountTag) !== NoEffect$1) {
17385 // Mount
17386 var create = effect.create;
17387 effect.destroy = create();
17388
17389 {
17390 var _destroy = effect.destroy;
17391 if (_destroy !== undefined && typeof _destroy !== 'function') {
17392 var addendum = void 0;
17393 if (_destroy === null) {
17394 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
17395 } else if (typeof _destroy.then === 'function') {
17396 addendum = '\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + 'useEffect(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + '}, [someId]); // Or [] if effect doesn\'t need props or state\n\n' + 'Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching';
17397 } else {
17398 addendum = ' You returned: ' + _destroy;
17399 }
17400 warningWithoutStack$1(false, 'An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
17401 }
17402 }
17403 }
17404 effect = effect.next;
17405 } while (effect !== firstEffect);
17406 }
17407}
17408
17409function commitPassiveHookEffects(finishedWork) {
17410 commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
17411 commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
17412}
17413
17414function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) {
17415 switch (finishedWork.tag) {
17416 case FunctionComponent:
17417 case ForwardRef:
17418 case SimpleMemoComponent:
17419 {
17420 commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
17421 break;
17422 }
17423 case ClassComponent:
17424 {
17425 var instance = finishedWork.stateNode;
17426 if (finishedWork.effectTag & Update) {
17427 if (current$$1 === null) {
17428 startPhaseTimer(finishedWork, 'componentDidMount');
17429 // We could update instance props and state here,
17430 // but instead we rely on them being set during last render.
17431 // TODO: revisit this when we implement resuming.
17432 {
17433 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
17434 !(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;
17435 !(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;
17436 }
17437 }
17438 instance.componentDidMount();
17439 stopPhaseTimer();
17440 } else {
17441 var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);
17442 var prevState = current$$1.memoizedState;
17443 startPhaseTimer(finishedWork, 'componentDidUpdate');
17444 // We could update instance props and state here,
17445 // but instead we rely on them being set during last render.
17446 // TODO: revisit this when we implement resuming.
17447 {
17448 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
17449 !(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;
17450 !(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;
17451 }
17452 }
17453 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
17454 stopPhaseTimer();
17455 }
17456 }
17457 var updateQueue = finishedWork.updateQueue;
17458 if (updateQueue !== null) {
17459 {
17460 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
17461 !(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;
17462 !(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;
17463 }
17464 }
17465 // We could update instance props and state here,
17466 // but instead we rely on them being set during last render.
17467 // TODO: revisit this when we implement resuming.
17468 commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
17469 }
17470 return;
17471 }
17472 case HostRoot:
17473 {
17474 var _updateQueue = finishedWork.updateQueue;
17475 if (_updateQueue !== null) {
17476 var _instance = null;
17477 if (finishedWork.child !== null) {
17478 switch (finishedWork.child.tag) {
17479 case HostComponent:
17480 _instance = getPublicInstance(finishedWork.child.stateNode);
17481 break;
17482 case ClassComponent:
17483 _instance = finishedWork.child.stateNode;
17484 break;
17485 }
17486 }
17487 commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
17488 }
17489 return;
17490 }
17491 case HostComponent:
17492 {
17493 var _instance2 = finishedWork.stateNode;
17494
17495 // Renderers may schedule work to be done after host components are mounted
17496 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
17497 // These effects should only be committed when components are first mounted,
17498 // aka when there is no current/alternate.
17499 if (current$$1 === null && finishedWork.effectTag & Update) {
17500 var type = finishedWork.type;
17501 var props = finishedWork.memoizedProps;
17502 commitMount(_instance2, type, props, finishedWork);
17503 }
17504
17505 return;
17506 }
17507 case HostText:
17508 {
17509 // We have no life-cycles associated with text.
17510 return;
17511 }
17512 case HostPortal:
17513 {
17514 // We have no life-cycles associated with portals.
17515 return;
17516 }
17517 case Profiler:
17518 {
17519 if (enableProfilerTimer) {
17520 var onRender = finishedWork.memoizedProps.onRender;
17521
17522 if (enableSchedulerTracing) {
17523 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
17524 } else {
17525 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
17526 }
17527 }
17528 return;
17529 }
17530 case SuspenseComponent:
17531 break;
17532 case IncompleteClassComponent:
17533 break;
17534 default:
17535 {
17536 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.');
17537 }
17538 }
17539}
17540
17541function hideOrUnhideAllChildren(finishedWork, isHidden) {
17542 if (supportsMutation) {
17543 // We only have the top Fiber that was inserted but we need to recurse down its
17544 var node = finishedWork;
17545 while (true) {
17546 if (node.tag === HostComponent) {
17547 var instance = node.stateNode;
17548 if (isHidden) {
17549 hideInstance(instance);
17550 } else {
17551 unhideInstance(node.stateNode, node.memoizedProps);
17552 }
17553 } else if (node.tag === HostText) {
17554 var _instance3 = node.stateNode;
17555 if (isHidden) {
17556 hideTextInstance(_instance3);
17557 } else {
17558 unhideTextInstance(_instance3, node.memoizedProps);
17559 }
17560 } else if (node.tag === SuspenseComponent && node.memoizedState !== null) {
17561 // Found a nested Suspense component that timed out. Skip over the
17562 var fallbackChildFragment = node.child.sibling;
17563 fallbackChildFragment.return = node;
17564 node = fallbackChildFragment;
17565 continue;
17566 } else if (node.child !== null) {
17567 node.child.return = node;
17568 node = node.child;
17569 continue;
17570 }
17571 if (node === finishedWork) {
17572 return;
17573 }
17574 while (node.sibling === null) {
17575 if (node.return === null || node.return === finishedWork) {
17576 return;
17577 }
17578 node = node.return;
17579 }
17580 node.sibling.return = node.return;
17581 node = node.sibling;
17582 }
17583 }
17584}
17585
17586function commitAttachRef(finishedWork) {
17587 var ref = finishedWork.ref;
17588 if (ref !== null) {
17589 var instance = finishedWork.stateNode;
17590 var instanceToUse = void 0;
17591 switch (finishedWork.tag) {
17592 case HostComponent:
17593 instanceToUse = getPublicInstance(instance);
17594 break;
17595 default:
17596 instanceToUse = instance;
17597 }
17598 if (typeof ref === 'function') {
17599 ref(instanceToUse);
17600 } else {
17601 {
17602 if (!ref.hasOwnProperty('current')) {
17603 warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
17604 }
17605 }
17606
17607 ref.current = instanceToUse;
17608 }
17609 }
17610}
17611
17612function commitDetachRef(current$$1) {
17613 var currentRef = current$$1.ref;
17614 if (currentRef !== null) {
17615 if (typeof currentRef === 'function') {
17616 currentRef(null);
17617 } else {
17618 currentRef.current = null;
17619 }
17620 }
17621}
17622
17623// User-originating errors (lifecycles and refs) should not interrupt
17624// deletion, so don't let them throw. Host-originating errors should
17625// interrupt deletion, so it's okay
17626function commitUnmount(current$$1) {
17627 onCommitUnmount(current$$1);
17628
17629 switch (current$$1.tag) {
17630 case FunctionComponent:
17631 case ForwardRef:
17632 case MemoComponent:
17633 case SimpleMemoComponent:
17634 {
17635 var updateQueue = current$$1.updateQueue;
17636 if (updateQueue !== null) {
17637 var lastEffect = updateQueue.lastEffect;
17638 if (lastEffect !== null) {
17639 var firstEffect = lastEffect.next;
17640 var effect = firstEffect;
17641 do {
17642 var destroy = effect.destroy;
17643 if (destroy !== undefined) {
17644 safelyCallDestroy(current$$1, destroy);
17645 }
17646 effect = effect.next;
17647 } while (effect !== firstEffect);
17648 }
17649 }
17650 break;
17651 }
17652 case ClassComponent:
17653 {
17654 safelyDetachRef(current$$1);
17655 var instance = current$$1.stateNode;
17656 if (typeof instance.componentWillUnmount === 'function') {
17657 safelyCallComponentWillUnmount(current$$1, instance);
17658 }
17659 return;
17660 }
17661 case HostComponent:
17662 {
17663 safelyDetachRef(current$$1);
17664 return;
17665 }
17666 case HostPortal:
17667 {
17668 // TODO: this is recursive.
17669 // We are also not using this parent because
17670 // the portal will get pushed immediately.
17671 if (supportsMutation) {
17672 unmountHostComponents(current$$1);
17673 } else if (supportsPersistence) {
17674 emptyPortalContainer(current$$1);
17675 }
17676 return;
17677 }
17678 }
17679}
17680
17681function commitNestedUnmounts(root) {
17682 // While we're inside a removed host node we don't want to call
17683 // removeChild on the inner nodes because they're removed by the top
17684 // call anyway. We also want to call componentWillUnmount on all
17685 // composites before this host node is removed from the tree. Therefore
17686 var node = root;
17687 while (true) {
17688 commitUnmount(node);
17689 // Visit children because they may contain more composite or host nodes.
17690 // Skip portals because commitUnmount() currently visits them recursively.
17691 if (node.child !== null && (
17692 // If we use mutation we drill down into portals using commitUnmount above.
17693 // If we don't use mutation we drill down into portals here instead.
17694 !supportsMutation || node.tag !== HostPortal)) {
17695 node.child.return = node;
17696 node = node.child;
17697 continue;
17698 }
17699 if (node === root) {
17700 return;
17701 }
17702 while (node.sibling === null) {
17703 if (node.return === null || node.return === root) {
17704 return;
17705 }
17706 node = node.return;
17707 }
17708 node.sibling.return = node.return;
17709 node = node.sibling;
17710 }
17711}
17712
17713function detachFiber(current$$1) {
17714 // Cut off the return pointers to disconnect it from the tree. Ideally, we
17715 // should clear the child pointer of the parent alternate to let this
17716 // get GC:ed but we don't know which for sure which parent is the current
17717 // one so we'll settle for GC:ing the subtree of this child. This child
17718 // itself will be GC:ed when the parent updates the next time.
17719 current$$1.return = null;
17720 current$$1.child = null;
17721 current$$1.memoizedState = null;
17722 current$$1.updateQueue = null;
17723 var alternate = current$$1.alternate;
17724 if (alternate !== null) {
17725 alternate.return = null;
17726 alternate.child = null;
17727 alternate.memoizedState = null;
17728 alternate.updateQueue = null;
17729 }
17730}
17731
17732function emptyPortalContainer(current$$1) {
17733 if (!supportsPersistence) {
17734 return;
17735 }
17736
17737 var portal = current$$1.stateNode;
17738 var containerInfo = portal.containerInfo;
17739
17740 var emptyChildSet = createContainerChildSet(containerInfo);
17741 replaceContainerChildren(containerInfo, emptyChildSet);
17742}
17743
17744function commitContainer(finishedWork) {
17745 if (!supportsPersistence) {
17746 return;
17747 }
17748
17749 switch (finishedWork.tag) {
17750 case ClassComponent:
17751 {
17752 return;
17753 }
17754 case HostComponent:
17755 {
17756 return;
17757 }
17758 case HostText:
17759 {
17760 return;
17761 }
17762 case HostRoot:
17763 case HostPortal:
17764 {
17765 var portalOrRoot = finishedWork.stateNode;
17766 var containerInfo = portalOrRoot.containerInfo,
17767 _pendingChildren = portalOrRoot.pendingChildren;
17768
17769 replaceContainerChildren(containerInfo, _pendingChildren);
17770 return;
17771 }
17772 default:
17773 {
17774 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.');
17775 }
17776 }
17777}
17778
17779function getHostParentFiber(fiber) {
17780 var parent = fiber.return;
17781 while (parent !== null) {
17782 if (isHostParent(parent)) {
17783 return parent;
17784 }
17785 parent = parent.return;
17786 }
17787 invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.');
17788}
17789
17790function isHostParent(fiber) {
17791 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
17792}
17793
17794function getHostSibling(fiber) {
17795 // We're going to search forward into the tree until we find a sibling host
17796 // node. Unfortunately, if multiple insertions are done in a row we have to
17797 // search past them. This leads to exponential search for the next sibling.
17798 var node = fiber;
17799 siblings: while (true) {
17800 // If we didn't find anything, let's try the next sibling.
17801 while (node.sibling === null) {
17802 if (node.return === null || isHostParent(node.return)) {
17803 // If we pop out of the root or hit the parent the fiber we are the
17804 // last sibling.
17805 return null;
17806 }
17807 node = node.return;
17808 }
17809 node.sibling.return = node.return;
17810 node = node.sibling;
17811 while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedSuspenseComponent) {
17812 // If it is not host node and, we might have a host node inside it.
17813 // Try to search down until we find one.
17814 if (node.effectTag & Placement) {
17815 // If we don't have a child, try the siblings instead.
17816 continue siblings;
17817 }
17818 // If we don't have a child, try the siblings instead.
17819 // We also skip portals because they are not part of this host tree.
17820 if (node.child === null || node.tag === HostPortal) {
17821 continue siblings;
17822 } else {
17823 node.child.return = node;
17824 node = node.child;
17825 }
17826 }
17827 // Check if this host node is stable or about to be placed.
17828 if (!(node.effectTag & Placement)) {
17829 // Found it!
17830 return node.stateNode;
17831 }
17832 }
17833}
17834
17835function commitPlacement(finishedWork) {
17836 if (!supportsMutation) {
17837 return;
17838 }
17839
17840 // Recursively insert all host nodes into the parent.
17841 var parentFiber = getHostParentFiber(finishedWork);
17842
17843 // Note: these two variables *must* always be updated together.
17844 var parent = void 0;
17845 var isContainer = void 0;
17846
17847 switch (parentFiber.tag) {
17848 case HostComponent:
17849 parent = parentFiber.stateNode;
17850 isContainer = false;
17851 break;
17852 case HostRoot:
17853 parent = parentFiber.stateNode.containerInfo;
17854 isContainer = true;
17855 break;
17856 case HostPortal:
17857 parent = parentFiber.stateNode.containerInfo;
17858 isContainer = true;
17859 break;
17860 default:
17861 invariant(false, 'Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.');
17862 }
17863 if (parentFiber.effectTag & ContentReset) {
17864 // Reset the text content of the parent before doing any insertions
17865 resetTextContent(parent);
17866 // Clear ContentReset from the effect tag
17867 parentFiber.effectTag &= ~ContentReset;
17868 }
17869
17870 var before = getHostSibling(finishedWork);
17871 // We only have the top Fiber that was inserted but we need to recurse down its
17872 // children to find all the terminal nodes.
17873 var node = finishedWork;
17874 while (true) {
17875 if (node.tag === HostComponent || node.tag === HostText) {
17876 if (before) {
17877 if (isContainer) {
17878 insertInContainerBefore(parent, node.stateNode, before);
17879 } else {
17880 insertBefore(parent, node.stateNode, before);
17881 }
17882 } else {
17883 if (isContainer) {
17884 appendChildToContainer(parent, node.stateNode);
17885 } else {
17886 appendChild(parent, node.stateNode);
17887 }
17888 }
17889 } else if (node.tag === HostPortal) {
17890 // If the insertion itself is a portal, then we don't want to traverse
17891 // down its children. Instead, we'll get insertions from each child in
17892 // the portal directly.
17893 } else if (node.child !== null) {
17894 node.child.return = node;
17895 node = node.child;
17896 continue;
17897 }
17898 if (node === finishedWork) {
17899 return;
17900 }
17901 while (node.sibling === null) {
17902 if (node.return === null || node.return === finishedWork) {
17903 return;
17904 }
17905 node = node.return;
17906 }
17907 node.sibling.return = node.return;
17908 node = node.sibling;
17909 }
17910}
17911
17912function unmountHostComponents(current$$1) {
17913 // We only have the top Fiber that was deleted but we need to recurse down its
17914 var node = current$$1;
17915
17916 // Each iteration, currentParent is populated with node's host parent if not
17917 // currentParentIsValid.
17918 var currentParentIsValid = false;
17919
17920 // Note: these two variables *must* always be updated together.
17921 var currentParent = void 0;
17922 var currentParentIsContainer = void 0;
17923
17924 while (true) {
17925 if (!currentParentIsValid) {
17926 var parent = node.return;
17927 findParent: while (true) {
17928 !(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;
17929 switch (parent.tag) {
17930 case HostComponent:
17931 currentParent = parent.stateNode;
17932 currentParentIsContainer = false;
17933 break findParent;
17934 case HostRoot:
17935 currentParent = parent.stateNode.containerInfo;
17936 currentParentIsContainer = true;
17937 break findParent;
17938 case HostPortal:
17939 currentParent = parent.stateNode.containerInfo;
17940 currentParentIsContainer = true;
17941 break findParent;
17942 }
17943 parent = parent.return;
17944 }
17945 currentParentIsValid = true;
17946 }
17947
17948 if (node.tag === HostComponent || node.tag === HostText) {
17949 commitNestedUnmounts(node);
17950 // After all the children have unmounted, it is now safe to remove the
17951 // node from the tree.
17952 if (currentParentIsContainer) {
17953 removeChildFromContainer(currentParent, node.stateNode);
17954 } else {
17955 removeChild(currentParent, node.stateNode);
17956 }
17957 // Don't visit children because we already visited them.
17958 } else if (enableSuspenseServerRenderer && node.tag === DehydratedSuspenseComponent) {
17959 // Delete the dehydrated suspense boundary and all of its content.
17960 if (currentParentIsContainer) {
17961 clearSuspenseBoundaryFromContainer(currentParent, node.stateNode);
17962 } else {
17963 clearSuspenseBoundary(currentParent, node.stateNode);
17964 }
17965 } else if (node.tag === HostPortal) {
17966 if (node.child !== null) {
17967 // When we go into a portal, it becomes the parent to remove from.
17968 // We will reassign it back when we pop the portal on the way up.
17969 currentParent = node.stateNode.containerInfo;
17970 currentParentIsContainer = true;
17971 // Visit children because portals might contain host components.
17972 node.child.return = node;
17973 node = node.child;
17974 continue;
17975 }
17976 } else {
17977 commitUnmount(node);
17978 // Visit children because we may find more host components below.
17979 if (node.child !== null) {
17980 node.child.return = node;
17981 node = node.child;
17982 continue;
17983 }
17984 }
17985 if (node === current$$1) {
17986 return;
17987 }
17988 while (node.sibling === null) {
17989 if (node.return === null || node.return === current$$1) {
17990 return;
17991 }
17992 node = node.return;
17993 if (node.tag === HostPortal) {
17994 // When we go out of the portal, we need to restore the parent.
17995 // Since we don't keep a stack of them, we will search for it.
17996 currentParentIsValid = false;
17997 }
17998 }
17999 node.sibling.return = node.return;
18000 node = node.sibling;
18001 }
18002}
18003
18004function commitDeletion(current$$1) {
18005 if (supportsMutation) {
18006 // Recursively delete all host nodes from the parent.
18007 // Detach refs and call componentWillUnmount() on the whole subtree.
18008 unmountHostComponents(current$$1);
18009 } else {
18010 // Detach refs and call componentWillUnmount() on the whole subtree.
18011 commitNestedUnmounts(current$$1);
18012 }
18013 detachFiber(current$$1);
18014}
18015
18016function commitWork(current$$1, finishedWork) {
18017 if (!supportsMutation) {
18018 switch (finishedWork.tag) {
18019 case FunctionComponent:
18020 case ForwardRef:
18021 case MemoComponent:
18022 case SimpleMemoComponent:
18023 {
18024 // Note: We currently never use MountMutation, but useLayout uses
18025 // UnmountMutation.
18026 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
18027 return;
18028 }
18029 }
18030
18031 commitContainer(finishedWork);
18032 return;
18033 }
18034
18035 switch (finishedWork.tag) {
18036 case FunctionComponent:
18037 case ForwardRef:
18038 case MemoComponent:
18039 case SimpleMemoComponent:
18040 {
18041 // Note: We currently never use MountMutation, but useLayout uses
18042 // UnmountMutation.
18043 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
18044 return;
18045 }
18046 case ClassComponent:
18047 {
18048 return;
18049 }
18050 case HostComponent:
18051 {
18052 var instance = finishedWork.stateNode;
18053 if (instance != null) {
18054 // Commit the work prepared earlier.
18055 var newProps = finishedWork.memoizedProps;
18056 // For hydration we reuse the update path but we treat the oldProps
18057 // as the newProps. The updatePayload will contain the real change in
18058 // this case.
18059 var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps;
18060 var type = finishedWork.type;
18061 // TODO: Type the updateQueue to be specific to host components.
18062 var updatePayload = finishedWork.updateQueue;
18063 finishedWork.updateQueue = null;
18064 if (updatePayload !== null) {
18065 commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
18066 }
18067 }
18068 return;
18069 }
18070 case HostText:
18071 {
18072 !(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;
18073 var textInstance = finishedWork.stateNode;
18074 var newText = finishedWork.memoizedProps;
18075 // For hydration we reuse the update path but we treat the oldProps
18076 // as the newProps. The updatePayload will contain the real change in
18077 // this case.
18078 var oldText = current$$1 !== null ? current$$1.memoizedProps : newText;
18079 commitTextUpdate(textInstance, oldText, newText);
18080 return;
18081 }
18082 case HostRoot:
18083 {
18084 return;
18085 }
18086 case Profiler:
18087 {
18088 return;
18089 }
18090 case SuspenseComponent:
18091 {
18092 var newState = finishedWork.memoizedState;
18093
18094 var newDidTimeout = void 0;
18095 var primaryChildParent = finishedWork;
18096 if (newState === null) {
18097 newDidTimeout = false;
18098 } else {
18099 newDidTimeout = true;
18100 primaryChildParent = finishedWork.child;
18101 if (newState.timedOutAt === NoWork) {
18102 // If the children had not already timed out, record the time.
18103 // This is used to compute the elapsed time during subsequent
18104 // attempts to render the children.
18105 newState.timedOutAt = requestCurrentTime();
18106 }
18107 }
18108
18109 if (primaryChildParent !== null) {
18110 hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
18111 }
18112
18113 // If this boundary just timed out, then it will have a set of thenables.
18114 // For each thenable, attach a listener so that when it resolves, React
18115 // attempts to re-render the boundary in the primary (pre-timeout) state.
18116 var thenables = finishedWork.updateQueue;
18117 if (thenables !== null) {
18118 finishedWork.updateQueue = null;
18119 var retryCache = finishedWork.stateNode;
18120 if (retryCache === null) {
18121 retryCache = finishedWork.stateNode = new PossiblyWeakSet$1();
18122 }
18123 thenables.forEach(function (thenable) {
18124 // Memoize using the boundary fiber to prevent redundant listeners.
18125 var retry = retryTimedOutBoundary.bind(null, finishedWork, thenable);
18126 if (enableSchedulerTracing) {
18127 retry = unstable_wrap(retry);
18128 }
18129 if (!retryCache.has(thenable)) {
18130 retryCache.add(thenable);
18131 thenable.then(retry, retry);
18132 }
18133 });
18134 }
18135
18136 return;
18137 }
18138 case IncompleteClassComponent:
18139 {
18140 return;
18141 }
18142 default:
18143 {
18144 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.');
18145 }
18146 }
18147}
18148
18149function commitResetTextContent(current$$1) {
18150 if (!supportsMutation) {
18151 return;
18152 }
18153 resetTextContent(current$$1.stateNode);
18154}
18155
18156var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
18157var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
18158
18159function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
18160 var update = createUpdate(expirationTime);
18161 // Unmount the root by rendering null.
18162 update.tag = CaptureUpdate;
18163 // Caution: React DevTools currently depends on this property
18164 // being called "element".
18165 update.payload = { element: null };
18166 var error = errorInfo.value;
18167 update.callback = function () {
18168 onUncaughtError(error);
18169 logError(fiber, errorInfo);
18170 };
18171 return update;
18172}
18173
18174function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
18175 var update = createUpdate(expirationTime);
18176 update.tag = CaptureUpdate;
18177 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
18178 if (typeof getDerivedStateFromError === 'function') {
18179 var error = errorInfo.value;
18180 update.payload = function () {
18181 return getDerivedStateFromError(error);
18182 };
18183 }
18184
18185 var inst = fiber.stateNode;
18186 if (inst !== null && typeof inst.componentDidCatch === 'function') {
18187 update.callback = function callback() {
18188 if (typeof getDerivedStateFromError !== 'function') {
18189 // To preserve the preexisting retry behavior of error boundaries,
18190 // we keep track of which ones already failed during this batch.
18191 // This gets reset before we yield back to the browser.
18192 // TODO: Warn in strict mode if getDerivedStateFromError is
18193 // not defined.
18194 markLegacyErrorBoundaryAsFailed(this);
18195 }
18196 var error = errorInfo.value;
18197 var stack = errorInfo.stack;
18198 logError(fiber, errorInfo);
18199 this.componentDidCatch(error, {
18200 componentStack: stack !== null ? stack : ''
18201 });
18202 {
18203 if (typeof getDerivedStateFromError !== 'function') {
18204 // If componentDidCatch is the only error boundary method defined,
18205 // then it needs to call setState to recover from errors.
18206 // If no state update is scheduled then the boundary will swallow the error.
18207 !(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;
18208 }
18209 }
18210 };
18211 }
18212 return update;
18213}
18214
18215function attachPingListener(root, renderExpirationTime, thenable) {
18216 // Attach a listener to the promise to "ping" the root and retry. But
18217 // only if one does not already exist for the current render expiration
18218 // time (which acts like a "thread ID" here).
18219 var pingCache = root.pingCache;
18220 var threadIDs = void 0;
18221 if (pingCache === null) {
18222 pingCache = root.pingCache = new PossiblyWeakMap();
18223 threadIDs = new Set();
18224 pingCache.set(thenable, threadIDs);
18225 } else {
18226 threadIDs = pingCache.get(thenable);
18227 if (threadIDs === undefined) {
18228 threadIDs = new Set();
18229 pingCache.set(thenable, threadIDs);
18230 }
18231 }
18232 if (!threadIDs.has(renderExpirationTime)) {
18233 // Memoize using the thread ID to prevent redundant listeners.
18234 threadIDs.add(renderExpirationTime);
18235 var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);
18236 if (enableSchedulerTracing) {
18237 ping = unstable_wrap(ping);
18238 }
18239 thenable.then(ping, ping);
18240 }
18241}
18242
18243function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
18244 // The source fiber did not complete.
18245 sourceFiber.effectTag |= Incomplete;
18246 // Its effect list is no longer valid.
18247 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
18248
18249 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
18250 // This is a thenable.
18251 var thenable = value;
18252
18253 // Find the earliest timeout threshold of all the placeholders in the
18254 // ancestor path. We could avoid this traversal by storing the thresholds on
18255 // the stack, but we choose not to because we only hit this path if we're
18256 // IO-bound (i.e. if something suspends). Whereas the stack is used even in
18257 // the non-IO- bound case.
18258 var _workInProgress = returnFiber;
18259 var earliestTimeoutMs = -1;
18260 var startTimeMs = -1;
18261 do {
18262 if (_workInProgress.tag === SuspenseComponent) {
18263 var current$$1 = _workInProgress.alternate;
18264 if (current$$1 !== null) {
18265 var currentState = current$$1.memoizedState;
18266 if (currentState !== null) {
18267 // Reached a boundary that already timed out. Do not search
18268 // any further.
18269 var timedOutAt = currentState.timedOutAt;
18270 startTimeMs = expirationTimeToMs(timedOutAt);
18271 // Do not search any further.
18272 break;
18273 }
18274 }
18275 var timeoutPropMs = _workInProgress.pendingProps.maxDuration;
18276 if (typeof timeoutPropMs === 'number') {
18277 if (timeoutPropMs <= 0) {
18278 earliestTimeoutMs = 0;
18279 } else if (earliestTimeoutMs === -1 || timeoutPropMs < earliestTimeoutMs) {
18280 earliestTimeoutMs = timeoutPropMs;
18281 }
18282 }
18283 }
18284 // If there is a DehydratedSuspenseComponent we don't have to do anything because
18285 // if something suspends inside it, we will simply leave that as dehydrated. It
18286 // will never timeout.
18287 _workInProgress = _workInProgress.return;
18288 } while (_workInProgress !== null);
18289
18290 // Schedule the nearest Suspense to re-render the timed out view.
18291 _workInProgress = returnFiber;
18292 do {
18293 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress)) {
18294 // Found the nearest boundary.
18295
18296 // Stash the promise on the boundary fiber. If the boundary times out, we'll
18297 var thenables = _workInProgress.updateQueue;
18298 if (thenables === null) {
18299 var updateQueue = new Set();
18300 updateQueue.add(thenable);
18301 _workInProgress.updateQueue = updateQueue;
18302 } else {
18303 thenables.add(thenable);
18304 }
18305
18306 // If the boundary is outside of concurrent mode, we should *not*
18307 // suspend the commit. Pretend as if the suspended component rendered
18308 // null and keep rendering. In the commit phase, we'll schedule a
18309 // subsequent synchronous update to re-render the Suspense.
18310 //
18311 // Note: It doesn't matter whether the component that suspended was
18312 // inside a concurrent mode tree. If the Suspense is outside of it, we
18313 // should *not* suspend the commit.
18314 if ((_workInProgress.mode & ConcurrentMode) === NoEffect) {
18315 _workInProgress.effectTag |= DidCapture;
18316
18317 // We're going to commit this fiber even though it didn't complete.
18318 // But we shouldn't call any lifecycle methods or callbacks. Remove
18319 // all lifecycle effect tags.
18320 sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
18321
18322 if (sourceFiber.tag === ClassComponent) {
18323 var currentSourceFiber = sourceFiber.alternate;
18324 if (currentSourceFiber === null) {
18325 // This is a new mount. Change the tag so it's not mistaken for a
18326 // completed class component. For example, we should not call
18327 // componentWillUnmount if it is deleted.
18328 sourceFiber.tag = IncompleteClassComponent;
18329 } else {
18330 // When we try rendering again, we should not reuse the current fiber,
18331 // since it's known to be in an inconsistent state. Use a force updte to
18332 // prevent a bail out.
18333 var update = createUpdate(Sync);
18334 update.tag = ForceUpdate;
18335 enqueueUpdate(sourceFiber, update);
18336 }
18337 }
18338
18339 // The source fiber did not complete. Mark it with Sync priority to
18340 // indicate that it still has pending work.
18341 sourceFiber.expirationTime = Sync;
18342
18343 // Exit without suspending.
18344 return;
18345 }
18346
18347 // Confirmed that the boundary is in a concurrent mode tree. Continue
18348 // with the normal suspend path.
18349
18350 attachPingListener(root, renderExpirationTime, thenable);
18351
18352 var absoluteTimeoutMs = void 0;
18353 if (earliestTimeoutMs === -1) {
18354 // If no explicit threshold is given, default to an arbitrarily large
18355 // value. The actual size doesn't matter because the threshold for the
18356 // whole tree will be clamped to the expiration time.
18357 absoluteTimeoutMs = maxSigned31BitInt;
18358 } else {
18359 if (startTimeMs === -1) {
18360 // This suspend happened outside of any already timed-out
18361 // placeholders. We don't know exactly when the update was
18362 // scheduled, but we can infer an approximate start time from the
18363 // expiration time. First, find the earliest uncommitted expiration
18364 // time in the tree, including work that is suspended. Then subtract
18365 // the offset used to compute an async update's expiration time.
18366 // This will cause high priority (interactive) work to expire
18367 // earlier than necessary, but we can account for this by adjusting
18368 // for the Just Noticeable Difference.
18369 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, renderExpirationTime);
18370 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
18371 startTimeMs = earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
18372 }
18373 absoluteTimeoutMs = startTimeMs + earliestTimeoutMs;
18374 }
18375
18376 // Mark the earliest timeout in the suspended fiber's ancestor path.
18377 // After completing the root, we'll take the largest of all the
18378 // suspended fiber's timeouts and use it to compute a timeout for the
18379 // whole tree.
18380 renderDidSuspend(root, absoluteTimeoutMs, renderExpirationTime);
18381
18382 _workInProgress.effectTag |= ShouldCapture;
18383 _workInProgress.expirationTime = renderExpirationTime;
18384 return;
18385 } else if (enableSuspenseServerRenderer && _workInProgress.tag === DehydratedSuspenseComponent) {
18386 attachPingListener(root, renderExpirationTime, thenable);
18387
18388 // Since we already have a current fiber, we can eagerly add a retry listener.
18389 var retryCache = _workInProgress.memoizedState;
18390 if (retryCache === null) {
18391 retryCache = _workInProgress.memoizedState = new PossiblyWeakSet();
18392 var _current = _workInProgress.alternate;
18393 !_current ? invariant(false, 'A dehydrated suspense boundary must commit before trying to render. This is probably a bug in React.') : void 0;
18394 _current.memoizedState = retryCache;
18395 }
18396 // Memoize using the boundary fiber to prevent redundant listeners.
18397 if (!retryCache.has(thenable)) {
18398 retryCache.add(thenable);
18399 var retry = retryTimedOutBoundary.bind(null, _workInProgress, thenable);
18400 if (enableSchedulerTracing) {
18401 retry = unstable_wrap(retry);
18402 }
18403 thenable.then(retry, retry);
18404 }
18405 _workInProgress.effectTag |= ShouldCapture;
18406 _workInProgress.expirationTime = renderExpirationTime;
18407 return;
18408 }
18409 // This boundary already captured during this render. Continue to the next
18410 // boundary.
18411 _workInProgress = _workInProgress.return;
18412 } while (_workInProgress !== null);
18413 // No boundary was found. Fallthrough to error mode.
18414 // TODO: Use invariant so the message is stripped in prod?
18415 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));
18416 }
18417
18418 // We didn't find a boundary that could handle this type of exception. Start
18419 // over and traverse parent path again, this time treating the exception
18420 // as an error.
18421 renderDidError();
18422 value = createCapturedValue(value, sourceFiber);
18423 var workInProgress = returnFiber;
18424 do {
18425 switch (workInProgress.tag) {
18426 case HostRoot:
18427 {
18428 var _errorInfo = value;
18429 workInProgress.effectTag |= ShouldCapture;
18430 workInProgress.expirationTime = renderExpirationTime;
18431 var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
18432 enqueueCapturedUpdate(workInProgress, _update);
18433 return;
18434 }
18435 case ClassComponent:
18436 // Capture and retry
18437 var errorInfo = value;
18438 var ctor = workInProgress.type;
18439 var instance = workInProgress.stateNode;
18440 if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
18441 workInProgress.effectTag |= ShouldCapture;
18442 workInProgress.expirationTime = renderExpirationTime;
18443 // Schedule the error boundary to re-render using updated state
18444 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
18445 enqueueCapturedUpdate(workInProgress, _update2);
18446 return;
18447 }
18448 break;
18449 default:
18450 break;
18451 }
18452 workInProgress = workInProgress.return;
18453 } while (workInProgress !== null);
18454}
18455
18456function unwindWork(workInProgress, renderExpirationTime) {
18457 switch (workInProgress.tag) {
18458 case ClassComponent:
18459 {
18460 var Component = workInProgress.type;
18461 if (isContextProvider(Component)) {
18462 popContext(workInProgress);
18463 }
18464 var effectTag = workInProgress.effectTag;
18465 if (effectTag & ShouldCapture) {
18466 workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
18467 return workInProgress;
18468 }
18469 return null;
18470 }
18471 case HostRoot:
18472 {
18473 popHostContainer(workInProgress);
18474 popTopLevelContextObject(workInProgress);
18475 var _effectTag = workInProgress.effectTag;
18476 !((_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;
18477 workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
18478 return workInProgress;
18479 }
18480 case HostComponent:
18481 {
18482 // TODO: popHydrationState
18483 popHostContext(workInProgress);
18484 return null;
18485 }
18486 case SuspenseComponent:
18487 {
18488 var _effectTag2 = workInProgress.effectTag;
18489 if (_effectTag2 & ShouldCapture) {
18490 workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture;
18491 // Captured a suspense effect. Re-render the boundary.
18492 return workInProgress;
18493 }
18494 return null;
18495 }
18496 case DehydratedSuspenseComponent:
18497 {
18498 if (enableSuspenseServerRenderer) {
18499 // TODO: popHydrationState
18500 var _effectTag3 = workInProgress.effectTag;
18501 if (_effectTag3 & ShouldCapture) {
18502 workInProgress.effectTag = _effectTag3 & ~ShouldCapture | DidCapture;
18503 // Captured a suspense effect. Re-render the boundary.
18504 return workInProgress;
18505 }
18506 }
18507 return null;
18508 }
18509 case HostPortal:
18510 popHostContainer(workInProgress);
18511 return null;
18512 case ContextProvider:
18513 popProvider(workInProgress);
18514 return null;
18515 default:
18516 return null;
18517 }
18518}
18519
18520function unwindInterruptedWork(interruptedWork) {
18521 switch (interruptedWork.tag) {
18522 case ClassComponent:
18523 {
18524 var childContextTypes = interruptedWork.type.childContextTypes;
18525 if (childContextTypes !== null && childContextTypes !== undefined) {
18526 popContext(interruptedWork);
18527 }
18528 break;
18529 }
18530 case HostRoot:
18531 {
18532 popHostContainer(interruptedWork);
18533 popTopLevelContextObject(interruptedWork);
18534 break;
18535 }
18536 case HostComponent:
18537 {
18538 popHostContext(interruptedWork);
18539 break;
18540 }
18541 case HostPortal:
18542 popHostContainer(interruptedWork);
18543 break;
18544 case ContextProvider:
18545 popProvider(interruptedWork);
18546 break;
18547 default:
18548 break;
18549 }
18550}
18551
18552var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
18553var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
18554
18555
18556var didWarnAboutStateTransition = void 0;
18557var didWarnSetStateChildContext = void 0;
18558var warnAboutUpdateOnUnmounted = void 0;
18559var warnAboutInvalidUpdates = void 0;
18560
18561if (enableSchedulerTracing) {
18562 // Provide explicit error message when production+profiling bundle of e.g. react-dom
18563 // is used with production (non-profiling) bundle of scheduler/tracing
18564 !(__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;
18565}
18566
18567{
18568 didWarnAboutStateTransition = false;
18569 didWarnSetStateChildContext = false;
18570 var didWarnStateUpdateForUnmountedComponent = {};
18571
18572 warnAboutUpdateOnUnmounted = function (fiber, isClass) {
18573 // We show the whole stack but dedupe on the top component's name because
18574 // the problematic code almost always lies inside that component.
18575 var componentName = getComponentName(fiber.type) || 'ReactComponent';
18576 if (didWarnStateUpdateForUnmountedComponent[componentName]) {
18577 return;
18578 }
18579 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));
18580 didWarnStateUpdateForUnmountedComponent[componentName] = true;
18581 };
18582
18583 warnAboutInvalidUpdates = function (instance) {
18584 switch (phase) {
18585 case 'getChildContext':
18586 if (didWarnSetStateChildContext) {
18587 return;
18588 }
18589 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
18590 didWarnSetStateChildContext = true;
18591 break;
18592 case 'render':
18593 if (didWarnAboutStateTransition) {
18594 return;
18595 }
18596 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.');
18597 didWarnAboutStateTransition = true;
18598 break;
18599 }
18600 };
18601}
18602
18603// Used to ensure computeUniqueAsyncExpiration is monotonically decreasing.
18604var lastUniqueAsyncExpiration = Sync - 1;
18605
18606var isWorking = false;
18607
18608// The next work in progress fiber that we're currently working on.
18609var nextUnitOfWork = null;
18610var nextRoot = null;
18611// The time at which we're currently rendering work.
18612var nextRenderExpirationTime = NoWork;
18613var nextLatestAbsoluteTimeoutMs = -1;
18614var nextRenderDidError = false;
18615
18616// The next fiber with an effect that we're currently committing.
18617var nextEffect = null;
18618
18619var isCommitting$1 = false;
18620var rootWithPendingPassiveEffects = null;
18621var passiveEffectCallbackHandle = null;
18622var passiveEffectCallback = null;
18623
18624var legacyErrorBoundariesThatAlreadyFailed = null;
18625
18626// Used for performance tracking.
18627var interruptedBy = null;
18628
18629var stashedWorkInProgressProperties = void 0;
18630var replayUnitOfWork = void 0;
18631var mayReplayFailedUnitOfWork = void 0;
18632var isReplayingFailedUnitOfWork = void 0;
18633var originalReplayError = void 0;
18634var rethrowOriginalError = void 0;
18635if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
18636 stashedWorkInProgressProperties = null;
18637 mayReplayFailedUnitOfWork = true;
18638 isReplayingFailedUnitOfWork = false;
18639 originalReplayError = null;
18640 replayUnitOfWork = function (failedUnitOfWork, thrownValue, isYieldy) {
18641 if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
18642 // Don't replay promises. Treat everything else like an error.
18643 // TODO: Need to figure out a different strategy if/when we add
18644 // support for catching other types.
18645 return;
18646 }
18647
18648 // Restore the original state of the work-in-progress
18649 if (stashedWorkInProgressProperties === null) {
18650 // This should never happen. Don't throw because this code is DEV-only.
18651 warningWithoutStack$1(false, 'Could not replay rendering after an error. This is likely a bug in React. ' + 'Please file an issue.');
18652 return;
18653 }
18654 assignFiberPropertiesInDEV(failedUnitOfWork, stashedWorkInProgressProperties);
18655
18656 switch (failedUnitOfWork.tag) {
18657 case HostRoot:
18658 popHostContainer(failedUnitOfWork);
18659 popTopLevelContextObject(failedUnitOfWork);
18660 break;
18661 case HostComponent:
18662 popHostContext(failedUnitOfWork);
18663 break;
18664 case ClassComponent:
18665 {
18666 var Component = failedUnitOfWork.type;
18667 if (isContextProvider(Component)) {
18668 popContext(failedUnitOfWork);
18669 }
18670 break;
18671 }
18672 case HostPortal:
18673 popHostContainer(failedUnitOfWork);
18674 break;
18675 case ContextProvider:
18676 popProvider(failedUnitOfWork);
18677 break;
18678 }
18679 // Replay the begin phase.
18680 isReplayingFailedUnitOfWork = true;
18681 originalReplayError = thrownValue;
18682 invokeGuardedCallback(null, workLoop, null, isYieldy);
18683 isReplayingFailedUnitOfWork = false;
18684 originalReplayError = null;
18685 if (hasCaughtError()) {
18686 var replayError = clearCaughtError();
18687 if (replayError != null && thrownValue != null) {
18688 try {
18689 // Reading the expando property is intentionally
18690 // inside `try` because it might be a getter or Proxy.
18691 if (replayError._suppressLogging) {
18692 // Also suppress logging for the original error.
18693 thrownValue._suppressLogging = true;
18694 }
18695 } catch (inner) {
18696 // Ignore.
18697 }
18698 }
18699 } else {
18700 // If the begin phase did not fail the second time, set this pointer
18701 // back to the original value.
18702 nextUnitOfWork = failedUnitOfWork;
18703 }
18704 };
18705 rethrowOriginalError = function () {
18706 throw originalReplayError;
18707 };
18708}
18709
18710function resetStack() {
18711 if (nextUnitOfWork !== null) {
18712 var interruptedWork = nextUnitOfWork.return;
18713 while (interruptedWork !== null) {
18714 unwindInterruptedWork(interruptedWork);
18715 interruptedWork = interruptedWork.return;
18716 }
18717 }
18718
18719 {
18720 ReactStrictModeWarnings.discardPendingWarnings();
18721 checkThatStackIsEmpty();
18722 }
18723
18724 nextRoot = null;
18725 nextRenderExpirationTime = NoWork;
18726 nextLatestAbsoluteTimeoutMs = -1;
18727 nextRenderDidError = false;
18728 nextUnitOfWork = null;
18729}
18730
18731function commitAllHostEffects() {
18732 while (nextEffect !== null) {
18733 {
18734 setCurrentFiber(nextEffect);
18735 }
18736 recordEffect();
18737
18738 var effectTag = nextEffect.effectTag;
18739
18740 if (effectTag & ContentReset) {
18741 commitResetTextContent(nextEffect);
18742 }
18743
18744 if (effectTag & Ref) {
18745 var current$$1 = nextEffect.alternate;
18746 if (current$$1 !== null) {
18747 commitDetachRef(current$$1);
18748 }
18749 }
18750
18751 // The following switch statement is only concerned about placement,
18752 // updates, and deletions. To avoid needing to add a case for every
18753 // possible bitmap value, we remove the secondary effects from the
18754 // effect tag and switch on that value.
18755 var primaryEffectTag = effectTag & (Placement | Update | Deletion);
18756 switch (primaryEffectTag) {
18757 case Placement:
18758 {
18759 commitPlacement(nextEffect);
18760 // Clear the "placement" from effect tag so that we know that this is inserted, before
18761 // any life-cycles like componentDidMount gets called.
18762 // TODO: findDOMNode doesn't rely on this any more but isMounted
18763 // does and isMounted is deprecated anyway so we should be able
18764 // to kill this.
18765 nextEffect.effectTag &= ~Placement;
18766 break;
18767 }
18768 case PlacementAndUpdate:
18769 {
18770 // Placement
18771 commitPlacement(nextEffect);
18772 // Clear the "placement" from effect tag so that we know that this is inserted, before
18773 // any life-cycles like componentDidMount gets called.
18774 nextEffect.effectTag &= ~Placement;
18775
18776 // Update
18777 var _current = nextEffect.alternate;
18778 commitWork(_current, nextEffect);
18779 break;
18780 }
18781 case Update:
18782 {
18783 var _current2 = nextEffect.alternate;
18784 commitWork(_current2, nextEffect);
18785 break;
18786 }
18787 case Deletion:
18788 {
18789 commitDeletion(nextEffect);
18790 break;
18791 }
18792 }
18793 nextEffect = nextEffect.nextEffect;
18794 }
18795
18796 {
18797 resetCurrentFiber();
18798 }
18799}
18800
18801function commitBeforeMutationLifecycles() {
18802 while (nextEffect !== null) {
18803 {
18804 setCurrentFiber(nextEffect);
18805 }
18806
18807 var effectTag = nextEffect.effectTag;
18808 if (effectTag & Snapshot) {
18809 recordEffect();
18810 var current$$1 = nextEffect.alternate;
18811 commitBeforeMutationLifeCycles(current$$1, nextEffect);
18812 }
18813
18814 nextEffect = nextEffect.nextEffect;
18815 }
18816
18817 {
18818 resetCurrentFiber();
18819 }
18820}
18821
18822function commitAllLifeCycles(finishedRoot, committedExpirationTime) {
18823 {
18824 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
18825 ReactStrictModeWarnings.flushLegacyContextWarning();
18826
18827 if (warnAboutDeprecatedLifecycles) {
18828 ReactStrictModeWarnings.flushPendingDeprecationWarnings();
18829 }
18830 }
18831 while (nextEffect !== null) {
18832 {
18833 setCurrentFiber(nextEffect);
18834 }
18835 var effectTag = nextEffect.effectTag;
18836
18837 if (effectTag & (Update | Callback)) {
18838 recordEffect();
18839 var current$$1 = nextEffect.alternate;
18840 commitLifeCycles(finishedRoot, current$$1, nextEffect, committedExpirationTime);
18841 }
18842
18843 if (effectTag & Ref) {
18844 recordEffect();
18845 commitAttachRef(nextEffect);
18846 }
18847
18848 if (effectTag & Passive) {
18849 rootWithPendingPassiveEffects = finishedRoot;
18850 }
18851
18852 nextEffect = nextEffect.nextEffect;
18853 }
18854 {
18855 resetCurrentFiber();
18856 }
18857}
18858
18859function commitPassiveEffects(root, firstEffect) {
18860 rootWithPendingPassiveEffects = null;
18861 passiveEffectCallbackHandle = null;
18862 passiveEffectCallback = null;
18863
18864 // Set this to true to prevent re-entrancy
18865 var previousIsRendering = isRendering;
18866 isRendering = true;
18867
18868 var effect = firstEffect;
18869 do {
18870 {
18871 setCurrentFiber(effect);
18872 }
18873
18874 if (effect.effectTag & Passive) {
18875 var didError = false;
18876 var error = void 0;
18877 {
18878 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
18879 if (hasCaughtError()) {
18880 didError = true;
18881 error = clearCaughtError();
18882 }
18883 }
18884 if (didError) {
18885 captureCommitPhaseError(effect, error);
18886 }
18887 }
18888 effect = effect.nextEffect;
18889 } while (effect !== null);
18890 {
18891 resetCurrentFiber();
18892 }
18893
18894 isRendering = previousIsRendering;
18895
18896 // Check if work was scheduled by one of the effects
18897 var rootExpirationTime = root.expirationTime;
18898 if (rootExpirationTime !== NoWork) {
18899 requestWork(root, rootExpirationTime);
18900 }
18901 // Flush any sync work that was scheduled by effects
18902 if (!isBatchingUpdates && !isRendering) {
18903 performSyncWork();
18904 }
18905}
18906
18907function isAlreadyFailedLegacyErrorBoundary(instance) {
18908 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
18909}
18910
18911function markLegacyErrorBoundaryAsFailed(instance) {
18912 if (legacyErrorBoundariesThatAlreadyFailed === null) {
18913 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
18914 } else {
18915 legacyErrorBoundariesThatAlreadyFailed.add(instance);
18916 }
18917}
18918
18919function flushPassiveEffects() {
18920 if (passiveEffectCallbackHandle !== null) {
18921 cancelPassiveEffects(passiveEffectCallbackHandle);
18922 }
18923 if (passiveEffectCallback !== null) {
18924 // We call the scheduled callback instead of commitPassiveEffects directly
18925 // to ensure tracing works correctly.
18926 passiveEffectCallback();
18927 }
18928}
18929
18930function commitRoot(root, finishedWork) {
18931 isWorking = true;
18932 isCommitting$1 = true;
18933 startCommitTimer();
18934
18935 !(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;
18936 var committedExpirationTime = root.pendingCommitExpirationTime;
18937 !(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;
18938 root.pendingCommitExpirationTime = NoWork;
18939
18940 // Update the pending priority levels to account for the work that we are
18941 // about to commit. This needs to happen before calling the lifecycles, since
18942 // they may schedule additional updates.
18943 var updateExpirationTimeBeforeCommit = finishedWork.expirationTime;
18944 var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime;
18945 var earliestRemainingTimeBeforeCommit = childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit ? childExpirationTimeBeforeCommit : updateExpirationTimeBeforeCommit;
18946 markCommittedPriorityLevels(root, earliestRemainingTimeBeforeCommit);
18947
18948 var prevInteractions = null;
18949 if (enableSchedulerTracing) {
18950 // Restore any pending interactions at this point,
18951 // So that cascading work triggered during the render phase will be accounted for.
18952 prevInteractions = __interactionsRef.current;
18953 __interactionsRef.current = root.memoizedInteractions;
18954 }
18955
18956 // Reset this to null before calling lifecycles
18957 ReactCurrentOwner$2.current = null;
18958
18959 var firstEffect = void 0;
18960 if (finishedWork.effectTag > PerformedWork) {
18961 // A fiber's effect list consists only of its children, not itself. So if
18962 // the root has an effect, we need to add it to the end of the list. The
18963 // resulting list is the set that would belong to the root's parent, if
18964 // it had one; that is, all the effects in the tree including the root.
18965 if (finishedWork.lastEffect !== null) {
18966 finishedWork.lastEffect.nextEffect = finishedWork;
18967 firstEffect = finishedWork.firstEffect;
18968 } else {
18969 firstEffect = finishedWork;
18970 }
18971 } else {
18972 // There is no effect on the root.
18973 firstEffect = finishedWork.firstEffect;
18974 }
18975
18976 prepareForCommit(root.containerInfo);
18977
18978 // Invoke instances of getSnapshotBeforeUpdate before mutation.
18979 nextEffect = firstEffect;
18980 startCommitSnapshotEffectsTimer();
18981 while (nextEffect !== null) {
18982 var didError = false;
18983 var error = void 0;
18984 {
18985 invokeGuardedCallback(null, commitBeforeMutationLifecycles, null);
18986 if (hasCaughtError()) {
18987 didError = true;
18988 error = clearCaughtError();
18989 }
18990 }
18991 if (didError) {
18992 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
18993 captureCommitPhaseError(nextEffect, error);
18994 // Clean-up
18995 if (nextEffect !== null) {
18996 nextEffect = nextEffect.nextEffect;
18997 }
18998 }
18999 }
19000 stopCommitSnapshotEffectsTimer();
19001
19002 if (enableProfilerTimer) {
19003 // Mark the current commit time to be shared by all Profilers in this batch.
19004 // This enables them to be grouped later.
19005 recordCommitTime();
19006 }
19007
19008 // Commit all the side-effects within a tree. We'll do this in two passes.
19009 // The first pass performs all the host insertions, updates, deletions and
19010 // ref unmounts.
19011 nextEffect = firstEffect;
19012 startCommitHostEffectsTimer();
19013 while (nextEffect !== null) {
19014 var _didError = false;
19015 var _error = void 0;
19016 {
19017 invokeGuardedCallback(null, commitAllHostEffects, null);
19018 if (hasCaughtError()) {
19019 _didError = true;
19020 _error = clearCaughtError();
19021 }
19022 }
19023 if (_didError) {
19024 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
19025 captureCommitPhaseError(nextEffect, _error);
19026 // Clean-up
19027 if (nextEffect !== null) {
19028 nextEffect = nextEffect.nextEffect;
19029 }
19030 }
19031 }
19032 stopCommitHostEffectsTimer();
19033
19034 resetAfterCommit(root.containerInfo);
19035
19036 // The work-in-progress tree is now the current tree. This must come after
19037 // the first pass of the commit phase, so that the previous tree is still
19038 // current during componentWillUnmount, but before the second pass, so that
19039 // the finished work is current during componentDidMount/Update.
19040 root.current = finishedWork;
19041
19042 // In the second pass we'll perform all life-cycles and ref callbacks.
19043 // Life-cycles happen as a separate pass so that all placements, updates,
19044 // and deletions in the entire tree have already been invoked.
19045 // This pass also triggers any renderer-specific initial effects.
19046 nextEffect = firstEffect;
19047 startCommitLifeCyclesTimer();
19048 while (nextEffect !== null) {
19049 var _didError2 = false;
19050 var _error2 = void 0;
19051 {
19052 invokeGuardedCallback(null, commitAllLifeCycles, null, root, committedExpirationTime);
19053 if (hasCaughtError()) {
19054 _didError2 = true;
19055 _error2 = clearCaughtError();
19056 }
19057 }
19058 if (_didError2) {
19059 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
19060 captureCommitPhaseError(nextEffect, _error2);
19061 if (nextEffect !== null) {
19062 nextEffect = nextEffect.nextEffect;
19063 }
19064 }
19065 }
19066
19067 if (firstEffect !== null && rootWithPendingPassiveEffects !== null) {
19068 // This commit included a passive effect. These do not need to fire until
19069 // after the next paint. Schedule an callback to fire them in an async
19070 // event. To ensure serial execution, the callback will be flushed early if
19071 // we enter rootWithPendingPassiveEffects commit phase before then.
19072 var callback = commitPassiveEffects.bind(null, root, firstEffect);
19073 if (enableSchedulerTracing) {
19074 // TODO: Avoid this extra callback by mutating the tracing ref directly,
19075 // like we do at the beginning of commitRoot. I've opted not to do that
19076 // here because that code is still in flux.
19077 callback = unstable_wrap(callback);
19078 }
19079 passiveEffectCallbackHandle = unstable_runWithPriority(unstable_NormalPriority, function () {
19080 return schedulePassiveEffects(callback);
19081 });
19082 passiveEffectCallback = callback;
19083 }
19084
19085 isCommitting$1 = false;
19086 isWorking = false;
19087 stopCommitLifeCyclesTimer();
19088 stopCommitTimer();
19089 onCommitRoot(finishedWork.stateNode);
19090 if (true && ReactFiberInstrumentation_1.debugTool) {
19091 ReactFiberInstrumentation_1.debugTool.onCommitWork(finishedWork);
19092 }
19093
19094 var updateExpirationTimeAfterCommit = finishedWork.expirationTime;
19095 var childExpirationTimeAfterCommit = finishedWork.childExpirationTime;
19096 var earliestRemainingTimeAfterCommit = childExpirationTimeAfterCommit > updateExpirationTimeAfterCommit ? childExpirationTimeAfterCommit : updateExpirationTimeAfterCommit;
19097 if (earliestRemainingTimeAfterCommit === NoWork) {
19098 // If there's no remaining work, we can clear the set of already failed
19099 // error boundaries.
19100 legacyErrorBoundariesThatAlreadyFailed = null;
19101 }
19102 onCommit(root, earliestRemainingTimeAfterCommit);
19103
19104 if (enableSchedulerTracing) {
19105 __interactionsRef.current = prevInteractions;
19106
19107 var subscriber = void 0;
19108
19109 try {
19110 subscriber = __subscriberRef.current;
19111 if (subscriber !== null && root.memoizedInteractions.size > 0) {
19112 var threadID = computeThreadID(committedExpirationTime, root.interactionThreadID);
19113 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
19114 }
19115 } catch (error) {
19116 // It's not safe for commitRoot() to throw.
19117 // Store the error for now and we'll re-throw in finishRendering().
19118 if (!hasUnhandledError) {
19119 hasUnhandledError = true;
19120 unhandledError = error;
19121 }
19122 } finally {
19123 // Clear completed interactions from the pending Map.
19124 // Unless the render was suspended or cascading work was scheduled,
19125 // In which case– leave pending interactions until the subsequent render.
19126 var pendingInteractionMap = root.pendingInteractionMap;
19127 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
19128 // Only decrement the pending interaction count if we're done.
19129 // If there's still work at the current priority,
19130 // That indicates that we are waiting for suspense data.
19131 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
19132 pendingInteractionMap.delete(scheduledExpirationTime);
19133
19134 scheduledInteractions.forEach(function (interaction) {
19135 interaction.__count--;
19136
19137 if (subscriber !== null && interaction.__count === 0) {
19138 try {
19139 subscriber.onInteractionScheduledWorkCompleted(interaction);
19140 } catch (error) {
19141 // It's not safe for commitRoot() to throw.
19142 // Store the error for now and we'll re-throw in finishRendering().
19143 if (!hasUnhandledError) {
19144 hasUnhandledError = true;
19145 unhandledError = error;
19146 }
19147 }
19148 }
19149 });
19150 }
19151 });
19152 }
19153 }
19154}
19155
19156function resetChildExpirationTime(workInProgress, renderTime) {
19157 if (renderTime !== Never && workInProgress.childExpirationTime === Never) {
19158 // The children of this component are hidden. Don't bubble their
19159 // expiration times.
19160 return;
19161 }
19162
19163 var newChildExpirationTime = NoWork;
19164
19165 // Bubble up the earliest expiration time.
19166 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19167 // We're in profiling mode.
19168 // Let's use this same traversal to update the render durations.
19169 var actualDuration = workInProgress.actualDuration;
19170 var treeBaseDuration = workInProgress.selfBaseDuration;
19171
19172 // When a fiber is cloned, its actualDuration is reset to 0.
19173 // This value will only be updated if work is done on the fiber (i.e. it doesn't bailout).
19174 // When work is done, it should bubble to the parent's actualDuration.
19175 // If the fiber has not been cloned though, (meaning no work was done),
19176 // Then this value will reflect the amount of time spent working on a previous render.
19177 // In that case it should not bubble.
19178 // We determine whether it was cloned by comparing the child pointer.
19179 var shouldBubbleActualDurations = workInProgress.alternate === null || workInProgress.child !== workInProgress.alternate.child;
19180
19181 var child = workInProgress.child;
19182 while (child !== null) {
19183 var childUpdateExpirationTime = child.expirationTime;
19184 var childChildExpirationTime = child.childExpirationTime;
19185 if (childUpdateExpirationTime > newChildExpirationTime) {
19186 newChildExpirationTime = childUpdateExpirationTime;
19187 }
19188 if (childChildExpirationTime > newChildExpirationTime) {
19189 newChildExpirationTime = childChildExpirationTime;
19190 }
19191 if (shouldBubbleActualDurations) {
19192 actualDuration += child.actualDuration;
19193 }
19194 treeBaseDuration += child.treeBaseDuration;
19195 child = child.sibling;
19196 }
19197 workInProgress.actualDuration = actualDuration;
19198 workInProgress.treeBaseDuration = treeBaseDuration;
19199 } else {
19200 var _child = workInProgress.child;
19201 while (_child !== null) {
19202 var _childUpdateExpirationTime = _child.expirationTime;
19203 var _childChildExpirationTime = _child.childExpirationTime;
19204 if (_childUpdateExpirationTime > newChildExpirationTime) {
19205 newChildExpirationTime = _childUpdateExpirationTime;
19206 }
19207 if (_childChildExpirationTime > newChildExpirationTime) {
19208 newChildExpirationTime = _childChildExpirationTime;
19209 }
19210 _child = _child.sibling;
19211 }
19212 }
19213
19214 workInProgress.childExpirationTime = newChildExpirationTime;
19215}
19216
19217function completeUnitOfWork(workInProgress) {
19218 // Attempt to complete the current unit of work, then move to the
19219 // next sibling. If there are no more siblings, return to the
19220 // parent fiber.
19221 while (true) {
19222 // The current, flushed, state of this fiber is the alternate.
19223 // Ideally nothing should rely on this, but relying on it here
19224 // means that we don't need an additional field on the work in
19225 // progress.
19226 var current$$1 = workInProgress.alternate;
19227 {
19228 setCurrentFiber(workInProgress);
19229 }
19230
19231 var returnFiber = workInProgress.return;
19232 var siblingFiber = workInProgress.sibling;
19233
19234 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
19235 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
19236 // Don't replay if it fails during completion phase.
19237 mayReplayFailedUnitOfWork = false;
19238 }
19239 // This fiber completed.
19240 // Remember we're completing this unit so we can find a boundary if it fails.
19241 nextUnitOfWork = workInProgress;
19242 if (enableProfilerTimer) {
19243 if (workInProgress.mode & ProfileMode) {
19244 startProfilerTimer(workInProgress);
19245 }
19246 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
19247 if (workInProgress.mode & ProfileMode) {
19248 // Update render duration assuming we didn't error.
19249 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
19250 }
19251 } else {
19252 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
19253 }
19254 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
19255 // We're out of completion phase so replaying is fine now.
19256 mayReplayFailedUnitOfWork = true;
19257 }
19258 stopWorkTimer(workInProgress);
19259 resetChildExpirationTime(workInProgress, nextRenderExpirationTime);
19260 {
19261 resetCurrentFiber();
19262 }
19263
19264 if (nextUnitOfWork !== null) {
19265 // Completing this fiber spawned new work. Work on that next.
19266 return nextUnitOfWork;
19267 }
19268
19269 if (returnFiber !== null &&
19270 // Do not append effects to parents if a sibling failed to complete
19271 (returnFiber.effectTag & Incomplete) === NoEffect) {
19272 // Append all the effects of the subtree and this fiber onto the effect
19273 // list of the parent. The completion order of the children affects the
19274 // side-effect order.
19275 if (returnFiber.firstEffect === null) {
19276 returnFiber.firstEffect = workInProgress.firstEffect;
19277 }
19278 if (workInProgress.lastEffect !== null) {
19279 if (returnFiber.lastEffect !== null) {
19280 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
19281 }
19282 returnFiber.lastEffect = workInProgress.lastEffect;
19283 }
19284
19285 // If this fiber had side-effects, we append it AFTER the children's
19286 // side-effects. We can perform certain side-effects earlier if
19287 // needed, by doing multiple passes over the effect list. We don't want
19288 // to schedule our own side-effect on our own list because if end up
19289 // reusing children we'll schedule this effect onto itself since we're
19290 // at the end.
19291 var effectTag = workInProgress.effectTag;
19292 // Skip both NoWork and PerformedWork tags when creating the effect list.
19293 // PerformedWork effect is read by React DevTools but shouldn't be committed.
19294 if (effectTag > PerformedWork) {
19295 if (returnFiber.lastEffect !== null) {
19296 returnFiber.lastEffect.nextEffect = workInProgress;
19297 } else {
19298 returnFiber.firstEffect = workInProgress;
19299 }
19300 returnFiber.lastEffect = workInProgress;
19301 }
19302 }
19303
19304 if (true && ReactFiberInstrumentation_1.debugTool) {
19305 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
19306 }
19307
19308 if (siblingFiber !== null) {
19309 // If there is more work to do in this returnFiber, do that next.
19310 return siblingFiber;
19311 } else if (returnFiber !== null) {
19312 // If there's no more work in this returnFiber. Complete the returnFiber.
19313 workInProgress = returnFiber;
19314 continue;
19315 } else {
19316 // We've reached the root.
19317 return null;
19318 }
19319 } else {
19320 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19321 // Record the render duration for the fiber that errored.
19322 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
19323
19324 // Include the time spent working on failed children before continuing.
19325 var actualDuration = workInProgress.actualDuration;
19326 var child = workInProgress.child;
19327 while (child !== null) {
19328 actualDuration += child.actualDuration;
19329 child = child.sibling;
19330 }
19331 workInProgress.actualDuration = actualDuration;
19332 }
19333
19334 // This fiber did not complete because something threw. Pop values off
19335 // the stack without entering the complete phase. If this is a boundary,
19336 // capture values if possible.
19337 var next = unwindWork(workInProgress, nextRenderExpirationTime);
19338 // Because this fiber did not complete, don't reset its expiration time.
19339 if (workInProgress.effectTag & DidCapture) {
19340 // Restarting an error boundary
19341 stopFailedWorkTimer(workInProgress);
19342 } else {
19343 stopWorkTimer(workInProgress);
19344 }
19345
19346 {
19347 resetCurrentFiber();
19348 }
19349
19350 if (next !== null) {
19351 stopWorkTimer(workInProgress);
19352 if (true && ReactFiberInstrumentation_1.debugTool) {
19353 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
19354 }
19355
19356 // If completing this work spawned new work, do that next. We'll come
19357 // back here again.
19358 // Since we're restarting, remove anything that is not a host effect
19359 // from the effect tag.
19360 next.effectTag &= HostEffectMask;
19361 return next;
19362 }
19363
19364 if (returnFiber !== null) {
19365 // Mark the parent fiber as incomplete and clear its effect list.
19366 returnFiber.firstEffect = returnFiber.lastEffect = null;
19367 returnFiber.effectTag |= Incomplete;
19368 }
19369
19370 if (true && ReactFiberInstrumentation_1.debugTool) {
19371 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
19372 }
19373
19374 if (siblingFiber !== null) {
19375 // If there is more work to do in this returnFiber, do that next.
19376 return siblingFiber;
19377 } else if (returnFiber !== null) {
19378 // If there's no more work in this returnFiber. Complete the returnFiber.
19379 workInProgress = returnFiber;
19380 continue;
19381 } else {
19382 return null;
19383 }
19384 }
19385 }
19386
19387 // Without this explicit null return Flow complains of invalid return type
19388 // TODO Remove the above while(true) loop
19389 // eslint-disable-next-line no-unreachable
19390 return null;
19391}
19392
19393function performUnitOfWork(workInProgress) {
19394 // The current, flushed, state of this fiber is the alternate.
19395 // Ideally nothing should rely on this, but relying on it here
19396 // means that we don't need an additional field on the work in
19397 // progress.
19398 var current$$1 = workInProgress.alternate;
19399
19400 // See if beginning this work spawns more work.
19401 startWorkTimer(workInProgress);
19402 {
19403 setCurrentFiber(workInProgress);
19404 }
19405
19406 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
19407 stashedWorkInProgressProperties = assignFiberPropertiesInDEV(stashedWorkInProgressProperties, workInProgress);
19408 }
19409
19410 var next = void 0;
19411 if (enableProfilerTimer) {
19412 if (workInProgress.mode & ProfileMode) {
19413 startProfilerTimer(workInProgress);
19414 }
19415
19416 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
19417 workInProgress.memoizedProps = workInProgress.pendingProps;
19418
19419 if (workInProgress.mode & ProfileMode) {
19420 // Record the render duration assuming we didn't bailout (or error).
19421 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
19422 }
19423 } else {
19424 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
19425 workInProgress.memoizedProps = workInProgress.pendingProps;
19426 }
19427
19428 {
19429 resetCurrentFiber();
19430 if (isReplayingFailedUnitOfWork) {
19431 // Currently replaying a failed unit of work. This should be unreachable,
19432 // because the render phase is meant to be idempotent, and it should
19433 // have thrown again. Since it didn't, rethrow the original error, so
19434 // React's internal stack is not misaligned.
19435 rethrowOriginalError();
19436 }
19437 }
19438 if (true && ReactFiberInstrumentation_1.debugTool) {
19439 ReactFiberInstrumentation_1.debugTool.onBeginWork(workInProgress);
19440 }
19441
19442 if (next === null) {
19443 // If this doesn't spawn new work, complete the current work.
19444 next = completeUnitOfWork(workInProgress);
19445 }
19446
19447 ReactCurrentOwner$2.current = null;
19448
19449 return next;
19450}
19451
19452function workLoop(isYieldy) {
19453 if (!isYieldy) {
19454 // Flush work without yielding
19455 while (nextUnitOfWork !== null) {
19456 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
19457 }
19458 } else {
19459 // Flush asynchronous work until there's a higher priority event
19460 while (nextUnitOfWork !== null && !shouldYieldToRenderer()) {
19461 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
19462 }
19463 }
19464}
19465
19466function renderRoot(root, isYieldy) {
19467 !!isWorking ? invariant(false, 'renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;
19468
19469 flushPassiveEffects();
19470
19471 isWorking = true;
19472 var previousDispatcher = ReactCurrentDispatcher.current;
19473 ReactCurrentDispatcher.current = ContextOnlyDispatcher;
19474
19475 var expirationTime = root.nextExpirationTimeToWorkOn;
19476
19477 // Check if we're starting from a fresh stack, or if we're resuming from
19478 // previously yielded work.
19479 if (expirationTime !== nextRenderExpirationTime || root !== nextRoot || nextUnitOfWork === null) {
19480 // Reset the stack and start working from the root.
19481 resetStack();
19482 nextRoot = root;
19483 nextRenderExpirationTime = expirationTime;
19484 nextUnitOfWork = createWorkInProgress(nextRoot.current, null, nextRenderExpirationTime);
19485 root.pendingCommitExpirationTime = NoWork;
19486
19487 if (enableSchedulerTracing) {
19488 // Determine which interactions this batch of work currently includes,
19489 // So that we can accurately attribute time spent working on it,
19490 var interactions = new Set();
19491 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
19492 if (scheduledExpirationTime >= expirationTime) {
19493 scheduledInteractions.forEach(function (interaction) {
19494 return interactions.add(interaction);
19495 });
19496 }
19497 });
19498
19499 // Store the current set of interactions on the FiberRoot for a few reasons:
19500 // We can re-use it in hot functions like renderRoot() without having to recalculate it.
19501 // We will also use it in commitWork() to pass to any Profiler onRender() hooks.
19502 // This also provides DevTools with a way to access it when the onCommitRoot() hook is called.
19503 root.memoizedInteractions = interactions;
19504
19505 if (interactions.size > 0) {
19506 var subscriber = __subscriberRef.current;
19507 if (subscriber !== null) {
19508 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
19509 try {
19510 subscriber.onWorkStarted(interactions, threadID);
19511 } catch (error) {
19512 // Work thrown by an interaction tracing subscriber should be rethrown,
19513 // But only once it's safe (to avoid leaving the scheduler in an invalid state).
19514 // Store the error for now and we'll re-throw in finishRendering().
19515 if (!hasUnhandledError) {
19516 hasUnhandledError = true;
19517 unhandledError = error;
19518 }
19519 }
19520 }
19521 }
19522 }
19523 }
19524
19525 var prevInteractions = null;
19526 if (enableSchedulerTracing) {
19527 // We're about to start new traced work.
19528 // Restore pending interactions so cascading work triggered during the render phase will be accounted for.
19529 prevInteractions = __interactionsRef.current;
19530 __interactionsRef.current = root.memoizedInteractions;
19531 }
19532
19533 var didFatal = false;
19534
19535 startWorkLoopTimer(nextUnitOfWork);
19536
19537 do {
19538 try {
19539 workLoop(isYieldy);
19540 } catch (thrownValue) {
19541 resetContextDependences();
19542 resetHooks();
19543
19544 // Reset in case completion throws.
19545 // This is only used in DEV and when replaying is on.
19546 var mayReplay = void 0;
19547 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
19548 mayReplay = mayReplayFailedUnitOfWork;
19549 mayReplayFailedUnitOfWork = true;
19550 }
19551
19552 if (nextUnitOfWork === null) {
19553 // This is a fatal error.
19554 didFatal = true;
19555 onUncaughtError(thrownValue);
19556 } else {
19557 if (enableProfilerTimer && nextUnitOfWork.mode & ProfileMode) {
19558 // Record the time spent rendering before an error was thrown.
19559 // This avoids inaccurate Profiler durations in the case of a suspended render.
19560 stopProfilerTimerIfRunningAndRecordDelta(nextUnitOfWork, true);
19561 }
19562
19563 {
19564 // Reset global debug state
19565 // We assume this is defined in DEV
19566 resetCurrentlyProcessingQueue();
19567 }
19568
19569 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
19570 if (mayReplay) {
19571 var failedUnitOfWork = nextUnitOfWork;
19572 replayUnitOfWork(failedUnitOfWork, thrownValue, isYieldy);
19573 }
19574 }
19575
19576 // TODO: we already know this isn't true in some cases.
19577 // At least this shows a nicer error message until we figure out the cause.
19578 // https://github.com/facebook/react/issues/12449#issuecomment-386727431
19579 !(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;
19580
19581 var sourceFiber = nextUnitOfWork;
19582 var returnFiber = sourceFiber.return;
19583 if (returnFiber === null) {
19584 // This is the root. The root could capture its own errors. However,
19585 // we don't know if it errors before or after we pushed the host
19586 // context. This information is needed to avoid a stack mismatch.
19587 // Because we're not sure, treat this as a fatal error. We could track
19588 // which phase it fails in, but doesn't seem worth it. At least
19589 // for now.
19590 didFatal = true;
19591 onUncaughtError(thrownValue);
19592 } else {
19593 throwException(root, returnFiber, sourceFiber, thrownValue, nextRenderExpirationTime);
19594 nextUnitOfWork = completeUnitOfWork(sourceFiber);
19595 continue;
19596 }
19597 }
19598 }
19599 break;
19600 } while (true);
19601
19602 if (enableSchedulerTracing) {
19603 // Traced work is done for now; restore the previous interactions.
19604 __interactionsRef.current = prevInteractions;
19605 }
19606
19607 // We're done performing work. Time to clean up.
19608 isWorking = false;
19609 ReactCurrentDispatcher.current = previousDispatcher;
19610 resetContextDependences();
19611 resetHooks();
19612
19613 // Yield back to main thread.
19614 if (didFatal) {
19615 var _didCompleteRoot = false;
19616 stopWorkLoopTimer(interruptedBy, _didCompleteRoot);
19617 interruptedBy = null;
19618 // There was a fatal error.
19619 {
19620 resetStackAfterFatalErrorInDev();
19621 }
19622 // `nextRoot` points to the in-progress root. A non-null value indicates
19623 // that we're in the middle of an async render. Set it to null to indicate
19624 // there's no more work to be done in the current batch.
19625 nextRoot = null;
19626 onFatal(root);
19627 return;
19628 }
19629
19630 if (nextUnitOfWork !== null) {
19631 // There's still remaining async work in this tree, but we ran out of time
19632 // in the current frame. Yield back to the renderer. Unless we're
19633 // interrupted by a higher priority update, we'll continue later from where
19634 // we left off.
19635 var _didCompleteRoot2 = false;
19636 stopWorkLoopTimer(interruptedBy, _didCompleteRoot2);
19637 interruptedBy = null;
19638 onYield(root);
19639 return;
19640 }
19641
19642 // We completed the whole tree.
19643 var didCompleteRoot = true;
19644 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
19645 var rootWorkInProgress = root.current.alternate;
19646 !(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;
19647
19648 // `nextRoot` points to the in-progress root. A non-null value indicates
19649 // that we're in the middle of an async render. Set it to null to indicate
19650 // there's no more work to be done in the current batch.
19651 nextRoot = null;
19652 interruptedBy = null;
19653
19654 if (nextRenderDidError) {
19655 // There was an error
19656 if (hasLowerPriorityWork(root, expirationTime)) {
19657 // There's lower priority work. If so, it may have the effect of fixing
19658 // the exception that was just thrown. Exit without committing. This is
19659 // similar to a suspend, but without a timeout because we're not waiting
19660 // for a promise to resolve. React will restart at the lower
19661 // priority level.
19662 markSuspendedPriorityLevel(root, expirationTime);
19663 var suspendedExpirationTime = expirationTime;
19664 var rootExpirationTime = root.expirationTime;
19665 onSuspend(root, rootWorkInProgress, suspendedExpirationTime, rootExpirationTime, -1 // Indicates no timeout
19666 );
19667 return;
19668 } else if (
19669 // There's no lower priority work, but we're rendering asynchronously.
19670 // Synchronously attempt to render the same level one more time. This is
19671 // similar to a suspend, but without a timeout because we're not waiting
19672 // for a promise to resolve.
19673 !root.didError && isYieldy) {
19674 root.didError = true;
19675 var _suspendedExpirationTime = root.nextExpirationTimeToWorkOn = expirationTime;
19676 var _rootExpirationTime = root.expirationTime = Sync;
19677 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime, _rootExpirationTime, -1 // Indicates no timeout
19678 );
19679 return;
19680 }
19681 }
19682
19683 if (isYieldy && nextLatestAbsoluteTimeoutMs !== -1) {
19684 // The tree was suspended.
19685 var _suspendedExpirationTime2 = expirationTime;
19686 markSuspendedPriorityLevel(root, _suspendedExpirationTime2);
19687
19688 // Find the earliest uncommitted expiration time in the tree, including
19689 // work that is suspended. The timeout threshold cannot be longer than
19690 // the overall expiration.
19691 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, expirationTime);
19692 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
19693 if (earliestExpirationTimeMs < nextLatestAbsoluteTimeoutMs) {
19694 nextLatestAbsoluteTimeoutMs = earliestExpirationTimeMs;
19695 }
19696
19697 // Subtract the current time from the absolute timeout to get the number
19698 // of milliseconds until the timeout. In other words, convert an absolute
19699 // timestamp to a relative time. This is the value that is passed
19700 // to `setTimeout`.
19701 var currentTimeMs = expirationTimeToMs(requestCurrentTime());
19702 var msUntilTimeout = nextLatestAbsoluteTimeoutMs - currentTimeMs;
19703 msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout;
19704
19705 // TODO: Account for the Just Noticeable Difference
19706
19707 var _rootExpirationTime2 = root.expirationTime;
19708 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime2, _rootExpirationTime2, msUntilTimeout);
19709 return;
19710 }
19711
19712 // Ready to commit.
19713 onComplete(root, rootWorkInProgress, expirationTime);
19714}
19715
19716function captureCommitPhaseError(sourceFiber, value) {
19717 var expirationTime = Sync;
19718 var fiber = sourceFiber.return;
19719 while (fiber !== null) {
19720 switch (fiber.tag) {
19721 case ClassComponent:
19722 var ctor = fiber.type;
19723 var instance = fiber.stateNode;
19724 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
19725 var errorInfo = createCapturedValue(value, sourceFiber);
19726 var update = createClassErrorUpdate(fiber, errorInfo, expirationTime);
19727 enqueueUpdate(fiber, update);
19728 scheduleWork(fiber, expirationTime);
19729 return;
19730 }
19731 break;
19732 case HostRoot:
19733 {
19734 var _errorInfo = createCapturedValue(value, sourceFiber);
19735 var _update = createRootErrorUpdate(fiber, _errorInfo, expirationTime);
19736 enqueueUpdate(fiber, _update);
19737 scheduleWork(fiber, expirationTime);
19738 return;
19739 }
19740 }
19741 fiber = fiber.return;
19742 }
19743
19744 if (sourceFiber.tag === HostRoot) {
19745 // Error was thrown at the root. There is no parent, so the root
19746 // itself should capture it.
19747 var rootFiber = sourceFiber;
19748 var _errorInfo2 = createCapturedValue(value, rootFiber);
19749 var _update2 = createRootErrorUpdate(rootFiber, _errorInfo2, expirationTime);
19750 enqueueUpdate(rootFiber, _update2);
19751 scheduleWork(rootFiber, expirationTime);
19752 }
19753}
19754
19755function computeThreadID(expirationTime, interactionThreadID) {
19756 // Interaction threads are unique per root and expiration time.
19757 return expirationTime * 1000 + interactionThreadID;
19758}
19759
19760// Creates a unique async expiration time.
19761function computeUniqueAsyncExpiration() {
19762 var currentTime = requestCurrentTime();
19763 var result = computeAsyncExpiration(currentTime);
19764 if (result >= lastUniqueAsyncExpiration) {
19765 // Since we assume the current time monotonically increases, we only hit
19766 // this branch when computeUniqueAsyncExpiration is fired multiple times
19767 // within a 200ms window (or whatever the async bucket size is).
19768 result = lastUniqueAsyncExpiration - 1;
19769 }
19770 lastUniqueAsyncExpiration = result;
19771 return lastUniqueAsyncExpiration;
19772}
19773
19774function computeExpirationForFiber(currentTime, fiber) {
19775 var priorityLevel = unstable_getCurrentPriorityLevel();
19776
19777 var expirationTime = void 0;
19778 if ((fiber.mode & ConcurrentMode) === NoContext) {
19779 // Outside of concurrent mode, updates are always synchronous.
19780 expirationTime = Sync;
19781 } else if (isWorking && !isCommitting$1) {
19782 // During render phase, updates expire during as the current render.
19783 expirationTime = nextRenderExpirationTime;
19784 } else {
19785 switch (priorityLevel) {
19786 case unstable_ImmediatePriority:
19787 expirationTime = Sync;
19788 break;
19789 case unstable_UserBlockingPriority:
19790 expirationTime = computeInteractiveExpiration(currentTime);
19791 break;
19792 case unstable_NormalPriority:
19793 // This is a normal, concurrent update
19794 expirationTime = computeAsyncExpiration(currentTime);
19795 break;
19796 case unstable_LowPriority:
19797 case unstable_IdlePriority:
19798 expirationTime = Never;
19799 break;
19800 default:
19801 invariant(false, 'Unknown priority level. This error is likely caused by a bug in React. Please file an issue.');
19802 }
19803
19804 // If we're in the middle of rendering a tree, do not update at the same
19805 // expiration time that is already rendering.
19806 if (nextRoot !== null && expirationTime === nextRenderExpirationTime) {
19807 expirationTime -= 1;
19808 }
19809 }
19810
19811 // Keep track of the lowest pending interactive expiration time. This
19812 // allows us to synchronously flush all interactive updates
19813 // when needed.
19814 // TODO: Move this to renderer?
19815 if (priorityLevel === unstable_UserBlockingPriority && (lowestPriorityPendingInteractiveExpirationTime === NoWork || expirationTime < lowestPriorityPendingInteractiveExpirationTime)) {
19816 lowestPriorityPendingInteractiveExpirationTime = expirationTime;
19817 }
19818
19819 return expirationTime;
19820}
19821
19822function renderDidSuspend(root, absoluteTimeoutMs, suspendedTime) {
19823 // Schedule the timeout.
19824 if (absoluteTimeoutMs >= 0 && nextLatestAbsoluteTimeoutMs < absoluteTimeoutMs) {
19825 nextLatestAbsoluteTimeoutMs = absoluteTimeoutMs;
19826 }
19827}
19828
19829function renderDidError() {
19830 nextRenderDidError = true;
19831}
19832
19833function pingSuspendedRoot(root, thenable, pingTime) {
19834 // A promise that previously suspended React from committing has resolved.
19835 // If React is still suspended, try again at the previous level (pingTime).
19836
19837 var pingCache = root.pingCache;
19838 if (pingCache !== null) {
19839 // The thenable resolved, so we no longer need to memoize, because it will
19840 // never be thrown again.
19841 pingCache.delete(thenable);
19842 }
19843
19844 if (nextRoot !== null && nextRenderExpirationTime === pingTime) {
19845 // Received a ping at the same priority level at which we're currently
19846 // rendering. Restart from the root.
19847 nextRoot = null;
19848 } else {
19849 // Confirm that the root is still suspended at this level. Otherwise exit.
19850 if (isPriorityLevelSuspended(root, pingTime)) {
19851 // Ping at the original level
19852 markPingedPriorityLevel(root, pingTime);
19853 var rootExpirationTime = root.expirationTime;
19854 if (rootExpirationTime !== NoWork) {
19855 requestWork(root, rootExpirationTime);
19856 }
19857 }
19858 }
19859}
19860
19861function retryTimedOutBoundary(boundaryFiber, thenable) {
19862 // The boundary fiber (a Suspense component) previously timed out and was
19863 // rendered in its fallback state. One of the promises that suspended it has
19864 // resolved, which means at least part of the tree was likely unblocked. Try
19865 var retryCache = void 0;
19866 if (enableSuspenseServerRenderer) {
19867 switch (boundaryFiber.tag) {
19868 case SuspenseComponent:
19869 retryCache = boundaryFiber.stateNode;
19870 break;
19871 case DehydratedSuspenseComponent:
19872 retryCache = boundaryFiber.memoizedState;
19873 break;
19874 default:
19875 invariant(false, 'Pinged unknown suspense boundary type. This is probably a bug in React.');
19876 }
19877 } else {
19878 retryCache = boundaryFiber.stateNode;
19879 }
19880 if (retryCache !== null) {
19881 // The thenable resolved, so we no longer need to memoize, because it will
19882 // never be thrown again.
19883 retryCache.delete(thenable);
19884 }
19885
19886 var currentTime = requestCurrentTime();
19887 var retryTime = computeExpirationForFiber(currentTime, boundaryFiber);
19888 var root = scheduleWorkToRoot(boundaryFiber, retryTime);
19889 if (root !== null) {
19890 markPendingPriorityLevel(root, retryTime);
19891 var rootExpirationTime = root.expirationTime;
19892 if (rootExpirationTime !== NoWork) {
19893 requestWork(root, rootExpirationTime);
19894 }
19895 }
19896}
19897
19898function scheduleWorkToRoot(fiber, expirationTime) {
19899 recordScheduleUpdate();
19900
19901 {
19902 if (fiber.tag === ClassComponent) {
19903 var instance = fiber.stateNode;
19904 warnAboutInvalidUpdates(instance);
19905 }
19906 }
19907
19908 // Update the source fiber's expiration time
19909 if (fiber.expirationTime < expirationTime) {
19910 fiber.expirationTime = expirationTime;
19911 }
19912 var alternate = fiber.alternate;
19913 if (alternate !== null && alternate.expirationTime < expirationTime) {
19914 alternate.expirationTime = expirationTime;
19915 }
19916 // Walk the parent path to the root and update the child expiration time.
19917 var node = fiber.return;
19918 var root = null;
19919 if (node === null && fiber.tag === HostRoot) {
19920 root = fiber.stateNode;
19921 } else {
19922 while (node !== null) {
19923 alternate = node.alternate;
19924 if (node.childExpirationTime < expirationTime) {
19925 node.childExpirationTime = expirationTime;
19926 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
19927 alternate.childExpirationTime = expirationTime;
19928 }
19929 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
19930 alternate.childExpirationTime = expirationTime;
19931 }
19932 if (node.return === null && node.tag === HostRoot) {
19933 root = node.stateNode;
19934 break;
19935 }
19936 node = node.return;
19937 }
19938 }
19939
19940 if (enableSchedulerTracing) {
19941 if (root !== null) {
19942 var interactions = __interactionsRef.current;
19943 if (interactions.size > 0) {
19944 var pendingInteractionMap = root.pendingInteractionMap;
19945 var pendingInteractions = pendingInteractionMap.get(expirationTime);
19946 if (pendingInteractions != null) {
19947 interactions.forEach(function (interaction) {
19948 if (!pendingInteractions.has(interaction)) {
19949 // Update the pending async work count for previously unscheduled interaction.
19950 interaction.__count++;
19951 }
19952
19953 pendingInteractions.add(interaction);
19954 });
19955 } else {
19956 pendingInteractionMap.set(expirationTime, new Set(interactions));
19957
19958 // Update the pending async work count for the current interactions.
19959 interactions.forEach(function (interaction) {
19960 interaction.__count++;
19961 });
19962 }
19963
19964 var subscriber = __subscriberRef.current;
19965 if (subscriber !== null) {
19966 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
19967 subscriber.onWorkScheduled(interactions, threadID);
19968 }
19969 }
19970 }
19971 }
19972 return root;
19973}
19974
19975function warnIfNotCurrentlyBatchingInDev(fiber) {
19976 {
19977 if (isRendering === false && isBatchingUpdates === false) {
19978 warningWithoutStack$1(false, 'An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see in the browser." + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));
19979 }
19980 }
19981}
19982
19983function scheduleWork(fiber, expirationTime) {
19984 var root = scheduleWorkToRoot(fiber, expirationTime);
19985 if (root === null) {
19986 {
19987 switch (fiber.tag) {
19988 case ClassComponent:
19989 warnAboutUpdateOnUnmounted(fiber, true);
19990 break;
19991 case FunctionComponent:
19992 case ForwardRef:
19993 case MemoComponent:
19994 case SimpleMemoComponent:
19995 warnAboutUpdateOnUnmounted(fiber, false);
19996 break;
19997 }
19998 }
19999 return;
20000 }
20001
20002 if (!isWorking && nextRenderExpirationTime !== NoWork && expirationTime > nextRenderExpirationTime) {
20003 // This is an interruption. (Used for performance tracking.)
20004 interruptedBy = fiber;
20005 resetStack();
20006 }
20007 markPendingPriorityLevel(root, expirationTime);
20008 if (
20009 // If we're in the render phase, we don't need to schedule this root
20010 // for an update, because we'll do it before we exit...
20011 !isWorking || isCommitting$1 ||
20012 // ...unless this is a different root than the one we're rendering.
20013 nextRoot !== root) {
20014 var rootExpirationTime = root.expirationTime;
20015 requestWork(root, rootExpirationTime);
20016 }
20017 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
20018 // Reset this back to zero so subsequent updates don't throw.
20019 nestedUpdateCount = 0;
20020 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.');
20021 }
20022}
20023
20024function syncUpdates(fn, a, b, c, d) {
20025 return unstable_runWithPriority(unstable_ImmediatePriority, function () {
20026 return fn(a, b, c, d);
20027 });
20028}
20029
20030// TODO: Everything below this is written as if it has been lifted to the
20031// renderers. I'll do this in a follow-up.
20032
20033// Linked-list of roots
20034var firstScheduledRoot = null;
20035var lastScheduledRoot = null;
20036
20037var callbackExpirationTime = NoWork;
20038var callbackID = void 0;
20039var isRendering = false;
20040var nextFlushedRoot = null;
20041var nextFlushedExpirationTime = NoWork;
20042var lowestPriorityPendingInteractiveExpirationTime = NoWork;
20043var hasUnhandledError = false;
20044var unhandledError = null;
20045
20046var isBatchingUpdates = false;
20047var isUnbatchingUpdates = false;
20048
20049var completedBatches = null;
20050
20051var originalStartTimeMs = unstable_now();
20052var currentRendererTime = msToExpirationTime(originalStartTimeMs);
20053var currentSchedulerTime = currentRendererTime;
20054
20055// Use these to prevent an infinite loop of nested updates
20056var NESTED_UPDATE_LIMIT = 50;
20057var nestedUpdateCount = 0;
20058var lastCommittedRootDuringThisBatch = null;
20059
20060function recomputeCurrentRendererTime() {
20061 var currentTimeMs = unstable_now() - originalStartTimeMs;
20062 currentRendererTime = msToExpirationTime(currentTimeMs);
20063}
20064
20065function scheduleCallbackWithExpirationTime(root, expirationTime) {
20066 if (callbackExpirationTime !== NoWork) {
20067 // A callback is already scheduled. Check its expiration time (timeout).
20068 if (expirationTime < callbackExpirationTime) {
20069 // Existing callback has sufficient timeout. Exit.
20070 return;
20071 } else {
20072 if (callbackID !== null) {
20073 // Existing callback has insufficient timeout. Cancel and schedule a
20074 // new one.
20075 unstable_cancelCallback(callbackID);
20076 }
20077 }
20078 // The request callback timer is already running. Don't start a new one.
20079 } else {
20080 startRequestCallbackTimer();
20081 }
20082
20083 callbackExpirationTime = expirationTime;
20084 var currentMs = unstable_now() - originalStartTimeMs;
20085 var expirationTimeMs = expirationTimeToMs(expirationTime);
20086 var timeout = expirationTimeMs - currentMs;
20087 callbackID = unstable_scheduleCallback(performAsyncWork, { timeout: timeout });
20088}
20089
20090// For every call to renderRoot, one of onFatal, onComplete, onSuspend, and
20091// onYield is called upon exiting. We use these in lieu of returning a tuple.
20092// I've also chosen not to inline them into renderRoot because these will
20093// eventually be lifted into the renderer.
20094function onFatal(root) {
20095 root.finishedWork = null;
20096}
20097
20098function onComplete(root, finishedWork, expirationTime) {
20099 root.pendingCommitExpirationTime = expirationTime;
20100 root.finishedWork = finishedWork;
20101}
20102
20103function onSuspend(root, finishedWork, suspendedExpirationTime, rootExpirationTime, msUntilTimeout) {
20104 root.expirationTime = rootExpirationTime;
20105 if (msUntilTimeout === 0 && !shouldYieldToRenderer()) {
20106 // Don't wait an additional tick. Commit the tree immediately.
20107 root.pendingCommitExpirationTime = suspendedExpirationTime;
20108 root.finishedWork = finishedWork;
20109 } else if (msUntilTimeout > 0) {
20110 // Wait `msUntilTimeout` milliseconds before committing.
20111 root.timeoutHandle = scheduleTimeout(onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), msUntilTimeout);
20112 }
20113}
20114
20115function onYield(root) {
20116 root.finishedWork = null;
20117}
20118
20119function onTimeout(root, finishedWork, suspendedExpirationTime) {
20120 // The root timed out. Commit it.
20121 root.pendingCommitExpirationTime = suspendedExpirationTime;
20122 root.finishedWork = finishedWork;
20123 // Read the current time before entering the commit phase. We can be
20124 // certain this won't cause tearing related to batching of event updates
20125 // because we're at the top of a timer event.
20126 recomputeCurrentRendererTime();
20127 currentSchedulerTime = currentRendererTime;
20128 flushRoot(root, suspendedExpirationTime);
20129}
20130
20131function onCommit(root, expirationTime) {
20132 root.expirationTime = expirationTime;
20133 root.finishedWork = null;
20134}
20135
20136function requestCurrentTime() {
20137 // requestCurrentTime is called by the scheduler to compute an expiration
20138 // time.
20139 //
20140 // Expiration times are computed by adding to the current time (the start
20141 // time). However, if two updates are scheduled within the same event, we
20142 // should treat their start times as simultaneous, even if the actual clock
20143 // time has advanced between the first and second call.
20144
20145 // In other words, because expiration times determine how updates are batched,
20146 // we want all updates of like priority that occur within the same event to
20147 // receive the same expiration time. Otherwise we get tearing.
20148 //
20149 // We keep track of two separate times: the current "renderer" time and the
20150 // current "scheduler" time. The renderer time can be updated whenever; it
20151 // only exists to minimize the calls performance.now.
20152 //
20153 // But the scheduler time can only be updated if there's no pending work, or
20154 // if we know for certain that we're not in the middle of an event.
20155
20156 if (isRendering) {
20157 // We're already rendering. Return the most recently read time.
20158 return currentSchedulerTime;
20159 }
20160 // Check if there's pending work.
20161 findHighestPriorityRoot();
20162 if (nextFlushedExpirationTime === NoWork || nextFlushedExpirationTime === Never) {
20163 // If there's no pending work, or if the pending work is offscreen, we can
20164 // read the current time without risk of tearing.
20165 recomputeCurrentRendererTime();
20166 currentSchedulerTime = currentRendererTime;
20167 return currentSchedulerTime;
20168 }
20169 // There's already pending work. We might be in the middle of a browser
20170 // event. If we were to read the current time, it could cause multiple updates
20171 // within the same event to receive different expiration times, leading to
20172 // tearing. Return the last read time. During the next idle callback, the
20173 // time will be updated.
20174 return currentSchedulerTime;
20175}
20176
20177// requestWork is called by the scheduler whenever a root receives an update.
20178// It's up to the renderer to call renderRoot at some point in the future.
20179function requestWork(root, expirationTime) {
20180 addRootToSchedule(root, expirationTime);
20181 if (isRendering) {
20182 // Prevent reentrancy. Remaining work will be scheduled at the end of
20183 // the currently rendering batch.
20184 return;
20185 }
20186
20187 if (isBatchingUpdates) {
20188 // Flush work at the end of the batch.
20189 if (isUnbatchingUpdates) {
20190 // ...unless we're inside unbatchedUpdates, in which case we should
20191 // flush it now.
20192 nextFlushedRoot = root;
20193 nextFlushedExpirationTime = Sync;
20194 performWorkOnRoot(root, Sync, false);
20195 }
20196 return;
20197 }
20198
20199 // TODO: Get rid of Sync and use current time?
20200 if (expirationTime === Sync) {
20201 performSyncWork();
20202 } else {
20203 scheduleCallbackWithExpirationTime(root, expirationTime);
20204 }
20205}
20206
20207function addRootToSchedule(root, expirationTime) {
20208 // Add the root to the schedule.
20209 // Check if this root is already part of the schedule.
20210 if (root.nextScheduledRoot === null) {
20211 // This root is not already scheduled. Add it.
20212 root.expirationTime = expirationTime;
20213 if (lastScheduledRoot === null) {
20214 firstScheduledRoot = lastScheduledRoot = root;
20215 root.nextScheduledRoot = root;
20216 } else {
20217 lastScheduledRoot.nextScheduledRoot = root;
20218 lastScheduledRoot = root;
20219 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
20220 }
20221 } else {
20222 // This root is already scheduled, but its priority may have increased.
20223 var remainingExpirationTime = root.expirationTime;
20224 if (expirationTime > remainingExpirationTime) {
20225 // Update the priority.
20226 root.expirationTime = expirationTime;
20227 }
20228 }
20229}
20230
20231function findHighestPriorityRoot() {
20232 var highestPriorityWork = NoWork;
20233 var highestPriorityRoot = null;
20234 if (lastScheduledRoot !== null) {
20235 var previousScheduledRoot = lastScheduledRoot;
20236 var root = firstScheduledRoot;
20237 while (root !== null) {
20238 var remainingExpirationTime = root.expirationTime;
20239 if (remainingExpirationTime === NoWork) {
20240 // This root no longer has work. Remove it from the scheduler.
20241
20242 // TODO: This check is redudant, but Flow is confused by the branch
20243 // below where we set lastScheduledRoot to null, even though we break
20244 // from the loop right after.
20245 !(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;
20246 if (root === root.nextScheduledRoot) {
20247 // This is the only root in the list.
20248 root.nextScheduledRoot = null;
20249 firstScheduledRoot = lastScheduledRoot = null;
20250 break;
20251 } else if (root === firstScheduledRoot) {
20252 // This is the first root in the list.
20253 var next = root.nextScheduledRoot;
20254 firstScheduledRoot = next;
20255 lastScheduledRoot.nextScheduledRoot = next;
20256 root.nextScheduledRoot = null;
20257 } else if (root === lastScheduledRoot) {
20258 // This is the last root in the list.
20259 lastScheduledRoot = previousScheduledRoot;
20260 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
20261 root.nextScheduledRoot = null;
20262 break;
20263 } else {
20264 previousScheduledRoot.nextScheduledRoot = root.nextScheduledRoot;
20265 root.nextScheduledRoot = null;
20266 }
20267 root = previousScheduledRoot.nextScheduledRoot;
20268 } else {
20269 if (remainingExpirationTime > highestPriorityWork) {
20270 // Update the priority, if it's higher
20271 highestPriorityWork = remainingExpirationTime;
20272 highestPriorityRoot = root;
20273 }
20274 if (root === lastScheduledRoot) {
20275 break;
20276 }
20277 if (highestPriorityWork === Sync) {
20278 // Sync is highest priority by definition so
20279 // we can stop searching.
20280 break;
20281 }
20282 previousScheduledRoot = root;
20283 root = root.nextScheduledRoot;
20284 }
20285 }
20286 }
20287
20288 nextFlushedRoot = highestPriorityRoot;
20289 nextFlushedExpirationTime = highestPriorityWork;
20290}
20291
20292// TODO: This wrapper exists because many of the older tests (the ones that use
20293// flushDeferredPri) rely on the number of times `shouldYield` is called. We
20294// should get rid of it.
20295var didYield = false;
20296function shouldYieldToRenderer() {
20297 if (didYield) {
20298 return true;
20299 }
20300 if (unstable_shouldYield()) {
20301 didYield = true;
20302 return true;
20303 }
20304 return false;
20305}
20306
20307function performAsyncWork() {
20308 try {
20309 if (!shouldYieldToRenderer()) {
20310 // The callback timed out. That means at least one update has expired.
20311 // Iterate through the root schedule. If they contain expired work, set
20312 // the next render expiration time to the current time. This has the effect
20313 // of flushing all expired work in a single batch, instead of flushing each
20314 // level one at a time.
20315 if (firstScheduledRoot !== null) {
20316 recomputeCurrentRendererTime();
20317 var root = firstScheduledRoot;
20318 do {
20319 didExpireAtExpirationTime(root, currentRendererTime);
20320 // The root schedule is circular, so this is never null.
20321 root = root.nextScheduledRoot;
20322 } while (root !== firstScheduledRoot);
20323 }
20324 }
20325 performWork(NoWork, true);
20326 } finally {
20327 didYield = false;
20328 }
20329}
20330
20331function performSyncWork() {
20332 performWork(Sync, false);
20333}
20334
20335function performWork(minExpirationTime, isYieldy) {
20336 // Keep working on roots until there's no more work, or until there's a higher
20337 // priority event.
20338 findHighestPriorityRoot();
20339
20340 if (isYieldy) {
20341 recomputeCurrentRendererTime();
20342 currentSchedulerTime = currentRendererTime;
20343
20344 if (enableUserTimingAPI) {
20345 var didExpire = nextFlushedExpirationTime > currentRendererTime;
20346 var timeout = expirationTimeToMs(nextFlushedExpirationTime);
20347 stopRequestCallbackTimer(didExpire, timeout);
20348 }
20349
20350 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime && !(didYield && currentRendererTime > nextFlushedExpirationTime)) {
20351 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, currentRendererTime > nextFlushedExpirationTime);
20352 findHighestPriorityRoot();
20353 recomputeCurrentRendererTime();
20354 currentSchedulerTime = currentRendererTime;
20355 }
20356 } else {
20357 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime) {
20358 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false);
20359 findHighestPriorityRoot();
20360 }
20361 }
20362
20363 // We're done flushing work. Either we ran out of time in this callback,
20364 // or there's no more work left with sufficient priority.
20365
20366 // If we're inside a callback, set this to false since we just completed it.
20367 if (isYieldy) {
20368 callbackExpirationTime = NoWork;
20369 callbackID = null;
20370 }
20371 // If there's work left over, schedule a new callback.
20372 if (nextFlushedExpirationTime !== NoWork) {
20373 scheduleCallbackWithExpirationTime(nextFlushedRoot, nextFlushedExpirationTime);
20374 }
20375
20376 // Clean-up.
20377 finishRendering();
20378}
20379
20380function flushRoot(root, expirationTime) {
20381 !!isRendering ? invariant(false, 'work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.') : void 0;
20382 // Perform work on root as if the given expiration time is the current time.
20383 // This has the effect of synchronously flushing all work up to and
20384 // including the given time.
20385 nextFlushedRoot = root;
20386 nextFlushedExpirationTime = expirationTime;
20387 performWorkOnRoot(root, expirationTime, false);
20388 // Flush any sync work that was scheduled by lifecycles
20389 performSyncWork();
20390}
20391
20392function finishRendering() {
20393 nestedUpdateCount = 0;
20394 lastCommittedRootDuringThisBatch = null;
20395
20396 if (completedBatches !== null) {
20397 var batches = completedBatches;
20398 completedBatches = null;
20399 for (var i = 0; i < batches.length; i++) {
20400 var batch = batches[i];
20401 try {
20402 batch._onComplete();
20403 } catch (error) {
20404 if (!hasUnhandledError) {
20405 hasUnhandledError = true;
20406 unhandledError = error;
20407 }
20408 }
20409 }
20410 }
20411
20412 if (hasUnhandledError) {
20413 var error = unhandledError;
20414 unhandledError = null;
20415 hasUnhandledError = false;
20416 throw error;
20417 }
20418}
20419
20420function performWorkOnRoot(root, expirationTime, isYieldy) {
20421 !!isRendering ? invariant(false, 'performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;
20422
20423 isRendering = true;
20424
20425 // Check if this is async work or sync/expired work.
20426 if (!isYieldy) {
20427 // Flush work without yielding.
20428 // TODO: Non-yieldy work does not necessarily imply expired work. A renderer
20429 // may want to perform some work without yielding, but also without
20430 // requiring the root to complete (by triggering placeholders).
20431
20432 var finishedWork = root.finishedWork;
20433 if (finishedWork !== null) {
20434 // This root is already complete. We can commit it.
20435 completeRoot(root, finishedWork, expirationTime);
20436 } else {
20437 root.finishedWork = null;
20438 // If this root previously suspended, clear its existing timeout, since
20439 // we're about to try rendering again.
20440 var timeoutHandle = root.timeoutHandle;
20441 if (timeoutHandle !== noTimeout) {
20442 root.timeoutHandle = noTimeout;
20443 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
20444 cancelTimeout(timeoutHandle);
20445 }
20446 renderRoot(root, isYieldy);
20447 finishedWork = root.finishedWork;
20448 if (finishedWork !== null) {
20449 // We've completed the root. Commit it.
20450 completeRoot(root, finishedWork, expirationTime);
20451 }
20452 }
20453 } else {
20454 // Flush async work.
20455 var _finishedWork = root.finishedWork;
20456 if (_finishedWork !== null) {
20457 // This root is already complete. We can commit it.
20458 completeRoot(root, _finishedWork, expirationTime);
20459 } else {
20460 root.finishedWork = null;
20461 // If this root previously suspended, clear its existing timeout, since
20462 // we're about to try rendering again.
20463 var _timeoutHandle = root.timeoutHandle;
20464 if (_timeoutHandle !== noTimeout) {
20465 root.timeoutHandle = noTimeout;
20466 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
20467 cancelTimeout(_timeoutHandle);
20468 }
20469 renderRoot(root, isYieldy);
20470 _finishedWork = root.finishedWork;
20471 if (_finishedWork !== null) {
20472 // We've completed the root. Check the if we should yield one more time
20473 // before committing.
20474 if (!shouldYieldToRenderer()) {
20475 // Still time left. Commit the root.
20476 completeRoot(root, _finishedWork, expirationTime);
20477 } else {
20478 // There's no time left. Mark this root as complete. We'll come
20479 // back and commit it later.
20480 root.finishedWork = _finishedWork;
20481 }
20482 }
20483 }
20484 }
20485
20486 isRendering = false;
20487}
20488
20489function completeRoot(root, finishedWork, expirationTime) {
20490 // Check if there's a batch that matches this expiration time.
20491 var firstBatch = root.firstBatch;
20492 if (firstBatch !== null && firstBatch._expirationTime >= expirationTime) {
20493 if (completedBatches === null) {
20494 completedBatches = [firstBatch];
20495 } else {
20496 completedBatches.push(firstBatch);
20497 }
20498 if (firstBatch._defer) {
20499 // This root is blocked from committing by a batch. Unschedule it until
20500 // we receive another update.
20501 root.finishedWork = finishedWork;
20502 root.expirationTime = NoWork;
20503 return;
20504 }
20505 }
20506
20507 // Commit the root.
20508 root.finishedWork = null;
20509
20510 // Check if this is a nested update (a sync update scheduled during the
20511 // commit phase).
20512 if (root === lastCommittedRootDuringThisBatch) {
20513 // If the next root is the same as the previous root, this is a nested
20514 // update. To prevent an infinite loop, increment the nested update count.
20515 nestedUpdateCount++;
20516 } else {
20517 // Reset whenever we switch roots.
20518 lastCommittedRootDuringThisBatch = root;
20519 nestedUpdateCount = 0;
20520 }
20521 unstable_runWithPriority(unstable_ImmediatePriority, function () {
20522 commitRoot(root, finishedWork);
20523 });
20524}
20525
20526function onUncaughtError(error) {
20527 !(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;
20528 // Unschedule this root so we don't work on it again until there's
20529 // another update.
20530 nextFlushedRoot.expirationTime = NoWork;
20531 if (!hasUnhandledError) {
20532 hasUnhandledError = true;
20533 unhandledError = error;
20534 }
20535}
20536
20537// TODO: Batching should be implemented at the renderer level, not inside
20538// the reconciler.
20539function batchedUpdates$1(fn, a) {
20540 var previousIsBatchingUpdates = isBatchingUpdates;
20541 isBatchingUpdates = true;
20542 try {
20543 return fn(a);
20544 } finally {
20545 isBatchingUpdates = previousIsBatchingUpdates;
20546 if (!isBatchingUpdates && !isRendering) {
20547 performSyncWork();
20548 }
20549 }
20550}
20551
20552// TODO: Batching should be implemented at the renderer level, not inside
20553// the reconciler.
20554function unbatchedUpdates(fn, a) {
20555 if (isBatchingUpdates && !isUnbatchingUpdates) {
20556 isUnbatchingUpdates = true;
20557 try {
20558 return fn(a);
20559 } finally {
20560 isUnbatchingUpdates = false;
20561 }
20562 }
20563 return fn(a);
20564}
20565
20566// TODO: Batching should be implemented at the renderer level, not within
20567// the reconciler.
20568function flushSync(fn, a) {
20569 !!isRendering ? invariant(false, 'flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.') : void 0;
20570 var previousIsBatchingUpdates = isBatchingUpdates;
20571 isBatchingUpdates = true;
20572 try {
20573 return syncUpdates(fn, a);
20574 } finally {
20575 isBatchingUpdates = previousIsBatchingUpdates;
20576 performSyncWork();
20577 }
20578}
20579
20580function interactiveUpdates$1(fn, a, b) {
20581 // If there are any pending interactive updates, synchronously flush them.
20582 // This needs to happen before we read any handlers, because the effect of
20583 // the previous event may influence which handlers are called during
20584 // this event.
20585 if (!isBatchingUpdates && !isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) {
20586 // Synchronously flush pending interactive updates.
20587 performWork(lowestPriorityPendingInteractiveExpirationTime, false);
20588 lowestPriorityPendingInteractiveExpirationTime = NoWork;
20589 }
20590 var previousIsBatchingUpdates = isBatchingUpdates;
20591 isBatchingUpdates = true;
20592 try {
20593 return unstable_runWithPriority(unstable_UserBlockingPriority, function () {
20594 return fn(a, b);
20595 });
20596 } finally {
20597 isBatchingUpdates = previousIsBatchingUpdates;
20598 if (!isBatchingUpdates && !isRendering) {
20599 performSyncWork();
20600 }
20601 }
20602}
20603
20604function flushInteractiveUpdates$1() {
20605 if (!isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) {
20606 // Synchronously flush pending interactive updates.
20607 performWork(lowestPriorityPendingInteractiveExpirationTime, false);
20608 lowestPriorityPendingInteractiveExpirationTime = NoWork;
20609 }
20610}
20611
20612function flushControlled(fn) {
20613 var previousIsBatchingUpdates = isBatchingUpdates;
20614 isBatchingUpdates = true;
20615 try {
20616 syncUpdates(fn);
20617 } finally {
20618 isBatchingUpdates = previousIsBatchingUpdates;
20619 if (!isBatchingUpdates && !isRendering) {
20620 performSyncWork();
20621 }
20622 }
20623}
20624
20625// 0 is PROD, 1 is DEV.
20626// Might add PROFILE later.
20627
20628
20629var didWarnAboutNestedUpdates = void 0;
20630var didWarnAboutFindNodeInStrictMode = void 0;
20631
20632{
20633 didWarnAboutNestedUpdates = false;
20634 didWarnAboutFindNodeInStrictMode = {};
20635}
20636
20637function getContextForSubtree(parentComponent) {
20638 if (!parentComponent) {
20639 return emptyContextObject;
20640 }
20641
20642 var fiber = get(parentComponent);
20643 var parentContext = findCurrentUnmaskedContext(fiber);
20644
20645 if (fiber.tag === ClassComponent) {
20646 var Component = fiber.type;
20647 if (isContextProvider(Component)) {
20648 return processChildContext(fiber, Component, parentContext);
20649 }
20650 }
20651
20652 return parentContext;
20653}
20654
20655function scheduleRootUpdate(current$$1, element, expirationTime, callback) {
20656 {
20657 if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) {
20658 didWarnAboutNestedUpdates = true;
20659 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');
20660 }
20661 }
20662
20663 var update = createUpdate(expirationTime);
20664 // Caution: React DevTools currently depends on this property
20665 // being called "element".
20666 update.payload = { element: element };
20667
20668 callback = callback === undefined ? null : callback;
20669 if (callback !== null) {
20670 !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
20671 update.callback = callback;
20672 }
20673
20674 flushPassiveEffects();
20675 enqueueUpdate(current$$1, update);
20676 scheduleWork(current$$1, expirationTime);
20677
20678 return expirationTime;
20679}
20680
20681function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback) {
20682 // TODO: If this is a nested container, this won't be the root.
20683 var current$$1 = container.current;
20684
20685 {
20686 if (ReactFiberInstrumentation_1.debugTool) {
20687 if (current$$1.alternate === null) {
20688 ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
20689 } else if (element === null) {
20690 ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
20691 } else {
20692 ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
20693 }
20694 }
20695 }
20696
20697 var context = getContextForSubtree(parentComponent);
20698 if (container.context === null) {
20699 container.context = context;
20700 } else {
20701 container.pendingContext = context;
20702 }
20703
20704 return scheduleRootUpdate(current$$1, element, expirationTime, callback);
20705}
20706
20707function findHostInstance(component) {
20708 var fiber = get(component);
20709 if (fiber === undefined) {
20710 if (typeof component.render === 'function') {
20711 invariant(false, 'Unable to find node on an unmounted component.');
20712 } else {
20713 invariant(false, 'Argument appears to not be a ReactComponent. Keys: %s', Object.keys(component));
20714 }
20715 }
20716 var hostFiber = findCurrentHostFiber(fiber);
20717 if (hostFiber === null) {
20718 return null;
20719 }
20720 return hostFiber.stateNode;
20721}
20722
20723function findHostInstanceWithWarning(component, methodName) {
20724 {
20725 var fiber = get(component);
20726 if (fiber === undefined) {
20727 if (typeof component.render === 'function') {
20728 invariant(false, 'Unable to find node on an unmounted component.');
20729 } else {
20730 invariant(false, 'Argument appears to not be a ReactComponent. Keys: %s', Object.keys(component));
20731 }
20732 }
20733 var hostFiber = findCurrentHostFiber(fiber);
20734 if (hostFiber === null) {
20735 return null;
20736 }
20737 if (hostFiber.mode & StrictMode) {
20738 var componentName = getComponentName(fiber.type) || 'Component';
20739 if (!didWarnAboutFindNodeInStrictMode[componentName]) {
20740 didWarnAboutFindNodeInStrictMode[componentName] = true;
20741 if (fiber.mode & StrictMode) {
20742 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));
20743 } else {
20744 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));
20745 }
20746 }
20747 }
20748 return hostFiber.stateNode;
20749 }
20750 return findHostInstance(component);
20751}
20752
20753function createContainer(containerInfo, isConcurrent, hydrate) {
20754 return createFiberRoot(containerInfo, isConcurrent, hydrate);
20755}
20756
20757function updateContainer(element, container, parentComponent, callback) {
20758 var current$$1 = container.current;
20759 var currentTime = requestCurrentTime();
20760 var expirationTime = computeExpirationForFiber(currentTime, current$$1);
20761 return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback);
20762}
20763
20764function getPublicRootInstance(container) {
20765 var containerFiber = container.current;
20766 if (!containerFiber.child) {
20767 return null;
20768 }
20769 switch (containerFiber.child.tag) {
20770 case HostComponent:
20771 return getPublicInstance(containerFiber.child.stateNode);
20772 default:
20773 return containerFiber.child.stateNode;
20774 }
20775}
20776
20777function findHostInstanceWithNoPortals(fiber) {
20778 var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
20779 if (hostFiber === null) {
20780 return null;
20781 }
20782 return hostFiber.stateNode;
20783}
20784
20785var overrideProps = null;
20786
20787{
20788 var copyWithSetImpl = function (obj, path, idx, value) {
20789 if (idx >= path.length) {
20790 return value;
20791 }
20792 var key = path[idx];
20793 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
20794 // $FlowFixMe number or string is fine here
20795 updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
20796 return updated;
20797 };
20798
20799 var copyWithSet = function (obj, path, value) {
20800 return copyWithSetImpl(obj, path, 0, value);
20801 };
20802
20803 // Support DevTools props for function components, forwardRef, memo, host components, etc.
20804 overrideProps = function (fiber, path, value) {
20805 flushPassiveEffects();
20806 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
20807 if (fiber.alternate) {
20808 fiber.alternate.pendingProps = fiber.pendingProps;
20809 }
20810 scheduleWork(fiber, Sync);
20811 };
20812}
20813
20814function injectIntoDevTools(devToolsConfig) {
20815 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
20816 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
20817
20818
20819 return injectInternals(_assign({}, devToolsConfig, {
20820 overrideProps: overrideProps,
20821 currentDispatcherRef: ReactCurrentDispatcher,
20822 findHostInstanceByFiber: function (fiber) {
20823 var hostFiber = findCurrentHostFiber(fiber);
20824 if (hostFiber === null) {
20825 return null;
20826 }
20827 return hostFiber.stateNode;
20828 },
20829 findFiberByHostInstance: function (instance) {
20830 if (!findFiberByHostInstance) {
20831 // Might not be implemented by the renderer.
20832 return null;
20833 }
20834 return findFiberByHostInstance(instance);
20835 }
20836 }));
20837}
20838
20839// This file intentionally does *not* have the Flow annotation.
20840// Don't add it. See `./inline-typed.js` for an explanation.
20841
20842function createPortal$1(children, containerInfo,
20843// TODO: figure out the API for cross-renderer implementation.
20844implementation) {
20845 var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
20846
20847 return {
20848 // This tag allow us to uniquely identify this as a React Portal
20849 $$typeof: REACT_PORTAL_TYPE,
20850 key: key == null ? null : '' + key,
20851 children: children,
20852 containerInfo: containerInfo,
20853 implementation: implementation
20854 };
20855}
20856
20857// TODO: this is special because it gets imported during build.
20858
20859var ReactVersion = '16.8.5';
20860
20861// This file is copy paste from ReactDOM with adjusted paths
20862// and a different host config import (react-reconciler/inline.fire).
20863// TODO: real implementation.
20864// console.log('Hello from Fire entry point.');
20865
20866// TODO: This type is shared between the reconciler and ReactDOM, but will
20867// eventually be lifted out to the renderer.
20868
20869var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
20870
20871var topLevelUpdateWarnings = void 0;
20872var warnOnInvalidCallback = void 0;
20873var didWarnAboutUnstableCreatePortal = false;
20874
20875{
20876 if (typeof Map !== 'function' ||
20877 // $FlowIssue Flow incorrectly thinks Map has no prototype
20878 Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' ||
20879 // $FlowIssue Flow incorrectly thinks Set has no prototype
20880 Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
20881 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');
20882 }
20883
20884 topLevelUpdateWarnings = function (container) {
20885 if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
20886 var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
20887 if (hostInstance) {
20888 !(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;
20889 }
20890 }
20891
20892 var isRootRenderedBySomeReact = !!container._reactRootContainer;
20893 var rootEl = getReactRootElementInContainer(container);
20894 var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));
20895
20896 !(!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;
20897
20898 !(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;
20899 };
20900
20901 warnOnInvalidCallback = function (callback, callerName) {
20902 !(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;
20903 };
20904}
20905
20906setRestoreImplementation(restoreControlledState$1);
20907
20908function ReactBatch(root) {
20909 var expirationTime = computeUniqueAsyncExpiration();
20910 this._expirationTime = expirationTime;
20911 this._root = root;
20912 this._next = null;
20913 this._callbacks = null;
20914 this._didComplete = false;
20915 this._hasChildren = false;
20916 this._children = null;
20917 this._defer = true;
20918}
20919ReactBatch.prototype.render = function (children) {
20920 !this._defer ? invariant(false, 'batch.render: Cannot render a batch that already committed.') : void 0;
20921 this._hasChildren = true;
20922 this._children = children;
20923 var internalRoot = this._root._internalRoot;
20924 var expirationTime = this._expirationTime;
20925 var work = new ReactWork();
20926 updateContainerAtExpirationTime(children, internalRoot, null, expirationTime, work._onCommit);
20927 return work;
20928};
20929ReactBatch.prototype.then = function (onComplete) {
20930 if (this._didComplete) {
20931 onComplete();
20932 return;
20933 }
20934 var callbacks = this._callbacks;
20935 if (callbacks === null) {
20936 callbacks = this._callbacks = [];
20937 }
20938 callbacks.push(onComplete);
20939};
20940ReactBatch.prototype.commit = function () {
20941 var internalRoot = this._root._internalRoot;
20942 var firstBatch = internalRoot.firstBatch;
20943 !(this._defer && firstBatch !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0;
20944
20945 if (!this._hasChildren) {
20946 // This batch is empty. Return.
20947 this._next = null;
20948 this._defer = false;
20949 return;
20950 }
20951
20952 var expirationTime = this._expirationTime;
20953
20954 // Ensure this is the first batch in the list.
20955 if (firstBatch !== this) {
20956 // This batch is not the earliest batch. We need to move it to the front.
20957 // Update its expiration time to be the expiration time of the earliest
20958 // batch, so that we can flush it without flushing the other batches.
20959 if (this._hasChildren) {
20960 expirationTime = this._expirationTime = firstBatch._expirationTime;
20961 // Rendering this batch again ensures its children will be the final state
20962 // when we flush (updates are processed in insertion order: last
20963 // update wins).
20964 // TODO: This forces a restart. Should we print a warning?
20965 this.render(this._children);
20966 }
20967
20968 // Remove the batch from the list.
20969 var previous = null;
20970 var batch = firstBatch;
20971 while (batch !== this) {
20972 previous = batch;
20973 batch = batch._next;
20974 }
20975 !(previous !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0;
20976 previous._next = batch._next;
20977
20978 // Add it to the front.
20979 this._next = firstBatch;
20980 firstBatch = internalRoot.firstBatch = this;
20981 }
20982
20983 // Synchronously flush all the work up to this batch's expiration time.
20984 this._defer = false;
20985 flushRoot(internalRoot, expirationTime);
20986
20987 // Pop the batch from the list.
20988 var next = this._next;
20989 this._next = null;
20990 firstBatch = internalRoot.firstBatch = next;
20991
20992 // Append the next earliest batch's children to the update queue.
20993 if (firstBatch !== null && firstBatch._hasChildren) {
20994 firstBatch.render(firstBatch._children);
20995 }
20996};
20997ReactBatch.prototype._onComplete = function () {
20998 if (this._didComplete) {
20999 return;
21000 }
21001 this._didComplete = true;
21002 var callbacks = this._callbacks;
21003 if (callbacks === null) {
21004 return;
21005 }
21006 // TODO: Error handling.
21007 for (var i = 0; i < callbacks.length; i++) {
21008 var _callback = callbacks[i];
21009 _callback();
21010 }
21011};
21012
21013function ReactWork() {
21014 this._callbacks = null;
21015 this._didCommit = false;
21016 // TODO: Avoid need to bind by replacing callbacks in the update queue with
21017 // list of Work objects.
21018 this._onCommit = this._onCommit.bind(this);
21019}
21020ReactWork.prototype.then = function (onCommit) {
21021 if (this._didCommit) {
21022 onCommit();
21023 return;
21024 }
21025 var callbacks = this._callbacks;
21026 if (callbacks === null) {
21027 callbacks = this._callbacks = [];
21028 }
21029 callbacks.push(onCommit);
21030};
21031ReactWork.prototype._onCommit = function () {
21032 if (this._didCommit) {
21033 return;
21034 }
21035 this._didCommit = true;
21036 var callbacks = this._callbacks;
21037 if (callbacks === null) {
21038 return;
21039 }
21040 // TODO: Error handling.
21041 for (var i = 0; i < callbacks.length; i++) {
21042 var _callback2 = callbacks[i];
21043 !(typeof _callback2 === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', _callback2) : void 0;
21044 _callback2();
21045 }
21046};
21047
21048function ReactRoot(container, isConcurrent, hydrate) {
21049 var root = createContainer(container, isConcurrent, hydrate);
21050 this._internalRoot = root;
21051}
21052ReactRoot.prototype.render = function (children, callback) {
21053 var root = this._internalRoot;
21054 var work = new ReactWork();
21055 callback = callback === undefined ? null : callback;
21056 {
21057 warnOnInvalidCallback(callback, 'render');
21058 }
21059 if (callback !== null) {
21060 work.then(callback);
21061 }
21062 updateContainer(children, root, null, work._onCommit);
21063 return work;
21064};
21065ReactRoot.prototype.unmount = function (callback) {
21066 var root = this._internalRoot;
21067 var work = new ReactWork();
21068 callback = callback === undefined ? null : callback;
21069 {
21070 warnOnInvalidCallback(callback, 'render');
21071 }
21072 if (callback !== null) {
21073 work.then(callback);
21074 }
21075 updateContainer(null, root, null, work._onCommit);
21076 return work;
21077};
21078ReactRoot.prototype.legacy_renderSubtreeIntoContainer = function (parentComponent, children, callback) {
21079 var root = this._internalRoot;
21080 var work = new ReactWork();
21081 callback = callback === undefined ? null : callback;
21082 {
21083 warnOnInvalidCallback(callback, 'render');
21084 }
21085 if (callback !== null) {
21086 work.then(callback);
21087 }
21088 updateContainer(children, root, parentComponent, work._onCommit);
21089 return work;
21090};
21091ReactRoot.prototype.createBatch = function () {
21092 var batch = new ReactBatch(this);
21093 var expirationTime = batch._expirationTime;
21094
21095 var internalRoot = this._internalRoot;
21096 var firstBatch = internalRoot.firstBatch;
21097 if (firstBatch === null) {
21098 internalRoot.firstBatch = batch;
21099 batch._next = null;
21100 } else {
21101 // Insert sorted by expiration time then insertion order
21102 var insertAfter = null;
21103 var insertBefore = firstBatch;
21104 while (insertBefore !== null && insertBefore._expirationTime >= expirationTime) {
21105 insertAfter = insertBefore;
21106 insertBefore = insertBefore._next;
21107 }
21108 batch._next = insertBefore;
21109 if (insertAfter !== null) {
21110 insertAfter._next = batch;
21111 }
21112 }
21113
21114 return batch;
21115};
21116
21117/**
21118 * True if the supplied DOM node is a valid node element.
21119 *
21120 * @param {?DOMElement} node The candidate DOM node.
21121 * @return {boolean} True if the DOM is a valid DOM node.
21122 * @internal
21123 */
21124function isValidContainer(node) {
21125 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 '));
21126}
21127
21128function getReactRootElementInContainer(container) {
21129 if (!container) {
21130 return null;
21131 }
21132
21133 if (container.nodeType === DOCUMENT_NODE) {
21134 return container.documentElement;
21135 } else {
21136 return container.firstChild;
21137 }
21138}
21139
21140function shouldHydrateDueToLegacyHeuristic(container) {
21141 var rootElement = getReactRootElementInContainer(container);
21142 return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
21143}
21144
21145setBatchingImplementation(batchedUpdates$1, interactiveUpdates$1, flushInteractiveUpdates$1);
21146
21147var warnedAboutHydrateAPI = false;
21148
21149function legacyCreateRootFromDOMContainer(container, forceHydrate) {
21150 var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container);
21151 // First clear any existing content.
21152 if (!shouldHydrate) {
21153 var warned = false;
21154 var rootSibling = void 0;
21155 while (rootSibling = container.lastChild) {
21156 {
21157 if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
21158 warned = true;
21159 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.');
21160 }
21161 }
21162 container.removeChild(rootSibling);
21163 }
21164 }
21165 {
21166 if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
21167 warnedAboutHydrateAPI = true;
21168 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.');
21169 }
21170 }
21171 // Legacy roots are not async by default.
21172 var isConcurrent = false;
21173 return new ReactRoot(container, isConcurrent, shouldHydrate);
21174}
21175
21176function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
21177 {
21178 topLevelUpdateWarnings(container);
21179 }
21180
21181 // TODO: Without `any` type, Flow says "Property cannot be accessed on any
21182 // member of intersection type." Whyyyyyy.
21183 var root = container._reactRootContainer;
21184 if (!root) {
21185 // Initial mount
21186 root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
21187 if (typeof callback === 'function') {
21188 var originalCallback = callback;
21189 callback = function () {
21190 var instance = getPublicRootInstance(root._internalRoot);
21191 originalCallback.call(instance);
21192 };
21193 }
21194 // Initial mount should not be batched.
21195 unbatchedUpdates(function () {
21196 if (parentComponent != null) {
21197 root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
21198 } else {
21199 root.render(children, callback);
21200 }
21201 });
21202 } else {
21203 if (typeof callback === 'function') {
21204 var _originalCallback = callback;
21205 callback = function () {
21206 var instance = getPublicRootInstance(root._internalRoot);
21207 _originalCallback.call(instance);
21208 };
21209 }
21210 // Update
21211 if (parentComponent != null) {
21212 root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
21213 } else {
21214 root.render(children, callback);
21215 }
21216 }
21217 return getPublicRootInstance(root._internalRoot);
21218}
21219
21220function createPortal$$1(children, container) {
21221 var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
21222
21223 !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;
21224 // TODO: pass ReactDOM portal implementation as third argument
21225 return createPortal$1(children, container, null, key);
21226}
21227
21228var ReactDOM = {
21229 createPortal: createPortal$$1,
21230
21231 findDOMNode: function (componentOrElement) {
21232 {
21233 var owner = ReactCurrentOwner.current;
21234 if (owner !== null && owner.stateNode !== null) {
21235 var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
21236 !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;
21237 owner.stateNode._warnedAboutRefsInRender = true;
21238 }
21239 }
21240 if (componentOrElement == null) {
21241 return null;
21242 }
21243 if (componentOrElement.nodeType === ELEMENT_NODE) {
21244 return componentOrElement;
21245 }
21246 {
21247 return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
21248 }
21249 return findHostInstance(componentOrElement);
21250 },
21251 hydrate: function (element, container, callback) {
21252 !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;
21253 {
21254 !!container._reactHasBeenPassedToCreateRootDEV ? warningWithoutStack$1(false, 'You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOM.%s(). This is not supported. ' + 'Did you mean to call createRoot(container, {hydrate: true}).render(element)?', enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot') : void 0;
21255 }
21256 // TODO: throw or warn if we couldn't hydrate?
21257 return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
21258 },
21259 render: function (element, container, callback) {
21260 !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;
21261 {
21262 !!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;
21263 }
21264 return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
21265 },
21266 unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) {
21267 !isValidContainer(containerNode) ? invariant(false, 'Target container is not a DOM element.') : void 0;
21268 !(parentComponent != null && has(parentComponent)) ? invariant(false, 'parentComponent must be a valid React Component') : void 0;
21269 return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
21270 },
21271 unmountComponentAtNode: function (container) {
21272 !isValidContainer(container) ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : void 0;
21273
21274 {
21275 !!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;
21276 }
21277
21278 if (container._reactRootContainer) {
21279 {
21280 var rootEl = getReactRootElementInContainer(container);
21281 var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);
21282 !!renderedByDifferentReact ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0;
21283 }
21284
21285 // Unmount should not be batched.
21286 unbatchedUpdates(function () {
21287 legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
21288 container._reactRootContainer = null;
21289 });
21290 });
21291 // If you call unmountComponentAtNode twice in quick succession, you'll
21292 // get `true` twice. That's probably fine?
21293 return true;
21294 } else {
21295 {
21296 var _rootEl = getReactRootElementInContainer(container);
21297 var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl));
21298
21299 // Check if the container itself is a React root node.
21300 var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;
21301
21302 !!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;
21303 }
21304
21305 return false;
21306 }
21307 },
21308
21309
21310 // Temporary alias since we already shipped React 16 RC with it.
21311 // TODO: remove in React 17.
21312 unstable_createPortal: function () {
21313 if (!didWarnAboutUnstableCreatePortal) {
21314 didWarnAboutUnstableCreatePortal = true;
21315 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.');
21316 }
21317 return createPortal$$1.apply(undefined, arguments);
21318 },
21319
21320
21321 unstable_batchedUpdates: batchedUpdates$1,
21322
21323 unstable_interactiveUpdates: interactiveUpdates$1,
21324
21325 flushSync: flushSync,
21326
21327 unstable_createRoot: createRoot,
21328 unstable_flushControlled: flushControlled,
21329
21330 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
21331 // Keep in sync with ReactDOMUnstableNativeDependencies.js
21332 // and ReactTestUtils.js. This is an array for better minification.
21333 Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injection.injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch]
21334 }
21335};
21336
21337function createRoot(container, options) {
21338 var functionName = enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot';
21339 !isValidContainer(container) ? invariant(false, '%s(...): Target container is not a DOM element.', functionName) : void 0;
21340 {
21341 !!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;
21342 container._reactHasBeenPassedToCreateRootDEV = true;
21343 }
21344 var hydrate = options != null && options.hydrate === true;
21345 return new ReactRoot(container, true, hydrate);
21346}
21347
21348if (enableStableConcurrentModeAPIs) {
21349 ReactDOM.createRoot = createRoot;
21350 ReactDOM.unstable_createRoot = undefined;
21351}
21352
21353var foundDevTools = injectIntoDevTools({
21354 findFiberByHostInstance: getClosestInstanceFromNode,
21355 bundleType: 1,
21356 version: ReactVersion,
21357 rendererPackageName: 'react-dom'
21358});
21359
21360{
21361 if (!foundDevTools && canUseDOM && window.top === window.self) {
21362 // If we're in Chrome or Firefox, provide a download link if not installed.
21363 if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
21364 var protocol = window.location.protocol;
21365 // Don't warn in exotic cases like chrome-extension://.
21366 if (/^(https?|file):$/.test(protocol)) {
21367 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');
21368 }
21369 }
21370 }
21371}
21372
21373
21374
21375var ReactFire = Object.freeze({
21376 default: ReactDOM
21377});
21378
21379var ReactFire$1 = ( ReactFire && ReactDOM ) || ReactFire;
21380
21381// TODO: decide on the top-level export form.
21382// This is hacky but makes it work with both Rollup and Jest.
21383var unstableFire = ReactFire$1.default || ReactFire$1;
21384
21385return unstableFire;
21386
21387})));