UNPKG

792 kBJavaScriptView Raw
1/** @license React v16.8.6
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 isSameOriginFrame(iframe) {
5439 try {
5440 // Accessing the contentDocument of a HTMLIframeElement can cause the browser
5441 // to throw, e.g. if it has a cross-origin src attribute.
5442 // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
5443 // iframe.contentDocument.defaultView;
5444 // A safety way is to access one of the cross origin properties: Window or Location
5445 // Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
5446 // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
5447
5448 return typeof iframe.contentWindow.location.href === 'string';
5449 } catch (err) {
5450 return false;
5451 }
5452}
5453
5454function getActiveElementDeep() {
5455 var win = window;
5456 var element = getActiveElement();
5457 while (element instanceof win.HTMLIFrameElement) {
5458 if (isSameOriginFrame(element)) {
5459 win = element.contentWindow;
5460 } else {
5461 return element;
5462 }
5463 element = getActiveElement(win.document);
5464 }
5465 return element;
5466}
5467
5468/**
5469 * @ReactInputSelection: React input selection module. Based on Selection.js,
5470 * but modified to be suitable for react and has a couple of bug fixes (doesn't
5471 * assume buttons have range selections allowed).
5472 * Input selection module for React.
5473 */
5474
5475/**
5476 * @hasSelectionCapabilities: we get the element types that support selection
5477 * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
5478 * and `selectionEnd` rows.
5479 */
5480function hasSelectionCapabilities(elem) {
5481 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
5482 return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
5483}
5484
5485function getSelectionInformation() {
5486 var focusedElem = getActiveElementDeep();
5487 return {
5488 focusedElem: focusedElem,
5489 selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection$1(focusedElem) : null
5490 };
5491}
5492
5493/**
5494 * @restoreSelection: If any selection information was potentially lost,
5495 * restore it. This is useful when performing operations that could remove dom
5496 * nodes and place them back in, resulting in focus being lost.
5497 */
5498function restoreSelection(priorSelectionInformation) {
5499 var curFocusedElem = getActiveElementDeep();
5500 var priorFocusedElem = priorSelectionInformation.focusedElem;
5501 var priorSelectionRange = priorSelectionInformation.selectionRange;
5502 if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
5503 if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
5504 setSelection(priorFocusedElem, priorSelectionRange);
5505 }
5506
5507 // Focusing a node can change the scroll position, which is undesirable
5508 var ancestors = [];
5509 var ancestor = priorFocusedElem;
5510 while (ancestor = ancestor.parentNode) {
5511 if (ancestor.nodeType === ELEMENT_NODE) {
5512 ancestors.push({
5513 element: ancestor,
5514 left: ancestor.scrollLeft,
5515 top: ancestor.scrollTop
5516 });
5517 }
5518 }
5519
5520 if (typeof priorFocusedElem.focus === 'function') {
5521 priorFocusedElem.focus();
5522 }
5523
5524 for (var i = 0; i < ancestors.length; i++) {
5525 var info = ancestors[i];
5526 info.element.scrollLeft = info.left;
5527 info.element.scrollTop = info.top;
5528 }
5529 }
5530}
5531
5532/**
5533 * @getSelection: Gets the selection bounds of a focused textarea, input or
5534 * contentEditable node.
5535 * -@input: Look up selection bounds of this input
5536 * -@return {start: selectionStart, end: selectionEnd}
5537 */
5538function getSelection$1(input) {
5539 var selection = void 0;
5540
5541 if ('selectionStart' in input) {
5542 // Modern browser with input or textarea.
5543 selection = {
5544 start: input.selectionStart,
5545 end: input.selectionEnd
5546 };
5547 } else {
5548 // Content editable or old IE textarea.
5549 selection = getOffsets(input);
5550 }
5551
5552 return selection || { start: 0, end: 0 };
5553}
5554
5555/**
5556 * @setSelection: Sets the selection bounds of a textarea or input and focuses
5557 * the input.
5558 * -@input Set selection bounds of this input or textarea
5559 * -@offsets Object of same form that is returned from get*
5560 */
5561function setSelection(input, offsets) {
5562 var start = offsets.start,
5563 end = offsets.end;
5564
5565 if (end === undefined) {
5566 end = start;
5567 }
5568
5569 if ('selectionStart' in input) {
5570 input.selectionStart = start;
5571 input.selectionEnd = Math.min(end, input.value.length);
5572 } else {
5573 setOffsets(input, offsets);
5574 }
5575}
5576
5577var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;
5578
5579var eventTypes$3 = {
5580 select: {
5581 phasedRegistrationNames: {
5582 bubbled: 'onSelect',
5583 captured: 'onSelectCapture'
5584 },
5585 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]
5586 }
5587};
5588
5589var activeElement$1 = null;
5590var activeElementInst$1 = null;
5591var lastSelection = null;
5592var mouseDown = false;
5593
5594/**
5595 * Get an object which is a unique representation of the current selection.
5596 *
5597 * The return value will not be consistent across nodes or browsers, but
5598 * two identical selections on the same node will return identical objects.
5599 *
5600 * @param {DOMElement} node
5601 * @return {object}
5602 */
5603function getSelection(node) {
5604 if ('selectionStart' in node && hasSelectionCapabilities(node)) {
5605 return {
5606 start: node.selectionStart,
5607 end: node.selectionEnd
5608 };
5609 } else {
5610 var win = node.ownerDocument && node.ownerDocument.defaultView || window;
5611 var selection = win.getSelection();
5612 return {
5613 anchorNode: selection.anchorNode,
5614 anchorOffset: selection.anchorOffset,
5615 focusNode: selection.focusNode,
5616 focusOffset: selection.focusOffset
5617 };
5618 }
5619}
5620
5621/**
5622 * Get document associated with the event target.
5623 *
5624 * @param {object} nativeEventTarget
5625 * @return {Document}
5626 */
5627function getEventTargetDocument(eventTarget) {
5628 return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
5629}
5630
5631/**
5632 * Poll selection to see whether it's changed.
5633 *
5634 * @param {object} nativeEvent
5635 * @param {object} nativeEventTarget
5636 * @return {?SyntheticEvent}
5637 */
5638function constructSelectEvent(nativeEvent, nativeEventTarget) {
5639 // Ensure we have the right element, and that the user is not dragging a
5640 // selection (this matches native `select` event behavior). In HTML5, select
5641 // fires only on input and textarea thus if there's no focused element we
5642 // won't dispatch.
5643 var doc = getEventTargetDocument(nativeEventTarget);
5644
5645 if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
5646 return null;
5647 }
5648
5649 // Only fire when selection has actually changed.
5650 var currentSelection = getSelection(activeElement$1);
5651 if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
5652 lastSelection = currentSelection;
5653
5654 var syntheticEvent = SyntheticEvent.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget);
5655
5656 syntheticEvent.type = 'select';
5657 syntheticEvent.target = activeElement$1;
5658
5659 accumulateTwoPhaseDispatches(syntheticEvent);
5660
5661 return syntheticEvent;
5662 }
5663
5664 return null;
5665}
5666
5667/**
5668 * This plugin creates an `onSelect` event that normalizes select events
5669 * across form elements.
5670 *
5671 * Supported elements are:
5672 * - input (see `isTextInputElement`)
5673 * - textarea
5674 * - contentEditable
5675 *
5676 * This differs from native browser implementations in the following ways:
5677 * - Fires on contentEditable fields as well as inputs.
5678 * - Fires for collapsed selection.
5679 * - Fires after user input.
5680 */
5681var SelectEventPlugin = {
5682 eventTypes: eventTypes$3,
5683
5684 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
5685 var doc = getEventTargetDocument(nativeEventTarget);
5686 // Track whether all listeners exists for this plugin. If none exist, we do
5687 // not extract events. See #3639.
5688 if (!doc || !isListeningToAllDependencies('onSelect', doc)) {
5689 return null;
5690 }
5691
5692 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
5693
5694 switch (topLevelType) {
5695 // Track the input node that has focus.
5696 case TOP_FOCUS:
5697 if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
5698 activeElement$1 = targetNode;
5699 activeElementInst$1 = targetInst;
5700 lastSelection = null;
5701 }
5702 break;
5703 case TOP_BLUR:
5704 activeElement$1 = null;
5705 activeElementInst$1 = null;
5706 lastSelection = null;
5707 break;
5708 // Don't fire the event while the user is dragging. This matches the
5709 // semantics of the native select event.
5710 case TOP_MOUSE_DOWN:
5711 mouseDown = true;
5712 break;
5713 case TOP_CONTEXT_MENU:
5714 case TOP_MOUSE_UP:
5715 case TOP_DRAG_END:
5716 mouseDown = false;
5717 return constructSelectEvent(nativeEvent, nativeEventTarget);
5718 // Chrome and IE fire non-standard event when selection is changed (and
5719 // sometimes when it hasn't). IE's event fires out of order with respect
5720 // to key and input events on deletion, so we discard it.
5721 //
5722 // Firefox doesn't support selectionchange, so check selection status
5723 // after each key entry. The selection changes after keydown and before
5724 // keyup, but we check on keydown as well in the case of holding down a
5725 // key, when multiple keydown events are fired but only one keyup is.
5726 // This is also our approach for IE handling, for the reason above.
5727 case TOP_SELECTION_CHANGE:
5728 if (skipSelectionChangeEvent) {
5729 break;
5730 }
5731 // falls through
5732 case TOP_KEY_DOWN:
5733 case TOP_KEY_UP:
5734 return constructSelectEvent(nativeEvent, nativeEventTarget);
5735 }
5736
5737 return null;
5738 }
5739};
5740
5741/**
5742 * Inject modules for resolving DOM hierarchy and plugin ordering.
5743 */
5744injection.injectEventPluginOrder(DOMEventPluginOrder);
5745setComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);
5746
5747/**
5748 * Some important event plugins included by default (without having to require
5749 * them).
5750 */
5751injection.injectEventPluginsByName({
5752 SimpleEventPlugin: SimpleEventPlugin,
5753 EnterLeaveEventPlugin: EnterLeaveEventPlugin,
5754 ChangeEventPlugin: ChangeEventPlugin,
5755 SelectEventPlugin: SelectEventPlugin,
5756 BeforeInputEventPlugin: BeforeInputEventPlugin
5757});
5758
5759var didWarnSelectedSetOnOption = false;
5760var didWarnInvalidChild = false;
5761
5762function flattenChildren(children) {
5763 var content = '';
5764
5765 // Flatten children. We'll warn if they are invalid
5766 // during validateProps() which runs for hydration too.
5767 // Note that this would throw on non-element objects.
5768 // Elements are stringified (which is normally irrelevant
5769 // but matters for <fbt>).
5770 React.Children.forEach(children, function (child) {
5771 if (child == null) {
5772 return;
5773 }
5774 content += child;
5775 // Note: we don't warn about invalid children here.
5776 // Instead, this is done separately below so that
5777 // it happens during the hydration codepath too.
5778 });
5779
5780 return content;
5781}
5782
5783/**
5784 * Implements an <option> host component that warns when `selected` is set.
5785 */
5786
5787function validateProps(element, props) {
5788 {
5789 // This mirrors the codepath above, but runs for hydration too.
5790 // Warn about invalid children here so that client and hydration are consistent.
5791 // TODO: this seems like it could cause a DEV-only throw for hydration
5792 // if children contains a non-element object. We should try to avoid that.
5793 if (typeof props.children === 'object' && props.children !== null) {
5794 React.Children.forEach(props.children, function (child) {
5795 if (child == null) {
5796 return;
5797 }
5798 if (typeof child === 'string' || typeof child === 'number') {
5799 return;
5800 }
5801 if (typeof child.type !== 'string') {
5802 return;
5803 }
5804 if (!didWarnInvalidChild) {
5805 didWarnInvalidChild = true;
5806 warning$1(false, 'Only strings and numbers are supported as <option> children.');
5807 }
5808 });
5809 }
5810
5811 // TODO: Remove support for `selected` in <option>.
5812 if (props.selected != null && !didWarnSelectedSetOnOption) {
5813 warning$1(false, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
5814 didWarnSelectedSetOnOption = true;
5815 }
5816 }
5817}
5818
5819function postMountWrapper$1(element, props) {
5820 // value="" should make a value attribute (#6219)
5821 if (props.value != null) {
5822 element.setAttribute('value', toString(getToStringValue(props.value)));
5823 }
5824}
5825
5826function getHostProps$1(element, props) {
5827 var hostProps = _assign({ children: undefined }, props);
5828 var content = flattenChildren(props.children);
5829
5830 if (content) {
5831 hostProps.children = content;
5832 }
5833
5834 return hostProps;
5835}
5836
5837// TODO: direct imports like some-package/src/* are bad. Fix me.
5838var didWarnValueDefaultValue$1 = void 0;
5839
5840{
5841 didWarnValueDefaultValue$1 = false;
5842}
5843
5844function getDeclarationErrorAddendum() {
5845 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
5846 if (ownerName) {
5847 return '\n\nCheck the render method of `' + ownerName + '`.';
5848 }
5849 return '';
5850}
5851
5852var valuePropNames = ['value', 'defaultValue'];
5853
5854/**
5855 * Validation function for `value` and `defaultValue`.
5856 */
5857function checkSelectPropTypes(props) {
5858 ReactControlledValuePropTypes.checkPropTypes('select', props);
5859
5860 for (var i = 0; i < valuePropNames.length; i++) {
5861 var propName = valuePropNames[i];
5862 if (props[propName] == null) {
5863 continue;
5864 }
5865 var isArray = Array.isArray(props[propName]);
5866 if (props.multiple && !isArray) {
5867 warning$1(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
5868 } else if (!props.multiple && isArray) {
5869 warning$1(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
5870 }
5871 }
5872}
5873
5874function updateOptions(node, multiple, propValue, setDefaultSelected) {
5875 var options = node.options;
5876
5877 if (multiple) {
5878 var selectedValues = propValue;
5879 var selectedValue = {};
5880 for (var i = 0; i < selectedValues.length; i++) {
5881 // Prefix to avoid chaos with special keys.
5882 selectedValue['$' + selectedValues[i]] = true;
5883 }
5884 for (var _i = 0; _i < options.length; _i++) {
5885 var selected = selectedValue.hasOwnProperty('$' + options[_i].value);
5886 if (options[_i].selected !== selected) {
5887 options[_i].selected = selected;
5888 }
5889 if (selected && setDefaultSelected) {
5890 options[_i].defaultSelected = true;
5891 }
5892 }
5893 } else {
5894 // Do not set `select.value` as exact behavior isn't consistent across all
5895 // browsers for all cases.
5896 var _selectedValue = toString(getToStringValue(propValue));
5897 var defaultSelected = null;
5898 for (var _i2 = 0; _i2 < options.length; _i2++) {
5899 if (options[_i2].value === _selectedValue) {
5900 options[_i2].selected = true;
5901 if (setDefaultSelected) {
5902 options[_i2].defaultSelected = true;
5903 }
5904 return;
5905 }
5906 if (defaultSelected === null && !options[_i2].disabled) {
5907 defaultSelected = options[_i2];
5908 }
5909 }
5910 if (defaultSelected !== null) {
5911 defaultSelected.selected = true;
5912 }
5913 }
5914}
5915
5916/**
5917 * Implements a <select> host component that allows optionally setting the
5918 * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
5919 * stringable. If `multiple` is true, the prop must be an array of stringables.
5920 *
5921 * If `value` is not supplied (or null/undefined), user actions that change the
5922 * selected option will trigger updates to the rendered options.
5923 *
5924 * If it is supplied (and not null/undefined), the rendered options will not
5925 * update in response to user actions. Instead, the `value` prop must change in
5926 * order for the rendered options to update.
5927 *
5928 * If `defaultValue` is provided, any options with the supplied values will be
5929 * selected.
5930 */
5931
5932function getHostProps$2(element, props) {
5933 return _assign({}, props, {
5934 value: undefined
5935 });
5936}
5937
5938function initWrapperState$1(element, props) {
5939 var node = element;
5940 {
5941 checkSelectPropTypes(props);
5942 }
5943
5944 node._wrapperState = {
5945 wasMultiple: !!props.multiple
5946 };
5947
5948 {
5949 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
5950 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');
5951 didWarnValueDefaultValue$1 = true;
5952 }
5953 }
5954}
5955
5956function postMountWrapper$2(element, props) {
5957 var node = element;
5958 node.multiple = !!props.multiple;
5959 var value = props.value;
5960 if (value != null) {
5961 updateOptions(node, !!props.multiple, value, false);
5962 } else if (props.defaultValue != null) {
5963 updateOptions(node, !!props.multiple, props.defaultValue, true);
5964 }
5965}
5966
5967function postUpdateWrapper(element, props) {
5968 var node = element;
5969 var wasMultiple = node._wrapperState.wasMultiple;
5970 node._wrapperState.wasMultiple = !!props.multiple;
5971
5972 var value = props.value;
5973 if (value != null) {
5974 updateOptions(node, !!props.multiple, value, false);
5975 } else if (wasMultiple !== !!props.multiple) {
5976 // For simplicity, reapply `defaultValue` if `multiple` is toggled.
5977 if (props.defaultValue != null) {
5978 updateOptions(node, !!props.multiple, props.defaultValue, true);
5979 } else {
5980 // Revert the select back to its default unselected state.
5981 updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
5982 }
5983 }
5984}
5985
5986function restoreControlledState$2(element, props) {
5987 var node = element;
5988 var value = props.value;
5989
5990 if (value != null) {
5991 updateOptions(node, !!props.multiple, value, false);
5992 }
5993}
5994
5995var didWarnValDefaultVal = false;
5996
5997/**
5998 * Implements a <textarea> host component that allows setting `value`, and
5999 * `defaultValue`. This differs from the traditional DOM API because value is
6000 * usually set as PCDATA children.
6001 *
6002 * If `value` is not supplied (or null/undefined), user actions that affect the
6003 * value will trigger updates to the element.
6004 *
6005 * If `value` is supplied (and not null/undefined), the rendered element will
6006 * not trigger updates to the element. Instead, the `value` prop must change in
6007 * order for the rendered element to be updated.
6008 *
6009 * The rendered element will be initialized with an empty value, the prop
6010 * `defaultValue` if specified, or the children content (deprecated).
6011 */
6012
6013function getHostProps$3(element, props) {
6014 var node = element;
6015 !(props.dangerouslySetInnerHTML == null) ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : void 0;
6016
6017 // Always set children to the same thing. In IE9, the selection range will
6018 // get reset if `textContent` is mutated. We could add a check in setTextContent
6019 // to only set the value if/when the value differs from the node value (which would
6020 // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
6021 // solution. The value can be a boolean or object so that's why it's forced
6022 // to be a string.
6023 var hostProps = _assign({}, props, {
6024 value: undefined,
6025 defaultValue: undefined,
6026 children: toString(node._wrapperState.initialValue)
6027 });
6028
6029 return hostProps;
6030}
6031
6032function initWrapperState$2(element, props) {
6033 var node = element;
6034 {
6035 ReactControlledValuePropTypes.checkPropTypes('textarea', props);
6036 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
6037 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');
6038 didWarnValDefaultVal = true;
6039 }
6040 }
6041
6042 var initialValue = props.value;
6043
6044 // Only bother fetching default value if we're going to use it
6045 if (initialValue == null) {
6046 var defaultValue = props.defaultValue;
6047 // TODO (yungsters): Remove support for children content in <textarea>.
6048 var children = props.children;
6049 if (children != null) {
6050 {
6051 warning$1(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
6052 }
6053 !(defaultValue == null) ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : void 0;
6054 if (Array.isArray(children)) {
6055 !(children.length <= 1) ? invariant(false, '<textarea> can only have at most one child.') : void 0;
6056 children = children[0];
6057 }
6058
6059 defaultValue = children;
6060 }
6061 if (defaultValue == null) {
6062 defaultValue = '';
6063 }
6064 initialValue = defaultValue;
6065 }
6066
6067 node._wrapperState = {
6068 initialValue: getToStringValue(initialValue)
6069 };
6070}
6071
6072function updateWrapper$1(element, props) {
6073 var node = element;
6074 var value = getToStringValue(props.value);
6075 var defaultValue = getToStringValue(props.defaultValue);
6076 if (value != null) {
6077 // Cast `value` to a string to ensure the value is set correctly. While
6078 // browsers typically do this as necessary, jsdom doesn't.
6079 var newValue = toString(value);
6080 // To avoid side effects (such as losing text selection), only set value if changed
6081 if (newValue !== node.value) {
6082 node.value = newValue;
6083 }
6084 if (props.defaultValue == null && node.defaultValue !== newValue) {
6085 node.defaultValue = newValue;
6086 }
6087 }
6088 if (defaultValue != null) {
6089 node.defaultValue = toString(defaultValue);
6090 }
6091}
6092
6093function postMountWrapper$3(element, props) {
6094 var node = element;
6095 // This is in postMount because we need access to the DOM node, which is not
6096 // available until after the component has mounted.
6097 var textContent = node.textContent;
6098
6099 // Only set node.value if textContent is equal to the expected
6100 // initial value. In IE10/IE11 there is a bug where the placeholder attribute
6101 // will populate textContent as well.
6102 // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
6103 if (textContent === node._wrapperState.initialValue) {
6104 node.value = textContent;
6105 }
6106}
6107
6108function restoreControlledState$3(element, props) {
6109 // DOM component is still mounted; update
6110 updateWrapper$1(element, props);
6111}
6112
6113var HTML_NAMESPACE$1 = 'http://www.w3.org/1999/xhtml';
6114var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
6115var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
6116
6117var Namespaces = {
6118 html: HTML_NAMESPACE$1,
6119 mathml: MATH_NAMESPACE,
6120 svg: SVG_NAMESPACE
6121};
6122
6123// Assumes there is no parent namespace.
6124function getIntrinsicNamespace(type) {
6125 switch (type) {
6126 case 'svg':
6127 return SVG_NAMESPACE;
6128 case 'math':
6129 return MATH_NAMESPACE;
6130 default:
6131 return HTML_NAMESPACE$1;
6132 }
6133}
6134
6135function getChildNamespace(parentNamespace, type) {
6136 if (parentNamespace == null || parentNamespace === HTML_NAMESPACE$1) {
6137 // No (or default) parent namespace: potential entry point.
6138 return getIntrinsicNamespace(type);
6139 }
6140 if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
6141 // We're leaving SVG.
6142 return HTML_NAMESPACE$1;
6143 }
6144 // By default, pass namespace below.
6145 return parentNamespace;
6146}
6147
6148/* globals MSApp */
6149
6150/**
6151 * Create a function which has 'unsafe' privileges (required by windows8 apps)
6152 */
6153var createMicrosoftUnsafeLocalFunction = function (func) {
6154 if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
6155 return function (arg0, arg1, arg2, arg3) {
6156 MSApp.execUnsafeLocalFunction(function () {
6157 return func(arg0, arg1, arg2, arg3);
6158 });
6159 };
6160 } else {
6161 return func;
6162 }
6163};
6164
6165// SVG temp container for IE lacking innerHTML
6166var reusableSVGContainer = void 0;
6167
6168/**
6169 * Set the innerHTML property of a node
6170 *
6171 * @param {DOMElement} node
6172 * @param {string} html
6173 * @internal
6174 */
6175var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
6176 // IE does not have innerHTML for SVG nodes, so instead we inject the
6177 // new markup in a temp node and then move the child nodes across into
6178 // the target node
6179
6180 if (node.namespaceURI === Namespaces.svg && !('innerHTML' in node)) {
6181 reusableSVGContainer = reusableSVGContainer || document.createElement('div');
6182 reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
6183 var svgNode = reusableSVGContainer.firstChild;
6184 while (node.firstChild) {
6185 node.removeChild(node.firstChild);
6186 }
6187 while (svgNode.firstChild) {
6188 node.appendChild(svgNode.firstChild);
6189 }
6190 } else {
6191 node.innerHTML = html;
6192 }
6193});
6194
6195/**
6196 * Set the textContent property of a node. For text updates, it's faster
6197 * to set the `nodeValue` of the Text node directly instead of using
6198 * `.textContent` which will remove the existing node and create a new one.
6199 *
6200 * @param {DOMElement} node
6201 * @param {string} text
6202 * @internal
6203 */
6204var setTextContent = function (node, text) {
6205 if (text) {
6206 var firstChild = node.firstChild;
6207
6208 if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
6209 firstChild.nodeValue = text;
6210 return;
6211 }
6212 }
6213 node.textContent = text;
6214};
6215
6216// List derived from Gecko source code:
6217// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
6218var shorthandToLonghand = {
6219 animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
6220 background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
6221 backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
6222 border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6223 borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
6224 borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
6225 borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
6226 borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
6227 borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
6228 borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
6229 borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
6230 borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
6231 borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
6232 borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
6233 borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
6234 borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6235 borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
6236 columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
6237 columns: ['columnCount', 'columnWidth'],
6238 flex: ['flexBasis', 'flexGrow', 'flexShrink'],
6239 flexFlow: ['flexDirection', 'flexWrap'],
6240 font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
6241 fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
6242 gap: ['columnGap', 'rowGap'],
6243 grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6244 gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
6245 gridColumn: ['gridColumnEnd', 'gridColumnStart'],
6246 gridColumnGap: ['columnGap'],
6247 gridGap: ['columnGap', 'rowGap'],
6248 gridRow: ['gridRowEnd', 'gridRowStart'],
6249 gridRowGap: ['rowGap'],
6250 gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6251 listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
6252 margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
6253 marker: ['markerEnd', 'markerMid', 'markerStart'],
6254 mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
6255 maskPosition: ['maskPositionX', 'maskPositionY'],
6256 outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
6257 overflow: ['overflowX', 'overflowY'],
6258 padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
6259 placeContent: ['alignContent', 'justifyContent'],
6260 placeItems: ['alignItems', 'justifyItems'],
6261 placeSelf: ['alignSelf', 'justifySelf'],
6262 textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
6263 textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
6264 transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
6265 wordWrap: ['overflowWrap']
6266};
6267
6268/**
6269 * CSS properties which accept numbers but are not in units of "px".
6270 */
6271var isUnitlessNumber = {
6272 animationIterationCount: true,
6273 borderImageOutset: true,
6274 borderImageSlice: true,
6275 borderImageWidth: true,
6276 boxFlex: true,
6277 boxFlexGroup: true,
6278 boxOrdinalGroup: true,
6279 columnCount: true,
6280 columns: true,
6281 flex: true,
6282 flexGrow: true,
6283 flexPositive: true,
6284 flexShrink: true,
6285 flexNegative: true,
6286 flexOrder: true,
6287 gridArea: true,
6288 gridRow: true,
6289 gridRowEnd: true,
6290 gridRowSpan: true,
6291 gridRowStart: true,
6292 gridColumn: true,
6293 gridColumnEnd: true,
6294 gridColumnSpan: true,
6295 gridColumnStart: true,
6296 fontWeight: true,
6297 lineClamp: true,
6298 lineHeight: true,
6299 opacity: true,
6300 order: true,
6301 orphans: true,
6302 tabSize: true,
6303 widows: true,
6304 zIndex: true,
6305 zoom: true,
6306
6307 // SVG-related properties
6308 fillOpacity: true,
6309 floodOpacity: true,
6310 stopOpacity: true,
6311 strokeDasharray: true,
6312 strokeDashoffset: true,
6313 strokeMiterlimit: true,
6314 strokeOpacity: true,
6315 strokeWidth: true
6316};
6317
6318/**
6319 * @param {string} prefix vendor-specific prefix, eg: Webkit
6320 * @param {string} key style name, eg: transitionDuration
6321 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
6322 * WebkitTransitionDuration
6323 */
6324function prefixKey(prefix, key) {
6325 return prefix + key.charAt(0).toUpperCase() + key.substring(1);
6326}
6327
6328/**
6329 * Support style names that may come passed in prefixed by adding permutations
6330 * of vendor prefixes.
6331 */
6332var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
6333
6334// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
6335// infinite loop, because it iterates over the newly added props too.
6336Object.keys(isUnitlessNumber).forEach(function (prop) {
6337 prefixes.forEach(function (prefix) {
6338 isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
6339 });
6340});
6341
6342/**
6343 * Convert a value into the proper css writable value. The style name `name`
6344 * should be logical (no hyphens), as specified
6345 * in `CSSProperty.isUnitlessNumber`.
6346 *
6347 * @param {string} name CSS property name such as `topMargin`.
6348 * @param {*} value CSS property value such as `10px`.
6349 * @return {string} Normalized style value with dimensions applied.
6350 */
6351function dangerousStyleValue(name, value, isCustomProperty) {
6352 // Note that we've removed escapeTextForBrowser() calls here since the
6353 // whole string will be escaped when the attribute is injected into
6354 // the markup. If you provide unsafe user data here they can inject
6355 // arbitrary CSS which may be problematic (I couldn't repro this):
6356 // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
6357 // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
6358 // This is not an XSS hole but instead a potential CSS injection issue
6359 // which has lead to a greater discussion about how we're going to
6360 // trust URLs moving forward. See #2115901
6361
6362 var isEmpty = value == null || typeof value === 'boolean' || value === '';
6363 if (isEmpty) {
6364 return '';
6365 }
6366
6367 if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
6368 return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
6369 }
6370
6371 return ('' + value).trim();
6372}
6373
6374var uppercasePattern = /([A-Z])/g;
6375var msPattern = /^ms-/;
6376
6377/**
6378 * Hyphenates a camelcased CSS property name, for example:
6379 *
6380 * > hyphenateStyleName('backgroundColor')
6381 * < "background-color"
6382 * > hyphenateStyleName('MozTransition')
6383 * < "-moz-transition"
6384 * > hyphenateStyleName('msTransition')
6385 * < "-ms-transition"
6386 *
6387 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
6388 * is converted to `-ms-`.
6389 */
6390function hyphenateStyleName(name) {
6391 return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
6392}
6393
6394var warnValidStyle = function () {};
6395
6396{
6397 // 'msTransform' is correct, but the other prefixes should be capitalized
6398 var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
6399 var msPattern$1 = /^-ms-/;
6400 var hyphenPattern = /-(.)/g;
6401
6402 // style values shouldn't contain a semicolon
6403 var badStyleValueWithSemicolonPattern = /;\s*$/;
6404
6405 var warnedStyleNames = {};
6406 var warnedStyleValues = {};
6407 var warnedForNaNValue = false;
6408 var warnedForInfinityValue = false;
6409
6410 var camelize = function (string) {
6411 return string.replace(hyphenPattern, function (_, character) {
6412 return character.toUpperCase();
6413 });
6414 };
6415
6416 var warnHyphenatedStyleName = function (name) {
6417 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6418 return;
6419 }
6420
6421 warnedStyleNames[name] = true;
6422 warning$1(false, 'Unsupported style property %s. Did you mean %s?', name,
6423 // As Andi Smith suggests
6424 // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
6425 // is converted to lowercase `ms`.
6426 camelize(name.replace(msPattern$1, 'ms-')));
6427 };
6428
6429 var warnBadVendoredStyleName = function (name) {
6430 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6431 return;
6432 }
6433
6434 warnedStyleNames[name] = true;
6435 warning$1(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
6436 };
6437
6438 var warnStyleValueWithSemicolon = function (name, value) {
6439 if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
6440 return;
6441 }
6442
6443 warnedStyleValues[value] = true;
6444 warning$1(false, "Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
6445 };
6446
6447 var warnStyleValueIsNaN = function (name, value) {
6448 if (warnedForNaNValue) {
6449 return;
6450 }
6451
6452 warnedForNaNValue = true;
6453 warning$1(false, '`NaN` is an invalid value for the `%s` css style property.', name);
6454 };
6455
6456 var warnStyleValueIsInfinity = function (name, value) {
6457 if (warnedForInfinityValue) {
6458 return;
6459 }
6460
6461 warnedForInfinityValue = true;
6462 warning$1(false, '`Infinity` is an invalid value for the `%s` css style property.', name);
6463 };
6464
6465 warnValidStyle = function (name, value) {
6466 if (name.indexOf('-') > -1) {
6467 warnHyphenatedStyleName(name);
6468 } else if (badVendoredStyleNamePattern.test(name)) {
6469 warnBadVendoredStyleName(name);
6470 } else if (badStyleValueWithSemicolonPattern.test(value)) {
6471 warnStyleValueWithSemicolon(name, value);
6472 }
6473
6474 if (typeof value === 'number') {
6475 if (isNaN(value)) {
6476 warnStyleValueIsNaN(name, value);
6477 } else if (!isFinite(value)) {
6478 warnStyleValueIsInfinity(name, value);
6479 }
6480 }
6481 };
6482}
6483
6484var warnValidStyle$1 = warnValidStyle;
6485
6486/**
6487 * Operations for dealing with CSS properties.
6488 */
6489
6490/**
6491 * This creates a string that is expected to be equivalent to the style
6492 * attribute generated by server-side rendering. It by-passes warnings and
6493 * security checks so it's not safe to use this value for anything other than
6494 * comparison. It is only used in DEV for SSR validation.
6495 */
6496function createDangerousStringForStyles(styles) {
6497 {
6498 var serialized = '';
6499 var delimiter = '';
6500 for (var styleName in styles) {
6501 if (!styles.hasOwnProperty(styleName)) {
6502 continue;
6503 }
6504 var styleValue = styles[styleName];
6505 if (styleValue != null) {
6506 var isCustomProperty = styleName.indexOf('--') === 0;
6507 serialized += delimiter + hyphenateStyleName(styleName) + ':';
6508 serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
6509
6510 delimiter = ';';
6511 }
6512 }
6513 return serialized || null;
6514 }
6515}
6516
6517/**
6518 * Sets the value for multiple styles on a node. If a value is specified as
6519 * '' (empty string), the corresponding style property will be unset.
6520 *
6521 * @param {DOMElement} node
6522 * @param {object} styles
6523 */
6524function setValueForStyles(node, styles) {
6525 var style = node.style;
6526 for (var styleName in styles) {
6527 if (!styles.hasOwnProperty(styleName)) {
6528 continue;
6529 }
6530 var isCustomProperty = styleName.indexOf('--') === 0;
6531 {
6532 if (!isCustomProperty) {
6533 warnValidStyle$1(styleName, styles[styleName]);
6534 }
6535 }
6536 var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
6537 if (styleName === 'float') {
6538 styleName = 'cssFloat';
6539 }
6540 if (isCustomProperty) {
6541 style.setProperty(styleName, styleValue);
6542 } else {
6543 style[styleName] = styleValue;
6544 }
6545 }
6546}
6547
6548function isValueEmpty(value) {
6549 return value == null || typeof value === 'boolean' || value === '';
6550}
6551
6552/**
6553 * Given {color: 'red', overflow: 'hidden'} returns {
6554 * color: 'color',
6555 * overflowX: 'overflow',
6556 * overflowY: 'overflow',
6557 * }. This can be read as "the overflowY property was set by the overflow
6558 * shorthand". That is, the values are the property that each was derived from.
6559 */
6560function expandShorthandMap(styles) {
6561 var expanded = {};
6562 for (var key in styles) {
6563 var longhands = shorthandToLonghand[key] || [key];
6564 for (var i = 0; i < longhands.length; i++) {
6565 expanded[longhands[i]] = key;
6566 }
6567 }
6568 return expanded;
6569}
6570
6571/**
6572 * When mixing shorthand and longhand property names, we warn during updates if
6573 * we expect an incorrect result to occur. In particular, we warn for:
6574 *
6575 * Updating a shorthand property (longhand gets overwritten):
6576 * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
6577 * becomes .style.font = 'baz'
6578 * Removing a shorthand property (longhand gets lost too):
6579 * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
6580 * becomes .style.font = ''
6581 * Removing a longhand property (should revert to shorthand; doesn't):
6582 * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
6583 * becomes .style.fontVariant = ''
6584 */
6585function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
6586 if (!warnAboutShorthandPropertyCollision) {
6587 return;
6588 }
6589
6590 if (!nextStyles) {
6591 return;
6592 }
6593
6594 var expandedUpdates = expandShorthandMap(styleUpdates);
6595 var expandedStyles = expandShorthandMap(nextStyles);
6596 var warnedAbout = {};
6597 for (var key in expandedUpdates) {
6598 var originalKey = expandedUpdates[key];
6599 var correctOriginalKey = expandedStyles[key];
6600 if (correctOriginalKey && originalKey !== correctOriginalKey) {
6601 var warningKey = originalKey + ',' + correctOriginalKey;
6602 if (warnedAbout[warningKey]) {
6603 continue;
6604 }
6605 warnedAbout[warningKey] = true;
6606 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);
6607 }
6608 }
6609}
6610
6611// For HTML, certain tags should omit their close tag. We keep a whitelist for
6612// those special-case tags.
6613
6614var omittedCloseTags = {
6615 area: true,
6616 base: true,
6617 br: true,
6618 col: true,
6619 embed: true,
6620 hr: true,
6621 img: true,
6622 input: true,
6623 keygen: true,
6624 link: true,
6625 meta: true,
6626 param: true,
6627 source: true,
6628 track: true,
6629 wbr: true
6630 // NOTE: menuitem's close tag should be omitted, but that causes problems.
6631};
6632
6633// For HTML, certain tags cannot have children. This has the same purpose as
6634// `omittedCloseTags` except that `menuitem` should still have its closing tag.
6635
6636var voidElementTags = _assign({
6637 menuitem: true
6638}, omittedCloseTags);
6639
6640// TODO: We can remove this if we add invariantWithStack()
6641// or add stack by default to invariants where possible.
6642var HTML$1 = '__html';
6643
6644var ReactDebugCurrentFrame$2 = null;
6645{
6646 ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame;
6647}
6648
6649function assertValidProps(tag, props) {
6650 if (!props) {
6651 return;
6652 }
6653 // Note the use of `==` which checks for null or undefined.
6654 if (voidElementTags[tag]) {
6655 !(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;
6656 }
6657 if (props.dangerouslySetInnerHTML != null) {
6658 !(props.children == null) ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : void 0;
6659 !(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;
6660 }
6661 {
6662 !(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;
6663 }
6664 !(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;
6665}
6666
6667function isCustomComponent(tagName, props) {
6668 if (tagName.indexOf('-') === -1) {
6669 return typeof props.is === 'string';
6670 }
6671 switch (tagName) {
6672 // These are reserved SVG and MathML elements.
6673 // We don't mind this whitelist too much because we expect it to never grow.
6674 // The alternative is to track the namespace in a few places which is convoluted.
6675 // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
6676 case 'annotation-xml':
6677 case 'color-profile':
6678 case 'font-face':
6679 case 'font-face-src':
6680 case 'font-face-uri':
6681 case 'font-face-format':
6682 case 'font-face-name':
6683 case 'missing-glyph':
6684 return false;
6685 default:
6686 return true;
6687 }
6688}
6689
6690// When adding attributes to the HTML or SVG whitelist, be sure to
6691// also add them to this module to ensure casing and incorrect name
6692// warnings.
6693var possibleStandardNames = {
6694 // HTML
6695 accept: 'accept',
6696 acceptcharset: 'acceptCharset',
6697 'accept-charset': 'acceptCharset',
6698 accesskey: 'accessKey',
6699 action: 'action',
6700 allowfullscreen: 'allowFullScreen',
6701 alt: 'alt',
6702 as: 'as',
6703 async: 'async',
6704 autocapitalize: 'autoCapitalize',
6705 autocomplete: 'autoComplete',
6706 autocorrect: 'autoCorrect',
6707 autofocus: 'autoFocus',
6708 autoplay: 'autoPlay',
6709 autosave: 'autoSave',
6710 capture: 'capture',
6711 cellpadding: 'cellPadding',
6712 cellspacing: 'cellSpacing',
6713 challenge: 'challenge',
6714 charset: 'charSet',
6715 checked: 'checked',
6716 children: 'children',
6717 cite: 'cite',
6718 class: 'className',
6719 classid: 'classID',
6720 classname: 'className',
6721 cols: 'cols',
6722 colspan: 'colSpan',
6723 content: 'content',
6724 contenteditable: 'contentEditable',
6725 contextmenu: 'contextMenu',
6726 controls: 'controls',
6727 controlslist: 'controlsList',
6728 coords: 'coords',
6729 crossorigin: 'crossOrigin',
6730 dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
6731 data: 'data',
6732 datetime: 'dateTime',
6733 default: 'default',
6734 defaultchecked: 'defaultChecked',
6735 defaultvalue: 'defaultValue',
6736 defer: 'defer',
6737 dir: 'dir',
6738 disabled: 'disabled',
6739 download: 'download',
6740 draggable: 'draggable',
6741 enctype: 'encType',
6742 for: 'htmlFor',
6743 form: 'form',
6744 formmethod: 'formMethod',
6745 formaction: 'formAction',
6746 formenctype: 'formEncType',
6747 formnovalidate: 'formNoValidate',
6748 formtarget: 'formTarget',
6749 frameborder: 'frameBorder',
6750 headers: 'headers',
6751 height: 'height',
6752 hidden: 'hidden',
6753 high: 'high',
6754 href: 'href',
6755 hreflang: 'hrefLang',
6756 htmlfor: 'htmlFor',
6757 httpequiv: 'httpEquiv',
6758 'http-equiv': 'httpEquiv',
6759 icon: 'icon',
6760 id: 'id',
6761 innerhtml: 'innerHTML',
6762 inputmode: 'inputMode',
6763 integrity: 'integrity',
6764 is: 'is',
6765 itemid: 'itemID',
6766 itemprop: 'itemProp',
6767 itemref: 'itemRef',
6768 itemscope: 'itemScope',
6769 itemtype: 'itemType',
6770 keyparams: 'keyParams',
6771 keytype: 'keyType',
6772 kind: 'kind',
6773 label: 'label',
6774 lang: 'lang',
6775 list: 'list',
6776 loop: 'loop',
6777 low: 'low',
6778 manifest: 'manifest',
6779 marginwidth: 'marginWidth',
6780 marginheight: 'marginHeight',
6781 max: 'max',
6782 maxlength: 'maxLength',
6783 media: 'media',
6784 mediagroup: 'mediaGroup',
6785 method: 'method',
6786 min: 'min',
6787 minlength: 'minLength',
6788 multiple: 'multiple',
6789 muted: 'muted',
6790 name: 'name',
6791 nomodule: 'noModule',
6792 nonce: 'nonce',
6793 novalidate: 'noValidate',
6794 open: 'open',
6795 optimum: 'optimum',
6796 pattern: 'pattern',
6797 placeholder: 'placeholder',
6798 playsinline: 'playsInline',
6799 poster: 'poster',
6800 preload: 'preload',
6801 profile: 'profile',
6802 radiogroup: 'radioGroup',
6803 readonly: 'readOnly',
6804 referrerpolicy: 'referrerPolicy',
6805 rel: 'rel',
6806 required: 'required',
6807 reversed: 'reversed',
6808 role: 'role',
6809 rows: 'rows',
6810 rowspan: 'rowSpan',
6811 sandbox: 'sandbox',
6812 scope: 'scope',
6813 scoped: 'scoped',
6814 scrolling: 'scrolling',
6815 seamless: 'seamless',
6816 selected: 'selected',
6817 shape: 'shape',
6818 size: 'size',
6819 sizes: 'sizes',
6820 span: 'span',
6821 spellcheck: 'spellCheck',
6822 src: 'src',
6823 srcdoc: 'srcDoc',
6824 srclang: 'srcLang',
6825 srcset: 'srcSet',
6826 start: 'start',
6827 step: 'step',
6828 style: 'style',
6829 summary: 'summary',
6830 tabindex: 'tabIndex',
6831 target: 'target',
6832 title: 'title',
6833 type: 'type',
6834 usemap: 'useMap',
6835 value: 'value',
6836 width: 'width',
6837 wmode: 'wmode',
6838 wrap: 'wrap',
6839
6840 // SVG
6841 about: 'about',
6842 accentheight: 'accentHeight',
6843 'accent-height': 'accentHeight',
6844 accumulate: 'accumulate',
6845 additive: 'additive',
6846 alignmentbaseline: 'alignmentBaseline',
6847 'alignment-baseline': 'alignmentBaseline',
6848 allowreorder: 'allowReorder',
6849 alphabetic: 'alphabetic',
6850 amplitude: 'amplitude',
6851 arabicform: 'arabicForm',
6852 'arabic-form': 'arabicForm',
6853 ascent: 'ascent',
6854 attributename: 'attributeName',
6855 attributetype: 'attributeType',
6856 autoreverse: 'autoReverse',
6857 azimuth: 'azimuth',
6858 basefrequency: 'baseFrequency',
6859 baselineshift: 'baselineShift',
6860 'baseline-shift': 'baselineShift',
6861 baseprofile: 'baseProfile',
6862 bbox: 'bbox',
6863 begin: 'begin',
6864 bias: 'bias',
6865 by: 'by',
6866 calcmode: 'calcMode',
6867 capheight: 'capHeight',
6868 'cap-height': 'capHeight',
6869 clip: 'clip',
6870 clippath: 'clipPath',
6871 'clip-path': 'clipPath',
6872 clippathunits: 'clipPathUnits',
6873 cliprule: 'clipRule',
6874 'clip-rule': 'clipRule',
6875 color: 'color',
6876 colorinterpolation: 'colorInterpolation',
6877 'color-interpolation': 'colorInterpolation',
6878 colorinterpolationfilters: 'colorInterpolationFilters',
6879 'color-interpolation-filters': 'colorInterpolationFilters',
6880 colorprofile: 'colorProfile',
6881 'color-profile': 'colorProfile',
6882 colorrendering: 'colorRendering',
6883 'color-rendering': 'colorRendering',
6884 contentscripttype: 'contentScriptType',
6885 contentstyletype: 'contentStyleType',
6886 cursor: 'cursor',
6887 cx: 'cx',
6888 cy: 'cy',
6889 d: 'd',
6890 datatype: 'datatype',
6891 decelerate: 'decelerate',
6892 descent: 'descent',
6893 diffuseconstant: 'diffuseConstant',
6894 direction: 'direction',
6895 display: 'display',
6896 divisor: 'divisor',
6897 dominantbaseline: 'dominantBaseline',
6898 'dominant-baseline': 'dominantBaseline',
6899 dur: 'dur',
6900 dx: 'dx',
6901 dy: 'dy',
6902 edgemode: 'edgeMode',
6903 elevation: 'elevation',
6904 enablebackground: 'enableBackground',
6905 'enable-background': 'enableBackground',
6906 end: 'end',
6907 exponent: 'exponent',
6908 externalresourcesrequired: 'externalResourcesRequired',
6909 fill: 'fill',
6910 fillopacity: 'fillOpacity',
6911 'fill-opacity': 'fillOpacity',
6912 fillrule: 'fillRule',
6913 'fill-rule': 'fillRule',
6914 filter: 'filter',
6915 filterres: 'filterRes',
6916 filterunits: 'filterUnits',
6917 floodopacity: 'floodOpacity',
6918 'flood-opacity': 'floodOpacity',
6919 floodcolor: 'floodColor',
6920 'flood-color': 'floodColor',
6921 focusable: 'focusable',
6922 fontfamily: 'fontFamily',
6923 'font-family': 'fontFamily',
6924 fontsize: 'fontSize',
6925 'font-size': 'fontSize',
6926 fontsizeadjust: 'fontSizeAdjust',
6927 'font-size-adjust': 'fontSizeAdjust',
6928 fontstretch: 'fontStretch',
6929 'font-stretch': 'fontStretch',
6930 fontstyle: 'fontStyle',
6931 'font-style': 'fontStyle',
6932 fontvariant: 'fontVariant',
6933 'font-variant': 'fontVariant',
6934 fontweight: 'fontWeight',
6935 'font-weight': 'fontWeight',
6936 format: 'format',
6937 from: 'from',
6938 fx: 'fx',
6939 fy: 'fy',
6940 g1: 'g1',
6941 g2: 'g2',
6942 glyphname: 'glyphName',
6943 'glyph-name': 'glyphName',
6944 glyphorientationhorizontal: 'glyphOrientationHorizontal',
6945 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
6946 glyphorientationvertical: 'glyphOrientationVertical',
6947 'glyph-orientation-vertical': 'glyphOrientationVertical',
6948 glyphref: 'glyphRef',
6949 gradienttransform: 'gradientTransform',
6950 gradientunits: 'gradientUnits',
6951 hanging: 'hanging',
6952 horizadvx: 'horizAdvX',
6953 'horiz-adv-x': 'horizAdvX',
6954 horizoriginx: 'horizOriginX',
6955 'horiz-origin-x': 'horizOriginX',
6956 ideographic: 'ideographic',
6957 imagerendering: 'imageRendering',
6958 'image-rendering': 'imageRendering',
6959 in2: 'in2',
6960 in: 'in',
6961 inlist: 'inlist',
6962 intercept: 'intercept',
6963 k1: 'k1',
6964 k2: 'k2',
6965 k3: 'k3',
6966 k4: 'k4',
6967 k: 'k',
6968 kernelmatrix: 'kernelMatrix',
6969 kernelunitlength: 'kernelUnitLength',
6970 kerning: 'kerning',
6971 keypoints: 'keyPoints',
6972 keysplines: 'keySplines',
6973 keytimes: 'keyTimes',
6974 lengthadjust: 'lengthAdjust',
6975 letterspacing: 'letterSpacing',
6976 'letter-spacing': 'letterSpacing',
6977 lightingcolor: 'lightingColor',
6978 'lighting-color': 'lightingColor',
6979 limitingconeangle: 'limitingConeAngle',
6980 local: 'local',
6981 markerend: 'markerEnd',
6982 'marker-end': 'markerEnd',
6983 markerheight: 'markerHeight',
6984 markermid: 'markerMid',
6985 'marker-mid': 'markerMid',
6986 markerstart: 'markerStart',
6987 'marker-start': 'markerStart',
6988 markerunits: 'markerUnits',
6989 markerwidth: 'markerWidth',
6990 mask: 'mask',
6991 maskcontentunits: 'maskContentUnits',
6992 maskunits: 'maskUnits',
6993 mathematical: 'mathematical',
6994 mode: 'mode',
6995 numoctaves: 'numOctaves',
6996 offset: 'offset',
6997 opacity: 'opacity',
6998 operator: 'operator',
6999 order: 'order',
7000 orient: 'orient',
7001 orientation: 'orientation',
7002 origin: 'origin',
7003 overflow: 'overflow',
7004 overlineposition: 'overlinePosition',
7005 'overline-position': 'overlinePosition',
7006 overlinethickness: 'overlineThickness',
7007 'overline-thickness': 'overlineThickness',
7008 paintorder: 'paintOrder',
7009 'paint-order': 'paintOrder',
7010 panose1: 'panose1',
7011 'panose-1': 'panose1',
7012 pathlength: 'pathLength',
7013 patterncontentunits: 'patternContentUnits',
7014 patterntransform: 'patternTransform',
7015 patternunits: 'patternUnits',
7016 pointerevents: 'pointerEvents',
7017 'pointer-events': 'pointerEvents',
7018 points: 'points',
7019 pointsatx: 'pointsAtX',
7020 pointsaty: 'pointsAtY',
7021 pointsatz: 'pointsAtZ',
7022 prefix: 'prefix',
7023 preservealpha: 'preserveAlpha',
7024 preserveaspectratio: 'preserveAspectRatio',
7025 primitiveunits: 'primitiveUnits',
7026 property: 'property',
7027 r: 'r',
7028 radius: 'radius',
7029 refx: 'refX',
7030 refy: 'refY',
7031 renderingintent: 'renderingIntent',
7032 'rendering-intent': 'renderingIntent',
7033 repeatcount: 'repeatCount',
7034 repeatdur: 'repeatDur',
7035 requiredextensions: 'requiredExtensions',
7036 requiredfeatures: 'requiredFeatures',
7037 resource: 'resource',
7038 restart: 'restart',
7039 result: 'result',
7040 results: 'results',
7041 rotate: 'rotate',
7042 rx: 'rx',
7043 ry: 'ry',
7044 scale: 'scale',
7045 security: 'security',
7046 seed: 'seed',
7047 shaperendering: 'shapeRendering',
7048 'shape-rendering': 'shapeRendering',
7049 slope: 'slope',
7050 spacing: 'spacing',
7051 specularconstant: 'specularConstant',
7052 specularexponent: 'specularExponent',
7053 speed: 'speed',
7054 spreadmethod: 'spreadMethod',
7055 startoffset: 'startOffset',
7056 stddeviation: 'stdDeviation',
7057 stemh: 'stemh',
7058 stemv: 'stemv',
7059 stitchtiles: 'stitchTiles',
7060 stopcolor: 'stopColor',
7061 'stop-color': 'stopColor',
7062 stopopacity: 'stopOpacity',
7063 'stop-opacity': 'stopOpacity',
7064 strikethroughposition: 'strikethroughPosition',
7065 'strikethrough-position': 'strikethroughPosition',
7066 strikethroughthickness: 'strikethroughThickness',
7067 'strikethrough-thickness': 'strikethroughThickness',
7068 string: 'string',
7069 stroke: 'stroke',
7070 strokedasharray: 'strokeDasharray',
7071 'stroke-dasharray': 'strokeDasharray',
7072 strokedashoffset: 'strokeDashoffset',
7073 'stroke-dashoffset': 'strokeDashoffset',
7074 strokelinecap: 'strokeLinecap',
7075 'stroke-linecap': 'strokeLinecap',
7076 strokelinejoin: 'strokeLinejoin',
7077 'stroke-linejoin': 'strokeLinejoin',
7078 strokemiterlimit: 'strokeMiterlimit',
7079 'stroke-miterlimit': 'strokeMiterlimit',
7080 strokewidth: 'strokeWidth',
7081 'stroke-width': 'strokeWidth',
7082 strokeopacity: 'strokeOpacity',
7083 'stroke-opacity': 'strokeOpacity',
7084 suppresscontenteditablewarning: 'suppressContentEditableWarning',
7085 suppresshydrationwarning: 'suppressHydrationWarning',
7086 surfacescale: 'surfaceScale',
7087 systemlanguage: 'systemLanguage',
7088 tablevalues: 'tableValues',
7089 targetx: 'targetX',
7090 targety: 'targetY',
7091 textanchor: 'textAnchor',
7092 'text-anchor': 'textAnchor',
7093 textdecoration: 'textDecoration',
7094 'text-decoration': 'textDecoration',
7095 textlength: 'textLength',
7096 textrendering: 'textRendering',
7097 'text-rendering': 'textRendering',
7098 to: 'to',
7099 transform: 'transform',
7100 typeof: 'typeof',
7101 u1: 'u1',
7102 u2: 'u2',
7103 underlineposition: 'underlinePosition',
7104 'underline-position': 'underlinePosition',
7105 underlinethickness: 'underlineThickness',
7106 'underline-thickness': 'underlineThickness',
7107 unicode: 'unicode',
7108 unicodebidi: 'unicodeBidi',
7109 'unicode-bidi': 'unicodeBidi',
7110 unicoderange: 'unicodeRange',
7111 'unicode-range': 'unicodeRange',
7112 unitsperem: 'unitsPerEm',
7113 'units-per-em': 'unitsPerEm',
7114 unselectable: 'unselectable',
7115 valphabetic: 'vAlphabetic',
7116 'v-alphabetic': 'vAlphabetic',
7117 values: 'values',
7118 vectoreffect: 'vectorEffect',
7119 'vector-effect': 'vectorEffect',
7120 version: 'version',
7121 vertadvy: 'vertAdvY',
7122 'vert-adv-y': 'vertAdvY',
7123 vertoriginx: 'vertOriginX',
7124 'vert-origin-x': 'vertOriginX',
7125 vertoriginy: 'vertOriginY',
7126 'vert-origin-y': 'vertOriginY',
7127 vhanging: 'vHanging',
7128 'v-hanging': 'vHanging',
7129 videographic: 'vIdeographic',
7130 'v-ideographic': 'vIdeographic',
7131 viewbox: 'viewBox',
7132 viewtarget: 'viewTarget',
7133 visibility: 'visibility',
7134 vmathematical: 'vMathematical',
7135 'v-mathematical': 'vMathematical',
7136 vocab: 'vocab',
7137 widths: 'widths',
7138 wordspacing: 'wordSpacing',
7139 'word-spacing': 'wordSpacing',
7140 writingmode: 'writingMode',
7141 'writing-mode': 'writingMode',
7142 x1: 'x1',
7143 x2: 'x2',
7144 x: 'x',
7145 xchannelselector: 'xChannelSelector',
7146 xheight: 'xHeight',
7147 'x-height': 'xHeight',
7148 xlinkactuate: 'xlinkActuate',
7149 'xlink:actuate': 'xlinkActuate',
7150 xlinkarcrole: 'xlinkArcrole',
7151 'xlink:arcrole': 'xlinkArcrole',
7152 xlinkhref: 'xlinkHref',
7153 'xlink:href': 'xlinkHref',
7154 xlinkrole: 'xlinkRole',
7155 'xlink:role': 'xlinkRole',
7156 xlinkshow: 'xlinkShow',
7157 'xlink:show': 'xlinkShow',
7158 xlinktitle: 'xlinkTitle',
7159 'xlink:title': 'xlinkTitle',
7160 xlinktype: 'xlinkType',
7161 'xlink:type': 'xlinkType',
7162 xmlbase: 'xmlBase',
7163 'xml:base': 'xmlBase',
7164 xmllang: 'xmlLang',
7165 'xml:lang': 'xmlLang',
7166 xmlns: 'xmlns',
7167 'xml:space': 'xmlSpace',
7168 xmlnsxlink: 'xmlnsXlink',
7169 'xmlns:xlink': 'xmlnsXlink',
7170 xmlspace: 'xmlSpace',
7171 y1: 'y1',
7172 y2: 'y2',
7173 y: 'y',
7174 ychannelselector: 'yChannelSelector',
7175 z: 'z',
7176 zoomandpan: 'zoomAndPan'
7177};
7178
7179var ariaProperties = {
7180 'aria-current': 0, // state
7181 'aria-details': 0,
7182 'aria-disabled': 0, // state
7183 'aria-hidden': 0, // state
7184 'aria-invalid': 0, // state
7185 'aria-keyshortcuts': 0,
7186 'aria-label': 0,
7187 'aria-roledescription': 0,
7188 // Widget Attributes
7189 'aria-autocomplete': 0,
7190 'aria-checked': 0,
7191 'aria-expanded': 0,
7192 'aria-haspopup': 0,
7193 'aria-level': 0,
7194 'aria-modal': 0,
7195 'aria-multiline': 0,
7196 'aria-multiselectable': 0,
7197 'aria-orientation': 0,
7198 'aria-placeholder': 0,
7199 'aria-pressed': 0,
7200 'aria-readonly': 0,
7201 'aria-required': 0,
7202 'aria-selected': 0,
7203 'aria-sort': 0,
7204 'aria-valuemax': 0,
7205 'aria-valuemin': 0,
7206 'aria-valuenow': 0,
7207 'aria-valuetext': 0,
7208 // Live Region Attributes
7209 'aria-atomic': 0,
7210 'aria-busy': 0,
7211 'aria-live': 0,
7212 'aria-relevant': 0,
7213 // Drag-and-Drop Attributes
7214 'aria-dropeffect': 0,
7215 'aria-grabbed': 0,
7216 // Relationship Attributes
7217 'aria-activedescendant': 0,
7218 'aria-colcount': 0,
7219 'aria-colindex': 0,
7220 'aria-colspan': 0,
7221 'aria-controls': 0,
7222 'aria-describedby': 0,
7223 'aria-errormessage': 0,
7224 'aria-flowto': 0,
7225 'aria-labelledby': 0,
7226 'aria-owns': 0,
7227 'aria-posinset': 0,
7228 'aria-rowcount': 0,
7229 'aria-rowindex': 0,
7230 'aria-rowspan': 0,
7231 'aria-setsize': 0
7232};
7233
7234var warnedProperties = {};
7235var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7236var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7237
7238var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
7239
7240function validateProperty(tagName, name) {
7241 if (hasOwnProperty$2.call(warnedProperties, name) && warnedProperties[name]) {
7242 return true;
7243 }
7244
7245 if (rARIACamel.test(name)) {
7246 var ariaName = 'aria-' + name.slice(4).toLowerCase();
7247 var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null;
7248
7249 // If this is an aria-* attribute, but is not listed in the known DOM
7250 // DOM properties, then it is an invalid aria-* attribute.
7251 if (correctName == null) {
7252 warning$1(false, 'Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
7253 warnedProperties[name] = true;
7254 return true;
7255 }
7256 // aria-* attributes should be lowercase; suggest the lowercase version.
7257 if (name !== correctName) {
7258 warning$1(false, 'Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
7259 warnedProperties[name] = true;
7260 return true;
7261 }
7262 }
7263
7264 if (rARIA.test(name)) {
7265 var lowerCasedName = name.toLowerCase();
7266 var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null;
7267
7268 // If this is an aria-* attribute, but is not listed in the known DOM
7269 // DOM properties, then it is an invalid aria-* attribute.
7270 if (standardName == null) {
7271 warnedProperties[name] = true;
7272 return false;
7273 }
7274 // aria-* attributes should be lowercase; suggest the lowercase version.
7275 if (name !== standardName) {
7276 warning$1(false, 'Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
7277 warnedProperties[name] = true;
7278 return true;
7279 }
7280 }
7281
7282 return true;
7283}
7284
7285function warnInvalidARIAProps(type, props) {
7286 var invalidProps = [];
7287
7288 for (var key in props) {
7289 var isValid = validateProperty(type, key);
7290 if (!isValid) {
7291 invalidProps.push(key);
7292 }
7293 }
7294
7295 var unknownPropString = invalidProps.map(function (prop) {
7296 return '`' + prop + '`';
7297 }).join(', ');
7298
7299 if (invalidProps.length === 1) {
7300 warning$1(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7301 } else if (invalidProps.length > 1) {
7302 warning$1(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7303 }
7304}
7305
7306function validateProperties(type, props) {
7307 if (isCustomComponent(type, props)) {
7308 return;
7309 }
7310 warnInvalidARIAProps(type, props);
7311}
7312
7313var didWarnValueNull = false;
7314
7315function validateProperties$1(type, props) {
7316 if (type !== 'input' && type !== 'textarea' && type !== 'select') {
7317 return;
7318 }
7319
7320 if (props != null && props.value === null && !didWarnValueNull) {
7321 didWarnValueNull = true;
7322 if (type === 'select' && props.multiple) {
7323 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);
7324 } else {
7325 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);
7326 }
7327 }
7328}
7329
7330var validateProperty$1 = function () {};
7331
7332{
7333 var warnedProperties$1 = {};
7334 var _hasOwnProperty = Object.prototype.hasOwnProperty;
7335 var EVENT_NAME_REGEX = /^on./;
7336 var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
7337 var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7338 var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7339
7340 validateProperty$1 = function (tagName, name, value, canUseEventSystem) {
7341 if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
7342 return true;
7343 }
7344
7345 var lowerCasedName = name.toLowerCase();
7346 if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
7347 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.');
7348 warnedProperties$1[name] = true;
7349 return true;
7350 }
7351
7352 // We can't rely on the event system being injected on the server.
7353 if (canUseEventSystem) {
7354 if (registrationNameModules.hasOwnProperty(name)) {
7355 return true;
7356 }
7357 var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
7358 if (registrationName != null) {
7359 warning$1(false, 'Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
7360 warnedProperties$1[name] = true;
7361 return true;
7362 }
7363 if (EVENT_NAME_REGEX.test(name)) {
7364 warning$1(false, 'Unknown event handler property `%s`. It will be ignored.', name);
7365 warnedProperties$1[name] = true;
7366 return true;
7367 }
7368 } else if (EVENT_NAME_REGEX.test(name)) {
7369 // If no event plugins have been injected, we are in a server environment.
7370 // So we can't tell if the event name is correct for sure, but we can filter
7371 // out known bad ones like `onclick`. We can't suggest a specific replacement though.
7372 if (INVALID_EVENT_NAME_REGEX.test(name)) {
7373 warning$1(false, 'Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
7374 }
7375 warnedProperties$1[name] = true;
7376 return true;
7377 }
7378
7379 // Let the ARIA attribute hook validate ARIA attributes
7380 if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
7381 return true;
7382 }
7383
7384 if (lowerCasedName === 'innerhtml') {
7385 warning$1(false, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
7386 warnedProperties$1[name] = true;
7387 return true;
7388 }
7389
7390 if (lowerCasedName === 'aria') {
7391 warning$1(false, 'The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
7392 warnedProperties$1[name] = true;
7393 return true;
7394 }
7395
7396 if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
7397 warning$1(false, 'Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
7398 warnedProperties$1[name] = true;
7399 return true;
7400 }
7401
7402 if (typeof value === 'number' && isNaN(value)) {
7403 warning$1(false, 'Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
7404 warnedProperties$1[name] = true;
7405 return true;
7406 }
7407
7408 var propertyInfo = getPropertyInfo(name);
7409 var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED;
7410
7411 // Known attributes should match the casing specified in the property config.
7412 if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
7413 var standardName = possibleStandardNames[lowerCasedName];
7414 if (standardName !== name) {
7415 warning$1(false, 'Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
7416 warnedProperties$1[name] = true;
7417 return true;
7418 }
7419 } else if (!isReserved && name !== lowerCasedName) {
7420 // Unknown attributes should have lowercase casing since that's how they
7421 // will be cased anyway with server rendering.
7422 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);
7423 warnedProperties$1[name] = true;
7424 return true;
7425 }
7426
7427 if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7428 if (value) {
7429 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);
7430 } else {
7431 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);
7432 }
7433 warnedProperties$1[name] = true;
7434 return true;
7435 }
7436
7437 // Now that we've validated casing, do not validate
7438 // data types for reserved props
7439 if (isReserved) {
7440 return true;
7441 }
7442
7443 // Warn when a known attribute is a bad type
7444 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7445 warnedProperties$1[name] = true;
7446 return false;
7447 }
7448
7449 // Warn when passing the strings 'false' or 'true' into a boolean prop
7450 if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
7451 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);
7452 warnedProperties$1[name] = true;
7453 return true;
7454 }
7455
7456 return true;
7457 };
7458}
7459
7460var warnUnknownProperties = function (type, props, canUseEventSystem) {
7461 var unknownProps = [];
7462 for (var key in props) {
7463 var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);
7464 if (!isValid) {
7465 unknownProps.push(key);
7466 }
7467 }
7468
7469 var unknownPropString = unknownProps.map(function (prop) {
7470 return '`' + prop + '`';
7471 }).join(', ');
7472 if (unknownProps.length === 1) {
7473 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);
7474 } else if (unknownProps.length > 1) {
7475 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);
7476 }
7477};
7478
7479function validateProperties$2(type, props, canUseEventSystem) {
7480 if (isCustomComponent(type, props)) {
7481 return;
7482 }
7483 warnUnknownProperties(type, props, canUseEventSystem);
7484}
7485
7486// TODO: direct imports like some-package/src/* are bad. Fix me.
7487var didWarnInvalidHydration = false;
7488var didWarnShadyDOM = false;
7489
7490var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
7491var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
7492var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
7493var AUTOFOCUS = 'autoFocus';
7494var CHILDREN = 'children';
7495var STYLE$1 = 'style';
7496var HTML = '__html';
7497
7498var HTML_NAMESPACE = Namespaces.html;
7499
7500
7501var warnedUnknownTags = void 0;
7502var suppressHydrationWarning = void 0;
7503
7504var validatePropertiesInDevelopment = void 0;
7505var warnForTextDifference = void 0;
7506var warnForPropDifference = void 0;
7507var warnForExtraAttributes = void 0;
7508var warnForInvalidEventListener = void 0;
7509var canDiffStyleForHydrationWarning = void 0;
7510
7511var normalizeMarkupForTextOrAttribute = void 0;
7512var normalizeHTML = void 0;
7513
7514{
7515 warnedUnknownTags = {
7516 // Chrome is the only major browser not shipping <time>. But as of July
7517 // 2017 it intends to ship it due to widespread usage. We intentionally
7518 // *don't* warn for <time> even if it's unrecognized by Chrome because
7519 // it soon will be, and many apps have been using it anyway.
7520 time: true,
7521 // There are working polyfills for <dialog>. Let people use it.
7522 dialog: true,
7523 // Electron ships a custom <webview> tag to display external web content in
7524 // an isolated frame and process.
7525 // This tag is not present in non Electron environments such as JSDom which
7526 // is often used for testing purposes.
7527 // @see https://electronjs.org/docs/api/webview-tag
7528 webview: true
7529 };
7530
7531 validatePropertiesInDevelopment = function (type, props) {
7532 validateProperties(type, props);
7533 validateProperties$1(type, props);
7534 validateProperties$2(type, props, /* canUseEventSystem */true);
7535 };
7536
7537 // IE 11 parses & normalizes the style attribute as opposed to other
7538 // browsers. It adds spaces and sorts the properties in some
7539 // non-alphabetical order. Handling that would require sorting CSS
7540 // properties in the client & server versions or applying
7541 // `expectedStyle` to a temporary DOM node to read its `style` attribute
7542 // normalized. Since it only affects IE, we're skipping style warnings
7543 // in that browser completely in favor of doing all that work.
7544 // See https://github.com/facebook/react/issues/11807
7545 canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode;
7546
7547 // HTML parsing normalizes CR and CRLF to LF.
7548 // It also can turn \u0000 into \uFFFD inside attributes.
7549 // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
7550 // If we have a mismatch, it might be caused by that.
7551 // We will still patch up in this case but not fire the warning.
7552 var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
7553 var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
7554
7555 normalizeMarkupForTextOrAttribute = function (markup) {
7556 var markupString = typeof markup === 'string' ? markup : '' + markup;
7557 return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
7558 };
7559
7560 warnForTextDifference = function (serverText, clientText) {
7561 if (didWarnInvalidHydration) {
7562 return;
7563 }
7564 var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
7565 var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
7566 if (normalizedServerText === normalizedClientText) {
7567 return;
7568 }
7569 didWarnInvalidHydration = true;
7570 warningWithoutStack$1(false, 'Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
7571 };
7572
7573 warnForPropDifference = function (propName, serverValue, clientValue) {
7574 if (didWarnInvalidHydration) {
7575 return;
7576 }
7577 var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
7578 var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
7579 if (normalizedServerValue === normalizedClientValue) {
7580 return;
7581 }
7582 didWarnInvalidHydration = true;
7583 warningWithoutStack$1(false, 'Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
7584 };
7585
7586 warnForExtraAttributes = function (attributeNames) {
7587 if (didWarnInvalidHydration) {
7588 return;
7589 }
7590 didWarnInvalidHydration = true;
7591 var names = [];
7592 attributeNames.forEach(function (name) {
7593 names.push(name);
7594 });
7595 warningWithoutStack$1(false, 'Extra attributes from the server: %s', names);
7596 };
7597
7598 warnForInvalidEventListener = function (registrationName, listener) {
7599 if (listener === false) {
7600 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);
7601 } else {
7602 warning$1(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
7603 }
7604 };
7605
7606 // Parse the HTML and read it back to normalize the HTML string so that it
7607 // can be used for comparison.
7608 normalizeHTML = function (parent, html) {
7609 // We could have created a separate document here to avoid
7610 // re-initializing custom elements if they exist. But this breaks
7611 // how <noscript> is being handled. So we use the same document.
7612 // See the discussion in https://github.com/facebook/react/pull/11157.
7613 var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
7614 testElement.innerHTML = html;
7615 return testElement.innerHTML;
7616 };
7617}
7618
7619function ensureListeningTo(rootContainerElement, registrationName) {
7620 var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;
7621 var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;
7622 listenTo(registrationName, doc);
7623}
7624
7625function getOwnerDocumentFromRootContainer(rootContainerElement) {
7626 return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
7627}
7628
7629function noop() {}
7630
7631function trapClickOnNonInteractiveElement(node) {
7632 // Mobile Safari does not fire properly bubble click events on
7633 // non-interactive elements, which means delegated click listeners do not
7634 // fire. The workaround for this bug involves attaching an empty click
7635 // listener on the target node.
7636 // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
7637 // Just set it using the onclick property so that we don't have to manage any
7638 // bookkeeping for it. Not sure if we need to clear it when the listener is
7639 // removed.
7640 // TODO: Only do this for the relevant Safaris maybe?
7641 node.onclick = noop;
7642}
7643
7644function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
7645 for (var propKey in nextProps) {
7646 if (!nextProps.hasOwnProperty(propKey)) {
7647 continue;
7648 }
7649 var nextProp = nextProps[propKey];
7650 if (propKey === STYLE$1) {
7651 {
7652 if (nextProp) {
7653 // Freeze the next style object so that we can assume it won't be
7654 // mutated. We have already warned for this in the past.
7655 Object.freeze(nextProp);
7656 }
7657 }
7658 // Relies on `updateStylesByID` not mutating `styleUpdates`.
7659 setValueForStyles(domElement, nextProp);
7660 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7661 var nextHtml = nextProp ? nextProp[HTML] : undefined;
7662 if (nextHtml != null) {
7663 setInnerHTML(domElement, nextHtml);
7664 }
7665 } else if (propKey === CHILDREN) {
7666 if (typeof nextProp === 'string') {
7667 // Avoid setting initial textContent when the text is empty. In IE11 setting
7668 // textContent on a <textarea> will cause the placeholder to not
7669 // show within the <textarea> until it has been focused and blurred again.
7670 // https://github.com/facebook/react/issues/6731#issuecomment-254874553
7671 var canSetTextContent = tag !== 'textarea' || nextProp !== '';
7672 if (canSetTextContent) {
7673 setTextContent(domElement, nextProp);
7674 }
7675 } else if (typeof nextProp === 'number') {
7676 setTextContent(domElement, '' + nextProp);
7677 }
7678 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
7679 // Noop
7680 } else if (propKey === AUTOFOCUS) {
7681 // We polyfill it separately on the client during commit.
7682 // We could have excluded it in the property list instead of
7683 // adding a special case here, but then it wouldn't be emitted
7684 // on server rendering (but we *do* want to emit it in SSR).
7685 } else if (registrationNameModules.hasOwnProperty(propKey)) {
7686 if (nextProp != null) {
7687 if (true && typeof nextProp !== 'function') {
7688 warnForInvalidEventListener(propKey, nextProp);
7689 }
7690 ensureListeningTo(rootContainerElement, propKey);
7691 }
7692 } else if (nextProp != null) {
7693 setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
7694 }
7695 }
7696}
7697
7698function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
7699 // TODO: Handle wasCustomComponentTag
7700 for (var i = 0; i < updatePayload.length; i += 2) {
7701 var propKey = updatePayload[i];
7702 var propValue = updatePayload[i + 1];
7703 if (propKey === STYLE$1) {
7704 setValueForStyles(domElement, propValue);
7705 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7706 setInnerHTML(domElement, propValue);
7707 } else if (propKey === CHILDREN) {
7708 setTextContent(domElement, propValue);
7709 } else {
7710 setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
7711 }
7712 }
7713}
7714
7715function createElement(type, props, rootContainerElement, parentNamespace) {
7716 var isCustomComponentTag = void 0;
7717
7718 // We create tags in the namespace of their parent container, except HTML
7719 // tags get no namespace.
7720 var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
7721 var domElement = void 0;
7722 var namespaceURI = parentNamespace;
7723 if (namespaceURI === HTML_NAMESPACE) {
7724 namespaceURI = getIntrinsicNamespace(type);
7725 }
7726 if (namespaceURI === HTML_NAMESPACE) {
7727 {
7728 isCustomComponentTag = isCustomComponent(type, props);
7729 // Should this check be gated by parent namespace? Not sure we want to
7730 // allow <SVG> or <mATH>.
7731 !(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;
7732 }
7733
7734 if (type === 'script') {
7735 // Create the script via .innerHTML so its "parser-inserted" flag is
7736 // set to true and it does not execute
7737 var div = ownerDocument.createElement('div');
7738 div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
7739 // This is guaranteed to yield a script element.
7740 var firstChild = div.firstChild;
7741 domElement = div.removeChild(firstChild);
7742 } else if (typeof props.is === 'string') {
7743 // $FlowIssue `createElement` should be updated for Web Components
7744 domElement = ownerDocument.createElement(type, { is: props.is });
7745 } else {
7746 // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
7747 // See discussion in https://github.com/facebook/react/pull/6896
7748 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
7749 domElement = ownerDocument.createElement(type);
7750 // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
7751 // attributes on `select`s needs to be added before `option`s are inserted.
7752 // This prevents:
7753 // - a bug where the `select` does not scroll to the correct option because singular
7754 // `select` elements automatically pick the first item #13222
7755 // - a bug where the `select` set the first item as selected despite the `size` attribute #14239
7756 // See https://github.com/facebook/react/issues/13222
7757 // and https://github.com/facebook/react/issues/14239
7758 if (type === 'select') {
7759 var node = domElement;
7760 if (props.multiple) {
7761 node.multiple = true;
7762 } else if (props.size) {
7763 // Setting a size greater than 1 causes a select to behave like `multiple=true`, where
7764 // it is possible that no option is selected.
7765 //
7766 // This is only necessary when a select in "single selection mode".
7767 node.size = props.size;
7768 }
7769 }
7770 }
7771 } else {
7772 domElement = ownerDocument.createElementNS(namespaceURI, type);
7773 }
7774
7775 {
7776 if (namespaceURI === HTML_NAMESPACE) {
7777 if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {
7778 warnedUnknownTags[type] = true;
7779 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);
7780 }
7781 }
7782 }
7783
7784 return domElement;
7785}
7786
7787function createTextNode(text, rootContainerElement) {
7788 return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
7789}
7790
7791function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
7792 var isCustomComponentTag = isCustomComponent(tag, rawProps);
7793 {
7794 validatePropertiesInDevelopment(tag, rawProps);
7795 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
7796 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
7797 didWarnShadyDOM = true;
7798 }
7799 }
7800
7801 // TODO: Make sure that we check isMounted before firing any of these events.
7802 var props = void 0;
7803 switch (tag) {
7804 case 'iframe':
7805 case 'object':
7806 trapBubbledEvent(TOP_LOAD, domElement);
7807 props = rawProps;
7808 break;
7809 case 'video':
7810 case 'audio':
7811 // Create listener for each media event
7812 for (var i = 0; i < mediaEventTypes.length; i++) {
7813 trapBubbledEvent(mediaEventTypes[i], domElement);
7814 }
7815 props = rawProps;
7816 break;
7817 case 'source':
7818 trapBubbledEvent(TOP_ERROR, domElement);
7819 props = rawProps;
7820 break;
7821 case 'img':
7822 case 'image':
7823 case 'link':
7824 trapBubbledEvent(TOP_ERROR, domElement);
7825 trapBubbledEvent(TOP_LOAD, domElement);
7826 props = rawProps;
7827 break;
7828 case 'form':
7829 trapBubbledEvent(TOP_RESET, domElement);
7830 trapBubbledEvent(TOP_SUBMIT, domElement);
7831 props = rawProps;
7832 break;
7833 case 'details':
7834 trapBubbledEvent(TOP_TOGGLE, domElement);
7835 props = rawProps;
7836 break;
7837 case 'input':
7838 initWrapperState(domElement, rawProps);
7839 props = getHostProps(domElement, rawProps);
7840 trapBubbledEvent(TOP_INVALID, domElement);
7841 // For controlled components we always need to ensure we're listening
7842 // to onChange. Even if there is no listener.
7843 ensureListeningTo(rootContainerElement, 'onChange');
7844 break;
7845 case 'option':
7846 validateProps(domElement, rawProps);
7847 props = getHostProps$1(domElement, rawProps);
7848 break;
7849 case 'select':
7850 initWrapperState$1(domElement, rawProps);
7851 props = getHostProps$2(domElement, rawProps);
7852 trapBubbledEvent(TOP_INVALID, domElement);
7853 // For controlled components we always need to ensure we're listening
7854 // to onChange. Even if there is no listener.
7855 ensureListeningTo(rootContainerElement, 'onChange');
7856 break;
7857 case 'textarea':
7858 initWrapperState$2(domElement, rawProps);
7859 props = getHostProps$3(domElement, rawProps);
7860 trapBubbledEvent(TOP_INVALID, domElement);
7861 // For controlled components we always need to ensure we're listening
7862 // to onChange. Even if there is no listener.
7863 ensureListeningTo(rootContainerElement, 'onChange');
7864 break;
7865 default:
7866 props = rawProps;
7867 }
7868
7869 assertValidProps(tag, props);
7870
7871 setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
7872
7873 switch (tag) {
7874 case 'input':
7875 // TODO: Make sure we check if this is still unmounted or do any clean
7876 // up necessary since we never stop tracking anymore.
7877 track(domElement);
7878 postMountWrapper(domElement, rawProps, false);
7879 break;
7880 case 'textarea':
7881 // TODO: Make sure we check if this is still unmounted or do any clean
7882 // up necessary since we never stop tracking anymore.
7883 track(domElement);
7884 postMountWrapper$3(domElement, rawProps);
7885 break;
7886 case 'option':
7887 postMountWrapper$1(domElement, rawProps);
7888 break;
7889 case 'select':
7890 postMountWrapper$2(domElement, rawProps);
7891 break;
7892 default:
7893 if (typeof props.onClick === 'function') {
7894 // TODO: This cast may not be sound for SVG, MathML or custom elements.
7895 trapClickOnNonInteractiveElement(domElement);
7896 }
7897 break;
7898 }
7899}
7900
7901// Calculate the diff between the two objects.
7902function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
7903 {
7904 validatePropertiesInDevelopment(tag, nextRawProps);
7905 }
7906
7907 var updatePayload = null;
7908
7909 var lastProps = void 0;
7910 var nextProps = void 0;
7911 switch (tag) {
7912 case 'input':
7913 lastProps = getHostProps(domElement, lastRawProps);
7914 nextProps = getHostProps(domElement, nextRawProps);
7915 updatePayload = [];
7916 break;
7917 case 'option':
7918 lastProps = getHostProps$1(domElement, lastRawProps);
7919 nextProps = getHostProps$1(domElement, nextRawProps);
7920 updatePayload = [];
7921 break;
7922 case 'select':
7923 lastProps = getHostProps$2(domElement, lastRawProps);
7924 nextProps = getHostProps$2(domElement, nextRawProps);
7925 updatePayload = [];
7926 break;
7927 case 'textarea':
7928 lastProps = getHostProps$3(domElement, lastRawProps);
7929 nextProps = getHostProps$3(domElement, nextRawProps);
7930 updatePayload = [];
7931 break;
7932 default:
7933 lastProps = lastRawProps;
7934 nextProps = nextRawProps;
7935 if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
7936 // TODO: This cast may not be sound for SVG, MathML or custom elements.
7937 trapClickOnNonInteractiveElement(domElement);
7938 }
7939 break;
7940 }
7941
7942 assertValidProps(tag, nextProps);
7943
7944 var propKey = void 0;
7945 var styleName = void 0;
7946 var styleUpdates = null;
7947 for (propKey in lastProps) {
7948 if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
7949 continue;
7950 }
7951 if (propKey === STYLE$1) {
7952 var lastStyle = lastProps[propKey];
7953 for (styleName in lastStyle) {
7954 if (lastStyle.hasOwnProperty(styleName)) {
7955 if (!styleUpdates) {
7956 styleUpdates = {};
7957 }
7958 styleUpdates[styleName] = '';
7959 }
7960 }
7961 } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) {
7962 // Noop. This is handled by the clear text mechanism.
7963 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
7964 // Noop
7965 } else if (propKey === AUTOFOCUS) {
7966 // Noop. It doesn't work on updates anyway.
7967 } else if (registrationNameModules.hasOwnProperty(propKey)) {
7968 // This is a special case. If any listener updates we need to ensure
7969 // that the "current" fiber pointer gets updated so we need a commit
7970 // to update this element.
7971 if (!updatePayload) {
7972 updatePayload = [];
7973 }
7974 } else {
7975 // For all other deleted properties we add it to the queue. We use
7976 // the whitelist in the commit phase instead.
7977 (updatePayload = updatePayload || []).push(propKey, null);
7978 }
7979 }
7980 for (propKey in nextProps) {
7981 var nextProp = nextProps[propKey];
7982 var lastProp = lastProps != null ? lastProps[propKey] : undefined;
7983 if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
7984 continue;
7985 }
7986 if (propKey === STYLE$1) {
7987 {
7988 if (nextProp) {
7989 // Freeze the next style object so that we can assume it won't be
7990 // mutated. We have already warned for this in the past.
7991 Object.freeze(nextProp);
7992 }
7993 }
7994 if (lastProp) {
7995 // Unset styles on `lastProp` but not on `nextProp`.
7996 for (styleName in lastProp) {
7997 if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
7998 if (!styleUpdates) {
7999 styleUpdates = {};
8000 }
8001 styleUpdates[styleName] = '';
8002 }
8003 }
8004 // Update styles that changed since `lastProp`.
8005 for (styleName in nextProp) {
8006 if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
8007 if (!styleUpdates) {
8008 styleUpdates = {};
8009 }
8010 styleUpdates[styleName] = nextProp[styleName];
8011 }
8012 }
8013 } else {
8014 // Relies on `updateStylesByID` not mutating `styleUpdates`.
8015 if (!styleUpdates) {
8016 if (!updatePayload) {
8017 updatePayload = [];
8018 }
8019 updatePayload.push(propKey, styleUpdates);
8020 }
8021 styleUpdates = nextProp;
8022 }
8023 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8024 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8025 var lastHtml = lastProp ? lastProp[HTML] : undefined;
8026 if (nextHtml != null) {
8027 if (lastHtml !== nextHtml) {
8028 (updatePayload = updatePayload || []).push(propKey, '' + nextHtml);
8029 }
8030 } else {
8031 // TODO: It might be too late to clear this if we have children
8032 // inserted already.
8033 }
8034 } else if (propKey === CHILDREN) {
8035 if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {
8036 (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
8037 }
8038 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
8039 // Noop
8040 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8041 if (nextProp != null) {
8042 // We eagerly listen to this even though we haven't committed yet.
8043 if (true && typeof nextProp !== 'function') {
8044 warnForInvalidEventListener(propKey, nextProp);
8045 }
8046 ensureListeningTo(rootContainerElement, propKey);
8047 }
8048 if (!updatePayload && lastProp !== nextProp) {
8049 // This is a special case. If any listener updates we need to ensure
8050 // that the "current" props pointer gets updated so we need a commit
8051 // to update this element.
8052 updatePayload = [];
8053 }
8054 } else {
8055 // For any other property we always add it to the queue and then we
8056 // filter it out using the whitelist during the commit.
8057 (updatePayload = updatePayload || []).push(propKey, nextProp);
8058 }
8059 }
8060 if (styleUpdates) {
8061 {
8062 validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE$1]);
8063 }
8064 (updatePayload = updatePayload || []).push(STYLE$1, styleUpdates);
8065 }
8066 return updatePayload;
8067}
8068
8069// Apply the diff.
8070function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
8071 // Update checked *before* name.
8072 // In the middle of an update, it is possible to have multiple checked.
8073 // When a checked radio tries to change name, browser makes another radio's checked false.
8074 if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
8075 updateChecked(domElement, nextRawProps);
8076 }
8077
8078 var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
8079 var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
8080 // Apply the diff.
8081 updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag);
8082
8083 // TODO: Ensure that an update gets scheduled if any of the special props
8084 // changed.
8085 switch (tag) {
8086 case 'input':
8087 // Update the wrapper around inputs *after* updating props. This has to
8088 // happen after `updateDOMProperties`. Otherwise HTML5 input validations
8089 // raise warnings and prevent the new value from being assigned.
8090 updateWrapper(domElement, nextRawProps);
8091 break;
8092 case 'textarea':
8093 updateWrapper$1(domElement, nextRawProps);
8094 break;
8095 case 'select':
8096 // <select> value update needs to occur after <option> children
8097 // reconciliation
8098 postUpdateWrapper(domElement, nextRawProps);
8099 break;
8100 }
8101}
8102
8103function getPossibleStandardName(propName) {
8104 {
8105 var lowerCasedName = propName.toLowerCase();
8106 if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
8107 return null;
8108 }
8109 return possibleStandardNames[lowerCasedName] || null;
8110 }
8111 return null;
8112}
8113
8114function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {
8115 var isCustomComponentTag = void 0;
8116 var extraAttributeNames = void 0;
8117
8118 {
8119 suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING$1] === true;
8120 isCustomComponentTag = isCustomComponent(tag, rawProps);
8121 validatePropertiesInDevelopment(tag, rawProps);
8122 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
8123 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
8124 didWarnShadyDOM = true;
8125 }
8126 }
8127
8128 // TODO: Make sure that we check isMounted before firing any of these events.
8129 switch (tag) {
8130 case 'iframe':
8131 case 'object':
8132 trapBubbledEvent(TOP_LOAD, domElement);
8133 break;
8134 case 'video':
8135 case 'audio':
8136 // Create listener for each media event
8137 for (var i = 0; i < mediaEventTypes.length; i++) {
8138 trapBubbledEvent(mediaEventTypes[i], domElement);
8139 }
8140 break;
8141 case 'source':
8142 trapBubbledEvent(TOP_ERROR, domElement);
8143 break;
8144 case 'img':
8145 case 'image':
8146 case 'link':
8147 trapBubbledEvent(TOP_ERROR, domElement);
8148 trapBubbledEvent(TOP_LOAD, domElement);
8149 break;
8150 case 'form':
8151 trapBubbledEvent(TOP_RESET, domElement);
8152 trapBubbledEvent(TOP_SUBMIT, domElement);
8153 break;
8154 case 'details':
8155 trapBubbledEvent(TOP_TOGGLE, domElement);
8156 break;
8157 case 'input':
8158 initWrapperState(domElement, rawProps);
8159 trapBubbledEvent(TOP_INVALID, domElement);
8160 // For controlled components we always need to ensure we're listening
8161 // to onChange. Even if there is no listener.
8162 ensureListeningTo(rootContainerElement, 'onChange');
8163 break;
8164 case 'option':
8165 validateProps(domElement, rawProps);
8166 break;
8167 case 'select':
8168 initWrapperState$1(domElement, rawProps);
8169 trapBubbledEvent(TOP_INVALID, domElement);
8170 // For controlled components we always need to ensure we're listening
8171 // to onChange. Even if there is no listener.
8172 ensureListeningTo(rootContainerElement, 'onChange');
8173 break;
8174 case 'textarea':
8175 initWrapperState$2(domElement, rawProps);
8176 trapBubbledEvent(TOP_INVALID, domElement);
8177 // For controlled components we always need to ensure we're listening
8178 // to onChange. Even if there is no listener.
8179 ensureListeningTo(rootContainerElement, 'onChange');
8180 break;
8181 }
8182
8183 assertValidProps(tag, rawProps);
8184
8185 {
8186 extraAttributeNames = new Set();
8187 var attributes = domElement.attributes;
8188 for (var _i = 0; _i < attributes.length; _i++) {
8189 var name = attributes[_i].name.toLowerCase();
8190 switch (name) {
8191 // Built-in SSR attribute is whitelisted
8192 case 'data-reactroot':
8193 break;
8194 // Controlled attributes are not validated
8195 // TODO: Only ignore them on controlled tags.
8196 case 'value':
8197 break;
8198 case 'checked':
8199 break;
8200 case 'selected':
8201 break;
8202 default:
8203 // Intentionally use the original name.
8204 // See discussion in https://github.com/facebook/react/pull/10676.
8205 extraAttributeNames.add(attributes[_i].name);
8206 }
8207 }
8208 }
8209
8210 var updatePayload = null;
8211 for (var propKey in rawProps) {
8212 if (!rawProps.hasOwnProperty(propKey)) {
8213 continue;
8214 }
8215 var nextProp = rawProps[propKey];
8216 if (propKey === CHILDREN) {
8217 // For text content children we compare against textContent. This
8218 // might match additional HTML that is hidden when we read it using
8219 // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
8220 // satisfies our requirement. Our requirement is not to produce perfect
8221 // HTML and attributes. Ideally we should preserve structure but it's
8222 // ok not to if the visible content is still enough to indicate what
8223 // even listeners these nodes might be wired up to.
8224 // TODO: Warn if there is more than a single textNode as a child.
8225 // TODO: Should we use domElement.firstChild.nodeValue to compare?
8226 if (typeof nextProp === 'string') {
8227 if (domElement.textContent !== nextProp) {
8228 if (true && !suppressHydrationWarning) {
8229 warnForTextDifference(domElement.textContent, nextProp);
8230 }
8231 updatePayload = [CHILDREN, nextProp];
8232 }
8233 } else if (typeof nextProp === 'number') {
8234 if (domElement.textContent !== '' + nextProp) {
8235 if (true && !suppressHydrationWarning) {
8236 warnForTextDifference(domElement.textContent, nextProp);
8237 }
8238 updatePayload = [CHILDREN, '' + nextProp];
8239 }
8240 }
8241 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8242 if (nextProp != null) {
8243 if (true && typeof nextProp !== 'function') {
8244 warnForInvalidEventListener(propKey, nextProp);
8245 }
8246 ensureListeningTo(rootContainerElement, propKey);
8247 }
8248 } else if (true &&
8249 // Convince Flow we've calculated it (it's DEV-only in this method.)
8250 typeof isCustomComponentTag === 'boolean') {
8251 // Validate that the properties correspond to their expected values.
8252 var serverValue = void 0;
8253 var propertyInfo = getPropertyInfo(propKey);
8254 if (suppressHydrationWarning) {
8255 // Don't bother comparing. We're ignoring all these warnings.
8256 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1 ||
8257 // Controlled attributes are not validated
8258 // TODO: Only ignore them on controlled tags.
8259 propKey === 'value' || propKey === 'checked' || propKey === 'selected') {
8260 // Noop
8261 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8262 var serverHTML = domElement.innerHTML;
8263 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8264 var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : '');
8265 if (expectedHTML !== serverHTML) {
8266 warnForPropDifference(propKey, serverHTML, expectedHTML);
8267 }
8268 } else if (propKey === STYLE$1) {
8269 // $FlowFixMe - Should be inferred as not undefined.
8270 extraAttributeNames.delete(propKey);
8271
8272 if (canDiffStyleForHydrationWarning) {
8273 var expectedStyle = createDangerousStringForStyles(nextProp);
8274 serverValue = domElement.getAttribute('style');
8275 if (expectedStyle !== serverValue) {
8276 warnForPropDifference(propKey, serverValue, expectedStyle);
8277 }
8278 }
8279 } else if (isCustomComponentTag) {
8280 // $FlowFixMe - Should be inferred as not undefined.
8281 extraAttributeNames.delete(propKey.toLowerCase());
8282 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8283
8284 if (nextProp !== serverValue) {
8285 warnForPropDifference(propKey, serverValue, nextProp);
8286 }
8287 } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
8288 var isMismatchDueToBadCasing = false;
8289 if (propertyInfo !== null) {
8290 // $FlowFixMe - Should be inferred as not undefined.
8291 extraAttributeNames.delete(propertyInfo.attributeName);
8292 serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
8293 } else {
8294 var ownNamespace = parentNamespace;
8295 if (ownNamespace === HTML_NAMESPACE) {
8296 ownNamespace = getIntrinsicNamespace(tag);
8297 }
8298 if (ownNamespace === HTML_NAMESPACE) {
8299 // $FlowFixMe - Should be inferred as not undefined.
8300 extraAttributeNames.delete(propKey.toLowerCase());
8301 } else {
8302 var standardName = getPossibleStandardName(propKey);
8303 if (standardName !== null && standardName !== propKey) {
8304 // If an SVG prop is supplied with bad casing, it will
8305 // be successfully parsed from HTML, but will produce a mismatch
8306 // (and would be incorrectly rendered on the client).
8307 // However, we already warn about bad casing elsewhere.
8308 // So we'll skip the misleading extra mismatch warning in this case.
8309 isMismatchDueToBadCasing = true;
8310 // $FlowFixMe - Should be inferred as not undefined.
8311 extraAttributeNames.delete(standardName);
8312 }
8313 // $FlowFixMe - Should be inferred as not undefined.
8314 extraAttributeNames.delete(propKey);
8315 }
8316 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8317 }
8318
8319 if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
8320 warnForPropDifference(propKey, serverValue, nextProp);
8321 }
8322 }
8323 }
8324 }
8325
8326 {
8327 // $FlowFixMe - Should be inferred as not undefined.
8328 if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
8329 // $FlowFixMe - Should be inferred as not undefined.
8330 warnForExtraAttributes(extraAttributeNames);
8331 }
8332 }
8333
8334 switch (tag) {
8335 case 'input':
8336 // TODO: Make sure we check if this is still unmounted or do any clean
8337 // up necessary since we never stop tracking anymore.
8338 track(domElement);
8339 postMountWrapper(domElement, rawProps, true);
8340 break;
8341 case 'textarea':
8342 // TODO: Make sure we check if this is still unmounted or do any clean
8343 // up necessary since we never stop tracking anymore.
8344 track(domElement);
8345 postMountWrapper$3(domElement, rawProps);
8346 break;
8347 case 'select':
8348 case 'option':
8349 // For input and textarea we current always set the value property at
8350 // post mount to force it to diverge from attributes. However, for
8351 // option and select we don't quite do the same thing and select
8352 // is not resilient to the DOM state changing so we don't do that here.
8353 // TODO: Consider not doing this for input and textarea.
8354 break;
8355 default:
8356 if (typeof rawProps.onClick === 'function') {
8357 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8358 trapClickOnNonInteractiveElement(domElement);
8359 }
8360 break;
8361 }
8362
8363 return updatePayload;
8364}
8365
8366function diffHydratedText(textNode, text) {
8367 var isDifferent = textNode.nodeValue !== text;
8368 return isDifferent;
8369}
8370
8371function warnForUnmatchedText(textNode, text) {
8372 {
8373 warnForTextDifference(textNode.nodeValue, text);
8374 }
8375}
8376
8377function warnForDeletedHydratableElement(parentNode, child) {
8378 {
8379 if (didWarnInvalidHydration) {
8380 return;
8381 }
8382 didWarnInvalidHydration = true;
8383 warningWithoutStack$1(false, 'Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
8384 }
8385}
8386
8387function warnForDeletedHydratableText(parentNode, child) {
8388 {
8389 if (didWarnInvalidHydration) {
8390 return;
8391 }
8392 didWarnInvalidHydration = true;
8393 warningWithoutStack$1(false, 'Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
8394 }
8395}
8396
8397function warnForInsertedHydratedElement(parentNode, tag, props) {
8398 {
8399 if (didWarnInvalidHydration) {
8400 return;
8401 }
8402 didWarnInvalidHydration = true;
8403 warningWithoutStack$1(false, 'Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
8404 }
8405}
8406
8407function warnForInsertedHydratedText(parentNode, text) {
8408 {
8409 if (text === '') {
8410 // We expect to insert empty text nodes since they're not represented in
8411 // the HTML.
8412 // TODO: Remove this special case if we can just avoid inserting empty
8413 // text nodes.
8414 return;
8415 }
8416 if (didWarnInvalidHydration) {
8417 return;
8418 }
8419 didWarnInvalidHydration = true;
8420 warningWithoutStack$1(false, 'Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
8421 }
8422}
8423
8424function restoreControlledState$1(domElement, tag, props) {
8425 switch (tag) {
8426 case 'input':
8427 restoreControlledState(domElement, props);
8428 return;
8429 case 'textarea':
8430 restoreControlledState$3(domElement, props);
8431 return;
8432 case 'select':
8433 restoreControlledState$2(domElement, props);
8434 return;
8435 }
8436}
8437
8438// TODO: direct imports like some-package/src/* are bad. Fix me.
8439var validateDOMNesting = function () {};
8440var updatedAncestorInfo = function () {};
8441
8442{
8443 // This validation code was written based on the HTML5 parsing spec:
8444 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
8445 //
8446 // Note: this does not catch all invalid nesting, nor does it try to (as it's
8447 // not clear what practical benefit doing so provides); instead, we warn only
8448 // for cases where the parser will give a parse tree differing from what React
8449 // intended. For example, <b><div></div></b> is invalid but we don't warn
8450 // because it still parses correctly; we do warn for other cases like nested
8451 // <p> tags where the beginning of the second element implicitly closes the
8452 // first, causing a confusing mess.
8453
8454 // https://html.spec.whatwg.org/multipage/syntax.html#special
8455 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'];
8456
8457 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
8458 var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template',
8459
8460 // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
8461 // TODO: Distinguish by namespace here -- for <title>, including it here
8462 // errs on the side of fewer warnings
8463 'foreignObject', 'desc', 'title'];
8464
8465 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
8466 var buttonScopeTags = inScopeTags.concat(['button']);
8467
8468 // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
8469 var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
8470
8471 var emptyAncestorInfo = {
8472 current: null,
8473
8474 formTag: null,
8475 aTagInScope: null,
8476 buttonTagInScope: null,
8477 nobrTagInScope: null,
8478 pTagInButtonScope: null,
8479
8480 listItemTagAutoclosing: null,
8481 dlItemTagAutoclosing: null
8482 };
8483
8484 updatedAncestorInfo = function (oldInfo, tag) {
8485 var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
8486 var info = { tag: tag };
8487
8488 if (inScopeTags.indexOf(tag) !== -1) {
8489 ancestorInfo.aTagInScope = null;
8490 ancestorInfo.buttonTagInScope = null;
8491 ancestorInfo.nobrTagInScope = null;
8492 }
8493 if (buttonScopeTags.indexOf(tag) !== -1) {
8494 ancestorInfo.pTagInButtonScope = null;
8495 }
8496
8497 // See rules for 'li', 'dd', 'dt' start tags in
8498 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
8499 if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
8500 ancestorInfo.listItemTagAutoclosing = null;
8501 ancestorInfo.dlItemTagAutoclosing = null;
8502 }
8503
8504 ancestorInfo.current = info;
8505
8506 if (tag === 'form') {
8507 ancestorInfo.formTag = info;
8508 }
8509 if (tag === 'a') {
8510 ancestorInfo.aTagInScope = info;
8511 }
8512 if (tag === 'button') {
8513 ancestorInfo.buttonTagInScope = info;
8514 }
8515 if (tag === 'nobr') {
8516 ancestorInfo.nobrTagInScope = info;
8517 }
8518 if (tag === 'p') {
8519 ancestorInfo.pTagInButtonScope = info;
8520 }
8521 if (tag === 'li') {
8522 ancestorInfo.listItemTagAutoclosing = info;
8523 }
8524 if (tag === 'dd' || tag === 'dt') {
8525 ancestorInfo.dlItemTagAutoclosing = info;
8526 }
8527
8528 return ancestorInfo;
8529 };
8530
8531 /**
8532 * Returns whether
8533 */
8534 var isTagValidWithParent = function (tag, parentTag) {
8535 // First, let's check if we're in an unusual parsing mode...
8536 switch (parentTag) {
8537 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
8538 case 'select':
8539 return tag === 'option' || tag === 'optgroup' || tag === '#text';
8540 case 'optgroup':
8541 return tag === 'option' || tag === '#text';
8542 // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
8543 // but
8544 case 'option':
8545 return tag === '#text';
8546 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
8547 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
8548 // No special behavior since these rules fall back to "in body" mode for
8549 // all except special table nodes which cause bad parsing behavior anyway.
8550
8551 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
8552 case 'tr':
8553 return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
8554 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
8555 case 'tbody':
8556 case 'thead':
8557 case 'tfoot':
8558 return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
8559 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
8560 case 'colgroup':
8561 return tag === 'col' || tag === 'template';
8562 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
8563 case 'table':
8564 return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
8565 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
8566 case 'head':
8567 return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
8568 // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
8569 case 'html':
8570 return tag === 'head' || tag === 'body';
8571 case '#document':
8572 return tag === 'html';
8573 }
8574
8575 // Probably in the "in body" parsing mode, so we outlaw only tag combos
8576 // where the parsing rules cause implicit opens or closes to be added.
8577 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
8578 switch (tag) {
8579 case 'h1':
8580 case 'h2':
8581 case 'h3':
8582 case 'h4':
8583 case 'h5':
8584 case 'h6':
8585 return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
8586
8587 case 'rp':
8588 case 'rt':
8589 return impliedEndTags.indexOf(parentTag) === -1;
8590
8591 case 'body':
8592 case 'caption':
8593 case 'col':
8594 case 'colgroup':
8595 case 'frame':
8596 case 'head':
8597 case 'html':
8598 case 'tbody':
8599 case 'td':
8600 case 'tfoot':
8601 case 'th':
8602 case 'thead':
8603 case 'tr':
8604 // These tags are only valid with a few parents that have special child
8605 // parsing rules -- if we're down here, then none of those matched and
8606 // so we allow it only if we don't know what the parent is, as all other
8607 // cases are invalid.
8608 return parentTag == null;
8609 }
8610
8611 return true;
8612 };
8613
8614 /**
8615 * Returns whether
8616 */
8617 var findInvalidAncestorForTag = function (tag, ancestorInfo) {
8618 switch (tag) {
8619 case 'address':
8620 case 'article':
8621 case 'aside':
8622 case 'blockquote':
8623 case 'center':
8624 case 'details':
8625 case 'dialog':
8626 case 'dir':
8627 case 'div':
8628 case 'dl':
8629 case 'fieldset':
8630 case 'figcaption':
8631 case 'figure':
8632 case 'footer':
8633 case 'header':
8634 case 'hgroup':
8635 case 'main':
8636 case 'menu':
8637 case 'nav':
8638 case 'ol':
8639 case 'p':
8640 case 'section':
8641 case 'summary':
8642 case 'ul':
8643 case 'pre':
8644 case 'listing':
8645 case 'table':
8646 case 'hr':
8647 case 'xmp':
8648 case 'h1':
8649 case 'h2':
8650 case 'h3':
8651 case 'h4':
8652 case 'h5':
8653 case 'h6':
8654 return ancestorInfo.pTagInButtonScope;
8655
8656 case 'form':
8657 return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
8658
8659 case 'li':
8660 return ancestorInfo.listItemTagAutoclosing;
8661
8662 case 'dd':
8663 case 'dt':
8664 return ancestorInfo.dlItemTagAutoclosing;
8665
8666 case 'button':
8667 return ancestorInfo.buttonTagInScope;
8668
8669 case 'a':
8670 // Spec says something about storing a list of markers, but it sounds
8671 // equivalent to this check.
8672 return ancestorInfo.aTagInScope;
8673
8674 case 'nobr':
8675 return ancestorInfo.nobrTagInScope;
8676 }
8677
8678 return null;
8679 };
8680
8681 var didWarn = {};
8682
8683 validateDOMNesting = function (childTag, childText, ancestorInfo) {
8684 ancestorInfo = ancestorInfo || emptyAncestorInfo;
8685 var parentInfo = ancestorInfo.current;
8686 var parentTag = parentInfo && parentInfo.tag;
8687
8688 if (childText != null) {
8689 !(childTag == null) ? warningWithoutStack$1(false, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0;
8690 childTag = '#text';
8691 }
8692
8693 var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
8694 var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
8695 var invalidParentOrAncestor = invalidParent || invalidAncestor;
8696 if (!invalidParentOrAncestor) {
8697 return;
8698 }
8699
8700 var ancestorTag = invalidParentOrAncestor.tag;
8701 var addendum = getCurrentFiberStackInDev();
8702
8703 var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;
8704 if (didWarn[warnKey]) {
8705 return;
8706 }
8707 didWarn[warnKey] = true;
8708
8709 var tagDisplayName = childTag;
8710 var whitespaceInfo = '';
8711 if (childTag === '#text') {
8712 if (/\S/.test(childText)) {
8713 tagDisplayName = 'Text nodes';
8714 } else {
8715 tagDisplayName = 'Whitespace text nodes';
8716 whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
8717 }
8718 } else {
8719 tagDisplayName = '<' + childTag + '>';
8720 }
8721
8722 if (invalidParent) {
8723 var info = '';
8724 if (ancestorTag === 'table' && childTag === 'tr') {
8725 info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.';
8726 }
8727 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info, addendum);
8728 } else {
8729 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.%s', tagDisplayName, ancestorTag, addendum);
8730 }
8731 };
8732}
8733
8734var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
8735
8736var _ReactInternals$Sched = ReactInternals$1.Scheduler;
8737var unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback;
8738var unstable_now = _ReactInternals$Sched.unstable_now;
8739var unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback;
8740var unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield;
8741var unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode;
8742var unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority;
8743var unstable_next = _ReactInternals$Sched.unstable_next;
8744var unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution;
8745var unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution;
8746var unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel;
8747var unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority;
8748var unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority;
8749var unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority;
8750var unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority;
8751var unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority;
8752
8753// Renderers that don't support persistence
8754// can re-export everything from this module.
8755
8756function shim() {
8757 invariant(false, 'The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.');
8758}
8759
8760// Persistence (when unsupported)
8761var supportsPersistence = false;
8762var cloneInstance = shim;
8763var createContainerChildSet = shim;
8764var appendChildToContainerChildSet = shim;
8765var finalizeContainerChildren = shim;
8766var replaceContainerChildren = shim;
8767var cloneHiddenInstance = shim;
8768var cloneUnhiddenInstance = shim;
8769var createHiddenTextInstance = shim;
8770
8771var SUPPRESS_HYDRATION_WARNING = void 0;
8772{
8773 SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
8774}
8775
8776var SUSPENSE_START_DATA = '$';
8777var SUSPENSE_END_DATA = '/$';
8778
8779var STYLE = 'style';
8780
8781var eventsEnabled = null;
8782var selectionInformation = null;
8783
8784function shouldAutoFocusHostComponent(type, props) {
8785 switch (type) {
8786 case 'button':
8787 case 'input':
8788 case 'select':
8789 case 'textarea':
8790 return !!props.autoFocus;
8791 }
8792 return false;
8793}
8794
8795function getRootHostContext(rootContainerInstance) {
8796 var type = void 0;
8797 var namespace = void 0;
8798 var nodeType = rootContainerInstance.nodeType;
8799 switch (nodeType) {
8800 case DOCUMENT_NODE:
8801 case DOCUMENT_FRAGMENT_NODE:
8802 {
8803 type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
8804 var root = rootContainerInstance.documentElement;
8805 namespace = root ? root.namespaceURI : getChildNamespace(null, '');
8806 break;
8807 }
8808 default:
8809 {
8810 var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
8811 var ownNamespace = container.namespaceURI || null;
8812 type = container.tagName;
8813 namespace = getChildNamespace(ownNamespace, type);
8814 break;
8815 }
8816 }
8817 {
8818 var validatedTag = type.toLowerCase();
8819 var _ancestorInfo = updatedAncestorInfo(null, validatedTag);
8820 return { namespace: namespace, ancestorInfo: _ancestorInfo };
8821 }
8822 return namespace;
8823}
8824
8825function getChildHostContext(parentHostContext, type, rootContainerInstance) {
8826 {
8827 var parentHostContextDev = parentHostContext;
8828 var _namespace = getChildNamespace(parentHostContextDev.namespace, type);
8829 var _ancestorInfo2 = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
8830 return { namespace: _namespace, ancestorInfo: _ancestorInfo2 };
8831 }
8832 var parentNamespace = parentHostContext;
8833 return getChildNamespace(parentNamespace, type);
8834}
8835
8836function getPublicInstance(instance) {
8837 return instance;
8838}
8839
8840function prepareForCommit(containerInfo) {
8841 eventsEnabled = isEnabled();
8842 selectionInformation = getSelectionInformation();
8843 setEnabled(false);
8844}
8845
8846function resetAfterCommit(containerInfo) {
8847 restoreSelection(selectionInformation);
8848 selectionInformation = null;
8849 setEnabled(eventsEnabled);
8850 eventsEnabled = null;
8851}
8852
8853function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
8854 var parentNamespace = void 0;
8855 {
8856 // TODO: take namespace into account when validating.
8857 var hostContextDev = hostContext;
8858 validateDOMNesting(type, null, hostContextDev.ancestorInfo);
8859 if (typeof props.children === 'string' || typeof props.children === 'number') {
8860 var string = '' + props.children;
8861 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
8862 validateDOMNesting(null, string, ownAncestorInfo);
8863 }
8864 parentNamespace = hostContextDev.namespace;
8865 }
8866 var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
8867 precacheFiberNode(internalInstanceHandle, domElement);
8868 updateFiberProps(domElement, props);
8869 return domElement;
8870}
8871
8872function appendInitialChild(parentInstance, child) {
8873 parentInstance.appendChild(child);
8874}
8875
8876function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
8877 setInitialProperties(domElement, type, props, rootContainerInstance);
8878 return shouldAutoFocusHostComponent(type, props);
8879}
8880
8881function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
8882 {
8883 var hostContextDev = hostContext;
8884 if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
8885 var string = '' + newProps.children;
8886 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
8887 validateDOMNesting(null, string, ownAncestorInfo);
8888 }
8889 }
8890 return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);
8891}
8892
8893function shouldSetTextContent(type, props) {
8894 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;
8895}
8896
8897function shouldDeprioritizeSubtree(type, props) {
8898 return !!props.hidden;
8899}
8900
8901function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
8902 {
8903 var hostContextDev = hostContext;
8904 validateDOMNesting(null, text, hostContextDev.ancestorInfo);
8905 }
8906 var textNode = createTextNode(text, rootContainerInstance);
8907 precacheFiberNode(internalInstanceHandle, textNode);
8908 return textNode;
8909}
8910
8911var isPrimaryRenderer = true;
8912// This initialization code may run even on server environments
8913// if a component just imports ReactDOM (e.g. for findDOMNode).
8914// Some environments might not have setTimeout or clearTimeout.
8915var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
8916var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
8917var noTimeout = -1;
8918var schedulePassiveEffects = unstable_scheduleCallback;
8919var cancelPassiveEffects = unstable_cancelCallback;
8920
8921// -------------------
8922// Mutation
8923// -------------------
8924
8925var supportsMutation = true;
8926
8927function commitMount(domElement, type, newProps, internalInstanceHandle) {
8928 // Despite the naming that might imply otherwise, this method only
8929 // fires if there is an `Update` effect scheduled during mounting.
8930 // This happens if `finalizeInitialChildren` returns `true` (which it
8931 // does to implement the `autoFocus` attribute on the client). But
8932 // there are also other cases when this might happen (such as patching
8933 // up text content during hydration mismatch). So we'll check this again.
8934 if (shouldAutoFocusHostComponent(type, newProps)) {
8935 domElement.focus();
8936 }
8937}
8938
8939function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
8940 // Update the props handle so that we know which props are the ones with
8941 // with current event handlers.
8942 updateFiberProps(domElement, newProps);
8943 // Apply the diff to the DOM node.
8944 updateProperties(domElement, updatePayload, type, oldProps, newProps);
8945}
8946
8947function resetTextContent(domElement) {
8948 setTextContent(domElement, '');
8949}
8950
8951function commitTextUpdate(textInstance, oldText, newText) {
8952 textInstance.nodeValue = newText;
8953}
8954
8955function appendChild(parentInstance, child) {
8956 parentInstance.appendChild(child);
8957}
8958
8959function appendChildToContainer(container, child) {
8960 var parentNode = void 0;
8961 if (container.nodeType === COMMENT_NODE) {
8962 parentNode = container.parentNode;
8963 parentNode.insertBefore(child, container);
8964 } else {
8965 parentNode = container;
8966 parentNode.appendChild(child);
8967 }
8968 // This container might be used for a portal.
8969 // If something inside a portal is clicked, that click should bubble
8970 // through the React tree. However, on Mobile Safari the click would
8971 // never bubble through the *DOM* tree unless an ancestor with onclick
8972 // event exists. So we wouldn't see it and dispatch it.
8973 // This is why we ensure that non React root containers have inline onclick
8974 // defined.
8975 // https://github.com/facebook/react/issues/11918
8976 var reactRootContainer = container._reactRootContainer;
8977 if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
8978 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8979 trapClickOnNonInteractiveElement(parentNode);
8980 }
8981}
8982
8983function insertBefore(parentInstance, child, beforeChild) {
8984 parentInstance.insertBefore(child, beforeChild);
8985}
8986
8987function insertInContainerBefore(container, child, beforeChild) {
8988 if (container.nodeType === COMMENT_NODE) {
8989 container.parentNode.insertBefore(child, beforeChild);
8990 } else {
8991 container.insertBefore(child, beforeChild);
8992 }
8993}
8994
8995function removeChild(parentInstance, child) {
8996 parentInstance.removeChild(child);
8997}
8998
8999function removeChildFromContainer(container, child) {
9000 if (container.nodeType === COMMENT_NODE) {
9001 container.parentNode.removeChild(child);
9002 } else {
9003 container.removeChild(child);
9004 }
9005}
9006
9007function clearSuspenseBoundary(parentInstance, suspenseInstance) {
9008 var node = suspenseInstance;
9009 // Delete all nodes within this suspense boundary.
9010 // There might be nested nodes so we need to keep track of how
9011 // deep we are and only break out when we're back on top.
9012 var depth = 0;
9013 do {
9014 var nextNode = node.nextSibling;
9015 parentInstance.removeChild(node);
9016 if (nextNode && nextNode.nodeType === COMMENT_NODE) {
9017 var data = nextNode.data;
9018 if (data === SUSPENSE_END_DATA) {
9019 if (depth === 0) {
9020 parentInstance.removeChild(nextNode);
9021 return;
9022 } else {
9023 depth--;
9024 }
9025 } else if (data === SUSPENSE_START_DATA) {
9026 depth++;
9027 }
9028 }
9029 node = nextNode;
9030 } while (node);
9031 // TODO: Warn, we didn't find the end comment boundary.
9032}
9033
9034function clearSuspenseBoundaryFromContainer(container, suspenseInstance) {
9035 if (container.nodeType === COMMENT_NODE) {
9036 clearSuspenseBoundary(container.parentNode, suspenseInstance);
9037 } else if (container.nodeType === ELEMENT_NODE) {
9038 clearSuspenseBoundary(container, suspenseInstance);
9039 } else {
9040 // Document nodes should never contain suspense boundaries.
9041 }
9042}
9043
9044function hideInstance(instance) {
9045 // TODO: Does this work for all element types? What about MathML? Should we
9046 // pass host context to this method?
9047 instance = instance;
9048 instance.style.display = 'none';
9049}
9050
9051function hideTextInstance(textInstance) {
9052 textInstance.nodeValue = '';
9053}
9054
9055function unhideInstance(instance, props) {
9056 instance = instance;
9057 var styleProp = props[STYLE];
9058 var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
9059 instance.style.display = dangerousStyleValue('display', display);
9060}
9061
9062function unhideTextInstance(textInstance, text) {
9063 textInstance.nodeValue = text;
9064}
9065
9066// -------------------
9067// Hydration
9068// -------------------
9069
9070var supportsHydration = true;
9071
9072function canHydrateInstance(instance, type, props) {
9073 if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
9074 return null;
9075 }
9076 // This has now been refined to an element node.
9077 return instance;
9078}
9079
9080function canHydrateTextInstance(instance, text) {
9081 if (text === '' || instance.nodeType !== TEXT_NODE) {
9082 // Empty strings are not parsed by HTML so there won't be a correct match here.
9083 return null;
9084 }
9085 // This has now been refined to a text node.
9086 return instance;
9087}
9088
9089function canHydrateSuspenseInstance(instance) {
9090 if (instance.nodeType !== COMMENT_NODE) {
9091 // Empty strings are not parsed by HTML so there won't be a correct match here.
9092 return null;
9093 }
9094 // This has now been refined to a suspense node.
9095 return instance;
9096}
9097
9098function getNextHydratableSibling(instance) {
9099 var node = instance.nextSibling;
9100 // Skip non-hydratable nodes.
9101 while (node && node.nodeType !== ELEMENT_NODE && node.nodeType !== TEXT_NODE && (!enableSuspenseServerRenderer || node.nodeType !== COMMENT_NODE || node.data !== SUSPENSE_START_DATA)) {
9102 node = node.nextSibling;
9103 }
9104 return node;
9105}
9106
9107function getFirstHydratableChild(parentInstance) {
9108 var next = parentInstance.firstChild;
9109 // Skip non-hydratable nodes.
9110 while (next && next.nodeType !== ELEMENT_NODE && next.nodeType !== TEXT_NODE && (!enableSuspenseServerRenderer || next.nodeType !== COMMENT_NODE || next.data !== SUSPENSE_START_DATA)) {
9111 next = next.nextSibling;
9112 }
9113 return next;
9114}
9115
9116function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
9117 precacheFiberNode(internalInstanceHandle, instance);
9118 // TODO: Possibly defer this until the commit phase where all the events
9119 // get attached.
9120 updateFiberProps(instance, props);
9121 var parentNamespace = void 0;
9122 {
9123 var hostContextDev = hostContext;
9124 parentNamespace = hostContextDev.namespace;
9125 }
9126 return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);
9127}
9128
9129function hydrateTextInstance(textInstance, text, internalInstanceHandle) {
9130 precacheFiberNode(internalInstanceHandle, textInstance);
9131 return diffHydratedText(textInstance, text);
9132}
9133
9134function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
9135 var node = suspenseInstance.nextSibling;
9136 // Skip past all nodes within this suspense boundary.
9137 // There might be nested nodes so we need to keep track of how
9138 // deep we are and only break out when we're back on top.
9139 var depth = 0;
9140 while (node) {
9141 if (node.nodeType === COMMENT_NODE) {
9142 var data = node.data;
9143 if (data === SUSPENSE_END_DATA) {
9144 if (depth === 0) {
9145 return getNextHydratableSibling(node);
9146 } else {
9147 depth--;
9148 }
9149 } else if (data === SUSPENSE_START_DATA) {
9150 depth++;
9151 }
9152 }
9153 node = node.nextSibling;
9154 }
9155 // TODO: Warn, we didn't find the end comment boundary.
9156 return null;
9157}
9158
9159function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {
9160 {
9161 warnForUnmatchedText(textInstance, text);
9162 }
9163}
9164
9165function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {
9166 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9167 warnForUnmatchedText(textInstance, text);
9168 }
9169}
9170
9171function didNotHydrateContainerInstance(parentContainer, instance) {
9172 {
9173 if (instance.nodeType === ELEMENT_NODE) {
9174 warnForDeletedHydratableElement(parentContainer, instance);
9175 } else if (instance.nodeType === COMMENT_NODE) {
9176 // TODO: warnForDeletedHydratableSuspenseBoundary
9177 } else {
9178 warnForDeletedHydratableText(parentContainer, instance);
9179 }
9180 }
9181}
9182
9183function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {
9184 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9185 if (instance.nodeType === ELEMENT_NODE) {
9186 warnForDeletedHydratableElement(parentInstance, instance);
9187 } else if (instance.nodeType === COMMENT_NODE) {
9188 // TODO: warnForDeletedHydratableSuspenseBoundary
9189 } else {
9190 warnForDeletedHydratableText(parentInstance, instance);
9191 }
9192 }
9193}
9194
9195function didNotFindHydratableContainerInstance(parentContainer, type, props) {
9196 {
9197 warnForInsertedHydratedElement(parentContainer, type, props);
9198 }
9199}
9200
9201function didNotFindHydratableContainerTextInstance(parentContainer, text) {
9202 {
9203 warnForInsertedHydratedText(parentContainer, text);
9204 }
9205}
9206
9207
9208
9209function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {
9210 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9211 warnForInsertedHydratedElement(parentInstance, type, props);
9212 }
9213}
9214
9215function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {
9216 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9217 warnForInsertedHydratedText(parentInstance, text);
9218 }
9219}
9220
9221function didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance) {
9222 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9223 // TODO: warnForInsertedHydratedSuspense(parentInstance);
9224 }
9225}
9226
9227// This is just to get the setup running.
9228// TODO: real implementation.
9229// console.log('Hello from Fire host config.');
9230
9231// Prefix measurements so that it's possible to filter them.
9232// Longer prefixes are hard to read in DevTools.
9233var reactEmoji = '\u269B';
9234var warningEmoji = '\u26D4';
9235var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function';
9236
9237// Keep track of current fiber so that we know the path to unwind on pause.
9238// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
9239var currentFiber = null;
9240// If we're in the middle of user code, which fiber and method is it?
9241// Reusing `currentFiber` would be confusing for this because user code fiber
9242// can change during commit phase too, but we don't need to unwind it (since
9243// lifecycles in the commit phase don't resemble a tree).
9244var currentPhase = null;
9245var currentPhaseFiber = null;
9246// Did lifecycle hook schedule an update? This is often a performance problem,
9247// so we will keep track of it, and include it in the report.
9248// Track commits caused by cascading updates.
9249var isCommitting = false;
9250var hasScheduledUpdateInCurrentCommit = false;
9251var hasScheduledUpdateInCurrentPhase = false;
9252var commitCountInCurrentWorkLoop = 0;
9253var effectCountInCurrentCommit = 0;
9254var isWaitingForCallback = false;
9255// During commits, we only show a measurement once per method name
9256// to avoid stretch the commit phase with measurement overhead.
9257var labelsInCurrentCommit = new Set();
9258
9259var formatMarkName = function (markName) {
9260 return reactEmoji + ' ' + markName;
9261};
9262
9263var formatLabel = function (label, warning) {
9264 var prefix = warning ? warningEmoji + ' ' : reactEmoji + ' ';
9265 var suffix = warning ? ' Warning: ' + warning : '';
9266 return '' + prefix + label + suffix;
9267};
9268
9269var beginMark = function (markName) {
9270 performance.mark(formatMarkName(markName));
9271};
9272
9273var clearMark = function (markName) {
9274 performance.clearMarks(formatMarkName(markName));
9275};
9276
9277var endMark = function (label, markName, warning) {
9278 var formattedMarkName = formatMarkName(markName);
9279 var formattedLabel = formatLabel(label, warning);
9280 try {
9281 performance.measure(formattedLabel, formattedMarkName);
9282 } catch (err) {}
9283 // If previous mark was missing for some reason, this will throw.
9284 // This could only happen if React crashed in an unexpected place earlier.
9285 // Don't pile on with more errors.
9286
9287 // Clear marks immediately to avoid growing buffer.
9288 performance.clearMarks(formattedMarkName);
9289 performance.clearMeasures(formattedLabel);
9290};
9291
9292var getFiberMarkName = function (label, debugID) {
9293 return label + ' (#' + debugID + ')';
9294};
9295
9296var getFiberLabel = function (componentName, isMounted, phase) {
9297 if (phase === null) {
9298 // These are composite component total time measurements.
9299 return componentName + ' [' + (isMounted ? 'update' : 'mount') + ']';
9300 } else {
9301 // Composite component methods.
9302 return componentName + '.' + phase;
9303 }
9304};
9305
9306var beginFiberMark = function (fiber, phase) {
9307 var componentName = getComponentName(fiber.type) || 'Unknown';
9308 var debugID = fiber._debugID;
9309 var isMounted = fiber.alternate !== null;
9310 var label = getFiberLabel(componentName, isMounted, phase);
9311
9312 if (isCommitting && labelsInCurrentCommit.has(label)) {
9313 // During the commit phase, we don't show duplicate labels because
9314 // there is a fixed overhead for every measurement, and we don't
9315 // want to stretch the commit phase beyond necessary.
9316 return false;
9317 }
9318 labelsInCurrentCommit.add(label);
9319
9320 var markName = getFiberMarkName(label, debugID);
9321 beginMark(markName);
9322 return true;
9323};
9324
9325var clearFiberMark = function (fiber, phase) {
9326 var componentName = getComponentName(fiber.type) || 'Unknown';
9327 var debugID = fiber._debugID;
9328 var isMounted = fiber.alternate !== null;
9329 var label = getFiberLabel(componentName, isMounted, phase);
9330 var markName = getFiberMarkName(label, debugID);
9331 clearMark(markName);
9332};
9333
9334var endFiberMark = function (fiber, phase, warning) {
9335 var componentName = getComponentName(fiber.type) || 'Unknown';
9336 var debugID = fiber._debugID;
9337 var isMounted = fiber.alternate !== null;
9338 var label = getFiberLabel(componentName, isMounted, phase);
9339 var markName = getFiberMarkName(label, debugID);
9340 endMark(label, markName, warning);
9341};
9342
9343var shouldIgnoreFiber = function (fiber) {
9344 // Host components should be skipped in the timeline.
9345 // We could check typeof fiber.type, but does this work with RN?
9346 switch (fiber.tag) {
9347 case HostRoot:
9348 case HostComponent:
9349 case HostText:
9350 case HostPortal:
9351 case Fragment:
9352 case ContextProvider:
9353 case ContextConsumer:
9354 case Mode:
9355 return true;
9356 default:
9357 return false;
9358 }
9359};
9360
9361var clearPendingPhaseMeasurement = function () {
9362 if (currentPhase !== null && currentPhaseFiber !== null) {
9363 clearFiberMark(currentPhaseFiber, currentPhase);
9364 }
9365 currentPhaseFiber = null;
9366 currentPhase = null;
9367 hasScheduledUpdateInCurrentPhase = false;
9368};
9369
9370var pauseTimers = function () {
9371 // Stops all currently active measurements so that they can be resumed
9372 // if we continue in a later deferred loop from the same unit of work.
9373 var fiber = currentFiber;
9374 while (fiber) {
9375 if (fiber._debugIsCurrentlyTiming) {
9376 endFiberMark(fiber, null, null);
9377 }
9378 fiber = fiber.return;
9379 }
9380};
9381
9382var resumeTimersRecursively = function (fiber) {
9383 if (fiber.return !== null) {
9384 resumeTimersRecursively(fiber.return);
9385 }
9386 if (fiber._debugIsCurrentlyTiming) {
9387 beginFiberMark(fiber, null);
9388 }
9389};
9390
9391var resumeTimers = function () {
9392 // Resumes all measurements that were active during the last deferred loop.
9393 if (currentFiber !== null) {
9394 resumeTimersRecursively(currentFiber);
9395 }
9396};
9397
9398function recordEffect() {
9399 if (enableUserTimingAPI) {
9400 effectCountInCurrentCommit++;
9401 }
9402}
9403
9404function recordScheduleUpdate() {
9405 if (enableUserTimingAPI) {
9406 if (isCommitting) {
9407 hasScheduledUpdateInCurrentCommit = true;
9408 }
9409 if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
9410 hasScheduledUpdateInCurrentPhase = true;
9411 }
9412 }
9413}
9414
9415function startRequestCallbackTimer() {
9416 if (enableUserTimingAPI) {
9417 if (supportsUserTiming && !isWaitingForCallback) {
9418 isWaitingForCallback = true;
9419 beginMark('(Waiting for async callback...)');
9420 }
9421 }
9422}
9423
9424function stopRequestCallbackTimer(didExpire, expirationTime) {
9425 if (enableUserTimingAPI) {
9426 if (supportsUserTiming) {
9427 isWaitingForCallback = false;
9428 var warning = didExpire ? 'React was blocked by main thread' : null;
9429 endMark('(Waiting for async callback... will force flush in ' + expirationTime + ' ms)', '(Waiting for async callback...)', warning);
9430 }
9431 }
9432}
9433
9434function startWorkTimer(fiber) {
9435 if (enableUserTimingAPI) {
9436 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9437 return;
9438 }
9439 // If we pause, this is the fiber to unwind from.
9440 currentFiber = fiber;
9441 if (!beginFiberMark(fiber, null)) {
9442 return;
9443 }
9444 fiber._debugIsCurrentlyTiming = true;
9445 }
9446}
9447
9448function cancelWorkTimer(fiber) {
9449 if (enableUserTimingAPI) {
9450 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9451 return;
9452 }
9453 // Remember we shouldn't complete measurement for this fiber.
9454 // Otherwise flamechart will be deep even for small updates.
9455 fiber._debugIsCurrentlyTiming = false;
9456 clearFiberMark(fiber, null);
9457 }
9458}
9459
9460function stopWorkTimer(fiber) {
9461 if (enableUserTimingAPI) {
9462 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9463 return;
9464 }
9465 // If we pause, its parent is the fiber to unwind from.
9466 currentFiber = fiber.return;
9467 if (!fiber._debugIsCurrentlyTiming) {
9468 return;
9469 }
9470 fiber._debugIsCurrentlyTiming = false;
9471 endFiberMark(fiber, null, null);
9472 }
9473}
9474
9475function stopFailedWorkTimer(fiber) {
9476 if (enableUserTimingAPI) {
9477 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9478 return;
9479 }
9480 // If we pause, its parent is the fiber to unwind from.
9481 currentFiber = fiber.return;
9482 if (!fiber._debugIsCurrentlyTiming) {
9483 return;
9484 }
9485 fiber._debugIsCurrentlyTiming = false;
9486 var warning = fiber.tag === SuspenseComponent || fiber.tag === DehydratedSuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
9487 endFiberMark(fiber, null, warning);
9488 }
9489}
9490
9491function startPhaseTimer(fiber, phase) {
9492 if (enableUserTimingAPI) {
9493 if (!supportsUserTiming) {
9494 return;
9495 }
9496 clearPendingPhaseMeasurement();
9497 if (!beginFiberMark(fiber, phase)) {
9498 return;
9499 }
9500 currentPhaseFiber = fiber;
9501 currentPhase = phase;
9502 }
9503}
9504
9505function stopPhaseTimer() {
9506 if (enableUserTimingAPI) {
9507 if (!supportsUserTiming) {
9508 return;
9509 }
9510 if (currentPhase !== null && currentPhaseFiber !== null) {
9511 var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
9512 endFiberMark(currentPhaseFiber, currentPhase, warning);
9513 }
9514 currentPhase = null;
9515 currentPhaseFiber = null;
9516 }
9517}
9518
9519function startWorkLoopTimer(nextUnitOfWork) {
9520 if (enableUserTimingAPI) {
9521 currentFiber = nextUnitOfWork;
9522 if (!supportsUserTiming) {
9523 return;
9524 }
9525 commitCountInCurrentWorkLoop = 0;
9526 // This is top level call.
9527 // Any other measurements are performed within.
9528 beginMark('(React Tree Reconciliation)');
9529 // Resume any measurements that were in progress during the last loop.
9530 resumeTimers();
9531 }
9532}
9533
9534function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
9535 if (enableUserTimingAPI) {
9536 if (!supportsUserTiming) {
9537 return;
9538 }
9539 var warning = null;
9540 if (interruptedBy !== null) {
9541 if (interruptedBy.tag === HostRoot) {
9542 warning = 'A top-level update interrupted the previous render';
9543 } else {
9544 var componentName = getComponentName(interruptedBy.type) || 'Unknown';
9545 warning = 'An update to ' + componentName + ' interrupted the previous render';
9546 }
9547 } else if (commitCountInCurrentWorkLoop > 1) {
9548 warning = 'There were cascading updates';
9549 }
9550 commitCountInCurrentWorkLoop = 0;
9551 var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)';
9552 // Pause any measurements until the next loop.
9553 pauseTimers();
9554 endMark(label, '(React Tree Reconciliation)', warning);
9555 }
9556}
9557
9558function startCommitTimer() {
9559 if (enableUserTimingAPI) {
9560 if (!supportsUserTiming) {
9561 return;
9562 }
9563 isCommitting = true;
9564 hasScheduledUpdateInCurrentCommit = false;
9565 labelsInCurrentCommit.clear();
9566 beginMark('(Committing Changes)');
9567 }
9568}
9569
9570function stopCommitTimer() {
9571 if (enableUserTimingAPI) {
9572 if (!supportsUserTiming) {
9573 return;
9574 }
9575
9576 var warning = null;
9577 if (hasScheduledUpdateInCurrentCommit) {
9578 warning = 'Lifecycle hook scheduled a cascading update';
9579 } else if (commitCountInCurrentWorkLoop > 0) {
9580 warning = 'Caused by a cascading update in earlier commit';
9581 }
9582 hasScheduledUpdateInCurrentCommit = false;
9583 commitCountInCurrentWorkLoop++;
9584 isCommitting = false;
9585 labelsInCurrentCommit.clear();
9586
9587 endMark('(Committing Changes)', '(Committing Changes)', warning);
9588 }
9589}
9590
9591function startCommitSnapshotEffectsTimer() {
9592 if (enableUserTimingAPI) {
9593 if (!supportsUserTiming) {
9594 return;
9595 }
9596 effectCountInCurrentCommit = 0;
9597 beginMark('(Committing Snapshot Effects)');
9598 }
9599}
9600
9601function stopCommitSnapshotEffectsTimer() {
9602 if (enableUserTimingAPI) {
9603 if (!supportsUserTiming) {
9604 return;
9605 }
9606 var count = effectCountInCurrentCommit;
9607 effectCountInCurrentCommit = 0;
9608 endMark('(Committing Snapshot Effects: ' + count + ' Total)', '(Committing Snapshot Effects)', null);
9609 }
9610}
9611
9612function startCommitHostEffectsTimer() {
9613 if (enableUserTimingAPI) {
9614 if (!supportsUserTiming) {
9615 return;
9616 }
9617 effectCountInCurrentCommit = 0;
9618 beginMark('(Committing Host Effects)');
9619 }
9620}
9621
9622function stopCommitHostEffectsTimer() {
9623 if (enableUserTimingAPI) {
9624 if (!supportsUserTiming) {
9625 return;
9626 }
9627 var count = effectCountInCurrentCommit;
9628 effectCountInCurrentCommit = 0;
9629 endMark('(Committing Host Effects: ' + count + ' Total)', '(Committing Host Effects)', null);
9630 }
9631}
9632
9633function startCommitLifeCyclesTimer() {
9634 if (enableUserTimingAPI) {
9635 if (!supportsUserTiming) {
9636 return;
9637 }
9638 effectCountInCurrentCommit = 0;
9639 beginMark('(Calling Lifecycle Methods)');
9640 }
9641}
9642
9643function stopCommitLifeCyclesTimer() {
9644 if (enableUserTimingAPI) {
9645 if (!supportsUserTiming) {
9646 return;
9647 }
9648 var count = effectCountInCurrentCommit;
9649 effectCountInCurrentCommit = 0;
9650 endMark('(Calling Lifecycle Methods: ' + count + ' Total)', '(Calling Lifecycle Methods)', null);
9651 }
9652}
9653
9654var valueStack = [];
9655
9656var fiberStack = void 0;
9657
9658{
9659 fiberStack = [];
9660}
9661
9662var index = -1;
9663
9664function createCursor(defaultValue) {
9665 return {
9666 current: defaultValue
9667 };
9668}
9669
9670function pop(cursor, fiber) {
9671 if (index < 0) {
9672 {
9673 warningWithoutStack$1(false, 'Unexpected pop.');
9674 }
9675 return;
9676 }
9677
9678 {
9679 if (fiber !== fiberStack[index]) {
9680 warningWithoutStack$1(false, 'Unexpected Fiber popped.');
9681 }
9682 }
9683
9684 cursor.current = valueStack[index];
9685
9686 valueStack[index] = null;
9687
9688 {
9689 fiberStack[index] = null;
9690 }
9691
9692 index--;
9693}
9694
9695function push(cursor, value, fiber) {
9696 index++;
9697
9698 valueStack[index] = cursor.current;
9699
9700 {
9701 fiberStack[index] = fiber;
9702 }
9703
9704 cursor.current = value;
9705}
9706
9707function checkThatStackIsEmpty() {
9708 {
9709 if (index !== -1) {
9710 warningWithoutStack$1(false, 'Expected an empty stack. Something was not reset properly.');
9711 }
9712 }
9713}
9714
9715function resetStackAfterFatalErrorInDev() {
9716 {
9717 index = -1;
9718 valueStack.length = 0;
9719 fiberStack.length = 0;
9720 }
9721}
9722
9723var warnedAboutMissingGetChildContext = void 0;
9724
9725{
9726 warnedAboutMissingGetChildContext = {};
9727}
9728
9729var emptyContextObject = {};
9730{
9731 Object.freeze(emptyContextObject);
9732}
9733
9734// A cursor to the current merged context object on the stack.
9735var contextStackCursor = createCursor(emptyContextObject);
9736// A cursor to a boolean indicating whether the context has changed.
9737var didPerformWorkStackCursor = createCursor(false);
9738// Keep track of the previous context object that was on the stack.
9739// We use this to get access to the parent context after we have already
9740// pushed the next context provider, and now need to merge their contexts.
9741var previousContext = emptyContextObject;
9742
9743function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
9744 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
9745 // If the fiber is a context provider itself, when we read its context
9746 // we may have already pushed its own child context on the stack. A context
9747 // provider should not "see" its own child context. Therefore we read the
9748 // previous (parent) context instead for a context provider.
9749 return previousContext;
9750 }
9751 return contextStackCursor.current;
9752}
9753
9754function cacheContext(workInProgress, unmaskedContext, maskedContext) {
9755 var instance = workInProgress.stateNode;
9756 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
9757 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
9758}
9759
9760function getMaskedContext(workInProgress, unmaskedContext) {
9761 var type = workInProgress.type;
9762 var contextTypes = type.contextTypes;
9763 if (!contextTypes) {
9764 return emptyContextObject;
9765 }
9766
9767 // Avoid recreating masked context unless unmasked context has changed.
9768 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
9769 // This may trigger infinite loops if componentWillReceiveProps calls setState.
9770 var instance = workInProgress.stateNode;
9771 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
9772 return instance.__reactInternalMemoizedMaskedChildContext;
9773 }
9774
9775 var context = {};
9776 for (var key in contextTypes) {
9777 context[key] = unmaskedContext[key];
9778 }
9779
9780 {
9781 var name = getComponentName(type) || 'Unknown';
9782 checkPropTypes_1(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
9783 }
9784
9785 // Cache unmasked context so we can avoid recreating masked context unless necessary.
9786 // Context is created before the class component is instantiated so check for instance.
9787 if (instance) {
9788 cacheContext(workInProgress, unmaskedContext, context);
9789 }
9790
9791 return context;
9792}
9793
9794function hasContextChanged() {
9795 return didPerformWorkStackCursor.current;
9796}
9797
9798function isContextProvider(type) {
9799 var childContextTypes = type.childContextTypes;
9800 return childContextTypes !== null && childContextTypes !== undefined;
9801}
9802
9803function popContext(fiber) {
9804 pop(didPerformWorkStackCursor, fiber);
9805 pop(contextStackCursor, fiber);
9806}
9807
9808function popTopLevelContextObject(fiber) {
9809 pop(didPerformWorkStackCursor, fiber);
9810 pop(contextStackCursor, fiber);
9811}
9812
9813function pushTopLevelContextObject(fiber, context, didChange) {
9814 !(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;
9815
9816 push(contextStackCursor, context, fiber);
9817 push(didPerformWorkStackCursor, didChange, fiber);
9818}
9819
9820function processChildContext(fiber, type, parentContext) {
9821 var instance = fiber.stateNode;
9822 var childContextTypes = type.childContextTypes;
9823
9824 // TODO (bvaughn) Replace this behavior with an invariant() in the future.
9825 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
9826 if (typeof instance.getChildContext !== 'function') {
9827 {
9828 var componentName = getComponentName(type) || 'Unknown';
9829
9830 if (!warnedAboutMissingGetChildContext[componentName]) {
9831 warnedAboutMissingGetChildContext[componentName] = true;
9832 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);
9833 }
9834 }
9835 return parentContext;
9836 }
9837
9838 var childContext = void 0;
9839 {
9840 setCurrentPhase('getChildContext');
9841 }
9842 startPhaseTimer(fiber, 'getChildContext');
9843 childContext = instance.getChildContext();
9844 stopPhaseTimer();
9845 {
9846 setCurrentPhase(null);
9847 }
9848 for (var contextKey in childContext) {
9849 !(contextKey in childContextTypes) ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName(type) || 'Unknown', contextKey) : void 0;
9850 }
9851 {
9852 var name = getComponentName(type) || 'Unknown';
9853 checkPropTypes_1(childContextTypes, childContext, 'child context', name,
9854 // In practice, there is one case in which we won't get a stack. It's when
9855 // somebody calls unstable_renderSubtreeIntoContainer() and we process
9856 // context from the parent component instance. The stack will be missing
9857 // because it's outside of the reconciliation, and so the pointer has not
9858 // been set. This is rare and doesn't matter. We'll also remove that API.
9859 getCurrentFiberStackInDev);
9860 }
9861
9862 return _assign({}, parentContext, childContext);
9863}
9864
9865function pushContextProvider(workInProgress) {
9866 var instance = workInProgress.stateNode;
9867 // We push the context as early as possible to ensure stack integrity.
9868 // If the instance does not exist yet, we will push null at first,
9869 // and replace it on the stack later when invalidating the context.
9870 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject;
9871
9872 // Remember the parent context so we can merge with it later.
9873 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
9874 previousContext = contextStackCursor.current;
9875 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
9876 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
9877
9878 return true;
9879}
9880
9881function invalidateContextProvider(workInProgress, type, didChange) {
9882 var instance = workInProgress.stateNode;
9883 !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;
9884
9885 if (didChange) {
9886 // Merge parent and own context.
9887 // Skip this if we're not updating due to sCU.
9888 // This avoids unnecessarily recomputing memoized values.
9889 var mergedContext = processChildContext(workInProgress, type, previousContext);
9890 instance.__reactInternalMemoizedMergedChildContext = mergedContext;
9891
9892 // Replace the old (or empty) context with the new one.
9893 // It is important to unwind the context in the reverse order.
9894 pop(didPerformWorkStackCursor, workInProgress);
9895 pop(contextStackCursor, workInProgress);
9896 // Now push the new context and mark that it has changed.
9897 push(contextStackCursor, mergedContext, workInProgress);
9898 push(didPerformWorkStackCursor, didChange, workInProgress);
9899 } else {
9900 pop(didPerformWorkStackCursor, workInProgress);
9901 push(didPerformWorkStackCursor, didChange, workInProgress);
9902 }
9903}
9904
9905function findCurrentUnmaskedContext(fiber) {
9906 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
9907 // makes sense elsewhere
9908 !(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;
9909
9910 var node = fiber;
9911 do {
9912 switch (node.tag) {
9913 case HostRoot:
9914 return node.stateNode.context;
9915 case ClassComponent:
9916 {
9917 var Component = node.type;
9918 if (isContextProvider(Component)) {
9919 return node.stateNode.__reactInternalMemoizedMergedChildContext;
9920 }
9921 break;
9922 }
9923 }
9924 node = node.return;
9925 } while (node !== null);
9926 invariant(false, 'Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.');
9927}
9928
9929var onCommitFiberRoot = null;
9930var onCommitFiberUnmount = null;
9931var hasLoggedError = false;
9932
9933function catchErrors(fn) {
9934 return function (arg) {
9935 try {
9936 return fn(arg);
9937 } catch (err) {
9938 if (true && !hasLoggedError) {
9939 hasLoggedError = true;
9940 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
9941 }
9942 }
9943 };
9944}
9945
9946var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
9947
9948function injectInternals(internals) {
9949 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
9950 // No DevTools
9951 return false;
9952 }
9953 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
9954 if (hook.isDisabled) {
9955 // This isn't a real property on the hook, but it can be set to opt out
9956 // of DevTools integration and associated warnings and logs.
9957 // https://github.com/facebook/react/issues/3877
9958 return true;
9959 }
9960 if (!hook.supportsFiber) {
9961 {
9962 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');
9963 }
9964 // DevTools exists, even though it doesn't support Fiber.
9965 return true;
9966 }
9967 try {
9968 var rendererID = hook.inject(internals);
9969 // We have successfully injected, so now it is safe to set up hooks.
9970 onCommitFiberRoot = catchErrors(function (root) {
9971 return hook.onCommitFiberRoot(rendererID, root);
9972 });
9973 onCommitFiberUnmount = catchErrors(function (fiber) {
9974 return hook.onCommitFiberUnmount(rendererID, fiber);
9975 });
9976 } catch (err) {
9977 // Catch all errors because it is unsafe to throw during initialization.
9978 {
9979 warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
9980 }
9981 }
9982 // DevTools exists
9983 return true;
9984}
9985
9986function onCommitRoot(root) {
9987 if (typeof onCommitFiberRoot === 'function') {
9988 onCommitFiberRoot(root);
9989 }
9990}
9991
9992function onCommitUnmount(fiber) {
9993 if (typeof onCommitFiberUnmount === 'function') {
9994 onCommitFiberUnmount(fiber);
9995 }
9996}
9997
9998// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
9999// Math.pow(2, 30) - 1
10000// 0b111111111111111111111111111111
10001var maxSigned31BitInt = 1073741823;
10002
10003var NoWork = 0;
10004var Never = 1;
10005var Sync = maxSigned31BitInt;
10006
10007var UNIT_SIZE = 10;
10008var MAGIC_NUMBER_OFFSET = maxSigned31BitInt - 1;
10009
10010// 1 unit of expiration time represents 10ms.
10011function msToExpirationTime(ms) {
10012 // Always add an offset so that we don't clash with the magic number for NoWork.
10013 return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
10014}
10015
10016function expirationTimeToMs(expirationTime) {
10017 return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
10018}
10019
10020function ceiling(num, precision) {
10021 return ((num / precision | 0) + 1) * precision;
10022}
10023
10024function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
10025 return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
10026}
10027
10028var LOW_PRIORITY_EXPIRATION = 5000;
10029var LOW_PRIORITY_BATCH_SIZE = 250;
10030
10031function computeAsyncExpiration(currentTime) {
10032 return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
10033}
10034
10035// We intentionally set a higher expiration time for interactive updates in
10036// dev than in production.
10037//
10038// If the main thread is being blocked so long that you hit the expiration,
10039// it's a problem that could be solved with better scheduling.
10040//
10041// People will be more likely to notice this and fix it with the long
10042// expiration time in development.
10043//
10044// In production we opt for better UX at the risk of masking scheduling
10045// problems, by expiring fast.
10046var HIGH_PRIORITY_EXPIRATION = 500;
10047var HIGH_PRIORITY_BATCH_SIZE = 100;
10048
10049function computeInteractiveExpiration(currentTime) {
10050 return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
10051}
10052
10053var NoContext = 0;
10054var ConcurrentMode = 1;
10055var StrictMode = 2;
10056var ProfileMode = 4;
10057
10058var hasBadMapPolyfill = void 0;
10059
10060{
10061 hasBadMapPolyfill = false;
10062 try {
10063 var nonExtensibleObject = Object.preventExtensions({});
10064 var testMap = new Map([[nonExtensibleObject, null]]);
10065 var testSet = new Set([nonExtensibleObject]);
10066 // This is necessary for Rollup to not consider these unused.
10067 // https://github.com/rollup/rollup/issues/1771
10068 // TODO: we can remove these if Rollup fixes the bug.
10069 testMap.set(0, 0);
10070 testSet.add(0);
10071 } catch (e) {
10072 // TODO: Consider warning about bad polyfills
10073 hasBadMapPolyfill = true;
10074 }
10075}
10076
10077// A Fiber is work on a Component that needs to be done or was done. There can
10078// be more than one per component.
10079
10080
10081var debugCounter = void 0;
10082
10083{
10084 debugCounter = 1;
10085}
10086
10087function FiberNode(tag, pendingProps, key, mode) {
10088 // Instance
10089 this.tag = tag;
10090 this.key = key;
10091 this.elementType = null;
10092 this.type = null;
10093 this.stateNode = null;
10094
10095 // Fiber
10096 this.return = null;
10097 this.child = null;
10098 this.sibling = null;
10099 this.index = 0;
10100
10101 this.ref = null;
10102
10103 this.pendingProps = pendingProps;
10104 this.memoizedProps = null;
10105 this.updateQueue = null;
10106 this.memoizedState = null;
10107 this.contextDependencies = null;
10108
10109 this.mode = mode;
10110
10111 // Effects
10112 this.effectTag = NoEffect;
10113 this.nextEffect = null;
10114
10115 this.firstEffect = null;
10116 this.lastEffect = null;
10117
10118 this.expirationTime = NoWork;
10119 this.childExpirationTime = NoWork;
10120
10121 this.alternate = null;
10122
10123 if (enableProfilerTimer) {
10124 // Note: The following is done to avoid a v8 performance cliff.
10125 //
10126 // Initializing the fields below to smis and later updating them with
10127 // double values will cause Fibers to end up having separate shapes.
10128 // This behavior/bug has something to do with Object.preventExtension().
10129 // Fortunately this only impacts DEV builds.
10130 // Unfortunately it makes React unusably slow for some applications.
10131 // To work around this, initialize the fields below with doubles.
10132 //
10133 // Learn more about this here:
10134 // https://github.com/facebook/react/issues/14365
10135 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
10136 this.actualDuration = Number.NaN;
10137 this.actualStartTime = Number.NaN;
10138 this.selfBaseDuration = Number.NaN;
10139 this.treeBaseDuration = Number.NaN;
10140
10141 // It's okay to replace the initial doubles with smis after initialization.
10142 // This won't trigger the performance cliff mentioned above,
10143 // and it simplifies other profiler code (including DevTools).
10144 this.actualDuration = 0;
10145 this.actualStartTime = -1;
10146 this.selfBaseDuration = 0;
10147 this.treeBaseDuration = 0;
10148 }
10149
10150 {
10151 this._debugID = debugCounter++;
10152 this._debugSource = null;
10153 this._debugOwner = null;
10154 this._debugIsCurrentlyTiming = false;
10155 this._debugHookTypes = null;
10156 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
10157 Object.preventExtensions(this);
10158 }
10159 }
10160}
10161
10162// This is a constructor function, rather than a POJO constructor, still
10163// please ensure we do the following:
10164// 1) Nobody should add any instance methods on this. Instance methods can be
10165// more difficult to predict when they get optimized and they are almost
10166// never inlined properly in static compilers.
10167// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
10168// always know when it is a fiber.
10169// 3) We might want to experiment with using numeric keys since they are easier
10170// to optimize in a non-JIT environment.
10171// 4) We can easily go from a constructor to a createFiber object literal if that
10172// is faster.
10173// 5) It should be easy to port this to a C struct and keep a C implementation
10174// compatible.
10175var createFiber = function (tag, pendingProps, key, mode) {
10176 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
10177 return new FiberNode(tag, pendingProps, key, mode);
10178};
10179
10180function shouldConstruct(Component) {
10181 var prototype = Component.prototype;
10182 return !!(prototype && prototype.isReactComponent);
10183}
10184
10185function isSimpleFunctionComponent(type) {
10186 return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
10187}
10188
10189function resolveLazyComponentTag(Component) {
10190 if (typeof Component === 'function') {
10191 return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
10192 } else if (Component !== undefined && Component !== null) {
10193 var $$typeof = Component.$$typeof;
10194 if ($$typeof === REACT_FORWARD_REF_TYPE) {
10195 return ForwardRef;
10196 }
10197 if ($$typeof === REACT_MEMO_TYPE) {
10198 return MemoComponent;
10199 }
10200 }
10201 return IndeterminateComponent;
10202}
10203
10204// This is used to create an alternate fiber to do work on.
10205function createWorkInProgress(current, pendingProps, expirationTime) {
10206 var workInProgress = current.alternate;
10207 if (workInProgress === null) {
10208 // We use a double buffering pooling technique because we know that we'll
10209 // only ever need at most two versions of a tree. We pool the "other" unused
10210 // node that we're free to reuse. This is lazily created to avoid allocating
10211 // extra objects for things that are never updated. It also allow us to
10212 // reclaim the extra memory if needed.
10213 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
10214 workInProgress.elementType = current.elementType;
10215 workInProgress.type = current.type;
10216 workInProgress.stateNode = current.stateNode;
10217
10218 {
10219 // DEV-only fields
10220 workInProgress._debugID = current._debugID;
10221 workInProgress._debugSource = current._debugSource;
10222 workInProgress._debugOwner = current._debugOwner;
10223 workInProgress._debugHookTypes = current._debugHookTypes;
10224 }
10225
10226 workInProgress.alternate = current;
10227 current.alternate = workInProgress;
10228 } else {
10229 workInProgress.pendingProps = pendingProps;
10230
10231 // We already have an alternate.
10232 // Reset the effect tag.
10233 workInProgress.effectTag = NoEffect;
10234
10235 // The effect list is no longer valid.
10236 workInProgress.nextEffect = null;
10237 workInProgress.firstEffect = null;
10238 workInProgress.lastEffect = null;
10239
10240 if (enableProfilerTimer) {
10241 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
10242 // This prevents time from endlessly accumulating in new commits.
10243 // This has the downside of resetting values for different priority renders,
10244 // But works for yielding (the common case) and should support resuming.
10245 workInProgress.actualDuration = 0;
10246 workInProgress.actualStartTime = -1;
10247 }
10248 }
10249
10250 workInProgress.childExpirationTime = current.childExpirationTime;
10251 workInProgress.expirationTime = current.expirationTime;
10252
10253 workInProgress.child = current.child;
10254 workInProgress.memoizedProps = current.memoizedProps;
10255 workInProgress.memoizedState = current.memoizedState;
10256 workInProgress.updateQueue = current.updateQueue;
10257 workInProgress.contextDependencies = current.contextDependencies;
10258
10259 // These will be overridden during the parent's reconciliation
10260 workInProgress.sibling = current.sibling;
10261 workInProgress.index = current.index;
10262 workInProgress.ref = current.ref;
10263
10264 if (enableProfilerTimer) {
10265 workInProgress.selfBaseDuration = current.selfBaseDuration;
10266 workInProgress.treeBaseDuration = current.treeBaseDuration;
10267 }
10268
10269 return workInProgress;
10270}
10271
10272function createHostRootFiber(isConcurrent) {
10273 var mode = isConcurrent ? ConcurrentMode | StrictMode : NoContext;
10274
10275 if (enableProfilerTimer && isDevToolsPresent) {
10276 // Always collect profile timings when DevTools are present.
10277 // This enables DevTools to start capturing timing at any point–
10278 // Without some nodes in the tree having empty base times.
10279 mode |= ProfileMode;
10280 }
10281
10282 return createFiber(HostRoot, null, null, mode);
10283}
10284
10285function createFiberFromTypeAndProps(type, // React$ElementType
10286key, pendingProps, owner, mode, expirationTime) {
10287 var fiber = void 0;
10288
10289 var fiberTag = IndeterminateComponent;
10290 // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
10291 var resolvedType = type;
10292 if (typeof type === 'function') {
10293 if (shouldConstruct(type)) {
10294 fiberTag = ClassComponent;
10295 }
10296 } else if (typeof type === 'string') {
10297 fiberTag = HostComponent;
10298 } else {
10299 getTag: switch (type) {
10300 case REACT_FRAGMENT_TYPE:
10301 return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
10302 case REACT_CONCURRENT_MODE_TYPE:
10303 return createFiberFromMode(pendingProps, mode | ConcurrentMode | StrictMode, expirationTime, key);
10304 case REACT_STRICT_MODE_TYPE:
10305 return createFiberFromMode(pendingProps, mode | StrictMode, expirationTime, key);
10306 case REACT_PROFILER_TYPE:
10307 return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
10308 case REACT_SUSPENSE_TYPE:
10309 return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
10310 default:
10311 {
10312 if (typeof type === 'object' && type !== null) {
10313 switch (type.$$typeof) {
10314 case REACT_PROVIDER_TYPE:
10315 fiberTag = ContextProvider;
10316 break getTag;
10317 case REACT_CONTEXT_TYPE:
10318 // This is a consumer
10319 fiberTag = ContextConsumer;
10320 break getTag;
10321 case REACT_FORWARD_REF_TYPE:
10322 fiberTag = ForwardRef;
10323 break getTag;
10324 case REACT_MEMO_TYPE:
10325 fiberTag = MemoComponent;
10326 break getTag;
10327 case REACT_LAZY_TYPE:
10328 fiberTag = LazyComponent;
10329 resolvedType = null;
10330 break getTag;
10331 }
10332 }
10333 var info = '';
10334 {
10335 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
10336 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.';
10337 }
10338 var ownerName = owner ? getComponentName(owner.type) : null;
10339 if (ownerName) {
10340 info += '\n\nCheck the render method of `' + ownerName + '`.';
10341 }
10342 }
10343 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);
10344 }
10345 }
10346 }
10347
10348 fiber = createFiber(fiberTag, pendingProps, key, mode);
10349 fiber.elementType = type;
10350 fiber.type = resolvedType;
10351 fiber.expirationTime = expirationTime;
10352
10353 return fiber;
10354}
10355
10356function createFiberFromElement(element, mode, expirationTime) {
10357 var owner = null;
10358 {
10359 owner = element._owner;
10360 }
10361 var type = element.type;
10362 var key = element.key;
10363 var pendingProps = element.props;
10364 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
10365 {
10366 fiber._debugSource = element._source;
10367 fiber._debugOwner = element._owner;
10368 }
10369 return fiber;
10370}
10371
10372function createFiberFromFragment(elements, mode, expirationTime, key) {
10373 var fiber = createFiber(Fragment, elements, key, mode);
10374 fiber.expirationTime = expirationTime;
10375 return fiber;
10376}
10377
10378function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
10379 {
10380 if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
10381 warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
10382 }
10383 }
10384
10385 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
10386 // TODO: The Profiler fiber shouldn't have a type. It has a tag.
10387 fiber.elementType = REACT_PROFILER_TYPE;
10388 fiber.type = REACT_PROFILER_TYPE;
10389 fiber.expirationTime = expirationTime;
10390
10391 return fiber;
10392}
10393
10394function createFiberFromMode(pendingProps, mode, expirationTime, key) {
10395 var fiber = createFiber(Mode, pendingProps, key, mode);
10396
10397 // TODO: The Mode fiber shouldn't have a type. It has a tag.
10398 var type = (mode & ConcurrentMode) === NoContext ? REACT_STRICT_MODE_TYPE : REACT_CONCURRENT_MODE_TYPE;
10399 fiber.elementType = type;
10400 fiber.type = type;
10401
10402 fiber.expirationTime = expirationTime;
10403 return fiber;
10404}
10405
10406function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
10407 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
10408
10409 // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
10410 var type = REACT_SUSPENSE_TYPE;
10411 fiber.elementType = type;
10412 fiber.type = type;
10413
10414 fiber.expirationTime = expirationTime;
10415 return fiber;
10416}
10417
10418function createFiberFromText(content, mode, expirationTime) {
10419 var fiber = createFiber(HostText, content, null, mode);
10420 fiber.expirationTime = expirationTime;
10421 return fiber;
10422}
10423
10424function createFiberFromHostInstanceForDeletion() {
10425 var fiber = createFiber(HostComponent, null, null, NoContext);
10426 // TODO: These should not need a type.
10427 fiber.elementType = 'DELETED';
10428 fiber.type = 'DELETED';
10429 return fiber;
10430}
10431
10432function createFiberFromPortal(portal, mode, expirationTime) {
10433 var pendingProps = portal.children !== null ? portal.children : [];
10434 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
10435 fiber.expirationTime = expirationTime;
10436 fiber.stateNode = {
10437 containerInfo: portal.containerInfo,
10438 pendingChildren: null, // Used by persistent updates
10439 implementation: portal.implementation
10440 };
10441 return fiber;
10442}
10443
10444// Used for stashing WIP properties to replay failed work in DEV.
10445function assignFiberPropertiesInDEV(target, source) {
10446 if (target === null) {
10447 // This Fiber's initial properties will always be overwritten.
10448 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
10449 target = createFiber(IndeterminateComponent, null, null, NoContext);
10450 }
10451
10452 // This is intentionally written as a list of all properties.
10453 // We tried to use Object.assign() instead but this is called in
10454 // the hottest path, and Object.assign() was too slow:
10455 // https://github.com/facebook/react/issues/12502
10456 // This code is DEV-only so size is not a concern.
10457
10458 target.tag = source.tag;
10459 target.key = source.key;
10460 target.elementType = source.elementType;
10461 target.type = source.type;
10462 target.stateNode = source.stateNode;
10463 target.return = source.return;
10464 target.child = source.child;
10465 target.sibling = source.sibling;
10466 target.index = source.index;
10467 target.ref = source.ref;
10468 target.pendingProps = source.pendingProps;
10469 target.memoizedProps = source.memoizedProps;
10470 target.updateQueue = source.updateQueue;
10471 target.memoizedState = source.memoizedState;
10472 target.contextDependencies = source.contextDependencies;
10473 target.mode = source.mode;
10474 target.effectTag = source.effectTag;
10475 target.nextEffect = source.nextEffect;
10476 target.firstEffect = source.firstEffect;
10477 target.lastEffect = source.lastEffect;
10478 target.expirationTime = source.expirationTime;
10479 target.childExpirationTime = source.childExpirationTime;
10480 target.alternate = source.alternate;
10481 if (enableProfilerTimer) {
10482 target.actualDuration = source.actualDuration;
10483 target.actualStartTime = source.actualStartTime;
10484 target.selfBaseDuration = source.selfBaseDuration;
10485 target.treeBaseDuration = source.treeBaseDuration;
10486 }
10487 target._debugID = source._debugID;
10488 target._debugSource = source._debugSource;
10489 target._debugOwner = source._debugOwner;
10490 target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
10491 target._debugHookTypes = source._debugHookTypes;
10492 return target;
10493}
10494
10495var ReactInternals$2 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
10496
10497var _ReactInternals$Sched$1 = ReactInternals$2.SchedulerTracing;
10498var __interactionsRef = _ReactInternals$Sched$1.__interactionsRef;
10499var __subscriberRef = _ReactInternals$Sched$1.__subscriberRef;
10500var unstable_clear = _ReactInternals$Sched$1.unstable_clear;
10501var unstable_getCurrent = _ReactInternals$Sched$1.unstable_getCurrent;
10502var unstable_getThreadID = _ReactInternals$Sched$1.unstable_getThreadID;
10503var unstable_subscribe = _ReactInternals$Sched$1.unstable_subscribe;
10504var unstable_trace = _ReactInternals$Sched$1.unstable_trace;
10505var unstable_unsubscribe = _ReactInternals$Sched$1.unstable_unsubscribe;
10506var unstable_wrap = _ReactInternals$Sched$1.unstable_wrap;
10507
10508// TODO: This should be lifted into the renderer.
10509
10510
10511// The following attributes are only used by interaction tracing builds.
10512// They enable interactions to be associated with their async work,
10513// And expose interaction metadata to the React DevTools Profiler plugin.
10514// Note that these attributes are only defined when the enableSchedulerTracing flag is enabled.
10515
10516
10517// Exported FiberRoot type includes all properties,
10518// To avoid requiring potentially error-prone :any casts throughout the project.
10519// Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true).
10520// The types are defined separately within this file to ensure they stay in sync.
10521// (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.)
10522
10523
10524function createFiberRoot(containerInfo, isConcurrent, hydrate) {
10525 // Cyclic construction. This cheats the type system right now because
10526 // stateNode is any.
10527 var uninitializedFiber = createHostRootFiber(isConcurrent);
10528
10529 var root = void 0;
10530 if (enableSchedulerTracing) {
10531 root = {
10532 current: uninitializedFiber,
10533 containerInfo: containerInfo,
10534 pendingChildren: null,
10535
10536 earliestPendingTime: NoWork,
10537 latestPendingTime: NoWork,
10538 earliestSuspendedTime: NoWork,
10539 latestSuspendedTime: NoWork,
10540 latestPingedTime: NoWork,
10541
10542 pingCache: null,
10543
10544 didError: false,
10545
10546 pendingCommitExpirationTime: NoWork,
10547 finishedWork: null,
10548 timeoutHandle: noTimeout,
10549 context: null,
10550 pendingContext: null,
10551 hydrate: hydrate,
10552 nextExpirationTimeToWorkOn: NoWork,
10553 expirationTime: NoWork,
10554 firstBatch: null,
10555 nextScheduledRoot: null,
10556
10557 interactionThreadID: unstable_getThreadID(),
10558 memoizedInteractions: new Set(),
10559 pendingInteractionMap: new Map()
10560 };
10561 } else {
10562 root = {
10563 current: uninitializedFiber,
10564 containerInfo: containerInfo,
10565 pendingChildren: null,
10566
10567 pingCache: null,
10568
10569 earliestPendingTime: NoWork,
10570 latestPendingTime: NoWork,
10571 earliestSuspendedTime: NoWork,
10572 latestSuspendedTime: NoWork,
10573 latestPingedTime: NoWork,
10574
10575 didError: false,
10576
10577 pendingCommitExpirationTime: NoWork,
10578 finishedWork: null,
10579 timeoutHandle: noTimeout,
10580 context: null,
10581 pendingContext: null,
10582 hydrate: hydrate,
10583 nextExpirationTimeToWorkOn: NoWork,
10584 expirationTime: NoWork,
10585 firstBatch: null,
10586 nextScheduledRoot: null
10587 };
10588 }
10589
10590 uninitializedFiber.stateNode = root;
10591
10592 // The reason for the way the Flow types are structured in this file,
10593 // Is to avoid needing :any casts everywhere interaction tracing fields are used.
10594 // Unfortunately that requires an :any cast for non-interaction tracing capable builds.
10595 // $FlowFixMe Remove this :any cast and replace it with something better.
10596 return root;
10597}
10598
10599/**
10600 * Forked from fbjs/warning:
10601 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
10602 *
10603 * Only change is we use console.warn instead of console.error,
10604 * and do nothing when 'console' is not supported.
10605 * This really simplifies the code.
10606 * ---
10607 * Similar to invariant but only logs a warning if the condition is not met.
10608 * This can be used to log issues in development environments in critical
10609 * paths. Removing the logging code for production environments will keep the
10610 * same logic and follow the same code paths.
10611 */
10612
10613var lowPriorityWarning = function () {};
10614
10615{
10616 var printWarning$1 = function (format) {
10617 for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
10618 args[_key - 1] = arguments[_key];
10619 }
10620
10621 var argIndex = 0;
10622 var message = 'Warning: ' + format.replace(/%s/g, function () {
10623 return args[argIndex++];
10624 });
10625 if (typeof console !== 'undefined') {
10626 console.warn(message);
10627 }
10628 try {
10629 // --- Welcome to debugging React ---
10630 // This error was thrown as a convenience so that you can use this stack
10631 // to find the callsite that caused this warning to fire.
10632 throw new Error(message);
10633 } catch (x) {}
10634 };
10635
10636 lowPriorityWarning = function (condition, format) {
10637 if (format === undefined) {
10638 throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
10639 }
10640 if (!condition) {
10641 for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
10642 args[_key2 - 2] = arguments[_key2];
10643 }
10644
10645 printWarning$1.apply(undefined, [format].concat(args));
10646 }
10647 };
10648}
10649
10650var lowPriorityWarning$1 = lowPriorityWarning;
10651
10652var ReactStrictModeWarnings = {
10653 discardPendingWarnings: function () {},
10654 flushPendingDeprecationWarnings: function () {},
10655 flushPendingUnsafeLifecycleWarnings: function () {},
10656 recordDeprecationWarnings: function (fiber, instance) {},
10657 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
10658 recordLegacyContextWarning: function (fiber, instance) {},
10659 flushLegacyContextWarning: function () {}
10660};
10661
10662{
10663 var LIFECYCLE_SUGGESTIONS = {
10664 UNSAFE_componentWillMount: 'componentDidMount',
10665 UNSAFE_componentWillReceiveProps: 'static getDerivedStateFromProps',
10666 UNSAFE_componentWillUpdate: 'componentDidUpdate'
10667 };
10668
10669 var pendingComponentWillMountWarnings = [];
10670 var pendingComponentWillReceivePropsWarnings = [];
10671 var pendingComponentWillUpdateWarnings = [];
10672 var pendingUnsafeLifecycleWarnings = new Map();
10673 var pendingLegacyContextWarning = new Map();
10674
10675 // Tracks components we have already warned about.
10676 var didWarnAboutDeprecatedLifecycles = new Set();
10677 var didWarnAboutUnsafeLifecycles = new Set();
10678 var didWarnAboutLegacyContext = new Set();
10679
10680 var setToSortedString = function (set) {
10681 var array = [];
10682 set.forEach(function (value) {
10683 array.push(value);
10684 });
10685 return array.sort().join(', ');
10686 };
10687
10688 ReactStrictModeWarnings.discardPendingWarnings = function () {
10689 pendingComponentWillMountWarnings = [];
10690 pendingComponentWillReceivePropsWarnings = [];
10691 pendingComponentWillUpdateWarnings = [];
10692 pendingUnsafeLifecycleWarnings = new Map();
10693 pendingLegacyContextWarning = new Map();
10694 };
10695
10696 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
10697 pendingUnsafeLifecycleWarnings.forEach(function (lifecycleWarningsMap, strictRoot) {
10698 var lifecyclesWarningMessages = [];
10699
10700 Object.keys(lifecycleWarningsMap).forEach(function (lifecycle) {
10701 var lifecycleWarnings = lifecycleWarningsMap[lifecycle];
10702 if (lifecycleWarnings.length > 0) {
10703 var componentNames = new Set();
10704 lifecycleWarnings.forEach(function (fiber) {
10705 componentNames.add(getComponentName(fiber.type) || 'Component');
10706 didWarnAboutUnsafeLifecycles.add(fiber.type);
10707 });
10708
10709 var formatted = lifecycle.replace('UNSAFE_', '');
10710 var suggestion = LIFECYCLE_SUGGESTIONS[lifecycle];
10711 var sortedComponentNames = setToSortedString(componentNames);
10712
10713 lifecyclesWarningMessages.push(formatted + ': Please update the following components to use ' + (suggestion + ' instead: ' + sortedComponentNames));
10714 }
10715 });
10716
10717 if (lifecyclesWarningMessages.length > 0) {
10718 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
10719
10720 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'));
10721 }
10722 });
10723
10724 pendingUnsafeLifecycleWarnings = new Map();
10725 };
10726
10727 var findStrictRoot = function (fiber) {
10728 var maybeStrictRoot = null;
10729
10730 var node = fiber;
10731 while (node !== null) {
10732 if (node.mode & StrictMode) {
10733 maybeStrictRoot = node;
10734 }
10735 node = node.return;
10736 }
10737
10738 return maybeStrictRoot;
10739 };
10740
10741 ReactStrictModeWarnings.flushPendingDeprecationWarnings = function () {
10742 if (pendingComponentWillMountWarnings.length > 0) {
10743 var uniqueNames = new Set();
10744 pendingComponentWillMountWarnings.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, '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);
10752
10753 pendingComponentWillMountWarnings = [];
10754 }
10755
10756 if (pendingComponentWillReceivePropsWarnings.length > 0) {
10757 var _uniqueNames = new Set();
10758 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
10759 _uniqueNames.add(getComponentName(fiber.type) || 'Component');
10760 didWarnAboutDeprecatedLifecycles.add(fiber.type);
10761 });
10762
10763 var _sortedNames = setToSortedString(_uniqueNames);
10764
10765 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);
10766
10767 pendingComponentWillReceivePropsWarnings = [];
10768 }
10769
10770 if (pendingComponentWillUpdateWarnings.length > 0) {
10771 var _uniqueNames2 = new Set();
10772 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
10773 _uniqueNames2.add(getComponentName(fiber.type) || 'Component');
10774 didWarnAboutDeprecatedLifecycles.add(fiber.type);
10775 });
10776
10777 var _sortedNames2 = setToSortedString(_uniqueNames2);
10778
10779 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);
10780
10781 pendingComponentWillUpdateWarnings = [];
10782 }
10783 };
10784
10785 ReactStrictModeWarnings.recordDeprecationWarnings = function (fiber, instance) {
10786 // Dedup strategy: Warn once per component.
10787 if (didWarnAboutDeprecatedLifecycles.has(fiber.type)) {
10788 return;
10789 }
10790
10791 // Don't warn about react-lifecycles-compat polyfilled components.
10792 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
10793 pendingComponentWillMountWarnings.push(fiber);
10794 }
10795 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
10796 pendingComponentWillReceivePropsWarnings.push(fiber);
10797 }
10798 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
10799 pendingComponentWillUpdateWarnings.push(fiber);
10800 }
10801 };
10802
10803 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
10804 var strictRoot = findStrictRoot(fiber);
10805 if (strictRoot === null) {
10806 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.');
10807 return;
10808 }
10809
10810 // Dedup strategy: Warn once per component.
10811 // This is difficult to track any other way since component names
10812 // are often vague and are likely to collide between 3rd party libraries.
10813 // An expand property is probably okay to use here since it's DEV-only,
10814 // and will only be set in the event of serious warnings.
10815 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
10816 return;
10817 }
10818
10819 var warningsForRoot = void 0;
10820 if (!pendingUnsafeLifecycleWarnings.has(strictRoot)) {
10821 warningsForRoot = {
10822 UNSAFE_componentWillMount: [],
10823 UNSAFE_componentWillReceiveProps: [],
10824 UNSAFE_componentWillUpdate: []
10825 };
10826
10827 pendingUnsafeLifecycleWarnings.set(strictRoot, warningsForRoot);
10828 } else {
10829 warningsForRoot = pendingUnsafeLifecycleWarnings.get(strictRoot);
10830 }
10831
10832 var unsafeLifecycles = [];
10833 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillMount === 'function') {
10834 unsafeLifecycles.push('UNSAFE_componentWillMount');
10835 }
10836 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
10837 unsafeLifecycles.push('UNSAFE_componentWillReceiveProps');
10838 }
10839 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillUpdate === 'function') {
10840 unsafeLifecycles.push('UNSAFE_componentWillUpdate');
10841 }
10842
10843 if (unsafeLifecycles.length > 0) {
10844 unsafeLifecycles.forEach(function (lifecycle) {
10845 warningsForRoot[lifecycle].push(fiber);
10846 });
10847 }
10848 };
10849
10850 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
10851 var strictRoot = findStrictRoot(fiber);
10852 if (strictRoot === null) {
10853 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.');
10854 return;
10855 }
10856
10857 // Dedup strategy: Warn once per component.
10858 if (didWarnAboutLegacyContext.has(fiber.type)) {
10859 return;
10860 }
10861
10862 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
10863
10864 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
10865 if (warningsForRoot === undefined) {
10866 warningsForRoot = [];
10867 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
10868 }
10869 warningsForRoot.push(fiber);
10870 }
10871 };
10872
10873 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
10874 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
10875 var uniqueNames = new Set();
10876 fiberArray.forEach(function (fiber) {
10877 uniqueNames.add(getComponentName(fiber.type) || 'Component');
10878 didWarnAboutLegacyContext.add(fiber.type);
10879 });
10880
10881 var sortedNames = setToSortedString(uniqueNames);
10882 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
10883
10884 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);
10885 });
10886 };
10887}
10888
10889// This lets us hook into Fiber to debug what it's doing.
10890// See https://github.com/facebook/react/pull/8033.
10891// This is not part of the public API, not even for React DevTools.
10892// You may only inject a debugTool if you work on React Fiber itself.
10893var ReactFiberInstrumentation = {
10894 debugTool: null
10895};
10896
10897var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
10898
10899// TODO: Offscreen updates should never suspend. However, a promise that
10900// suspended inside an offscreen subtree should be able to ping at the priority
10901// of the outer render.
10902
10903function markPendingPriorityLevel(root, expirationTime) {
10904 // If there's a gap between completing a failed root and retrying it,
10905 // additional updates may be scheduled. Clear `didError`, in case the update
10906 // is sufficient to fix the error.
10907 root.didError = false;
10908
10909 // Update the latest and earliest pending times
10910 var earliestPendingTime = root.earliestPendingTime;
10911 if (earliestPendingTime === NoWork) {
10912 // No other pending updates.
10913 root.earliestPendingTime = root.latestPendingTime = expirationTime;
10914 } else {
10915 if (earliestPendingTime < expirationTime) {
10916 // This is the earliest pending update.
10917 root.earliestPendingTime = expirationTime;
10918 } else {
10919 var latestPendingTime = root.latestPendingTime;
10920 if (latestPendingTime > expirationTime) {
10921 // This is the latest pending update
10922 root.latestPendingTime = expirationTime;
10923 }
10924 }
10925 }
10926 findNextExpirationTimeToWorkOn(expirationTime, root);
10927}
10928
10929function markCommittedPriorityLevels(root, earliestRemainingTime) {
10930 root.didError = false;
10931
10932 if (earliestRemainingTime === NoWork) {
10933 // Fast path. There's no remaining work. Clear everything.
10934 root.earliestPendingTime = NoWork;
10935 root.latestPendingTime = NoWork;
10936 root.earliestSuspendedTime = NoWork;
10937 root.latestSuspendedTime = NoWork;
10938 root.latestPingedTime = NoWork;
10939 findNextExpirationTimeToWorkOn(NoWork, root);
10940 return;
10941 }
10942
10943 if (earliestRemainingTime < root.latestPingedTime) {
10944 root.latestPingedTime = NoWork;
10945 }
10946
10947 // Let's see if the previous latest known pending level was just flushed.
10948 var latestPendingTime = root.latestPendingTime;
10949 if (latestPendingTime !== NoWork) {
10950 if (latestPendingTime > earliestRemainingTime) {
10951 // We've flushed all the known pending levels.
10952 root.earliestPendingTime = root.latestPendingTime = NoWork;
10953 } else {
10954 var earliestPendingTime = root.earliestPendingTime;
10955 if (earliestPendingTime > earliestRemainingTime) {
10956 // We've flushed the earliest known pending level. Set this to the
10957 // latest pending time.
10958 root.earliestPendingTime = root.latestPendingTime;
10959 }
10960 }
10961 }
10962
10963 // Now let's handle the earliest remaining level in the whole tree. We need to
10964 // decide whether to treat it as a pending level or as suspended. Check
10965 // it falls within the range of known suspended levels.
10966
10967 var earliestSuspendedTime = root.earliestSuspendedTime;
10968 if (earliestSuspendedTime === NoWork) {
10969 // There's no suspended work. Treat the earliest remaining level as a
10970 // pending level.
10971 markPendingPriorityLevel(root, earliestRemainingTime);
10972 findNextExpirationTimeToWorkOn(NoWork, root);
10973 return;
10974 }
10975
10976 var latestSuspendedTime = root.latestSuspendedTime;
10977 if (earliestRemainingTime < latestSuspendedTime) {
10978 // The earliest remaining level is later than all the suspended work. That
10979 // means we've flushed all the suspended work.
10980 root.earliestSuspendedTime = NoWork;
10981 root.latestSuspendedTime = NoWork;
10982 root.latestPingedTime = NoWork;
10983
10984 // There's no suspended work. Treat the earliest remaining level as a
10985 // pending level.
10986 markPendingPriorityLevel(root, earliestRemainingTime);
10987 findNextExpirationTimeToWorkOn(NoWork, root);
10988 return;
10989 }
10990
10991 if (earliestRemainingTime > earliestSuspendedTime) {
10992 // The earliest remaining time is earlier than all the suspended work.
10993 // Treat it as a pending update.
10994 markPendingPriorityLevel(root, earliestRemainingTime);
10995 findNextExpirationTimeToWorkOn(NoWork, root);
10996 return;
10997 }
10998
10999 // The earliest remaining time falls within the range of known suspended
11000 // levels. We should treat this as suspended work.
11001 findNextExpirationTimeToWorkOn(NoWork, root);
11002}
11003
11004function hasLowerPriorityWork(root, erroredExpirationTime) {
11005 var latestPendingTime = root.latestPendingTime;
11006 var latestSuspendedTime = root.latestSuspendedTime;
11007 var latestPingedTime = root.latestPingedTime;
11008 return latestPendingTime !== NoWork && latestPendingTime < erroredExpirationTime || latestSuspendedTime !== NoWork && latestSuspendedTime < erroredExpirationTime || latestPingedTime !== NoWork && latestPingedTime < erroredExpirationTime;
11009}
11010
11011function isPriorityLevelSuspended(root, expirationTime) {
11012 var earliestSuspendedTime = root.earliestSuspendedTime;
11013 var latestSuspendedTime = root.latestSuspendedTime;
11014 return earliestSuspendedTime !== NoWork && expirationTime <= earliestSuspendedTime && expirationTime >= latestSuspendedTime;
11015}
11016
11017function markSuspendedPriorityLevel(root, suspendedTime) {
11018 root.didError = false;
11019 clearPing(root, suspendedTime);
11020
11021 // First, check the known pending levels and update them if needed.
11022 var earliestPendingTime = root.earliestPendingTime;
11023 var latestPendingTime = root.latestPendingTime;
11024 if (earliestPendingTime === suspendedTime) {
11025 if (latestPendingTime === suspendedTime) {
11026 // Both known pending levels were suspended. Clear them.
11027 root.earliestPendingTime = root.latestPendingTime = NoWork;
11028 } else {
11029 // The earliest pending level was suspended. Clear by setting it to the
11030 // latest pending level.
11031 root.earliestPendingTime = latestPendingTime;
11032 }
11033 } else if (latestPendingTime === suspendedTime) {
11034 // The latest pending level was suspended. Clear by setting it to the
11035 // latest pending level.
11036 root.latestPendingTime = earliestPendingTime;
11037 }
11038
11039 // Finally, update the known suspended levels.
11040 var earliestSuspendedTime = root.earliestSuspendedTime;
11041 var latestSuspendedTime = root.latestSuspendedTime;
11042 if (earliestSuspendedTime === NoWork) {
11043 // No other suspended levels.
11044 root.earliestSuspendedTime = root.latestSuspendedTime = suspendedTime;
11045 } else {
11046 if (earliestSuspendedTime < suspendedTime) {
11047 // This is the earliest suspended level.
11048 root.earliestSuspendedTime = suspendedTime;
11049 } else if (latestSuspendedTime > suspendedTime) {
11050 // This is the latest suspended level
11051 root.latestSuspendedTime = suspendedTime;
11052 }
11053 }
11054
11055 findNextExpirationTimeToWorkOn(suspendedTime, root);
11056}
11057
11058function markPingedPriorityLevel(root, pingedTime) {
11059 root.didError = false;
11060
11061 // TODO: When we add back resuming, we need to ensure the progressed work
11062 // is thrown out and not reused during the restarted render. One way to
11063 // invalidate the progressed work is to restart at expirationTime + 1.
11064 var latestPingedTime = root.latestPingedTime;
11065 if (latestPingedTime === NoWork || latestPingedTime > pingedTime) {
11066 root.latestPingedTime = pingedTime;
11067 }
11068 findNextExpirationTimeToWorkOn(pingedTime, root);
11069}
11070
11071function clearPing(root, completedTime) {
11072 var latestPingedTime = root.latestPingedTime;
11073 if (latestPingedTime >= completedTime) {
11074 root.latestPingedTime = NoWork;
11075 }
11076}
11077
11078function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) {
11079 var earliestExpirationTime = renderExpirationTime;
11080
11081 var earliestPendingTime = root.earliestPendingTime;
11082 var earliestSuspendedTime = root.earliestSuspendedTime;
11083 if (earliestPendingTime > earliestExpirationTime) {
11084 earliestExpirationTime = earliestPendingTime;
11085 }
11086 if (earliestSuspendedTime > earliestExpirationTime) {
11087 earliestExpirationTime = earliestSuspendedTime;
11088 }
11089 return earliestExpirationTime;
11090}
11091
11092function didExpireAtExpirationTime(root, currentTime) {
11093 var expirationTime = root.expirationTime;
11094 if (expirationTime !== NoWork && currentTime <= expirationTime) {
11095 // The root has expired. Flush all work up to the current time.
11096 root.nextExpirationTimeToWorkOn = currentTime;
11097 }
11098}
11099
11100function findNextExpirationTimeToWorkOn(completedExpirationTime, root) {
11101 var earliestSuspendedTime = root.earliestSuspendedTime;
11102 var latestSuspendedTime = root.latestSuspendedTime;
11103 var earliestPendingTime = root.earliestPendingTime;
11104 var latestPingedTime = root.latestPingedTime;
11105
11106 // Work on the earliest pending time. Failing that, work on the latest
11107 // pinged time.
11108 var nextExpirationTimeToWorkOn = earliestPendingTime !== NoWork ? earliestPendingTime : latestPingedTime;
11109
11110 // If there is no pending or pinged work, check if there's suspended work
11111 // that's lower priority than what we just completed.
11112 if (nextExpirationTimeToWorkOn === NoWork && (completedExpirationTime === NoWork || latestSuspendedTime < completedExpirationTime)) {
11113 // The lowest priority suspended work is the work most likely to be
11114 // committed next. Let's start rendering it again, so that if it times out,
11115 // it's ready to commit.
11116 nextExpirationTimeToWorkOn = latestSuspendedTime;
11117 }
11118
11119 var expirationTime = nextExpirationTimeToWorkOn;
11120 if (expirationTime !== NoWork && earliestSuspendedTime > expirationTime) {
11121 // Expire using the earliest known expiration time.
11122 expirationTime = earliestSuspendedTime;
11123 }
11124
11125 root.nextExpirationTimeToWorkOn = nextExpirationTimeToWorkOn;
11126 root.expirationTime = expirationTime;
11127}
11128
11129function resolveDefaultProps(Component, baseProps) {
11130 if (Component && Component.defaultProps) {
11131 // Resolve default props. Taken from ReactElement
11132 var props = _assign({}, baseProps);
11133 var defaultProps = Component.defaultProps;
11134 for (var propName in defaultProps) {
11135 if (props[propName] === undefined) {
11136 props[propName] = defaultProps[propName];
11137 }
11138 }
11139 return props;
11140 }
11141 return baseProps;
11142}
11143
11144function readLazyComponentType(lazyComponent) {
11145 var status = lazyComponent._status;
11146 var result = lazyComponent._result;
11147 switch (status) {
11148 case Resolved:
11149 {
11150 var Component = result;
11151 return Component;
11152 }
11153 case Rejected:
11154 {
11155 var error = result;
11156 throw error;
11157 }
11158 case Pending:
11159 {
11160 var thenable = result;
11161 throw thenable;
11162 }
11163 default:
11164 {
11165 lazyComponent._status = Pending;
11166 var ctor = lazyComponent._ctor;
11167 var _thenable = ctor();
11168 _thenable.then(function (moduleObject) {
11169 if (lazyComponent._status === Pending) {
11170 var defaultExport = moduleObject.default;
11171 {
11172 if (defaultExport === undefined) {
11173 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);
11174 }
11175 }
11176 lazyComponent._status = Resolved;
11177 lazyComponent._result = defaultExport;
11178 }
11179 }, function (error) {
11180 if (lazyComponent._status === Pending) {
11181 lazyComponent._status = Rejected;
11182 lazyComponent._result = error;
11183 }
11184 });
11185 // Handle synchronous thenables.
11186 switch (lazyComponent._status) {
11187 case Resolved:
11188 return lazyComponent._result;
11189 case Rejected:
11190 throw lazyComponent._result;
11191 }
11192 lazyComponent._result = _thenable;
11193 throw _thenable;
11194 }
11195 }
11196}
11197
11198var fakeInternalInstance = {};
11199var isArray$1 = Array.isArray;
11200
11201// React.Component uses a shared frozen object by default.
11202// We'll use it to determine whether we need to initialize legacy refs.
11203var emptyRefsObject = new React.Component().refs;
11204
11205var didWarnAboutStateAssignmentForComponent = void 0;
11206var didWarnAboutUninitializedState = void 0;
11207var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0;
11208var didWarnAboutLegacyLifecyclesAndDerivedState = void 0;
11209var didWarnAboutUndefinedDerivedState = void 0;
11210var warnOnUndefinedDerivedState = void 0;
11211var warnOnInvalidCallback$1 = void 0;
11212var didWarnAboutDirectlyAssigningPropsToState = void 0;
11213var didWarnAboutContextTypeAndContextTypes = void 0;
11214var didWarnAboutInvalidateContextType = void 0;
11215
11216{
11217 didWarnAboutStateAssignmentForComponent = new Set();
11218 didWarnAboutUninitializedState = new Set();
11219 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
11220 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
11221 didWarnAboutDirectlyAssigningPropsToState = new Set();
11222 didWarnAboutUndefinedDerivedState = new Set();
11223 didWarnAboutContextTypeAndContextTypes = new Set();
11224 didWarnAboutInvalidateContextType = new Set();
11225
11226 var didWarnOnInvalidCallback = new Set();
11227
11228 warnOnInvalidCallback$1 = function (callback, callerName) {
11229 if (callback === null || typeof callback === 'function') {
11230 return;
11231 }
11232 var key = callerName + '_' + callback;
11233 if (!didWarnOnInvalidCallback.has(key)) {
11234 didWarnOnInvalidCallback.add(key);
11235 warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
11236 }
11237 };
11238
11239 warnOnUndefinedDerivedState = function (type, partialState) {
11240 if (partialState === undefined) {
11241 var componentName = getComponentName(type) || 'Component';
11242 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
11243 didWarnAboutUndefinedDerivedState.add(componentName);
11244 warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
11245 }
11246 }
11247 };
11248
11249 // This is so gross but it's at least non-critical and can be removed if
11250 // it causes problems. This is meant to give a nicer error message for
11251 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
11252 // ...)) which otherwise throws a "_processChildContext is not a function"
11253 // exception.
11254 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
11255 enumerable: false,
11256 value: function () {
11257 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).');
11258 }
11259 });
11260 Object.freeze(fakeInternalInstance);
11261}
11262
11263function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
11264 var prevState = workInProgress.memoizedState;
11265
11266 {
11267 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
11268 // Invoke the function an extra time to help detect side-effects.
11269 getDerivedStateFromProps(nextProps, prevState);
11270 }
11271 }
11272
11273 var partialState = getDerivedStateFromProps(nextProps, prevState);
11274
11275 {
11276 warnOnUndefinedDerivedState(ctor, partialState);
11277 }
11278 // Merge the partial state and the previous state.
11279 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
11280 workInProgress.memoizedState = memoizedState;
11281
11282 // Once the update queue is empty, persist the derived state onto the
11283 // base state.
11284 var updateQueue = workInProgress.updateQueue;
11285 if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
11286 updateQueue.baseState = memoizedState;
11287 }
11288}
11289
11290var classComponentUpdater = {
11291 isMounted: isMounted,
11292 enqueueSetState: function (inst, payload, callback) {
11293 var fiber = get(inst);
11294 var currentTime = requestCurrentTime();
11295 var expirationTime = computeExpirationForFiber(currentTime, fiber);
11296
11297 var update = createUpdate(expirationTime);
11298 update.payload = payload;
11299 if (callback !== undefined && callback !== null) {
11300 {
11301 warnOnInvalidCallback$1(callback, 'setState');
11302 }
11303 update.callback = callback;
11304 }
11305
11306 flushPassiveEffects();
11307 enqueueUpdate(fiber, update);
11308 scheduleWork(fiber, expirationTime);
11309 },
11310 enqueueReplaceState: function (inst, payload, callback) {
11311 var fiber = get(inst);
11312 var currentTime = requestCurrentTime();
11313 var expirationTime = computeExpirationForFiber(currentTime, fiber);
11314
11315 var update = createUpdate(expirationTime);
11316 update.tag = ReplaceState;
11317 update.payload = payload;
11318
11319 if (callback !== undefined && callback !== null) {
11320 {
11321 warnOnInvalidCallback$1(callback, 'replaceState');
11322 }
11323 update.callback = callback;
11324 }
11325
11326 flushPassiveEffects();
11327 enqueueUpdate(fiber, update);
11328 scheduleWork(fiber, expirationTime);
11329 },
11330 enqueueForceUpdate: function (inst, callback) {
11331 var fiber = get(inst);
11332 var currentTime = requestCurrentTime();
11333 var expirationTime = computeExpirationForFiber(currentTime, fiber);
11334
11335 var update = createUpdate(expirationTime);
11336 update.tag = ForceUpdate;
11337
11338 if (callback !== undefined && callback !== null) {
11339 {
11340 warnOnInvalidCallback$1(callback, 'forceUpdate');
11341 }
11342 update.callback = callback;
11343 }
11344
11345 flushPassiveEffects();
11346 enqueueUpdate(fiber, update);
11347 scheduleWork(fiber, expirationTime);
11348 }
11349};
11350
11351function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
11352 var instance = workInProgress.stateNode;
11353 if (typeof instance.shouldComponentUpdate === 'function') {
11354 startPhaseTimer(workInProgress, 'shouldComponentUpdate');
11355 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
11356 stopPhaseTimer();
11357
11358 {
11359 !(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;
11360 }
11361
11362 return shouldUpdate;
11363 }
11364
11365 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
11366 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
11367 }
11368
11369 return true;
11370}
11371
11372function checkClassInstance(workInProgress, ctor, newProps) {
11373 var instance = workInProgress.stateNode;
11374 {
11375 var name = getComponentName(ctor) || 'Component';
11376 var renderPresent = instance.render;
11377
11378 if (!renderPresent) {
11379 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
11380 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
11381 } else {
11382 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
11383 }
11384 }
11385
11386 var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
11387 !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;
11388 var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
11389 !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;
11390 var noInstancePropTypes = !instance.propTypes;
11391 !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
11392 var noInstanceContextType = !instance.contextType;
11393 !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0;
11394 var noInstanceContextTypes = !instance.contextTypes;
11395 !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
11396
11397 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
11398 didWarnAboutContextTypeAndContextTypes.add(ctor);
11399 warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
11400 }
11401
11402 var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
11403 !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;
11404 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
11405 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');
11406 }
11407 var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
11408 !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
11409 var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
11410 !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;
11411 var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
11412 !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
11413 var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
11414 !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
11415 var hasMutatedProps = instance.props !== newProps;
11416 !(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;
11417 var noInstanceDefaultProps = !instance.defaultProps;
11418 !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;
11419
11420 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
11421 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
11422 warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
11423 }
11424
11425 var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
11426 !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;
11427 var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function';
11428 !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;
11429 var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function';
11430 !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;
11431 var _state = instance.state;
11432 if (_state && (typeof _state !== 'object' || isArray$1(_state))) {
11433 warningWithoutStack$1(false, '%s.state: must be set to an object or null', name);
11434 }
11435 if (typeof instance.getChildContext === 'function') {
11436 !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
11437 }
11438 }
11439}
11440
11441function adoptClassInstance(workInProgress, instance) {
11442 instance.updater = classComponentUpdater;
11443 workInProgress.stateNode = instance;
11444 // The instance needs access to the fiber so that it can schedule updates
11445 set(instance, workInProgress);
11446 {
11447 instance._reactInternalInstance = fakeInternalInstance;
11448 }
11449}
11450
11451function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) {
11452 var isLegacyContextConsumer = false;
11453 var unmaskedContext = emptyContextObject;
11454 var context = null;
11455 var contextType = ctor.contextType;
11456
11457 {
11458 if ('contextType' in ctor) {
11459 var isValid =
11460 // Allow null for conditional declaration
11461 contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
11462
11463 if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
11464 didWarnAboutInvalidateContextType.add(ctor);
11465
11466 var addendum = '';
11467 if (contextType === undefined) {
11468 addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
11469 } else if (typeof contextType !== 'object') {
11470 addendum = ' However, it is set to a ' + typeof contextType + '.';
11471 } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
11472 addendum = ' Did you accidentally pass the Context.Provider instead?';
11473 } else if (contextType._context !== undefined) {
11474 // <Context.Consumer>
11475 addendum = ' Did you accidentally pass the Context.Consumer instead?';
11476 } else {
11477 addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
11478 }
11479 warningWithoutStack$1(false, '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);
11480 }
11481 }
11482 }
11483
11484 if (typeof contextType === 'object' && contextType !== null) {
11485 context = readContext(contextType);
11486 } else {
11487 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11488 var contextTypes = ctor.contextTypes;
11489 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
11490 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
11491 }
11492
11493 // Instantiate twice to help detect side-effects.
11494 {
11495 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
11496 new ctor(props, context); // eslint-disable-line no-new
11497 }
11498 }
11499
11500 var instance = new ctor(props, context);
11501 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
11502 adoptClassInstance(workInProgress, instance);
11503
11504 {
11505 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
11506 var componentName = getComponentName(ctor) || 'Component';
11507 if (!didWarnAboutUninitializedState.has(componentName)) {
11508 didWarnAboutUninitializedState.add(componentName);
11509 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);
11510 }
11511 }
11512
11513 // If new component APIs are defined, "unsafe" lifecycles won't be called.
11514 // Warn about these lifecycles if they are present.
11515 // Don't warn about react-lifecycles-compat polyfilled methods though.
11516 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
11517 var foundWillMountName = null;
11518 var foundWillReceivePropsName = null;
11519 var foundWillUpdateName = null;
11520 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
11521 foundWillMountName = 'componentWillMount';
11522 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
11523 foundWillMountName = 'UNSAFE_componentWillMount';
11524 }
11525 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
11526 foundWillReceivePropsName = 'componentWillReceiveProps';
11527 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
11528 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
11529 }
11530 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
11531 foundWillUpdateName = 'componentWillUpdate';
11532 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
11533 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
11534 }
11535 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
11536 var _componentName = getComponentName(ctor) || 'Component';
11537 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
11538 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
11539 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
11540 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 : '');
11541 }
11542 }
11543 }
11544 }
11545
11546 // Cache unmasked context so we can avoid recreating masked context unless necessary.
11547 // ReactFiberContext usually updates this cache but can't for newly-created instances.
11548 if (isLegacyContextConsumer) {
11549 cacheContext(workInProgress, unmaskedContext, context);
11550 }
11551
11552 return instance;
11553}
11554
11555function callComponentWillMount(workInProgress, instance) {
11556 startPhaseTimer(workInProgress, 'componentWillMount');
11557 var oldState = instance.state;
11558
11559 if (typeof instance.componentWillMount === 'function') {
11560 instance.componentWillMount();
11561 }
11562 if (typeof instance.UNSAFE_componentWillMount === 'function') {
11563 instance.UNSAFE_componentWillMount();
11564 }
11565
11566 stopPhaseTimer();
11567
11568 if (oldState !== instance.state) {
11569 {
11570 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');
11571 }
11572 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
11573 }
11574}
11575
11576function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
11577 var oldState = instance.state;
11578 startPhaseTimer(workInProgress, 'componentWillReceiveProps');
11579 if (typeof instance.componentWillReceiveProps === 'function') {
11580 instance.componentWillReceiveProps(newProps, nextContext);
11581 }
11582 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
11583 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
11584 }
11585 stopPhaseTimer();
11586
11587 if (instance.state !== oldState) {
11588 {
11589 var componentName = getComponentName(workInProgress.type) || 'Component';
11590 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
11591 didWarnAboutStateAssignmentForComponent.add(componentName);
11592 warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
11593 }
11594 }
11595 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
11596 }
11597}
11598
11599// Invokes the mount life-cycles on a previously never rendered instance.
11600function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
11601 {
11602 checkClassInstance(workInProgress, ctor, newProps);
11603 }
11604
11605 var instance = workInProgress.stateNode;
11606 instance.props = newProps;
11607 instance.state = workInProgress.memoizedState;
11608 instance.refs = emptyRefsObject;
11609
11610 var contextType = ctor.contextType;
11611 if (typeof contextType === 'object' && contextType !== null) {
11612 instance.context = readContext(contextType);
11613 } else {
11614 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11615 instance.context = getMaskedContext(workInProgress, unmaskedContext);
11616 }
11617
11618 {
11619 if (instance.state === newProps) {
11620 var componentName = getComponentName(ctor) || 'Component';
11621 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
11622 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
11623 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);
11624 }
11625 }
11626
11627 if (workInProgress.mode & StrictMode) {
11628 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
11629
11630 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
11631 }
11632
11633 if (warnAboutDeprecatedLifecycles) {
11634 ReactStrictModeWarnings.recordDeprecationWarnings(workInProgress, instance);
11635 }
11636 }
11637
11638 var updateQueue = workInProgress.updateQueue;
11639 if (updateQueue !== null) {
11640 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11641 instance.state = workInProgress.memoizedState;
11642 }
11643
11644 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
11645 if (typeof getDerivedStateFromProps === 'function') {
11646 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
11647 instance.state = workInProgress.memoizedState;
11648 }
11649
11650 // In order to support react-lifecycles-compat polyfilled components,
11651 // Unsafe lifecycles should not be invoked for components using the new APIs.
11652 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
11653 callComponentWillMount(workInProgress, instance);
11654 // If we had additional state updates during this life-cycle, let's
11655 // process them now.
11656 updateQueue = workInProgress.updateQueue;
11657 if (updateQueue !== null) {
11658 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11659 instance.state = workInProgress.memoizedState;
11660 }
11661 }
11662
11663 if (typeof instance.componentDidMount === 'function') {
11664 workInProgress.effectTag |= Update;
11665 }
11666}
11667
11668function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
11669 var instance = workInProgress.stateNode;
11670
11671 var oldProps = workInProgress.memoizedProps;
11672 instance.props = oldProps;
11673
11674 var oldContext = instance.context;
11675 var contextType = ctor.contextType;
11676 var nextContext = void 0;
11677 if (typeof contextType === 'object' && contextType !== null) {
11678 nextContext = readContext(contextType);
11679 } else {
11680 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11681 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
11682 }
11683
11684 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
11685 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
11686
11687 // Note: During these life-cycles, instance.props/instance.state are what
11688 // ever the previously attempted to render - not the "current". However,
11689 // during componentDidUpdate we pass the "current" props.
11690
11691 // In order to support react-lifecycles-compat polyfilled components,
11692 // Unsafe lifecycles should not be invoked for components using the new APIs.
11693 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
11694 if (oldProps !== newProps || oldContext !== nextContext) {
11695 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
11696 }
11697 }
11698
11699 resetHasForceUpdateBeforeProcessing();
11700
11701 var oldState = workInProgress.memoizedState;
11702 var newState = instance.state = oldState;
11703 var updateQueue = workInProgress.updateQueue;
11704 if (updateQueue !== null) {
11705 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11706 newState = workInProgress.memoizedState;
11707 }
11708 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
11709 // If an update was already in progress, we should schedule an Update
11710 // effect even though we're bailing out, so that cWU/cDU are called.
11711 if (typeof instance.componentDidMount === 'function') {
11712 workInProgress.effectTag |= Update;
11713 }
11714 return false;
11715 }
11716
11717 if (typeof getDerivedStateFromProps === 'function') {
11718 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
11719 newState = workInProgress.memoizedState;
11720 }
11721
11722 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
11723
11724 if (shouldUpdate) {
11725 // In order to support react-lifecycles-compat polyfilled components,
11726 // Unsafe lifecycles should not be invoked for components using the new APIs.
11727 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
11728 startPhaseTimer(workInProgress, 'componentWillMount');
11729 if (typeof instance.componentWillMount === 'function') {
11730 instance.componentWillMount();
11731 }
11732 if (typeof instance.UNSAFE_componentWillMount === 'function') {
11733 instance.UNSAFE_componentWillMount();
11734 }
11735 stopPhaseTimer();
11736 }
11737 if (typeof instance.componentDidMount === 'function') {
11738 workInProgress.effectTag |= Update;
11739 }
11740 } else {
11741 // If an update was already in progress, we should schedule an Update
11742 // effect even though we're bailing out, so that cWU/cDU are called.
11743 if (typeof instance.componentDidMount === 'function') {
11744 workInProgress.effectTag |= Update;
11745 }
11746
11747 // If shouldComponentUpdate returned false, we should still update the
11748 // memoized state to indicate that this work can be reused.
11749 workInProgress.memoizedProps = newProps;
11750 workInProgress.memoizedState = newState;
11751 }
11752
11753 // Update the existing instance's state, props, and context pointers even
11754 // if shouldComponentUpdate returns false.
11755 instance.props = newProps;
11756 instance.state = newState;
11757 instance.context = nextContext;
11758
11759 return shouldUpdate;
11760}
11761
11762// Invokes the update life-cycles and returns false if it shouldn't rerender.
11763function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
11764 var instance = workInProgress.stateNode;
11765
11766 var oldProps = workInProgress.memoizedProps;
11767 instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
11768
11769 var oldContext = instance.context;
11770 var contextType = ctor.contextType;
11771 var nextContext = void 0;
11772 if (typeof contextType === 'object' && contextType !== null) {
11773 nextContext = readContext(contextType);
11774 } else {
11775 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11776 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
11777 }
11778
11779 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
11780 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
11781
11782 // Note: During these life-cycles, instance.props/instance.state are what
11783 // ever the previously attempted to render - not the "current". However,
11784 // during componentDidUpdate we pass the "current" props.
11785
11786 // In order to support react-lifecycles-compat polyfilled components,
11787 // Unsafe lifecycles should not be invoked for components using the new APIs.
11788 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
11789 if (oldProps !== newProps || oldContext !== nextContext) {
11790 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
11791 }
11792 }
11793
11794 resetHasForceUpdateBeforeProcessing();
11795
11796 var oldState = workInProgress.memoizedState;
11797 var newState = instance.state = oldState;
11798 var updateQueue = workInProgress.updateQueue;
11799 if (updateQueue !== null) {
11800 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11801 newState = workInProgress.memoizedState;
11802 }
11803
11804 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
11805 // If an update was already in progress, we should schedule an Update
11806 // effect even though we're bailing out, so that cWU/cDU are called.
11807 if (typeof instance.componentDidUpdate === 'function') {
11808 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11809 workInProgress.effectTag |= Update;
11810 }
11811 }
11812 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
11813 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11814 workInProgress.effectTag |= Snapshot;
11815 }
11816 }
11817 return false;
11818 }
11819
11820 if (typeof getDerivedStateFromProps === 'function') {
11821 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
11822 newState = workInProgress.memoizedState;
11823 }
11824
11825 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
11826
11827 if (shouldUpdate) {
11828 // In order to support react-lifecycles-compat polyfilled components,
11829 // Unsafe lifecycles should not be invoked for components using the new APIs.
11830 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
11831 startPhaseTimer(workInProgress, 'componentWillUpdate');
11832 if (typeof instance.componentWillUpdate === 'function') {
11833 instance.componentWillUpdate(newProps, newState, nextContext);
11834 }
11835 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
11836 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
11837 }
11838 stopPhaseTimer();
11839 }
11840 if (typeof instance.componentDidUpdate === 'function') {
11841 workInProgress.effectTag |= Update;
11842 }
11843 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
11844 workInProgress.effectTag |= Snapshot;
11845 }
11846 } else {
11847 // If an update was already in progress, we should schedule an Update
11848 // effect even though we're bailing out, so that cWU/cDU are called.
11849 if (typeof instance.componentDidUpdate === 'function') {
11850 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11851 workInProgress.effectTag |= Update;
11852 }
11853 }
11854 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
11855 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11856 workInProgress.effectTag |= Snapshot;
11857 }
11858 }
11859
11860 // If shouldComponentUpdate returned false, we should still update the
11861 // memoized props/state to indicate that this work can be reused.
11862 workInProgress.memoizedProps = newProps;
11863 workInProgress.memoizedState = newState;
11864 }
11865
11866 // Update the existing instance's state, props, and context pointers even
11867 // if shouldComponentUpdate returns false.
11868 instance.props = newProps;
11869 instance.state = newState;
11870 instance.context = nextContext;
11871
11872 return shouldUpdate;
11873}
11874
11875var didWarnAboutMaps = void 0;
11876var didWarnAboutGenerators = void 0;
11877var didWarnAboutStringRefInStrictMode = void 0;
11878var ownerHasKeyUseWarning = void 0;
11879var ownerHasFunctionTypeWarning = void 0;
11880var warnForMissingKey = function (child) {};
11881
11882{
11883 didWarnAboutMaps = false;
11884 didWarnAboutGenerators = false;
11885 didWarnAboutStringRefInStrictMode = {};
11886
11887 /**
11888 * Warn if there's no key explicitly set on dynamic arrays of children or
11889 * object keys are not valid. This allows us to keep track of children between
11890 * updates.
11891 */
11892 ownerHasKeyUseWarning = {};
11893 ownerHasFunctionTypeWarning = {};
11894
11895 warnForMissingKey = function (child) {
11896 if (child === null || typeof child !== 'object') {
11897 return;
11898 }
11899 if (!child._store || child._store.validated || child.key != null) {
11900 return;
11901 }
11902 !(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;
11903 child._store.validated = true;
11904
11905 var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
11906 if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
11907 return;
11908 }
11909 ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
11910
11911 warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
11912 };
11913}
11914
11915var isArray = Array.isArray;
11916
11917function coerceRef(returnFiber, current$$1, element) {
11918 var mixedRef = element.ref;
11919 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
11920 {
11921 if (returnFiber.mode & StrictMode) {
11922 var componentName = getComponentName(returnFiber.type) || 'Component';
11923 if (!didWarnAboutStringRefInStrictMode[componentName]) {
11924 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));
11925 didWarnAboutStringRefInStrictMode[componentName] = true;
11926 }
11927 }
11928 }
11929
11930 if (element._owner) {
11931 var owner = element._owner;
11932 var inst = void 0;
11933 if (owner) {
11934 var ownerFiber = owner;
11935 !(ownerFiber.tag === ClassComponent) ? invariant(false, 'Function components cannot have refs. Did you mean to use React.forwardRef()?') : void 0;
11936 inst = ownerFiber.stateNode;
11937 }
11938 !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;
11939 var stringRef = '' + mixedRef;
11940 // Check if previous string ref matches new string ref
11941 if (current$$1 !== null && current$$1.ref !== null && typeof current$$1.ref === 'function' && current$$1.ref._stringRef === stringRef) {
11942 return current$$1.ref;
11943 }
11944 var ref = function (value) {
11945 var refs = inst.refs;
11946 if (refs === emptyRefsObject) {
11947 // This is a lazy pooled frozen object, so we need to initialize.
11948 refs = inst.refs = {};
11949 }
11950 if (value === null) {
11951 delete refs[stringRef];
11952 } else {
11953 refs[stringRef] = value;
11954 }
11955 };
11956 ref._stringRef = stringRef;
11957 return ref;
11958 } else {
11959 !(typeof mixedRef === 'string') ? invariant(false, 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.') : void 0;
11960 !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;
11961 }
11962 }
11963 return mixedRef;
11964}
11965
11966function throwOnInvalidObjectType(returnFiber, newChild) {
11967 if (returnFiber.type !== 'textarea') {
11968 var addendum = '';
11969 {
11970 addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
11971 }
11972 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);
11973 }
11974}
11975
11976function warnOnFunctionType() {
11977 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();
11978
11979 if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
11980 return;
11981 }
11982 ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
11983
11984 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.');
11985}
11986
11987// This wrapper function exists because I expect to clone the code in each path
11988// to be able to optimize each path individually by branching early. This needs
11989// a compiler or we can do it manually. Helpers that don't need this branching
11990// live outside of this function.
11991function ChildReconciler(shouldTrackSideEffects) {
11992 function deleteChild(returnFiber, childToDelete) {
11993 if (!shouldTrackSideEffects) {
11994 // Noop.
11995 return;
11996 }
11997 // Deletions are added in reversed order so we add it to the front.
11998 // At this point, the return fiber's effect list is empty except for
11999 // deletions, so we can just append the deletion to the list. The remaining
12000 // effects aren't added until the complete phase. Once we implement
12001 // resuming, this may not be true.
12002 var last = returnFiber.lastEffect;
12003 if (last !== null) {
12004 last.nextEffect = childToDelete;
12005 returnFiber.lastEffect = childToDelete;
12006 } else {
12007 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
12008 }
12009 childToDelete.nextEffect = null;
12010 childToDelete.effectTag = Deletion;
12011 }
12012
12013 function deleteRemainingChildren(returnFiber, currentFirstChild) {
12014 if (!shouldTrackSideEffects) {
12015 // Noop.
12016 return null;
12017 }
12018
12019 // TODO: For the shouldClone case, this could be micro-optimized a bit by
12020 // assuming that after the first child we've already added everything.
12021 var childToDelete = currentFirstChild;
12022 while (childToDelete !== null) {
12023 deleteChild(returnFiber, childToDelete);
12024 childToDelete = childToDelete.sibling;
12025 }
12026 return null;
12027 }
12028
12029 function mapRemainingChildren(returnFiber, currentFirstChild) {
12030 // Add the remaining children to a temporary map so that we can find them by
12031 // keys quickly. Implicit (null) keys get added to this set with their index
12032 var existingChildren = new Map();
12033
12034 var existingChild = currentFirstChild;
12035 while (existingChild !== null) {
12036 if (existingChild.key !== null) {
12037 existingChildren.set(existingChild.key, existingChild);
12038 } else {
12039 existingChildren.set(existingChild.index, existingChild);
12040 }
12041 existingChild = existingChild.sibling;
12042 }
12043 return existingChildren;
12044 }
12045
12046 function useFiber(fiber, pendingProps, expirationTime) {
12047 // We currently set sibling to null and index to 0 here because it is easy
12048 // to forget to do before returning it. E.g. for the single child case.
12049 var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
12050 clone.index = 0;
12051 clone.sibling = null;
12052 return clone;
12053 }
12054
12055 function placeChild(newFiber, lastPlacedIndex, newIndex) {
12056 newFiber.index = newIndex;
12057 if (!shouldTrackSideEffects) {
12058 // Noop.
12059 return lastPlacedIndex;
12060 }
12061 var current$$1 = newFiber.alternate;
12062 if (current$$1 !== null) {
12063 var oldIndex = current$$1.index;
12064 if (oldIndex < lastPlacedIndex) {
12065 // This is a move.
12066 newFiber.effectTag = Placement;
12067 return lastPlacedIndex;
12068 } else {
12069 // This item can stay in place.
12070 return oldIndex;
12071 }
12072 } else {
12073 // This is an insertion.
12074 newFiber.effectTag = Placement;
12075 return lastPlacedIndex;
12076 }
12077 }
12078
12079 function placeSingleChild(newFiber) {
12080 // This is simpler for the single child case. We only need to do a
12081 // placement for inserting new children.
12082 if (shouldTrackSideEffects && newFiber.alternate === null) {
12083 newFiber.effectTag = Placement;
12084 }
12085 return newFiber;
12086 }
12087
12088 function updateTextNode(returnFiber, current$$1, textContent, expirationTime) {
12089 if (current$$1 === null || current$$1.tag !== HostText) {
12090 // Insert
12091 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
12092 created.return = returnFiber;
12093 return created;
12094 } else {
12095 // Update
12096 var existing = useFiber(current$$1, textContent, expirationTime);
12097 existing.return = returnFiber;
12098 return existing;
12099 }
12100 }
12101
12102 function updateElement(returnFiber, current$$1, element, expirationTime) {
12103 if (current$$1 !== null && current$$1.elementType === element.type) {
12104 // Move based on index
12105 var existing = useFiber(current$$1, element.props, expirationTime);
12106 existing.ref = coerceRef(returnFiber, current$$1, element);
12107 existing.return = returnFiber;
12108 {
12109 existing._debugSource = element._source;
12110 existing._debugOwner = element._owner;
12111 }
12112 return existing;
12113 } else {
12114 // Insert
12115 var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
12116 created.ref = coerceRef(returnFiber, current$$1, element);
12117 created.return = returnFiber;
12118 return created;
12119 }
12120 }
12121
12122 function updatePortal(returnFiber, current$$1, portal, expirationTime) {
12123 if (current$$1 === null || current$$1.tag !== HostPortal || current$$1.stateNode.containerInfo !== portal.containerInfo || current$$1.stateNode.implementation !== portal.implementation) {
12124 // Insert
12125 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
12126 created.return = returnFiber;
12127 return created;
12128 } else {
12129 // Update
12130 var existing = useFiber(current$$1, portal.children || [], expirationTime);
12131 existing.return = returnFiber;
12132 return existing;
12133 }
12134 }
12135
12136 function updateFragment(returnFiber, current$$1, fragment, expirationTime, key) {
12137 if (current$$1 === null || current$$1.tag !== Fragment) {
12138 // Insert
12139 var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
12140 created.return = returnFiber;
12141 return created;
12142 } else {
12143 // Update
12144 var existing = useFiber(current$$1, fragment, expirationTime);
12145 existing.return = returnFiber;
12146 return existing;
12147 }
12148 }
12149
12150 function createChild(returnFiber, newChild, expirationTime) {
12151 if (typeof newChild === 'string' || typeof newChild === 'number') {
12152 // Text nodes don't have keys. If the previous node is implicitly keyed
12153 // we can continue to replace it without aborting even if it is not a text
12154 // node.
12155 var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
12156 created.return = returnFiber;
12157 return created;
12158 }
12159
12160 if (typeof newChild === 'object' && newChild !== null) {
12161 switch (newChild.$$typeof) {
12162 case REACT_ELEMENT_TYPE:
12163 {
12164 var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
12165 _created.ref = coerceRef(returnFiber, null, newChild);
12166 _created.return = returnFiber;
12167 return _created;
12168 }
12169 case REACT_PORTAL_TYPE:
12170 {
12171 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
12172 _created2.return = returnFiber;
12173 return _created2;
12174 }
12175 }
12176
12177 if (isArray(newChild) || getIteratorFn(newChild)) {
12178 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
12179 _created3.return = returnFiber;
12180 return _created3;
12181 }
12182
12183 throwOnInvalidObjectType(returnFiber, newChild);
12184 }
12185
12186 {
12187 if (typeof newChild === 'function') {
12188 warnOnFunctionType();
12189 }
12190 }
12191
12192 return null;
12193 }
12194
12195 function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
12196 // Update the fiber if the keys match, otherwise return null.
12197
12198 var key = oldFiber !== null ? oldFiber.key : null;
12199
12200 if (typeof newChild === 'string' || typeof newChild === 'number') {
12201 // Text nodes don't have keys. If the previous node is implicitly keyed
12202 // we can continue to replace it without aborting even if it is not a text
12203 // node.
12204 if (key !== null) {
12205 return null;
12206 }
12207 return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
12208 }
12209
12210 if (typeof newChild === 'object' && newChild !== null) {
12211 switch (newChild.$$typeof) {
12212 case REACT_ELEMENT_TYPE:
12213 {
12214 if (newChild.key === key) {
12215 if (newChild.type === REACT_FRAGMENT_TYPE) {
12216 return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
12217 }
12218 return updateElement(returnFiber, oldFiber, newChild, expirationTime);
12219 } else {
12220 return null;
12221 }
12222 }
12223 case REACT_PORTAL_TYPE:
12224 {
12225 if (newChild.key === key) {
12226 return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
12227 } else {
12228 return null;
12229 }
12230 }
12231 }
12232
12233 if (isArray(newChild) || getIteratorFn(newChild)) {
12234 if (key !== null) {
12235 return null;
12236 }
12237
12238 return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
12239 }
12240
12241 throwOnInvalidObjectType(returnFiber, newChild);
12242 }
12243
12244 {
12245 if (typeof newChild === 'function') {
12246 warnOnFunctionType();
12247 }
12248 }
12249
12250 return null;
12251 }
12252
12253 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
12254 if (typeof newChild === 'string' || typeof newChild === 'number') {
12255 // Text nodes don't have keys, so we neither have to check the old nor
12256 // new node for the key. If both are text nodes, they match.
12257 var matchedFiber = existingChildren.get(newIdx) || null;
12258 return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
12259 }
12260
12261 if (typeof newChild === 'object' && newChild !== null) {
12262 switch (newChild.$$typeof) {
12263 case REACT_ELEMENT_TYPE:
12264 {
12265 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
12266 if (newChild.type === REACT_FRAGMENT_TYPE) {
12267 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
12268 }
12269 return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
12270 }
12271 case REACT_PORTAL_TYPE:
12272 {
12273 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
12274 return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
12275 }
12276 }
12277
12278 if (isArray(newChild) || getIteratorFn(newChild)) {
12279 var _matchedFiber3 = existingChildren.get(newIdx) || null;
12280 return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
12281 }
12282
12283 throwOnInvalidObjectType(returnFiber, newChild);
12284 }
12285
12286 {
12287 if (typeof newChild === 'function') {
12288 warnOnFunctionType();
12289 }
12290 }
12291
12292 return null;
12293 }
12294
12295 /**
12296 * Warns if there is a duplicate or missing key
12297 */
12298 function warnOnInvalidKey(child, knownKeys) {
12299 {
12300 if (typeof child !== 'object' || child === null) {
12301 return knownKeys;
12302 }
12303 switch (child.$$typeof) {
12304 case REACT_ELEMENT_TYPE:
12305 case REACT_PORTAL_TYPE:
12306 warnForMissingKey(child);
12307 var key = child.key;
12308 if (typeof key !== 'string') {
12309 break;
12310 }
12311 if (knownKeys === null) {
12312 knownKeys = new Set();
12313 knownKeys.add(key);
12314 break;
12315 }
12316 if (!knownKeys.has(key)) {
12317 knownKeys.add(key);
12318 break;
12319 }
12320 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);
12321 break;
12322 default:
12323 break;
12324 }
12325 }
12326 return knownKeys;
12327 }
12328
12329 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
12330 // This algorithm can't optimize by searching from both ends since we
12331 // don't have backpointers on fibers. I'm trying to see how far we can get
12332 // with that model. If it ends up not being worth the tradeoffs, we can
12333 // add it later.
12334
12335 // Even with a two ended optimization, we'd want to optimize for the case
12336 // where there are few changes and brute force the comparison instead of
12337 // going for the Map. It'd like to explore hitting that path first in
12338 // forward-only mode and only go for the Map once we notice that we need
12339 // lots of look ahead. This doesn't handle reversal as well as two ended
12340 // search but that's unusual. Besides, for the two ended optimization to
12341 // work on Iterables, we'd need to copy the whole set.
12342
12343 // In this first iteration, we'll just live with hitting the bad case
12344 // (adding everything to a Map) in for every insert/move.
12345
12346 // If you change this code, also update reconcileChildrenIterator() which
12347 // uses the same algorithm.
12348
12349 {
12350 // First, validate keys.
12351 var knownKeys = null;
12352 for (var i = 0; i < newChildren.length; i++) {
12353 var child = newChildren[i];
12354 knownKeys = warnOnInvalidKey(child, knownKeys);
12355 }
12356 }
12357
12358 var resultingFirstChild = null;
12359 var previousNewFiber = null;
12360
12361 var oldFiber = currentFirstChild;
12362 var lastPlacedIndex = 0;
12363 var newIdx = 0;
12364 var nextOldFiber = null;
12365 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
12366 if (oldFiber.index > newIdx) {
12367 nextOldFiber = oldFiber;
12368 oldFiber = null;
12369 } else {
12370 nextOldFiber = oldFiber.sibling;
12371 }
12372 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
12373 if (newFiber === null) {
12374 // TODO: This breaks on empty slots like null children. That's
12375 // unfortunate because it triggers the slow path all the time. We need
12376 // a better way to communicate whether this was a miss or null,
12377 // boolean, undefined, etc.
12378 if (oldFiber === null) {
12379 oldFiber = nextOldFiber;
12380 }
12381 break;
12382 }
12383 if (shouldTrackSideEffects) {
12384 if (oldFiber && newFiber.alternate === null) {
12385 // We matched the slot, but we didn't reuse the existing fiber, so we
12386 // need to delete the existing child.
12387 deleteChild(returnFiber, oldFiber);
12388 }
12389 }
12390 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
12391 if (previousNewFiber === null) {
12392 // TODO: Move out of the loop. This only happens for the first run.
12393 resultingFirstChild = newFiber;
12394 } else {
12395 // TODO: Defer siblings if we're not at the right index for this slot.
12396 // I.e. if we had null values before, then we want to defer this
12397 // for each null value. However, we also don't want to call updateSlot
12398 // with the previous one.
12399 previousNewFiber.sibling = newFiber;
12400 }
12401 previousNewFiber = newFiber;
12402 oldFiber = nextOldFiber;
12403 }
12404
12405 if (newIdx === newChildren.length) {
12406 // We've reached the end of the new children. We can delete the rest.
12407 deleteRemainingChildren(returnFiber, oldFiber);
12408 return resultingFirstChild;
12409 }
12410
12411 if (oldFiber === null) {
12412 // If we don't have any more existing children we can choose a fast path
12413 // since the rest will all be insertions.
12414 for (; newIdx < newChildren.length; newIdx++) {
12415 var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
12416 if (!_newFiber) {
12417 continue;
12418 }
12419 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
12420 if (previousNewFiber === null) {
12421 // TODO: Move out of the loop. This only happens for the first run.
12422 resultingFirstChild = _newFiber;
12423 } else {
12424 previousNewFiber.sibling = _newFiber;
12425 }
12426 previousNewFiber = _newFiber;
12427 }
12428 return resultingFirstChild;
12429 }
12430
12431 // Add all children to a key map for quick lookups.
12432 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
12433
12434 // Keep scanning and use the map to restore deleted items as moves.
12435 for (; newIdx < newChildren.length; newIdx++) {
12436 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
12437 if (_newFiber2) {
12438 if (shouldTrackSideEffects) {
12439 if (_newFiber2.alternate !== null) {
12440 // The new fiber is a work in progress, but if there exists a
12441 // current, that means that we reused the fiber. We need to delete
12442 // it from the child list so that we don't add it to the deletion
12443 // list.
12444 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
12445 }
12446 }
12447 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
12448 if (previousNewFiber === null) {
12449 resultingFirstChild = _newFiber2;
12450 } else {
12451 previousNewFiber.sibling = _newFiber2;
12452 }
12453 previousNewFiber = _newFiber2;
12454 }
12455 }
12456
12457 if (shouldTrackSideEffects) {
12458 // Any existing children that weren't consumed above were deleted. We need
12459 // to add them to the deletion list.
12460 existingChildren.forEach(function (child) {
12461 return deleteChild(returnFiber, child);
12462 });
12463 }
12464
12465 return resultingFirstChild;
12466 }
12467
12468 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
12469 // This is the same implementation as reconcileChildrenArray(),
12470 // but using the iterator instead.
12471
12472 var iteratorFn = getIteratorFn(newChildrenIterable);
12473 !(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;
12474
12475 {
12476 // We don't support rendering Generators because it's a mutation.
12477 // See https://github.com/facebook/react/issues/12995
12478 if (typeof Symbol === 'function' &&
12479 // $FlowFixMe Flow doesn't know about toStringTag
12480 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
12481 !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;
12482 didWarnAboutGenerators = true;
12483 }
12484
12485 // Warn about using Maps as children
12486 if (newChildrenIterable.entries === iteratorFn) {
12487 !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;
12488 didWarnAboutMaps = true;
12489 }
12490
12491 // First, validate keys.
12492 // We'll get a different iterator later for the main pass.
12493 var _newChildren = iteratorFn.call(newChildrenIterable);
12494 if (_newChildren) {
12495 var knownKeys = null;
12496 var _step = _newChildren.next();
12497 for (; !_step.done; _step = _newChildren.next()) {
12498 var child = _step.value;
12499 knownKeys = warnOnInvalidKey(child, knownKeys);
12500 }
12501 }
12502 }
12503
12504 var newChildren = iteratorFn.call(newChildrenIterable);
12505 !(newChildren != null) ? invariant(false, 'An iterable object provided no iterator.') : void 0;
12506
12507 var resultingFirstChild = null;
12508 var previousNewFiber = null;
12509
12510 var oldFiber = currentFirstChild;
12511 var lastPlacedIndex = 0;
12512 var newIdx = 0;
12513 var nextOldFiber = null;
12514
12515 var step = newChildren.next();
12516 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
12517 if (oldFiber.index > newIdx) {
12518 nextOldFiber = oldFiber;
12519 oldFiber = null;
12520 } else {
12521 nextOldFiber = oldFiber.sibling;
12522 }
12523 var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
12524 if (newFiber === null) {
12525 // TODO: This breaks on empty slots like null children. That's
12526 // unfortunate because it triggers the slow path all the time. We need
12527 // a better way to communicate whether this was a miss or null,
12528 // boolean, undefined, etc.
12529 if (!oldFiber) {
12530 oldFiber = nextOldFiber;
12531 }
12532 break;
12533 }
12534 if (shouldTrackSideEffects) {
12535 if (oldFiber && newFiber.alternate === null) {
12536 // We matched the slot, but we didn't reuse the existing fiber, so we
12537 // need to delete the existing child.
12538 deleteChild(returnFiber, oldFiber);
12539 }
12540 }
12541 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
12542 if (previousNewFiber === null) {
12543 // TODO: Move out of the loop. This only happens for the first run.
12544 resultingFirstChild = newFiber;
12545 } else {
12546 // TODO: Defer siblings if we're not at the right index for this slot.
12547 // I.e. if we had null values before, then we want to defer this
12548 // for each null value. However, we also don't want to call updateSlot
12549 // with the previous one.
12550 previousNewFiber.sibling = newFiber;
12551 }
12552 previousNewFiber = newFiber;
12553 oldFiber = nextOldFiber;
12554 }
12555
12556 if (step.done) {
12557 // We've reached the end of the new children. We can delete the rest.
12558 deleteRemainingChildren(returnFiber, oldFiber);
12559 return resultingFirstChild;
12560 }
12561
12562 if (oldFiber === null) {
12563 // If we don't have any more existing children we can choose a fast path
12564 // since the rest will all be insertions.
12565 for (; !step.done; newIdx++, step = newChildren.next()) {
12566 var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
12567 if (_newFiber3 === null) {
12568 continue;
12569 }
12570 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
12571 if (previousNewFiber === null) {
12572 // TODO: Move out of the loop. This only happens for the first run.
12573 resultingFirstChild = _newFiber3;
12574 } else {
12575 previousNewFiber.sibling = _newFiber3;
12576 }
12577 previousNewFiber = _newFiber3;
12578 }
12579 return resultingFirstChild;
12580 }
12581
12582 // Add all children to a key map for quick lookups.
12583 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
12584
12585 // Keep scanning and use the map to restore deleted items as moves.
12586 for (; !step.done; newIdx++, step = newChildren.next()) {
12587 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
12588 if (_newFiber4 !== null) {
12589 if (shouldTrackSideEffects) {
12590 if (_newFiber4.alternate !== null) {
12591 // The new fiber is a work in progress, but if there exists a
12592 // current, that means that we reused the fiber. We need to delete
12593 // it from the child list so that we don't add it to the deletion
12594 // list.
12595 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
12596 }
12597 }
12598 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
12599 if (previousNewFiber === null) {
12600 resultingFirstChild = _newFiber4;
12601 } else {
12602 previousNewFiber.sibling = _newFiber4;
12603 }
12604 previousNewFiber = _newFiber4;
12605 }
12606 }
12607
12608 if (shouldTrackSideEffects) {
12609 // Any existing children that weren't consumed above were deleted. We need
12610 // to add them to the deletion list.
12611 existingChildren.forEach(function (child) {
12612 return deleteChild(returnFiber, child);
12613 });
12614 }
12615
12616 return resultingFirstChild;
12617 }
12618
12619 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
12620 // There's no need to check for keys on text nodes since we don't have a
12621 // way to define them.
12622 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
12623 // We already have an existing node so let's just update it and delete
12624 // the rest.
12625 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
12626 var existing = useFiber(currentFirstChild, textContent, expirationTime);
12627 existing.return = returnFiber;
12628 return existing;
12629 }
12630 // The existing first child is not a text node so we need to create one
12631 // and delete the existing ones.
12632 deleteRemainingChildren(returnFiber, currentFirstChild);
12633 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
12634 created.return = returnFiber;
12635 return created;
12636 }
12637
12638 function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
12639 var key = element.key;
12640 var child = currentFirstChild;
12641 while (child !== null) {
12642 // TODO: If key === null and child.key === null, then this only applies to
12643 // the first item in the list.
12644 if (child.key === key) {
12645 if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.elementType === element.type) {
12646 deleteRemainingChildren(returnFiber, child.sibling);
12647 var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
12648 existing.ref = coerceRef(returnFiber, child, element);
12649 existing.return = returnFiber;
12650 {
12651 existing._debugSource = element._source;
12652 existing._debugOwner = element._owner;
12653 }
12654 return existing;
12655 } else {
12656 deleteRemainingChildren(returnFiber, child);
12657 break;
12658 }
12659 } else {
12660 deleteChild(returnFiber, child);
12661 }
12662 child = child.sibling;
12663 }
12664
12665 if (element.type === REACT_FRAGMENT_TYPE) {
12666 var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
12667 created.return = returnFiber;
12668 return created;
12669 } else {
12670 var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
12671 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
12672 _created4.return = returnFiber;
12673 return _created4;
12674 }
12675 }
12676
12677 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
12678 var key = portal.key;
12679 var child = currentFirstChild;
12680 while (child !== null) {
12681 // TODO: If key === null and child.key === null, then this only applies to
12682 // the first item in the list.
12683 if (child.key === key) {
12684 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
12685 deleteRemainingChildren(returnFiber, child.sibling);
12686 var existing = useFiber(child, portal.children || [], expirationTime);
12687 existing.return = returnFiber;
12688 return existing;
12689 } else {
12690 deleteRemainingChildren(returnFiber, child);
12691 break;
12692 }
12693 } else {
12694 deleteChild(returnFiber, child);
12695 }
12696 child = child.sibling;
12697 }
12698
12699 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
12700 created.return = returnFiber;
12701 return created;
12702 }
12703
12704 // This API will tag the children with the side-effect of the reconciliation
12705 // itself. They will be added to the side-effect list as we pass through the
12706 // children and the parent.
12707 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
12708 // This function is not recursive.
12709 // If the top level item is an array, we treat it as a set of children,
12710 // not as a fragment. Nested arrays on the other hand will be treated as
12711 // fragment nodes. Recursion happens at the normal flow.
12712
12713 // Handle top level unkeyed fragments as if they were arrays.
12714 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
12715 // We treat the ambiguous cases above the same.
12716 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
12717 if (isUnkeyedTopLevelFragment) {
12718 newChild = newChild.props.children;
12719 }
12720
12721 // Handle object types
12722 var isObject = typeof newChild === 'object' && newChild !== null;
12723
12724 if (isObject) {
12725 switch (newChild.$$typeof) {
12726 case REACT_ELEMENT_TYPE:
12727 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
12728 case REACT_PORTAL_TYPE:
12729 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
12730 }
12731 }
12732
12733 if (typeof newChild === 'string' || typeof newChild === 'number') {
12734 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
12735 }
12736
12737 if (isArray(newChild)) {
12738 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
12739 }
12740
12741 if (getIteratorFn(newChild)) {
12742 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
12743 }
12744
12745 if (isObject) {
12746 throwOnInvalidObjectType(returnFiber, newChild);
12747 }
12748
12749 {
12750 if (typeof newChild === 'function') {
12751 warnOnFunctionType();
12752 }
12753 }
12754 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
12755 // If the new child is undefined, and the return fiber is a composite
12756 // component, throw an error. If Fiber return types are disabled,
12757 // we already threw above.
12758 switch (returnFiber.tag) {
12759 case ClassComponent:
12760 {
12761 {
12762 var instance = returnFiber.stateNode;
12763 if (instance.render._isMockFunction) {
12764 // We allow auto-mocks to proceed as if they're returning null.
12765 break;
12766 }
12767 }
12768 }
12769 // Intentionally fall through to the next case, which handles both
12770 // functions and classes
12771 // eslint-disable-next-lined no-fallthrough
12772 case FunctionComponent:
12773 {
12774 var Component = returnFiber.type;
12775 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');
12776 }
12777 }
12778 }
12779
12780 // Remaining cases are all treated as empty.
12781 return deleteRemainingChildren(returnFiber, currentFirstChild);
12782 }
12783
12784 return reconcileChildFibers;
12785}
12786
12787var reconcileChildFibers = ChildReconciler(true);
12788var mountChildFibers = ChildReconciler(false);
12789
12790function cloneChildFibers(current$$1, workInProgress) {
12791 !(current$$1 === null || workInProgress.child === current$$1.child) ? invariant(false, 'Resuming work not yet implemented.') : void 0;
12792
12793 if (workInProgress.child === null) {
12794 return;
12795 }
12796
12797 var currentChild = workInProgress.child;
12798 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
12799 workInProgress.child = newChild;
12800
12801 newChild.return = workInProgress;
12802 while (currentChild.sibling !== null) {
12803 currentChild = currentChild.sibling;
12804 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
12805 newChild.return = workInProgress;
12806 }
12807 newChild.sibling = null;
12808}
12809
12810var NO_CONTEXT = {};
12811
12812var contextStackCursor$1 = createCursor(NO_CONTEXT);
12813var contextFiberStackCursor = createCursor(NO_CONTEXT);
12814var rootInstanceStackCursor = createCursor(NO_CONTEXT);
12815
12816function requiredContext(c) {
12817 !(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;
12818 return c;
12819}
12820
12821function getRootHostContainer() {
12822 var rootInstance = requiredContext(rootInstanceStackCursor.current);
12823 return rootInstance;
12824}
12825
12826function pushHostContainer(fiber, nextRootInstance) {
12827 // Push current root instance onto the stack;
12828 // This allows us to reset root when portals are popped.
12829 push(rootInstanceStackCursor, nextRootInstance, fiber);
12830 // Track the context and the Fiber that provided it.
12831 // This enables us to pop only Fibers that provide unique contexts.
12832 push(contextFiberStackCursor, fiber, fiber);
12833
12834 // Finally, we need to push the host context to the stack.
12835 // However, we can't just call getRootHostContext() and push it because
12836 // we'd have a different number of entries on the stack depending on
12837 // whether getRootHostContext() throws somewhere in renderer code or not.
12838 // So we push an empty value first. This lets us safely unwind on errors.
12839 push(contextStackCursor$1, NO_CONTEXT, fiber);
12840 var nextRootContext = getRootHostContext(nextRootInstance);
12841 // Now that we know this function doesn't throw, replace it.
12842 pop(contextStackCursor$1, fiber);
12843 push(contextStackCursor$1, nextRootContext, fiber);
12844}
12845
12846function popHostContainer(fiber) {
12847 pop(contextStackCursor$1, fiber);
12848 pop(contextFiberStackCursor, fiber);
12849 pop(rootInstanceStackCursor, fiber);
12850}
12851
12852function getHostContext() {
12853 var context = requiredContext(contextStackCursor$1.current);
12854 return context;
12855}
12856
12857function pushHostContext(fiber) {
12858 var rootInstance = requiredContext(rootInstanceStackCursor.current);
12859 var context = requiredContext(contextStackCursor$1.current);
12860 var nextContext = getChildHostContext(context, fiber.type, rootInstance);
12861
12862 // Don't push this Fiber's context unless it's unique.
12863 if (context === nextContext) {
12864 return;
12865 }
12866
12867 // Track the context and the Fiber that provided it.
12868 // This enables us to pop only Fibers that provide unique contexts.
12869 push(contextFiberStackCursor, fiber, fiber);
12870 push(contextStackCursor$1, nextContext, fiber);
12871}
12872
12873function popHostContext(fiber) {
12874 // Do not pop unless this Fiber provided the current context.
12875 // pushHostContext() only pushes Fibers that provide unique contexts.
12876 if (contextFiberStackCursor.current !== fiber) {
12877 return;
12878 }
12879
12880 pop(contextStackCursor$1, fiber);
12881 pop(contextFiberStackCursor, fiber);
12882}
12883
12884var NoEffect$1 = /* */0;
12885var UnmountSnapshot = /* */2;
12886var UnmountMutation = /* */4;
12887var MountMutation = /* */8;
12888var UnmountLayout = /* */16;
12889var MountLayout = /* */32;
12890var MountPassive = /* */64;
12891var UnmountPassive = /* */128;
12892
12893var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
12894
12895
12896var didWarnAboutMismatchedHooksForComponent = void 0;
12897{
12898 didWarnAboutMismatchedHooksForComponent = new Set();
12899}
12900
12901// These are set right before calling the component.
12902var renderExpirationTime = NoWork;
12903// The work-in-progress fiber. I've named it differently to distinguish it from
12904// the work-in-progress hook.
12905var currentlyRenderingFiber$1 = null;
12906
12907// Hooks are stored as a linked list on the fiber's memoizedState field. The
12908// current hook list is the list that belongs to the current fiber. The
12909// work-in-progress hook list is a new list that will be added to the
12910// work-in-progress fiber.
12911var currentHook = null;
12912var nextCurrentHook = null;
12913var firstWorkInProgressHook = null;
12914var workInProgressHook = null;
12915var nextWorkInProgressHook = null;
12916
12917var remainingExpirationTime = NoWork;
12918var componentUpdateQueue = null;
12919var sideEffectTag = 0;
12920
12921// Updates scheduled during render will trigger an immediate re-render at the
12922// end of the current pass. We can't store these updates on the normal queue,
12923// because if the work is aborted, they should be discarded. Because this is
12924// a relatively rare case, we also don't want to add an additional field to
12925// either the hook or queue object types. So we store them in a lazily create
12926// map of queue -> render-phase updates, which are discarded once the component
12927// completes without re-rendering.
12928
12929// Whether an update was scheduled during the currently executing render pass.
12930var didScheduleRenderPhaseUpdate = false;
12931// Lazily created map of render-phase updates
12932var renderPhaseUpdates = null;
12933// Counter to prevent infinite loops.
12934var numberOfReRenders = 0;
12935var RE_RENDER_LIMIT = 25;
12936
12937// In DEV, this is the name of the currently executing primitive hook
12938var currentHookNameInDev = null;
12939
12940// In DEV, this list ensures that hooks are called in the same order between renders.
12941// The list stores the order of hooks used during the initial render (mount).
12942// Subsequent renders (updates) reference this list.
12943var hookTypesDev = null;
12944var hookTypesUpdateIndexDev = -1;
12945
12946function mountHookTypesDev() {
12947 {
12948 var hookName = currentHookNameInDev;
12949
12950 if (hookTypesDev === null) {
12951 hookTypesDev = [hookName];
12952 } else {
12953 hookTypesDev.push(hookName);
12954 }
12955 }
12956}
12957
12958function updateHookTypesDev() {
12959 {
12960 var hookName = currentHookNameInDev;
12961
12962 if (hookTypesDev !== null) {
12963 hookTypesUpdateIndexDev++;
12964 if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
12965 warnOnHookMismatchInDev(hookName);
12966 }
12967 }
12968 }
12969}
12970
12971function warnOnHookMismatchInDev(currentHookName) {
12972 {
12973 var componentName = getComponentName(currentlyRenderingFiber$1.type);
12974 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
12975 didWarnAboutMismatchedHooksForComponent.add(componentName);
12976
12977 if (hookTypesDev !== null) {
12978 var table = '';
12979
12980 var secondColumnStart = 30;
12981
12982 for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
12983 var oldHookName = hookTypesDev[i];
12984 var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
12985
12986 var row = i + 1 + '. ' + oldHookName;
12987
12988 // Extra space so second column lines up
12989 // lol @ IE not supporting String#repeat
12990 while (row.length < secondColumnStart) {
12991 row += ' ';
12992 }
12993
12994 row += newHookName + '\n';
12995
12996 table += row;
12997 }
12998
12999 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);
13000 }
13001 }
13002 }
13003}
13004
13005function throwInvalidHookError() {
13006 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.');
13007}
13008
13009function areHookInputsEqual(nextDeps, prevDeps) {
13010 if (prevDeps === null) {
13011 {
13012 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);
13013 }
13014 return false;
13015 }
13016
13017 {
13018 // Don't bother comparing lengths in prod because these arrays should be
13019 // passed inline.
13020 if (nextDeps.length !== prevDeps.length) {
13021 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(', ') + ']');
13022 }
13023 }
13024 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
13025 if (is(nextDeps[i], prevDeps[i])) {
13026 continue;
13027 }
13028 return false;
13029 }
13030 return true;
13031}
13032
13033function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) {
13034 renderExpirationTime = nextRenderExpirationTime;
13035 currentlyRenderingFiber$1 = workInProgress;
13036 nextCurrentHook = current !== null ? current.memoizedState : null;
13037
13038 {
13039 hookTypesDev = current !== null ? current._debugHookTypes : null;
13040 hookTypesUpdateIndexDev = -1;
13041 }
13042
13043 // The following should have already been reset
13044 // currentHook = null;
13045 // workInProgressHook = null;
13046
13047 // remainingExpirationTime = NoWork;
13048 // componentUpdateQueue = null;
13049
13050 // didScheduleRenderPhaseUpdate = false;
13051 // renderPhaseUpdates = null;
13052 // numberOfReRenders = 0;
13053 // sideEffectTag = 0;
13054
13055 // TODO Warn if no hooks are used at all during mount, then some are used during update.
13056 // Currently we will identify the update render as a mount because nextCurrentHook === null.
13057 // This is tricky because it's valid for certain types of components (e.g. React.lazy)
13058
13059 // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used.
13060 // Non-stateful hooks (e.g. context) don't get added to memoizedState,
13061 // so nextCurrentHook would be null during updates and mounts.
13062 {
13063 if (nextCurrentHook !== null) {
13064 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
13065 } else if (hookTypesDev !== null) {
13066 // This dispatcher handles an edge case where a component is updating,
13067 // but no stateful hooks have been used.
13068 // We want to match the production code behavior (which will use HooksDispatcherOnMount),
13069 // but with the extra DEV validation to ensure hooks ordering hasn't changed.
13070 // This dispatcher does that.
13071 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
13072 } else {
13073 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
13074 }
13075 }
13076
13077 var children = Component(props, refOrContext);
13078
13079 if (didScheduleRenderPhaseUpdate) {
13080 do {
13081 didScheduleRenderPhaseUpdate = false;
13082 numberOfReRenders += 1;
13083
13084 // Start over from the beginning of the list
13085 nextCurrentHook = current !== null ? current.memoizedState : null;
13086 nextWorkInProgressHook = firstWorkInProgressHook;
13087
13088 currentHook = null;
13089 workInProgressHook = null;
13090 componentUpdateQueue = null;
13091
13092 {
13093 // Also validate hook order for cascading updates.
13094 hookTypesUpdateIndexDev = -1;
13095 }
13096
13097 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
13098
13099 children = Component(props, refOrContext);
13100 } while (didScheduleRenderPhaseUpdate);
13101
13102 renderPhaseUpdates = null;
13103 numberOfReRenders = 0;
13104 }
13105
13106 // We can assume the previous dispatcher is always this one, since we set it
13107 // at the beginning of the render phase and there's no re-entrancy.
13108 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
13109
13110 var renderedWork = currentlyRenderingFiber$1;
13111
13112 renderedWork.memoizedState = firstWorkInProgressHook;
13113 renderedWork.expirationTime = remainingExpirationTime;
13114 renderedWork.updateQueue = componentUpdateQueue;
13115 renderedWork.effectTag |= sideEffectTag;
13116
13117 {
13118 renderedWork._debugHookTypes = hookTypesDev;
13119 }
13120
13121 // This check uses currentHook so that it works the same in DEV and prod bundles.
13122 // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
13123 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
13124
13125 renderExpirationTime = NoWork;
13126 currentlyRenderingFiber$1 = null;
13127
13128 currentHook = null;
13129 nextCurrentHook = null;
13130 firstWorkInProgressHook = null;
13131 workInProgressHook = null;
13132 nextWorkInProgressHook = null;
13133
13134 {
13135 currentHookNameInDev = null;
13136 hookTypesDev = null;
13137 hookTypesUpdateIndexDev = -1;
13138 }
13139
13140 remainingExpirationTime = NoWork;
13141 componentUpdateQueue = null;
13142 sideEffectTag = 0;
13143
13144 // These were reset above
13145 // didScheduleRenderPhaseUpdate = false;
13146 // renderPhaseUpdates = null;
13147 // numberOfReRenders = 0;
13148
13149 !!didRenderTooFewHooks ? invariant(false, 'Rendered fewer hooks than expected. This may be caused by an accidental early return statement.') : void 0;
13150
13151 return children;
13152}
13153
13154function bailoutHooks(current, workInProgress, expirationTime) {
13155 workInProgress.updateQueue = current.updateQueue;
13156 workInProgress.effectTag &= ~(Passive | Update);
13157 if (current.expirationTime <= expirationTime) {
13158 current.expirationTime = NoWork;
13159 }
13160}
13161
13162function resetHooks() {
13163 // We can assume the previous dispatcher is always this one, since we set it
13164 // at the beginning of the render phase and there's no re-entrancy.
13165 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
13166
13167 // This is used to reset the state of this module when a component throws.
13168 // It's also called inside mountIndeterminateComponent if we determine the
13169 // component is a module-style component.
13170 renderExpirationTime = NoWork;
13171 currentlyRenderingFiber$1 = null;
13172
13173 currentHook = null;
13174 nextCurrentHook = null;
13175 firstWorkInProgressHook = null;
13176 workInProgressHook = null;
13177 nextWorkInProgressHook = null;
13178
13179 {
13180 hookTypesDev = null;
13181 hookTypesUpdateIndexDev = -1;
13182
13183 currentHookNameInDev = null;
13184 }
13185
13186 remainingExpirationTime = NoWork;
13187 componentUpdateQueue = null;
13188 sideEffectTag = 0;
13189
13190 didScheduleRenderPhaseUpdate = false;
13191 renderPhaseUpdates = null;
13192 numberOfReRenders = 0;
13193}
13194
13195function mountWorkInProgressHook() {
13196 var hook = {
13197 memoizedState: null,
13198
13199 baseState: null,
13200 queue: null,
13201 baseUpdate: null,
13202
13203 next: null
13204 };
13205
13206 if (workInProgressHook === null) {
13207 // This is the first hook in the list
13208 firstWorkInProgressHook = workInProgressHook = hook;
13209 } else {
13210 // Append to the end of the list
13211 workInProgressHook = workInProgressHook.next = hook;
13212 }
13213 return workInProgressHook;
13214}
13215
13216function updateWorkInProgressHook() {
13217 // This function is used both for updates and for re-renders triggered by a
13218 // render phase update. It assumes there is either a current hook we can
13219 // clone, or a work-in-progress hook from a previous render pass that we can
13220 // use as a base. When we reach the end of the base list, we must switch to
13221 // the dispatcher used for mounts.
13222 if (nextWorkInProgressHook !== null) {
13223 // There's already a work-in-progress. Reuse it.
13224 workInProgressHook = nextWorkInProgressHook;
13225 nextWorkInProgressHook = workInProgressHook.next;
13226
13227 currentHook = nextCurrentHook;
13228 nextCurrentHook = currentHook !== null ? currentHook.next : null;
13229 } else {
13230 // Clone from the current hook.
13231 !(nextCurrentHook !== null) ? invariant(false, 'Rendered more hooks than during the previous render.') : void 0;
13232 currentHook = nextCurrentHook;
13233
13234 var newHook = {
13235 memoizedState: currentHook.memoizedState,
13236
13237 baseState: currentHook.baseState,
13238 queue: currentHook.queue,
13239 baseUpdate: currentHook.baseUpdate,
13240
13241 next: null
13242 };
13243
13244 if (workInProgressHook === null) {
13245 // This is the first hook in the list.
13246 workInProgressHook = firstWorkInProgressHook = newHook;
13247 } else {
13248 // Append to the end of the list.
13249 workInProgressHook = workInProgressHook.next = newHook;
13250 }
13251 nextCurrentHook = currentHook.next;
13252 }
13253 return workInProgressHook;
13254}
13255
13256function createFunctionComponentUpdateQueue() {
13257 return {
13258 lastEffect: null
13259 };
13260}
13261
13262function basicStateReducer(state, action) {
13263 return typeof action === 'function' ? action(state) : action;
13264}
13265
13266function mountReducer(reducer, initialArg, init) {
13267 var hook = mountWorkInProgressHook();
13268 var initialState = void 0;
13269 if (init !== undefined) {
13270 initialState = init(initialArg);
13271 } else {
13272 initialState = initialArg;
13273 }
13274 hook.memoizedState = hook.baseState = initialState;
13275 var queue = hook.queue = {
13276 last: null,
13277 dispatch: null,
13278 lastRenderedReducer: reducer,
13279 lastRenderedState: initialState
13280 };
13281 var dispatch = queue.dispatch = dispatchAction.bind(null,
13282 // Flow doesn't know this is non-null, but we do.
13283 currentlyRenderingFiber$1, queue);
13284 return [hook.memoizedState, dispatch];
13285}
13286
13287function updateReducer(reducer, initialArg, init) {
13288 var hook = updateWorkInProgressHook();
13289 var queue = hook.queue;
13290 !(queue !== null) ? invariant(false, 'Should have a queue. This is likely a bug in React. Please file an issue.') : void 0;
13291
13292 queue.lastRenderedReducer = reducer;
13293
13294 if (numberOfReRenders > 0) {
13295 // This is a re-render. Apply the new render phase updates to the previous
13296 var _dispatch = queue.dispatch;
13297 if (renderPhaseUpdates !== null) {
13298 // Render phase updates are stored in a map of queue -> linked list
13299 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
13300 if (firstRenderPhaseUpdate !== undefined) {
13301 renderPhaseUpdates.delete(queue);
13302 var newState = hook.memoizedState;
13303 var update = firstRenderPhaseUpdate;
13304 do {
13305 // Process this render phase update. We don't have to check the
13306 // priority because it will always be the same as the current
13307 // render's.
13308 var _action = update.action;
13309 newState = reducer(newState, _action);
13310 update = update.next;
13311 } while (update !== null);
13312
13313 // Mark that the fiber performed work, but only if the new state is
13314 // different from the current state.
13315 if (!is(newState, hook.memoizedState)) {
13316 markWorkInProgressReceivedUpdate();
13317 }
13318
13319 hook.memoizedState = newState;
13320 // Don't persist the state accumlated from the render phase updates to
13321 // the base state unless the queue is empty.
13322 // TODO: Not sure if this is the desired semantics, but it's what we
13323 // do for gDSFP. I can't remember why.
13324 if (hook.baseUpdate === queue.last) {
13325 hook.baseState = newState;
13326 }
13327
13328 queue.lastRenderedState = newState;
13329
13330 return [newState, _dispatch];
13331 }
13332 }
13333 return [hook.memoizedState, _dispatch];
13334 }
13335
13336 // The last update in the entire queue
13337 var last = queue.last;
13338 // The last update that is part of the base state.
13339 var baseUpdate = hook.baseUpdate;
13340 var baseState = hook.baseState;
13341
13342 // Find the first unprocessed update.
13343 var first = void 0;
13344 if (baseUpdate !== null) {
13345 if (last !== null) {
13346 // For the first update, the queue is a circular linked list where
13347 // `queue.last.next = queue.first`. Once the first update commits, and
13348 // the `baseUpdate` is no longer empty, we can unravel the list.
13349 last.next = null;
13350 }
13351 first = baseUpdate.next;
13352 } else {
13353 first = last !== null ? last.next : null;
13354 }
13355 if (first !== null) {
13356 var _newState = baseState;
13357 var newBaseState = null;
13358 var newBaseUpdate = null;
13359 var prevUpdate = baseUpdate;
13360 var _update = first;
13361 var didSkip = false;
13362 do {
13363 var updateExpirationTime = _update.expirationTime;
13364 if (updateExpirationTime < renderExpirationTime) {
13365 // Priority is insufficient. Skip this update. If this is the first
13366 // skipped update, the previous update/state is the new base
13367 // update/state.
13368 if (!didSkip) {
13369 didSkip = true;
13370 newBaseUpdate = prevUpdate;
13371 newBaseState = _newState;
13372 }
13373 // Update the remaining priority in the queue.
13374 if (updateExpirationTime > remainingExpirationTime) {
13375 remainingExpirationTime = updateExpirationTime;
13376 }
13377 } else {
13378 // Process this update.
13379 if (_update.eagerReducer === reducer) {
13380 // If this update was processed eagerly, and its reducer matches the
13381 // current reducer, we can use the eagerly computed state.
13382 _newState = _update.eagerState;
13383 } else {
13384 var _action2 = _update.action;
13385 _newState = reducer(_newState, _action2);
13386 }
13387 }
13388 prevUpdate = _update;
13389 _update = _update.next;
13390 } while (_update !== null && _update !== first);
13391
13392 if (!didSkip) {
13393 newBaseUpdate = prevUpdate;
13394 newBaseState = _newState;
13395 }
13396
13397 // Mark that the fiber performed work, but only if the new state is
13398 // different from the current state.
13399 if (!is(_newState, hook.memoizedState)) {
13400 markWorkInProgressReceivedUpdate();
13401 }
13402
13403 hook.memoizedState = _newState;
13404 hook.baseUpdate = newBaseUpdate;
13405 hook.baseState = newBaseState;
13406
13407 queue.lastRenderedState = _newState;
13408 }
13409
13410 var dispatch = queue.dispatch;
13411 return [hook.memoizedState, dispatch];
13412}
13413
13414function mountState(initialState) {
13415 var hook = mountWorkInProgressHook();
13416 if (typeof initialState === 'function') {
13417 initialState = initialState();
13418 }
13419 hook.memoizedState = hook.baseState = initialState;
13420 var queue = hook.queue = {
13421 last: null,
13422 dispatch: null,
13423 lastRenderedReducer: basicStateReducer,
13424 lastRenderedState: initialState
13425 };
13426 var dispatch = queue.dispatch = dispatchAction.bind(null,
13427 // Flow doesn't know this is non-null, but we do.
13428 currentlyRenderingFiber$1, queue);
13429 return [hook.memoizedState, dispatch];
13430}
13431
13432function updateState(initialState) {
13433 return updateReducer(basicStateReducer, initialState);
13434}
13435
13436function pushEffect(tag, create, destroy, deps) {
13437 var effect = {
13438 tag: tag,
13439 create: create,
13440 destroy: destroy,
13441 deps: deps,
13442 // Circular
13443 next: null
13444 };
13445 if (componentUpdateQueue === null) {
13446 componentUpdateQueue = createFunctionComponentUpdateQueue();
13447 componentUpdateQueue.lastEffect = effect.next = effect;
13448 } else {
13449 var _lastEffect = componentUpdateQueue.lastEffect;
13450 if (_lastEffect === null) {
13451 componentUpdateQueue.lastEffect = effect.next = effect;
13452 } else {
13453 var firstEffect = _lastEffect.next;
13454 _lastEffect.next = effect;
13455 effect.next = firstEffect;
13456 componentUpdateQueue.lastEffect = effect;
13457 }
13458 }
13459 return effect;
13460}
13461
13462function mountRef(initialValue) {
13463 var hook = mountWorkInProgressHook();
13464 var ref = { current: initialValue };
13465 {
13466 Object.seal(ref);
13467 }
13468 hook.memoizedState = ref;
13469 return ref;
13470}
13471
13472function updateRef(initialValue) {
13473 var hook = updateWorkInProgressHook();
13474 return hook.memoizedState;
13475}
13476
13477function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
13478 var hook = mountWorkInProgressHook();
13479 var nextDeps = deps === undefined ? null : deps;
13480 sideEffectTag |= fiberEffectTag;
13481 hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps);
13482}
13483
13484function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
13485 var hook = updateWorkInProgressHook();
13486 var nextDeps = deps === undefined ? null : deps;
13487 var destroy = undefined;
13488
13489 if (currentHook !== null) {
13490 var prevEffect = currentHook.memoizedState;
13491 destroy = prevEffect.destroy;
13492 if (nextDeps !== null) {
13493 var prevDeps = prevEffect.deps;
13494 if (areHookInputsEqual(nextDeps, prevDeps)) {
13495 pushEffect(NoEffect$1, create, destroy, nextDeps);
13496 return;
13497 }
13498 }
13499 }
13500
13501 sideEffectTag |= fiberEffectTag;
13502 hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps);
13503}
13504
13505function mountEffect(create, deps) {
13506 return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
13507}
13508
13509function updateEffect(create, deps) {
13510 return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
13511}
13512
13513function mountLayoutEffect(create, deps) {
13514 return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
13515}
13516
13517function updateLayoutEffect(create, deps) {
13518 return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
13519}
13520
13521function imperativeHandleEffect(create, ref) {
13522 if (typeof ref === 'function') {
13523 var refCallback = ref;
13524 var _inst = create();
13525 refCallback(_inst);
13526 return function () {
13527 refCallback(null);
13528 };
13529 } else if (ref !== null && ref !== undefined) {
13530 var refObject = ref;
13531 {
13532 !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;
13533 }
13534 var _inst2 = create();
13535 refObject.current = _inst2;
13536 return function () {
13537 refObject.current = null;
13538 };
13539 }
13540}
13541
13542function mountImperativeHandle(ref, create, deps) {
13543 {
13544 !(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;
13545 }
13546
13547 // TODO: If deps are provided, should we skip comparing the ref itself?
13548 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
13549
13550 return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
13551}
13552
13553function updateImperativeHandle(ref, create, deps) {
13554 {
13555 !(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;
13556 }
13557
13558 // TODO: If deps are provided, should we skip comparing the ref itself?
13559 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
13560
13561 return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
13562}
13563
13564function mountDebugValue(value, formatterFn) {
13565 // This hook is normally a no-op.
13566 // The react-debug-hooks package injects its own implementation
13567 // so that e.g. DevTools can display custom hook values.
13568}
13569
13570var updateDebugValue = mountDebugValue;
13571
13572function mountCallback(callback, deps) {
13573 var hook = mountWorkInProgressHook();
13574 var nextDeps = deps === undefined ? null : deps;
13575 hook.memoizedState = [callback, nextDeps];
13576 return callback;
13577}
13578
13579function updateCallback(callback, deps) {
13580 var hook = updateWorkInProgressHook();
13581 var nextDeps = deps === undefined ? null : deps;
13582 var prevState = hook.memoizedState;
13583 if (prevState !== null) {
13584 if (nextDeps !== null) {
13585 var prevDeps = prevState[1];
13586 if (areHookInputsEqual(nextDeps, prevDeps)) {
13587 return prevState[0];
13588 }
13589 }
13590 }
13591 hook.memoizedState = [callback, nextDeps];
13592 return callback;
13593}
13594
13595function mountMemo(nextCreate, deps) {
13596 var hook = mountWorkInProgressHook();
13597 var nextDeps = deps === undefined ? null : deps;
13598 var nextValue = nextCreate();
13599 hook.memoizedState = [nextValue, nextDeps];
13600 return nextValue;
13601}
13602
13603function updateMemo(nextCreate, deps) {
13604 var hook = updateWorkInProgressHook();
13605 var nextDeps = deps === undefined ? null : deps;
13606 var prevState = hook.memoizedState;
13607 if (prevState !== null) {
13608 // Assume these are defined. If they're not, areHookInputsEqual will warn.
13609 if (nextDeps !== null) {
13610 var prevDeps = prevState[1];
13611 if (areHookInputsEqual(nextDeps, prevDeps)) {
13612 return prevState[0];
13613 }
13614 }
13615 }
13616 var nextValue = nextCreate();
13617 hook.memoizedState = [nextValue, nextDeps];
13618 return nextValue;
13619}
13620
13621// in a test-like environment, we want to warn if dispatchAction()
13622// is called outside of a batchedUpdates/TestUtils.act(...) call.
13623var shouldWarnForUnbatchedSetState = false;
13624
13625{
13626 // jest isn't a 'global', it's just exposed to tests via a wrapped function
13627 // further, this isn't a test file, so flow doesn't recognize the symbol. So...
13628 // $FlowExpectedError - because requirements don't give a damn about your type sigs.
13629 if ('undefined' !== typeof jest) {
13630 shouldWarnForUnbatchedSetState = true;
13631 }
13632}
13633
13634function dispatchAction(fiber, queue, action) {
13635 !(numberOfReRenders < RE_RENDER_LIMIT) ? invariant(false, 'Too many re-renders. React limits the number of renders to prevent an infinite loop.') : void 0;
13636
13637 {
13638 !(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;
13639 }
13640
13641 var alternate = fiber.alternate;
13642 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
13643 // This is a render phase update. Stash it in a lazily-created map of
13644 // queue -> linked list of updates. After this render pass, we'll restart
13645 // and apply the stashed updates on top of the work-in-progress hook.
13646 didScheduleRenderPhaseUpdate = true;
13647 var update = {
13648 expirationTime: renderExpirationTime,
13649 action: action,
13650 eagerReducer: null,
13651 eagerState: null,
13652 next: null
13653 };
13654 if (renderPhaseUpdates === null) {
13655 renderPhaseUpdates = new Map();
13656 }
13657 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
13658 if (firstRenderPhaseUpdate === undefined) {
13659 renderPhaseUpdates.set(queue, update);
13660 } else {
13661 // Append the update to the end of the list.
13662 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
13663 while (lastRenderPhaseUpdate.next !== null) {
13664 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
13665 }
13666 lastRenderPhaseUpdate.next = update;
13667 }
13668 } else {
13669 flushPassiveEffects();
13670
13671 var currentTime = requestCurrentTime();
13672 var _expirationTime = computeExpirationForFiber(currentTime, fiber);
13673
13674 var _update2 = {
13675 expirationTime: _expirationTime,
13676 action: action,
13677 eagerReducer: null,
13678 eagerState: null,
13679 next: null
13680 };
13681
13682 // Append the update to the end of the list.
13683 var _last = queue.last;
13684 if (_last === null) {
13685 // This is the first update. Create a circular list.
13686 _update2.next = _update2;
13687 } else {
13688 var first = _last.next;
13689 if (first !== null) {
13690 // Still circular.
13691 _update2.next = first;
13692 }
13693 _last.next = _update2;
13694 }
13695 queue.last = _update2;
13696
13697 if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
13698 // The queue is currently empty, which means we can eagerly compute the
13699 // next state before entering the render phase. If the new state is the
13700 // same as the current state, we may be able to bail out entirely.
13701 var _lastRenderedReducer = queue.lastRenderedReducer;
13702 if (_lastRenderedReducer !== null) {
13703 var prevDispatcher = void 0;
13704 {
13705 prevDispatcher = ReactCurrentDispatcher$1.current;
13706 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13707 }
13708 try {
13709 var currentState = queue.lastRenderedState;
13710 var _eagerState = _lastRenderedReducer(currentState, action);
13711 // Stash the eagerly computed state, and the reducer used to compute
13712 // it, on the update object. If the reducer hasn't changed by the
13713 // time we enter the render phase, then the eager state can be used
13714 // without calling the reducer again.
13715 _update2.eagerReducer = _lastRenderedReducer;
13716 _update2.eagerState = _eagerState;
13717 if (is(_eagerState, currentState)) {
13718 // Fast path. We can bail out without scheduling React to re-render.
13719 // It's still possible that we'll need to rebase this update later,
13720 // if the component re-renders for a different reason and by that
13721 // time the reducer has changed.
13722 return;
13723 }
13724 } catch (error) {
13725 // Suppress the error. It will throw again in the render phase.
13726 } finally {
13727 {
13728 ReactCurrentDispatcher$1.current = prevDispatcher;
13729 }
13730 }
13731 }
13732 }
13733 {
13734 if (shouldWarnForUnbatchedSetState === true) {
13735 warnIfNotCurrentlyBatchingInDev(fiber);
13736 }
13737 }
13738 scheduleWork(fiber, _expirationTime);
13739 }
13740}
13741
13742var ContextOnlyDispatcher = {
13743 readContext: readContext,
13744
13745 useCallback: throwInvalidHookError,
13746 useContext: throwInvalidHookError,
13747 useEffect: throwInvalidHookError,
13748 useImperativeHandle: throwInvalidHookError,
13749 useLayoutEffect: throwInvalidHookError,
13750 useMemo: throwInvalidHookError,
13751 useReducer: throwInvalidHookError,
13752 useRef: throwInvalidHookError,
13753 useState: throwInvalidHookError,
13754 useDebugValue: throwInvalidHookError
13755};
13756
13757var HooksDispatcherOnMountInDEV = null;
13758var HooksDispatcherOnMountWithHookTypesInDEV = null;
13759var HooksDispatcherOnUpdateInDEV = null;
13760var InvalidNestedHooksDispatcherOnMountInDEV = null;
13761var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
13762
13763{
13764 var warnInvalidContextAccess = function () {
13765 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().');
13766 };
13767
13768 var warnInvalidHookAccess = function () {
13769 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');
13770 };
13771
13772 HooksDispatcherOnMountInDEV = {
13773 readContext: function (context, observedBits) {
13774 return readContext(context, observedBits);
13775 },
13776 useCallback: function (callback, deps) {
13777 currentHookNameInDev = 'useCallback';
13778 mountHookTypesDev();
13779 return mountCallback(callback, deps);
13780 },
13781 useContext: function (context, observedBits) {
13782 currentHookNameInDev = 'useContext';
13783 mountHookTypesDev();
13784 return readContext(context, observedBits);
13785 },
13786 useEffect: function (create, deps) {
13787 currentHookNameInDev = 'useEffect';
13788 mountHookTypesDev();
13789 return mountEffect(create, deps);
13790 },
13791 useImperativeHandle: function (ref, create, deps) {
13792 currentHookNameInDev = 'useImperativeHandle';
13793 mountHookTypesDev();
13794 return mountImperativeHandle(ref, create, deps);
13795 },
13796 useLayoutEffect: function (create, deps) {
13797 currentHookNameInDev = 'useLayoutEffect';
13798 mountHookTypesDev();
13799 return mountLayoutEffect(create, deps);
13800 },
13801 useMemo: function (create, deps) {
13802 currentHookNameInDev = 'useMemo';
13803 mountHookTypesDev();
13804 var prevDispatcher = ReactCurrentDispatcher$1.current;
13805 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13806 try {
13807 return mountMemo(create, deps);
13808 } finally {
13809 ReactCurrentDispatcher$1.current = prevDispatcher;
13810 }
13811 },
13812 useReducer: function (reducer, initialArg, init) {
13813 currentHookNameInDev = 'useReducer';
13814 mountHookTypesDev();
13815 var prevDispatcher = ReactCurrentDispatcher$1.current;
13816 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13817 try {
13818 return mountReducer(reducer, initialArg, init);
13819 } finally {
13820 ReactCurrentDispatcher$1.current = prevDispatcher;
13821 }
13822 },
13823 useRef: function (initialValue) {
13824 currentHookNameInDev = 'useRef';
13825 mountHookTypesDev();
13826 return mountRef(initialValue);
13827 },
13828 useState: function (initialState) {
13829 currentHookNameInDev = 'useState';
13830 mountHookTypesDev();
13831 var prevDispatcher = ReactCurrentDispatcher$1.current;
13832 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13833 try {
13834 return mountState(initialState);
13835 } finally {
13836 ReactCurrentDispatcher$1.current = prevDispatcher;
13837 }
13838 },
13839 useDebugValue: function (value, formatterFn) {
13840 currentHookNameInDev = 'useDebugValue';
13841 mountHookTypesDev();
13842 return mountDebugValue(value, formatterFn);
13843 }
13844 };
13845
13846 HooksDispatcherOnMountWithHookTypesInDEV = {
13847 readContext: function (context, observedBits) {
13848 return readContext(context, observedBits);
13849 },
13850 useCallback: function (callback, deps) {
13851 currentHookNameInDev = 'useCallback';
13852 updateHookTypesDev();
13853 return mountCallback(callback, deps);
13854 },
13855 useContext: function (context, observedBits) {
13856 currentHookNameInDev = 'useContext';
13857 updateHookTypesDev();
13858 return readContext(context, observedBits);
13859 },
13860 useEffect: function (create, deps) {
13861 currentHookNameInDev = 'useEffect';
13862 updateHookTypesDev();
13863 return mountEffect(create, deps);
13864 },
13865 useImperativeHandle: function (ref, create, deps) {
13866 currentHookNameInDev = 'useImperativeHandle';
13867 updateHookTypesDev();
13868 return mountImperativeHandle(ref, create, deps);
13869 },
13870 useLayoutEffect: function (create, deps) {
13871 currentHookNameInDev = 'useLayoutEffect';
13872 updateHookTypesDev();
13873 return mountLayoutEffect(create, deps);
13874 },
13875 useMemo: function (create, deps) {
13876 currentHookNameInDev = 'useMemo';
13877 updateHookTypesDev();
13878 var prevDispatcher = ReactCurrentDispatcher$1.current;
13879 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13880 try {
13881 return mountMemo(create, deps);
13882 } finally {
13883 ReactCurrentDispatcher$1.current = prevDispatcher;
13884 }
13885 },
13886 useReducer: function (reducer, initialArg, init) {
13887 currentHookNameInDev = 'useReducer';
13888 updateHookTypesDev();
13889 var prevDispatcher = ReactCurrentDispatcher$1.current;
13890 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13891 try {
13892 return mountReducer(reducer, initialArg, init);
13893 } finally {
13894 ReactCurrentDispatcher$1.current = prevDispatcher;
13895 }
13896 },
13897 useRef: function (initialValue) {
13898 currentHookNameInDev = 'useRef';
13899 updateHookTypesDev();
13900 return mountRef(initialValue);
13901 },
13902 useState: function (initialState) {
13903 currentHookNameInDev = 'useState';
13904 updateHookTypesDev();
13905 var prevDispatcher = ReactCurrentDispatcher$1.current;
13906 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13907 try {
13908 return mountState(initialState);
13909 } finally {
13910 ReactCurrentDispatcher$1.current = prevDispatcher;
13911 }
13912 },
13913 useDebugValue: function (value, formatterFn) {
13914 currentHookNameInDev = 'useDebugValue';
13915 updateHookTypesDev();
13916 return mountDebugValue(value, formatterFn);
13917 }
13918 };
13919
13920 HooksDispatcherOnUpdateInDEV = {
13921 readContext: function (context, observedBits) {
13922 return readContext(context, observedBits);
13923 },
13924 useCallback: function (callback, deps) {
13925 currentHookNameInDev = 'useCallback';
13926 updateHookTypesDev();
13927 return updateCallback(callback, deps);
13928 },
13929 useContext: function (context, observedBits) {
13930 currentHookNameInDev = 'useContext';
13931 updateHookTypesDev();
13932 return readContext(context, observedBits);
13933 },
13934 useEffect: function (create, deps) {
13935 currentHookNameInDev = 'useEffect';
13936 updateHookTypesDev();
13937 return updateEffect(create, deps);
13938 },
13939 useImperativeHandle: function (ref, create, deps) {
13940 currentHookNameInDev = 'useImperativeHandle';
13941 updateHookTypesDev();
13942 return updateImperativeHandle(ref, create, deps);
13943 },
13944 useLayoutEffect: function (create, deps) {
13945 currentHookNameInDev = 'useLayoutEffect';
13946 updateHookTypesDev();
13947 return updateLayoutEffect(create, deps);
13948 },
13949 useMemo: function (create, deps) {
13950 currentHookNameInDev = 'useMemo';
13951 updateHookTypesDev();
13952 var prevDispatcher = ReactCurrentDispatcher$1.current;
13953 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13954 try {
13955 return updateMemo(create, deps);
13956 } finally {
13957 ReactCurrentDispatcher$1.current = prevDispatcher;
13958 }
13959 },
13960 useReducer: function (reducer, initialArg, init) {
13961 currentHookNameInDev = 'useReducer';
13962 updateHookTypesDev();
13963 var prevDispatcher = ReactCurrentDispatcher$1.current;
13964 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13965 try {
13966 return updateReducer(reducer, initialArg, init);
13967 } finally {
13968 ReactCurrentDispatcher$1.current = prevDispatcher;
13969 }
13970 },
13971 useRef: function (initialValue) {
13972 currentHookNameInDev = 'useRef';
13973 updateHookTypesDev();
13974 return updateRef(initialValue);
13975 },
13976 useState: function (initialState) {
13977 currentHookNameInDev = 'useState';
13978 updateHookTypesDev();
13979 var prevDispatcher = ReactCurrentDispatcher$1.current;
13980 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13981 try {
13982 return updateState(initialState);
13983 } finally {
13984 ReactCurrentDispatcher$1.current = prevDispatcher;
13985 }
13986 },
13987 useDebugValue: function (value, formatterFn) {
13988 currentHookNameInDev = 'useDebugValue';
13989 updateHookTypesDev();
13990 return updateDebugValue(value, formatterFn);
13991 }
13992 };
13993
13994 InvalidNestedHooksDispatcherOnMountInDEV = {
13995 readContext: function (context, observedBits) {
13996 warnInvalidContextAccess();
13997 return readContext(context, observedBits);
13998 },
13999 useCallback: function (callback, deps) {
14000 currentHookNameInDev = 'useCallback';
14001 warnInvalidHookAccess();
14002 mountHookTypesDev();
14003 return mountCallback(callback, deps);
14004 },
14005 useContext: function (context, observedBits) {
14006 currentHookNameInDev = 'useContext';
14007 warnInvalidHookAccess();
14008 mountHookTypesDev();
14009 return readContext(context, observedBits);
14010 },
14011 useEffect: function (create, deps) {
14012 currentHookNameInDev = 'useEffect';
14013 warnInvalidHookAccess();
14014 mountHookTypesDev();
14015 return mountEffect(create, deps);
14016 },
14017 useImperativeHandle: function (ref, create, deps) {
14018 currentHookNameInDev = 'useImperativeHandle';
14019 warnInvalidHookAccess();
14020 mountHookTypesDev();
14021 return mountImperativeHandle(ref, create, deps);
14022 },
14023 useLayoutEffect: function (create, deps) {
14024 currentHookNameInDev = 'useLayoutEffect';
14025 warnInvalidHookAccess();
14026 mountHookTypesDev();
14027 return mountLayoutEffect(create, deps);
14028 },
14029 useMemo: function (create, deps) {
14030 currentHookNameInDev = 'useMemo';
14031 warnInvalidHookAccess();
14032 mountHookTypesDev();
14033 var prevDispatcher = ReactCurrentDispatcher$1.current;
14034 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14035 try {
14036 return mountMemo(create, deps);
14037 } finally {
14038 ReactCurrentDispatcher$1.current = prevDispatcher;
14039 }
14040 },
14041 useReducer: function (reducer, initialArg, init) {
14042 currentHookNameInDev = 'useReducer';
14043 warnInvalidHookAccess();
14044 mountHookTypesDev();
14045 var prevDispatcher = ReactCurrentDispatcher$1.current;
14046 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14047 try {
14048 return mountReducer(reducer, initialArg, init);
14049 } finally {
14050 ReactCurrentDispatcher$1.current = prevDispatcher;
14051 }
14052 },
14053 useRef: function (initialValue) {
14054 currentHookNameInDev = 'useRef';
14055 warnInvalidHookAccess();
14056 mountHookTypesDev();
14057 return mountRef(initialValue);
14058 },
14059 useState: function (initialState) {
14060 currentHookNameInDev = 'useState';
14061 warnInvalidHookAccess();
14062 mountHookTypesDev();
14063 var prevDispatcher = ReactCurrentDispatcher$1.current;
14064 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14065 try {
14066 return mountState(initialState);
14067 } finally {
14068 ReactCurrentDispatcher$1.current = prevDispatcher;
14069 }
14070 },
14071 useDebugValue: function (value, formatterFn) {
14072 currentHookNameInDev = 'useDebugValue';
14073 warnInvalidHookAccess();
14074 mountHookTypesDev();
14075 return mountDebugValue(value, formatterFn);
14076 }
14077 };
14078
14079 InvalidNestedHooksDispatcherOnUpdateInDEV = {
14080 readContext: function (context, observedBits) {
14081 warnInvalidContextAccess();
14082 return readContext(context, observedBits);
14083 },
14084 useCallback: function (callback, deps) {
14085 currentHookNameInDev = 'useCallback';
14086 warnInvalidHookAccess();
14087 updateHookTypesDev();
14088 return updateCallback(callback, deps);
14089 },
14090 useContext: function (context, observedBits) {
14091 currentHookNameInDev = 'useContext';
14092 warnInvalidHookAccess();
14093 updateHookTypesDev();
14094 return readContext(context, observedBits);
14095 },
14096 useEffect: function (create, deps) {
14097 currentHookNameInDev = 'useEffect';
14098 warnInvalidHookAccess();
14099 updateHookTypesDev();
14100 return updateEffect(create, deps);
14101 },
14102 useImperativeHandle: function (ref, create, deps) {
14103 currentHookNameInDev = 'useImperativeHandle';
14104 warnInvalidHookAccess();
14105 updateHookTypesDev();
14106 return updateImperativeHandle(ref, create, deps);
14107 },
14108 useLayoutEffect: function (create, deps) {
14109 currentHookNameInDev = 'useLayoutEffect';
14110 warnInvalidHookAccess();
14111 updateHookTypesDev();
14112 return updateLayoutEffect(create, deps);
14113 },
14114 useMemo: function (create, deps) {
14115 currentHookNameInDev = 'useMemo';
14116 warnInvalidHookAccess();
14117 updateHookTypesDev();
14118 var prevDispatcher = ReactCurrentDispatcher$1.current;
14119 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
14120 try {
14121 return updateMemo(create, deps);
14122 } finally {
14123 ReactCurrentDispatcher$1.current = prevDispatcher;
14124 }
14125 },
14126 useReducer: function (reducer, initialArg, init) {
14127 currentHookNameInDev = 'useReducer';
14128 warnInvalidHookAccess();
14129 updateHookTypesDev();
14130 var prevDispatcher = ReactCurrentDispatcher$1.current;
14131 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
14132 try {
14133 return updateReducer(reducer, initialArg, init);
14134 } finally {
14135 ReactCurrentDispatcher$1.current = prevDispatcher;
14136 }
14137 },
14138 useRef: function (initialValue) {
14139 currentHookNameInDev = 'useRef';
14140 warnInvalidHookAccess();
14141 updateHookTypesDev();
14142 return updateRef(initialValue);
14143 },
14144 useState: function (initialState) {
14145 currentHookNameInDev = 'useState';
14146 warnInvalidHookAccess();
14147 updateHookTypesDev();
14148 var prevDispatcher = ReactCurrentDispatcher$1.current;
14149 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
14150 try {
14151 return updateState(initialState);
14152 } finally {
14153 ReactCurrentDispatcher$1.current = prevDispatcher;
14154 }
14155 },
14156 useDebugValue: function (value, formatterFn) {
14157 currentHookNameInDev = 'useDebugValue';
14158 warnInvalidHookAccess();
14159 updateHookTypesDev();
14160 return updateDebugValue(value, formatterFn);
14161 }
14162 };
14163}
14164
14165var commitTime = 0;
14166var profilerStartTime = -1;
14167
14168function getCommitTime() {
14169 return commitTime;
14170}
14171
14172function recordCommitTime() {
14173 if (!enableProfilerTimer) {
14174 return;
14175 }
14176 commitTime = unstable_now();
14177}
14178
14179function startProfilerTimer(fiber) {
14180 if (!enableProfilerTimer) {
14181 return;
14182 }
14183
14184 profilerStartTime = unstable_now();
14185
14186 if (fiber.actualStartTime < 0) {
14187 fiber.actualStartTime = unstable_now();
14188 }
14189}
14190
14191function stopProfilerTimerIfRunning(fiber) {
14192 if (!enableProfilerTimer) {
14193 return;
14194 }
14195 profilerStartTime = -1;
14196}
14197
14198function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
14199 if (!enableProfilerTimer) {
14200 return;
14201 }
14202
14203 if (profilerStartTime >= 0) {
14204 var elapsedTime = unstable_now() - profilerStartTime;
14205 fiber.actualDuration += elapsedTime;
14206 if (overrideBaseTime) {
14207 fiber.selfBaseDuration = elapsedTime;
14208 }
14209 profilerStartTime = -1;
14210 }
14211}
14212
14213// The deepest Fiber on the stack involved in a hydration context.
14214// This may have been an insertion or a hydration.
14215var hydrationParentFiber = null;
14216var nextHydratableInstance = null;
14217var isHydrating = false;
14218
14219function enterHydrationState(fiber) {
14220 if (!supportsHydration) {
14221 return false;
14222 }
14223
14224 var parentInstance = fiber.stateNode.containerInfo;
14225 nextHydratableInstance = getFirstHydratableChild(parentInstance);
14226 hydrationParentFiber = fiber;
14227 isHydrating = true;
14228 return true;
14229}
14230
14231function reenterHydrationStateFromDehydratedSuspenseInstance(fiber) {
14232 if (!supportsHydration) {
14233 return false;
14234 }
14235
14236 var suspenseInstance = fiber.stateNode;
14237 nextHydratableInstance = getNextHydratableSibling(suspenseInstance);
14238 popToNextHostParent(fiber);
14239 isHydrating = true;
14240 return true;
14241}
14242
14243function deleteHydratableInstance(returnFiber, instance) {
14244 {
14245 switch (returnFiber.tag) {
14246 case HostRoot:
14247 didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
14248 break;
14249 case HostComponent:
14250 didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
14251 break;
14252 }
14253 }
14254
14255 var childToDelete = createFiberFromHostInstanceForDeletion();
14256 childToDelete.stateNode = instance;
14257 childToDelete.return = returnFiber;
14258 childToDelete.effectTag = Deletion;
14259
14260 // This might seem like it belongs on progressedFirstDeletion. However,
14261 // these children are not part of the reconciliation list of children.
14262 // Even if we abort and rereconcile the children, that will try to hydrate
14263 // again and the nodes are still in the host tree so these will be
14264 // recreated.
14265 if (returnFiber.lastEffect !== null) {
14266 returnFiber.lastEffect.nextEffect = childToDelete;
14267 returnFiber.lastEffect = childToDelete;
14268 } else {
14269 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
14270 }
14271}
14272
14273function insertNonHydratedInstance(returnFiber, fiber) {
14274 fiber.effectTag |= Placement;
14275 {
14276 switch (returnFiber.tag) {
14277 case HostRoot:
14278 {
14279 var parentContainer = returnFiber.stateNode.containerInfo;
14280 switch (fiber.tag) {
14281 case HostComponent:
14282 var type = fiber.type;
14283 var props = fiber.pendingProps;
14284 didNotFindHydratableContainerInstance(parentContainer, type, props);
14285 break;
14286 case HostText:
14287 var text = fiber.pendingProps;
14288 didNotFindHydratableContainerTextInstance(parentContainer, text);
14289 break;
14290 case SuspenseComponent:
14291
14292 break;
14293 }
14294 break;
14295 }
14296 case HostComponent:
14297 {
14298 var parentType = returnFiber.type;
14299 var parentProps = returnFiber.memoizedProps;
14300 var parentInstance = returnFiber.stateNode;
14301 switch (fiber.tag) {
14302 case HostComponent:
14303 var _type = fiber.type;
14304 var _props = fiber.pendingProps;
14305 didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
14306 break;
14307 case HostText:
14308 var _text = fiber.pendingProps;
14309 didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
14310 break;
14311 case SuspenseComponent:
14312 didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance);
14313 break;
14314 }
14315 break;
14316 }
14317 default:
14318 return;
14319 }
14320 }
14321}
14322
14323function tryHydrate(fiber, nextInstance) {
14324 switch (fiber.tag) {
14325 case HostComponent:
14326 {
14327 var type = fiber.type;
14328 var props = fiber.pendingProps;
14329 var instance = canHydrateInstance(nextInstance, type, props);
14330 if (instance !== null) {
14331 fiber.stateNode = instance;
14332 return true;
14333 }
14334 return false;
14335 }
14336 case HostText:
14337 {
14338 var text = fiber.pendingProps;
14339 var textInstance = canHydrateTextInstance(nextInstance, text);
14340 if (textInstance !== null) {
14341 fiber.stateNode = textInstance;
14342 return true;
14343 }
14344 return false;
14345 }
14346 case SuspenseComponent:
14347 {
14348 if (enableSuspenseServerRenderer) {
14349 var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
14350 if (suspenseInstance !== null) {
14351 // Downgrade the tag to a dehydrated component until we've hydrated it.
14352 fiber.tag = DehydratedSuspenseComponent;
14353 fiber.stateNode = suspenseInstance;
14354 return true;
14355 }
14356 }
14357 return false;
14358 }
14359 default:
14360 return false;
14361 }
14362}
14363
14364function tryToClaimNextHydratableInstance(fiber) {
14365 if (!isHydrating) {
14366 return;
14367 }
14368 var nextInstance = nextHydratableInstance;
14369 if (!nextInstance) {
14370 // Nothing to hydrate. Make it an insertion.
14371 insertNonHydratedInstance(hydrationParentFiber, fiber);
14372 isHydrating = false;
14373 hydrationParentFiber = fiber;
14374 return;
14375 }
14376 var firstAttemptedInstance = nextInstance;
14377 if (!tryHydrate(fiber, nextInstance)) {
14378 // If we can't hydrate this instance let's try the next one.
14379 // We use this as a heuristic. It's based on intuition and not data so it
14380 // might be flawed or unnecessary.
14381 nextInstance = getNextHydratableSibling(firstAttemptedInstance);
14382 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
14383 // Nothing to hydrate. Make it an insertion.
14384 insertNonHydratedInstance(hydrationParentFiber, fiber);
14385 isHydrating = false;
14386 hydrationParentFiber = fiber;
14387 return;
14388 }
14389 // We matched the next one, we'll now assume that the first one was
14390 // superfluous and we'll delete it. Since we can't eagerly delete it
14391 // we'll have to schedule a deletion. To do that, this node needs a dummy
14392 // fiber associated with it.
14393 deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
14394 }
14395 hydrationParentFiber = fiber;
14396 nextHydratableInstance = getFirstHydratableChild(nextInstance);
14397}
14398
14399function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
14400 if (!supportsHydration) {
14401 invariant(false, 'Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
14402 }
14403
14404 var instance = fiber.stateNode;
14405 var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber);
14406 // TODO: Type this specific to this type of component.
14407 fiber.updateQueue = updatePayload;
14408 // If the update payload indicates that there is a change or if there
14409 // is a new ref we mark this as an update.
14410 if (updatePayload !== null) {
14411 return true;
14412 }
14413 return false;
14414}
14415
14416function prepareToHydrateHostTextInstance(fiber) {
14417 if (!supportsHydration) {
14418 invariant(false, 'Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
14419 }
14420
14421 var textInstance = fiber.stateNode;
14422 var textContent = fiber.memoizedProps;
14423 var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
14424 {
14425 if (shouldUpdate) {
14426 // We assume that prepareToHydrateHostTextInstance is called in a context where the
14427 // hydration parent is the parent host component of this host text.
14428 var returnFiber = hydrationParentFiber;
14429 if (returnFiber !== null) {
14430 switch (returnFiber.tag) {
14431 case HostRoot:
14432 {
14433 var parentContainer = returnFiber.stateNode.containerInfo;
14434 didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
14435 break;
14436 }
14437 case HostComponent:
14438 {
14439 var parentType = returnFiber.type;
14440 var parentProps = returnFiber.memoizedProps;
14441 var parentInstance = returnFiber.stateNode;
14442 didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
14443 break;
14444 }
14445 }
14446 }
14447 }
14448 }
14449 return shouldUpdate;
14450}
14451
14452function skipPastDehydratedSuspenseInstance(fiber) {
14453 if (!supportsHydration) {
14454 invariant(false, 'Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
14455 }
14456 var suspenseInstance = fiber.stateNode;
14457 !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;
14458 nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
14459}
14460
14461function popToNextHostParent(fiber) {
14462 var parent = fiber.return;
14463 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== DehydratedSuspenseComponent) {
14464 parent = parent.return;
14465 }
14466 hydrationParentFiber = parent;
14467}
14468
14469function popHydrationState(fiber) {
14470 if (!supportsHydration) {
14471 return false;
14472 }
14473 if (fiber !== hydrationParentFiber) {
14474 // We're deeper than the current hydration context, inside an inserted
14475 // tree.
14476 return false;
14477 }
14478 if (!isHydrating) {
14479 // If we're not currently hydrating but we're in a hydration context, then
14480 // we were an insertion and now need to pop up reenter hydration of our
14481 // siblings.
14482 popToNextHostParent(fiber);
14483 isHydrating = true;
14484 return false;
14485 }
14486
14487 var type = fiber.type;
14488
14489 // If we have any remaining hydratable nodes, we need to delete them now.
14490 // We only do this deeper than head and body since they tend to have random
14491 // other nodes in them. We also ignore components with pure text content in
14492 // side of them.
14493 // TODO: Better heuristic.
14494 if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
14495 var nextInstance = nextHydratableInstance;
14496 while (nextInstance) {
14497 deleteHydratableInstance(fiber, nextInstance);
14498 nextInstance = getNextHydratableSibling(nextInstance);
14499 }
14500 }
14501
14502 popToNextHostParent(fiber);
14503 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
14504 return true;
14505}
14506
14507function resetHydrationState() {
14508 if (!supportsHydration) {
14509 return;
14510 }
14511
14512 hydrationParentFiber = null;
14513 nextHydratableInstance = null;
14514 isHydrating = false;
14515}
14516
14517var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
14518
14519var didReceiveUpdate = false;
14520
14521var didWarnAboutBadClass = void 0;
14522var didWarnAboutContextTypeOnFunctionComponent = void 0;
14523var didWarnAboutGetDerivedStateOnFunctionComponent = void 0;
14524var didWarnAboutFunctionRefs = void 0;
14525var didWarnAboutReassigningProps = void 0;
14526
14527{
14528 didWarnAboutBadClass = {};
14529 didWarnAboutContextTypeOnFunctionComponent = {};
14530 didWarnAboutGetDerivedStateOnFunctionComponent = {};
14531 didWarnAboutFunctionRefs = {};
14532 didWarnAboutReassigningProps = false;
14533}
14534
14535function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) {
14536 if (current$$1 === null) {
14537 // If this is a fresh new component that hasn't been rendered yet, we
14538 // won't update its child set by applying minimal side-effects. Instead,
14539 // we will add them all to the child before it gets rendered. That means
14540 // we can optimize this reconciliation pass by not tracking side-effects.
14541 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
14542 } else {
14543 // If the current child is the same as the work in progress, it means that
14544 // we haven't yet started any work on these children. Therefore, we use
14545 // the clone algorithm to create a copy of all the current children.
14546
14547 // If we had any progressed work already, that is invalid at this point so
14548 // let's throw it out.
14549 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime);
14550 }
14551}
14552
14553function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) {
14554 // This function is fork of reconcileChildren. It's used in cases where we
14555 // want to reconcile without matching against the existing set. This has the
14556 // effect of all current children being unmounted; even if the type and key
14557 // are the same, the old child is unmounted and a new child is created.
14558 //
14559 // To do this, we're going to go through the reconcile algorithm twice. In
14560 // the first pass, we schedule a deletion for all the current children by
14561 // passing null.
14562 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime);
14563 // In the second pass, we mount the new children. The trick here is that we
14564 // pass null in place of where we usually pass the current child set. This has
14565 // the effect of remounting all children regardless of whether their their
14566 // identity matches.
14567 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
14568}
14569
14570function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
14571 // TODO: current can be non-null here even if the component
14572 // hasn't yet mounted. This happens after the first render suspends.
14573 // We'll need to figure out if this is fine or can cause issues.
14574
14575 {
14576 if (workInProgress.type !== workInProgress.elementType) {
14577 // Lazy component props can't be validated in createElement
14578 // because they're only guaranteed to be resolved here.
14579 var innerPropTypes = Component.propTypes;
14580 if (innerPropTypes) {
14581 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
14582 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14583 }
14584 }
14585 }
14586
14587 var render = Component.render;
14588 var ref = workInProgress.ref;
14589
14590 // The rest is a fork of updateFunctionComponent
14591 var nextChildren = void 0;
14592 prepareToReadContext(workInProgress, renderExpirationTime);
14593 {
14594 ReactCurrentOwner$3.current = workInProgress;
14595 setCurrentPhase('render');
14596 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
14597 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14598 // Only double-render components with Hooks
14599 if (workInProgress.memoizedState !== null) {
14600 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
14601 }
14602 }
14603 setCurrentPhase(null);
14604 }
14605
14606 if (current$$1 !== null && !didReceiveUpdate) {
14607 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
14608 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14609 }
14610
14611 // React DevTools reads this flag.
14612 workInProgress.effectTag |= PerformedWork;
14613 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14614 return workInProgress.child;
14615}
14616
14617function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
14618 if (current$$1 === null) {
14619 var type = Component.type;
14620 if (isSimpleFunctionComponent(type) && Component.compare === null &&
14621 // SimpleMemoComponent codepath doesn't resolve outer props either.
14622 Component.defaultProps === undefined) {
14623 // If this is a plain function component without default props,
14624 // and with only the default shallow comparison, we upgrade it
14625 // to a SimpleMemoComponent to allow fast path updates.
14626 workInProgress.tag = SimpleMemoComponent;
14627 workInProgress.type = type;
14628 {
14629 validateFunctionComponentInDev(workInProgress, type);
14630 }
14631 return updateSimpleMemoComponent(current$$1, workInProgress, type, nextProps, updateExpirationTime, renderExpirationTime);
14632 }
14633 {
14634 var innerPropTypes = type.propTypes;
14635 if (innerPropTypes) {
14636 // Inner memo component props aren't currently validated in createElement.
14637 // We could move it there, but we'd still need this for lazy code path.
14638 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
14639 'prop', getComponentName(type), getCurrentFiberStackInDev);
14640 }
14641 }
14642 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
14643 child.ref = workInProgress.ref;
14644 child.return = workInProgress;
14645 workInProgress.child = child;
14646 return child;
14647 }
14648 {
14649 var _type = Component.type;
14650 var _innerPropTypes = _type.propTypes;
14651 if (_innerPropTypes) {
14652 // Inner memo component props aren't currently validated in createElement.
14653 // We could move it there, but we'd still need this for lazy code path.
14654 checkPropTypes_1(_innerPropTypes, nextProps, // Resolved props
14655 'prop', getComponentName(_type), getCurrentFiberStackInDev);
14656 }
14657 }
14658 var currentChild = current$$1.child; // This is always exactly one child
14659 if (updateExpirationTime < renderExpirationTime) {
14660 // This will be the props with resolved defaultProps,
14661 // unlike current.memoizedProps which will be the unresolved ones.
14662 var prevProps = currentChild.memoizedProps;
14663 // Default to shallow comparison
14664 var compare = Component.compare;
14665 compare = compare !== null ? compare : shallowEqual;
14666 if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
14667 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14668 }
14669 }
14670 // React DevTools reads this flag.
14671 workInProgress.effectTag |= PerformedWork;
14672 var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
14673 newChild.ref = workInProgress.ref;
14674 newChild.return = workInProgress;
14675 workInProgress.child = newChild;
14676 return newChild;
14677}
14678
14679function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
14680 // TODO: current can be non-null here even if the component
14681 // hasn't yet mounted. This happens when the inner render suspends.
14682 // We'll need to figure out if this is fine or can cause issues.
14683
14684 {
14685 if (workInProgress.type !== workInProgress.elementType) {
14686 // Lazy component props can't be validated in createElement
14687 // because they're only guaranteed to be resolved here.
14688 var outerMemoType = workInProgress.elementType;
14689 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
14690 // We warn when you define propTypes on lazy()
14691 // so let's just skip over it to find memo() outer wrapper.
14692 // Inner props for memo are validated later.
14693 outerMemoType = refineResolvedLazyComponent(outerMemoType);
14694 }
14695 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
14696 if (outerPropTypes) {
14697 checkPropTypes_1(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
14698 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
14699 }
14700 // Inner propTypes will be validated in the function component path.
14701 }
14702 }
14703 if (current$$1 !== null) {
14704 var prevProps = current$$1.memoizedProps;
14705 if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
14706 didReceiveUpdate = false;
14707 if (updateExpirationTime < renderExpirationTime) {
14708 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14709 }
14710 }
14711 }
14712 return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
14713}
14714
14715function updateFragment(current$$1, workInProgress, renderExpirationTime) {
14716 var nextChildren = workInProgress.pendingProps;
14717 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14718 return workInProgress.child;
14719}
14720
14721function updateMode(current$$1, workInProgress, renderExpirationTime) {
14722 var nextChildren = workInProgress.pendingProps.children;
14723 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14724 return workInProgress.child;
14725}
14726
14727function updateProfiler(current$$1, workInProgress, renderExpirationTime) {
14728 if (enableProfilerTimer) {
14729 workInProgress.effectTag |= Update;
14730 }
14731 var nextProps = workInProgress.pendingProps;
14732 var nextChildren = nextProps.children;
14733 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14734 return workInProgress.child;
14735}
14736
14737function markRef(current$$1, workInProgress) {
14738 var ref = workInProgress.ref;
14739 if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) {
14740 // Schedule a Ref effect
14741 workInProgress.effectTag |= Ref;
14742 }
14743}
14744
14745function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
14746 {
14747 if (workInProgress.type !== workInProgress.elementType) {
14748 // Lazy component props can't be validated in createElement
14749 // because they're only guaranteed to be resolved here.
14750 var innerPropTypes = Component.propTypes;
14751 if (innerPropTypes) {
14752 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
14753 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14754 }
14755 }
14756 }
14757
14758 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
14759 var context = getMaskedContext(workInProgress, unmaskedContext);
14760
14761 var nextChildren = void 0;
14762 prepareToReadContext(workInProgress, renderExpirationTime);
14763 {
14764 ReactCurrentOwner$3.current = workInProgress;
14765 setCurrentPhase('render');
14766 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
14767 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14768 // Only double-render components with Hooks
14769 if (workInProgress.memoizedState !== null) {
14770 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
14771 }
14772 }
14773 setCurrentPhase(null);
14774 }
14775
14776 if (current$$1 !== null && !didReceiveUpdate) {
14777 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
14778 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14779 }
14780
14781 // React DevTools reads this flag.
14782 workInProgress.effectTag |= PerformedWork;
14783 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14784 return workInProgress.child;
14785}
14786
14787function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
14788 {
14789 if (workInProgress.type !== workInProgress.elementType) {
14790 // Lazy component props can't be validated in createElement
14791 // because they're only guaranteed to be resolved here.
14792 var innerPropTypes = Component.propTypes;
14793 if (innerPropTypes) {
14794 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
14795 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14796 }
14797 }
14798 }
14799
14800 // Push context providers early to prevent context stack mismatches.
14801 // During mounting we don't know the child context yet as the instance doesn't exist.
14802 // We will invalidate the child context in finishClassComponent() right after rendering.
14803 var hasContext = void 0;
14804 if (isContextProvider(Component)) {
14805 hasContext = true;
14806 pushContextProvider(workInProgress);
14807 } else {
14808 hasContext = false;
14809 }
14810 prepareToReadContext(workInProgress, renderExpirationTime);
14811
14812 var instance = workInProgress.stateNode;
14813 var shouldUpdate = void 0;
14814 if (instance === null) {
14815 if (current$$1 !== null) {
14816 // An class component without an instance only mounts if it suspended
14817 // inside a non- concurrent tree, in an inconsistent state. We want to
14818 // tree it like a new mount, even though an empty version of it already
14819 // committed. Disconnect the alternate pointers.
14820 current$$1.alternate = null;
14821 workInProgress.alternate = null;
14822 // Since this is conceptually a new fiber, schedule a Placement effect
14823 workInProgress.effectTag |= Placement;
14824 }
14825 // In the initial pass we might need to construct the instance.
14826 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14827 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14828 shouldUpdate = true;
14829 } else if (current$$1 === null) {
14830 // In a resume, we'll already have an instance we can reuse.
14831 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14832 } else {
14833 shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
14834 }
14835 var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
14836 {
14837 var inst = workInProgress.stateNode;
14838 if (inst.props !== nextProps) {
14839 !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;
14840 didWarnAboutReassigningProps = true;
14841 }
14842 }
14843 return nextUnitOfWork;
14844}
14845
14846function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
14847 // Refs should update even if shouldComponentUpdate returns false
14848 markRef(current$$1, workInProgress);
14849
14850 var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
14851
14852 if (!shouldUpdate && !didCaptureError) {
14853 // Context providers should defer to sCU for rendering
14854 if (hasContext) {
14855 invalidateContextProvider(workInProgress, Component, false);
14856 }
14857
14858 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14859 }
14860
14861 var instance = workInProgress.stateNode;
14862
14863 // Rerender
14864 ReactCurrentOwner$3.current = workInProgress;
14865 var nextChildren = void 0;
14866 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
14867 // If we captured an error, but getDerivedStateFrom catch is not defined,
14868 // unmount all the children. componentDidCatch will schedule an update to
14869 // re-render a fallback. This is temporary until we migrate everyone to
14870 // the new API.
14871 // TODO: Warn in a future release.
14872 nextChildren = null;
14873
14874 if (enableProfilerTimer) {
14875 stopProfilerTimerIfRunning(workInProgress);
14876 }
14877 } else {
14878 {
14879 setCurrentPhase('render');
14880 nextChildren = instance.render();
14881 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14882 instance.render();
14883 }
14884 setCurrentPhase(null);
14885 }
14886 }
14887
14888 // React DevTools reads this flag.
14889 workInProgress.effectTag |= PerformedWork;
14890 if (current$$1 !== null && didCaptureError) {
14891 // If we're recovering from an error, reconcile without reusing any of
14892 // the existing children. Conceptually, the normal children and the children
14893 // that are shown on error are two different sets, so we shouldn't reuse
14894 // normal children even if their identities match.
14895 forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime);
14896 } else {
14897 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14898 }
14899
14900 // Memoize state using the values we just used to render.
14901 // TODO: Restructure so we never read values from the instance.
14902 workInProgress.memoizedState = instance.state;
14903
14904 // The context might have changed so we need to recalculate it.
14905 if (hasContext) {
14906 invalidateContextProvider(workInProgress, Component, true);
14907 }
14908
14909 return workInProgress.child;
14910}
14911
14912function pushHostRootContext(workInProgress) {
14913 var root = workInProgress.stateNode;
14914 if (root.pendingContext) {
14915 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
14916 } else if (root.context) {
14917 // Should always be set
14918 pushTopLevelContextObject(workInProgress, root.context, false);
14919 }
14920 pushHostContainer(workInProgress, root.containerInfo);
14921}
14922
14923function updateHostRoot(current$$1, workInProgress, renderExpirationTime) {
14924 pushHostRootContext(workInProgress);
14925 var updateQueue = workInProgress.updateQueue;
14926 !(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;
14927 var nextProps = workInProgress.pendingProps;
14928 var prevState = workInProgress.memoizedState;
14929 var prevChildren = prevState !== null ? prevState.element : null;
14930 processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
14931 var nextState = workInProgress.memoizedState;
14932 // Caution: React DevTools currently depends on this property
14933 // being called "element".
14934 var nextChildren = nextState.element;
14935 if (nextChildren === prevChildren) {
14936 // If the state is the same as before, that's a bailout because we had
14937 // no work that expires at this time.
14938 resetHydrationState();
14939 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14940 }
14941 var root = workInProgress.stateNode;
14942 if ((current$$1 === null || current$$1.child === null) && root.hydrate && enterHydrationState(workInProgress)) {
14943 // If we don't have any current children this might be the first pass.
14944 // We always try to hydrate. If this isn't a hydration pass there won't
14945 // be any children to hydrate which is effectively the same thing as
14946 // not hydrating.
14947
14948 // This is a bit of a hack. We track the host root as a placement to
14949 // know that we're currently in a mounting state. That way isMounted
14950 // works as expected. We must reset this before committing.
14951 // TODO: Delete this when we delete isMounted and findDOMNode.
14952 workInProgress.effectTag |= Placement;
14953
14954 // Ensure that children mount into this root without tracking
14955 // side-effects. This ensures that we don't store Placement effects on
14956 // nodes that will be hydrated.
14957 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
14958 } else {
14959 // Otherwise reset hydration state in case we aborted and resumed another
14960 // root.
14961 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14962 resetHydrationState();
14963 }
14964 return workInProgress.child;
14965}
14966
14967function updateHostComponent(current$$1, workInProgress, renderExpirationTime) {
14968 pushHostContext(workInProgress);
14969
14970 if (current$$1 === null) {
14971 tryToClaimNextHydratableInstance(workInProgress);
14972 }
14973
14974 var type = workInProgress.type;
14975 var nextProps = workInProgress.pendingProps;
14976 var prevProps = current$$1 !== null ? current$$1.memoizedProps : null;
14977
14978 var nextChildren = nextProps.children;
14979 var isDirectTextChild = shouldSetTextContent(type, nextProps);
14980
14981 if (isDirectTextChild) {
14982 // We special case a direct text child of a host node. This is a common
14983 // case. We won't handle it as a reified child. We will instead handle
14984 // this in the host environment that also have access to this prop. That
14985 // avoids allocating another HostText fiber and traversing it.
14986 nextChildren = null;
14987 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
14988 // If we're switching from a direct text child to a normal child, or to
14989 // empty, we need to schedule the text content to be reset.
14990 workInProgress.effectTag |= ContentReset;
14991 }
14992
14993 markRef(current$$1, workInProgress);
14994
14995 // Check the host config to see if the children are offscreen/hidden.
14996 if (renderExpirationTime !== Never && workInProgress.mode & ConcurrentMode && shouldDeprioritizeSubtree(type, nextProps)) {
14997 // Schedule this fiber to re-render at offscreen priority. Then bailout.
14998 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
14999 return null;
15000 }
15001
15002 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15003 return workInProgress.child;
15004}
15005
15006function updateHostText(current$$1, workInProgress) {
15007 if (current$$1 === null) {
15008 tryToClaimNextHydratableInstance(workInProgress);
15009 }
15010 // Nothing to do here. This is terminal. We'll do the completion step
15011 // immediately after.
15012 return null;
15013}
15014
15015function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
15016 if (_current !== null) {
15017 // An lazy component only mounts if it suspended inside a non-
15018 // concurrent tree, in an inconsistent state. We want to treat it like
15019 // a new mount, even though an empty version of it already committed.
15020 // Disconnect the alternate pointers.
15021 _current.alternate = null;
15022 workInProgress.alternate = null;
15023 // Since this is conceptually a new fiber, schedule a Placement effect
15024 workInProgress.effectTag |= Placement;
15025 }
15026
15027 var props = workInProgress.pendingProps;
15028 // We can't start a User Timing measurement with correct label yet.
15029 // Cancel and resume right after we know the tag.
15030 cancelWorkTimer(workInProgress);
15031 var Component = readLazyComponentType(elementType);
15032 // Store the unwrapped component in the type.
15033 workInProgress.type = Component;
15034 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
15035 startWorkTimer(workInProgress);
15036 var resolvedProps = resolveDefaultProps(Component, props);
15037 var child = void 0;
15038 switch (resolvedTag) {
15039 case FunctionComponent:
15040 {
15041 {
15042 validateFunctionComponentInDev(workInProgress, Component);
15043 }
15044 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
15045 break;
15046 }
15047 case ClassComponent:
15048 {
15049 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
15050 break;
15051 }
15052 case ForwardRef:
15053 {
15054 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
15055 break;
15056 }
15057 case MemoComponent:
15058 {
15059 {
15060 if (workInProgress.type !== workInProgress.elementType) {
15061 var outerPropTypes = Component.propTypes;
15062 if (outerPropTypes) {
15063 checkPropTypes_1(outerPropTypes, resolvedProps, // Resolved for outer only
15064 'prop', getComponentName(Component), getCurrentFiberStackInDev);
15065 }
15066 }
15067 }
15068 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
15069 updateExpirationTime, renderExpirationTime);
15070 break;
15071 }
15072 default:
15073 {
15074 var hint = '';
15075 {
15076 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
15077 hint = ' Did you wrap a component in React.lazy() more than once?';
15078 }
15079 }
15080 // This message intentionally doesn't mention ForwardRef or MemoComponent
15081 // because the fact that it's a separate type of work is an
15082 // implementation detail.
15083 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);
15084 }
15085 }
15086 return child;
15087}
15088
15089function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
15090 if (_current !== null) {
15091 // An incomplete 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 // Promote the fiber to a class and try rendering again.
15102 workInProgress.tag = ClassComponent;
15103
15104 // The rest of this function is a fork of `updateClassComponent`
15105
15106 // Push context providers early to prevent context stack mismatches.
15107 // During mounting we don't know the child context yet as the instance doesn't exist.
15108 // We will invalidate the child context in finishClassComponent() right after rendering.
15109 var hasContext = void 0;
15110 if (isContextProvider(Component)) {
15111 hasContext = true;
15112 pushContextProvider(workInProgress);
15113 } else {
15114 hasContext = false;
15115 }
15116 prepareToReadContext(workInProgress, renderExpirationTime);
15117
15118 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
15119 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
15120
15121 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
15122}
15123
15124function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
15125 if (_current !== null) {
15126 // An indeterminate component only mounts if it suspended inside a non-
15127 // concurrent tree, in an inconsistent state. We want to treat it like
15128 // a new mount, even though an empty version of it already committed.
15129 // Disconnect the alternate pointers.
15130 _current.alternate = null;
15131 workInProgress.alternate = null;
15132 // Since this is conceptually a new fiber, schedule a Placement effect
15133 workInProgress.effectTag |= Placement;
15134 }
15135
15136 var props = workInProgress.pendingProps;
15137 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
15138 var context = getMaskedContext(workInProgress, unmaskedContext);
15139
15140 prepareToReadContext(workInProgress, renderExpirationTime);
15141
15142 var value = void 0;
15143
15144 {
15145 if (Component.prototype && typeof Component.prototype.render === 'function') {
15146 var componentName = getComponentName(Component) || 'Unknown';
15147
15148 if (!didWarnAboutBadClass[componentName]) {
15149 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);
15150 didWarnAboutBadClass[componentName] = true;
15151 }
15152 }
15153
15154 if (workInProgress.mode & StrictMode) {
15155 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
15156 }
15157
15158 ReactCurrentOwner$3.current = workInProgress;
15159 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
15160 }
15161 // React DevTools reads this flag.
15162 workInProgress.effectTag |= PerformedWork;
15163
15164 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
15165 // Proceed under the assumption that this is a class instance
15166 workInProgress.tag = ClassComponent;
15167
15168 // Throw out any hooks that were used.
15169 resetHooks();
15170
15171 // Push context providers early to prevent context stack mismatches.
15172 // During mounting we don't know the child context yet as the instance doesn't exist.
15173 // We will invalidate the child context in finishClassComponent() right after rendering.
15174 var hasContext = false;
15175 if (isContextProvider(Component)) {
15176 hasContext = true;
15177 pushContextProvider(workInProgress);
15178 } else {
15179 hasContext = false;
15180 }
15181
15182 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
15183
15184 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
15185 if (typeof getDerivedStateFromProps === 'function') {
15186 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
15187 }
15188
15189 adoptClassInstance(workInProgress, value);
15190 mountClassInstance(workInProgress, Component, props, renderExpirationTime);
15191 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
15192 } else {
15193 // Proceed under the assumption that this is a function component
15194 workInProgress.tag = FunctionComponent;
15195 {
15196 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
15197 // Only double-render components with Hooks
15198 if (workInProgress.memoizedState !== null) {
15199 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
15200 }
15201 }
15202 }
15203 reconcileChildren(null, workInProgress, value, renderExpirationTime);
15204 {
15205 validateFunctionComponentInDev(workInProgress, Component);
15206 }
15207 return workInProgress.child;
15208 }
15209}
15210
15211function validateFunctionComponentInDev(workInProgress, Component) {
15212 if (Component) {
15213 !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
15214 }
15215 if (workInProgress.ref !== null) {
15216 var info = '';
15217 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
15218 if (ownerName) {
15219 info += '\n\nCheck the render method of `' + ownerName + '`.';
15220 }
15221
15222 var warningKey = ownerName || workInProgress._debugID || '';
15223 var debugSource = workInProgress._debugSource;
15224 if (debugSource) {
15225 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
15226 }
15227 if (!didWarnAboutFunctionRefs[warningKey]) {
15228 didWarnAboutFunctionRefs[warningKey] = true;
15229 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);
15230 }
15231 }
15232
15233 if (typeof Component.getDerivedStateFromProps === 'function') {
15234 var componentName = getComponentName(Component) || 'Unknown';
15235
15236 if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) {
15237 warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', componentName);
15238 didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true;
15239 }
15240 }
15241
15242 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
15243 var _componentName = getComponentName(Component) || 'Unknown';
15244
15245 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName]) {
15246 warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName);
15247 didWarnAboutContextTypeOnFunctionComponent[_componentName] = true;
15248 }
15249 }
15250}
15251
15252function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
15253 var mode = workInProgress.mode;
15254 var nextProps = workInProgress.pendingProps;
15255
15256 // We should attempt to render the primary children unless this boundary
15257 // already suspended during this render (`alreadyCaptured` is true).
15258 var nextState = workInProgress.memoizedState;
15259
15260 var nextDidTimeout = void 0;
15261 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
15262 // This is the first attempt.
15263 nextState = null;
15264 nextDidTimeout = false;
15265 } else {
15266 // Something in this boundary's subtree already suspended. Switch to
15267 // rendering the fallback children.
15268 nextState = {
15269 timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork
15270 };
15271 nextDidTimeout = true;
15272 workInProgress.effectTag &= ~DidCapture;
15273 }
15274
15275 // This next part is a bit confusing. If the children timeout, we switch to
15276 // showing the fallback children in place of the "primary" children.
15277 // However, we don't want to delete the primary children because then their
15278 // state will be lost (both the React state and the host state, e.g.
15279 // uncontrolled form inputs). Instead we keep them mounted and hide them.
15280 // Both the fallback children AND the primary children are rendered at the
15281 // same time. Once the primary children are un-suspended, we can delete
15282 // the fallback children — don't need to preserve their state.
15283 //
15284 // The two sets of children are siblings in the host environment, but
15285 // semantically, for purposes of reconciliation, they are two separate sets.
15286 // So we store them using two fragment fibers.
15287 //
15288 // However, we want to avoid allocating extra fibers for every placeholder.
15289 // They're only necessary when the children time out, because that's the
15290 // only time when both sets are mounted.
15291 //
15292 // So, the extra fragment fibers are only used if the children time out.
15293 // Otherwise, we render the primary children directly. This requires some
15294 // custom reconciliation logic to preserve the state of the primary
15295 // children. It's essentially a very basic form of re-parenting.
15296
15297 // `child` points to the child fiber. In the normal case, this is the first
15298 // fiber of the primary children set. In the timed-out case, it's a
15299 // a fragment fiber containing the primary children.
15300 var child = void 0;
15301 // `next` points to the next fiber React should render. In the normal case,
15302 // it's the same as `child`: the first fiber of the primary children set.
15303 // In the timed-out case, it's a fragment fiber containing the *fallback*
15304 // children -- we skip over the primary children entirely.
15305 var next = void 0;
15306 if (current$$1 === null) {
15307 if (enableSuspenseServerRenderer) {
15308 // If we're currently hydrating, try to hydrate this boundary.
15309 // But only if this has a fallback.
15310 if (nextProps.fallback !== undefined) {
15311 tryToClaimNextHydratableInstance(workInProgress);
15312 // This could've changed the tag if this was a dehydrated suspense component.
15313 if (workInProgress.tag === DehydratedSuspenseComponent) {
15314 return updateDehydratedSuspenseComponent(null, workInProgress, renderExpirationTime);
15315 }
15316 }
15317 }
15318
15319 // This is the initial mount. This branch is pretty simple because there's
15320 // no previous state that needs to be preserved.
15321 if (nextDidTimeout) {
15322 // Mount separate fragments for primary and fallback children.
15323 var nextFallbackChildren = nextProps.fallback;
15324 var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
15325
15326 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
15327 // Outside of concurrent mode, we commit the effects from the
15328 var progressedState = workInProgress.memoizedState;
15329 var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
15330 primaryChildFragment.child = progressedPrimaryChild;
15331 }
15332
15333 var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
15334 primaryChildFragment.sibling = fallbackChildFragment;
15335 child = primaryChildFragment;
15336 // Skip the primary children, and continue working on the
15337 // fallback children.
15338 next = fallbackChildFragment;
15339 child.return = next.return = workInProgress;
15340 } else {
15341 // Mount the primary children without an intermediate fragment fiber.
15342 var nextPrimaryChildren = nextProps.children;
15343 child = next = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
15344 }
15345 } else {
15346 // This is an update. This branch is more complicated because we need to
15347 // ensure the state of the primary children is preserved.
15348 var prevState = current$$1.memoizedState;
15349 var prevDidTimeout = prevState !== null;
15350 if (prevDidTimeout) {
15351 // The current tree already timed out. That means each child set is
15352 var currentPrimaryChildFragment = current$$1.child;
15353 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
15354 if (nextDidTimeout) {
15355 // Still timed out. Reuse the current primary children by cloning
15356 // its fragment. We're going to skip over these entirely.
15357 var _nextFallbackChildren = nextProps.fallback;
15358 var _primaryChildFragment = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
15359
15360 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
15361 // Outside of concurrent mode, we commit the effects from the
15362 var _progressedState = workInProgress.memoizedState;
15363 var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
15364 if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
15365 _primaryChildFragment.child = _progressedPrimaryChild;
15366 }
15367 }
15368
15369 // Because primaryChildFragment is a new fiber that we're inserting as the
15370 // parent of a new tree, we need to set its treeBaseDuration.
15371 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
15372 // treeBaseDuration is the sum of all the child tree base durations.
15373 var treeBaseDuration = 0;
15374 var hiddenChild = _primaryChildFragment.child;
15375 while (hiddenChild !== null) {
15376 treeBaseDuration += hiddenChild.treeBaseDuration;
15377 hiddenChild = hiddenChild.sibling;
15378 }
15379 _primaryChildFragment.treeBaseDuration = treeBaseDuration;
15380 }
15381
15382 // Clone the fallback child fragment, too. These we'll continue
15383 // working on.
15384 var _fallbackChildFragment = _primaryChildFragment.sibling = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren, currentFallbackChildFragment.expirationTime);
15385 child = _primaryChildFragment;
15386 _primaryChildFragment.childExpirationTime = NoWork;
15387 // Skip the primary children, and continue working on the
15388 // fallback children.
15389 next = _fallbackChildFragment;
15390 child.return = next.return = workInProgress;
15391 } else {
15392 // No longer suspended. Switch back to showing the primary children,
15393 // and remove the intermediate fragment fiber.
15394 var _nextPrimaryChildren = nextProps.children;
15395 var currentPrimaryChild = currentPrimaryChildFragment.child;
15396 var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime);
15397
15398 // If this render doesn't suspend, we need to delete the fallback
15399 // children. Wait until the complete phase, after we've confirmed the
15400 // fallback is no longer needed.
15401 // TODO: Would it be better to store the fallback fragment on
15402 // the stateNode?
15403
15404 // Continue rendering the children, like we normally do.
15405 child = next = primaryChild;
15406 }
15407 } else {
15408 // The current tree has not already timed out. That means the primary
15409 // children are not wrapped in a fragment fiber.
15410 var _currentPrimaryChild = current$$1.child;
15411 if (nextDidTimeout) {
15412 // Timed out. Wrap the children in a fragment fiber to keep them
15413 // separate from the fallback children.
15414 var _nextFallbackChildren2 = nextProps.fallback;
15415 var _primaryChildFragment2 = createFiberFromFragment(
15416 // It shouldn't matter what the pending props are because we aren't
15417 // going to render this fragment.
15418 null, mode, NoWork, null);
15419 _primaryChildFragment2.child = _currentPrimaryChild;
15420
15421 // Even though we're creating a new fiber, there are no new children,
15422 // because we're reusing an already mounted tree. So we don't need to
15423 // schedule a placement.
15424 // primaryChildFragment.effectTag |= Placement;
15425
15426 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
15427 // Outside of concurrent mode, we commit the effects from the
15428 var _progressedState2 = workInProgress.memoizedState;
15429 var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
15430 _primaryChildFragment2.child = _progressedPrimaryChild2;
15431 }
15432
15433 // Because primaryChildFragment is a new fiber that we're inserting as the
15434 // parent of a new tree, we need to set its treeBaseDuration.
15435 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
15436 // treeBaseDuration is the sum of all the child tree base durations.
15437 var _treeBaseDuration = 0;
15438 var _hiddenChild = _primaryChildFragment2.child;
15439 while (_hiddenChild !== null) {
15440 _treeBaseDuration += _hiddenChild.treeBaseDuration;
15441 _hiddenChild = _hiddenChild.sibling;
15442 }
15443 _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
15444 }
15445
15446 // Create a fragment from the fallback children, too.
15447 var _fallbackChildFragment2 = _primaryChildFragment2.sibling = createFiberFromFragment(_nextFallbackChildren2, mode, renderExpirationTime, null);
15448 _fallbackChildFragment2.effectTag |= Placement;
15449 child = _primaryChildFragment2;
15450 _primaryChildFragment2.childExpirationTime = NoWork;
15451 // Skip the primary children, and continue working on the
15452 // fallback children.
15453 next = _fallbackChildFragment2;
15454 child.return = next.return = workInProgress;
15455 } else {
15456 // Still haven't timed out. Continue rendering the children, like we
15457 // normally do.
15458 var _nextPrimaryChildren2 = nextProps.children;
15459 next = child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
15460 }
15461 }
15462 workInProgress.stateNode = current$$1.stateNode;
15463 }
15464
15465 workInProgress.memoizedState = nextState;
15466 workInProgress.child = child;
15467 return next;
15468}
15469
15470function updateDehydratedSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
15471 if (current$$1 === null) {
15472 // During the first pass, we'll bail out and not drill into the children.
15473 // Instead, we'll leave the content in place and try to hydrate it later.
15474 workInProgress.expirationTime = Never;
15475 return null;
15476 }
15477 // We use childExpirationTime to indicate that a child might depend on context, so if
15478 // any context has changed, we need to treat is as if the input might have changed.
15479 var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime;
15480 if (didReceiveUpdate || hasContextChanged$$1) {
15481 // This boundary has changed since the first render. This means that we are now unable to
15482 // hydrate it. We might still be able to hydrate it using an earlier expiration time but
15483 // during this render we can't. Instead, we're going to delete the whole subtree and
15484 // instead inject a new real Suspense boundary to take its place, which may render content
15485 // or fallback. The real Suspense boundary will suspend for a while so we have some time
15486 // to ensure it can produce real content, but all state and pending events will be lost.
15487
15488 // Detach from the current dehydrated boundary.
15489 current$$1.alternate = null;
15490 workInProgress.alternate = null;
15491
15492 // Insert a deletion in the effect list.
15493 var returnFiber = workInProgress.return;
15494 !(returnFiber !== null) ? invariant(false, 'Suspense boundaries are never on the root. This is probably a bug in React.') : void 0;
15495 var last = returnFiber.lastEffect;
15496 if (last !== null) {
15497 last.nextEffect = current$$1;
15498 returnFiber.lastEffect = current$$1;
15499 } else {
15500 returnFiber.firstEffect = returnFiber.lastEffect = current$$1;
15501 }
15502 current$$1.nextEffect = null;
15503 current$$1.effectTag = Deletion;
15504
15505 // Upgrade this work in progress to a real Suspense component.
15506 workInProgress.tag = SuspenseComponent;
15507 workInProgress.stateNode = null;
15508 workInProgress.memoizedState = null;
15509 // This is now an insertion.
15510 workInProgress.effectTag |= Placement;
15511 // Retry as a real Suspense component.
15512 return updateSuspenseComponent(null, workInProgress, renderExpirationTime);
15513 }
15514 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
15515 // This is the first attempt.
15516 reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress);
15517 var nextProps = workInProgress.pendingProps;
15518 var nextChildren = nextProps.children;
15519 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
15520 return workInProgress.child;
15521 } else {
15522 // Something suspended. Leave the existing children in place.
15523 // TODO: In non-concurrent mode, should we commit the nodes we have hydrated so far?
15524 workInProgress.child = null;
15525 return null;
15526 }
15527}
15528
15529function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) {
15530 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
15531 var nextChildren = workInProgress.pendingProps;
15532 if (current$$1 === null) {
15533 // Portals are special because we don't append the children during mount
15534 // but at commit. Therefore we need to track insertions which the normal
15535 // flow doesn't do during mount. This doesn't happen at the root because
15536 // the root always starts with a "current" with a null child.
15537 // TODO: Consider unifying this with how the root works.
15538 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
15539 } else {
15540 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15541 }
15542 return workInProgress.child;
15543}
15544
15545function updateContextProvider(current$$1, workInProgress, renderExpirationTime) {
15546 var providerType = workInProgress.type;
15547 var context = providerType._context;
15548
15549 var newProps = workInProgress.pendingProps;
15550 var oldProps = workInProgress.memoizedProps;
15551
15552 var newValue = newProps.value;
15553
15554 {
15555 var providerPropTypes = workInProgress.type.propTypes;
15556
15557 if (providerPropTypes) {
15558 checkPropTypes_1(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
15559 }
15560 }
15561
15562 pushProvider(workInProgress, newValue);
15563
15564 if (oldProps !== null) {
15565 var oldValue = oldProps.value;
15566 var changedBits = calculateChangedBits(context, newValue, oldValue);
15567 if (changedBits === 0) {
15568 // No change. Bailout early if children are the same.
15569 if (oldProps.children === newProps.children && !hasContextChanged()) {
15570 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15571 }
15572 } else {
15573 // The context value changed. Search for matching consumers and schedule
15574 // them to update.
15575 propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
15576 }
15577 }
15578
15579 var newChildren = newProps.children;
15580 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
15581 return workInProgress.child;
15582}
15583
15584var hasWarnedAboutUsingContextAsConsumer = false;
15585
15586function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) {
15587 var context = workInProgress.type;
15588 // The logic below for Context differs depending on PROD or DEV mode. In
15589 // DEV mode, we create a separate object for Context.Consumer that acts
15590 // like a proxy to Context. This proxy object adds unnecessary code in PROD
15591 // so we use the old behaviour (Context.Consumer references Context) to
15592 // reduce size and overhead. The separate object references context via
15593 // a property called "_context", which also gives us the ability to check
15594 // in DEV mode if this property exists or not and warn if it does not.
15595 {
15596 if (context._context === undefined) {
15597 // This may be because it's a Context (rather than a Consumer).
15598 // Or it may be because it's older React where they're the same thing.
15599 // We only want to warn if we're sure it's a new React.
15600 if (context !== context.Consumer) {
15601 if (!hasWarnedAboutUsingContextAsConsumer) {
15602 hasWarnedAboutUsingContextAsConsumer = true;
15603 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?');
15604 }
15605 }
15606 } else {
15607 context = context._context;
15608 }
15609 }
15610 var newProps = workInProgress.pendingProps;
15611 var render = newProps.children;
15612
15613 {
15614 !(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;
15615 }
15616
15617 prepareToReadContext(workInProgress, renderExpirationTime);
15618 var newValue = readContext(context, newProps.unstable_observedBits);
15619 var newChildren = void 0;
15620 {
15621 ReactCurrentOwner$3.current = workInProgress;
15622 setCurrentPhase('render');
15623 newChildren = render(newValue);
15624 setCurrentPhase(null);
15625 }
15626
15627 // React DevTools reads this flag.
15628 workInProgress.effectTag |= PerformedWork;
15629 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
15630 return workInProgress.child;
15631}
15632
15633function markWorkInProgressReceivedUpdate() {
15634 didReceiveUpdate = true;
15635}
15636
15637function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) {
15638 cancelWorkTimer(workInProgress);
15639
15640 if (current$$1 !== null) {
15641 // Reuse previous context list
15642 workInProgress.contextDependencies = current$$1.contextDependencies;
15643 }
15644
15645 if (enableProfilerTimer) {
15646 // Don't update "base" render times for bailouts.
15647 stopProfilerTimerIfRunning(workInProgress);
15648 }
15649
15650 // Check if the children have any pending work.
15651 var childExpirationTime = workInProgress.childExpirationTime;
15652 if (childExpirationTime < renderExpirationTime) {
15653 // The children don't have any work either. We can skip them.
15654 // TODO: Once we add back resuming, we should check if the children are
15655 // a work-in-progress set. If so, we need to transfer their effects.
15656 return null;
15657 } else {
15658 // This fiber doesn't have work, but its subtree does. Clone the child
15659 // fibers and continue.
15660 cloneChildFibers(current$$1, workInProgress);
15661 return workInProgress.child;
15662 }
15663}
15664
15665function beginWork(current$$1, workInProgress, renderExpirationTime) {
15666 var updateExpirationTime = workInProgress.expirationTime;
15667
15668 if (current$$1 !== null) {
15669 var oldProps = current$$1.memoizedProps;
15670 var newProps = workInProgress.pendingProps;
15671
15672 if (oldProps !== newProps || hasContextChanged()) {
15673 // If props or context changed, mark the fiber as having performed work.
15674 // This may be unset if the props are determined to be equal later (memo).
15675 didReceiveUpdate = true;
15676 } else if (updateExpirationTime < renderExpirationTime) {
15677 didReceiveUpdate = false;
15678 // This fiber does not have any pending work. Bailout without entering
15679 // the begin phase. There's still some bookkeeping we that needs to be done
15680 // in this optimized path, mostly pushing stuff onto the stack.
15681 switch (workInProgress.tag) {
15682 case HostRoot:
15683 pushHostRootContext(workInProgress);
15684 resetHydrationState();
15685 break;
15686 case HostComponent:
15687 pushHostContext(workInProgress);
15688 break;
15689 case ClassComponent:
15690 {
15691 var Component = workInProgress.type;
15692 if (isContextProvider(Component)) {
15693 pushContextProvider(workInProgress);
15694 }
15695 break;
15696 }
15697 case HostPortal:
15698 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
15699 break;
15700 case ContextProvider:
15701 {
15702 var newValue = workInProgress.memoizedProps.value;
15703 pushProvider(workInProgress, newValue);
15704 break;
15705 }
15706 case Profiler:
15707 if (enableProfilerTimer) {
15708 workInProgress.effectTag |= Update;
15709 }
15710 break;
15711 case SuspenseComponent:
15712 {
15713 var state = workInProgress.memoizedState;
15714 var didTimeout = state !== null;
15715 if (didTimeout) {
15716 // If this boundary is currently timed out, we need to decide
15717 // whether to retry the primary children, or to skip over it and
15718 // go straight to the fallback. Check the priority of the primary
15719 var primaryChildFragment = workInProgress.child;
15720 var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
15721 if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
15722 // The primary children have pending work. Use the normal path
15723 // to attempt to render the primary children again.
15724 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
15725 } else {
15726 // The primary children do not have pending work with sufficient
15727 // priority. Bailout.
15728 var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15729 if (child !== null) {
15730 // The fallback children have pending work. Skip over the
15731 // primary children and work on the fallback.
15732 return child.sibling;
15733 } else {
15734 return null;
15735 }
15736 }
15737 }
15738 break;
15739 }
15740 case DehydratedSuspenseComponent:
15741 {
15742 if (enableSuspenseServerRenderer) {
15743 // We know that this component will suspend again because if it has
15744 // been unsuspended it has committed as a regular Suspense component.
15745 // If it needs to be retried, it should have work scheduled on it.
15746 workInProgress.effectTag |= DidCapture;
15747 break;
15748 }
15749 }
15750 }
15751 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15752 }
15753 } else {
15754 didReceiveUpdate = false;
15755 }
15756
15757 // Before entering the begin phase, clear the expiration time.
15758 workInProgress.expirationTime = NoWork;
15759
15760 switch (workInProgress.tag) {
15761 case IndeterminateComponent:
15762 {
15763 var elementType = workInProgress.elementType;
15764 return mountIndeterminateComponent(current$$1, workInProgress, elementType, renderExpirationTime);
15765 }
15766 case LazyComponent:
15767 {
15768 var _elementType = workInProgress.elementType;
15769 return mountLazyComponent(current$$1, workInProgress, _elementType, updateExpirationTime, renderExpirationTime);
15770 }
15771 case FunctionComponent:
15772 {
15773 var _Component = workInProgress.type;
15774 var unresolvedProps = workInProgress.pendingProps;
15775 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
15776 return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime);
15777 }
15778 case ClassComponent:
15779 {
15780 var _Component2 = workInProgress.type;
15781 var _unresolvedProps = workInProgress.pendingProps;
15782 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
15783 return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
15784 }
15785 case HostRoot:
15786 return updateHostRoot(current$$1, workInProgress, renderExpirationTime);
15787 case HostComponent:
15788 return updateHostComponent(current$$1, workInProgress, renderExpirationTime);
15789 case HostText:
15790 return updateHostText(current$$1, workInProgress);
15791 case SuspenseComponent:
15792 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
15793 case HostPortal:
15794 return updatePortalComponent(current$$1, workInProgress, renderExpirationTime);
15795 case ForwardRef:
15796 {
15797 var type = workInProgress.type;
15798 var _unresolvedProps2 = workInProgress.pendingProps;
15799 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
15800 return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime);
15801 }
15802 case Fragment:
15803 return updateFragment(current$$1, workInProgress, renderExpirationTime);
15804 case Mode:
15805 return updateMode(current$$1, workInProgress, renderExpirationTime);
15806 case Profiler:
15807 return updateProfiler(current$$1, workInProgress, renderExpirationTime);
15808 case ContextProvider:
15809 return updateContextProvider(current$$1, workInProgress, renderExpirationTime);
15810 case ContextConsumer:
15811 return updateContextConsumer(current$$1, workInProgress, renderExpirationTime);
15812 case MemoComponent:
15813 {
15814 var _type2 = workInProgress.type;
15815 var _unresolvedProps3 = workInProgress.pendingProps;
15816 // Resolve outer props first, then resolve inner props.
15817 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
15818 {
15819 if (workInProgress.type !== workInProgress.elementType) {
15820 var outerPropTypes = _type2.propTypes;
15821 if (outerPropTypes) {
15822 checkPropTypes_1(outerPropTypes, _resolvedProps3, // Resolved for outer only
15823 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
15824 }
15825 }
15826 }
15827 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
15828 return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
15829 }
15830 case SimpleMemoComponent:
15831 {
15832 return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
15833 }
15834 case IncompleteClassComponent:
15835 {
15836 var _Component3 = workInProgress.type;
15837 var _unresolvedProps4 = workInProgress.pendingProps;
15838 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
15839 return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
15840 }
15841 case DehydratedSuspenseComponent:
15842 {
15843 if (enableSuspenseServerRenderer) {
15844 return updateDehydratedSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
15845 }
15846 break;
15847 }
15848 }
15849 invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
15850}
15851
15852var valueCursor = createCursor(null);
15853
15854var rendererSigil = void 0;
15855{
15856 // Use this to detect multiple renderers using the same context
15857 rendererSigil = {};
15858}
15859
15860var currentlyRenderingFiber = null;
15861var lastContextDependency = null;
15862var lastContextWithAllBitsObserved = null;
15863
15864var isDisallowedContextReadInDEV = false;
15865
15866function resetContextDependences() {
15867 // This is called right before React yields execution, to ensure `readContext`
15868 // cannot be called outside the render phase.
15869 currentlyRenderingFiber = null;
15870 lastContextDependency = null;
15871 lastContextWithAllBitsObserved = null;
15872 {
15873 isDisallowedContextReadInDEV = false;
15874 }
15875}
15876
15877function enterDisallowedContextReadInDEV() {
15878 {
15879 isDisallowedContextReadInDEV = true;
15880 }
15881}
15882
15883function exitDisallowedContextReadInDEV() {
15884 {
15885 isDisallowedContextReadInDEV = false;
15886 }
15887}
15888
15889function pushProvider(providerFiber, nextValue) {
15890 var context = providerFiber.type._context;
15891
15892 if (isPrimaryRenderer) {
15893 push(valueCursor, context._currentValue, providerFiber);
15894
15895 context._currentValue = nextValue;
15896 {
15897 !(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;
15898 context._currentRenderer = rendererSigil;
15899 }
15900 } else {
15901 push(valueCursor, context._currentValue2, providerFiber);
15902
15903 context._currentValue2 = nextValue;
15904 {
15905 !(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;
15906 context._currentRenderer2 = rendererSigil;
15907 }
15908 }
15909}
15910
15911function popProvider(providerFiber) {
15912 var currentValue = valueCursor.current;
15913
15914 pop(valueCursor, providerFiber);
15915
15916 var context = providerFiber.type._context;
15917 if (isPrimaryRenderer) {
15918 context._currentValue = currentValue;
15919 } else {
15920 context._currentValue2 = currentValue;
15921 }
15922}
15923
15924function calculateChangedBits(context, newValue, oldValue) {
15925 if (is(oldValue, newValue)) {
15926 // No change
15927 return 0;
15928 } else {
15929 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : maxSigned31BitInt;
15930
15931 {
15932 !((changedBits & maxSigned31BitInt) === changedBits) ? warning$1(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0;
15933 }
15934 return changedBits | 0;
15935 }
15936}
15937
15938function scheduleWorkOnParentPath(parent, renderExpirationTime) {
15939 // Update the child expiration time of all the ancestors, including
15940 // the alternates.
15941 var node = parent;
15942 while (node !== null) {
15943 var alternate = node.alternate;
15944 if (node.childExpirationTime < renderExpirationTime) {
15945 node.childExpirationTime = renderExpirationTime;
15946 if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
15947 alternate.childExpirationTime = renderExpirationTime;
15948 }
15949 } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
15950 alternate.childExpirationTime = renderExpirationTime;
15951 } else {
15952 // Neither alternate was updated, which means the rest of the
15953 // ancestor path already has sufficient priority.
15954 break;
15955 }
15956 node = node.return;
15957 }
15958}
15959
15960function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
15961 var fiber = workInProgress.child;
15962 if (fiber !== null) {
15963 // Set the return pointer of the child to the work-in-progress fiber.
15964 fiber.return = workInProgress;
15965 }
15966 while (fiber !== null) {
15967 var nextFiber = void 0;
15968
15969 // Visit this fiber.
15970 var list = fiber.contextDependencies;
15971 if (list !== null) {
15972 nextFiber = fiber.child;
15973
15974 var dependency = list.first;
15975 while (dependency !== null) {
15976 // Check if the context matches.
15977 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
15978 // Match! Schedule an update on this fiber.
15979
15980 if (fiber.tag === ClassComponent) {
15981 // Schedule a force update on the work-in-progress.
15982 var update = createUpdate(renderExpirationTime);
15983 update.tag = ForceUpdate;
15984 // TODO: Because we don't have a work-in-progress, this will add the
15985 // update to the current fiber, too, which means it will persist even if
15986 // this render is thrown away. Since it's a race condition, not sure it's
15987 // worth fixing.
15988 enqueueUpdate(fiber, update);
15989 }
15990
15991 if (fiber.expirationTime < renderExpirationTime) {
15992 fiber.expirationTime = renderExpirationTime;
15993 }
15994 var alternate = fiber.alternate;
15995 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
15996 alternate.expirationTime = renderExpirationTime;
15997 }
15998
15999 scheduleWorkOnParentPath(fiber.return, renderExpirationTime);
16000
16001 // Mark the expiration time on the list, too.
16002 if (list.expirationTime < renderExpirationTime) {
16003 list.expirationTime = renderExpirationTime;
16004 }
16005
16006 // Since we already found a match, we can stop traversing the
16007 // dependency list.
16008 break;
16009 }
16010 dependency = dependency.next;
16011 }
16012 } else if (fiber.tag === ContextProvider) {
16013 // Don't scan deeper if this is a matching provider
16014 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
16015 } else if (enableSuspenseServerRenderer && fiber.tag === DehydratedSuspenseComponent) {
16016 // If a dehydrated suspense component is in this subtree, we don't know
16017 // if it will have any context consumers in it. The best we can do is
16018 // mark it as having updates on its children.
16019 if (fiber.expirationTime < renderExpirationTime) {
16020 fiber.expirationTime = renderExpirationTime;
16021 }
16022 var _alternate = fiber.alternate;
16023 if (_alternate !== null && _alternate.expirationTime < renderExpirationTime) {
16024 _alternate.expirationTime = renderExpirationTime;
16025 }
16026 // This is intentionally passing this fiber as the parent
16027 // because we want to schedule this fiber as having work
16028 // on its children. We'll use the childExpirationTime on
16029 // this fiber to indicate that a context has changed.
16030 scheduleWorkOnParentPath(fiber, renderExpirationTime);
16031 nextFiber = fiber.sibling;
16032 } else {
16033 // Traverse down.
16034 nextFiber = fiber.child;
16035 }
16036
16037 if (nextFiber !== null) {
16038 // Set the return pointer of the child to the work-in-progress fiber.
16039 nextFiber.return = fiber;
16040 } else {
16041 // No child. Traverse to next sibling.
16042 nextFiber = fiber;
16043 while (nextFiber !== null) {
16044 if (nextFiber === workInProgress) {
16045 // We're back to the root of this subtree. Exit.
16046 nextFiber = null;
16047 break;
16048 }
16049 var sibling = nextFiber.sibling;
16050 if (sibling !== null) {
16051 // Set the return pointer of the sibling to the work-in-progress fiber.
16052 sibling.return = nextFiber.return;
16053 nextFiber = sibling;
16054 break;
16055 }
16056 // No more siblings. Traverse up.
16057 nextFiber = nextFiber.return;
16058 }
16059 }
16060 fiber = nextFiber;
16061 }
16062}
16063
16064function prepareToReadContext(workInProgress, renderExpirationTime) {
16065 currentlyRenderingFiber = workInProgress;
16066 lastContextDependency = null;
16067 lastContextWithAllBitsObserved = null;
16068
16069 var currentDependencies = workInProgress.contextDependencies;
16070 if (currentDependencies !== null && currentDependencies.expirationTime >= renderExpirationTime) {
16071 // Context list has a pending update. Mark that this fiber performed work.
16072 markWorkInProgressReceivedUpdate();
16073 }
16074
16075 // Reset the work-in-progress list
16076 workInProgress.contextDependencies = null;
16077}
16078
16079function readContext(context, observedBits) {
16080 {
16081 // This warning would fire if you read context inside a Hook like useMemo.
16082 // Unlike the class check below, it's not enforced in production for perf.
16083 !!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;
16084 }
16085
16086 if (lastContextWithAllBitsObserved === context) {
16087 // Nothing to do. We already observe everything in this context.
16088 } else if (observedBits === false || observedBits === 0) {
16089 // Do not observe any updates.
16090 } else {
16091 var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types.
16092 if (typeof observedBits !== 'number' || observedBits === maxSigned31BitInt) {
16093 // Observe all updates.
16094 lastContextWithAllBitsObserved = context;
16095 resolvedObservedBits = maxSigned31BitInt;
16096 } else {
16097 resolvedObservedBits = observedBits;
16098 }
16099
16100 var contextItem = {
16101 context: context,
16102 observedBits: resolvedObservedBits,
16103 next: null
16104 };
16105
16106 if (lastContextDependency === null) {
16107 !(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;
16108
16109 // This is the first dependency for this component. Create a new list.
16110 lastContextDependency = contextItem;
16111 currentlyRenderingFiber.contextDependencies = {
16112 first: contextItem,
16113 expirationTime: NoWork
16114 };
16115 } else {
16116 // Append a new context item.
16117 lastContextDependency = lastContextDependency.next = contextItem;
16118 }
16119 }
16120 return isPrimaryRenderer ? context._currentValue : context._currentValue2;
16121}
16122
16123// UpdateQueue is a linked list of prioritized updates.
16124//
16125// Like fibers, update queues come in pairs: a current queue, which represents
16126// the visible state of the screen, and a work-in-progress queue, which can be
16127// mutated and processed asynchronously before it is committed — a form of
16128// double buffering. If a work-in-progress render is discarded before finishing,
16129// we create a new work-in-progress by cloning the current queue.
16130//
16131// Both queues share a persistent, singly-linked list structure. To schedule an
16132// update, we append it to the end of both queues. Each queue maintains a
16133// pointer to first update in the persistent list that hasn't been processed.
16134// The work-in-progress pointer always has a position equal to or greater than
16135// the current queue, since we always work on that one. The current queue's
16136// pointer is only updated during the commit phase, when we swap in the
16137// work-in-progress.
16138//
16139// For example:
16140//
16141// Current pointer: A - B - C - D - E - F
16142// Work-in-progress pointer: D - E - F
16143// ^
16144// The work-in-progress queue has
16145// processed more updates than current.
16146//
16147// The reason we append to both queues is because otherwise we might drop
16148// updates without ever processing them. For example, if we only add updates to
16149// the work-in-progress queue, some updates could be lost whenever a work-in
16150// -progress render restarts by cloning from current. Similarly, if we only add
16151// updates to the current queue, the updates will be lost whenever an already
16152// in-progress queue commits and swaps with the current queue. However, by
16153// adding to both queues, we guarantee that the update will be part of the next
16154// work-in-progress. (And because the work-in-progress queue becomes the
16155// current queue once it commits, there's no danger of applying the same
16156// update twice.)
16157//
16158// Prioritization
16159// --------------
16160//
16161// Updates are not sorted by priority, but by insertion; new updates are always
16162// appended to the end of the list.
16163//
16164// The priority is still important, though. When processing the update queue
16165// during the render phase, only the updates with sufficient priority are
16166// included in the result. If we skip an update because it has insufficient
16167// priority, it remains in the queue to be processed later, during a lower
16168// priority render. Crucially, all updates subsequent to a skipped update also
16169// remain in the queue *regardless of their priority*. That means high priority
16170// updates are sometimes processed twice, at two separate priorities. We also
16171// keep track of a base state, that represents the state before the first
16172// update in the queue is applied.
16173//
16174// For example:
16175//
16176// Given a base state of '', and the following queue of updates
16177//
16178// A1 - B2 - C1 - D2
16179//
16180// where the number indicates the priority, and the update is applied to the
16181// previous state by appending a letter, React will process these updates as
16182// two separate renders, one per distinct priority level:
16183//
16184// First render, at priority 1:
16185// Base state: ''
16186// Updates: [A1, C1]
16187// Result state: 'AC'
16188//
16189// Second render, at priority 2:
16190// Base state: 'A' <- The base state does not include C1,
16191// because B2 was skipped.
16192// Updates: [B2, C1, D2] <- C1 was rebased on top of B2
16193// Result state: 'ABCD'
16194//
16195// Because we process updates in insertion order, and rebase high priority
16196// updates when preceding updates are skipped, the final result is deterministic
16197// regardless of priority. Intermediate state may vary according to system
16198// resources, but the final state is always the same.
16199
16200var UpdateState = 0;
16201var ReplaceState = 1;
16202var ForceUpdate = 2;
16203var CaptureUpdate = 3;
16204
16205// Global state that is reset at the beginning of calling `processUpdateQueue`.
16206// It should only be read right after calling `processUpdateQueue`, via
16207// `checkHasForceUpdateAfterProcessing`.
16208var hasForceUpdate = false;
16209
16210var didWarnUpdateInsideUpdate = void 0;
16211var currentlyProcessingQueue = void 0;
16212var resetCurrentlyProcessingQueue = void 0;
16213{
16214 didWarnUpdateInsideUpdate = false;
16215 currentlyProcessingQueue = null;
16216 resetCurrentlyProcessingQueue = function () {
16217 currentlyProcessingQueue = null;
16218 };
16219}
16220
16221function createUpdateQueue(baseState) {
16222 var queue = {
16223 baseState: baseState,
16224 firstUpdate: null,
16225 lastUpdate: null,
16226 firstCapturedUpdate: null,
16227 lastCapturedUpdate: null,
16228 firstEffect: null,
16229 lastEffect: null,
16230 firstCapturedEffect: null,
16231 lastCapturedEffect: null
16232 };
16233 return queue;
16234}
16235
16236function cloneUpdateQueue(currentQueue) {
16237 var queue = {
16238 baseState: currentQueue.baseState,
16239 firstUpdate: currentQueue.firstUpdate,
16240 lastUpdate: currentQueue.lastUpdate,
16241
16242 // TODO: With resuming, if we bail out and resuse the child tree, we should
16243 // keep these effects.
16244 firstCapturedUpdate: null,
16245 lastCapturedUpdate: null,
16246
16247 firstEffect: null,
16248 lastEffect: null,
16249
16250 firstCapturedEffect: null,
16251 lastCapturedEffect: null
16252 };
16253 return queue;
16254}
16255
16256function createUpdate(expirationTime) {
16257 return {
16258 expirationTime: expirationTime,
16259
16260 tag: UpdateState,
16261 payload: null,
16262 callback: null,
16263
16264 next: null,
16265 nextEffect: null
16266 };
16267}
16268
16269function appendUpdateToQueue(queue, update) {
16270 // Append the update to the end of the list.
16271 if (queue.lastUpdate === null) {
16272 // Queue is empty
16273 queue.firstUpdate = queue.lastUpdate = update;
16274 } else {
16275 queue.lastUpdate.next = update;
16276 queue.lastUpdate = update;
16277 }
16278}
16279
16280function enqueueUpdate(fiber, update) {
16281 // Update queues are created lazily.
16282 var alternate = fiber.alternate;
16283 var queue1 = void 0;
16284 var queue2 = void 0;
16285 if (alternate === null) {
16286 // There's only one fiber.
16287 queue1 = fiber.updateQueue;
16288 queue2 = null;
16289 if (queue1 === null) {
16290 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
16291 }
16292 } else {
16293 // There are two owners.
16294 queue1 = fiber.updateQueue;
16295 queue2 = alternate.updateQueue;
16296 if (queue1 === null) {
16297 if (queue2 === null) {
16298 // Neither fiber has an update queue. Create new ones.
16299 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
16300 queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
16301 } else {
16302 // Only one fiber has an update queue. Clone to create a new one.
16303 queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
16304 }
16305 } else {
16306 if (queue2 === null) {
16307 // Only one fiber has an update queue. Clone to create a new one.
16308 queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
16309 } else {
16310 // Both owners have an update queue.
16311 }
16312 }
16313 }
16314 if (queue2 === null || queue1 === queue2) {
16315 // There's only a single queue.
16316 appendUpdateToQueue(queue1, update);
16317 } else {
16318 // There are two queues. We need to append the update to both queues,
16319 // while accounting for the persistent structure of the list — we don't
16320 // want the same update to be added multiple times.
16321 if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
16322 // One of the queues is not empty. We must add the update to both queues.
16323 appendUpdateToQueue(queue1, update);
16324 appendUpdateToQueue(queue2, update);
16325 } else {
16326 // Both queues are non-empty. The last update is the same in both lists,
16327 // because of structural sharing. So, only append to one of the lists.
16328 appendUpdateToQueue(queue1, update);
16329 // But we still need to update the `lastUpdate` pointer of queue2.
16330 queue2.lastUpdate = update;
16331 }
16332 }
16333
16334 {
16335 if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
16336 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.');
16337 didWarnUpdateInsideUpdate = true;
16338 }
16339 }
16340}
16341
16342function enqueueCapturedUpdate(workInProgress, update) {
16343 // Captured updates go into a separate list, and only on the work-in-
16344 // progress queue.
16345 var workInProgressQueue = workInProgress.updateQueue;
16346 if (workInProgressQueue === null) {
16347 workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
16348 } else {
16349 // TODO: I put this here rather than createWorkInProgress so that we don't
16350 // clone the queue unnecessarily. There's probably a better way to
16351 // structure this.
16352 workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
16353 }
16354
16355 // Append the update to the end of the list.
16356 if (workInProgressQueue.lastCapturedUpdate === null) {
16357 // This is the first render phase update
16358 workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
16359 } else {
16360 workInProgressQueue.lastCapturedUpdate.next = update;
16361 workInProgressQueue.lastCapturedUpdate = update;
16362 }
16363}
16364
16365function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
16366 var current = workInProgress.alternate;
16367 if (current !== null) {
16368 // If the work-in-progress queue is equal to the current queue,
16369 // we need to clone it first.
16370 if (queue === current.updateQueue) {
16371 queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
16372 }
16373 }
16374 return queue;
16375}
16376
16377function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
16378 switch (update.tag) {
16379 case ReplaceState:
16380 {
16381 var _payload = update.payload;
16382 if (typeof _payload === 'function') {
16383 // Updater function
16384 {
16385 enterDisallowedContextReadInDEV();
16386 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
16387 _payload.call(instance, prevState, nextProps);
16388 }
16389 }
16390 var nextState = _payload.call(instance, prevState, nextProps);
16391 {
16392 exitDisallowedContextReadInDEV();
16393 }
16394 return nextState;
16395 }
16396 // State object
16397 return _payload;
16398 }
16399 case CaptureUpdate:
16400 {
16401 workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
16402 }
16403 // Intentional fallthrough
16404 case UpdateState:
16405 {
16406 var _payload2 = update.payload;
16407 var partialState = void 0;
16408 if (typeof _payload2 === 'function') {
16409 // Updater function
16410 {
16411 enterDisallowedContextReadInDEV();
16412 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
16413 _payload2.call(instance, prevState, nextProps);
16414 }
16415 }
16416 partialState = _payload2.call(instance, prevState, nextProps);
16417 {
16418 exitDisallowedContextReadInDEV();
16419 }
16420 } else {
16421 // Partial state object
16422 partialState = _payload2;
16423 }
16424 if (partialState === null || partialState === undefined) {
16425 // Null and undefined are treated as no-ops.
16426 return prevState;
16427 }
16428 // Merge the partial state and the previous state.
16429 return _assign({}, prevState, partialState);
16430 }
16431 case ForceUpdate:
16432 {
16433 hasForceUpdate = true;
16434 return prevState;
16435 }
16436 }
16437 return prevState;
16438}
16439
16440function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
16441 hasForceUpdate = false;
16442
16443 queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
16444
16445 {
16446 currentlyProcessingQueue = queue;
16447 }
16448
16449 // These values may change as we process the queue.
16450 var newBaseState = queue.baseState;
16451 var newFirstUpdate = null;
16452 var newExpirationTime = NoWork;
16453
16454 // Iterate through the list of updates to compute the result.
16455 var update = queue.firstUpdate;
16456 var resultState = newBaseState;
16457 while (update !== null) {
16458 var updateExpirationTime = update.expirationTime;
16459 if (updateExpirationTime < renderExpirationTime) {
16460 // This update does not have sufficient priority. Skip it.
16461 if (newFirstUpdate === null) {
16462 // This is the first skipped update. It will be the first update in
16463 // the new list.
16464 newFirstUpdate = update;
16465 // Since this is the first update that was skipped, the current result
16466 // is the new base state.
16467 newBaseState = resultState;
16468 }
16469 // Since this update will remain in the list, update the remaining
16470 // expiration time.
16471 if (newExpirationTime < updateExpirationTime) {
16472 newExpirationTime = updateExpirationTime;
16473 }
16474 } else {
16475 // This update does have sufficient priority. Process it and compute
16476 // a new result.
16477 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
16478 var _callback = update.callback;
16479 if (_callback !== null) {
16480 workInProgress.effectTag |= Callback;
16481 // Set this to null, in case it was mutated during an aborted render.
16482 update.nextEffect = null;
16483 if (queue.lastEffect === null) {
16484 queue.firstEffect = queue.lastEffect = update;
16485 } else {
16486 queue.lastEffect.nextEffect = update;
16487 queue.lastEffect = update;
16488 }
16489 }
16490 }
16491 // Continue to the next update.
16492 update = update.next;
16493 }
16494
16495 // Separately, iterate though the list of captured updates.
16496 var newFirstCapturedUpdate = null;
16497 update = queue.firstCapturedUpdate;
16498 while (update !== null) {
16499 var _updateExpirationTime = update.expirationTime;
16500 if (_updateExpirationTime < renderExpirationTime) {
16501 // This update does not have sufficient priority. Skip it.
16502 if (newFirstCapturedUpdate === null) {
16503 // This is the first skipped captured update. It will be the first
16504 // update in the new list.
16505 newFirstCapturedUpdate = update;
16506 // If this is the first update that was skipped, the current result is
16507 // the new base state.
16508 if (newFirstUpdate === null) {
16509 newBaseState = resultState;
16510 }
16511 }
16512 // Since this update will remain in the list, update the remaining
16513 // expiration time.
16514 if (newExpirationTime < _updateExpirationTime) {
16515 newExpirationTime = _updateExpirationTime;
16516 }
16517 } else {
16518 // This update does have sufficient priority. Process it and compute
16519 // a new result.
16520 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
16521 var _callback2 = update.callback;
16522 if (_callback2 !== null) {
16523 workInProgress.effectTag |= Callback;
16524 // Set this to null, in case it was mutated during an aborted render.
16525 update.nextEffect = null;
16526 if (queue.lastCapturedEffect === null) {
16527 queue.firstCapturedEffect = queue.lastCapturedEffect = update;
16528 } else {
16529 queue.lastCapturedEffect.nextEffect = update;
16530 queue.lastCapturedEffect = update;
16531 }
16532 }
16533 }
16534 update = update.next;
16535 }
16536
16537 if (newFirstUpdate === null) {
16538 queue.lastUpdate = null;
16539 }
16540 if (newFirstCapturedUpdate === null) {
16541 queue.lastCapturedUpdate = null;
16542 } else {
16543 workInProgress.effectTag |= Callback;
16544 }
16545 if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
16546 // We processed every update, without skipping. That means the new base
16547 // state is the same as the result state.
16548 newBaseState = resultState;
16549 }
16550
16551 queue.baseState = newBaseState;
16552 queue.firstUpdate = newFirstUpdate;
16553 queue.firstCapturedUpdate = newFirstCapturedUpdate;
16554
16555 // Set the remaining expiration time to be whatever is remaining in the queue.
16556 // This should be fine because the only two other things that contribute to
16557 // expiration time are props and context. We're already in the middle of the
16558 // begin phase by the time we start processing the queue, so we've already
16559 // dealt with the props. Context in components that specify
16560 // shouldComponentUpdate is tricky; but we'll have to account for
16561 // that regardless.
16562 workInProgress.expirationTime = newExpirationTime;
16563 workInProgress.memoizedState = resultState;
16564
16565 {
16566 currentlyProcessingQueue = null;
16567 }
16568}
16569
16570function callCallback(callback, context) {
16571 !(typeof callback === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', callback) : void 0;
16572 callback.call(context);
16573}
16574
16575function resetHasForceUpdateBeforeProcessing() {
16576 hasForceUpdate = false;
16577}
16578
16579function checkHasForceUpdateAfterProcessing() {
16580 return hasForceUpdate;
16581}
16582
16583function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
16584 // If the finished render included captured updates, and there are still
16585 // lower priority updates left over, we need to keep the captured updates
16586 // in the queue so that they are rebased and not dropped once we process the
16587 // queue again at the lower priority.
16588 if (finishedQueue.firstCapturedUpdate !== null) {
16589 // Join the captured update list to the end of the normal list.
16590 if (finishedQueue.lastUpdate !== null) {
16591 finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
16592 finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
16593 }
16594 // Clear the list of captured updates.
16595 finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
16596 }
16597
16598 // Commit the effects
16599 commitUpdateEffects(finishedQueue.firstEffect, instance);
16600 finishedQueue.firstEffect = finishedQueue.lastEffect = null;
16601
16602 commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
16603 finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
16604}
16605
16606function commitUpdateEffects(effect, instance) {
16607 while (effect !== null) {
16608 var _callback3 = effect.callback;
16609 if (_callback3 !== null) {
16610 effect.callback = null;
16611 callCallback(_callback3, instance);
16612 }
16613 effect = effect.nextEffect;
16614 }
16615}
16616
16617function createCapturedValue(value, source) {
16618 // If the value is an error, call this function immediately after it is thrown
16619 // so the stack is accurate.
16620 return {
16621 value: value,
16622 source: source,
16623 stack: getStackByFiberInDevAndProd(source)
16624 };
16625}
16626
16627function markUpdate(workInProgress) {
16628 // Tag the fiber with an update effect. This turns a Placement into
16629 // a PlacementAndUpdate.
16630 workInProgress.effectTag |= Update;
16631}
16632
16633function markRef$1(workInProgress) {
16634 workInProgress.effectTag |= Ref;
16635}
16636
16637var appendAllChildren = void 0;
16638var updateHostContainer = void 0;
16639var updateHostComponent$1 = void 0;
16640var updateHostText$1 = void 0;
16641if (supportsMutation) {
16642 // Mutation mode
16643
16644 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
16645 // We only have the top Fiber that was created but we need recurse down its
16646 // children to find all the terminal nodes.
16647 var node = workInProgress.child;
16648 while (node !== null) {
16649 if (node.tag === HostComponent || node.tag === HostText) {
16650 appendInitialChild(parent, node.stateNode);
16651 } else if (node.tag === HostPortal) {
16652 // If we have a portal child, then we don't want to traverse
16653 // down its children. Instead, we'll get insertions from each child in
16654 // the portal directly.
16655 } else if (node.child !== null) {
16656 node.child.return = node;
16657 node = node.child;
16658 continue;
16659 }
16660 if (node === workInProgress) {
16661 return;
16662 }
16663 while (node.sibling === null) {
16664 if (node.return === null || node.return === workInProgress) {
16665 return;
16666 }
16667 node = node.return;
16668 }
16669 node.sibling.return = node.return;
16670 node = node.sibling;
16671 }
16672 };
16673
16674 updateHostContainer = function (workInProgress) {
16675 // Noop
16676 };
16677 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
16678 // If we have an alternate, that means this is an update and we need to
16679 // schedule a side-effect to do the updates.
16680 var oldProps = current.memoizedProps;
16681 if (oldProps === newProps) {
16682 // In mutation mode, this is sufficient for a bailout because
16683 // we won't touch this node even if children changed.
16684 return;
16685 }
16686
16687 // If we get updated because one of our children updated, we don't
16688 // have newProps so we'll have to reuse them.
16689 // TODO: Split the update API as separate for the props vs. children.
16690 // Even better would be if children weren't special cased at all tho.
16691 var instance = workInProgress.stateNode;
16692 var currentHostContext = getHostContext();
16693 // TODO: Experiencing an error where oldProps is null. Suggests a host
16694 // component is hitting the resume path. Figure out why. Possibly
16695 // related to `hidden`.
16696 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
16697 // TODO: Type this specific to this type of component.
16698 workInProgress.updateQueue = updatePayload;
16699 // If the update payload indicates that there is a change or if there
16700 // is a new ref we mark this as an update. All the work is done in commitWork.
16701 if (updatePayload) {
16702 markUpdate(workInProgress);
16703 }
16704 };
16705 updateHostText$1 = function (current, workInProgress, oldText, newText) {
16706 // If the text differs, mark it as an update. All the work in done in commitWork.
16707 if (oldText !== newText) {
16708 markUpdate(workInProgress);
16709 }
16710 };
16711} else if (supportsPersistence) {
16712 // Persistent host tree mode
16713
16714 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
16715 // We only have the top Fiber that was created but we need recurse down its
16716 // children to find all the terminal nodes.
16717 var node = workInProgress.child;
16718 while (node !== null) {
16719 // eslint-disable-next-line no-labels
16720 branches: if (node.tag === HostComponent) {
16721 var instance = node.stateNode;
16722 if (needsVisibilityToggle) {
16723 var props = node.memoizedProps;
16724 var type = node.type;
16725 if (isHidden) {
16726 // This child is inside a timed out tree. Hide it.
16727 instance = cloneHiddenInstance(instance, type, props, node);
16728 } else {
16729 // This child was previously inside a timed out tree. If it was not
16730 // updated during this render, it may need to be unhidden. Clone
16731 // again to be sure.
16732 instance = cloneUnhiddenInstance(instance, type, props, node);
16733 }
16734 node.stateNode = instance;
16735 }
16736 appendInitialChild(parent, instance);
16737 } else if (node.tag === HostText) {
16738 var _instance = node.stateNode;
16739 if (needsVisibilityToggle) {
16740 var text = node.memoizedProps;
16741 var rootContainerInstance = getRootHostContainer();
16742 var currentHostContext = getHostContext();
16743 if (isHidden) {
16744 _instance = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16745 } else {
16746 _instance = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16747 }
16748 node.stateNode = _instance;
16749 }
16750 appendInitialChild(parent, _instance);
16751 } else if (node.tag === HostPortal) {
16752 // If we have a portal child, then we don't want to traverse
16753 // down its children. Instead, we'll get insertions from each child in
16754 // the portal directly.
16755 } else if (node.tag === SuspenseComponent) {
16756 var current = node.alternate;
16757 if (current !== null) {
16758 var oldState = current.memoizedState;
16759 var newState = node.memoizedState;
16760 var oldIsHidden = oldState !== null;
16761 var newIsHidden = newState !== null;
16762 if (oldIsHidden !== newIsHidden) {
16763 // The placeholder either just timed out or switched back to the normal
16764 // children after having previously timed out. Toggle the visibility of
16765 // the direct host children.
16766 var primaryChildParent = newIsHidden ? node.child : node;
16767 if (primaryChildParent !== null) {
16768 appendAllChildren(parent, primaryChildParent, true, newIsHidden);
16769 }
16770 // eslint-disable-next-line no-labels
16771 break branches;
16772 }
16773 }
16774 if (node.child !== null) {
16775 // Continue traversing like normal
16776 node.child.return = node;
16777 node = node.child;
16778 continue;
16779 }
16780 } else if (node.child !== null) {
16781 node.child.return = node;
16782 node = node.child;
16783 continue;
16784 }
16785 // $FlowFixMe This is correct but Flow is confused by the labeled break.
16786 node = node;
16787 if (node === workInProgress) {
16788 return;
16789 }
16790 while (node.sibling === null) {
16791 if (node.return === null || node.return === workInProgress) {
16792 return;
16793 }
16794 node = node.return;
16795 }
16796 node.sibling.return = node.return;
16797 node = node.sibling;
16798 }
16799 };
16800
16801 // An unfortunate fork of appendAllChildren because we have two different parent types.
16802 var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
16803 // We only have the top Fiber that was created but we need recurse down its
16804 // children to find all the terminal nodes.
16805 var node = workInProgress.child;
16806 while (node !== null) {
16807 // eslint-disable-next-line no-labels
16808 branches: if (node.tag === HostComponent) {
16809 var instance = node.stateNode;
16810 if (needsVisibilityToggle) {
16811 var props = node.memoizedProps;
16812 var type = node.type;
16813 if (isHidden) {
16814 // This child is inside a timed out tree. Hide it.
16815 instance = cloneHiddenInstance(instance, type, props, node);
16816 } else {
16817 // This child was previously inside a timed out tree. If it was not
16818 // updated during this render, it may need to be unhidden. Clone
16819 // again to be sure.
16820 instance = cloneUnhiddenInstance(instance, type, props, node);
16821 }
16822 node.stateNode = instance;
16823 }
16824 appendChildToContainerChildSet(containerChildSet, instance);
16825 } else if (node.tag === HostText) {
16826 var _instance2 = node.stateNode;
16827 if (needsVisibilityToggle) {
16828 var text = node.memoizedProps;
16829 var rootContainerInstance = getRootHostContainer();
16830 var currentHostContext = getHostContext();
16831 if (isHidden) {
16832 _instance2 = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16833 } else {
16834 _instance2 = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16835 }
16836 node.stateNode = _instance2;
16837 }
16838 appendChildToContainerChildSet(containerChildSet, _instance2);
16839 } else if (node.tag === HostPortal) {
16840 // If we have a portal child, then we don't want to traverse
16841 // down its children. Instead, we'll get insertions from each child in
16842 // the portal directly.
16843 } else if (node.tag === SuspenseComponent) {
16844 var current = node.alternate;
16845 if (current !== null) {
16846 var oldState = current.memoizedState;
16847 var newState = node.memoizedState;
16848 var oldIsHidden = oldState !== null;
16849 var newIsHidden = newState !== null;
16850 if (oldIsHidden !== newIsHidden) {
16851 // The placeholder either just timed out or switched back to the normal
16852 // children after having previously timed out. Toggle the visibility of
16853 // the direct host children.
16854 var primaryChildParent = newIsHidden ? node.child : node;
16855 if (primaryChildParent !== null) {
16856 appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
16857 }
16858 // eslint-disable-next-line no-labels
16859 break branches;
16860 }
16861 }
16862 if (node.child !== null) {
16863 // Continue traversing like normal
16864 node.child.return = node;
16865 node = node.child;
16866 continue;
16867 }
16868 } else if (node.child !== null) {
16869 node.child.return = node;
16870 node = node.child;
16871 continue;
16872 }
16873 // $FlowFixMe This is correct but Flow is confused by the labeled break.
16874 node = node;
16875 if (node === workInProgress) {
16876 return;
16877 }
16878 while (node.sibling === null) {
16879 if (node.return === null || node.return === workInProgress) {
16880 return;
16881 }
16882 node = node.return;
16883 }
16884 node.sibling.return = node.return;
16885 node = node.sibling;
16886 }
16887 };
16888 updateHostContainer = function (workInProgress) {
16889 var portalOrRoot = workInProgress.stateNode;
16890 var childrenUnchanged = workInProgress.firstEffect === null;
16891 if (childrenUnchanged) {
16892 // No changes, just reuse the existing instance.
16893 } else {
16894 var container = portalOrRoot.containerInfo;
16895 var newChildSet = createContainerChildSet(container);
16896 // If children might have changed, we have to add them all to the set.
16897 appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
16898 portalOrRoot.pendingChildren = newChildSet;
16899 // Schedule an update on the container to swap out the container.
16900 markUpdate(workInProgress);
16901 finalizeContainerChildren(container, newChildSet);
16902 }
16903 };
16904 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
16905 var currentInstance = current.stateNode;
16906 var oldProps = current.memoizedProps;
16907 // If there are no effects associated with this node, then none of our children had any updates.
16908 // This guarantees that we can reuse all of them.
16909 var childrenUnchanged = workInProgress.firstEffect === null;
16910 if (childrenUnchanged && oldProps === newProps) {
16911 // No changes, just reuse the existing instance.
16912 // Note that this might release a previous clone.
16913 workInProgress.stateNode = currentInstance;
16914 return;
16915 }
16916 var recyclableInstance = workInProgress.stateNode;
16917 var currentHostContext = getHostContext();
16918 var updatePayload = null;
16919 if (oldProps !== newProps) {
16920 updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
16921 }
16922 if (childrenUnchanged && updatePayload === null) {
16923 // No changes, just reuse the existing instance.
16924 // Note that this might release a previous clone.
16925 workInProgress.stateNode = currentInstance;
16926 return;
16927 }
16928 var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
16929 if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
16930 markUpdate(workInProgress);
16931 }
16932 workInProgress.stateNode = newInstance;
16933 if (childrenUnchanged) {
16934 // If there are no other effects in this tree, we need to flag this node as having one.
16935 // Even though we're not going to use it for anything.
16936 // Otherwise parents won't know that there are new children to propagate upwards.
16937 markUpdate(workInProgress);
16938 } else {
16939 // If children might have changed, we have to add them all to the set.
16940 appendAllChildren(newInstance, workInProgress, false, false);
16941 }
16942 };
16943 updateHostText$1 = function (current, workInProgress, oldText, newText) {
16944 if (oldText !== newText) {
16945 // If the text content differs, we'll create a new text instance for it.
16946 var rootContainerInstance = getRootHostContainer();
16947 var currentHostContext = getHostContext();
16948 workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress);
16949 // We'll have to mark it as having an effect, even though we won't use the effect for anything.
16950 // This lets the parents know that at least one of their children has changed.
16951 markUpdate(workInProgress);
16952 }
16953 };
16954} else {
16955 // No host operations
16956 updateHostContainer = function (workInProgress) {
16957 // Noop
16958 };
16959 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
16960 // Noop
16961 };
16962 updateHostText$1 = function (current, workInProgress, oldText, newText) {
16963 // Noop
16964 };
16965}
16966
16967function completeWork(current, workInProgress, renderExpirationTime) {
16968 var newProps = workInProgress.pendingProps;
16969
16970 switch (workInProgress.tag) {
16971 case IndeterminateComponent:
16972 break;
16973 case LazyComponent:
16974 break;
16975 case SimpleMemoComponent:
16976 case FunctionComponent:
16977 break;
16978 case ClassComponent:
16979 {
16980 var Component = workInProgress.type;
16981 if (isContextProvider(Component)) {
16982 popContext(workInProgress);
16983 }
16984 break;
16985 }
16986 case HostRoot:
16987 {
16988 popHostContainer(workInProgress);
16989 popTopLevelContextObject(workInProgress);
16990 var fiberRoot = workInProgress.stateNode;
16991 if (fiberRoot.pendingContext) {
16992 fiberRoot.context = fiberRoot.pendingContext;
16993 fiberRoot.pendingContext = null;
16994 }
16995 if (current === null || current.child === null) {
16996 // If we hydrated, pop so that we can delete any remaining children
16997 // that weren't hydrated.
16998 popHydrationState(workInProgress);
16999 // This resets the hacky state to fix isMounted before committing.
17000 // TODO: Delete this when we delete isMounted and findDOMNode.
17001 workInProgress.effectTag &= ~Placement;
17002 }
17003 updateHostContainer(workInProgress);
17004 break;
17005 }
17006 case HostComponent:
17007 {
17008 popHostContext(workInProgress);
17009 var rootContainerInstance = getRootHostContainer();
17010 var type = workInProgress.type;
17011 if (current !== null && workInProgress.stateNode != null) {
17012 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
17013
17014 if (current.ref !== workInProgress.ref) {
17015 markRef$1(workInProgress);
17016 }
17017 } else {
17018 if (!newProps) {
17019 !(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;
17020 // This can happen when we abort work.
17021 break;
17022 }
17023
17024 var currentHostContext = getHostContext();
17025 // TODO: Move createInstance to beginWork and keep it on a context
17026 // "stack" as the parent. Then append children as we go in beginWork
17027 // or completeWork depending on we want to add then top->down or
17028 // bottom->up. Top->down is faster in IE11.
17029 var wasHydrated = popHydrationState(workInProgress);
17030 if (wasHydrated) {
17031 // TODO: Move this and createInstance step into the beginPhase
17032 // to consolidate.
17033 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
17034 // If changes to the hydrated node needs to be applied at the
17035 // commit-phase we mark this as such.
17036 markUpdate(workInProgress);
17037 }
17038 } else {
17039 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
17040
17041 appendAllChildren(instance, workInProgress, false, false);
17042
17043 // Certain renderers require commit-time effects for initial mount.
17044 // (eg DOM renderer supports auto-focus for certain elements).
17045 // Make sure such renderers get scheduled for later work.
17046 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
17047 markUpdate(workInProgress);
17048 }
17049 workInProgress.stateNode = instance;
17050 }
17051
17052 if (workInProgress.ref !== null) {
17053 // If there is a ref on a host node we need to schedule a callback
17054 markRef$1(workInProgress);
17055 }
17056 }
17057 break;
17058 }
17059 case HostText:
17060 {
17061 var newText = newProps;
17062 if (current && workInProgress.stateNode != null) {
17063 var oldText = current.memoizedProps;
17064 // If we have an alternate, that means this is an update and we need
17065 // to schedule a side-effect to do the updates.
17066 updateHostText$1(current, workInProgress, oldText, newText);
17067 } else {
17068 if (typeof newText !== 'string') {
17069 !(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;
17070 // This can happen when we abort work.
17071 }
17072 var _rootContainerInstance = getRootHostContainer();
17073 var _currentHostContext = getHostContext();
17074 var _wasHydrated = popHydrationState(workInProgress);
17075 if (_wasHydrated) {
17076 if (prepareToHydrateHostTextInstance(workInProgress)) {
17077 markUpdate(workInProgress);
17078 }
17079 } else {
17080 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
17081 }
17082 }
17083 break;
17084 }
17085 case ForwardRef:
17086 break;
17087 case SuspenseComponent:
17088 {
17089 var nextState = workInProgress.memoizedState;
17090 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
17091 // Something suspended. Re-render with the fallback children.
17092 workInProgress.expirationTime = renderExpirationTime;
17093 // Do not reset the effect list.
17094 return workInProgress;
17095 }
17096
17097 var nextDidTimeout = nextState !== null;
17098 var prevDidTimeout = current !== null && current.memoizedState !== null;
17099
17100 if (current !== null && !nextDidTimeout && prevDidTimeout) {
17101 // We just switched from the fallback to the normal children. Delete
17102 // the fallback.
17103 // TODO: Would it be better to store the fallback fragment on
17104 var currentFallbackChild = current.child.sibling;
17105 if (currentFallbackChild !== null) {
17106 // Deletions go at the beginning of the return fiber's effect list
17107 var first = workInProgress.firstEffect;
17108 if (first !== null) {
17109 workInProgress.firstEffect = currentFallbackChild;
17110 currentFallbackChild.nextEffect = first;
17111 } else {
17112 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
17113 currentFallbackChild.nextEffect = null;
17114 }
17115 currentFallbackChild.effectTag = Deletion;
17116 }
17117 }
17118
17119 if (nextDidTimeout || prevDidTimeout) {
17120 // If the children are hidden, or if they were previous hidden, schedule
17121 // an effect to toggle their visibility. This is also used to attach a
17122 // retry listener to the promise.
17123 workInProgress.effectTag |= Update;
17124 }
17125 break;
17126 }
17127 case Fragment:
17128 break;
17129 case Mode:
17130 break;
17131 case Profiler:
17132 break;
17133 case HostPortal:
17134 popHostContainer(workInProgress);
17135 updateHostContainer(workInProgress);
17136 break;
17137 case ContextProvider:
17138 // Pop provider fiber
17139 popProvider(workInProgress);
17140 break;
17141 case ContextConsumer:
17142 break;
17143 case MemoComponent:
17144 break;
17145 case IncompleteClassComponent:
17146 {
17147 // Same as class component case. I put it down here so that the tags are
17148 // sequential to ensure this switch is compiled to a jump table.
17149 var _Component = workInProgress.type;
17150 if (isContextProvider(_Component)) {
17151 popContext(workInProgress);
17152 }
17153 break;
17154 }
17155 case DehydratedSuspenseComponent:
17156 {
17157 if (enableSuspenseServerRenderer) {
17158 if (current === null) {
17159 var _wasHydrated2 = popHydrationState(workInProgress);
17160 !_wasHydrated2 ? invariant(false, 'A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React.') : void 0;
17161 skipPastDehydratedSuspenseInstance(workInProgress);
17162 } else if ((workInProgress.effectTag & DidCapture) === NoEffect) {
17163 // This boundary did not suspend so it's now hydrated.
17164 // To handle any future suspense cases, we're going to now upgrade it
17165 // to a Suspense component. We detach it from the existing current fiber.
17166 current.alternate = null;
17167 workInProgress.alternate = null;
17168 workInProgress.tag = SuspenseComponent;
17169 workInProgress.memoizedState = null;
17170 workInProgress.stateNode = null;
17171 }
17172 }
17173 break;
17174 }
17175 default:
17176 invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
17177 }
17178
17179 return null;
17180}
17181
17182function shouldCaptureSuspense(workInProgress) {
17183 // In order to capture, the Suspense component must have a fallback prop.
17184 if (workInProgress.memoizedProps.fallback === undefined) {
17185 return false;
17186 }
17187 // If it was the primary children that just suspended, capture and render the
17188 // fallback. Otherwise, don't capture and bubble to the next boundary.
17189 var nextState = workInProgress.memoizedState;
17190 return nextState === null;
17191}
17192
17193// This module is forked in different environments.
17194// By default, return `true` to log errors to the console.
17195// Forks can return `false` if this isn't desirable.
17196function showErrorDialog(capturedError) {
17197 return true;
17198}
17199
17200function logCapturedError(capturedError) {
17201 var logError = showErrorDialog(capturedError);
17202
17203 // Allow injected showErrorDialog() to prevent default console.error logging.
17204 // This enables renderers like ReactNative to better manage redbox behavior.
17205 if (logError === false) {
17206 return;
17207 }
17208
17209 var error = capturedError.error;
17210 {
17211 var componentName = capturedError.componentName,
17212 componentStack = capturedError.componentStack,
17213 errorBoundaryName = capturedError.errorBoundaryName,
17214 errorBoundaryFound = capturedError.errorBoundaryFound,
17215 willRetry = capturedError.willRetry;
17216
17217 // Browsers support silencing uncaught errors by calling
17218 // `preventDefault()` in window `error` handler.
17219 // We record this information as an expando on the error.
17220
17221 if (error != null && error._suppressLogging) {
17222 if (errorBoundaryFound && willRetry) {
17223 // The error is recoverable and was silenced.
17224 // Ignore it and don't print the stack addendum.
17225 // This is handy for testing error boundaries without noise.
17226 return;
17227 }
17228 // The error is fatal. Since the silencing might have
17229 // been accidental, we'll surface it anyway.
17230 // However, the browser would have silenced the original error
17231 // so we'll print it first, and then print the stack addendum.
17232 console.error(error);
17233 // For a more detailed description of this block, see:
17234 // https://github.com/facebook/react/pull/13384
17235 }
17236
17237 var componentNameMessage = componentName ? 'The above error occurred in the <' + componentName + '> component:' : 'The above error occurred in one of your React components:';
17238
17239 var errorBoundaryMessage = void 0;
17240 // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
17241 if (errorBoundaryFound && errorBoundaryName) {
17242 if (willRetry) {
17243 errorBoundaryMessage = 'React will try to recreate this component tree from scratch ' + ('using the error boundary you provided, ' + errorBoundaryName + '.');
17244 } else {
17245 errorBoundaryMessage = 'This error was initially handled by the error boundary ' + errorBoundaryName + '.\n' + 'Recreating the tree from scratch failed so React will unmount the tree.';
17246 }
17247 } else {
17248 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.';
17249 }
17250 var combinedMessage = '' + componentNameMessage + componentStack + '\n\n' + ('' + errorBoundaryMessage);
17251
17252 // In development, we provide our own message with just the component stack.
17253 // We don't include the original error message and JS stack because the browser
17254 // has already printed it. Even if the application swallows the error, it is still
17255 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
17256 console.error(combinedMessage);
17257 }
17258}
17259
17260var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
17261{
17262 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
17263}
17264
17265var PossiblyWeakSet$1 = typeof WeakSet === 'function' ? WeakSet : Set;
17266
17267function logError(boundary, errorInfo) {
17268 var source = errorInfo.source;
17269 var stack = errorInfo.stack;
17270 if (stack === null && source !== null) {
17271 stack = getStackByFiberInDevAndProd(source);
17272 }
17273
17274 var capturedError = {
17275 componentName: source !== null ? getComponentName(source.type) : null,
17276 componentStack: stack !== null ? stack : '',
17277 error: errorInfo.value,
17278 errorBoundary: null,
17279 errorBoundaryName: null,
17280 errorBoundaryFound: false,
17281 willRetry: false
17282 };
17283
17284 if (boundary !== null && boundary.tag === ClassComponent) {
17285 capturedError.errorBoundary = boundary.stateNode;
17286 capturedError.errorBoundaryName = getComponentName(boundary.type);
17287 capturedError.errorBoundaryFound = true;
17288 capturedError.willRetry = true;
17289 }
17290
17291 try {
17292 logCapturedError(capturedError);
17293 } catch (e) {
17294 // This method must not throw, or React internal state will get messed up.
17295 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
17296 // we want to report this error outside of the normal stack as a last resort.
17297 // https://github.com/facebook/react/issues/13188
17298 setTimeout(function () {
17299 throw e;
17300 });
17301 }
17302}
17303
17304var callComponentWillUnmountWithTimer = function (current$$1, instance) {
17305 startPhaseTimer(current$$1, 'componentWillUnmount');
17306 instance.props = current$$1.memoizedProps;
17307 instance.state = current$$1.memoizedState;
17308 instance.componentWillUnmount();
17309 stopPhaseTimer();
17310};
17311
17312// Capture errors so they don't interrupt unmounting.
17313function safelyCallComponentWillUnmount(current$$1, instance) {
17314 {
17315 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
17316 if (hasCaughtError()) {
17317 var unmountError = clearCaughtError();
17318 captureCommitPhaseError(current$$1, unmountError);
17319 }
17320 }
17321}
17322
17323function safelyDetachRef(current$$1) {
17324 var ref = current$$1.ref;
17325 if (ref !== null) {
17326 if (typeof ref === 'function') {
17327 {
17328 invokeGuardedCallback(null, ref, null, null);
17329 if (hasCaughtError()) {
17330 var refError = clearCaughtError();
17331 captureCommitPhaseError(current$$1, refError);
17332 }
17333 }
17334 } else {
17335 ref.current = null;
17336 }
17337 }
17338}
17339
17340function safelyCallDestroy(current$$1, destroy) {
17341 {
17342 invokeGuardedCallback(null, destroy, null);
17343 if (hasCaughtError()) {
17344 var error = clearCaughtError();
17345 captureCommitPhaseError(current$$1, error);
17346 }
17347 }
17348}
17349
17350function commitBeforeMutationLifeCycles(current$$1, finishedWork) {
17351 switch (finishedWork.tag) {
17352 case FunctionComponent:
17353 case ForwardRef:
17354 case SimpleMemoComponent:
17355 {
17356 commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
17357 return;
17358 }
17359 case ClassComponent:
17360 {
17361 if (finishedWork.effectTag & Snapshot) {
17362 if (current$$1 !== null) {
17363 var prevProps = current$$1.memoizedProps;
17364 var prevState = current$$1.memoizedState;
17365 startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
17366 var instance = finishedWork.stateNode;
17367 // We could update instance props and state here,
17368 // but instead we rely on them being set during last render.
17369 // TODO: revisit this when we implement resuming.
17370 {
17371 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
17372 !(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;
17373 !(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;
17374 }
17375 }
17376 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
17377 {
17378 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
17379 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
17380 didWarnSet.add(finishedWork.type);
17381 warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
17382 }
17383 }
17384 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
17385 stopPhaseTimer();
17386 }
17387 }
17388 return;
17389 }
17390 case HostRoot:
17391 case HostComponent:
17392 case HostText:
17393 case HostPortal:
17394 case IncompleteClassComponent:
17395 // Nothing to do for these component types
17396 return;
17397 default:
17398 {
17399 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.');
17400 }
17401 }
17402}
17403
17404function commitHookEffectList(unmountTag, mountTag, finishedWork) {
17405 var updateQueue = finishedWork.updateQueue;
17406 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
17407 if (lastEffect !== null) {
17408 var firstEffect = lastEffect.next;
17409 var effect = firstEffect;
17410 do {
17411 if ((effect.tag & unmountTag) !== NoEffect$1) {
17412 // Unmount
17413 var destroy = effect.destroy;
17414 effect.destroy = undefined;
17415 if (destroy !== undefined) {
17416 destroy();
17417 }
17418 }
17419 if ((effect.tag & mountTag) !== NoEffect$1) {
17420 // Mount
17421 var create = effect.create;
17422 effect.destroy = create();
17423
17424 {
17425 var _destroy = effect.destroy;
17426 if (_destroy !== undefined && typeof _destroy !== 'function') {
17427 var addendum = void 0;
17428 if (_destroy === null) {
17429 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
17430 } else if (typeof _destroy.then === 'function') {
17431 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';
17432 } else {
17433 addendum = ' You returned: ' + _destroy;
17434 }
17435 warningWithoutStack$1(false, 'An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
17436 }
17437 }
17438 }
17439 effect = effect.next;
17440 } while (effect !== firstEffect);
17441 }
17442}
17443
17444function commitPassiveHookEffects(finishedWork) {
17445 commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
17446 commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
17447}
17448
17449function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) {
17450 switch (finishedWork.tag) {
17451 case FunctionComponent:
17452 case ForwardRef:
17453 case SimpleMemoComponent:
17454 {
17455 commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
17456 break;
17457 }
17458 case ClassComponent:
17459 {
17460 var instance = finishedWork.stateNode;
17461 if (finishedWork.effectTag & Update) {
17462 if (current$$1 === null) {
17463 startPhaseTimer(finishedWork, 'componentDidMount');
17464 // We could update instance props and state here,
17465 // but instead we rely on them being set during last render.
17466 // TODO: revisit this when we implement resuming.
17467 {
17468 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
17469 !(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;
17470 !(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;
17471 }
17472 }
17473 instance.componentDidMount();
17474 stopPhaseTimer();
17475 } else {
17476 var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);
17477 var prevState = current$$1.memoizedState;
17478 startPhaseTimer(finishedWork, 'componentDidUpdate');
17479 // We could update instance props and state here,
17480 // but instead we rely on them being set during last render.
17481 // TODO: revisit this when we implement resuming.
17482 {
17483 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
17484 !(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;
17485 !(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;
17486 }
17487 }
17488 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
17489 stopPhaseTimer();
17490 }
17491 }
17492 var updateQueue = finishedWork.updateQueue;
17493 if (updateQueue !== null) {
17494 {
17495 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
17496 !(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;
17497 !(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;
17498 }
17499 }
17500 // We could update instance props and state here,
17501 // but instead we rely on them being set during last render.
17502 // TODO: revisit this when we implement resuming.
17503 commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
17504 }
17505 return;
17506 }
17507 case HostRoot:
17508 {
17509 var _updateQueue = finishedWork.updateQueue;
17510 if (_updateQueue !== null) {
17511 var _instance = null;
17512 if (finishedWork.child !== null) {
17513 switch (finishedWork.child.tag) {
17514 case HostComponent:
17515 _instance = getPublicInstance(finishedWork.child.stateNode);
17516 break;
17517 case ClassComponent:
17518 _instance = finishedWork.child.stateNode;
17519 break;
17520 }
17521 }
17522 commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
17523 }
17524 return;
17525 }
17526 case HostComponent:
17527 {
17528 var _instance2 = finishedWork.stateNode;
17529
17530 // Renderers may schedule work to be done after host components are mounted
17531 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
17532 // These effects should only be committed when components are first mounted,
17533 // aka when there is no current/alternate.
17534 if (current$$1 === null && finishedWork.effectTag & Update) {
17535 var type = finishedWork.type;
17536 var props = finishedWork.memoizedProps;
17537 commitMount(_instance2, type, props, finishedWork);
17538 }
17539
17540 return;
17541 }
17542 case HostText:
17543 {
17544 // We have no life-cycles associated with text.
17545 return;
17546 }
17547 case HostPortal:
17548 {
17549 // We have no life-cycles associated with portals.
17550 return;
17551 }
17552 case Profiler:
17553 {
17554 if (enableProfilerTimer) {
17555 var onRender = finishedWork.memoizedProps.onRender;
17556
17557 if (enableSchedulerTracing) {
17558 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
17559 } else {
17560 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
17561 }
17562 }
17563 return;
17564 }
17565 case SuspenseComponent:
17566 break;
17567 case IncompleteClassComponent:
17568 break;
17569 default:
17570 {
17571 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.');
17572 }
17573 }
17574}
17575
17576function hideOrUnhideAllChildren(finishedWork, isHidden) {
17577 if (supportsMutation) {
17578 // We only have the top Fiber that was inserted but we need to recurse down its
17579 var node = finishedWork;
17580 while (true) {
17581 if (node.tag === HostComponent) {
17582 var instance = node.stateNode;
17583 if (isHidden) {
17584 hideInstance(instance);
17585 } else {
17586 unhideInstance(node.stateNode, node.memoizedProps);
17587 }
17588 } else if (node.tag === HostText) {
17589 var _instance3 = node.stateNode;
17590 if (isHidden) {
17591 hideTextInstance(_instance3);
17592 } else {
17593 unhideTextInstance(_instance3, node.memoizedProps);
17594 }
17595 } else if (node.tag === SuspenseComponent && node.memoizedState !== null) {
17596 // Found a nested Suspense component that timed out. Skip over the
17597 var fallbackChildFragment = node.child.sibling;
17598 fallbackChildFragment.return = node;
17599 node = fallbackChildFragment;
17600 continue;
17601 } else if (node.child !== null) {
17602 node.child.return = node;
17603 node = node.child;
17604 continue;
17605 }
17606 if (node === finishedWork) {
17607 return;
17608 }
17609 while (node.sibling === null) {
17610 if (node.return === null || node.return === finishedWork) {
17611 return;
17612 }
17613 node = node.return;
17614 }
17615 node.sibling.return = node.return;
17616 node = node.sibling;
17617 }
17618 }
17619}
17620
17621function commitAttachRef(finishedWork) {
17622 var ref = finishedWork.ref;
17623 if (ref !== null) {
17624 var instance = finishedWork.stateNode;
17625 var instanceToUse = void 0;
17626 switch (finishedWork.tag) {
17627 case HostComponent:
17628 instanceToUse = getPublicInstance(instance);
17629 break;
17630 default:
17631 instanceToUse = instance;
17632 }
17633 if (typeof ref === 'function') {
17634 ref(instanceToUse);
17635 } else {
17636 {
17637 if (!ref.hasOwnProperty('current')) {
17638 warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
17639 }
17640 }
17641
17642 ref.current = instanceToUse;
17643 }
17644 }
17645}
17646
17647function commitDetachRef(current$$1) {
17648 var currentRef = current$$1.ref;
17649 if (currentRef !== null) {
17650 if (typeof currentRef === 'function') {
17651 currentRef(null);
17652 } else {
17653 currentRef.current = null;
17654 }
17655 }
17656}
17657
17658// User-originating errors (lifecycles and refs) should not interrupt
17659// deletion, so don't let them throw. Host-originating errors should
17660// interrupt deletion, so it's okay
17661function commitUnmount(current$$1) {
17662 onCommitUnmount(current$$1);
17663
17664 switch (current$$1.tag) {
17665 case FunctionComponent:
17666 case ForwardRef:
17667 case MemoComponent:
17668 case SimpleMemoComponent:
17669 {
17670 var updateQueue = current$$1.updateQueue;
17671 if (updateQueue !== null) {
17672 var lastEffect = updateQueue.lastEffect;
17673 if (lastEffect !== null) {
17674 var firstEffect = lastEffect.next;
17675 var effect = firstEffect;
17676 do {
17677 var destroy = effect.destroy;
17678 if (destroy !== undefined) {
17679 safelyCallDestroy(current$$1, destroy);
17680 }
17681 effect = effect.next;
17682 } while (effect !== firstEffect);
17683 }
17684 }
17685 break;
17686 }
17687 case ClassComponent:
17688 {
17689 safelyDetachRef(current$$1);
17690 var instance = current$$1.stateNode;
17691 if (typeof instance.componentWillUnmount === 'function') {
17692 safelyCallComponentWillUnmount(current$$1, instance);
17693 }
17694 return;
17695 }
17696 case HostComponent:
17697 {
17698 safelyDetachRef(current$$1);
17699 return;
17700 }
17701 case HostPortal:
17702 {
17703 // TODO: this is recursive.
17704 // We are also not using this parent because
17705 // the portal will get pushed immediately.
17706 if (supportsMutation) {
17707 unmountHostComponents(current$$1);
17708 } else if (supportsPersistence) {
17709 emptyPortalContainer(current$$1);
17710 }
17711 return;
17712 }
17713 }
17714}
17715
17716function commitNestedUnmounts(root) {
17717 // While we're inside a removed host node we don't want to call
17718 // removeChild on the inner nodes because they're removed by the top
17719 // call anyway. We also want to call componentWillUnmount on all
17720 // composites before this host node is removed from the tree. Therefore
17721 var node = root;
17722 while (true) {
17723 commitUnmount(node);
17724 // Visit children because they may contain more composite or host nodes.
17725 // Skip portals because commitUnmount() currently visits them recursively.
17726 if (node.child !== null && (
17727 // If we use mutation we drill down into portals using commitUnmount above.
17728 // If we don't use mutation we drill down into portals here instead.
17729 !supportsMutation || node.tag !== HostPortal)) {
17730 node.child.return = node;
17731 node = node.child;
17732 continue;
17733 }
17734 if (node === root) {
17735 return;
17736 }
17737 while (node.sibling === null) {
17738 if (node.return === null || node.return === root) {
17739 return;
17740 }
17741 node = node.return;
17742 }
17743 node.sibling.return = node.return;
17744 node = node.sibling;
17745 }
17746}
17747
17748function detachFiber(current$$1) {
17749 // Cut off the return pointers to disconnect it from the tree. Ideally, we
17750 // should clear the child pointer of the parent alternate to let this
17751 // get GC:ed but we don't know which for sure which parent is the current
17752 // one so we'll settle for GC:ing the subtree of this child. This child
17753 // itself will be GC:ed when the parent updates the next time.
17754 current$$1.return = null;
17755 current$$1.child = null;
17756 current$$1.memoizedState = null;
17757 current$$1.updateQueue = null;
17758 var alternate = current$$1.alternate;
17759 if (alternate !== null) {
17760 alternate.return = null;
17761 alternate.child = null;
17762 alternate.memoizedState = null;
17763 alternate.updateQueue = null;
17764 }
17765}
17766
17767function emptyPortalContainer(current$$1) {
17768 if (!supportsPersistence) {
17769 return;
17770 }
17771
17772 var portal = current$$1.stateNode;
17773 var containerInfo = portal.containerInfo;
17774
17775 var emptyChildSet = createContainerChildSet(containerInfo);
17776 replaceContainerChildren(containerInfo, emptyChildSet);
17777}
17778
17779function commitContainer(finishedWork) {
17780 if (!supportsPersistence) {
17781 return;
17782 }
17783
17784 switch (finishedWork.tag) {
17785 case ClassComponent:
17786 {
17787 return;
17788 }
17789 case HostComponent:
17790 {
17791 return;
17792 }
17793 case HostText:
17794 {
17795 return;
17796 }
17797 case HostRoot:
17798 case HostPortal:
17799 {
17800 var portalOrRoot = finishedWork.stateNode;
17801 var containerInfo = portalOrRoot.containerInfo,
17802 _pendingChildren = portalOrRoot.pendingChildren;
17803
17804 replaceContainerChildren(containerInfo, _pendingChildren);
17805 return;
17806 }
17807 default:
17808 {
17809 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.');
17810 }
17811 }
17812}
17813
17814function getHostParentFiber(fiber) {
17815 var parent = fiber.return;
17816 while (parent !== null) {
17817 if (isHostParent(parent)) {
17818 return parent;
17819 }
17820 parent = parent.return;
17821 }
17822 invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.');
17823}
17824
17825function isHostParent(fiber) {
17826 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
17827}
17828
17829function getHostSibling(fiber) {
17830 // We're going to search forward into the tree until we find a sibling host
17831 // node. Unfortunately, if multiple insertions are done in a row we have to
17832 // search past them. This leads to exponential search for the next sibling.
17833 var node = fiber;
17834 siblings: while (true) {
17835 // If we didn't find anything, let's try the next sibling.
17836 while (node.sibling === null) {
17837 if (node.return === null || isHostParent(node.return)) {
17838 // If we pop out of the root or hit the parent the fiber we are the
17839 // last sibling.
17840 return null;
17841 }
17842 node = node.return;
17843 }
17844 node.sibling.return = node.return;
17845 node = node.sibling;
17846 while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedSuspenseComponent) {
17847 // If it is not host node and, we might have a host node inside it.
17848 // Try to search down until we find one.
17849 if (node.effectTag & Placement) {
17850 // If we don't have a child, try the siblings instead.
17851 continue siblings;
17852 }
17853 // If we don't have a child, try the siblings instead.
17854 // We also skip portals because they are not part of this host tree.
17855 if (node.child === null || node.tag === HostPortal) {
17856 continue siblings;
17857 } else {
17858 node.child.return = node;
17859 node = node.child;
17860 }
17861 }
17862 // Check if this host node is stable or about to be placed.
17863 if (!(node.effectTag & Placement)) {
17864 // Found it!
17865 return node.stateNode;
17866 }
17867 }
17868}
17869
17870function commitPlacement(finishedWork) {
17871 if (!supportsMutation) {
17872 return;
17873 }
17874
17875 // Recursively insert all host nodes into the parent.
17876 var parentFiber = getHostParentFiber(finishedWork);
17877
17878 // Note: these two variables *must* always be updated together.
17879 var parent = void 0;
17880 var isContainer = void 0;
17881
17882 switch (parentFiber.tag) {
17883 case HostComponent:
17884 parent = parentFiber.stateNode;
17885 isContainer = false;
17886 break;
17887 case HostRoot:
17888 parent = parentFiber.stateNode.containerInfo;
17889 isContainer = true;
17890 break;
17891 case HostPortal:
17892 parent = parentFiber.stateNode.containerInfo;
17893 isContainer = true;
17894 break;
17895 default:
17896 invariant(false, 'Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.');
17897 }
17898 if (parentFiber.effectTag & ContentReset) {
17899 // Reset the text content of the parent before doing any insertions
17900 resetTextContent(parent);
17901 // Clear ContentReset from the effect tag
17902 parentFiber.effectTag &= ~ContentReset;
17903 }
17904
17905 var before = getHostSibling(finishedWork);
17906 // We only have the top Fiber that was inserted but we need to recurse down its
17907 // children to find all the terminal nodes.
17908 var node = finishedWork;
17909 while (true) {
17910 if (node.tag === HostComponent || node.tag === HostText) {
17911 if (before) {
17912 if (isContainer) {
17913 insertInContainerBefore(parent, node.stateNode, before);
17914 } else {
17915 insertBefore(parent, node.stateNode, before);
17916 }
17917 } else {
17918 if (isContainer) {
17919 appendChildToContainer(parent, node.stateNode);
17920 } else {
17921 appendChild(parent, node.stateNode);
17922 }
17923 }
17924 } else if (node.tag === HostPortal) {
17925 // If the insertion itself is a portal, then we don't want to traverse
17926 // down its children. Instead, we'll get insertions from each child in
17927 // the portal directly.
17928 } else if (node.child !== null) {
17929 node.child.return = node;
17930 node = node.child;
17931 continue;
17932 }
17933 if (node === finishedWork) {
17934 return;
17935 }
17936 while (node.sibling === null) {
17937 if (node.return === null || node.return === finishedWork) {
17938 return;
17939 }
17940 node = node.return;
17941 }
17942 node.sibling.return = node.return;
17943 node = node.sibling;
17944 }
17945}
17946
17947function unmountHostComponents(current$$1) {
17948 // We only have the top Fiber that was deleted but we need to recurse down its
17949 var node = current$$1;
17950
17951 // Each iteration, currentParent is populated with node's host parent if not
17952 // currentParentIsValid.
17953 var currentParentIsValid = false;
17954
17955 // Note: these two variables *must* always be updated together.
17956 var currentParent = void 0;
17957 var currentParentIsContainer = void 0;
17958
17959 while (true) {
17960 if (!currentParentIsValid) {
17961 var parent = node.return;
17962 findParent: while (true) {
17963 !(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;
17964 switch (parent.tag) {
17965 case HostComponent:
17966 currentParent = parent.stateNode;
17967 currentParentIsContainer = false;
17968 break findParent;
17969 case HostRoot:
17970 currentParent = parent.stateNode.containerInfo;
17971 currentParentIsContainer = true;
17972 break findParent;
17973 case HostPortal:
17974 currentParent = parent.stateNode.containerInfo;
17975 currentParentIsContainer = true;
17976 break findParent;
17977 }
17978 parent = parent.return;
17979 }
17980 currentParentIsValid = true;
17981 }
17982
17983 if (node.tag === HostComponent || node.tag === HostText) {
17984 commitNestedUnmounts(node);
17985 // After all the children have unmounted, it is now safe to remove the
17986 // node from the tree.
17987 if (currentParentIsContainer) {
17988 removeChildFromContainer(currentParent, node.stateNode);
17989 } else {
17990 removeChild(currentParent, node.stateNode);
17991 }
17992 // Don't visit children because we already visited them.
17993 } else if (enableSuspenseServerRenderer && node.tag === DehydratedSuspenseComponent) {
17994 // Delete the dehydrated suspense boundary and all of its content.
17995 if (currentParentIsContainer) {
17996 clearSuspenseBoundaryFromContainer(currentParent, node.stateNode);
17997 } else {
17998 clearSuspenseBoundary(currentParent, node.stateNode);
17999 }
18000 } else if (node.tag === HostPortal) {
18001 if (node.child !== null) {
18002 // When we go into a portal, it becomes the parent to remove from.
18003 // We will reassign it back when we pop the portal on the way up.
18004 currentParent = node.stateNode.containerInfo;
18005 currentParentIsContainer = true;
18006 // Visit children because portals might contain host components.
18007 node.child.return = node;
18008 node = node.child;
18009 continue;
18010 }
18011 } else {
18012 commitUnmount(node);
18013 // Visit children because we may find more host components below.
18014 if (node.child !== null) {
18015 node.child.return = node;
18016 node = node.child;
18017 continue;
18018 }
18019 }
18020 if (node === current$$1) {
18021 return;
18022 }
18023 while (node.sibling === null) {
18024 if (node.return === null || node.return === current$$1) {
18025 return;
18026 }
18027 node = node.return;
18028 if (node.tag === HostPortal) {
18029 // When we go out of the portal, we need to restore the parent.
18030 // Since we don't keep a stack of them, we will search for it.
18031 currentParentIsValid = false;
18032 }
18033 }
18034 node.sibling.return = node.return;
18035 node = node.sibling;
18036 }
18037}
18038
18039function commitDeletion(current$$1) {
18040 if (supportsMutation) {
18041 // Recursively delete all host nodes from the parent.
18042 // Detach refs and call componentWillUnmount() on the whole subtree.
18043 unmountHostComponents(current$$1);
18044 } else {
18045 // Detach refs and call componentWillUnmount() on the whole subtree.
18046 commitNestedUnmounts(current$$1);
18047 }
18048 detachFiber(current$$1);
18049}
18050
18051function commitWork(current$$1, finishedWork) {
18052 if (!supportsMutation) {
18053 switch (finishedWork.tag) {
18054 case FunctionComponent:
18055 case ForwardRef:
18056 case MemoComponent:
18057 case SimpleMemoComponent:
18058 {
18059 // Note: We currently never use MountMutation, but useLayout uses
18060 // UnmountMutation.
18061 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
18062 return;
18063 }
18064 }
18065
18066 commitContainer(finishedWork);
18067 return;
18068 }
18069
18070 switch (finishedWork.tag) {
18071 case FunctionComponent:
18072 case ForwardRef:
18073 case MemoComponent:
18074 case SimpleMemoComponent:
18075 {
18076 // Note: We currently never use MountMutation, but useLayout uses
18077 // UnmountMutation.
18078 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
18079 return;
18080 }
18081 case ClassComponent:
18082 {
18083 return;
18084 }
18085 case HostComponent:
18086 {
18087 var instance = finishedWork.stateNode;
18088 if (instance != null) {
18089 // Commit the work prepared earlier.
18090 var newProps = finishedWork.memoizedProps;
18091 // For hydration we reuse the update path but we treat the oldProps
18092 // as the newProps. The updatePayload will contain the real change in
18093 // this case.
18094 var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps;
18095 var type = finishedWork.type;
18096 // TODO: Type the updateQueue to be specific to host components.
18097 var updatePayload = finishedWork.updateQueue;
18098 finishedWork.updateQueue = null;
18099 if (updatePayload !== null) {
18100 commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
18101 }
18102 }
18103 return;
18104 }
18105 case HostText:
18106 {
18107 !(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;
18108 var textInstance = finishedWork.stateNode;
18109 var newText = finishedWork.memoizedProps;
18110 // For hydration we reuse the update path but we treat the oldProps
18111 // as the newProps. The updatePayload will contain the real change in
18112 // this case.
18113 var oldText = current$$1 !== null ? current$$1.memoizedProps : newText;
18114 commitTextUpdate(textInstance, oldText, newText);
18115 return;
18116 }
18117 case HostRoot:
18118 {
18119 return;
18120 }
18121 case Profiler:
18122 {
18123 return;
18124 }
18125 case SuspenseComponent:
18126 {
18127 var newState = finishedWork.memoizedState;
18128
18129 var newDidTimeout = void 0;
18130 var primaryChildParent = finishedWork;
18131 if (newState === null) {
18132 newDidTimeout = false;
18133 } else {
18134 newDidTimeout = true;
18135 primaryChildParent = finishedWork.child;
18136 if (newState.timedOutAt === NoWork) {
18137 // If the children had not already timed out, record the time.
18138 // This is used to compute the elapsed time during subsequent
18139 // attempts to render the children.
18140 newState.timedOutAt = requestCurrentTime();
18141 }
18142 }
18143
18144 if (primaryChildParent !== null) {
18145 hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
18146 }
18147
18148 // If this boundary just timed out, then it will have a set of thenables.
18149 // For each thenable, attach a listener so that when it resolves, React
18150 // attempts to re-render the boundary in the primary (pre-timeout) state.
18151 var thenables = finishedWork.updateQueue;
18152 if (thenables !== null) {
18153 finishedWork.updateQueue = null;
18154 var retryCache = finishedWork.stateNode;
18155 if (retryCache === null) {
18156 retryCache = finishedWork.stateNode = new PossiblyWeakSet$1();
18157 }
18158 thenables.forEach(function (thenable) {
18159 // Memoize using the boundary fiber to prevent redundant listeners.
18160 var retry = retryTimedOutBoundary.bind(null, finishedWork, thenable);
18161 if (enableSchedulerTracing) {
18162 retry = unstable_wrap(retry);
18163 }
18164 if (!retryCache.has(thenable)) {
18165 retryCache.add(thenable);
18166 thenable.then(retry, retry);
18167 }
18168 });
18169 }
18170
18171 return;
18172 }
18173 case IncompleteClassComponent:
18174 {
18175 return;
18176 }
18177 default:
18178 {
18179 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.');
18180 }
18181 }
18182}
18183
18184function commitResetTextContent(current$$1) {
18185 if (!supportsMutation) {
18186 return;
18187 }
18188 resetTextContent(current$$1.stateNode);
18189}
18190
18191var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
18192var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
18193
18194function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
18195 var update = createUpdate(expirationTime);
18196 // Unmount the root by rendering null.
18197 update.tag = CaptureUpdate;
18198 // Caution: React DevTools currently depends on this property
18199 // being called "element".
18200 update.payload = { element: null };
18201 var error = errorInfo.value;
18202 update.callback = function () {
18203 onUncaughtError(error);
18204 logError(fiber, errorInfo);
18205 };
18206 return update;
18207}
18208
18209function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
18210 var update = createUpdate(expirationTime);
18211 update.tag = CaptureUpdate;
18212 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
18213 if (typeof getDerivedStateFromError === 'function') {
18214 var error = errorInfo.value;
18215 update.payload = function () {
18216 return getDerivedStateFromError(error);
18217 };
18218 }
18219
18220 var inst = fiber.stateNode;
18221 if (inst !== null && typeof inst.componentDidCatch === 'function') {
18222 update.callback = function callback() {
18223 if (typeof getDerivedStateFromError !== 'function') {
18224 // To preserve the preexisting retry behavior of error boundaries,
18225 // we keep track of which ones already failed during this batch.
18226 // This gets reset before we yield back to the browser.
18227 // TODO: Warn in strict mode if getDerivedStateFromError is
18228 // not defined.
18229 markLegacyErrorBoundaryAsFailed(this);
18230 }
18231 var error = errorInfo.value;
18232 var stack = errorInfo.stack;
18233 logError(fiber, errorInfo);
18234 this.componentDidCatch(error, {
18235 componentStack: stack !== null ? stack : ''
18236 });
18237 {
18238 if (typeof getDerivedStateFromError !== 'function') {
18239 // If componentDidCatch is the only error boundary method defined,
18240 // then it needs to call setState to recover from errors.
18241 // If no state update is scheduled then the boundary will swallow the error.
18242 !(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;
18243 }
18244 }
18245 };
18246 }
18247 return update;
18248}
18249
18250function attachPingListener(root, renderExpirationTime, thenable) {
18251 // Attach a listener to the promise to "ping" the root and retry. But
18252 // only if one does not already exist for the current render expiration
18253 // time (which acts like a "thread ID" here).
18254 var pingCache = root.pingCache;
18255 var threadIDs = void 0;
18256 if (pingCache === null) {
18257 pingCache = root.pingCache = new PossiblyWeakMap();
18258 threadIDs = new Set();
18259 pingCache.set(thenable, threadIDs);
18260 } else {
18261 threadIDs = pingCache.get(thenable);
18262 if (threadIDs === undefined) {
18263 threadIDs = new Set();
18264 pingCache.set(thenable, threadIDs);
18265 }
18266 }
18267 if (!threadIDs.has(renderExpirationTime)) {
18268 // Memoize using the thread ID to prevent redundant listeners.
18269 threadIDs.add(renderExpirationTime);
18270 var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);
18271 if (enableSchedulerTracing) {
18272 ping = unstable_wrap(ping);
18273 }
18274 thenable.then(ping, ping);
18275 }
18276}
18277
18278function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
18279 // The source fiber did not complete.
18280 sourceFiber.effectTag |= Incomplete;
18281 // Its effect list is no longer valid.
18282 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
18283
18284 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
18285 // This is a thenable.
18286 var thenable = value;
18287
18288 // Find the earliest timeout threshold of all the placeholders in the
18289 // ancestor path. We could avoid this traversal by storing the thresholds on
18290 // the stack, but we choose not to because we only hit this path if we're
18291 // IO-bound (i.e. if something suspends). Whereas the stack is used even in
18292 // the non-IO- bound case.
18293 var _workInProgress = returnFiber;
18294 var earliestTimeoutMs = -1;
18295 var startTimeMs = -1;
18296 do {
18297 if (_workInProgress.tag === SuspenseComponent) {
18298 var current$$1 = _workInProgress.alternate;
18299 if (current$$1 !== null) {
18300 var currentState = current$$1.memoizedState;
18301 if (currentState !== null) {
18302 // Reached a boundary that already timed out. Do not search
18303 // any further.
18304 var timedOutAt = currentState.timedOutAt;
18305 startTimeMs = expirationTimeToMs(timedOutAt);
18306 // Do not search any further.
18307 break;
18308 }
18309 }
18310 var timeoutPropMs = _workInProgress.pendingProps.maxDuration;
18311 if (typeof timeoutPropMs === 'number') {
18312 if (timeoutPropMs <= 0) {
18313 earliestTimeoutMs = 0;
18314 } else if (earliestTimeoutMs === -1 || timeoutPropMs < earliestTimeoutMs) {
18315 earliestTimeoutMs = timeoutPropMs;
18316 }
18317 }
18318 }
18319 // If there is a DehydratedSuspenseComponent we don't have to do anything because
18320 // if something suspends inside it, we will simply leave that as dehydrated. It
18321 // will never timeout.
18322 _workInProgress = _workInProgress.return;
18323 } while (_workInProgress !== null);
18324
18325 // Schedule the nearest Suspense to re-render the timed out view.
18326 _workInProgress = returnFiber;
18327 do {
18328 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress)) {
18329 // Found the nearest boundary.
18330
18331 // Stash the promise on the boundary fiber. If the boundary times out, we'll
18332 var thenables = _workInProgress.updateQueue;
18333 if (thenables === null) {
18334 var updateQueue = new Set();
18335 updateQueue.add(thenable);
18336 _workInProgress.updateQueue = updateQueue;
18337 } else {
18338 thenables.add(thenable);
18339 }
18340
18341 // If the boundary is outside of concurrent mode, we should *not*
18342 // suspend the commit. Pretend as if the suspended component rendered
18343 // null and keep rendering. In the commit phase, we'll schedule a
18344 // subsequent synchronous update to re-render the Suspense.
18345 //
18346 // Note: It doesn't matter whether the component that suspended was
18347 // inside a concurrent mode tree. If the Suspense is outside of it, we
18348 // should *not* suspend the commit.
18349 if ((_workInProgress.mode & ConcurrentMode) === NoEffect) {
18350 _workInProgress.effectTag |= DidCapture;
18351
18352 // We're going to commit this fiber even though it didn't complete.
18353 // But we shouldn't call any lifecycle methods or callbacks. Remove
18354 // all lifecycle effect tags.
18355 sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
18356
18357 if (sourceFiber.tag === ClassComponent) {
18358 var currentSourceFiber = sourceFiber.alternate;
18359 if (currentSourceFiber === null) {
18360 // This is a new mount. Change the tag so it's not mistaken for a
18361 // completed class component. For example, we should not call
18362 // componentWillUnmount if it is deleted.
18363 sourceFiber.tag = IncompleteClassComponent;
18364 } else {
18365 // When we try rendering again, we should not reuse the current fiber,
18366 // since it's known to be in an inconsistent state. Use a force updte to
18367 // prevent a bail out.
18368 var update = createUpdate(Sync);
18369 update.tag = ForceUpdate;
18370 enqueueUpdate(sourceFiber, update);
18371 }
18372 }
18373
18374 // The source fiber did not complete. Mark it with Sync priority to
18375 // indicate that it still has pending work.
18376 sourceFiber.expirationTime = Sync;
18377
18378 // Exit without suspending.
18379 return;
18380 }
18381
18382 // Confirmed that the boundary is in a concurrent mode tree. Continue
18383 // with the normal suspend path.
18384
18385 attachPingListener(root, renderExpirationTime, thenable);
18386
18387 var absoluteTimeoutMs = void 0;
18388 if (earliestTimeoutMs === -1) {
18389 // If no explicit threshold is given, default to an arbitrarily large
18390 // value. The actual size doesn't matter because the threshold for the
18391 // whole tree will be clamped to the expiration time.
18392 absoluteTimeoutMs = maxSigned31BitInt;
18393 } else {
18394 if (startTimeMs === -1) {
18395 // This suspend happened outside of any already timed-out
18396 // placeholders. We don't know exactly when the update was
18397 // scheduled, but we can infer an approximate start time from the
18398 // expiration time. First, find the earliest uncommitted expiration
18399 // time in the tree, including work that is suspended. Then subtract
18400 // the offset used to compute an async update's expiration time.
18401 // This will cause high priority (interactive) work to expire
18402 // earlier than necessary, but we can account for this by adjusting
18403 // for the Just Noticeable Difference.
18404 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, renderExpirationTime);
18405 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
18406 startTimeMs = earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
18407 }
18408 absoluteTimeoutMs = startTimeMs + earliestTimeoutMs;
18409 }
18410
18411 // Mark the earliest timeout in the suspended fiber's ancestor path.
18412 // After completing the root, we'll take the largest of all the
18413 // suspended fiber's timeouts and use it to compute a timeout for the
18414 // whole tree.
18415 renderDidSuspend(root, absoluteTimeoutMs, renderExpirationTime);
18416
18417 _workInProgress.effectTag |= ShouldCapture;
18418 _workInProgress.expirationTime = renderExpirationTime;
18419 return;
18420 } else if (enableSuspenseServerRenderer && _workInProgress.tag === DehydratedSuspenseComponent) {
18421 attachPingListener(root, renderExpirationTime, thenable);
18422
18423 // Since we already have a current fiber, we can eagerly add a retry listener.
18424 var retryCache = _workInProgress.memoizedState;
18425 if (retryCache === null) {
18426 retryCache = _workInProgress.memoizedState = new PossiblyWeakSet();
18427 var _current = _workInProgress.alternate;
18428 !_current ? invariant(false, 'A dehydrated suspense boundary must commit before trying to render. This is probably a bug in React.') : void 0;
18429 _current.memoizedState = retryCache;
18430 }
18431 // Memoize using the boundary fiber to prevent redundant listeners.
18432 if (!retryCache.has(thenable)) {
18433 retryCache.add(thenable);
18434 var retry = retryTimedOutBoundary.bind(null, _workInProgress, thenable);
18435 if (enableSchedulerTracing) {
18436 retry = unstable_wrap(retry);
18437 }
18438 thenable.then(retry, retry);
18439 }
18440 _workInProgress.effectTag |= ShouldCapture;
18441 _workInProgress.expirationTime = renderExpirationTime;
18442 return;
18443 }
18444 // This boundary already captured during this render. Continue to the next
18445 // boundary.
18446 _workInProgress = _workInProgress.return;
18447 } while (_workInProgress !== null);
18448 // No boundary was found. Fallthrough to error mode.
18449 // TODO: Use invariant so the message is stripped in prod?
18450 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));
18451 }
18452
18453 // We didn't find a boundary that could handle this type of exception. Start
18454 // over and traverse parent path again, this time treating the exception
18455 // as an error.
18456 renderDidError();
18457 value = createCapturedValue(value, sourceFiber);
18458 var workInProgress = returnFiber;
18459 do {
18460 switch (workInProgress.tag) {
18461 case HostRoot:
18462 {
18463 var _errorInfo = value;
18464 workInProgress.effectTag |= ShouldCapture;
18465 workInProgress.expirationTime = renderExpirationTime;
18466 var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
18467 enqueueCapturedUpdate(workInProgress, _update);
18468 return;
18469 }
18470 case ClassComponent:
18471 // Capture and retry
18472 var errorInfo = value;
18473 var ctor = workInProgress.type;
18474 var instance = workInProgress.stateNode;
18475 if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
18476 workInProgress.effectTag |= ShouldCapture;
18477 workInProgress.expirationTime = renderExpirationTime;
18478 // Schedule the error boundary to re-render using updated state
18479 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
18480 enqueueCapturedUpdate(workInProgress, _update2);
18481 return;
18482 }
18483 break;
18484 default:
18485 break;
18486 }
18487 workInProgress = workInProgress.return;
18488 } while (workInProgress !== null);
18489}
18490
18491function unwindWork(workInProgress, renderExpirationTime) {
18492 switch (workInProgress.tag) {
18493 case ClassComponent:
18494 {
18495 var Component = workInProgress.type;
18496 if (isContextProvider(Component)) {
18497 popContext(workInProgress);
18498 }
18499 var effectTag = workInProgress.effectTag;
18500 if (effectTag & ShouldCapture) {
18501 workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
18502 return workInProgress;
18503 }
18504 return null;
18505 }
18506 case HostRoot:
18507 {
18508 popHostContainer(workInProgress);
18509 popTopLevelContextObject(workInProgress);
18510 var _effectTag = workInProgress.effectTag;
18511 !((_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;
18512 workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
18513 return workInProgress;
18514 }
18515 case HostComponent:
18516 {
18517 // TODO: popHydrationState
18518 popHostContext(workInProgress);
18519 return null;
18520 }
18521 case SuspenseComponent:
18522 {
18523 var _effectTag2 = workInProgress.effectTag;
18524 if (_effectTag2 & ShouldCapture) {
18525 workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture;
18526 // Captured a suspense effect. Re-render the boundary.
18527 return workInProgress;
18528 }
18529 return null;
18530 }
18531 case DehydratedSuspenseComponent:
18532 {
18533 if (enableSuspenseServerRenderer) {
18534 // TODO: popHydrationState
18535 var _effectTag3 = workInProgress.effectTag;
18536 if (_effectTag3 & ShouldCapture) {
18537 workInProgress.effectTag = _effectTag3 & ~ShouldCapture | DidCapture;
18538 // Captured a suspense effect. Re-render the boundary.
18539 return workInProgress;
18540 }
18541 }
18542 return null;
18543 }
18544 case HostPortal:
18545 popHostContainer(workInProgress);
18546 return null;
18547 case ContextProvider:
18548 popProvider(workInProgress);
18549 return null;
18550 default:
18551 return null;
18552 }
18553}
18554
18555function unwindInterruptedWork(interruptedWork) {
18556 switch (interruptedWork.tag) {
18557 case ClassComponent:
18558 {
18559 var childContextTypes = interruptedWork.type.childContextTypes;
18560 if (childContextTypes !== null && childContextTypes !== undefined) {
18561 popContext(interruptedWork);
18562 }
18563 break;
18564 }
18565 case HostRoot:
18566 {
18567 popHostContainer(interruptedWork);
18568 popTopLevelContextObject(interruptedWork);
18569 break;
18570 }
18571 case HostComponent:
18572 {
18573 popHostContext(interruptedWork);
18574 break;
18575 }
18576 case HostPortal:
18577 popHostContainer(interruptedWork);
18578 break;
18579 case ContextProvider:
18580 popProvider(interruptedWork);
18581 break;
18582 default:
18583 break;
18584 }
18585}
18586
18587var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
18588var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
18589
18590
18591var didWarnAboutStateTransition = void 0;
18592var didWarnSetStateChildContext = void 0;
18593var warnAboutUpdateOnUnmounted = void 0;
18594var warnAboutInvalidUpdates = void 0;
18595
18596if (enableSchedulerTracing) {
18597 // Provide explicit error message when production+profiling bundle of e.g. react-dom
18598 // is used with production (non-profiling) bundle of scheduler/tracing
18599 !(__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;
18600}
18601
18602{
18603 didWarnAboutStateTransition = false;
18604 didWarnSetStateChildContext = false;
18605 var didWarnStateUpdateForUnmountedComponent = {};
18606
18607 warnAboutUpdateOnUnmounted = function (fiber, isClass) {
18608 // We show the whole stack but dedupe on the top component's name because
18609 // the problematic code almost always lies inside that component.
18610 var componentName = getComponentName(fiber.type) || 'ReactComponent';
18611 if (didWarnStateUpdateForUnmountedComponent[componentName]) {
18612 return;
18613 }
18614 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));
18615 didWarnStateUpdateForUnmountedComponent[componentName] = true;
18616 };
18617
18618 warnAboutInvalidUpdates = function (instance) {
18619 switch (phase) {
18620 case 'getChildContext':
18621 if (didWarnSetStateChildContext) {
18622 return;
18623 }
18624 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
18625 didWarnSetStateChildContext = true;
18626 break;
18627 case 'render':
18628 if (didWarnAboutStateTransition) {
18629 return;
18630 }
18631 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.');
18632 didWarnAboutStateTransition = true;
18633 break;
18634 }
18635 };
18636}
18637
18638// Used to ensure computeUniqueAsyncExpiration is monotonically decreasing.
18639var lastUniqueAsyncExpiration = Sync - 1;
18640
18641var isWorking = false;
18642
18643// The next work in progress fiber that we're currently working on.
18644var nextUnitOfWork = null;
18645var nextRoot = null;
18646// The time at which we're currently rendering work.
18647var nextRenderExpirationTime = NoWork;
18648var nextLatestAbsoluteTimeoutMs = -1;
18649var nextRenderDidError = false;
18650
18651// The next fiber with an effect that we're currently committing.
18652var nextEffect = null;
18653
18654var isCommitting$1 = false;
18655var rootWithPendingPassiveEffects = null;
18656var passiveEffectCallbackHandle = null;
18657var passiveEffectCallback = null;
18658
18659var legacyErrorBoundariesThatAlreadyFailed = null;
18660
18661// Used for performance tracking.
18662var interruptedBy = null;
18663
18664var stashedWorkInProgressProperties = void 0;
18665var replayUnitOfWork = void 0;
18666var mayReplayFailedUnitOfWork = void 0;
18667var isReplayingFailedUnitOfWork = void 0;
18668var originalReplayError = void 0;
18669var rethrowOriginalError = void 0;
18670if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
18671 stashedWorkInProgressProperties = null;
18672 mayReplayFailedUnitOfWork = true;
18673 isReplayingFailedUnitOfWork = false;
18674 originalReplayError = null;
18675 replayUnitOfWork = function (failedUnitOfWork, thrownValue, isYieldy) {
18676 if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
18677 // Don't replay promises. Treat everything else like an error.
18678 // TODO: Need to figure out a different strategy if/when we add
18679 // support for catching other types.
18680 return;
18681 }
18682
18683 // Restore the original state of the work-in-progress
18684 if (stashedWorkInProgressProperties === null) {
18685 // This should never happen. Don't throw because this code is DEV-only.
18686 warningWithoutStack$1(false, 'Could not replay rendering after an error. This is likely a bug in React. ' + 'Please file an issue.');
18687 return;
18688 }
18689 assignFiberPropertiesInDEV(failedUnitOfWork, stashedWorkInProgressProperties);
18690
18691 switch (failedUnitOfWork.tag) {
18692 case HostRoot:
18693 popHostContainer(failedUnitOfWork);
18694 popTopLevelContextObject(failedUnitOfWork);
18695 break;
18696 case HostComponent:
18697 popHostContext(failedUnitOfWork);
18698 break;
18699 case ClassComponent:
18700 {
18701 var Component = failedUnitOfWork.type;
18702 if (isContextProvider(Component)) {
18703 popContext(failedUnitOfWork);
18704 }
18705 break;
18706 }
18707 case HostPortal:
18708 popHostContainer(failedUnitOfWork);
18709 break;
18710 case ContextProvider:
18711 popProvider(failedUnitOfWork);
18712 break;
18713 }
18714 // Replay the begin phase.
18715 isReplayingFailedUnitOfWork = true;
18716 originalReplayError = thrownValue;
18717 invokeGuardedCallback(null, workLoop, null, isYieldy);
18718 isReplayingFailedUnitOfWork = false;
18719 originalReplayError = null;
18720 if (hasCaughtError()) {
18721 var replayError = clearCaughtError();
18722 if (replayError != null && thrownValue != null) {
18723 try {
18724 // Reading the expando property is intentionally
18725 // inside `try` because it might be a getter or Proxy.
18726 if (replayError._suppressLogging) {
18727 // Also suppress logging for the original error.
18728 thrownValue._suppressLogging = true;
18729 }
18730 } catch (inner) {
18731 // Ignore.
18732 }
18733 }
18734 } else {
18735 // If the begin phase did not fail the second time, set this pointer
18736 // back to the original value.
18737 nextUnitOfWork = failedUnitOfWork;
18738 }
18739 };
18740 rethrowOriginalError = function () {
18741 throw originalReplayError;
18742 };
18743}
18744
18745function resetStack() {
18746 if (nextUnitOfWork !== null) {
18747 var interruptedWork = nextUnitOfWork.return;
18748 while (interruptedWork !== null) {
18749 unwindInterruptedWork(interruptedWork);
18750 interruptedWork = interruptedWork.return;
18751 }
18752 }
18753
18754 {
18755 ReactStrictModeWarnings.discardPendingWarnings();
18756 checkThatStackIsEmpty();
18757 }
18758
18759 nextRoot = null;
18760 nextRenderExpirationTime = NoWork;
18761 nextLatestAbsoluteTimeoutMs = -1;
18762 nextRenderDidError = false;
18763 nextUnitOfWork = null;
18764}
18765
18766function commitAllHostEffects() {
18767 while (nextEffect !== null) {
18768 {
18769 setCurrentFiber(nextEffect);
18770 }
18771 recordEffect();
18772
18773 var effectTag = nextEffect.effectTag;
18774
18775 if (effectTag & ContentReset) {
18776 commitResetTextContent(nextEffect);
18777 }
18778
18779 if (effectTag & Ref) {
18780 var current$$1 = nextEffect.alternate;
18781 if (current$$1 !== null) {
18782 commitDetachRef(current$$1);
18783 }
18784 }
18785
18786 // The following switch statement is only concerned about placement,
18787 // updates, and deletions. To avoid needing to add a case for every
18788 // possible bitmap value, we remove the secondary effects from the
18789 // effect tag and switch on that value.
18790 var primaryEffectTag = effectTag & (Placement | Update | Deletion);
18791 switch (primaryEffectTag) {
18792 case Placement:
18793 {
18794 commitPlacement(nextEffect);
18795 // Clear the "placement" from effect tag so that we know that this is inserted, before
18796 // any life-cycles like componentDidMount gets called.
18797 // TODO: findDOMNode doesn't rely on this any more but isMounted
18798 // does and isMounted is deprecated anyway so we should be able
18799 // to kill this.
18800 nextEffect.effectTag &= ~Placement;
18801 break;
18802 }
18803 case PlacementAndUpdate:
18804 {
18805 // Placement
18806 commitPlacement(nextEffect);
18807 // Clear the "placement" from effect tag so that we know that this is inserted, before
18808 // any life-cycles like componentDidMount gets called.
18809 nextEffect.effectTag &= ~Placement;
18810
18811 // Update
18812 var _current = nextEffect.alternate;
18813 commitWork(_current, nextEffect);
18814 break;
18815 }
18816 case Update:
18817 {
18818 var _current2 = nextEffect.alternate;
18819 commitWork(_current2, nextEffect);
18820 break;
18821 }
18822 case Deletion:
18823 {
18824 commitDeletion(nextEffect);
18825 break;
18826 }
18827 }
18828 nextEffect = nextEffect.nextEffect;
18829 }
18830
18831 {
18832 resetCurrentFiber();
18833 }
18834}
18835
18836function commitBeforeMutationLifecycles() {
18837 while (nextEffect !== null) {
18838 {
18839 setCurrentFiber(nextEffect);
18840 }
18841
18842 var effectTag = nextEffect.effectTag;
18843 if (effectTag & Snapshot) {
18844 recordEffect();
18845 var current$$1 = nextEffect.alternate;
18846 commitBeforeMutationLifeCycles(current$$1, nextEffect);
18847 }
18848
18849 nextEffect = nextEffect.nextEffect;
18850 }
18851
18852 {
18853 resetCurrentFiber();
18854 }
18855}
18856
18857function commitAllLifeCycles(finishedRoot, committedExpirationTime) {
18858 {
18859 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
18860 ReactStrictModeWarnings.flushLegacyContextWarning();
18861
18862 if (warnAboutDeprecatedLifecycles) {
18863 ReactStrictModeWarnings.flushPendingDeprecationWarnings();
18864 }
18865 }
18866 while (nextEffect !== null) {
18867 {
18868 setCurrentFiber(nextEffect);
18869 }
18870 var effectTag = nextEffect.effectTag;
18871
18872 if (effectTag & (Update | Callback)) {
18873 recordEffect();
18874 var current$$1 = nextEffect.alternate;
18875 commitLifeCycles(finishedRoot, current$$1, nextEffect, committedExpirationTime);
18876 }
18877
18878 if (effectTag & Ref) {
18879 recordEffect();
18880 commitAttachRef(nextEffect);
18881 }
18882
18883 if (effectTag & Passive) {
18884 rootWithPendingPassiveEffects = finishedRoot;
18885 }
18886
18887 nextEffect = nextEffect.nextEffect;
18888 }
18889 {
18890 resetCurrentFiber();
18891 }
18892}
18893
18894function commitPassiveEffects(root, firstEffect) {
18895 rootWithPendingPassiveEffects = null;
18896 passiveEffectCallbackHandle = null;
18897 passiveEffectCallback = null;
18898
18899 // Set this to true to prevent re-entrancy
18900 var previousIsRendering = isRendering;
18901 isRendering = true;
18902
18903 var effect = firstEffect;
18904 do {
18905 {
18906 setCurrentFiber(effect);
18907 }
18908
18909 if (effect.effectTag & Passive) {
18910 var didError = false;
18911 var error = void 0;
18912 {
18913 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
18914 if (hasCaughtError()) {
18915 didError = true;
18916 error = clearCaughtError();
18917 }
18918 }
18919 if (didError) {
18920 captureCommitPhaseError(effect, error);
18921 }
18922 }
18923 effect = effect.nextEffect;
18924 } while (effect !== null);
18925 {
18926 resetCurrentFiber();
18927 }
18928
18929 isRendering = previousIsRendering;
18930
18931 // Check if work was scheduled by one of the effects
18932 var rootExpirationTime = root.expirationTime;
18933 if (rootExpirationTime !== NoWork) {
18934 requestWork(root, rootExpirationTime);
18935 }
18936 // Flush any sync work that was scheduled by effects
18937 if (!isBatchingUpdates && !isRendering) {
18938 performSyncWork();
18939 }
18940}
18941
18942function isAlreadyFailedLegacyErrorBoundary(instance) {
18943 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
18944}
18945
18946function markLegacyErrorBoundaryAsFailed(instance) {
18947 if (legacyErrorBoundariesThatAlreadyFailed === null) {
18948 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
18949 } else {
18950 legacyErrorBoundariesThatAlreadyFailed.add(instance);
18951 }
18952}
18953
18954function flushPassiveEffects() {
18955 if (passiveEffectCallbackHandle !== null) {
18956 cancelPassiveEffects(passiveEffectCallbackHandle);
18957 }
18958 if (passiveEffectCallback !== null) {
18959 // We call the scheduled callback instead of commitPassiveEffects directly
18960 // to ensure tracing works correctly.
18961 passiveEffectCallback();
18962 }
18963}
18964
18965function commitRoot(root, finishedWork) {
18966 isWorking = true;
18967 isCommitting$1 = true;
18968 startCommitTimer();
18969
18970 !(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;
18971 var committedExpirationTime = root.pendingCommitExpirationTime;
18972 !(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;
18973 root.pendingCommitExpirationTime = NoWork;
18974
18975 // Update the pending priority levels to account for the work that we are
18976 // about to commit. This needs to happen before calling the lifecycles, since
18977 // they may schedule additional updates.
18978 var updateExpirationTimeBeforeCommit = finishedWork.expirationTime;
18979 var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime;
18980 var earliestRemainingTimeBeforeCommit = childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit ? childExpirationTimeBeforeCommit : updateExpirationTimeBeforeCommit;
18981 markCommittedPriorityLevels(root, earliestRemainingTimeBeforeCommit);
18982
18983 var prevInteractions = null;
18984 if (enableSchedulerTracing) {
18985 // Restore any pending interactions at this point,
18986 // So that cascading work triggered during the render phase will be accounted for.
18987 prevInteractions = __interactionsRef.current;
18988 __interactionsRef.current = root.memoizedInteractions;
18989 }
18990
18991 // Reset this to null before calling lifecycles
18992 ReactCurrentOwner$2.current = null;
18993
18994 var firstEffect = void 0;
18995 if (finishedWork.effectTag > PerformedWork) {
18996 // A fiber's effect list consists only of its children, not itself. So if
18997 // the root has an effect, we need to add it to the end of the list. The
18998 // resulting list is the set that would belong to the root's parent, if
18999 // it had one; that is, all the effects in the tree including the root.
19000 if (finishedWork.lastEffect !== null) {
19001 finishedWork.lastEffect.nextEffect = finishedWork;
19002 firstEffect = finishedWork.firstEffect;
19003 } else {
19004 firstEffect = finishedWork;
19005 }
19006 } else {
19007 // There is no effect on the root.
19008 firstEffect = finishedWork.firstEffect;
19009 }
19010
19011 prepareForCommit(root.containerInfo);
19012
19013 // Invoke instances of getSnapshotBeforeUpdate before mutation.
19014 nextEffect = firstEffect;
19015 startCommitSnapshotEffectsTimer();
19016 while (nextEffect !== null) {
19017 var didError = false;
19018 var error = void 0;
19019 {
19020 invokeGuardedCallback(null, commitBeforeMutationLifecycles, null);
19021 if (hasCaughtError()) {
19022 didError = true;
19023 error = clearCaughtError();
19024 }
19025 }
19026 if (didError) {
19027 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
19028 captureCommitPhaseError(nextEffect, error);
19029 // Clean-up
19030 if (nextEffect !== null) {
19031 nextEffect = nextEffect.nextEffect;
19032 }
19033 }
19034 }
19035 stopCommitSnapshotEffectsTimer();
19036
19037 if (enableProfilerTimer) {
19038 // Mark the current commit time to be shared by all Profilers in this batch.
19039 // This enables them to be grouped later.
19040 recordCommitTime();
19041 }
19042
19043 // Commit all the side-effects within a tree. We'll do this in two passes.
19044 // The first pass performs all the host insertions, updates, deletions and
19045 // ref unmounts.
19046 nextEffect = firstEffect;
19047 startCommitHostEffectsTimer();
19048 while (nextEffect !== null) {
19049 var _didError = false;
19050 var _error = void 0;
19051 {
19052 invokeGuardedCallback(null, commitAllHostEffects, null);
19053 if (hasCaughtError()) {
19054 _didError = true;
19055 _error = clearCaughtError();
19056 }
19057 }
19058 if (_didError) {
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, _error);
19061 // Clean-up
19062 if (nextEffect !== null) {
19063 nextEffect = nextEffect.nextEffect;
19064 }
19065 }
19066 }
19067 stopCommitHostEffectsTimer();
19068
19069 resetAfterCommit(root.containerInfo);
19070
19071 // The work-in-progress tree is now the current tree. This must come after
19072 // the first pass of the commit phase, so that the previous tree is still
19073 // current during componentWillUnmount, but before the second pass, so that
19074 // the finished work is current during componentDidMount/Update.
19075 root.current = finishedWork;
19076
19077 // In the second pass we'll perform all life-cycles and ref callbacks.
19078 // Life-cycles happen as a separate pass so that all placements, updates,
19079 // and deletions in the entire tree have already been invoked.
19080 // This pass also triggers any renderer-specific initial effects.
19081 nextEffect = firstEffect;
19082 startCommitLifeCyclesTimer();
19083 while (nextEffect !== null) {
19084 var _didError2 = false;
19085 var _error2 = void 0;
19086 {
19087 invokeGuardedCallback(null, commitAllLifeCycles, null, root, committedExpirationTime);
19088 if (hasCaughtError()) {
19089 _didError2 = true;
19090 _error2 = clearCaughtError();
19091 }
19092 }
19093 if (_didError2) {
19094 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
19095 captureCommitPhaseError(nextEffect, _error2);
19096 if (nextEffect !== null) {
19097 nextEffect = nextEffect.nextEffect;
19098 }
19099 }
19100 }
19101
19102 if (firstEffect !== null && rootWithPendingPassiveEffects !== null) {
19103 // This commit included a passive effect. These do not need to fire until
19104 // after the next paint. Schedule an callback to fire them in an async
19105 // event. To ensure serial execution, the callback will be flushed early if
19106 // we enter rootWithPendingPassiveEffects commit phase before then.
19107 var callback = commitPassiveEffects.bind(null, root, firstEffect);
19108 if (enableSchedulerTracing) {
19109 // TODO: Avoid this extra callback by mutating the tracing ref directly,
19110 // like we do at the beginning of commitRoot. I've opted not to do that
19111 // here because that code is still in flux.
19112 callback = unstable_wrap(callback);
19113 }
19114 passiveEffectCallbackHandle = unstable_runWithPriority(unstable_NormalPriority, function () {
19115 return schedulePassiveEffects(callback);
19116 });
19117 passiveEffectCallback = callback;
19118 }
19119
19120 isCommitting$1 = false;
19121 isWorking = false;
19122 stopCommitLifeCyclesTimer();
19123 stopCommitTimer();
19124 onCommitRoot(finishedWork.stateNode);
19125 if (true && ReactFiberInstrumentation_1.debugTool) {
19126 ReactFiberInstrumentation_1.debugTool.onCommitWork(finishedWork);
19127 }
19128
19129 var updateExpirationTimeAfterCommit = finishedWork.expirationTime;
19130 var childExpirationTimeAfterCommit = finishedWork.childExpirationTime;
19131 var earliestRemainingTimeAfterCommit = childExpirationTimeAfterCommit > updateExpirationTimeAfterCommit ? childExpirationTimeAfterCommit : updateExpirationTimeAfterCommit;
19132 if (earliestRemainingTimeAfterCommit === NoWork) {
19133 // If there's no remaining work, we can clear the set of already failed
19134 // error boundaries.
19135 legacyErrorBoundariesThatAlreadyFailed = null;
19136 }
19137 onCommit(root, earliestRemainingTimeAfterCommit);
19138
19139 if (enableSchedulerTracing) {
19140 __interactionsRef.current = prevInteractions;
19141
19142 var subscriber = void 0;
19143
19144 try {
19145 subscriber = __subscriberRef.current;
19146 if (subscriber !== null && root.memoizedInteractions.size > 0) {
19147 var threadID = computeThreadID(committedExpirationTime, root.interactionThreadID);
19148 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
19149 }
19150 } catch (error) {
19151 // It's not safe for commitRoot() to throw.
19152 // Store the error for now and we'll re-throw in finishRendering().
19153 if (!hasUnhandledError) {
19154 hasUnhandledError = true;
19155 unhandledError = error;
19156 }
19157 } finally {
19158 // Clear completed interactions from the pending Map.
19159 // Unless the render was suspended or cascading work was scheduled,
19160 // In which case– leave pending interactions until the subsequent render.
19161 var pendingInteractionMap = root.pendingInteractionMap;
19162 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
19163 // Only decrement the pending interaction count if we're done.
19164 // If there's still work at the current priority,
19165 // That indicates that we are waiting for suspense data.
19166 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
19167 pendingInteractionMap.delete(scheduledExpirationTime);
19168
19169 scheduledInteractions.forEach(function (interaction) {
19170 interaction.__count--;
19171
19172 if (subscriber !== null && interaction.__count === 0) {
19173 try {
19174 subscriber.onInteractionScheduledWorkCompleted(interaction);
19175 } catch (error) {
19176 // It's not safe for commitRoot() to throw.
19177 // Store the error for now and we'll re-throw in finishRendering().
19178 if (!hasUnhandledError) {
19179 hasUnhandledError = true;
19180 unhandledError = error;
19181 }
19182 }
19183 }
19184 });
19185 }
19186 });
19187 }
19188 }
19189}
19190
19191function resetChildExpirationTime(workInProgress, renderTime) {
19192 if (renderTime !== Never && workInProgress.childExpirationTime === Never) {
19193 // The children of this component are hidden. Don't bubble their
19194 // expiration times.
19195 return;
19196 }
19197
19198 var newChildExpirationTime = NoWork;
19199
19200 // Bubble up the earliest expiration time.
19201 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19202 // We're in profiling mode.
19203 // Let's use this same traversal to update the render durations.
19204 var actualDuration = workInProgress.actualDuration;
19205 var treeBaseDuration = workInProgress.selfBaseDuration;
19206
19207 // When a fiber is cloned, its actualDuration is reset to 0.
19208 // This value will only be updated if work is done on the fiber (i.e. it doesn't bailout).
19209 // When work is done, it should bubble to the parent's actualDuration.
19210 // If the fiber has not been cloned though, (meaning no work was done),
19211 // Then this value will reflect the amount of time spent working on a previous render.
19212 // In that case it should not bubble.
19213 // We determine whether it was cloned by comparing the child pointer.
19214 var shouldBubbleActualDurations = workInProgress.alternate === null || workInProgress.child !== workInProgress.alternate.child;
19215
19216 var child = workInProgress.child;
19217 while (child !== null) {
19218 var childUpdateExpirationTime = child.expirationTime;
19219 var childChildExpirationTime = child.childExpirationTime;
19220 if (childUpdateExpirationTime > newChildExpirationTime) {
19221 newChildExpirationTime = childUpdateExpirationTime;
19222 }
19223 if (childChildExpirationTime > newChildExpirationTime) {
19224 newChildExpirationTime = childChildExpirationTime;
19225 }
19226 if (shouldBubbleActualDurations) {
19227 actualDuration += child.actualDuration;
19228 }
19229 treeBaseDuration += child.treeBaseDuration;
19230 child = child.sibling;
19231 }
19232 workInProgress.actualDuration = actualDuration;
19233 workInProgress.treeBaseDuration = treeBaseDuration;
19234 } else {
19235 var _child = workInProgress.child;
19236 while (_child !== null) {
19237 var _childUpdateExpirationTime = _child.expirationTime;
19238 var _childChildExpirationTime = _child.childExpirationTime;
19239 if (_childUpdateExpirationTime > newChildExpirationTime) {
19240 newChildExpirationTime = _childUpdateExpirationTime;
19241 }
19242 if (_childChildExpirationTime > newChildExpirationTime) {
19243 newChildExpirationTime = _childChildExpirationTime;
19244 }
19245 _child = _child.sibling;
19246 }
19247 }
19248
19249 workInProgress.childExpirationTime = newChildExpirationTime;
19250}
19251
19252function completeUnitOfWork(workInProgress) {
19253 // Attempt to complete the current unit of work, then move to the
19254 // next sibling. If there are no more siblings, return to the
19255 // parent fiber.
19256 while (true) {
19257 // The current, flushed, state of this fiber is the alternate.
19258 // Ideally nothing should rely on this, but relying on it here
19259 // means that we don't need an additional field on the work in
19260 // progress.
19261 var current$$1 = workInProgress.alternate;
19262 {
19263 setCurrentFiber(workInProgress);
19264 }
19265
19266 var returnFiber = workInProgress.return;
19267 var siblingFiber = workInProgress.sibling;
19268
19269 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
19270 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
19271 // Don't replay if it fails during completion phase.
19272 mayReplayFailedUnitOfWork = false;
19273 }
19274 // This fiber completed.
19275 // Remember we're completing this unit so we can find a boundary if it fails.
19276 nextUnitOfWork = workInProgress;
19277 if (enableProfilerTimer) {
19278 if (workInProgress.mode & ProfileMode) {
19279 startProfilerTimer(workInProgress);
19280 }
19281 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
19282 if (workInProgress.mode & ProfileMode) {
19283 // Update render duration assuming we didn't error.
19284 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
19285 }
19286 } else {
19287 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
19288 }
19289 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
19290 // We're out of completion phase so replaying is fine now.
19291 mayReplayFailedUnitOfWork = true;
19292 }
19293 stopWorkTimer(workInProgress);
19294 resetChildExpirationTime(workInProgress, nextRenderExpirationTime);
19295 {
19296 resetCurrentFiber();
19297 }
19298
19299 if (nextUnitOfWork !== null) {
19300 // Completing this fiber spawned new work. Work on that next.
19301 return nextUnitOfWork;
19302 }
19303
19304 if (returnFiber !== null &&
19305 // Do not append effects to parents if a sibling failed to complete
19306 (returnFiber.effectTag & Incomplete) === NoEffect) {
19307 // Append all the effects of the subtree and this fiber onto the effect
19308 // list of the parent. The completion order of the children affects the
19309 // side-effect order.
19310 if (returnFiber.firstEffect === null) {
19311 returnFiber.firstEffect = workInProgress.firstEffect;
19312 }
19313 if (workInProgress.lastEffect !== null) {
19314 if (returnFiber.lastEffect !== null) {
19315 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
19316 }
19317 returnFiber.lastEffect = workInProgress.lastEffect;
19318 }
19319
19320 // If this fiber had side-effects, we append it AFTER the children's
19321 // side-effects. We can perform certain side-effects earlier if
19322 // needed, by doing multiple passes over the effect list. We don't want
19323 // to schedule our own side-effect on our own list because if end up
19324 // reusing children we'll schedule this effect onto itself since we're
19325 // at the end.
19326 var effectTag = workInProgress.effectTag;
19327 // Skip both NoWork and PerformedWork tags when creating the effect list.
19328 // PerformedWork effect is read by React DevTools but shouldn't be committed.
19329 if (effectTag > PerformedWork) {
19330 if (returnFiber.lastEffect !== null) {
19331 returnFiber.lastEffect.nextEffect = workInProgress;
19332 } else {
19333 returnFiber.firstEffect = workInProgress;
19334 }
19335 returnFiber.lastEffect = workInProgress;
19336 }
19337 }
19338
19339 if (true && ReactFiberInstrumentation_1.debugTool) {
19340 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
19341 }
19342
19343 if (siblingFiber !== null) {
19344 // If there is more work to do in this returnFiber, do that next.
19345 return siblingFiber;
19346 } else if (returnFiber !== null) {
19347 // If there's no more work in this returnFiber. Complete the returnFiber.
19348 workInProgress = returnFiber;
19349 continue;
19350 } else {
19351 // We've reached the root.
19352 return null;
19353 }
19354 } else {
19355 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19356 // Record the render duration for the fiber that errored.
19357 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
19358
19359 // Include the time spent working on failed children before continuing.
19360 var actualDuration = workInProgress.actualDuration;
19361 var child = workInProgress.child;
19362 while (child !== null) {
19363 actualDuration += child.actualDuration;
19364 child = child.sibling;
19365 }
19366 workInProgress.actualDuration = actualDuration;
19367 }
19368
19369 // This fiber did not complete because something threw. Pop values off
19370 // the stack without entering the complete phase. If this is a boundary,
19371 // capture values if possible.
19372 var next = unwindWork(workInProgress, nextRenderExpirationTime);
19373 // Because this fiber did not complete, don't reset its expiration time.
19374 if (workInProgress.effectTag & DidCapture) {
19375 // Restarting an error boundary
19376 stopFailedWorkTimer(workInProgress);
19377 } else {
19378 stopWorkTimer(workInProgress);
19379 }
19380
19381 {
19382 resetCurrentFiber();
19383 }
19384
19385 if (next !== null) {
19386 stopWorkTimer(workInProgress);
19387 if (true && ReactFiberInstrumentation_1.debugTool) {
19388 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
19389 }
19390
19391 // If completing this work spawned new work, do that next. We'll come
19392 // back here again.
19393 // Since we're restarting, remove anything that is not a host effect
19394 // from the effect tag.
19395 next.effectTag &= HostEffectMask;
19396 return next;
19397 }
19398
19399 if (returnFiber !== null) {
19400 // Mark the parent fiber as incomplete and clear its effect list.
19401 returnFiber.firstEffect = returnFiber.lastEffect = null;
19402 returnFiber.effectTag |= Incomplete;
19403 }
19404
19405 if (true && ReactFiberInstrumentation_1.debugTool) {
19406 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
19407 }
19408
19409 if (siblingFiber !== null) {
19410 // If there is more work to do in this returnFiber, do that next.
19411 return siblingFiber;
19412 } else if (returnFiber !== null) {
19413 // If there's no more work in this returnFiber. Complete the returnFiber.
19414 workInProgress = returnFiber;
19415 continue;
19416 } else {
19417 return null;
19418 }
19419 }
19420 }
19421
19422 // Without this explicit null return Flow complains of invalid return type
19423 // TODO Remove the above while(true) loop
19424 // eslint-disable-next-line no-unreachable
19425 return null;
19426}
19427
19428function performUnitOfWork(workInProgress) {
19429 // The current, flushed, state of this fiber is the alternate.
19430 // Ideally nothing should rely on this, but relying on it here
19431 // means that we don't need an additional field on the work in
19432 // progress.
19433 var current$$1 = workInProgress.alternate;
19434
19435 // See if beginning this work spawns more work.
19436 startWorkTimer(workInProgress);
19437 {
19438 setCurrentFiber(workInProgress);
19439 }
19440
19441 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
19442 stashedWorkInProgressProperties = assignFiberPropertiesInDEV(stashedWorkInProgressProperties, workInProgress);
19443 }
19444
19445 var next = void 0;
19446 if (enableProfilerTimer) {
19447 if (workInProgress.mode & ProfileMode) {
19448 startProfilerTimer(workInProgress);
19449 }
19450
19451 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
19452 workInProgress.memoizedProps = workInProgress.pendingProps;
19453
19454 if (workInProgress.mode & ProfileMode) {
19455 // Record the render duration assuming we didn't bailout (or error).
19456 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
19457 }
19458 } else {
19459 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
19460 workInProgress.memoizedProps = workInProgress.pendingProps;
19461 }
19462
19463 {
19464 resetCurrentFiber();
19465 if (isReplayingFailedUnitOfWork) {
19466 // Currently replaying a failed unit of work. This should be unreachable,
19467 // because the render phase is meant to be idempotent, and it should
19468 // have thrown again. Since it didn't, rethrow the original error, so
19469 // React's internal stack is not misaligned.
19470 rethrowOriginalError();
19471 }
19472 }
19473 if (true && ReactFiberInstrumentation_1.debugTool) {
19474 ReactFiberInstrumentation_1.debugTool.onBeginWork(workInProgress);
19475 }
19476
19477 if (next === null) {
19478 // If this doesn't spawn new work, complete the current work.
19479 next = completeUnitOfWork(workInProgress);
19480 }
19481
19482 ReactCurrentOwner$2.current = null;
19483
19484 return next;
19485}
19486
19487function workLoop(isYieldy) {
19488 if (!isYieldy) {
19489 // Flush work without yielding
19490 while (nextUnitOfWork !== null) {
19491 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
19492 }
19493 } else {
19494 // Flush asynchronous work until there's a higher priority event
19495 while (nextUnitOfWork !== null && !shouldYieldToRenderer()) {
19496 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
19497 }
19498 }
19499}
19500
19501function renderRoot(root, isYieldy) {
19502 !!isWorking ? invariant(false, 'renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;
19503
19504 flushPassiveEffects();
19505
19506 isWorking = true;
19507 var previousDispatcher = ReactCurrentDispatcher.current;
19508 ReactCurrentDispatcher.current = ContextOnlyDispatcher;
19509
19510 var expirationTime = root.nextExpirationTimeToWorkOn;
19511
19512 // Check if we're starting from a fresh stack, or if we're resuming from
19513 // previously yielded work.
19514 if (expirationTime !== nextRenderExpirationTime || root !== nextRoot || nextUnitOfWork === null) {
19515 // Reset the stack and start working from the root.
19516 resetStack();
19517 nextRoot = root;
19518 nextRenderExpirationTime = expirationTime;
19519 nextUnitOfWork = createWorkInProgress(nextRoot.current, null, nextRenderExpirationTime);
19520 root.pendingCommitExpirationTime = NoWork;
19521
19522 if (enableSchedulerTracing) {
19523 // Determine which interactions this batch of work currently includes,
19524 // So that we can accurately attribute time spent working on it,
19525 var interactions = new Set();
19526 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
19527 if (scheduledExpirationTime >= expirationTime) {
19528 scheduledInteractions.forEach(function (interaction) {
19529 return interactions.add(interaction);
19530 });
19531 }
19532 });
19533
19534 // Store the current set of interactions on the FiberRoot for a few reasons:
19535 // We can re-use it in hot functions like renderRoot() without having to recalculate it.
19536 // We will also use it in commitWork() to pass to any Profiler onRender() hooks.
19537 // This also provides DevTools with a way to access it when the onCommitRoot() hook is called.
19538 root.memoizedInteractions = interactions;
19539
19540 if (interactions.size > 0) {
19541 var subscriber = __subscriberRef.current;
19542 if (subscriber !== null) {
19543 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
19544 try {
19545 subscriber.onWorkStarted(interactions, threadID);
19546 } catch (error) {
19547 // Work thrown by an interaction tracing subscriber should be rethrown,
19548 // But only once it's safe (to avoid leaving the scheduler in an invalid state).
19549 // Store the error for now and we'll re-throw in finishRendering().
19550 if (!hasUnhandledError) {
19551 hasUnhandledError = true;
19552 unhandledError = error;
19553 }
19554 }
19555 }
19556 }
19557 }
19558 }
19559
19560 var prevInteractions = null;
19561 if (enableSchedulerTracing) {
19562 // We're about to start new traced work.
19563 // Restore pending interactions so cascading work triggered during the render phase will be accounted for.
19564 prevInteractions = __interactionsRef.current;
19565 __interactionsRef.current = root.memoizedInteractions;
19566 }
19567
19568 var didFatal = false;
19569
19570 startWorkLoopTimer(nextUnitOfWork);
19571
19572 do {
19573 try {
19574 workLoop(isYieldy);
19575 } catch (thrownValue) {
19576 resetContextDependences();
19577 resetHooks();
19578
19579 // Reset in case completion throws.
19580 // This is only used in DEV and when replaying is on.
19581 var mayReplay = void 0;
19582 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
19583 mayReplay = mayReplayFailedUnitOfWork;
19584 mayReplayFailedUnitOfWork = true;
19585 }
19586
19587 if (nextUnitOfWork === null) {
19588 // This is a fatal error.
19589 didFatal = true;
19590 onUncaughtError(thrownValue);
19591 } else {
19592 if (enableProfilerTimer && nextUnitOfWork.mode & ProfileMode) {
19593 // Record the time spent rendering before an error was thrown.
19594 // This avoids inaccurate Profiler durations in the case of a suspended render.
19595 stopProfilerTimerIfRunningAndRecordDelta(nextUnitOfWork, true);
19596 }
19597
19598 {
19599 // Reset global debug state
19600 // We assume this is defined in DEV
19601 resetCurrentlyProcessingQueue();
19602 }
19603
19604 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
19605 if (mayReplay) {
19606 var failedUnitOfWork = nextUnitOfWork;
19607 replayUnitOfWork(failedUnitOfWork, thrownValue, isYieldy);
19608 }
19609 }
19610
19611 // TODO: we already know this isn't true in some cases.
19612 // At least this shows a nicer error message until we figure out the cause.
19613 // https://github.com/facebook/react/issues/12449#issuecomment-386727431
19614 !(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;
19615
19616 var sourceFiber = nextUnitOfWork;
19617 var returnFiber = sourceFiber.return;
19618 if (returnFiber === null) {
19619 // This is the root. The root could capture its own errors. However,
19620 // we don't know if it errors before or after we pushed the host
19621 // context. This information is needed to avoid a stack mismatch.
19622 // Because we're not sure, treat this as a fatal error. We could track
19623 // which phase it fails in, but doesn't seem worth it. At least
19624 // for now.
19625 didFatal = true;
19626 onUncaughtError(thrownValue);
19627 } else {
19628 throwException(root, returnFiber, sourceFiber, thrownValue, nextRenderExpirationTime);
19629 nextUnitOfWork = completeUnitOfWork(sourceFiber);
19630 continue;
19631 }
19632 }
19633 }
19634 break;
19635 } while (true);
19636
19637 if (enableSchedulerTracing) {
19638 // Traced work is done for now; restore the previous interactions.
19639 __interactionsRef.current = prevInteractions;
19640 }
19641
19642 // We're done performing work. Time to clean up.
19643 isWorking = false;
19644 ReactCurrentDispatcher.current = previousDispatcher;
19645 resetContextDependences();
19646 resetHooks();
19647
19648 // Yield back to main thread.
19649 if (didFatal) {
19650 var _didCompleteRoot = false;
19651 stopWorkLoopTimer(interruptedBy, _didCompleteRoot);
19652 interruptedBy = null;
19653 // There was a fatal error.
19654 {
19655 resetStackAfterFatalErrorInDev();
19656 }
19657 // `nextRoot` points to the in-progress root. A non-null value indicates
19658 // that we're in the middle of an async render. Set it to null to indicate
19659 // there's no more work to be done in the current batch.
19660 nextRoot = null;
19661 onFatal(root);
19662 return;
19663 }
19664
19665 if (nextUnitOfWork !== null) {
19666 // There's still remaining async work in this tree, but we ran out of time
19667 // in the current frame. Yield back to the renderer. Unless we're
19668 // interrupted by a higher priority update, we'll continue later from where
19669 // we left off.
19670 var _didCompleteRoot2 = false;
19671 stopWorkLoopTimer(interruptedBy, _didCompleteRoot2);
19672 interruptedBy = null;
19673 onYield(root);
19674 return;
19675 }
19676
19677 // We completed the whole tree.
19678 var didCompleteRoot = true;
19679 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
19680 var rootWorkInProgress = root.current.alternate;
19681 !(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;
19682
19683 // `nextRoot` points to the in-progress root. A non-null value indicates
19684 // that we're in the middle of an async render. Set it to null to indicate
19685 // there's no more work to be done in the current batch.
19686 nextRoot = null;
19687 interruptedBy = null;
19688
19689 if (nextRenderDidError) {
19690 // There was an error
19691 if (hasLowerPriorityWork(root, expirationTime)) {
19692 // There's lower priority work. If so, it may have the effect of fixing
19693 // the exception that was just thrown. Exit without committing. This is
19694 // similar to a suspend, but without a timeout because we're not waiting
19695 // for a promise to resolve. React will restart at the lower
19696 // priority level.
19697 markSuspendedPriorityLevel(root, expirationTime);
19698 var suspendedExpirationTime = expirationTime;
19699 var rootExpirationTime = root.expirationTime;
19700 onSuspend(root, rootWorkInProgress, suspendedExpirationTime, rootExpirationTime, -1 // Indicates no timeout
19701 );
19702 return;
19703 } else if (
19704 // There's no lower priority work, but we're rendering asynchronously.
19705 // Synchronously attempt to render the same level one more time. This is
19706 // similar to a suspend, but without a timeout because we're not waiting
19707 // for a promise to resolve.
19708 !root.didError && isYieldy) {
19709 root.didError = true;
19710 var _suspendedExpirationTime = root.nextExpirationTimeToWorkOn = expirationTime;
19711 var _rootExpirationTime = root.expirationTime = Sync;
19712 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime, _rootExpirationTime, -1 // Indicates no timeout
19713 );
19714 return;
19715 }
19716 }
19717
19718 if (isYieldy && nextLatestAbsoluteTimeoutMs !== -1) {
19719 // The tree was suspended.
19720 var _suspendedExpirationTime2 = expirationTime;
19721 markSuspendedPriorityLevel(root, _suspendedExpirationTime2);
19722
19723 // Find the earliest uncommitted expiration time in the tree, including
19724 // work that is suspended. The timeout threshold cannot be longer than
19725 // the overall expiration.
19726 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, expirationTime);
19727 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
19728 if (earliestExpirationTimeMs < nextLatestAbsoluteTimeoutMs) {
19729 nextLatestAbsoluteTimeoutMs = earliestExpirationTimeMs;
19730 }
19731
19732 // Subtract the current time from the absolute timeout to get the number
19733 // of milliseconds until the timeout. In other words, convert an absolute
19734 // timestamp to a relative time. This is the value that is passed
19735 // to `setTimeout`.
19736 var currentTimeMs = expirationTimeToMs(requestCurrentTime());
19737 var msUntilTimeout = nextLatestAbsoluteTimeoutMs - currentTimeMs;
19738 msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout;
19739
19740 // TODO: Account for the Just Noticeable Difference
19741
19742 var _rootExpirationTime2 = root.expirationTime;
19743 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime2, _rootExpirationTime2, msUntilTimeout);
19744 return;
19745 }
19746
19747 // Ready to commit.
19748 onComplete(root, rootWorkInProgress, expirationTime);
19749}
19750
19751function captureCommitPhaseError(sourceFiber, value) {
19752 var expirationTime = Sync;
19753 var fiber = sourceFiber.return;
19754 while (fiber !== null) {
19755 switch (fiber.tag) {
19756 case ClassComponent:
19757 var ctor = fiber.type;
19758 var instance = fiber.stateNode;
19759 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
19760 var errorInfo = createCapturedValue(value, sourceFiber);
19761 var update = createClassErrorUpdate(fiber, errorInfo, expirationTime);
19762 enqueueUpdate(fiber, update);
19763 scheduleWork(fiber, expirationTime);
19764 return;
19765 }
19766 break;
19767 case HostRoot:
19768 {
19769 var _errorInfo = createCapturedValue(value, sourceFiber);
19770 var _update = createRootErrorUpdate(fiber, _errorInfo, expirationTime);
19771 enqueueUpdate(fiber, _update);
19772 scheduleWork(fiber, expirationTime);
19773 return;
19774 }
19775 }
19776 fiber = fiber.return;
19777 }
19778
19779 if (sourceFiber.tag === HostRoot) {
19780 // Error was thrown at the root. There is no parent, so the root
19781 // itself should capture it.
19782 var rootFiber = sourceFiber;
19783 var _errorInfo2 = createCapturedValue(value, rootFiber);
19784 var _update2 = createRootErrorUpdate(rootFiber, _errorInfo2, expirationTime);
19785 enqueueUpdate(rootFiber, _update2);
19786 scheduleWork(rootFiber, expirationTime);
19787 }
19788}
19789
19790function computeThreadID(expirationTime, interactionThreadID) {
19791 // Interaction threads are unique per root and expiration time.
19792 return expirationTime * 1000 + interactionThreadID;
19793}
19794
19795// Creates a unique async expiration time.
19796function computeUniqueAsyncExpiration() {
19797 var currentTime = requestCurrentTime();
19798 var result = computeAsyncExpiration(currentTime);
19799 if (result >= lastUniqueAsyncExpiration) {
19800 // Since we assume the current time monotonically increases, we only hit
19801 // this branch when computeUniqueAsyncExpiration is fired multiple times
19802 // within a 200ms window (or whatever the async bucket size is).
19803 result = lastUniqueAsyncExpiration - 1;
19804 }
19805 lastUniqueAsyncExpiration = result;
19806 return lastUniqueAsyncExpiration;
19807}
19808
19809function computeExpirationForFiber(currentTime, fiber) {
19810 var priorityLevel = unstable_getCurrentPriorityLevel();
19811
19812 var expirationTime = void 0;
19813 if ((fiber.mode & ConcurrentMode) === NoContext) {
19814 // Outside of concurrent mode, updates are always synchronous.
19815 expirationTime = Sync;
19816 } else if (isWorking && !isCommitting$1) {
19817 // During render phase, updates expire during as the current render.
19818 expirationTime = nextRenderExpirationTime;
19819 } else {
19820 switch (priorityLevel) {
19821 case unstable_ImmediatePriority:
19822 expirationTime = Sync;
19823 break;
19824 case unstable_UserBlockingPriority:
19825 expirationTime = computeInteractiveExpiration(currentTime);
19826 break;
19827 case unstable_NormalPriority:
19828 // This is a normal, concurrent update
19829 expirationTime = computeAsyncExpiration(currentTime);
19830 break;
19831 case unstable_LowPriority:
19832 case unstable_IdlePriority:
19833 expirationTime = Never;
19834 break;
19835 default:
19836 invariant(false, 'Unknown priority level. This error is likely caused by a bug in React. Please file an issue.');
19837 }
19838
19839 // If we're in the middle of rendering a tree, do not update at the same
19840 // expiration time that is already rendering.
19841 if (nextRoot !== null && expirationTime === nextRenderExpirationTime) {
19842 expirationTime -= 1;
19843 }
19844 }
19845
19846 // Keep track of the lowest pending interactive expiration time. This
19847 // allows us to synchronously flush all interactive updates
19848 // when needed.
19849 // TODO: Move this to renderer?
19850 if (priorityLevel === unstable_UserBlockingPriority && (lowestPriorityPendingInteractiveExpirationTime === NoWork || expirationTime < lowestPriorityPendingInteractiveExpirationTime)) {
19851 lowestPriorityPendingInteractiveExpirationTime = expirationTime;
19852 }
19853
19854 return expirationTime;
19855}
19856
19857function renderDidSuspend(root, absoluteTimeoutMs, suspendedTime) {
19858 // Schedule the timeout.
19859 if (absoluteTimeoutMs >= 0 && nextLatestAbsoluteTimeoutMs < absoluteTimeoutMs) {
19860 nextLatestAbsoluteTimeoutMs = absoluteTimeoutMs;
19861 }
19862}
19863
19864function renderDidError() {
19865 nextRenderDidError = true;
19866}
19867
19868function pingSuspendedRoot(root, thenable, pingTime) {
19869 // A promise that previously suspended React from committing has resolved.
19870 // If React is still suspended, try again at the previous level (pingTime).
19871
19872 var pingCache = root.pingCache;
19873 if (pingCache !== null) {
19874 // The thenable resolved, so we no longer need to memoize, because it will
19875 // never be thrown again.
19876 pingCache.delete(thenable);
19877 }
19878
19879 if (nextRoot !== null && nextRenderExpirationTime === pingTime) {
19880 // Received a ping at the same priority level at which we're currently
19881 // rendering. Restart from the root.
19882 nextRoot = null;
19883 } else {
19884 // Confirm that the root is still suspended at this level. Otherwise exit.
19885 if (isPriorityLevelSuspended(root, pingTime)) {
19886 // Ping at the original level
19887 markPingedPriorityLevel(root, pingTime);
19888 var rootExpirationTime = root.expirationTime;
19889 if (rootExpirationTime !== NoWork) {
19890 requestWork(root, rootExpirationTime);
19891 }
19892 }
19893 }
19894}
19895
19896function retryTimedOutBoundary(boundaryFiber, thenable) {
19897 // The boundary fiber (a Suspense component) previously timed out and was
19898 // rendered in its fallback state. One of the promises that suspended it has
19899 // resolved, which means at least part of the tree was likely unblocked. Try
19900 var retryCache = void 0;
19901 if (enableSuspenseServerRenderer) {
19902 switch (boundaryFiber.tag) {
19903 case SuspenseComponent:
19904 retryCache = boundaryFiber.stateNode;
19905 break;
19906 case DehydratedSuspenseComponent:
19907 retryCache = boundaryFiber.memoizedState;
19908 break;
19909 default:
19910 invariant(false, 'Pinged unknown suspense boundary type. This is probably a bug in React.');
19911 }
19912 } else {
19913 retryCache = boundaryFiber.stateNode;
19914 }
19915 if (retryCache !== null) {
19916 // The thenable resolved, so we no longer need to memoize, because it will
19917 // never be thrown again.
19918 retryCache.delete(thenable);
19919 }
19920
19921 var currentTime = requestCurrentTime();
19922 var retryTime = computeExpirationForFiber(currentTime, boundaryFiber);
19923 var root = scheduleWorkToRoot(boundaryFiber, retryTime);
19924 if (root !== null) {
19925 markPendingPriorityLevel(root, retryTime);
19926 var rootExpirationTime = root.expirationTime;
19927 if (rootExpirationTime !== NoWork) {
19928 requestWork(root, rootExpirationTime);
19929 }
19930 }
19931}
19932
19933function scheduleWorkToRoot(fiber, expirationTime) {
19934 recordScheduleUpdate();
19935
19936 {
19937 if (fiber.tag === ClassComponent) {
19938 var instance = fiber.stateNode;
19939 warnAboutInvalidUpdates(instance);
19940 }
19941 }
19942
19943 // Update the source fiber's expiration time
19944 if (fiber.expirationTime < expirationTime) {
19945 fiber.expirationTime = expirationTime;
19946 }
19947 var alternate = fiber.alternate;
19948 if (alternate !== null && alternate.expirationTime < expirationTime) {
19949 alternate.expirationTime = expirationTime;
19950 }
19951 // Walk the parent path to the root and update the child expiration time.
19952 var node = fiber.return;
19953 var root = null;
19954 if (node === null && fiber.tag === HostRoot) {
19955 root = fiber.stateNode;
19956 } else {
19957 while (node !== null) {
19958 alternate = node.alternate;
19959 if (node.childExpirationTime < expirationTime) {
19960 node.childExpirationTime = expirationTime;
19961 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
19962 alternate.childExpirationTime = expirationTime;
19963 }
19964 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
19965 alternate.childExpirationTime = expirationTime;
19966 }
19967 if (node.return === null && node.tag === HostRoot) {
19968 root = node.stateNode;
19969 break;
19970 }
19971 node = node.return;
19972 }
19973 }
19974
19975 if (enableSchedulerTracing) {
19976 if (root !== null) {
19977 var interactions = __interactionsRef.current;
19978 if (interactions.size > 0) {
19979 var pendingInteractionMap = root.pendingInteractionMap;
19980 var pendingInteractions = pendingInteractionMap.get(expirationTime);
19981 if (pendingInteractions != null) {
19982 interactions.forEach(function (interaction) {
19983 if (!pendingInteractions.has(interaction)) {
19984 // Update the pending async work count for previously unscheduled interaction.
19985 interaction.__count++;
19986 }
19987
19988 pendingInteractions.add(interaction);
19989 });
19990 } else {
19991 pendingInteractionMap.set(expirationTime, new Set(interactions));
19992
19993 // Update the pending async work count for the current interactions.
19994 interactions.forEach(function (interaction) {
19995 interaction.__count++;
19996 });
19997 }
19998
19999 var subscriber = __subscriberRef.current;
20000 if (subscriber !== null) {
20001 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
20002 subscriber.onWorkScheduled(interactions, threadID);
20003 }
20004 }
20005 }
20006 }
20007 return root;
20008}
20009
20010function warnIfNotCurrentlyBatchingInDev(fiber) {
20011 {
20012 if (isRendering === false && isBatchingUpdates === false) {
20013 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));
20014 }
20015 }
20016}
20017
20018function scheduleWork(fiber, expirationTime) {
20019 var root = scheduleWorkToRoot(fiber, expirationTime);
20020 if (root === null) {
20021 {
20022 switch (fiber.tag) {
20023 case ClassComponent:
20024 warnAboutUpdateOnUnmounted(fiber, true);
20025 break;
20026 case FunctionComponent:
20027 case ForwardRef:
20028 case MemoComponent:
20029 case SimpleMemoComponent:
20030 warnAboutUpdateOnUnmounted(fiber, false);
20031 break;
20032 }
20033 }
20034 return;
20035 }
20036
20037 if (!isWorking && nextRenderExpirationTime !== NoWork && expirationTime > nextRenderExpirationTime) {
20038 // This is an interruption. (Used for performance tracking.)
20039 interruptedBy = fiber;
20040 resetStack();
20041 }
20042 markPendingPriorityLevel(root, expirationTime);
20043 if (
20044 // If we're in the render phase, we don't need to schedule this root
20045 // for an update, because we'll do it before we exit...
20046 !isWorking || isCommitting$1 ||
20047 // ...unless this is a different root than the one we're rendering.
20048 nextRoot !== root) {
20049 var rootExpirationTime = root.expirationTime;
20050 requestWork(root, rootExpirationTime);
20051 }
20052 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
20053 // Reset this back to zero so subsequent updates don't throw.
20054 nestedUpdateCount = 0;
20055 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.');
20056 }
20057}
20058
20059function syncUpdates(fn, a, b, c, d) {
20060 return unstable_runWithPriority(unstable_ImmediatePriority, function () {
20061 return fn(a, b, c, d);
20062 });
20063}
20064
20065// TODO: Everything below this is written as if it has been lifted to the
20066// renderers. I'll do this in a follow-up.
20067
20068// Linked-list of roots
20069var firstScheduledRoot = null;
20070var lastScheduledRoot = null;
20071
20072var callbackExpirationTime = NoWork;
20073var callbackID = void 0;
20074var isRendering = false;
20075var nextFlushedRoot = null;
20076var nextFlushedExpirationTime = NoWork;
20077var lowestPriorityPendingInteractiveExpirationTime = NoWork;
20078var hasUnhandledError = false;
20079var unhandledError = null;
20080
20081var isBatchingUpdates = false;
20082var isUnbatchingUpdates = false;
20083
20084var completedBatches = null;
20085
20086var originalStartTimeMs = unstable_now();
20087var currentRendererTime = msToExpirationTime(originalStartTimeMs);
20088var currentSchedulerTime = currentRendererTime;
20089
20090// Use these to prevent an infinite loop of nested updates
20091var NESTED_UPDATE_LIMIT = 50;
20092var nestedUpdateCount = 0;
20093var lastCommittedRootDuringThisBatch = null;
20094
20095function recomputeCurrentRendererTime() {
20096 var currentTimeMs = unstable_now() - originalStartTimeMs;
20097 currentRendererTime = msToExpirationTime(currentTimeMs);
20098}
20099
20100function scheduleCallbackWithExpirationTime(root, expirationTime) {
20101 if (callbackExpirationTime !== NoWork) {
20102 // A callback is already scheduled. Check its expiration time (timeout).
20103 if (expirationTime < callbackExpirationTime) {
20104 // Existing callback has sufficient timeout. Exit.
20105 return;
20106 } else {
20107 if (callbackID !== null) {
20108 // Existing callback has insufficient timeout. Cancel and schedule a
20109 // new one.
20110 unstable_cancelCallback(callbackID);
20111 }
20112 }
20113 // The request callback timer is already running. Don't start a new one.
20114 } else {
20115 startRequestCallbackTimer();
20116 }
20117
20118 callbackExpirationTime = expirationTime;
20119 var currentMs = unstable_now() - originalStartTimeMs;
20120 var expirationTimeMs = expirationTimeToMs(expirationTime);
20121 var timeout = expirationTimeMs - currentMs;
20122 callbackID = unstable_scheduleCallback(performAsyncWork, { timeout: timeout });
20123}
20124
20125// For every call to renderRoot, one of onFatal, onComplete, onSuspend, and
20126// onYield is called upon exiting. We use these in lieu of returning a tuple.
20127// I've also chosen not to inline them into renderRoot because these will
20128// eventually be lifted into the renderer.
20129function onFatal(root) {
20130 root.finishedWork = null;
20131}
20132
20133function onComplete(root, finishedWork, expirationTime) {
20134 root.pendingCommitExpirationTime = expirationTime;
20135 root.finishedWork = finishedWork;
20136}
20137
20138function onSuspend(root, finishedWork, suspendedExpirationTime, rootExpirationTime, msUntilTimeout) {
20139 root.expirationTime = rootExpirationTime;
20140 if (msUntilTimeout === 0 && !shouldYieldToRenderer()) {
20141 // Don't wait an additional tick. Commit the tree immediately.
20142 root.pendingCommitExpirationTime = suspendedExpirationTime;
20143 root.finishedWork = finishedWork;
20144 } else if (msUntilTimeout > 0) {
20145 // Wait `msUntilTimeout` milliseconds before committing.
20146 root.timeoutHandle = scheduleTimeout(onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), msUntilTimeout);
20147 }
20148}
20149
20150function onYield(root) {
20151 root.finishedWork = null;
20152}
20153
20154function onTimeout(root, finishedWork, suspendedExpirationTime) {
20155 // The root timed out. Commit it.
20156 root.pendingCommitExpirationTime = suspendedExpirationTime;
20157 root.finishedWork = finishedWork;
20158 // Read the current time before entering the commit phase. We can be
20159 // certain this won't cause tearing related to batching of event updates
20160 // because we're at the top of a timer event.
20161 recomputeCurrentRendererTime();
20162 currentSchedulerTime = currentRendererTime;
20163 flushRoot(root, suspendedExpirationTime);
20164}
20165
20166function onCommit(root, expirationTime) {
20167 root.expirationTime = expirationTime;
20168 root.finishedWork = null;
20169}
20170
20171function requestCurrentTime() {
20172 // requestCurrentTime is called by the scheduler to compute an expiration
20173 // time.
20174 //
20175 // Expiration times are computed by adding to the current time (the start
20176 // time). However, if two updates are scheduled within the same event, we
20177 // should treat their start times as simultaneous, even if the actual clock
20178 // time has advanced between the first and second call.
20179
20180 // In other words, because expiration times determine how updates are batched,
20181 // we want all updates of like priority that occur within the same event to
20182 // receive the same expiration time. Otherwise we get tearing.
20183 //
20184 // We keep track of two separate times: the current "renderer" time and the
20185 // current "scheduler" time. The renderer time can be updated whenever; it
20186 // only exists to minimize the calls performance.now.
20187 //
20188 // But the scheduler time can only be updated if there's no pending work, or
20189 // if we know for certain that we're not in the middle of an event.
20190
20191 if (isRendering) {
20192 // We're already rendering. Return the most recently read time.
20193 return currentSchedulerTime;
20194 }
20195 // Check if there's pending work.
20196 findHighestPriorityRoot();
20197 if (nextFlushedExpirationTime === NoWork || nextFlushedExpirationTime === Never) {
20198 // If there's no pending work, or if the pending work is offscreen, we can
20199 // read the current time without risk of tearing.
20200 recomputeCurrentRendererTime();
20201 currentSchedulerTime = currentRendererTime;
20202 return currentSchedulerTime;
20203 }
20204 // There's already pending work. We might be in the middle of a browser
20205 // event. If we were to read the current time, it could cause multiple updates
20206 // within the same event to receive different expiration times, leading to
20207 // tearing. Return the last read time. During the next idle callback, the
20208 // time will be updated.
20209 return currentSchedulerTime;
20210}
20211
20212// requestWork is called by the scheduler whenever a root receives an update.
20213// It's up to the renderer to call renderRoot at some point in the future.
20214function requestWork(root, expirationTime) {
20215 addRootToSchedule(root, expirationTime);
20216 if (isRendering) {
20217 // Prevent reentrancy. Remaining work will be scheduled at the end of
20218 // the currently rendering batch.
20219 return;
20220 }
20221
20222 if (isBatchingUpdates) {
20223 // Flush work at the end of the batch.
20224 if (isUnbatchingUpdates) {
20225 // ...unless we're inside unbatchedUpdates, in which case we should
20226 // flush it now.
20227 nextFlushedRoot = root;
20228 nextFlushedExpirationTime = Sync;
20229 performWorkOnRoot(root, Sync, false);
20230 }
20231 return;
20232 }
20233
20234 // TODO: Get rid of Sync and use current time?
20235 if (expirationTime === Sync) {
20236 performSyncWork();
20237 } else {
20238 scheduleCallbackWithExpirationTime(root, expirationTime);
20239 }
20240}
20241
20242function addRootToSchedule(root, expirationTime) {
20243 // Add the root to the schedule.
20244 // Check if this root is already part of the schedule.
20245 if (root.nextScheduledRoot === null) {
20246 // This root is not already scheduled. Add it.
20247 root.expirationTime = expirationTime;
20248 if (lastScheduledRoot === null) {
20249 firstScheduledRoot = lastScheduledRoot = root;
20250 root.nextScheduledRoot = root;
20251 } else {
20252 lastScheduledRoot.nextScheduledRoot = root;
20253 lastScheduledRoot = root;
20254 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
20255 }
20256 } else {
20257 // This root is already scheduled, but its priority may have increased.
20258 var remainingExpirationTime = root.expirationTime;
20259 if (expirationTime > remainingExpirationTime) {
20260 // Update the priority.
20261 root.expirationTime = expirationTime;
20262 }
20263 }
20264}
20265
20266function findHighestPriorityRoot() {
20267 var highestPriorityWork = NoWork;
20268 var highestPriorityRoot = null;
20269 if (lastScheduledRoot !== null) {
20270 var previousScheduledRoot = lastScheduledRoot;
20271 var root = firstScheduledRoot;
20272 while (root !== null) {
20273 var remainingExpirationTime = root.expirationTime;
20274 if (remainingExpirationTime === NoWork) {
20275 // This root no longer has work. Remove it from the scheduler.
20276
20277 // TODO: This check is redudant, but Flow is confused by the branch
20278 // below where we set lastScheduledRoot to null, even though we break
20279 // from the loop right after.
20280 !(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;
20281 if (root === root.nextScheduledRoot) {
20282 // This is the only root in the list.
20283 root.nextScheduledRoot = null;
20284 firstScheduledRoot = lastScheduledRoot = null;
20285 break;
20286 } else if (root === firstScheduledRoot) {
20287 // This is the first root in the list.
20288 var next = root.nextScheduledRoot;
20289 firstScheduledRoot = next;
20290 lastScheduledRoot.nextScheduledRoot = next;
20291 root.nextScheduledRoot = null;
20292 } else if (root === lastScheduledRoot) {
20293 // This is the last root in the list.
20294 lastScheduledRoot = previousScheduledRoot;
20295 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
20296 root.nextScheduledRoot = null;
20297 break;
20298 } else {
20299 previousScheduledRoot.nextScheduledRoot = root.nextScheduledRoot;
20300 root.nextScheduledRoot = null;
20301 }
20302 root = previousScheduledRoot.nextScheduledRoot;
20303 } else {
20304 if (remainingExpirationTime > highestPriorityWork) {
20305 // Update the priority, if it's higher
20306 highestPriorityWork = remainingExpirationTime;
20307 highestPriorityRoot = root;
20308 }
20309 if (root === lastScheduledRoot) {
20310 break;
20311 }
20312 if (highestPriorityWork === Sync) {
20313 // Sync is highest priority by definition so
20314 // we can stop searching.
20315 break;
20316 }
20317 previousScheduledRoot = root;
20318 root = root.nextScheduledRoot;
20319 }
20320 }
20321 }
20322
20323 nextFlushedRoot = highestPriorityRoot;
20324 nextFlushedExpirationTime = highestPriorityWork;
20325}
20326
20327// TODO: This wrapper exists because many of the older tests (the ones that use
20328// flushDeferredPri) rely on the number of times `shouldYield` is called. We
20329// should get rid of it.
20330var didYield = false;
20331function shouldYieldToRenderer() {
20332 if (didYield) {
20333 return true;
20334 }
20335 if (unstable_shouldYield()) {
20336 didYield = true;
20337 return true;
20338 }
20339 return false;
20340}
20341
20342function performAsyncWork() {
20343 try {
20344 if (!shouldYieldToRenderer()) {
20345 // The callback timed out. That means at least one update has expired.
20346 // Iterate through the root schedule. If they contain expired work, set
20347 // the next render expiration time to the current time. This has the effect
20348 // of flushing all expired work in a single batch, instead of flushing each
20349 // level one at a time.
20350 if (firstScheduledRoot !== null) {
20351 recomputeCurrentRendererTime();
20352 var root = firstScheduledRoot;
20353 do {
20354 didExpireAtExpirationTime(root, currentRendererTime);
20355 // The root schedule is circular, so this is never null.
20356 root = root.nextScheduledRoot;
20357 } while (root !== firstScheduledRoot);
20358 }
20359 }
20360 performWork(NoWork, true);
20361 } finally {
20362 didYield = false;
20363 }
20364}
20365
20366function performSyncWork() {
20367 performWork(Sync, false);
20368}
20369
20370function performWork(minExpirationTime, isYieldy) {
20371 // Keep working on roots until there's no more work, or until there's a higher
20372 // priority event.
20373 findHighestPriorityRoot();
20374
20375 if (isYieldy) {
20376 recomputeCurrentRendererTime();
20377 currentSchedulerTime = currentRendererTime;
20378
20379 if (enableUserTimingAPI) {
20380 var didExpire = nextFlushedExpirationTime > currentRendererTime;
20381 var timeout = expirationTimeToMs(nextFlushedExpirationTime);
20382 stopRequestCallbackTimer(didExpire, timeout);
20383 }
20384
20385 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime && !(didYield && currentRendererTime > nextFlushedExpirationTime)) {
20386 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, currentRendererTime > nextFlushedExpirationTime);
20387 findHighestPriorityRoot();
20388 recomputeCurrentRendererTime();
20389 currentSchedulerTime = currentRendererTime;
20390 }
20391 } else {
20392 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime) {
20393 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false);
20394 findHighestPriorityRoot();
20395 }
20396 }
20397
20398 // We're done flushing work. Either we ran out of time in this callback,
20399 // or there's no more work left with sufficient priority.
20400
20401 // If we're inside a callback, set this to false since we just completed it.
20402 if (isYieldy) {
20403 callbackExpirationTime = NoWork;
20404 callbackID = null;
20405 }
20406 // If there's work left over, schedule a new callback.
20407 if (nextFlushedExpirationTime !== NoWork) {
20408 scheduleCallbackWithExpirationTime(nextFlushedRoot, nextFlushedExpirationTime);
20409 }
20410
20411 // Clean-up.
20412 finishRendering();
20413}
20414
20415function flushRoot(root, expirationTime) {
20416 !!isRendering ? invariant(false, 'work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.') : void 0;
20417 // Perform work on root as if the given expiration time is the current time.
20418 // This has the effect of synchronously flushing all work up to and
20419 // including the given time.
20420 nextFlushedRoot = root;
20421 nextFlushedExpirationTime = expirationTime;
20422 performWorkOnRoot(root, expirationTime, false);
20423 // Flush any sync work that was scheduled by lifecycles
20424 performSyncWork();
20425}
20426
20427function finishRendering() {
20428 nestedUpdateCount = 0;
20429 lastCommittedRootDuringThisBatch = null;
20430
20431 if (completedBatches !== null) {
20432 var batches = completedBatches;
20433 completedBatches = null;
20434 for (var i = 0; i < batches.length; i++) {
20435 var batch = batches[i];
20436 try {
20437 batch._onComplete();
20438 } catch (error) {
20439 if (!hasUnhandledError) {
20440 hasUnhandledError = true;
20441 unhandledError = error;
20442 }
20443 }
20444 }
20445 }
20446
20447 if (hasUnhandledError) {
20448 var error = unhandledError;
20449 unhandledError = null;
20450 hasUnhandledError = false;
20451 throw error;
20452 }
20453}
20454
20455function performWorkOnRoot(root, expirationTime, isYieldy) {
20456 !!isRendering ? invariant(false, 'performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;
20457
20458 isRendering = true;
20459
20460 // Check if this is async work or sync/expired work.
20461 if (!isYieldy) {
20462 // Flush work without yielding.
20463 // TODO: Non-yieldy work does not necessarily imply expired work. A renderer
20464 // may want to perform some work without yielding, but also without
20465 // requiring the root to complete (by triggering placeholders).
20466
20467 var finishedWork = root.finishedWork;
20468 if (finishedWork !== null) {
20469 // This root is already complete. We can commit it.
20470 completeRoot(root, finishedWork, expirationTime);
20471 } else {
20472 root.finishedWork = null;
20473 // If this root previously suspended, clear its existing timeout, since
20474 // we're about to try rendering again.
20475 var timeoutHandle = root.timeoutHandle;
20476 if (timeoutHandle !== noTimeout) {
20477 root.timeoutHandle = noTimeout;
20478 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
20479 cancelTimeout(timeoutHandle);
20480 }
20481 renderRoot(root, isYieldy);
20482 finishedWork = root.finishedWork;
20483 if (finishedWork !== null) {
20484 // We've completed the root. Commit it.
20485 completeRoot(root, finishedWork, expirationTime);
20486 }
20487 }
20488 } else {
20489 // Flush async work.
20490 var _finishedWork = root.finishedWork;
20491 if (_finishedWork !== null) {
20492 // This root is already complete. We can commit it.
20493 completeRoot(root, _finishedWork, expirationTime);
20494 } else {
20495 root.finishedWork = null;
20496 // If this root previously suspended, clear its existing timeout, since
20497 // we're about to try rendering again.
20498 var _timeoutHandle = root.timeoutHandle;
20499 if (_timeoutHandle !== noTimeout) {
20500 root.timeoutHandle = noTimeout;
20501 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
20502 cancelTimeout(_timeoutHandle);
20503 }
20504 renderRoot(root, isYieldy);
20505 _finishedWork = root.finishedWork;
20506 if (_finishedWork !== null) {
20507 // We've completed the root. Check the if we should yield one more time
20508 // before committing.
20509 if (!shouldYieldToRenderer()) {
20510 // Still time left. Commit the root.
20511 completeRoot(root, _finishedWork, expirationTime);
20512 } else {
20513 // There's no time left. Mark this root as complete. We'll come
20514 // back and commit it later.
20515 root.finishedWork = _finishedWork;
20516 }
20517 }
20518 }
20519 }
20520
20521 isRendering = false;
20522}
20523
20524function completeRoot(root, finishedWork, expirationTime) {
20525 // Check if there's a batch that matches this expiration time.
20526 var firstBatch = root.firstBatch;
20527 if (firstBatch !== null && firstBatch._expirationTime >= expirationTime) {
20528 if (completedBatches === null) {
20529 completedBatches = [firstBatch];
20530 } else {
20531 completedBatches.push(firstBatch);
20532 }
20533 if (firstBatch._defer) {
20534 // This root is blocked from committing by a batch. Unschedule it until
20535 // we receive another update.
20536 root.finishedWork = finishedWork;
20537 root.expirationTime = NoWork;
20538 return;
20539 }
20540 }
20541
20542 // Commit the root.
20543 root.finishedWork = null;
20544
20545 // Check if this is a nested update (a sync update scheduled during the
20546 // commit phase).
20547 if (root === lastCommittedRootDuringThisBatch) {
20548 // If the next root is the same as the previous root, this is a nested
20549 // update. To prevent an infinite loop, increment the nested update count.
20550 nestedUpdateCount++;
20551 } else {
20552 // Reset whenever we switch roots.
20553 lastCommittedRootDuringThisBatch = root;
20554 nestedUpdateCount = 0;
20555 }
20556 unstable_runWithPriority(unstable_ImmediatePriority, function () {
20557 commitRoot(root, finishedWork);
20558 });
20559}
20560
20561function onUncaughtError(error) {
20562 !(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;
20563 // Unschedule this root so we don't work on it again until there's
20564 // another update.
20565 nextFlushedRoot.expirationTime = NoWork;
20566 if (!hasUnhandledError) {
20567 hasUnhandledError = true;
20568 unhandledError = error;
20569 }
20570}
20571
20572// TODO: Batching should be implemented at the renderer level, not inside
20573// the reconciler.
20574function batchedUpdates$1(fn, a) {
20575 var previousIsBatchingUpdates = isBatchingUpdates;
20576 isBatchingUpdates = true;
20577 try {
20578 return fn(a);
20579 } finally {
20580 isBatchingUpdates = previousIsBatchingUpdates;
20581 if (!isBatchingUpdates && !isRendering) {
20582 performSyncWork();
20583 }
20584 }
20585}
20586
20587// TODO: Batching should be implemented at the renderer level, not inside
20588// the reconciler.
20589function unbatchedUpdates(fn, a) {
20590 if (isBatchingUpdates && !isUnbatchingUpdates) {
20591 isUnbatchingUpdates = true;
20592 try {
20593 return fn(a);
20594 } finally {
20595 isUnbatchingUpdates = false;
20596 }
20597 }
20598 return fn(a);
20599}
20600
20601// TODO: Batching should be implemented at the renderer level, not within
20602// the reconciler.
20603function flushSync(fn, a) {
20604 !!isRendering ? invariant(false, 'flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.') : void 0;
20605 var previousIsBatchingUpdates = isBatchingUpdates;
20606 isBatchingUpdates = true;
20607 try {
20608 return syncUpdates(fn, a);
20609 } finally {
20610 isBatchingUpdates = previousIsBatchingUpdates;
20611 performSyncWork();
20612 }
20613}
20614
20615function interactiveUpdates$1(fn, a, b) {
20616 // If there are any pending interactive updates, synchronously flush them.
20617 // This needs to happen before we read any handlers, because the effect of
20618 // the previous event may influence which handlers are called during
20619 // this event.
20620 if (!isBatchingUpdates && !isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) {
20621 // Synchronously flush pending interactive updates.
20622 performWork(lowestPriorityPendingInteractiveExpirationTime, false);
20623 lowestPriorityPendingInteractiveExpirationTime = NoWork;
20624 }
20625 var previousIsBatchingUpdates = isBatchingUpdates;
20626 isBatchingUpdates = true;
20627 try {
20628 return unstable_runWithPriority(unstable_UserBlockingPriority, function () {
20629 return fn(a, b);
20630 });
20631 } finally {
20632 isBatchingUpdates = previousIsBatchingUpdates;
20633 if (!isBatchingUpdates && !isRendering) {
20634 performSyncWork();
20635 }
20636 }
20637}
20638
20639function flushInteractiveUpdates$1() {
20640 if (!isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) {
20641 // Synchronously flush pending interactive updates.
20642 performWork(lowestPriorityPendingInteractiveExpirationTime, false);
20643 lowestPriorityPendingInteractiveExpirationTime = NoWork;
20644 }
20645}
20646
20647function flushControlled(fn) {
20648 var previousIsBatchingUpdates = isBatchingUpdates;
20649 isBatchingUpdates = true;
20650 try {
20651 syncUpdates(fn);
20652 } finally {
20653 isBatchingUpdates = previousIsBatchingUpdates;
20654 if (!isBatchingUpdates && !isRendering) {
20655 performSyncWork();
20656 }
20657 }
20658}
20659
20660// 0 is PROD, 1 is DEV.
20661// Might add PROFILE later.
20662
20663
20664var didWarnAboutNestedUpdates = void 0;
20665var didWarnAboutFindNodeInStrictMode = void 0;
20666
20667{
20668 didWarnAboutNestedUpdates = false;
20669 didWarnAboutFindNodeInStrictMode = {};
20670}
20671
20672function getContextForSubtree(parentComponent) {
20673 if (!parentComponent) {
20674 return emptyContextObject;
20675 }
20676
20677 var fiber = get(parentComponent);
20678 var parentContext = findCurrentUnmaskedContext(fiber);
20679
20680 if (fiber.tag === ClassComponent) {
20681 var Component = fiber.type;
20682 if (isContextProvider(Component)) {
20683 return processChildContext(fiber, Component, parentContext);
20684 }
20685 }
20686
20687 return parentContext;
20688}
20689
20690function scheduleRootUpdate(current$$1, element, expirationTime, callback) {
20691 {
20692 if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) {
20693 didWarnAboutNestedUpdates = true;
20694 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');
20695 }
20696 }
20697
20698 var update = createUpdate(expirationTime);
20699 // Caution: React DevTools currently depends on this property
20700 // being called "element".
20701 update.payload = { element: element };
20702
20703 callback = callback === undefined ? null : callback;
20704 if (callback !== null) {
20705 !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
20706 update.callback = callback;
20707 }
20708
20709 flushPassiveEffects();
20710 enqueueUpdate(current$$1, update);
20711 scheduleWork(current$$1, expirationTime);
20712
20713 return expirationTime;
20714}
20715
20716function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback) {
20717 // TODO: If this is a nested container, this won't be the root.
20718 var current$$1 = container.current;
20719
20720 {
20721 if (ReactFiberInstrumentation_1.debugTool) {
20722 if (current$$1.alternate === null) {
20723 ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
20724 } else if (element === null) {
20725 ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
20726 } else {
20727 ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
20728 }
20729 }
20730 }
20731
20732 var context = getContextForSubtree(parentComponent);
20733 if (container.context === null) {
20734 container.context = context;
20735 } else {
20736 container.pendingContext = context;
20737 }
20738
20739 return scheduleRootUpdate(current$$1, element, expirationTime, callback);
20740}
20741
20742function findHostInstance(component) {
20743 var fiber = get(component);
20744 if (fiber === undefined) {
20745 if (typeof component.render === 'function') {
20746 invariant(false, 'Unable to find node on an unmounted component.');
20747 } else {
20748 invariant(false, 'Argument appears to not be a ReactComponent. Keys: %s', Object.keys(component));
20749 }
20750 }
20751 var hostFiber = findCurrentHostFiber(fiber);
20752 if (hostFiber === null) {
20753 return null;
20754 }
20755 return hostFiber.stateNode;
20756}
20757
20758function findHostInstanceWithWarning(component, methodName) {
20759 {
20760 var fiber = get(component);
20761 if (fiber === undefined) {
20762 if (typeof component.render === 'function') {
20763 invariant(false, 'Unable to find node on an unmounted component.');
20764 } else {
20765 invariant(false, 'Argument appears to not be a ReactComponent. Keys: %s', Object.keys(component));
20766 }
20767 }
20768 var hostFiber = findCurrentHostFiber(fiber);
20769 if (hostFiber === null) {
20770 return null;
20771 }
20772 if (hostFiber.mode & StrictMode) {
20773 var componentName = getComponentName(fiber.type) || 'Component';
20774 if (!didWarnAboutFindNodeInStrictMode[componentName]) {
20775 didWarnAboutFindNodeInStrictMode[componentName] = true;
20776 if (fiber.mode & StrictMode) {
20777 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));
20778 } else {
20779 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));
20780 }
20781 }
20782 }
20783 return hostFiber.stateNode;
20784 }
20785 return findHostInstance(component);
20786}
20787
20788function createContainer(containerInfo, isConcurrent, hydrate) {
20789 return createFiberRoot(containerInfo, isConcurrent, hydrate);
20790}
20791
20792function updateContainer(element, container, parentComponent, callback) {
20793 var current$$1 = container.current;
20794 var currentTime = requestCurrentTime();
20795 var expirationTime = computeExpirationForFiber(currentTime, current$$1);
20796 return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback);
20797}
20798
20799function getPublicRootInstance(container) {
20800 var containerFiber = container.current;
20801 if (!containerFiber.child) {
20802 return null;
20803 }
20804 switch (containerFiber.child.tag) {
20805 case HostComponent:
20806 return getPublicInstance(containerFiber.child.stateNode);
20807 default:
20808 return containerFiber.child.stateNode;
20809 }
20810}
20811
20812function findHostInstanceWithNoPortals(fiber) {
20813 var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
20814 if (hostFiber === null) {
20815 return null;
20816 }
20817 return hostFiber.stateNode;
20818}
20819
20820var overrideProps = null;
20821
20822{
20823 var copyWithSetImpl = function (obj, path, idx, value) {
20824 if (idx >= path.length) {
20825 return value;
20826 }
20827 var key = path[idx];
20828 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
20829 // $FlowFixMe number or string is fine here
20830 updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
20831 return updated;
20832 };
20833
20834 var copyWithSet = function (obj, path, value) {
20835 return copyWithSetImpl(obj, path, 0, value);
20836 };
20837
20838 // Support DevTools props for function components, forwardRef, memo, host components, etc.
20839 overrideProps = function (fiber, path, value) {
20840 flushPassiveEffects();
20841 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
20842 if (fiber.alternate) {
20843 fiber.alternate.pendingProps = fiber.pendingProps;
20844 }
20845 scheduleWork(fiber, Sync);
20846 };
20847}
20848
20849function injectIntoDevTools(devToolsConfig) {
20850 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
20851 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
20852
20853
20854 return injectInternals(_assign({}, devToolsConfig, {
20855 overrideProps: overrideProps,
20856 currentDispatcherRef: ReactCurrentDispatcher,
20857 findHostInstanceByFiber: function (fiber) {
20858 var hostFiber = findCurrentHostFiber(fiber);
20859 if (hostFiber === null) {
20860 return null;
20861 }
20862 return hostFiber.stateNode;
20863 },
20864 findFiberByHostInstance: function (instance) {
20865 if (!findFiberByHostInstance) {
20866 // Might not be implemented by the renderer.
20867 return null;
20868 }
20869 return findFiberByHostInstance(instance);
20870 }
20871 }));
20872}
20873
20874// This file intentionally does *not* have the Flow annotation.
20875// Don't add it. See `./inline-typed.js` for an explanation.
20876
20877function createPortal$1(children, containerInfo,
20878// TODO: figure out the API for cross-renderer implementation.
20879implementation) {
20880 var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
20881
20882 return {
20883 // This tag allow us to uniquely identify this as a React Portal
20884 $$typeof: REACT_PORTAL_TYPE,
20885 key: key == null ? null : '' + key,
20886 children: children,
20887 containerInfo: containerInfo,
20888 implementation: implementation
20889 };
20890}
20891
20892// TODO: this is special because it gets imported during build.
20893
20894var ReactVersion = '16.8.6';
20895
20896// This file is copy paste from ReactDOM with adjusted paths
20897// and a different host config import (react-reconciler/inline.fire).
20898// TODO: real implementation.
20899// console.log('Hello from Fire entry point.');
20900
20901// TODO: This type is shared between the reconciler and ReactDOM, but will
20902// eventually be lifted out to the renderer.
20903
20904var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
20905
20906var topLevelUpdateWarnings = void 0;
20907var warnOnInvalidCallback = void 0;
20908var didWarnAboutUnstableCreatePortal = false;
20909
20910{
20911 if (typeof Map !== 'function' ||
20912 // $FlowIssue Flow incorrectly thinks Map has no prototype
20913 Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' ||
20914 // $FlowIssue Flow incorrectly thinks Set has no prototype
20915 Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
20916 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');
20917 }
20918
20919 topLevelUpdateWarnings = function (container) {
20920 if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
20921 var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
20922 if (hostInstance) {
20923 !(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;
20924 }
20925 }
20926
20927 var isRootRenderedBySomeReact = !!container._reactRootContainer;
20928 var rootEl = getReactRootElementInContainer(container);
20929 var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));
20930
20931 !(!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;
20932
20933 !(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;
20934 };
20935
20936 warnOnInvalidCallback = function (callback, callerName) {
20937 !(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;
20938 };
20939}
20940
20941setRestoreImplementation(restoreControlledState$1);
20942
20943function ReactBatch(root) {
20944 var expirationTime = computeUniqueAsyncExpiration();
20945 this._expirationTime = expirationTime;
20946 this._root = root;
20947 this._next = null;
20948 this._callbacks = null;
20949 this._didComplete = false;
20950 this._hasChildren = false;
20951 this._children = null;
20952 this._defer = true;
20953}
20954ReactBatch.prototype.render = function (children) {
20955 !this._defer ? invariant(false, 'batch.render: Cannot render a batch that already committed.') : void 0;
20956 this._hasChildren = true;
20957 this._children = children;
20958 var internalRoot = this._root._internalRoot;
20959 var expirationTime = this._expirationTime;
20960 var work = new ReactWork();
20961 updateContainerAtExpirationTime(children, internalRoot, null, expirationTime, work._onCommit);
20962 return work;
20963};
20964ReactBatch.prototype.then = function (onComplete) {
20965 if (this._didComplete) {
20966 onComplete();
20967 return;
20968 }
20969 var callbacks = this._callbacks;
20970 if (callbacks === null) {
20971 callbacks = this._callbacks = [];
20972 }
20973 callbacks.push(onComplete);
20974};
20975ReactBatch.prototype.commit = function () {
20976 var internalRoot = this._root._internalRoot;
20977 var firstBatch = internalRoot.firstBatch;
20978 !(this._defer && firstBatch !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0;
20979
20980 if (!this._hasChildren) {
20981 // This batch is empty. Return.
20982 this._next = null;
20983 this._defer = false;
20984 return;
20985 }
20986
20987 var expirationTime = this._expirationTime;
20988
20989 // Ensure this is the first batch in the list.
20990 if (firstBatch !== this) {
20991 // This batch is not the earliest batch. We need to move it to the front.
20992 // Update its expiration time to be the expiration time of the earliest
20993 // batch, so that we can flush it without flushing the other batches.
20994 if (this._hasChildren) {
20995 expirationTime = this._expirationTime = firstBatch._expirationTime;
20996 // Rendering this batch again ensures its children will be the final state
20997 // when we flush (updates are processed in insertion order: last
20998 // update wins).
20999 // TODO: This forces a restart. Should we print a warning?
21000 this.render(this._children);
21001 }
21002
21003 // Remove the batch from the list.
21004 var previous = null;
21005 var batch = firstBatch;
21006 while (batch !== this) {
21007 previous = batch;
21008 batch = batch._next;
21009 }
21010 !(previous !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0;
21011 previous._next = batch._next;
21012
21013 // Add it to the front.
21014 this._next = firstBatch;
21015 firstBatch = internalRoot.firstBatch = this;
21016 }
21017
21018 // Synchronously flush all the work up to this batch's expiration time.
21019 this._defer = false;
21020 flushRoot(internalRoot, expirationTime);
21021
21022 // Pop the batch from the list.
21023 var next = this._next;
21024 this._next = null;
21025 firstBatch = internalRoot.firstBatch = next;
21026
21027 // Append the next earliest batch's children to the update queue.
21028 if (firstBatch !== null && firstBatch._hasChildren) {
21029 firstBatch.render(firstBatch._children);
21030 }
21031};
21032ReactBatch.prototype._onComplete = function () {
21033 if (this._didComplete) {
21034 return;
21035 }
21036 this._didComplete = true;
21037 var callbacks = this._callbacks;
21038 if (callbacks === null) {
21039 return;
21040 }
21041 // TODO: Error handling.
21042 for (var i = 0; i < callbacks.length; i++) {
21043 var _callback = callbacks[i];
21044 _callback();
21045 }
21046};
21047
21048function ReactWork() {
21049 this._callbacks = null;
21050 this._didCommit = false;
21051 // TODO: Avoid need to bind by replacing callbacks in the update queue with
21052 // list of Work objects.
21053 this._onCommit = this._onCommit.bind(this);
21054}
21055ReactWork.prototype.then = function (onCommit) {
21056 if (this._didCommit) {
21057 onCommit();
21058 return;
21059 }
21060 var callbacks = this._callbacks;
21061 if (callbacks === null) {
21062 callbacks = this._callbacks = [];
21063 }
21064 callbacks.push(onCommit);
21065};
21066ReactWork.prototype._onCommit = function () {
21067 if (this._didCommit) {
21068 return;
21069 }
21070 this._didCommit = true;
21071 var callbacks = this._callbacks;
21072 if (callbacks === null) {
21073 return;
21074 }
21075 // TODO: Error handling.
21076 for (var i = 0; i < callbacks.length; i++) {
21077 var _callback2 = callbacks[i];
21078 !(typeof _callback2 === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', _callback2) : void 0;
21079 _callback2();
21080 }
21081};
21082
21083function ReactRoot(container, isConcurrent, hydrate) {
21084 var root = createContainer(container, isConcurrent, hydrate);
21085 this._internalRoot = root;
21086}
21087ReactRoot.prototype.render = function (children, callback) {
21088 var root = this._internalRoot;
21089 var work = new ReactWork();
21090 callback = callback === undefined ? null : callback;
21091 {
21092 warnOnInvalidCallback(callback, 'render');
21093 }
21094 if (callback !== null) {
21095 work.then(callback);
21096 }
21097 updateContainer(children, root, null, work._onCommit);
21098 return work;
21099};
21100ReactRoot.prototype.unmount = function (callback) {
21101 var root = this._internalRoot;
21102 var work = new ReactWork();
21103 callback = callback === undefined ? null : callback;
21104 {
21105 warnOnInvalidCallback(callback, 'render');
21106 }
21107 if (callback !== null) {
21108 work.then(callback);
21109 }
21110 updateContainer(null, root, null, work._onCommit);
21111 return work;
21112};
21113ReactRoot.prototype.legacy_renderSubtreeIntoContainer = function (parentComponent, children, callback) {
21114 var root = this._internalRoot;
21115 var work = new ReactWork();
21116 callback = callback === undefined ? null : callback;
21117 {
21118 warnOnInvalidCallback(callback, 'render');
21119 }
21120 if (callback !== null) {
21121 work.then(callback);
21122 }
21123 updateContainer(children, root, parentComponent, work._onCommit);
21124 return work;
21125};
21126ReactRoot.prototype.createBatch = function () {
21127 var batch = new ReactBatch(this);
21128 var expirationTime = batch._expirationTime;
21129
21130 var internalRoot = this._internalRoot;
21131 var firstBatch = internalRoot.firstBatch;
21132 if (firstBatch === null) {
21133 internalRoot.firstBatch = batch;
21134 batch._next = null;
21135 } else {
21136 // Insert sorted by expiration time then insertion order
21137 var insertAfter = null;
21138 var insertBefore = firstBatch;
21139 while (insertBefore !== null && insertBefore._expirationTime >= expirationTime) {
21140 insertAfter = insertBefore;
21141 insertBefore = insertBefore._next;
21142 }
21143 batch._next = insertBefore;
21144 if (insertAfter !== null) {
21145 insertAfter._next = batch;
21146 }
21147 }
21148
21149 return batch;
21150};
21151
21152/**
21153 * True if the supplied DOM node is a valid node element.
21154 *
21155 * @param {?DOMElement} node The candidate DOM node.
21156 * @return {boolean} True if the DOM is a valid DOM node.
21157 * @internal
21158 */
21159function isValidContainer(node) {
21160 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 '));
21161}
21162
21163function getReactRootElementInContainer(container) {
21164 if (!container) {
21165 return null;
21166 }
21167
21168 if (container.nodeType === DOCUMENT_NODE) {
21169 return container.documentElement;
21170 } else {
21171 return container.firstChild;
21172 }
21173}
21174
21175function shouldHydrateDueToLegacyHeuristic(container) {
21176 var rootElement = getReactRootElementInContainer(container);
21177 return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
21178}
21179
21180setBatchingImplementation(batchedUpdates$1, interactiveUpdates$1, flushInteractiveUpdates$1);
21181
21182var warnedAboutHydrateAPI = false;
21183
21184function legacyCreateRootFromDOMContainer(container, forceHydrate) {
21185 var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container);
21186 // First clear any existing content.
21187 if (!shouldHydrate) {
21188 var warned = false;
21189 var rootSibling = void 0;
21190 while (rootSibling = container.lastChild) {
21191 {
21192 if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
21193 warned = true;
21194 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.');
21195 }
21196 }
21197 container.removeChild(rootSibling);
21198 }
21199 }
21200 {
21201 if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
21202 warnedAboutHydrateAPI = true;
21203 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.');
21204 }
21205 }
21206 // Legacy roots are not async by default.
21207 var isConcurrent = false;
21208 return new ReactRoot(container, isConcurrent, shouldHydrate);
21209}
21210
21211function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
21212 {
21213 topLevelUpdateWarnings(container);
21214 }
21215
21216 // TODO: Without `any` type, Flow says "Property cannot be accessed on any
21217 // member of intersection type." Whyyyyyy.
21218 var root = container._reactRootContainer;
21219 if (!root) {
21220 // Initial mount
21221 root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
21222 if (typeof callback === 'function') {
21223 var originalCallback = callback;
21224 callback = function () {
21225 var instance = getPublicRootInstance(root._internalRoot);
21226 originalCallback.call(instance);
21227 };
21228 }
21229 // Initial mount should not be batched.
21230 unbatchedUpdates(function () {
21231 if (parentComponent != null) {
21232 root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
21233 } else {
21234 root.render(children, callback);
21235 }
21236 });
21237 } else {
21238 if (typeof callback === 'function') {
21239 var _originalCallback = callback;
21240 callback = function () {
21241 var instance = getPublicRootInstance(root._internalRoot);
21242 _originalCallback.call(instance);
21243 };
21244 }
21245 // Update
21246 if (parentComponent != null) {
21247 root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
21248 } else {
21249 root.render(children, callback);
21250 }
21251 }
21252 return getPublicRootInstance(root._internalRoot);
21253}
21254
21255function createPortal$$1(children, container) {
21256 var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
21257
21258 !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;
21259 // TODO: pass ReactDOM portal implementation as third argument
21260 return createPortal$1(children, container, null, key);
21261}
21262
21263var ReactDOM = {
21264 createPortal: createPortal$$1,
21265
21266 findDOMNode: function (componentOrElement) {
21267 {
21268 var owner = ReactCurrentOwner.current;
21269 if (owner !== null && owner.stateNode !== null) {
21270 var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
21271 !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;
21272 owner.stateNode._warnedAboutRefsInRender = true;
21273 }
21274 }
21275 if (componentOrElement == null) {
21276 return null;
21277 }
21278 if (componentOrElement.nodeType === ELEMENT_NODE) {
21279 return componentOrElement;
21280 }
21281 {
21282 return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
21283 }
21284 return findHostInstance(componentOrElement);
21285 },
21286 hydrate: function (element, container, callback) {
21287 !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;
21288 {
21289 !!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;
21290 }
21291 // TODO: throw or warn if we couldn't hydrate?
21292 return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
21293 },
21294 render: function (element, container, callback) {
21295 !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;
21296 {
21297 !!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;
21298 }
21299 return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
21300 },
21301 unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) {
21302 !isValidContainer(containerNode) ? invariant(false, 'Target container is not a DOM element.') : void 0;
21303 !(parentComponent != null && has(parentComponent)) ? invariant(false, 'parentComponent must be a valid React Component') : void 0;
21304 return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
21305 },
21306 unmountComponentAtNode: function (container) {
21307 !isValidContainer(container) ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : void 0;
21308
21309 {
21310 !!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;
21311 }
21312
21313 if (container._reactRootContainer) {
21314 {
21315 var rootEl = getReactRootElementInContainer(container);
21316 var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);
21317 !!renderedByDifferentReact ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0;
21318 }
21319
21320 // Unmount should not be batched.
21321 unbatchedUpdates(function () {
21322 legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
21323 container._reactRootContainer = null;
21324 });
21325 });
21326 // If you call unmountComponentAtNode twice in quick succession, you'll
21327 // get `true` twice. That's probably fine?
21328 return true;
21329 } else {
21330 {
21331 var _rootEl = getReactRootElementInContainer(container);
21332 var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl));
21333
21334 // Check if the container itself is a React root node.
21335 var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;
21336
21337 !!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;
21338 }
21339
21340 return false;
21341 }
21342 },
21343
21344
21345 // Temporary alias since we already shipped React 16 RC with it.
21346 // TODO: remove in React 17.
21347 unstable_createPortal: function () {
21348 if (!didWarnAboutUnstableCreatePortal) {
21349 didWarnAboutUnstableCreatePortal = true;
21350 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.');
21351 }
21352 return createPortal$$1.apply(undefined, arguments);
21353 },
21354
21355
21356 unstable_batchedUpdates: batchedUpdates$1,
21357
21358 unstable_interactiveUpdates: interactiveUpdates$1,
21359
21360 flushSync: flushSync,
21361
21362 unstable_createRoot: createRoot,
21363 unstable_flushControlled: flushControlled,
21364
21365 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
21366 // Keep in sync with ReactDOMUnstableNativeDependencies.js
21367 // and ReactTestUtils.js. This is an array for better minification.
21368 Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injection.injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch]
21369 }
21370};
21371
21372function createRoot(container, options) {
21373 var functionName = enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot';
21374 !isValidContainer(container) ? invariant(false, '%s(...): Target container is not a DOM element.', functionName) : void 0;
21375 {
21376 !!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;
21377 container._reactHasBeenPassedToCreateRootDEV = true;
21378 }
21379 var hydrate = options != null && options.hydrate === true;
21380 return new ReactRoot(container, true, hydrate);
21381}
21382
21383if (enableStableConcurrentModeAPIs) {
21384 ReactDOM.createRoot = createRoot;
21385 ReactDOM.unstable_createRoot = undefined;
21386}
21387
21388var foundDevTools = injectIntoDevTools({
21389 findFiberByHostInstance: getClosestInstanceFromNode,
21390 bundleType: 1,
21391 version: ReactVersion,
21392 rendererPackageName: 'react-dom'
21393});
21394
21395{
21396 if (!foundDevTools && canUseDOM && window.top === window.self) {
21397 // If we're in Chrome or Firefox, provide a download link if not installed.
21398 if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
21399 var protocol = window.location.protocol;
21400 // Don't warn in exotic cases like chrome-extension://.
21401 if (/^(https?|file):$/.test(protocol)) {
21402 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');
21403 }
21404 }
21405 }
21406}
21407
21408
21409
21410var ReactFire = Object.freeze({
21411 default: ReactDOM
21412});
21413
21414var ReactFire$1 = ( ReactFire && ReactDOM ) || ReactFire;
21415
21416// TODO: decide on the top-level export form.
21417// This is hacky but makes it work with both Rollup and Jest.
21418var unstableFire = ReactFire$1.default || ReactFire$1;
21419
21420return unstableFire;
21421
21422})));