UNPKG

764 kBJavaScriptView Raw
1/** @license React v16.8.1
2 * react-dom.development.js
3 *
4 * Copyright (c) Facebook, Inc. and its affiliates.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE file in the root directory of this source tree.
8 */
9
10'use strict';
11
12
13
14if (process.env.NODE_ENV !== "production") {
15 (function() {
16'use strict';
17
18var React = require('react');
19var _assign = require('object-assign');
20var checkPropTypes = require('prop-types/checkPropTypes');
21var scheduler = require('scheduler');
22var tracing = require('scheduler/tracing');
23
24/**
25 * Use invariant() to assert state which your program assumes to be true.
26 *
27 * Provide sprintf-style format (only %s is supported) and arguments
28 * to provide information about what broke and what you were
29 * expecting.
30 *
31 * The invariant message will be stripped in production, but the invariant
32 * will remain to ensure logic does not differ in production.
33 */
34
35var validateFormat = function () {};
36
37{
38 validateFormat = function (format) {
39 if (format === undefined) {
40 throw new Error('invariant requires an error message argument');
41 }
42 };
43}
44
45function invariant(condition, format, a, b, c, d, e, f) {
46 validateFormat(format);
47
48 if (!condition) {
49 var error = void 0;
50 if (format === undefined) {
51 error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
52 } else {
53 var args = [a, b, c, d, e, f];
54 var argIndex = 0;
55 error = new Error(format.replace(/%s/g, function () {
56 return args[argIndex++];
57 }));
58 error.name = 'Invariant Violation';
59 }
60
61 error.framesToPop = 1; // we don't care about invariant's own frame
62 throw error;
63 }
64}
65
66// Relying on the `invariant()` implementation lets us
67// preserve the format and params in the www builds.
68
69!React ? invariant(false, 'ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.') : void 0;
70
71var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {
72 var funcArgs = Array.prototype.slice.call(arguments, 3);
73 try {
74 func.apply(context, funcArgs);
75 } catch (error) {
76 this.onError(error);
77 }
78};
79
80{
81 // In DEV mode, we swap out invokeGuardedCallback for a special version
82 // that plays more nicely with the browser's DevTools. The idea is to preserve
83 // "Pause on exceptions" behavior. Because React wraps all user-provided
84 // functions in invokeGuardedCallback, and the production version of
85 // invokeGuardedCallback uses a try-catch, all user exceptions are treated
86 // like caught exceptions, and the DevTools won't pause unless the developer
87 // takes the extra step of enabling pause on caught exceptions. This is
88 // untintuitive, though, because even though React has caught the error, from
89 // the developer's perspective, the error is uncaught.
90 //
91 // To preserve the expected "Pause on exceptions" behavior, we don't use a
92 // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
93 // DOM node, and call the user-provided callback from inside an event handler
94 // for that fake event. If the callback throws, the error is "captured" using
95 // a global event handler. But because the error happens in a different
96 // event loop context, it does not interrupt the normal program flow.
97 // Effectively, this gives us try-catch behavior without actually using
98 // try-catch. Neat!
99
100 // Check that the browser supports the APIs we need to implement our special
101 // DEV version of invokeGuardedCallback
102 if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
103 var fakeNode = document.createElement('react');
104
105 var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {
106 // If document doesn't exist we know for sure we will crash in this method
107 // when we call document.createEvent(). However this can cause confusing
108 // errors: https://github.com/facebookincubator/create-react-app/issues/3482
109 // So we preemptively throw with a better message instead.
110 !(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;
111 var evt = document.createEvent('Event');
112
113 // Keeps track of whether the user-provided callback threw an error. We
114 // set this to true at the beginning, then set it to false right after
115 // calling the function. If the function errors, `didError` will never be
116 // set to false. This strategy works even if the browser is flaky and
117 // fails to call our global error handler, because it doesn't rely on
118 // the error event at all.
119 var didError = true;
120
121 // Keeps track of the value of window.event so that we can reset it
122 // during the callback to let user code access window.event in the
123 // browsers that support it.
124 var windowEvent = window.event;
125
126 // Keeps track of the descriptor of window.event to restore it after event
127 // dispatching: https://github.com/facebook/react/issues/13688
128 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');
129
130 // Create an event handler for our fake event. We will synchronously
131 // dispatch our fake event using `dispatchEvent`. Inside the handler, we
132 // call the user-provided callback.
133 var funcArgs = Array.prototype.slice.call(arguments, 3);
134 function callCallback() {
135 // We immediately remove the callback from event listeners so that
136 // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
137 // nested call would trigger the fake event handlers of any call higher
138 // in the stack.
139 fakeNode.removeEventListener(evtType, callCallback, false);
140
141 // We check for window.hasOwnProperty('event') to prevent the
142 // window.event assignment in both IE <= 10 as they throw an error
143 // "Member not found" in strict mode, and in Firefox which does not
144 // support window.event.
145 if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
146 window.event = windowEvent;
147 }
148
149 func.apply(context, funcArgs);
150 didError = false;
151 }
152
153 // Create a global error event handler. We use this to capture the value
154 // that was thrown. It's possible that this error handler will fire more
155 // than once; for example, if non-React code also calls `dispatchEvent`
156 // and a handler for that event throws. We should be resilient to most of
157 // those cases. Even if our error event handler fires more than once, the
158 // last error event is always used. If the callback actually does error,
159 // we know that the last error event is the correct one, because it's not
160 // possible for anything else to have happened in between our callback
161 // erroring and the code that follows the `dispatchEvent` call below. If
162 // the callback doesn't error, but the error event was fired, we know to
163 // ignore it because `didError` will be false, as described above.
164 var error = void 0;
165 // Use this to track whether the error event is ever called.
166 var didSetError = false;
167 var isCrossOriginError = false;
168
169 function handleWindowError(event) {
170 error = event.error;
171 didSetError = true;
172 if (error === null && event.colno === 0 && event.lineno === 0) {
173 isCrossOriginError = true;
174 }
175 if (event.defaultPrevented) {
176 // Some other error handler has prevented default.
177 // Browsers silence the error report if this happens.
178 // We'll remember this to later decide whether to log it or not.
179 if (error != null && typeof error === 'object') {
180 try {
181 error._suppressLogging = true;
182 } catch (inner) {
183 // Ignore.
184 }
185 }
186 }
187 }
188
189 // Create a fake event type.
190 var evtType = 'react-' + (name ? name : 'invokeguardedcallback');
191
192 // Attach our event handlers
193 window.addEventListener('error', handleWindowError);
194 fakeNode.addEventListener(evtType, callCallback, false);
195
196 // Synchronously dispatch our fake event. If the user-provided function
197 // errors, it will trigger our global error handler.
198 evt.initEvent(evtType, false, false);
199 fakeNode.dispatchEvent(evt);
200
201 if (windowEventDescriptor) {
202 Object.defineProperty(window, 'event', windowEventDescriptor);
203 }
204
205 if (didError) {
206 if (!didSetError) {
207 // The callback errored, but the error event never fired.
208 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.');
209 } else if (isCrossOriginError) {
210 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.');
211 }
212 this.onError(error);
213 }
214
215 // Remove our event listeners
216 window.removeEventListener('error', handleWindowError);
217 };
218
219 invokeGuardedCallbackImpl = invokeGuardedCallbackDev;
220 }
221}
222
223var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
224
225// Used by Fiber to simulate a try-catch.
226var hasError = false;
227var caughtError = null;
228
229// Used by event system to capture/rethrow the first error.
230var hasRethrowError = false;
231var rethrowError = null;
232
233var reporter = {
234 onError: function (error) {
235 hasError = true;
236 caughtError = error;
237 }
238};
239
240/**
241 * Call a function while guarding against errors that happens within it.
242 * Returns an error if it throws, otherwise null.
243 *
244 * In production, this is implemented using a try-catch. The reason we don't
245 * use a try-catch directly is so that we can swap out a different
246 * implementation in DEV mode.
247 *
248 * @param {String} name of the guard to use for logging or debugging
249 * @param {Function} func The function to invoke
250 * @param {*} context The context to use when calling the function
251 * @param {...*} args Arguments for function
252 */
253function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
254 hasError = false;
255 caughtError = null;
256 invokeGuardedCallbackImpl$1.apply(reporter, arguments);
257}
258
259/**
260 * Same as invokeGuardedCallback, but instead of returning an error, it stores
261 * it in a global so it can be rethrown by `rethrowCaughtError` later.
262 * TODO: See if caughtError and rethrowError can be unified.
263 *
264 * @param {String} name of the guard to use for logging or debugging
265 * @param {Function} func The function to invoke
266 * @param {*} context The context to use when calling the function
267 * @param {...*} args Arguments for function
268 */
269function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
270 invokeGuardedCallback.apply(this, arguments);
271 if (hasError) {
272 var error = clearCaughtError();
273 if (!hasRethrowError) {
274 hasRethrowError = true;
275 rethrowError = error;
276 }
277 }
278}
279
280/**
281 * During execution of guarded functions we will capture the first error which
282 * we will rethrow to be handled by the top level error handler.
283 */
284function rethrowCaughtError() {
285 if (hasRethrowError) {
286 var error = rethrowError;
287 hasRethrowError = false;
288 rethrowError = null;
289 throw error;
290 }
291}
292
293function hasCaughtError() {
294 return hasError;
295}
296
297function clearCaughtError() {
298 if (hasError) {
299 var error = caughtError;
300 hasError = false;
301 caughtError = null;
302 return error;
303 } else {
304 invariant(false, 'clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.');
305 }
306}
307
308/**
309 * Injectable ordering of event plugins.
310 */
311var eventPluginOrder = null;
312
313/**
314 * Injectable mapping from names to event plugin modules.
315 */
316var namesToPlugins = {};
317
318/**
319 * Recomputes the plugin list using the injected plugins and plugin ordering.
320 *
321 * @private
322 */
323function recomputePluginOrdering() {
324 if (!eventPluginOrder) {
325 // Wait until an `eventPluginOrder` is injected.
326 return;
327 }
328 for (var pluginName in namesToPlugins) {
329 var pluginModule = namesToPlugins[pluginName];
330 var pluginIndex = eventPluginOrder.indexOf(pluginName);
331 !(pluginIndex > -1) ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : void 0;
332 if (plugins[pluginIndex]) {
333 continue;
334 }
335 !pluginModule.extractEvents ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : void 0;
336 plugins[pluginIndex] = pluginModule;
337 var publishedEvents = pluginModule.eventTypes;
338 for (var eventName in publishedEvents) {
339 !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : void 0;
340 }
341 }
342}
343
344/**
345 * Publishes an event so that it can be dispatched by the supplied plugin.
346 *
347 * @param {object} dispatchConfig Dispatch configuration for the event.
348 * @param {object} PluginModule Plugin publishing the event.
349 * @return {boolean} True if the event was successfully published.
350 * @private
351 */
352function publishEventForPlugin(dispatchConfig, pluginModule, eventName) {
353 !!eventNameDispatchConfigs.hasOwnProperty(eventName) ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : void 0;
354 eventNameDispatchConfigs[eventName] = dispatchConfig;
355
356 var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
357 if (phasedRegistrationNames) {
358 for (var phaseName in phasedRegistrationNames) {
359 if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
360 var phasedRegistrationName = phasedRegistrationNames[phaseName];
361 publishRegistrationName(phasedRegistrationName, pluginModule, eventName);
362 }
363 }
364 return true;
365 } else if (dispatchConfig.registrationName) {
366 publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);
367 return true;
368 }
369 return false;
370}
371
372/**
373 * Publishes a registration name that is used to identify dispatched events.
374 *
375 * @param {string} registrationName Registration name to add.
376 * @param {object} PluginModule Plugin publishing the event.
377 * @private
378 */
379function publishRegistrationName(registrationName, pluginModule, eventName) {
380 !!registrationNameModules[registrationName] ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : void 0;
381 registrationNameModules[registrationName] = pluginModule;
382 registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;
383
384 {
385 var lowerCasedName = registrationName.toLowerCase();
386 possibleRegistrationNames[lowerCasedName] = registrationName;
387
388 if (registrationName === 'onDoubleClick') {
389 possibleRegistrationNames.ondblclick = registrationName;
390 }
391 }
392}
393
394/**
395 * Registers plugins so that they can extract and dispatch events.
396 *
397 * @see {EventPluginHub}
398 */
399
400/**
401 * Ordered list of injected plugins.
402 */
403var plugins = [];
404
405/**
406 * Mapping from event name to dispatch config
407 */
408var eventNameDispatchConfigs = {};
409
410/**
411 * Mapping from registration name to plugin module
412 */
413var registrationNameModules = {};
414
415/**
416 * Mapping from registration name to event name
417 */
418var registrationNameDependencies = {};
419
420/**
421 * Mapping from lowercase registration names to the properly cased version,
422 * used to warn in the case of missing event handlers. Available
423 * only in true.
424 * @type {Object}
425 */
426var possibleRegistrationNames = {};
427// Trust the developer to only use possibleRegistrationNames in true
428
429/**
430 * Injects an ordering of plugins (by plugin name). This allows the ordering
431 * to be decoupled from injection of the actual plugins so that ordering is
432 * always deterministic regardless of packaging, on-the-fly injection, etc.
433 *
434 * @param {array} InjectedEventPluginOrder
435 * @internal
436 * @see {EventPluginHub.injection.injectEventPluginOrder}
437 */
438function injectEventPluginOrder(injectedEventPluginOrder) {
439 !!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;
440 // Clone the ordering so it cannot be dynamically mutated.
441 eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
442 recomputePluginOrdering();
443}
444
445/**
446 * Injects plugins to be used by `EventPluginHub`. The plugin names must be
447 * in the ordering injected by `injectEventPluginOrder`.
448 *
449 * Plugins can be injected as part of page initialization or on-the-fly.
450 *
451 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
452 * @internal
453 * @see {EventPluginHub.injection.injectEventPluginsByName}
454 */
455function injectEventPluginsByName(injectedNamesToPlugins) {
456 var isOrderingDirty = false;
457 for (var pluginName in injectedNamesToPlugins) {
458 if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
459 continue;
460 }
461 var pluginModule = injectedNamesToPlugins[pluginName];
462 if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {
463 !!namesToPlugins[pluginName] ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : void 0;
464 namesToPlugins[pluginName] = pluginModule;
465 isOrderingDirty = true;
466 }
467 }
468 if (isOrderingDirty) {
469 recomputePluginOrdering();
470 }
471}
472
473/**
474 * Similar to invariant but only logs a warning if the condition is not met.
475 * This can be used to log issues in development environments in critical
476 * paths. Removing the logging code for production environments will keep the
477 * same logic and follow the same code paths.
478 */
479
480var warningWithoutStack = function () {};
481
482{
483 warningWithoutStack = function (condition, format) {
484 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
485 args[_key - 2] = arguments[_key];
486 }
487
488 if (format === undefined) {
489 throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
490 }
491 if (args.length > 8) {
492 // Check before the condition to catch violations early.
493 throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
494 }
495 if (condition) {
496 return;
497 }
498 if (typeof console !== 'undefined') {
499 var argsWithFormat = args.map(function (item) {
500 return '' + item;
501 });
502 argsWithFormat.unshift('Warning: ' + format);
503
504 // We intentionally don't use spread (or .apply) directly because it
505 // breaks IE9: https://github.com/facebook/react/issues/13610
506 Function.prototype.apply.call(console.error, console, argsWithFormat);
507 }
508 try {
509 // --- Welcome to debugging React ---
510 // This error was thrown as a convenience so that you can use this stack
511 // to find the callsite that caused this warning to fire.
512 var argIndex = 0;
513 var message = 'Warning: ' + format.replace(/%s/g, function () {
514 return args[argIndex++];
515 });
516 throw new Error(message);
517 } catch (x) {}
518 };
519}
520
521var warningWithoutStack$1 = warningWithoutStack;
522
523var getFiberCurrentPropsFromNode = null;
524var getInstanceFromNode = null;
525var getNodeFromInstance = null;
526
527function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) {
528 getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;
529 getInstanceFromNode = getInstanceFromNodeImpl;
530 getNodeFromInstance = getNodeFromInstanceImpl;
531 {
532 !(getNodeFromInstance && getInstanceFromNode) ? warningWithoutStack$1(false, 'EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0;
533 }
534}
535
536var validateEventDispatches = void 0;
537{
538 validateEventDispatches = function (event) {
539 var dispatchListeners = event._dispatchListeners;
540 var dispatchInstances = event._dispatchInstances;
541
542 var listenersIsArr = Array.isArray(dispatchListeners);
543 var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
544
545 var instancesIsArr = Array.isArray(dispatchInstances);
546 var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
547
548 !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, 'EventPluginUtils: Invalid `event`.') : void 0;
549 };
550}
551
552/**
553 * Dispatch the event to the listener.
554 * @param {SyntheticEvent} event SyntheticEvent to handle
555 * @param {function} listener Application-level callback
556 * @param {*} inst Internal component instance
557 */
558function executeDispatch(event, listener, inst) {
559 var type = event.type || 'unknown-event';
560 event.currentTarget = getNodeFromInstance(inst);
561 invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
562 event.currentTarget = null;
563}
564
565/**
566 * Standard/simple iteration through an event's collected dispatches.
567 */
568function executeDispatchesInOrder(event) {
569 var dispatchListeners = event._dispatchListeners;
570 var dispatchInstances = event._dispatchInstances;
571 {
572 validateEventDispatches(event);
573 }
574 if (Array.isArray(dispatchListeners)) {
575 for (var i = 0; i < dispatchListeners.length; i++) {
576 if (event.isPropagationStopped()) {
577 break;
578 }
579 // Listeners and Instances are two parallel arrays that are always in sync.
580 executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
581 }
582 } else if (dispatchListeners) {
583 executeDispatch(event, dispatchListeners, dispatchInstances);
584 }
585 event._dispatchListeners = null;
586 event._dispatchInstances = null;
587}
588
589/**
590 * @see executeDispatchesInOrderStopAtTrueImpl
591 */
592
593
594/**
595 * Execution of a "direct" dispatch - there must be at most one dispatch
596 * accumulated on the event or it is considered an error. It doesn't really make
597 * sense for an event with multiple dispatches (bubbled) to keep track of the
598 * return values at each dispatch execution, but it does tend to make sense when
599 * dealing with "direct" dispatches.
600 *
601 * @return {*} The return value of executing the single dispatch.
602 */
603
604
605/**
606 * @param {SyntheticEvent} event
607 * @return {boolean} True iff number of dispatches accumulated is greater than 0.
608 */
609
610/**
611 * Accumulates items that must not be null or undefined into the first one. This
612 * is used to conserve memory by avoiding array allocations, and thus sacrifices
613 * API cleanness. Since `current` can be null before being passed in and not
614 * null after this function, make sure to assign it back to `current`:
615 *
616 * `a = accumulateInto(a, b);`
617 *
618 * This API should be sparingly used. Try `accumulate` for something cleaner.
619 *
620 * @return {*|array<*>} An accumulation of items.
621 */
622
623function accumulateInto(current, next) {
624 !(next != null) ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : void 0;
625
626 if (current == null) {
627 return next;
628 }
629
630 // Both are not empty. Warning: Never call x.concat(y) when you are not
631 // certain that x is an Array (x could be a string with concat method).
632 if (Array.isArray(current)) {
633 if (Array.isArray(next)) {
634 current.push.apply(current, next);
635 return current;
636 }
637 current.push(next);
638 return current;
639 }
640
641 if (Array.isArray(next)) {
642 // A bit too dangerous to mutate `next`.
643 return [current].concat(next);
644 }
645
646 return [current, next];
647}
648
649/**
650 * @param {array} arr an "accumulation" of items which is either an Array or
651 * a single item. Useful when paired with the `accumulate` module. This is a
652 * simple utility that allows us to reason about a collection of items, but
653 * handling the case when there is exactly one item (and we do not need to
654 * allocate an array).
655 * @param {function} cb Callback invoked with each element or a collection.
656 * @param {?} [scope] Scope used as `this` in a callback.
657 */
658function forEachAccumulated(arr, cb, scope) {
659 if (Array.isArray(arr)) {
660 arr.forEach(cb, scope);
661 } else if (arr) {
662 cb.call(scope, arr);
663 }
664}
665
666/**
667 * Internal queue of events that have accumulated their dispatches and are
668 * waiting to have their dispatches executed.
669 */
670var eventQueue = null;
671
672/**
673 * Dispatches an event and releases it back into the pool, unless persistent.
674 *
675 * @param {?object} event Synthetic event to be dispatched.
676 * @private
677 */
678var executeDispatchesAndRelease = function (event) {
679 if (event) {
680 executeDispatchesInOrder(event);
681
682 if (!event.isPersistent()) {
683 event.constructor.release(event);
684 }
685 }
686};
687var executeDispatchesAndReleaseTopLevel = function (e) {
688 return executeDispatchesAndRelease(e);
689};
690
691function isInteractive(tag) {
692 return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
693}
694
695function shouldPreventMouseEvent(name, type, props) {
696 switch (name) {
697 case 'onClick':
698 case 'onClickCapture':
699 case 'onDoubleClick':
700 case 'onDoubleClickCapture':
701 case 'onMouseDown':
702 case 'onMouseDownCapture':
703 case 'onMouseMove':
704 case 'onMouseMoveCapture':
705 case 'onMouseUp':
706 case 'onMouseUpCapture':
707 return !!(props.disabled && isInteractive(type));
708 default:
709 return false;
710 }
711}
712
713/**
714 * This is a unified interface for event plugins to be installed and configured.
715 *
716 * Event plugins can implement the following properties:
717 *
718 * `extractEvents` {function(string, DOMEventTarget, string, object): *}
719 * Required. When a top-level event is fired, this method is expected to
720 * extract synthetic events that will in turn be queued and dispatched.
721 *
722 * `eventTypes` {object}
723 * Optional, plugins that fire events must publish a mapping of registration
724 * names that are used to register listeners. Values of this mapping must
725 * be objects that contain `registrationName` or `phasedRegistrationNames`.
726 *
727 * `executeDispatch` {function(object, function, string)}
728 * Optional, allows plugins to override how an event gets dispatched. By
729 * default, the listener is simply invoked.
730 *
731 * Each plugin that is injected into `EventsPluginHub` is immediately operable.
732 *
733 * @public
734 */
735
736/**
737 * Methods for injecting dependencies.
738 */
739var injection = {
740 /**
741 * @param {array} InjectedEventPluginOrder
742 * @public
743 */
744 injectEventPluginOrder: injectEventPluginOrder,
745
746 /**
747 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
748 */
749 injectEventPluginsByName: injectEventPluginsByName
750};
751
752/**
753 * @param {object} inst The instance, which is the source of events.
754 * @param {string} registrationName Name of listener (e.g. `onClick`).
755 * @return {?function} The stored callback.
756 */
757function getListener(inst, registrationName) {
758 var listener = void 0;
759
760 // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
761 // live here; needs to be moved to a better place soon
762 var stateNode = inst.stateNode;
763 if (!stateNode) {
764 // Work in progress (ex: onload events in incremental mode).
765 return null;
766 }
767 var props = getFiberCurrentPropsFromNode(stateNode);
768 if (!props) {
769 // Work in progress.
770 return null;
771 }
772 listener = props[registrationName];
773 if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
774 return null;
775 }
776 !(!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;
777 return listener;
778}
779
780/**
781 * Allows registered plugins an opportunity to extract events from top-level
782 * native browser events.
783 *
784 * @return {*} An accumulation of synthetic events.
785 * @internal
786 */
787function extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
788 var events = null;
789 for (var i = 0; i < plugins.length; i++) {
790 // Not every plugin in the ordering may be loaded at runtime.
791 var possiblePlugin = plugins[i];
792 if (possiblePlugin) {
793 var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
794 if (extractedEvents) {
795 events = accumulateInto(events, extractedEvents);
796 }
797 }
798 }
799 return events;
800}
801
802function runEventsInBatch(events) {
803 if (events !== null) {
804 eventQueue = accumulateInto(eventQueue, events);
805 }
806
807 // Set `eventQueue` to null before processing it so that we can tell if more
808 // events get enqueued while processing.
809 var processingEventQueue = eventQueue;
810 eventQueue = null;
811
812 if (!processingEventQueue) {
813 return;
814 }
815
816 forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
817 !!eventQueue ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : void 0;
818 // This would be a good time to rethrow if any of the event handlers threw.
819 rethrowCaughtError();
820}
821
822function runExtractedEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
823 var events = extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
824 runEventsInBatch(events);
825}
826
827var FunctionComponent = 0;
828var ClassComponent = 1;
829var IndeterminateComponent = 2; // Before we know whether it is function or class
830var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
831var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
832var HostComponent = 5;
833var HostText = 6;
834var Fragment = 7;
835var Mode = 8;
836var ContextConsumer = 9;
837var ContextProvider = 10;
838var ForwardRef = 11;
839var Profiler = 12;
840var SuspenseComponent = 13;
841var MemoComponent = 14;
842var SimpleMemoComponent = 15;
843var LazyComponent = 16;
844var IncompleteClassComponent = 17;
845
846var randomKey = Math.random().toString(36).slice(2);
847var internalInstanceKey = '__reactInternalInstance$' + randomKey;
848var internalEventHandlersKey = '__reactEventHandlers$' + randomKey;
849
850function precacheFiberNode(hostInst, node) {
851 node[internalInstanceKey] = hostInst;
852}
853
854/**
855 * Given a DOM node, return the closest ReactDOMComponent or
856 * ReactDOMTextComponent instance ancestor.
857 */
858function getClosestInstanceFromNode(node) {
859 if (node[internalInstanceKey]) {
860 return node[internalInstanceKey];
861 }
862
863 while (!node[internalInstanceKey]) {
864 if (node.parentNode) {
865 node = node.parentNode;
866 } else {
867 // Top of the tree. This node must not be part of a React tree (or is
868 // unmounted, potentially).
869 return null;
870 }
871 }
872
873 var inst = node[internalInstanceKey];
874 if (inst.tag === HostComponent || inst.tag === HostText) {
875 // In Fiber, this will always be the deepest root.
876 return inst;
877 }
878
879 return null;
880}
881
882/**
883 * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
884 * instance, or null if the node was not rendered by this React.
885 */
886function getInstanceFromNode$1(node) {
887 var inst = node[internalInstanceKey];
888 if (inst) {
889 if (inst.tag === HostComponent || inst.tag === HostText) {
890 return inst;
891 } else {
892 return null;
893 }
894 }
895 return null;
896}
897
898/**
899 * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
900 * DOM node.
901 */
902function getNodeFromInstance$1(inst) {
903 if (inst.tag === HostComponent || inst.tag === HostText) {
904 // In Fiber this, is just the state node right now. We assume it will be
905 // a host component or host text.
906 return inst.stateNode;
907 }
908
909 // Without this first invariant, passing a non-DOM-component triggers the next
910 // invariant for a missing parent, which is super confusing.
911 invariant(false, 'getNodeFromInstance: Invalid argument.');
912}
913
914function getFiberCurrentPropsFromNode$1(node) {
915 return node[internalEventHandlersKey] || null;
916}
917
918function updateFiberProps(node, props) {
919 node[internalEventHandlersKey] = props;
920}
921
922function getParent(inst) {
923 do {
924 inst = inst.return;
925 // TODO: If this is a HostRoot we might want to bail out.
926 // That is depending on if we want nested subtrees (layers) to bubble
927 // events to their parent. We could also go through parentNode on the
928 // host node but that wouldn't work for React Native and doesn't let us
929 // do the portal feature.
930 } while (inst && inst.tag !== HostComponent);
931 if (inst) {
932 return inst;
933 }
934 return null;
935}
936
937/**
938 * Return the lowest common ancestor of A and B, or null if they are in
939 * different trees.
940 */
941function getLowestCommonAncestor(instA, instB) {
942 var depthA = 0;
943 for (var tempA = instA; tempA; tempA = getParent(tempA)) {
944 depthA++;
945 }
946 var depthB = 0;
947 for (var tempB = instB; tempB; tempB = getParent(tempB)) {
948 depthB++;
949 }
950
951 // If A is deeper, crawl up.
952 while (depthA - depthB > 0) {
953 instA = getParent(instA);
954 depthA--;
955 }
956
957 // If B is deeper, crawl up.
958 while (depthB - depthA > 0) {
959 instB = getParent(instB);
960 depthB--;
961 }
962
963 // Walk in lockstep until we find a match.
964 var depth = depthA;
965 while (depth--) {
966 if (instA === instB || instA === instB.alternate) {
967 return instA;
968 }
969 instA = getParent(instA);
970 instB = getParent(instB);
971 }
972 return null;
973}
974
975/**
976 * Return if A is an ancestor of B.
977 */
978
979
980/**
981 * Return the parent instance of the passed-in instance.
982 */
983
984
985/**
986 * Simulates the traversal of a two-phase, capture/bubble event dispatch.
987 */
988function traverseTwoPhase(inst, fn, arg) {
989 var path = [];
990 while (inst) {
991 path.push(inst);
992 inst = getParent(inst);
993 }
994 var i = void 0;
995 for (i = path.length; i-- > 0;) {
996 fn(path[i], 'captured', arg);
997 }
998 for (i = 0; i < path.length; i++) {
999 fn(path[i], 'bubbled', arg);
1000 }
1001}
1002
1003/**
1004 * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
1005 * should would receive a `mouseEnter` or `mouseLeave` event.
1006 *
1007 * Does not invoke the callback on the nearest common ancestor because nothing
1008 * "entered" or "left" that element.
1009 */
1010function traverseEnterLeave(from, to, fn, argFrom, argTo) {
1011 var common = from && to ? getLowestCommonAncestor(from, to) : null;
1012 var pathFrom = [];
1013 while (true) {
1014 if (!from) {
1015 break;
1016 }
1017 if (from === common) {
1018 break;
1019 }
1020 var alternate = from.alternate;
1021 if (alternate !== null && alternate === common) {
1022 break;
1023 }
1024 pathFrom.push(from);
1025 from = getParent(from);
1026 }
1027 var pathTo = [];
1028 while (true) {
1029 if (!to) {
1030 break;
1031 }
1032 if (to === common) {
1033 break;
1034 }
1035 var _alternate = to.alternate;
1036 if (_alternate !== null && _alternate === common) {
1037 break;
1038 }
1039 pathTo.push(to);
1040 to = getParent(to);
1041 }
1042 for (var i = 0; i < pathFrom.length; i++) {
1043 fn(pathFrom[i], 'bubbled', argFrom);
1044 }
1045 for (var _i = pathTo.length; _i-- > 0;) {
1046 fn(pathTo[_i], 'captured', argTo);
1047 }
1048}
1049
1050/**
1051 * Some event types have a notion of different registration names for different
1052 * "phases" of propagation. This finds listeners by a given phase.
1053 */
1054function listenerAtPhase(inst, event, propagationPhase) {
1055 var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
1056 return getListener(inst, registrationName);
1057}
1058
1059/**
1060 * A small set of propagation patterns, each of which will accept a small amount
1061 * of information, and generate a set of "dispatch ready event objects" - which
1062 * are sets of events that have already been annotated with a set of dispatched
1063 * listener functions/ids. The API is designed this way to discourage these
1064 * propagation strategies from actually executing the dispatches, since we
1065 * always want to collect the entire set of dispatches before executing even a
1066 * single one.
1067 */
1068
1069/**
1070 * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
1071 * here, allows us to not have to bind or create functions for each event.
1072 * Mutating the event's members allows us to not have to create a wrapping
1073 * "dispatch" object that pairs the event with the listener.
1074 */
1075function accumulateDirectionalDispatches(inst, phase, event) {
1076 {
1077 !inst ? warningWithoutStack$1(false, 'Dispatching inst must not be null') : void 0;
1078 }
1079 var listener = listenerAtPhase(inst, event, phase);
1080 if (listener) {
1081 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
1082 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
1083 }
1084}
1085
1086/**
1087 * Collect dispatches (must be entirely collected before dispatching - see unit
1088 * tests). Lazily allocate the array to conserve memory. We must loop through
1089 * each event and perform the traversal for each one. We cannot perform a
1090 * single traversal for the entire collection of events because each event may
1091 * have a different target.
1092 */
1093function accumulateTwoPhaseDispatchesSingle(event) {
1094 if (event && event.dispatchConfig.phasedRegistrationNames) {
1095 traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
1096 }
1097}
1098
1099/**
1100 * Accumulates without regard to direction, does not look for phased
1101 * registration names. Same as `accumulateDirectDispatchesSingle` but without
1102 * requiring that the `dispatchMarker` be the same as the dispatched ID.
1103 */
1104function accumulateDispatches(inst, ignoredDirection, event) {
1105 if (inst && event && event.dispatchConfig.registrationName) {
1106 var registrationName = event.dispatchConfig.registrationName;
1107 var listener = getListener(inst, registrationName);
1108 if (listener) {
1109 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
1110 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
1111 }
1112 }
1113}
1114
1115/**
1116 * Accumulates dispatches on an `SyntheticEvent`, but only for the
1117 * `dispatchMarker`.
1118 * @param {SyntheticEvent} event
1119 */
1120function accumulateDirectDispatchesSingle(event) {
1121 if (event && event.dispatchConfig.registrationName) {
1122 accumulateDispatches(event._targetInst, null, event);
1123 }
1124}
1125
1126function accumulateTwoPhaseDispatches(events) {
1127 forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
1128}
1129
1130
1131
1132function accumulateEnterLeaveDispatches(leave, enter, from, to) {
1133 traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
1134}
1135
1136function accumulateDirectDispatches(events) {
1137 forEachAccumulated(events, accumulateDirectDispatchesSingle);
1138}
1139
1140var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
1141
1142// Do not uses the below two methods directly!
1143// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.
1144// (It is the only module that is allowed to access these methods.)
1145
1146function unsafeCastStringToDOMTopLevelType(topLevelType) {
1147 return topLevelType;
1148}
1149
1150function unsafeCastDOMTopLevelTypeToString(topLevelType) {
1151 return topLevelType;
1152}
1153
1154/**
1155 * Generate a mapping of standard vendor prefixes using the defined style property and event name.
1156 *
1157 * @param {string} styleProp
1158 * @param {string} eventName
1159 * @returns {object}
1160 */
1161function makePrefixMap(styleProp, eventName) {
1162 var prefixes = {};
1163
1164 prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
1165 prefixes['Webkit' + styleProp] = 'webkit' + eventName;
1166 prefixes['Moz' + styleProp] = 'moz' + eventName;
1167
1168 return prefixes;
1169}
1170
1171/**
1172 * A list of event names to a configurable list of vendor prefixes.
1173 */
1174var vendorPrefixes = {
1175 animationend: makePrefixMap('Animation', 'AnimationEnd'),
1176 animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
1177 animationstart: makePrefixMap('Animation', 'AnimationStart'),
1178 transitionend: makePrefixMap('Transition', 'TransitionEnd')
1179};
1180
1181/**
1182 * Event names that have already been detected and prefixed (if applicable).
1183 */
1184var prefixedEventNames = {};
1185
1186/**
1187 * Element to check for prefixes on.
1188 */
1189var style = {};
1190
1191/**
1192 * Bootstrap if a DOM exists.
1193 */
1194if (canUseDOM) {
1195 style = document.createElement('div').style;
1196
1197 // On some platforms, in particular some releases of Android 4.x,
1198 // the un-prefixed "animation" and "transition" properties are defined on the
1199 // style object but the events that fire will still be prefixed, so we need
1200 // to check if the un-prefixed events are usable, and if not remove them from the map.
1201 if (!('AnimationEvent' in window)) {
1202 delete vendorPrefixes.animationend.animation;
1203 delete vendorPrefixes.animationiteration.animation;
1204 delete vendorPrefixes.animationstart.animation;
1205 }
1206
1207 // Same as above
1208 if (!('TransitionEvent' in window)) {
1209 delete vendorPrefixes.transitionend.transition;
1210 }
1211}
1212
1213/**
1214 * Attempts to determine the correct vendor prefixed event name.
1215 *
1216 * @param {string} eventName
1217 * @returns {string}
1218 */
1219function getVendorPrefixedEventName(eventName) {
1220 if (prefixedEventNames[eventName]) {
1221 return prefixedEventNames[eventName];
1222 } else if (!vendorPrefixes[eventName]) {
1223 return eventName;
1224 }
1225
1226 var prefixMap = vendorPrefixes[eventName];
1227
1228 for (var styleProp in prefixMap) {
1229 if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
1230 return prefixedEventNames[eventName] = prefixMap[styleProp];
1231 }
1232 }
1233
1234 return eventName;
1235}
1236
1237/**
1238 * To identify top level events in ReactDOM, we use constants defined by this
1239 * module. This is the only module that uses the unsafe* methods to express
1240 * that the constants actually correspond to the browser event names. This lets
1241 * us save some bundle size by avoiding a top level type -> event name map.
1242 * The rest of ReactDOM code should import top level types from this file.
1243 */
1244var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
1245var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
1246var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));
1247var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
1248var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
1249var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
1250var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
1251var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
1252var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
1253var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
1254var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
1255var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
1256var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');
1257var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');
1258var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
1259var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
1260var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
1261var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
1262var TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick');
1263var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
1264var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
1265var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
1266var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
1267var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
1268var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
1269var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
1270var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
1271var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
1272var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
1273var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
1274var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
1275var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
1276var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
1277var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture');
1278var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
1279var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid');
1280var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
1281var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
1282var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
1283var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
1284var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
1285var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
1286var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
1287var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture');
1288var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
1289var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
1290var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
1291var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
1292var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
1293var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
1294var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
1295var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
1296var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
1297var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel');
1298var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown');
1299
1300
1301var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove');
1302var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout');
1303var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover');
1304var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup');
1305var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
1306var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
1307var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset');
1308var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
1309var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
1310var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
1311var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
1312var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
1313var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit');
1314var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
1315var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
1316var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
1317var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
1318var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
1319var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
1320var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
1321var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
1322var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
1323var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
1324var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
1325var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel');
1326
1327// List of events that need to be individually attached to media elements.
1328// Note that events in this list will *not* be listened to at the top level
1329// unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.
1330var 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];
1331
1332function getRawEventName(topLevelType) {
1333 return unsafeCastDOMTopLevelTypeToString(topLevelType);
1334}
1335
1336/**
1337 * These variables store information about text content of a target node,
1338 * allowing comparison of content before and after a given event.
1339 *
1340 * Identify the node where selection currently begins, then observe
1341 * both its text content and its current position in the DOM. Since the
1342 * browser may natively replace the target node during composition, we can
1343 * use its position to find its replacement.
1344 *
1345 *
1346 */
1347
1348var root = null;
1349var startText = null;
1350var fallbackText = null;
1351
1352function initialize(nativeEventTarget) {
1353 root = nativeEventTarget;
1354 startText = getText();
1355 return true;
1356}
1357
1358function reset() {
1359 root = null;
1360 startText = null;
1361 fallbackText = null;
1362}
1363
1364function getData() {
1365 if (fallbackText) {
1366 return fallbackText;
1367 }
1368
1369 var start = void 0;
1370 var startValue = startText;
1371 var startLength = startValue.length;
1372 var end = void 0;
1373 var endValue = getText();
1374 var endLength = endValue.length;
1375
1376 for (start = 0; start < startLength; start++) {
1377 if (startValue[start] !== endValue[start]) {
1378 break;
1379 }
1380 }
1381
1382 var minEnd = startLength - start;
1383 for (end = 1; end <= minEnd; end++) {
1384 if (startValue[startLength - end] !== endValue[endLength - end]) {
1385 break;
1386 }
1387 }
1388
1389 var sliceTail = end > 1 ? 1 - end : undefined;
1390 fallbackText = endValue.slice(start, sliceTail);
1391 return fallbackText;
1392}
1393
1394function getText() {
1395 if ('value' in root) {
1396 return root.value;
1397 }
1398 return root.textContent;
1399}
1400
1401/* eslint valid-typeof: 0 */
1402
1403var EVENT_POOL_SIZE = 10;
1404
1405/**
1406 * @interface Event
1407 * @see http://www.w3.org/TR/DOM-Level-3-Events/
1408 */
1409var EventInterface = {
1410 type: null,
1411 target: null,
1412 // currentTarget is set when dispatching; no use in copying it here
1413 currentTarget: function () {
1414 return null;
1415 },
1416 eventPhase: null,
1417 bubbles: null,
1418 cancelable: null,
1419 timeStamp: function (event) {
1420 return event.timeStamp || Date.now();
1421 },
1422 defaultPrevented: null,
1423 isTrusted: null
1424};
1425
1426function functionThatReturnsTrue() {
1427 return true;
1428}
1429
1430function functionThatReturnsFalse() {
1431 return false;
1432}
1433
1434/**
1435 * Synthetic events are dispatched by event plugins, typically in response to a
1436 * top-level event delegation handler.
1437 *
1438 * These systems should generally use pooling to reduce the frequency of garbage
1439 * collection. The system should check `isPersistent` to determine whether the
1440 * event should be released into the pool after being dispatched. Users that
1441 * need a persisted event should invoke `persist`.
1442 *
1443 * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
1444 * normalizing browser quirks. Subclasses do not necessarily have to implement a
1445 * DOM interface; custom application-specific events can also subclass this.
1446 *
1447 * @param {object} dispatchConfig Configuration used to dispatch this event.
1448 * @param {*} targetInst Marker identifying the event target.
1449 * @param {object} nativeEvent Native browser event.
1450 * @param {DOMEventTarget} nativeEventTarget Target node.
1451 */
1452function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
1453 {
1454 // these have a getter/setter for warnings
1455 delete this.nativeEvent;
1456 delete this.preventDefault;
1457 delete this.stopPropagation;
1458 delete this.isDefaultPrevented;
1459 delete this.isPropagationStopped;
1460 }
1461
1462 this.dispatchConfig = dispatchConfig;
1463 this._targetInst = targetInst;
1464 this.nativeEvent = nativeEvent;
1465
1466 var Interface = this.constructor.Interface;
1467 for (var propName in Interface) {
1468 if (!Interface.hasOwnProperty(propName)) {
1469 continue;
1470 }
1471 {
1472 delete this[propName]; // this has a getter/setter for warnings
1473 }
1474 var normalize = Interface[propName];
1475 if (normalize) {
1476 this[propName] = normalize(nativeEvent);
1477 } else {
1478 if (propName === 'target') {
1479 this.target = nativeEventTarget;
1480 } else {
1481 this[propName] = nativeEvent[propName];
1482 }
1483 }
1484 }
1485
1486 var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
1487 if (defaultPrevented) {
1488 this.isDefaultPrevented = functionThatReturnsTrue;
1489 } else {
1490 this.isDefaultPrevented = functionThatReturnsFalse;
1491 }
1492 this.isPropagationStopped = functionThatReturnsFalse;
1493 return this;
1494}
1495
1496_assign(SyntheticEvent.prototype, {
1497 preventDefault: function () {
1498 this.defaultPrevented = true;
1499 var event = this.nativeEvent;
1500 if (!event) {
1501 return;
1502 }
1503
1504 if (event.preventDefault) {
1505 event.preventDefault();
1506 } else if (typeof event.returnValue !== 'unknown') {
1507 event.returnValue = false;
1508 }
1509 this.isDefaultPrevented = functionThatReturnsTrue;
1510 },
1511
1512 stopPropagation: function () {
1513 var event = this.nativeEvent;
1514 if (!event) {
1515 return;
1516 }
1517
1518 if (event.stopPropagation) {
1519 event.stopPropagation();
1520 } else if (typeof event.cancelBubble !== 'unknown') {
1521 // The ChangeEventPlugin registers a "propertychange" event for
1522 // IE. This event does not support bubbling or cancelling, and
1523 // any references to cancelBubble throw "Member not found". A
1524 // typeof check of "unknown" circumvents this issue (and is also
1525 // IE specific).
1526 event.cancelBubble = true;
1527 }
1528
1529 this.isPropagationStopped = functionThatReturnsTrue;
1530 },
1531
1532 /**
1533 * We release all dispatched `SyntheticEvent`s after each event loop, adding
1534 * them back into the pool. This allows a way to hold onto a reference that
1535 * won't be added back into the pool.
1536 */
1537 persist: function () {
1538 this.isPersistent = functionThatReturnsTrue;
1539 },
1540
1541 /**
1542 * Checks if this event should be released back into the pool.
1543 *
1544 * @return {boolean} True if this should not be released, false otherwise.
1545 */
1546 isPersistent: functionThatReturnsFalse,
1547
1548 /**
1549 * `PooledClass` looks for `destructor` on each instance it releases.
1550 */
1551 destructor: function () {
1552 var Interface = this.constructor.Interface;
1553 for (var propName in Interface) {
1554 {
1555 Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
1556 }
1557 }
1558 this.dispatchConfig = null;
1559 this._targetInst = null;
1560 this.nativeEvent = null;
1561 this.isDefaultPrevented = functionThatReturnsFalse;
1562 this.isPropagationStopped = functionThatReturnsFalse;
1563 this._dispatchListeners = null;
1564 this._dispatchInstances = null;
1565 {
1566 Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
1567 Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
1568 Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
1569 Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
1570 Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
1571 }
1572 }
1573});
1574
1575SyntheticEvent.Interface = EventInterface;
1576
1577/**
1578 * Helper to reduce boilerplate when creating subclasses.
1579 */
1580SyntheticEvent.extend = function (Interface) {
1581 var Super = this;
1582
1583 var E = function () {};
1584 E.prototype = Super.prototype;
1585 var prototype = new E();
1586
1587 function Class() {
1588 return Super.apply(this, arguments);
1589 }
1590 _assign(prototype, Class.prototype);
1591 Class.prototype = prototype;
1592 Class.prototype.constructor = Class;
1593
1594 Class.Interface = _assign({}, Super.Interface, Interface);
1595 Class.extend = Super.extend;
1596 addEventPoolingTo(Class);
1597
1598 return Class;
1599};
1600
1601addEventPoolingTo(SyntheticEvent);
1602
1603/**
1604 * Helper to nullify syntheticEvent instance properties when destructing
1605 *
1606 * @param {String} propName
1607 * @param {?object} getVal
1608 * @return {object} defineProperty object
1609 */
1610function getPooledWarningPropertyDefinition(propName, getVal) {
1611 var isFunction = typeof getVal === 'function';
1612 return {
1613 configurable: true,
1614 set: set,
1615 get: get
1616 };
1617
1618 function set(val) {
1619 var action = isFunction ? 'setting the method' : 'setting the property';
1620 warn(action, 'This is effectively a no-op');
1621 return val;
1622 }
1623
1624 function get() {
1625 var action = isFunction ? 'accessing the method' : 'accessing the property';
1626 var result = isFunction ? 'This is a no-op function' : 'This is set to null';
1627 warn(action, result);
1628 return getVal;
1629 }
1630
1631 function warn(action, result) {
1632 var warningCondition = false;
1633 !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;
1634 }
1635}
1636
1637function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
1638 var EventConstructor = this;
1639 if (EventConstructor.eventPool.length) {
1640 var instance = EventConstructor.eventPool.pop();
1641 EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
1642 return instance;
1643 }
1644 return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
1645}
1646
1647function releasePooledEvent(event) {
1648 var EventConstructor = this;
1649 !(event instanceof EventConstructor) ? invariant(false, 'Trying to release an event instance into a pool of a different type.') : void 0;
1650 event.destructor();
1651 if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
1652 EventConstructor.eventPool.push(event);
1653 }
1654}
1655
1656function addEventPoolingTo(EventConstructor) {
1657 EventConstructor.eventPool = [];
1658 EventConstructor.getPooled = getPooledEvent;
1659 EventConstructor.release = releasePooledEvent;
1660}
1661
1662/**
1663 * @interface Event
1664 * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
1665 */
1666var SyntheticCompositionEvent = SyntheticEvent.extend({
1667 data: null
1668});
1669
1670/**
1671 * @interface Event
1672 * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
1673 * /#events-inputevents
1674 */
1675var SyntheticInputEvent = SyntheticEvent.extend({
1676 data: null
1677});
1678
1679var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
1680var START_KEYCODE = 229;
1681
1682var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
1683
1684var documentMode = null;
1685if (canUseDOM && 'documentMode' in document) {
1686 documentMode = document.documentMode;
1687}
1688
1689// Webkit offers a very useful `textInput` event that can be used to
1690// directly represent `beforeInput`. The IE `textinput` event is not as
1691// useful, so we don't use it.
1692var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode;
1693
1694// In IE9+, we have access to composition events, but the data supplied
1695// by the native compositionend event may be incorrect. Japanese ideographic
1696// spaces, for instance (\u3000) are not recorded correctly.
1697var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
1698
1699var SPACEBAR_CODE = 32;
1700var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
1701
1702// Events and their corresponding property names.
1703var eventTypes = {
1704 beforeInput: {
1705 phasedRegistrationNames: {
1706 bubbled: 'onBeforeInput',
1707 captured: 'onBeforeInputCapture'
1708 },
1709 dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]
1710 },
1711 compositionEnd: {
1712 phasedRegistrationNames: {
1713 bubbled: 'onCompositionEnd',
1714 captured: 'onCompositionEndCapture'
1715 },
1716 dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
1717 },
1718 compositionStart: {
1719 phasedRegistrationNames: {
1720 bubbled: 'onCompositionStart',
1721 captured: 'onCompositionStartCapture'
1722 },
1723 dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
1724 },
1725 compositionUpdate: {
1726 phasedRegistrationNames: {
1727 bubbled: 'onCompositionUpdate',
1728 captured: 'onCompositionUpdateCapture'
1729 },
1730 dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
1731 }
1732};
1733
1734// Track whether we've ever handled a keypress on the space key.
1735var hasSpaceKeypress = false;
1736
1737/**
1738 * Return whether a native keypress event is assumed to be a command.
1739 * This is required because Firefox fires `keypress` events for key commands
1740 * (cut, copy, select-all, etc.) even though no character is inserted.
1741 */
1742function isKeypressCommand(nativeEvent) {
1743 return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
1744 // ctrlKey && altKey is equivalent to AltGr, and is not a command.
1745 !(nativeEvent.ctrlKey && nativeEvent.altKey);
1746}
1747
1748/**
1749 * Translate native top level events into event types.
1750 *
1751 * @param {string} topLevelType
1752 * @return {object}
1753 */
1754function getCompositionEventType(topLevelType) {
1755 switch (topLevelType) {
1756 case TOP_COMPOSITION_START:
1757 return eventTypes.compositionStart;
1758 case TOP_COMPOSITION_END:
1759 return eventTypes.compositionEnd;
1760 case TOP_COMPOSITION_UPDATE:
1761 return eventTypes.compositionUpdate;
1762 }
1763}
1764
1765/**
1766 * Does our fallback best-guess model think this event signifies that
1767 * composition has begun?
1768 *
1769 * @param {string} topLevelType
1770 * @param {object} nativeEvent
1771 * @return {boolean}
1772 */
1773function isFallbackCompositionStart(topLevelType, nativeEvent) {
1774 return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;
1775}
1776
1777/**
1778 * Does our fallback mode think that this event is the end of composition?
1779 *
1780 * @param {string} topLevelType
1781 * @param {object} nativeEvent
1782 * @return {boolean}
1783 */
1784function isFallbackCompositionEnd(topLevelType, nativeEvent) {
1785 switch (topLevelType) {
1786 case TOP_KEY_UP:
1787 // Command keys insert or clear IME input.
1788 return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
1789 case TOP_KEY_DOWN:
1790 // Expect IME keyCode on each keydown. If we get any other
1791 // code we must have exited earlier.
1792 return nativeEvent.keyCode !== START_KEYCODE;
1793 case TOP_KEY_PRESS:
1794 case TOP_MOUSE_DOWN:
1795 case TOP_BLUR:
1796 // Events are not possible without cancelling IME.
1797 return true;
1798 default:
1799 return false;
1800 }
1801}
1802
1803/**
1804 * Google Input Tools provides composition data via a CustomEvent,
1805 * with the `data` property populated in the `detail` object. If this
1806 * is available on the event object, use it. If not, this is a plain
1807 * composition event and we have nothing special to extract.
1808 *
1809 * @param {object} nativeEvent
1810 * @return {?string}
1811 */
1812function getDataFromCustomEvent(nativeEvent) {
1813 var detail = nativeEvent.detail;
1814 if (typeof detail === 'object' && 'data' in detail) {
1815 return detail.data;
1816 }
1817 return null;
1818}
1819
1820/**
1821 * Check if a composition event was triggered by Korean IME.
1822 * Our fallback mode does not work well with IE's Korean IME,
1823 * so just use native composition events when Korean IME is used.
1824 * Although CompositionEvent.locale property is deprecated,
1825 * it is available in IE, where our fallback mode is enabled.
1826 *
1827 * @param {object} nativeEvent
1828 * @return {boolean}
1829 */
1830function isUsingKoreanIME(nativeEvent) {
1831 return nativeEvent.locale === 'ko';
1832}
1833
1834// Track the current IME composition status, if any.
1835var isComposing = false;
1836
1837/**
1838 * @return {?object} A SyntheticCompositionEvent.
1839 */
1840function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
1841 var eventType = void 0;
1842 var fallbackData = void 0;
1843
1844 if (canUseCompositionEvent) {
1845 eventType = getCompositionEventType(topLevelType);
1846 } else if (!isComposing) {
1847 if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
1848 eventType = eventTypes.compositionStart;
1849 }
1850 } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
1851 eventType = eventTypes.compositionEnd;
1852 }
1853
1854 if (!eventType) {
1855 return null;
1856 }
1857
1858 if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
1859 // The current composition is stored statically and must not be
1860 // overwritten while composition continues.
1861 if (!isComposing && eventType === eventTypes.compositionStart) {
1862 isComposing = initialize(nativeEventTarget);
1863 } else if (eventType === eventTypes.compositionEnd) {
1864 if (isComposing) {
1865 fallbackData = getData();
1866 }
1867 }
1868 }
1869
1870 var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
1871
1872 if (fallbackData) {
1873 // Inject data generated from fallback path into the synthetic event.
1874 // This matches the property of native CompositionEventInterface.
1875 event.data = fallbackData;
1876 } else {
1877 var customData = getDataFromCustomEvent(nativeEvent);
1878 if (customData !== null) {
1879 event.data = customData;
1880 }
1881 }
1882
1883 accumulateTwoPhaseDispatches(event);
1884 return event;
1885}
1886
1887/**
1888 * @param {TopLevelType} topLevelType Number from `TopLevelType`.
1889 * @param {object} nativeEvent Native browser event.
1890 * @return {?string} The string corresponding to this `beforeInput` event.
1891 */
1892function getNativeBeforeInputChars(topLevelType, nativeEvent) {
1893 switch (topLevelType) {
1894 case TOP_COMPOSITION_END:
1895 return getDataFromCustomEvent(nativeEvent);
1896 case TOP_KEY_PRESS:
1897 /**
1898 * If native `textInput` events are available, our goal is to make
1899 * use of them. However, there is a special case: the spacebar key.
1900 * In Webkit, preventing default on a spacebar `textInput` event
1901 * cancels character insertion, but it *also* causes the browser
1902 * to fall back to its default spacebar behavior of scrolling the
1903 * page.
1904 *
1905 * Tracking at:
1906 * https://code.google.com/p/chromium/issues/detail?id=355103
1907 *
1908 * To avoid this issue, use the keypress event as if no `textInput`
1909 * event is available.
1910 */
1911 var which = nativeEvent.which;
1912 if (which !== SPACEBAR_CODE) {
1913 return null;
1914 }
1915
1916 hasSpaceKeypress = true;
1917 return SPACEBAR_CHAR;
1918
1919 case TOP_TEXT_INPUT:
1920 // Record the characters to be added to the DOM.
1921 var chars = nativeEvent.data;
1922
1923 // If it's a spacebar character, assume that we have already handled
1924 // it at the keypress level and bail immediately. Android Chrome
1925 // doesn't give us keycodes, so we need to ignore it.
1926 if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
1927 return null;
1928 }
1929
1930 return chars;
1931
1932 default:
1933 // For other native event types, do nothing.
1934 return null;
1935 }
1936}
1937
1938/**
1939 * For browsers that do not provide the `textInput` event, extract the
1940 * appropriate string to use for SyntheticInputEvent.
1941 *
1942 * @param {number} topLevelType Number from `TopLevelEventTypes`.
1943 * @param {object} nativeEvent Native browser event.
1944 * @return {?string} The fallback string for this `beforeInput` event.
1945 */
1946function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
1947 // If we are currently composing (IME) and using a fallback to do so,
1948 // try to extract the composed characters from the fallback object.
1949 // If composition event is available, we extract a string only at
1950 // compositionevent, otherwise extract it at fallback events.
1951 if (isComposing) {
1952 if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {
1953 var chars = getData();
1954 reset();
1955 isComposing = false;
1956 return chars;
1957 }
1958 return null;
1959 }
1960
1961 switch (topLevelType) {
1962 case TOP_PASTE:
1963 // If a paste event occurs after a keypress, throw out the input
1964 // chars. Paste events should not lead to BeforeInput events.
1965 return null;
1966 case TOP_KEY_PRESS:
1967 /**
1968 * As of v27, Firefox may fire keypress events even when no character
1969 * will be inserted. A few possibilities:
1970 *
1971 * - `which` is `0`. Arrow keys, Esc key, etc.
1972 *
1973 * - `which` is the pressed key code, but no char is available.
1974 * Ex: 'AltGr + d` in Polish. There is no modified character for
1975 * this key combination and no character is inserted into the
1976 * document, but FF fires the keypress for char code `100` anyway.
1977 * No `input` event will occur.
1978 *
1979 * - `which` is the pressed key code, but a command combination is
1980 * being used. Ex: `Cmd+C`. No character is inserted, and no
1981 * `input` event will occur.
1982 */
1983 if (!isKeypressCommand(nativeEvent)) {
1984 // IE fires the `keypress` event when a user types an emoji via
1985 // Touch keyboard of Windows. In such a case, the `char` property
1986 // holds an emoji character like `\uD83D\uDE0A`. Because its length
1987 // is 2, the property `which` does not represent an emoji correctly.
1988 // In such a case, we directly return the `char` property instead of
1989 // using `which`.
1990 if (nativeEvent.char && nativeEvent.char.length > 1) {
1991 return nativeEvent.char;
1992 } else if (nativeEvent.which) {
1993 return String.fromCharCode(nativeEvent.which);
1994 }
1995 }
1996 return null;
1997 case TOP_COMPOSITION_END:
1998 return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
1999 default:
2000 return null;
2001 }
2002}
2003
2004/**
2005 * Extract a SyntheticInputEvent for `beforeInput`, based on either native
2006 * `textInput` or fallback behavior.
2007 *
2008 * @return {?object} A SyntheticInputEvent.
2009 */
2010function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
2011 var chars = void 0;
2012
2013 if (canUseTextInputEvent) {
2014 chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
2015 } else {
2016 chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
2017 }
2018
2019 // If no characters are being inserted, no BeforeInput event should
2020 // be fired.
2021 if (!chars) {
2022 return null;
2023 }
2024
2025 var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);
2026
2027 event.data = chars;
2028 accumulateTwoPhaseDispatches(event);
2029 return event;
2030}
2031
2032/**
2033 * Create an `onBeforeInput` event to match
2034 * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
2035 *
2036 * This event plugin is based on the native `textInput` event
2037 * available in Chrome, Safari, Opera, and IE. This event fires after
2038 * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
2039 *
2040 * `beforeInput` is spec'd but not implemented in any browsers, and
2041 * the `input` event does not provide any useful information about what has
2042 * actually been added, contrary to the spec. Thus, `textInput` is the best
2043 * available event to identify the characters that have actually been inserted
2044 * into the target node.
2045 *
2046 * This plugin is also responsible for emitting `composition` events, thus
2047 * allowing us to share composition fallback code for both `beforeInput` and
2048 * `composition` event types.
2049 */
2050var BeforeInputEventPlugin = {
2051 eventTypes: eventTypes,
2052
2053 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
2054 var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
2055
2056 var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
2057
2058 if (composition === null) {
2059 return beforeInput;
2060 }
2061
2062 if (beforeInput === null) {
2063 return composition;
2064 }
2065
2066 return [composition, beforeInput];
2067 }
2068};
2069
2070// Use to restore controlled state after a change event has fired.
2071
2072var restoreImpl = null;
2073var restoreTarget = null;
2074var restoreQueue = null;
2075
2076function restoreStateOfTarget(target) {
2077 // We perform this translation at the end of the event loop so that we
2078 // always receive the correct fiber here
2079 var internalInstance = getInstanceFromNode(target);
2080 if (!internalInstance) {
2081 // Unmounted
2082 return;
2083 }
2084 !(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;
2085 var props = getFiberCurrentPropsFromNode(internalInstance.stateNode);
2086 restoreImpl(internalInstance.stateNode, internalInstance.type, props);
2087}
2088
2089function setRestoreImplementation(impl) {
2090 restoreImpl = impl;
2091}
2092
2093function enqueueStateRestore(target) {
2094 if (restoreTarget) {
2095 if (restoreQueue) {
2096 restoreQueue.push(target);
2097 } else {
2098 restoreQueue = [target];
2099 }
2100 } else {
2101 restoreTarget = target;
2102 }
2103}
2104
2105function needsStateRestore() {
2106 return restoreTarget !== null || restoreQueue !== null;
2107}
2108
2109function restoreStateIfNeeded() {
2110 if (!restoreTarget) {
2111 return;
2112 }
2113 var target = restoreTarget;
2114 var queuedTargets = restoreQueue;
2115 restoreTarget = null;
2116 restoreQueue = null;
2117
2118 restoreStateOfTarget(target);
2119 if (queuedTargets) {
2120 for (var i = 0; i < queuedTargets.length; i++) {
2121 restoreStateOfTarget(queuedTargets[i]);
2122 }
2123 }
2124}
2125
2126// Used as a way to call batchedUpdates when we don't have a reference to
2127// the renderer. Such as when we're dispatching events or if third party
2128// libraries need to call batchedUpdates. Eventually, this API will go away when
2129// everything is batched by default. We'll then have a similar API to opt-out of
2130// scheduled work and instead do synchronous work.
2131
2132// Defaults
2133var _batchedUpdatesImpl = function (fn, bookkeeping) {
2134 return fn(bookkeeping);
2135};
2136var _interactiveUpdatesImpl = function (fn, a, b) {
2137 return fn(a, b);
2138};
2139var _flushInteractiveUpdatesImpl = function () {};
2140
2141var isBatching = false;
2142function batchedUpdates(fn, bookkeeping) {
2143 if (isBatching) {
2144 // If we are currently inside another batch, we need to wait until it
2145 // fully completes before restoring state.
2146 return fn(bookkeeping);
2147 }
2148 isBatching = true;
2149 try {
2150 return _batchedUpdatesImpl(fn, bookkeeping);
2151 } finally {
2152 // Here we wait until all updates have propagated, which is important
2153 // when using controlled components within layers:
2154 // https://github.com/facebook/react/issues/1698
2155 // Then we restore state of any controlled component.
2156 isBatching = false;
2157 var controlledComponentsHavePendingUpdates = needsStateRestore();
2158 if (controlledComponentsHavePendingUpdates) {
2159 // If a controlled event was fired, we may need to restore the state of
2160 // the DOM node back to the controlled value. This is necessary when React
2161 // bails out of the update without touching the DOM.
2162 _flushInteractiveUpdatesImpl();
2163 restoreStateIfNeeded();
2164 }
2165 }
2166}
2167
2168function interactiveUpdates(fn, a, b) {
2169 return _interactiveUpdatesImpl(fn, a, b);
2170}
2171
2172
2173
2174function setBatchingImplementation(batchedUpdatesImpl, interactiveUpdatesImpl, flushInteractiveUpdatesImpl) {
2175 _batchedUpdatesImpl = batchedUpdatesImpl;
2176 _interactiveUpdatesImpl = interactiveUpdatesImpl;
2177 _flushInteractiveUpdatesImpl = flushInteractiveUpdatesImpl;
2178}
2179
2180/**
2181 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
2182 */
2183var supportedInputTypes = {
2184 color: true,
2185 date: true,
2186 datetime: true,
2187 'datetime-local': true,
2188 email: true,
2189 month: true,
2190 number: true,
2191 password: true,
2192 range: true,
2193 search: true,
2194 tel: true,
2195 text: true,
2196 time: true,
2197 url: true,
2198 week: true
2199};
2200
2201function isTextInputElement(elem) {
2202 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
2203
2204 if (nodeName === 'input') {
2205 return !!supportedInputTypes[elem.type];
2206 }
2207
2208 if (nodeName === 'textarea') {
2209 return true;
2210 }
2211
2212 return false;
2213}
2214
2215/**
2216 * HTML nodeType values that represent the type of the node
2217 */
2218
2219var ELEMENT_NODE = 1;
2220var TEXT_NODE = 3;
2221var COMMENT_NODE = 8;
2222var DOCUMENT_NODE = 9;
2223var DOCUMENT_FRAGMENT_NODE = 11;
2224
2225/**
2226 * Gets the target node from a native browser event by accounting for
2227 * inconsistencies in browser DOM APIs.
2228 *
2229 * @param {object} nativeEvent Native browser event.
2230 * @return {DOMEventTarget} Target node.
2231 */
2232function getEventTarget(nativeEvent) {
2233 // Fallback to nativeEvent.srcElement for IE9
2234 // https://github.com/facebook/react/issues/12506
2235 var target = nativeEvent.target || nativeEvent.srcElement || window;
2236
2237 // Normalize SVG <use> element events #4963
2238 if (target.correspondingUseElement) {
2239 target = target.correspondingUseElement;
2240 }
2241
2242 // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
2243 // @see http://www.quirksmode.org/js/events_properties.html
2244 return target.nodeType === TEXT_NODE ? target.parentNode : target;
2245}
2246
2247/**
2248 * Checks if an event is supported in the current execution environment.
2249 *
2250 * NOTE: This will not work correctly for non-generic events such as `change`,
2251 * `reset`, `load`, `error`, and `select`.
2252 *
2253 * Borrows from Modernizr.
2254 *
2255 * @param {string} eventNameSuffix Event name, e.g. "click".
2256 * @return {boolean} True if the event is supported.
2257 * @internal
2258 * @license Modernizr 3.0.0pre (Custom Build) | MIT
2259 */
2260function isEventSupported(eventNameSuffix) {
2261 if (!canUseDOM) {
2262 return false;
2263 }
2264
2265 var eventName = 'on' + eventNameSuffix;
2266 var isSupported = eventName in document;
2267
2268 if (!isSupported) {
2269 var element = document.createElement('div');
2270 element.setAttribute(eventName, 'return;');
2271 isSupported = typeof element[eventName] === 'function';
2272 }
2273
2274 return isSupported;
2275}
2276
2277function isCheckable(elem) {
2278 var type = elem.type;
2279 var nodeName = elem.nodeName;
2280 return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
2281}
2282
2283function getTracker(node) {
2284 return node._valueTracker;
2285}
2286
2287function detachTracker(node) {
2288 node._valueTracker = null;
2289}
2290
2291function getValueFromNode(node) {
2292 var value = '';
2293 if (!node) {
2294 return value;
2295 }
2296
2297 if (isCheckable(node)) {
2298 value = node.checked ? 'true' : 'false';
2299 } else {
2300 value = node.value;
2301 }
2302
2303 return value;
2304}
2305
2306function trackValueOnNode(node) {
2307 var valueField = isCheckable(node) ? 'checked' : 'value';
2308 var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
2309
2310 var currentValue = '' + node[valueField];
2311
2312 // if someone has already defined a value or Safari, then bail
2313 // and don't track value will cause over reporting of changes,
2314 // but it's better then a hard failure
2315 // (needed for certain tests that spyOn input values and Safari)
2316 if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
2317 return;
2318 }
2319 var get = descriptor.get,
2320 set = descriptor.set;
2321
2322 Object.defineProperty(node, valueField, {
2323 configurable: true,
2324 get: function () {
2325 return get.call(this);
2326 },
2327 set: function (value) {
2328 currentValue = '' + value;
2329 set.call(this, value);
2330 }
2331 });
2332 // We could've passed this the first time
2333 // but it triggers a bug in IE11 and Edge 14/15.
2334 // Calling defineProperty() again should be equivalent.
2335 // https://github.com/facebook/react/issues/11768
2336 Object.defineProperty(node, valueField, {
2337 enumerable: descriptor.enumerable
2338 });
2339
2340 var tracker = {
2341 getValue: function () {
2342 return currentValue;
2343 },
2344 setValue: function (value) {
2345 currentValue = '' + value;
2346 },
2347 stopTracking: function () {
2348 detachTracker(node);
2349 delete node[valueField];
2350 }
2351 };
2352 return tracker;
2353}
2354
2355function track(node) {
2356 if (getTracker(node)) {
2357 return;
2358 }
2359
2360 // TODO: Once it's just Fiber we can move this to node._wrapperState
2361 node._valueTracker = trackValueOnNode(node);
2362}
2363
2364function updateValueIfChanged(node) {
2365 if (!node) {
2366 return false;
2367 }
2368
2369 var tracker = getTracker(node);
2370 // if there is no tracker at this point it's unlikely
2371 // that trying again will succeed
2372 if (!tracker) {
2373 return true;
2374 }
2375
2376 var lastValue = tracker.getValue();
2377 var nextValue = getValueFromNode(node);
2378 if (nextValue !== lastValue) {
2379 tracker.setValue(nextValue);
2380 return true;
2381 }
2382 return false;
2383}
2384
2385var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
2386
2387// Prevent newer renderers from RTE when used with older react package versions.
2388// Current owner and dispatcher used to share the same ref,
2389// but PR #14548 split them out to better support the react-debug-tools package.
2390if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
2391 ReactSharedInternals.ReactCurrentDispatcher = {
2392 current: null
2393 };
2394}
2395
2396var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
2397
2398var describeComponentFrame = function (name, source, ownerName) {
2399 var sourceInfo = '';
2400 if (source) {
2401 var path = source.fileName;
2402 var fileName = path.replace(BEFORE_SLASH_RE, '');
2403 {
2404 // In DEV, include code for a common special case:
2405 // prefer "folder/index.js" instead of just "index.js".
2406 if (/^index\./.test(fileName)) {
2407 var match = path.match(BEFORE_SLASH_RE);
2408 if (match) {
2409 var pathBeforeSlash = match[1];
2410 if (pathBeforeSlash) {
2411 var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
2412 fileName = folderName + '/' + fileName;
2413 }
2414 }
2415 }
2416 }
2417 sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
2418 } else if (ownerName) {
2419 sourceInfo = ' (created by ' + ownerName + ')';
2420 }
2421 return '\n in ' + (name || 'Unknown') + sourceInfo;
2422};
2423
2424// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
2425// nor polyfill, then a plain number is used for performance.
2426var hasSymbol = typeof Symbol === 'function' && Symbol.for;
2427
2428var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
2429var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
2430var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
2431var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
2432var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
2433var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
2434var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
2435
2436var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
2437var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
2438var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
2439var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
2440var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
2441
2442var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
2443var FAUX_ITERATOR_SYMBOL = '@@iterator';
2444
2445function getIteratorFn(maybeIterable) {
2446 if (maybeIterable === null || typeof maybeIterable !== 'object') {
2447 return null;
2448 }
2449 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
2450 if (typeof maybeIterator === 'function') {
2451 return maybeIterator;
2452 }
2453 return null;
2454}
2455
2456var Pending = 0;
2457var Resolved = 1;
2458var Rejected = 2;
2459
2460function refineResolvedLazyComponent(lazyComponent) {
2461 return lazyComponent._status === Resolved ? lazyComponent._result : null;
2462}
2463
2464function getWrappedName(outerType, innerType, wrapperName) {
2465 var functionName = innerType.displayName || innerType.name || '';
2466 return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName);
2467}
2468
2469function getComponentName(type) {
2470 if (type == null) {
2471 // Host root, text node or just invalid type.
2472 return null;
2473 }
2474 {
2475 if (typeof type.tag === 'number') {
2476 warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
2477 }
2478 }
2479 if (typeof type === 'function') {
2480 return type.displayName || type.name || null;
2481 }
2482 if (typeof type === 'string') {
2483 return type;
2484 }
2485 switch (type) {
2486 case REACT_CONCURRENT_MODE_TYPE:
2487 return 'ConcurrentMode';
2488 case REACT_FRAGMENT_TYPE:
2489 return 'Fragment';
2490 case REACT_PORTAL_TYPE:
2491 return 'Portal';
2492 case REACT_PROFILER_TYPE:
2493 return 'Profiler';
2494 case REACT_STRICT_MODE_TYPE:
2495 return 'StrictMode';
2496 case REACT_SUSPENSE_TYPE:
2497 return 'Suspense';
2498 }
2499 if (typeof type === 'object') {
2500 switch (type.$$typeof) {
2501 case REACT_CONTEXT_TYPE:
2502 return 'Context.Consumer';
2503 case REACT_PROVIDER_TYPE:
2504 return 'Context.Provider';
2505 case REACT_FORWARD_REF_TYPE:
2506 return getWrappedName(type, type.render, 'ForwardRef');
2507 case REACT_MEMO_TYPE:
2508 return getComponentName(type.type);
2509 case REACT_LAZY_TYPE:
2510 {
2511 var thenable = type;
2512 var resolvedThenable = refineResolvedLazyComponent(thenable);
2513 if (resolvedThenable) {
2514 return getComponentName(resolvedThenable);
2515 }
2516 }
2517 }
2518 }
2519 return null;
2520}
2521
2522var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
2523
2524function describeFiber(fiber) {
2525 switch (fiber.tag) {
2526 case HostRoot:
2527 case HostPortal:
2528 case HostText:
2529 case Fragment:
2530 case ContextProvider:
2531 case ContextConsumer:
2532 return '';
2533 default:
2534 var owner = fiber._debugOwner;
2535 var source = fiber._debugSource;
2536 var name = getComponentName(fiber.type);
2537 var ownerName = null;
2538 if (owner) {
2539 ownerName = getComponentName(owner.type);
2540 }
2541 return describeComponentFrame(name, source, ownerName);
2542 }
2543}
2544
2545function getStackByFiberInDevAndProd(workInProgress) {
2546 var info = '';
2547 var node = workInProgress;
2548 do {
2549 info += describeFiber(node);
2550 node = node.return;
2551 } while (node);
2552 return info;
2553}
2554
2555var current = null;
2556var phase = null;
2557
2558function getCurrentFiberOwnerNameInDevOrNull() {
2559 {
2560 if (current === null) {
2561 return null;
2562 }
2563 var owner = current._debugOwner;
2564 if (owner !== null && typeof owner !== 'undefined') {
2565 return getComponentName(owner.type);
2566 }
2567 }
2568 return null;
2569}
2570
2571function getCurrentFiberStackInDev() {
2572 {
2573 if (current === null) {
2574 return '';
2575 }
2576 // Safe because if current fiber exists, we are reconciling,
2577 // and it is guaranteed to be the work-in-progress version.
2578 return getStackByFiberInDevAndProd(current);
2579 }
2580 return '';
2581}
2582
2583function resetCurrentFiber() {
2584 {
2585 ReactDebugCurrentFrame.getCurrentStack = null;
2586 current = null;
2587 phase = null;
2588 }
2589}
2590
2591function setCurrentFiber(fiber) {
2592 {
2593 ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev;
2594 current = fiber;
2595 phase = null;
2596 }
2597}
2598
2599function setCurrentPhase(lifeCyclePhase) {
2600 {
2601 phase = lifeCyclePhase;
2602 }
2603}
2604
2605/**
2606 * Similar to invariant but only logs a warning if the condition is not met.
2607 * This can be used to log issues in development environments in critical
2608 * paths. Removing the logging code for production environments will keep the
2609 * same logic and follow the same code paths.
2610 */
2611
2612var warning = warningWithoutStack$1;
2613
2614{
2615 warning = function (condition, format) {
2616 if (condition) {
2617 return;
2618 }
2619 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
2620 var stack = ReactDebugCurrentFrame.getStackAddendum();
2621 // eslint-disable-next-line react-internal/warning-and-invariant-args
2622
2623 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
2624 args[_key - 2] = arguments[_key];
2625 }
2626
2627 warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack]));
2628 };
2629}
2630
2631var warning$1 = warning;
2632
2633// A reserved attribute.
2634// It is handled by React separately and shouldn't be written to the DOM.
2635var RESERVED = 0;
2636
2637// A simple string attribute.
2638// Attributes that aren't in the whitelist are presumed to have this type.
2639var STRING = 1;
2640
2641// A string attribute that accepts booleans in React. In HTML, these are called
2642// "enumerated" attributes with "true" and "false" as possible values.
2643// When true, it should be set to a "true" string.
2644// When false, it should be set to a "false" string.
2645var BOOLEANISH_STRING = 2;
2646
2647// A real boolean attribute.
2648// When true, it should be present (set either to an empty string or its name).
2649// When false, it should be omitted.
2650var BOOLEAN = 3;
2651
2652// An attribute that can be used as a flag as well as with a value.
2653// When true, it should be present (set either to an empty string or its name).
2654// When false, it should be omitted.
2655// For any other value, should be present with that value.
2656var OVERLOADED_BOOLEAN = 4;
2657
2658// An attribute that must be numeric or parse as a numeric.
2659// When falsy, it should be removed.
2660var NUMERIC = 5;
2661
2662// An attribute that must be positive numeric or parse as a positive numeric.
2663// When falsy, it should be removed.
2664var POSITIVE_NUMERIC = 6;
2665
2666/* eslint-disable max-len */
2667var 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';
2668/* eslint-enable max-len */
2669var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040';
2670
2671
2672var ROOT_ATTRIBUTE_NAME = 'data-reactroot';
2673var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
2674
2675var hasOwnProperty = Object.prototype.hasOwnProperty;
2676var illegalAttributeNameCache = {};
2677var validatedAttributeNameCache = {};
2678
2679function isAttributeNameSafe(attributeName) {
2680 if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
2681 return true;
2682 }
2683 if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
2684 return false;
2685 }
2686 if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
2687 validatedAttributeNameCache[attributeName] = true;
2688 return true;
2689 }
2690 illegalAttributeNameCache[attributeName] = true;
2691 {
2692 warning$1(false, 'Invalid attribute name: `%s`', attributeName);
2693 }
2694 return false;
2695}
2696
2697function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
2698 if (propertyInfo !== null) {
2699 return propertyInfo.type === RESERVED;
2700 }
2701 if (isCustomComponentTag) {
2702 return false;
2703 }
2704 if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
2705 return true;
2706 }
2707 return false;
2708}
2709
2710function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
2711 if (propertyInfo !== null && propertyInfo.type === RESERVED) {
2712 return false;
2713 }
2714 switch (typeof value) {
2715 case 'function':
2716 // $FlowIssue symbol is perfectly valid here
2717 case 'symbol':
2718 // eslint-disable-line
2719 return true;
2720 case 'boolean':
2721 {
2722 if (isCustomComponentTag) {
2723 return false;
2724 }
2725 if (propertyInfo !== null) {
2726 return !propertyInfo.acceptsBooleans;
2727 } else {
2728 var prefix = name.toLowerCase().slice(0, 5);
2729 return prefix !== 'data-' && prefix !== 'aria-';
2730 }
2731 }
2732 default:
2733 return false;
2734 }
2735}
2736
2737function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
2738 if (value === null || typeof value === 'undefined') {
2739 return true;
2740 }
2741 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
2742 return true;
2743 }
2744 if (isCustomComponentTag) {
2745 return false;
2746 }
2747 if (propertyInfo !== null) {
2748 switch (propertyInfo.type) {
2749 case BOOLEAN:
2750 return !value;
2751 case OVERLOADED_BOOLEAN:
2752 return value === false;
2753 case NUMERIC:
2754 return isNaN(value);
2755 case POSITIVE_NUMERIC:
2756 return isNaN(value) || value < 1;
2757 }
2758 }
2759 return false;
2760}
2761
2762function getPropertyInfo(name) {
2763 return properties.hasOwnProperty(name) ? properties[name] : null;
2764}
2765
2766function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace) {
2767 this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
2768 this.attributeName = attributeName;
2769 this.attributeNamespace = attributeNamespace;
2770 this.mustUseProperty = mustUseProperty;
2771 this.propertyName = name;
2772 this.type = type;
2773}
2774
2775// When adding attributes to this list, be sure to also add them to
2776// the `possibleStandardNames` module to ensure casing and incorrect
2777// name warnings.
2778var properties = {};
2779
2780// These props are reserved by React. They shouldn't be written to the DOM.
2781['children', 'dangerouslySetInnerHTML',
2782// TODO: This prevents the assignment of defaultValue to regular
2783// elements (not just inputs). Now that ReactDOMInput assigns to the
2784// defaultValue property -- do we need this?
2785'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'].forEach(function (name) {
2786 properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
2787 name, // attributeName
2788 null);
2789} // attributeNamespace
2790);
2791
2792// A few React string attributes have a different name.
2793// This is a mapping from React prop names to the attribute names.
2794[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
2795 var name = _ref[0],
2796 attributeName = _ref[1];
2797
2798 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2799 attributeName, // attributeName
2800 null);
2801} // attributeNamespace
2802);
2803
2804// These are "enumerated" HTML attributes that accept "true" and "false".
2805// In React, we let users pass `true` and `false` even though technically
2806// these aren't boolean attributes (they are coerced to strings).
2807['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
2808 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2809 name.toLowerCase(), // attributeName
2810 null);
2811} // attributeNamespace
2812);
2813
2814// These are "enumerated" SVG attributes that accept "true" and "false".
2815// In React, we let users pass `true` and `false` even though technically
2816// these aren't boolean attributes (they are coerced to strings).
2817// Since these are SVG attributes, their attribute names are case-sensitive.
2818['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
2819 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2820 name, // attributeName
2821 null);
2822} // attributeNamespace
2823);
2824
2825// These are HTML boolean attributes.
2826['allowFullScreen', 'async',
2827// Note: there is a special case that prevents it from being written to the DOM
2828// on the client side because the browsers are inconsistent. Instead we call focus().
2829'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless',
2830// Microdata
2831'itemScope'].forEach(function (name) {
2832 properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
2833 name.toLowerCase(), // attributeName
2834 null);
2835} // attributeNamespace
2836);
2837
2838// These are the few React props that we set as DOM properties
2839// rather than attributes. These are all booleans.
2840['checked',
2841// Note: `option.selected` is not updated if `select.multiple` is
2842// disabled with `removeAttribute`. We have special logic for handling this.
2843'multiple', 'muted', 'selected'].forEach(function (name) {
2844 properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
2845 name, // attributeName
2846 null);
2847} // attributeNamespace
2848);
2849
2850// These are HTML attributes that are "overloaded booleans": they behave like
2851// booleans, but can also accept a string value.
2852['capture', 'download'].forEach(function (name) {
2853 properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
2854 name, // attributeName
2855 null);
2856} // attributeNamespace
2857);
2858
2859// These are HTML attributes that must be positive numbers.
2860['cols', 'rows', 'size', 'span'].forEach(function (name) {
2861 properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
2862 name, // attributeName
2863 null);
2864} // attributeNamespace
2865);
2866
2867// These are HTML attributes that must be numbers.
2868['rowSpan', 'start'].forEach(function (name) {
2869 properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
2870 name.toLowerCase(), // attributeName
2871 null);
2872} // attributeNamespace
2873);
2874
2875var CAMELIZE = /[\-\:]([a-z])/g;
2876var capitalize = function (token) {
2877 return token[1].toUpperCase();
2878};
2879
2880// This is a list of all SVG attributes that need special casing, namespacing,
2881// or boolean value assignment. Regular attributes that just accept strings
2882// and have the same names are omitted, just like in the HTML whitelist.
2883// Some of these attributes can be hard to find. This list was created by
2884// scrapping the MDN documentation.
2885['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) {
2886 var name = attributeName.replace(CAMELIZE, capitalize);
2887 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2888 attributeName, null);
2889} // attributeNamespace
2890);
2891
2892// String SVG attributes with the xlink namespace.
2893['xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type'].forEach(function (attributeName) {
2894 var name = attributeName.replace(CAMELIZE, capitalize);
2895 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2896 attributeName, 'http://www.w3.org/1999/xlink');
2897});
2898
2899// String SVG attributes with the xml namespace.
2900['xml:base', 'xml:lang', 'xml:space'].forEach(function (attributeName) {
2901 var name = attributeName.replace(CAMELIZE, capitalize);
2902 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2903 attributeName, 'http://www.w3.org/XML/1998/namespace');
2904});
2905
2906// Special case: this attribute exists both in HTML and SVG.
2907// Its "tabindex" attribute name is case-sensitive in SVG so we can't just use
2908// its React `tabIndex` name, like we do for attributes that exist only in HTML.
2909properties.tabIndex = new PropertyInfoRecord('tabIndex', STRING, false, // mustUseProperty
2910'tabindex', // attributeName
2911null);
2912
2913/**
2914 * Get the value for a property on a node. Only used in DEV for SSR validation.
2915 * The "expected" argument is used as a hint of what the expected value is.
2916 * Some properties have multiple equivalent values.
2917 */
2918function getValueForProperty(node, name, expected, propertyInfo) {
2919 {
2920 if (propertyInfo.mustUseProperty) {
2921 var propertyName = propertyInfo.propertyName;
2922
2923 return node[propertyName];
2924 } else {
2925 var attributeName = propertyInfo.attributeName;
2926
2927 var stringValue = null;
2928
2929 if (propertyInfo.type === OVERLOADED_BOOLEAN) {
2930 if (node.hasAttribute(attributeName)) {
2931 var value = node.getAttribute(attributeName);
2932 if (value === '') {
2933 return true;
2934 }
2935 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2936 return value;
2937 }
2938 if (value === '' + expected) {
2939 return expected;
2940 }
2941 return value;
2942 }
2943 } else if (node.hasAttribute(attributeName)) {
2944 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2945 // We had an attribute but shouldn't have had one, so read it
2946 // for the error message.
2947 return node.getAttribute(attributeName);
2948 }
2949 if (propertyInfo.type === BOOLEAN) {
2950 // If this was a boolean, it doesn't matter what the value is
2951 // the fact that we have it is the same as the expected.
2952 return expected;
2953 }
2954 // Even if this property uses a namespace we use getAttribute
2955 // because we assume its namespaced name is the same as our config.
2956 // To use getAttributeNS we need the local name which we don't have
2957 // in our config atm.
2958 stringValue = node.getAttribute(attributeName);
2959 }
2960
2961 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2962 return stringValue === null ? expected : stringValue;
2963 } else if (stringValue === '' + expected) {
2964 return expected;
2965 } else {
2966 return stringValue;
2967 }
2968 }
2969 }
2970}
2971
2972/**
2973 * Get the value for a attribute on a node. Only used in DEV for SSR validation.
2974 * The third argument is used as a hint of what the expected value is. Some
2975 * attributes have multiple equivalent values.
2976 */
2977function getValueForAttribute(node, name, expected) {
2978 {
2979 if (!isAttributeNameSafe(name)) {
2980 return;
2981 }
2982 if (!node.hasAttribute(name)) {
2983 return expected === undefined ? undefined : null;
2984 }
2985 var value = node.getAttribute(name);
2986 if (value === '' + expected) {
2987 return expected;
2988 }
2989 return value;
2990 }
2991}
2992
2993/**
2994 * Sets the value for a property on a node.
2995 *
2996 * @param {DOMElement} node
2997 * @param {string} name
2998 * @param {*} value
2999 */
3000function setValueForProperty(node, name, value, isCustomComponentTag) {
3001 var propertyInfo = getPropertyInfo(name);
3002 if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
3003 return;
3004 }
3005 if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
3006 value = null;
3007 }
3008 // If the prop isn't in the special list, treat it as a simple attribute.
3009 if (isCustomComponentTag || propertyInfo === null) {
3010 if (isAttributeNameSafe(name)) {
3011 var _attributeName = name;
3012 if (value === null) {
3013 node.removeAttribute(_attributeName);
3014 } else {
3015 node.setAttribute(_attributeName, '' + value);
3016 }
3017 }
3018 return;
3019 }
3020 var mustUseProperty = propertyInfo.mustUseProperty;
3021
3022 if (mustUseProperty) {
3023 var propertyName = propertyInfo.propertyName;
3024
3025 if (value === null) {
3026 var type = propertyInfo.type;
3027
3028 node[propertyName] = type === BOOLEAN ? false : '';
3029 } else {
3030 // Contrary to `setAttribute`, object properties are properly
3031 // `toString`ed by IE8/9.
3032 node[propertyName] = value;
3033 }
3034 return;
3035 }
3036 // The rest are treated as attributes with special cases.
3037 var attributeName = propertyInfo.attributeName,
3038 attributeNamespace = propertyInfo.attributeNamespace;
3039
3040 if (value === null) {
3041 node.removeAttribute(attributeName);
3042 } else {
3043 var _type = propertyInfo.type;
3044
3045 var attributeValue = void 0;
3046 if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
3047 attributeValue = '';
3048 } else {
3049 // `setAttribute` with objects becomes only `[object]` in IE8/9,
3050 // ('' + value) makes it output the correct toString()-value.
3051 attributeValue = '' + value;
3052 }
3053 if (attributeNamespace) {
3054 node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
3055 } else {
3056 node.setAttribute(attributeName, attributeValue);
3057 }
3058 }
3059}
3060
3061// Flow does not allow string concatenation of most non-string types. To work
3062// around this limitation, we use an opaque type that can only be obtained by
3063// passing the value through getToStringValue first.
3064function toString(value) {
3065 return '' + value;
3066}
3067
3068function getToStringValue(value) {
3069 switch (typeof value) {
3070 case 'boolean':
3071 case 'number':
3072 case 'object':
3073 case 'string':
3074 case 'undefined':
3075 return value;
3076 default:
3077 // function, symbol are assigned as empty strings
3078 return '';
3079 }
3080}
3081
3082var ReactDebugCurrentFrame$1 = null;
3083
3084var ReactControlledValuePropTypes = {
3085 checkPropTypes: null
3086};
3087
3088{
3089 ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
3090
3091 var hasReadOnlyValue = {
3092 button: true,
3093 checkbox: true,
3094 image: true,
3095 hidden: true,
3096 radio: true,
3097 reset: true,
3098 submit: true
3099 };
3100
3101 var propTypes = {
3102 value: function (props, propName, componentName) {
3103 if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null) {
3104 return null;
3105 }
3106 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`.');
3107 },
3108 checked: function (props, propName, componentName) {
3109 if (props.onChange || props.readOnly || props.disabled || props[propName] == null) {
3110 return null;
3111 }
3112 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`.');
3113 }
3114 };
3115
3116 /**
3117 * Provide a linked `value` attribute for controlled forms. You should not use
3118 * this outside of the ReactDOM controlled form components.
3119 */
3120 ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) {
3121 checkPropTypes(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$1.getStackAddendum);
3122 };
3123}
3124
3125var enableUserTimingAPI = true;
3126
3127// Helps identify side effects in begin-phase lifecycle hooks and setState reducers:
3128var debugRenderPhaseSideEffects = false;
3129
3130// In some cases, StrictMode should also double-render lifecycles.
3131// This can be confusing for tests though,
3132// And it can be bad for performance in production.
3133// This feature flag can be used to control the behavior:
3134var debugRenderPhaseSideEffectsForStrictMode = true;
3135
3136// To preserve the "Pause on caught exceptions" behavior of the debugger, we
3137// replay the begin phase of a failed component inside invokeGuardedCallback.
3138var replayFailedUnitOfWorkWithInvokeGuardedCallback = true;
3139
3140// Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:
3141var warnAboutDeprecatedLifecycles = false;
3142
3143// Gather advanced timing metrics for Profiler subtrees.
3144var enableProfilerTimer = true;
3145
3146// Trace which interactions trigger each commit.
3147var enableSchedulerTracing = true;
3148
3149// Only used in www builds.
3150 // TODO: true? Here it might just be false.
3151
3152// Only used in www builds.
3153
3154
3155// Only used in www builds.
3156
3157
3158// React Fire: prevent the value and checked attributes from syncing
3159// with their related DOM properties
3160var disableInputAttributeSyncing = false;
3161
3162// These APIs will no longer be "unstable" in the upcoming 16.7 release,
3163// Control this behavior with a flag to support 16.6 minor releases in the meanwhile.
3164var enableStableConcurrentModeAPIs = false;
3165
3166var warnAboutShorthandPropertyCollision = false;
3167
3168// TODO: direct imports like some-package/src/* are bad. Fix me.
3169var didWarnValueDefaultValue = false;
3170var didWarnCheckedDefaultChecked = false;
3171var didWarnControlledToUncontrolled = false;
3172var didWarnUncontrolledToControlled = false;
3173
3174function isControlled(props) {
3175 var usesChecked = props.type === 'checkbox' || props.type === 'radio';
3176 return usesChecked ? props.checked != null : props.value != null;
3177}
3178
3179/**
3180 * Implements an <input> host component that allows setting these optional
3181 * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
3182 *
3183 * If `checked` or `value` are not supplied (or null/undefined), user actions
3184 * that affect the checked state or value will trigger updates to the element.
3185 *
3186 * If they are supplied (and not null/undefined), the rendered element will not
3187 * trigger updates to the element. Instead, the props must change in order for
3188 * the rendered element to be updated.
3189 *
3190 * The rendered element will be initialized as unchecked (or `defaultChecked`)
3191 * with an empty value (or `defaultValue`).
3192 *
3193 * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
3194 */
3195
3196function getHostProps(element, props) {
3197 var node = element;
3198 var checked = props.checked;
3199
3200 var hostProps = _assign({}, props, {
3201 defaultChecked: undefined,
3202 defaultValue: undefined,
3203 value: undefined,
3204 checked: checked != null ? checked : node._wrapperState.initialChecked
3205 });
3206
3207 return hostProps;
3208}
3209
3210function initWrapperState(element, props) {
3211 {
3212 ReactControlledValuePropTypes.checkPropTypes('input', props);
3213
3214 if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
3215 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);
3216 didWarnCheckedDefaultChecked = true;
3217 }
3218 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
3219 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);
3220 didWarnValueDefaultValue = true;
3221 }
3222 }
3223
3224 var node = element;
3225 var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
3226
3227 node._wrapperState = {
3228 initialChecked: props.checked != null ? props.checked : props.defaultChecked,
3229 initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
3230 controlled: isControlled(props)
3231 };
3232}
3233
3234function updateChecked(element, props) {
3235 var node = element;
3236 var checked = props.checked;
3237 if (checked != null) {
3238 setValueForProperty(node, 'checked', checked, false);
3239 }
3240}
3241
3242function updateWrapper(element, props) {
3243 var node = element;
3244 {
3245 var _controlled = isControlled(props);
3246
3247 if (!node._wrapperState.controlled && _controlled && !didWarnUncontrolledToControlled) {
3248 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);
3249 didWarnUncontrolledToControlled = true;
3250 }
3251 if (node._wrapperState.controlled && !_controlled && !didWarnControlledToUncontrolled) {
3252 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);
3253 didWarnControlledToUncontrolled = true;
3254 }
3255 }
3256
3257 updateChecked(element, props);
3258
3259 var value = getToStringValue(props.value);
3260 var type = props.type;
3261
3262 if (value != null) {
3263 if (type === 'number') {
3264 if (value === 0 && node.value === '' ||
3265 // We explicitly want to coerce to number here if possible.
3266 // eslint-disable-next-line
3267 node.value != value) {
3268 node.value = toString(value);
3269 }
3270 } else if (node.value !== toString(value)) {
3271 node.value = toString(value);
3272 }
3273 } else if (type === 'submit' || type === 'reset') {
3274 // Submit/reset inputs need the attribute removed completely to avoid
3275 // blank-text buttons.
3276 node.removeAttribute('value');
3277 return;
3278 }
3279
3280 if (disableInputAttributeSyncing) {
3281 // When not syncing the value attribute, React only assigns a new value
3282 // whenever the defaultValue React prop has changed. When not present,
3283 // React does nothing
3284 if (props.hasOwnProperty('defaultValue')) {
3285 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
3286 }
3287 } else {
3288 // When syncing the value attribute, the value comes from a cascade of
3289 // properties:
3290 // 1. The value React property
3291 // 2. The defaultValue React property
3292 // 3. Otherwise there should be no change
3293 if (props.hasOwnProperty('value')) {
3294 setDefaultValue(node, props.type, value);
3295 } else if (props.hasOwnProperty('defaultValue')) {
3296 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
3297 }
3298 }
3299
3300 if (disableInputAttributeSyncing) {
3301 // When not syncing the checked attribute, the attribute is directly
3302 // controllable from the defaultValue React property. It needs to be
3303 // updated as new props come in.
3304 if (props.defaultChecked == null) {
3305 node.removeAttribute('checked');
3306 } else {
3307 node.defaultChecked = !!props.defaultChecked;
3308 }
3309 } else {
3310 // When syncing the checked attribute, it only changes when it needs
3311 // to be removed, such as transitioning from a checkbox into a text input
3312 if (props.checked == null && props.defaultChecked != null) {
3313 node.defaultChecked = !!props.defaultChecked;
3314 }
3315 }
3316}
3317
3318function postMountWrapper(element, props, isHydrating) {
3319 var node = element;
3320
3321 // Do not assign value if it is already set. This prevents user text input
3322 // from being lost during SSR hydration.
3323 if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
3324 var type = props.type;
3325 var isButton = type === 'submit' || type === 'reset';
3326
3327 // Avoid setting value attribute on submit/reset inputs as it overrides the
3328 // default value provided by the browser. See: #12872
3329 if (isButton && (props.value === undefined || props.value === null)) {
3330 return;
3331 }
3332
3333 var _initialValue = toString(node._wrapperState.initialValue);
3334
3335 // Do not assign value if it is already set. This prevents user text input
3336 // from being lost during SSR hydration.
3337 if (!isHydrating) {
3338 if (disableInputAttributeSyncing) {
3339 var value = getToStringValue(props.value);
3340
3341 // When not syncing the value attribute, the value property points
3342 // directly to the React prop. Only assign it if it exists.
3343 if (value != null) {
3344 // Always assign on buttons so that it is possible to assign an
3345 // empty string to clear button text.
3346 //
3347 // Otherwise, do not re-assign the value property if is empty. This
3348 // potentially avoids a DOM write and prevents Firefox (~60.0.1) from
3349 // prematurely marking required inputs as invalid. Equality is compared
3350 // to the current value in case the browser provided value is not an
3351 // empty string.
3352 if (isButton || value !== node.value) {
3353 node.value = toString(value);
3354 }
3355 }
3356 } else {
3357 // When syncing the value attribute, the value property should use
3358 // the wrapperState._initialValue property. This uses:
3359 //
3360 // 1. The value React property when present
3361 // 2. The defaultValue React property when present
3362 // 3. An empty string
3363 if (_initialValue !== node.value) {
3364 node.value = _initialValue;
3365 }
3366 }
3367 }
3368
3369 if (disableInputAttributeSyncing) {
3370 // When not syncing the value attribute, assign the value attribute
3371 // directly from the defaultValue React property (when present)
3372 var defaultValue = getToStringValue(props.defaultValue);
3373 if (defaultValue != null) {
3374 node.defaultValue = toString(defaultValue);
3375 }
3376 } else {
3377 // Otherwise, the value attribute is synchronized to the property,
3378 // so we assign defaultValue to the same thing as the value property
3379 // assignment step above.
3380 node.defaultValue = _initialValue;
3381 }
3382 }
3383
3384 // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
3385 // this is needed to work around a chrome bug where setting defaultChecked
3386 // will sometimes influence the value of checked (even after detachment).
3387 // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
3388 // We need to temporarily unset name to avoid disrupting radio button groups.
3389 var name = node.name;
3390 if (name !== '') {
3391 node.name = '';
3392 }
3393
3394 if (disableInputAttributeSyncing) {
3395 // When not syncing the checked attribute, the checked property
3396 // never gets assigned. It must be manually set. We don't want
3397 // to do this when hydrating so that existing user input isn't
3398 // modified
3399 if (!isHydrating) {
3400 updateChecked(element, props);
3401 }
3402
3403 // Only assign the checked attribute if it is defined. This saves
3404 // a DOM write when controlling the checked attribute isn't needed
3405 // (text inputs, submit/reset)
3406 if (props.hasOwnProperty('defaultChecked')) {
3407 node.defaultChecked = !node.defaultChecked;
3408 node.defaultChecked = !!props.defaultChecked;
3409 }
3410 } else {
3411 // When syncing the checked attribute, both the checked property and
3412 // attribute are assigned at the same time using defaultChecked. This uses:
3413 //
3414 // 1. The checked React property when present
3415 // 2. The defaultChecked React property when present
3416 // 3. Otherwise, false
3417 node.defaultChecked = !node.defaultChecked;
3418 node.defaultChecked = !!node._wrapperState.initialChecked;
3419 }
3420
3421 if (name !== '') {
3422 node.name = name;
3423 }
3424}
3425
3426function restoreControlledState(element, props) {
3427 var node = element;
3428 updateWrapper(node, props);
3429 updateNamedCousins(node, props);
3430}
3431
3432function updateNamedCousins(rootNode, props) {
3433 var name = props.name;
3434 if (props.type === 'radio' && name != null) {
3435 var queryRoot = rootNode;
3436
3437 while (queryRoot.parentNode) {
3438 queryRoot = queryRoot.parentNode;
3439 }
3440
3441 // If `rootNode.form` was non-null, then we could try `form.elements`,
3442 // but that sometimes behaves strangely in IE8. We could also try using
3443 // `form.getElementsByName`, but that will only return direct children
3444 // and won't include inputs that use the HTML5 `form=` attribute. Since
3445 // the input might not even be in a form. It might not even be in the
3446 // document. Let's just use the local `querySelectorAll` to ensure we don't
3447 // miss anything.
3448 var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
3449
3450 for (var i = 0; i < group.length; i++) {
3451 var otherNode = group[i];
3452 if (otherNode === rootNode || otherNode.form !== rootNode.form) {
3453 continue;
3454 }
3455 // This will throw if radio buttons rendered by different copies of React
3456 // and the same name are rendered into the same form (same as #1939).
3457 // That's probably okay; we don't support it just as we don't support
3458 // mixing React radio buttons with non-React ones.
3459 var otherProps = getFiberCurrentPropsFromNode$1(otherNode);
3460 !otherProps ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : void 0;
3461
3462 // We need update the tracked value on the named cousin since the value
3463 // was changed but the input saw no event or value set
3464 updateValueIfChanged(otherNode);
3465
3466 // If this is a controlled radio button group, forcing the input that
3467 // was previously checked to update will cause it to be come re-checked
3468 // as appropriate.
3469 updateWrapper(otherNode, otherProps);
3470 }
3471 }
3472}
3473
3474// In Chrome, assigning defaultValue to certain input types triggers input validation.
3475// For number inputs, the display value loses trailing decimal points. For email inputs,
3476// Chrome raises "The specified value <x> is not a valid email address".
3477//
3478// Here we check to see if the defaultValue has actually changed, avoiding these problems
3479// when the user is inputting text
3480//
3481// https://github.com/facebook/react/issues/7253
3482function setDefaultValue(node, type, value) {
3483 if (
3484 // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
3485 type !== 'number' || node.ownerDocument.activeElement !== node) {
3486 if (value == null) {
3487 node.defaultValue = toString(node._wrapperState.initialValue);
3488 } else if (node.defaultValue !== toString(value)) {
3489 node.defaultValue = toString(value);
3490 }
3491 }
3492}
3493
3494var eventTypes$1 = {
3495 change: {
3496 phasedRegistrationNames: {
3497 bubbled: 'onChange',
3498 captured: 'onChangeCapture'
3499 },
3500 dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE]
3501 }
3502};
3503
3504function createAndAccumulateChangeEvent(inst, nativeEvent, target) {
3505 var event = SyntheticEvent.getPooled(eventTypes$1.change, inst, nativeEvent, target);
3506 event.type = 'change';
3507 // Flag this event loop as needing state restore.
3508 enqueueStateRestore(target);
3509 accumulateTwoPhaseDispatches(event);
3510 return event;
3511}
3512/**
3513 * For IE shims
3514 */
3515var activeElement = null;
3516var activeElementInst = null;
3517
3518/**
3519 * SECTION: handle `change` event
3520 */
3521function shouldUseChangeEvent(elem) {
3522 var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
3523 return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
3524}
3525
3526function manualDispatchChangeEvent(nativeEvent) {
3527 var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent));
3528
3529 // If change and propertychange bubbled, we'd just bind to it like all the
3530 // other events and have it go through ReactBrowserEventEmitter. Since it
3531 // doesn't, we manually listen for the events and so we have to enqueue and
3532 // process the abstract event manually.
3533 //
3534 // Batching is necessary here in order to ensure that all event handlers run
3535 // before the next rerender (including event handlers attached to ancestor
3536 // elements instead of directly on the input). Without this, controlled
3537 // components don't work properly in conjunction with event bubbling because
3538 // the component is rerendered and the value reverted before all the event
3539 // handlers can run. See https://github.com/facebook/react/issues/708.
3540 batchedUpdates(runEventInBatch, event);
3541}
3542
3543function runEventInBatch(event) {
3544 runEventsInBatch(event);
3545}
3546
3547function getInstIfValueChanged(targetInst) {
3548 var targetNode = getNodeFromInstance$1(targetInst);
3549 if (updateValueIfChanged(targetNode)) {
3550 return targetInst;
3551 }
3552}
3553
3554function getTargetInstForChangeEvent(topLevelType, targetInst) {
3555 if (topLevelType === TOP_CHANGE) {
3556 return targetInst;
3557 }
3558}
3559
3560/**
3561 * SECTION: handle `input` event
3562 */
3563var isInputEventSupported = false;
3564if (canUseDOM) {
3565 // IE9 claims to support the input event but fails to trigger it when
3566 // deleting text, so we ignore its input events.
3567 isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
3568}
3569
3570/**
3571 * (For IE <=9) Starts tracking propertychange events on the passed-in element
3572 * and override the value property so that we can distinguish user events from
3573 * value changes in JS.
3574 */
3575function startWatchingForValueChange(target, targetInst) {
3576 activeElement = target;
3577 activeElementInst = targetInst;
3578 activeElement.attachEvent('onpropertychange', handlePropertyChange);
3579}
3580
3581/**
3582 * (For IE <=9) Removes the event listeners from the currently-tracked element,
3583 * if any exists.
3584 */
3585function stopWatchingForValueChange() {
3586 if (!activeElement) {
3587 return;
3588 }
3589 activeElement.detachEvent('onpropertychange', handlePropertyChange);
3590 activeElement = null;
3591 activeElementInst = null;
3592}
3593
3594/**
3595 * (For IE <=9) Handles a propertychange event, sending a `change` event if
3596 * the value of the active element has changed.
3597 */
3598function handlePropertyChange(nativeEvent) {
3599 if (nativeEvent.propertyName !== 'value') {
3600 return;
3601 }
3602 if (getInstIfValueChanged(activeElementInst)) {
3603 manualDispatchChangeEvent(nativeEvent);
3604 }
3605}
3606
3607function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
3608 if (topLevelType === TOP_FOCUS) {
3609 // In IE9, propertychange fires for most input events but is buggy and
3610 // doesn't fire when text is deleted, but conveniently, selectionchange
3611 // appears to fire in all of the remaining cases so we catch those and
3612 // forward the event if the value has changed
3613 // In either case, we don't want to call the event handler if the value
3614 // is changed from JS so we redefine a setter for `.value` that updates
3615 // our activeElementValue variable, allowing us to ignore those changes
3616 //
3617 // stopWatching() should be a noop here but we call it just in case we
3618 // missed a blur event somehow.
3619 stopWatchingForValueChange();
3620 startWatchingForValueChange(target, targetInst);
3621 } else if (topLevelType === TOP_BLUR) {
3622 stopWatchingForValueChange();
3623 }
3624}
3625
3626// For IE8 and IE9.
3627function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {
3628 if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {
3629 // On the selectionchange event, the target is just document which isn't
3630 // helpful for us so just check activeElement instead.
3631 //
3632 // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
3633 // propertychange on the first input event after setting `value` from a
3634 // script and fires only keydown, keypress, keyup. Catching keyup usually
3635 // gets it and catching keydown lets us fire an event for the first
3636 // keystroke if user does a key repeat (it'll be a little delayed: right
3637 // before the second keystroke). Other input methods (e.g., paste) seem to
3638 // fire selectionchange normally.
3639 return getInstIfValueChanged(activeElementInst);
3640 }
3641}
3642
3643/**
3644 * SECTION: handle `click` event
3645 */
3646function shouldUseClickEvent(elem) {
3647 // Use the `click` event to detect changes to checkbox and radio inputs.
3648 // This approach works across all browsers, whereas `change` does not fire
3649 // until `blur` in IE8.
3650 var nodeName = elem.nodeName;
3651 return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
3652}
3653
3654function getTargetInstForClickEvent(topLevelType, targetInst) {
3655 if (topLevelType === TOP_CLICK) {
3656 return getInstIfValueChanged(targetInst);
3657 }
3658}
3659
3660function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {
3661 if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) {
3662 return getInstIfValueChanged(targetInst);
3663 }
3664}
3665
3666function handleControlledInputBlur(node) {
3667 var state = node._wrapperState;
3668
3669 if (!state || !state.controlled || node.type !== 'number') {
3670 return;
3671 }
3672
3673 if (!disableInputAttributeSyncing) {
3674 // If controlled, assign the value attribute to the current value on blur
3675 setDefaultValue(node, 'number', node.value);
3676 }
3677}
3678
3679/**
3680 * This plugin creates an `onChange` event that normalizes change events
3681 * across form elements. This event fires at a time when it's possible to
3682 * change the element's value without seeing a flicker.
3683 *
3684 * Supported elements are:
3685 * - input (see `isTextInputElement`)
3686 * - textarea
3687 * - select
3688 */
3689var ChangeEventPlugin = {
3690 eventTypes: eventTypes$1,
3691
3692 _isInputEventSupported: isInputEventSupported,
3693
3694 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
3695 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
3696
3697 var getTargetInstFunc = void 0,
3698 handleEventFunc = void 0;
3699 if (shouldUseChangeEvent(targetNode)) {
3700 getTargetInstFunc = getTargetInstForChangeEvent;
3701 } else if (isTextInputElement(targetNode)) {
3702 if (isInputEventSupported) {
3703 getTargetInstFunc = getTargetInstForInputOrChangeEvent;
3704 } else {
3705 getTargetInstFunc = getTargetInstForInputEventPolyfill;
3706 handleEventFunc = handleEventsForInputEventPolyfill;
3707 }
3708 } else if (shouldUseClickEvent(targetNode)) {
3709 getTargetInstFunc = getTargetInstForClickEvent;
3710 }
3711
3712 if (getTargetInstFunc) {
3713 var inst = getTargetInstFunc(topLevelType, targetInst);
3714 if (inst) {
3715 var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget);
3716 return event;
3717 }
3718 }
3719
3720 if (handleEventFunc) {
3721 handleEventFunc(topLevelType, targetNode, targetInst);
3722 }
3723
3724 // When blurring, set the value attribute for number inputs
3725 if (topLevelType === TOP_BLUR) {
3726 handleControlledInputBlur(targetNode);
3727 }
3728 }
3729};
3730
3731/**
3732 * Module that is injectable into `EventPluginHub`, that specifies a
3733 * deterministic ordering of `EventPlugin`s. A convenient way to reason about
3734 * plugins, without having to package every one of them. This is better than
3735 * having plugins be ordered in the same order that they are injected because
3736 * that ordering would be influenced by the packaging order.
3737 * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
3738 * preventing default on events is convenient in `SimpleEventPlugin` handlers.
3739 */
3740var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];
3741
3742var SyntheticUIEvent = SyntheticEvent.extend({
3743 view: null,
3744 detail: null
3745});
3746
3747var modifierKeyToProp = {
3748 Alt: 'altKey',
3749 Control: 'ctrlKey',
3750 Meta: 'metaKey',
3751 Shift: 'shiftKey'
3752};
3753
3754// Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
3755// getModifierState. If getModifierState is not supported, we map it to a set of
3756// modifier keys exposed by the event. In this case, Lock-keys are not supported.
3757/**
3758 * Translation from modifier key to the associated property in the event.
3759 * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
3760 */
3761
3762function modifierStateGetter(keyArg) {
3763 var syntheticEvent = this;
3764 var nativeEvent = syntheticEvent.nativeEvent;
3765 if (nativeEvent.getModifierState) {
3766 return nativeEvent.getModifierState(keyArg);
3767 }
3768 var keyProp = modifierKeyToProp[keyArg];
3769 return keyProp ? !!nativeEvent[keyProp] : false;
3770}
3771
3772function getEventModifierState(nativeEvent) {
3773 return modifierStateGetter;
3774}
3775
3776var previousScreenX = 0;
3777var previousScreenY = 0;
3778// Use flags to signal movementX/Y has already been set
3779var isMovementXSet = false;
3780var isMovementYSet = false;
3781
3782/**
3783 * @interface MouseEvent
3784 * @see http://www.w3.org/TR/DOM-Level-3-Events/
3785 */
3786var SyntheticMouseEvent = SyntheticUIEvent.extend({
3787 screenX: null,
3788 screenY: null,
3789 clientX: null,
3790 clientY: null,
3791 pageX: null,
3792 pageY: null,
3793 ctrlKey: null,
3794 shiftKey: null,
3795 altKey: null,
3796 metaKey: null,
3797 getModifierState: getEventModifierState,
3798 button: null,
3799 buttons: null,
3800 relatedTarget: function (event) {
3801 return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
3802 },
3803 movementX: function (event) {
3804 if ('movementX' in event) {
3805 return event.movementX;
3806 }
3807
3808 var screenX = previousScreenX;
3809 previousScreenX = event.screenX;
3810
3811 if (!isMovementXSet) {
3812 isMovementXSet = true;
3813 return 0;
3814 }
3815
3816 return event.type === 'mousemove' ? event.screenX - screenX : 0;
3817 },
3818 movementY: function (event) {
3819 if ('movementY' in event) {
3820 return event.movementY;
3821 }
3822
3823 var screenY = previousScreenY;
3824 previousScreenY = event.screenY;
3825
3826 if (!isMovementYSet) {
3827 isMovementYSet = true;
3828 return 0;
3829 }
3830
3831 return event.type === 'mousemove' ? event.screenY - screenY : 0;
3832 }
3833});
3834
3835/**
3836 * @interface PointerEvent
3837 * @see http://www.w3.org/TR/pointerevents/
3838 */
3839var SyntheticPointerEvent = SyntheticMouseEvent.extend({
3840 pointerId: null,
3841 width: null,
3842 height: null,
3843 pressure: null,
3844 tangentialPressure: null,
3845 tiltX: null,
3846 tiltY: null,
3847 twist: null,
3848 pointerType: null,
3849 isPrimary: null
3850});
3851
3852var eventTypes$2 = {
3853 mouseEnter: {
3854 registrationName: 'onMouseEnter',
3855 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
3856 },
3857 mouseLeave: {
3858 registrationName: 'onMouseLeave',
3859 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
3860 },
3861 pointerEnter: {
3862 registrationName: 'onPointerEnter',
3863 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
3864 },
3865 pointerLeave: {
3866 registrationName: 'onPointerLeave',
3867 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
3868 }
3869};
3870
3871var EnterLeaveEventPlugin = {
3872 eventTypes: eventTypes$2,
3873
3874 /**
3875 * For almost every interaction we care about, there will be both a top-level
3876 * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
3877 * we do not extract duplicate events. However, moving the mouse into the
3878 * browser from outside will not fire a `mouseout` event. In this case, we use
3879 * the `mouseover` top-level event.
3880 */
3881 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
3882 var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
3883 var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;
3884
3885 if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
3886 return null;
3887 }
3888
3889 if (!isOutEvent && !isOverEvent) {
3890 // Must not be a mouse or pointer in or out - ignoring.
3891 return null;
3892 }
3893
3894 var win = void 0;
3895 if (nativeEventTarget.window === nativeEventTarget) {
3896 // `nativeEventTarget` is probably a window object.
3897 win = nativeEventTarget;
3898 } else {
3899 // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
3900 var doc = nativeEventTarget.ownerDocument;
3901 if (doc) {
3902 win = doc.defaultView || doc.parentWindow;
3903 } else {
3904 win = window;
3905 }
3906 }
3907
3908 var from = void 0;
3909 var to = void 0;
3910 if (isOutEvent) {
3911 from = targetInst;
3912 var related = nativeEvent.relatedTarget || nativeEvent.toElement;
3913 to = related ? getClosestInstanceFromNode(related) : null;
3914 } else {
3915 // Moving to a node from outside the window.
3916 from = null;
3917 to = targetInst;
3918 }
3919
3920 if (from === to) {
3921 // Nothing pertains to our managed components.
3922 return null;
3923 }
3924
3925 var eventInterface = void 0,
3926 leaveEventType = void 0,
3927 enterEventType = void 0,
3928 eventTypePrefix = void 0;
3929
3930 if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
3931 eventInterface = SyntheticMouseEvent;
3932 leaveEventType = eventTypes$2.mouseLeave;
3933 enterEventType = eventTypes$2.mouseEnter;
3934 eventTypePrefix = 'mouse';
3935 } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {
3936 eventInterface = SyntheticPointerEvent;
3937 leaveEventType = eventTypes$2.pointerLeave;
3938 enterEventType = eventTypes$2.pointerEnter;
3939 eventTypePrefix = 'pointer';
3940 }
3941
3942 var fromNode = from == null ? win : getNodeFromInstance$1(from);
3943 var toNode = to == null ? win : getNodeFromInstance$1(to);
3944
3945 var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);
3946 leave.type = eventTypePrefix + 'leave';
3947 leave.target = fromNode;
3948 leave.relatedTarget = toNode;
3949
3950 var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);
3951 enter.type = eventTypePrefix + 'enter';
3952 enter.target = toNode;
3953 enter.relatedTarget = fromNode;
3954
3955 accumulateEnterLeaveDispatches(leave, enter, from, to);
3956
3957 return [leave, enter];
3958 }
3959};
3960
3961/**
3962 * inlined Object.is polyfill to avoid requiring consumers ship their own
3963 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
3964 */
3965function is(x, y) {
3966 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
3967 ;
3968}
3969
3970var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
3971
3972/**
3973 * Performs equality by iterating through keys on an object and returning false
3974 * when any key has values which are not strictly equal between the arguments.
3975 * Returns true when the values of all keys are strictly equal.
3976 */
3977function shallowEqual(objA, objB) {
3978 if (is(objA, objB)) {
3979 return true;
3980 }
3981
3982 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
3983 return false;
3984 }
3985
3986 var keysA = Object.keys(objA);
3987 var keysB = Object.keys(objB);
3988
3989 if (keysA.length !== keysB.length) {
3990 return false;
3991 }
3992
3993 // Test for A's keys different from B.
3994 for (var i = 0; i < keysA.length; i++) {
3995 if (!hasOwnProperty$1.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
3996 return false;
3997 }
3998 }
3999
4000 return true;
4001}
4002
4003/**
4004 * `ReactInstanceMap` maintains a mapping from a public facing stateful
4005 * instance (key) and the internal representation (value). This allows public
4006 * methods to accept the user facing instance as an argument and map them back
4007 * to internal methods.
4008 *
4009 * Note that this module is currently shared and assumed to be stateless.
4010 * If this becomes an actual Map, that will break.
4011 */
4012
4013/**
4014 * This API should be called `delete` but we'd have to make sure to always
4015 * transform these to strings for IE support. When this transform is fully
4016 * supported we can rename it.
4017 */
4018
4019
4020function get(key) {
4021 return key._reactInternalFiber;
4022}
4023
4024function has(key) {
4025 return key._reactInternalFiber !== undefined;
4026}
4027
4028function set(key, value) {
4029 key._reactInternalFiber = value;
4030}
4031
4032// Don't change these two values. They're used by React Dev Tools.
4033var NoEffect = /* */0;
4034var PerformedWork = /* */1;
4035
4036// You can change the rest (and add more).
4037var Placement = /* */2;
4038var Update = /* */4;
4039var PlacementAndUpdate = /* */6;
4040var Deletion = /* */8;
4041var ContentReset = /* */16;
4042var Callback = /* */32;
4043var DidCapture = /* */64;
4044var Ref = /* */128;
4045var Snapshot = /* */256;
4046var Passive = /* */512;
4047
4048// Passive & Update & Callback & Ref & Snapshot
4049var LifecycleEffectMask = /* */932;
4050
4051// Union of all host effects
4052var HostEffectMask = /* */1023;
4053
4054var Incomplete = /* */1024;
4055var ShouldCapture = /* */2048;
4056
4057var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
4058
4059var MOUNTING = 1;
4060var MOUNTED = 2;
4061var UNMOUNTED = 3;
4062
4063function isFiberMountedImpl(fiber) {
4064 var node = fiber;
4065 if (!fiber.alternate) {
4066 // If there is no alternate, this might be a new tree that isn't inserted
4067 // yet. If it is, then it will have a pending insertion effect on it.
4068 if ((node.effectTag & Placement) !== NoEffect) {
4069 return MOUNTING;
4070 }
4071 while (node.return) {
4072 node = node.return;
4073 if ((node.effectTag & Placement) !== NoEffect) {
4074 return MOUNTING;
4075 }
4076 }
4077 } else {
4078 while (node.return) {
4079 node = node.return;
4080 }
4081 }
4082 if (node.tag === HostRoot) {
4083 // TODO: Check if this was a nested HostRoot when used with
4084 // renderContainerIntoSubtree.
4085 return MOUNTED;
4086 }
4087 // If we didn't hit the root, that means that we're in an disconnected tree
4088 // that has been unmounted.
4089 return UNMOUNTED;
4090}
4091
4092function isFiberMounted(fiber) {
4093 return isFiberMountedImpl(fiber) === MOUNTED;
4094}
4095
4096function isMounted(component) {
4097 {
4098 var owner = ReactCurrentOwner$1.current;
4099 if (owner !== null && owner.tag === ClassComponent) {
4100 var ownerFiber = owner;
4101 var instance = ownerFiber.stateNode;
4102 !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;
4103 instance._warnedAboutRefsInRender = true;
4104 }
4105 }
4106
4107 var fiber = get(component);
4108 if (!fiber) {
4109 return false;
4110 }
4111 return isFiberMountedImpl(fiber) === MOUNTED;
4112}
4113
4114function assertIsMounted(fiber) {
4115 !(isFiberMountedImpl(fiber) === MOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
4116}
4117
4118function findCurrentFiberUsingSlowPath(fiber) {
4119 var alternate = fiber.alternate;
4120 if (!alternate) {
4121 // If there is no alternate, then we only need to check if it is mounted.
4122 var state = isFiberMountedImpl(fiber);
4123 !(state !== UNMOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
4124 if (state === MOUNTING) {
4125 return null;
4126 }
4127 return fiber;
4128 }
4129 // If we have two possible branches, we'll walk backwards up to the root
4130 // to see what path the root points to. On the way we may hit one of the
4131 // special cases and we'll deal with them.
4132 var a = fiber;
4133 var b = alternate;
4134 while (true) {
4135 var parentA = a.return;
4136 var parentB = parentA ? parentA.alternate : null;
4137 if (!parentA || !parentB) {
4138 // We're at the root.
4139 break;
4140 }
4141
4142 // If both copies of the parent fiber point to the same child, we can
4143 // assume that the child is current. This happens when we bailout on low
4144 // priority: the bailed out fiber's child reuses the current child.
4145 if (parentA.child === parentB.child) {
4146 var child = parentA.child;
4147 while (child) {
4148 if (child === a) {
4149 // We've determined that A is the current branch.
4150 assertIsMounted(parentA);
4151 return fiber;
4152 }
4153 if (child === b) {
4154 // We've determined that B is the current branch.
4155 assertIsMounted(parentA);
4156 return alternate;
4157 }
4158 child = child.sibling;
4159 }
4160 // We should never have an alternate for any mounting node. So the only
4161 // way this could possibly happen is if this was unmounted, if at all.
4162 invariant(false, 'Unable to find node on an unmounted component.');
4163 }
4164
4165 if (a.return !== b.return) {
4166 // The return pointer of A and the return pointer of B point to different
4167 // fibers. We assume that return pointers never criss-cross, so A must
4168 // belong to the child set of A.return, and B must belong to the child
4169 // set of B.return.
4170 a = parentA;
4171 b = parentB;
4172 } else {
4173 // The return pointers point to the same fiber. We'll have to use the
4174 // default, slow path: scan the child sets of each parent alternate to see
4175 // which child belongs to which set.
4176 //
4177 // Search parent A's child set
4178 var didFindChild = false;
4179 var _child = parentA.child;
4180 while (_child) {
4181 if (_child === a) {
4182 didFindChild = true;
4183 a = parentA;
4184 b = parentB;
4185 break;
4186 }
4187 if (_child === b) {
4188 didFindChild = true;
4189 b = parentA;
4190 a = parentB;
4191 break;
4192 }
4193 _child = _child.sibling;
4194 }
4195 if (!didFindChild) {
4196 // Search parent B's child set
4197 _child = parentB.child;
4198 while (_child) {
4199 if (_child === a) {
4200 didFindChild = true;
4201 a = parentB;
4202 b = parentA;
4203 break;
4204 }
4205 if (_child === b) {
4206 didFindChild = true;
4207 b = parentB;
4208 a = parentA;
4209 break;
4210 }
4211 _child = _child.sibling;
4212 }
4213 !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;
4214 }
4215 }
4216
4217 !(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;
4218 }
4219 // If the root is not a host container, we're in a disconnected tree. I.e.
4220 // unmounted.
4221 !(a.tag === HostRoot) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
4222 if (a.stateNode.current === a) {
4223 // We've determined that A is the current branch.
4224 return fiber;
4225 }
4226 // Otherwise B has to be current branch.
4227 return alternate;
4228}
4229
4230function findCurrentHostFiber(parent) {
4231 var currentParent = findCurrentFiberUsingSlowPath(parent);
4232 if (!currentParent) {
4233 return null;
4234 }
4235
4236 // Next we'll drill down this component to find the first HostComponent/Text.
4237 var node = currentParent;
4238 while (true) {
4239 if (node.tag === HostComponent || node.tag === HostText) {
4240 return node;
4241 } else if (node.child) {
4242 node.child.return = node;
4243 node = node.child;
4244 continue;
4245 }
4246 if (node === currentParent) {
4247 return null;
4248 }
4249 while (!node.sibling) {
4250 if (!node.return || node.return === currentParent) {
4251 return null;
4252 }
4253 node = node.return;
4254 }
4255 node.sibling.return = node.return;
4256 node = node.sibling;
4257 }
4258 // Flow needs the return null here, but ESLint complains about it.
4259 // eslint-disable-next-line no-unreachable
4260 return null;
4261}
4262
4263function findCurrentHostFiberWithNoPortals(parent) {
4264 var currentParent = findCurrentFiberUsingSlowPath(parent);
4265 if (!currentParent) {
4266 return null;
4267 }
4268
4269 // Next we'll drill down this component to find the first HostComponent/Text.
4270 var node = currentParent;
4271 while (true) {
4272 if (node.tag === HostComponent || node.tag === HostText) {
4273 return node;
4274 } else if (node.child && node.tag !== HostPortal) {
4275 node.child.return = node;
4276 node = node.child;
4277 continue;
4278 }
4279 if (node === currentParent) {
4280 return null;
4281 }
4282 while (!node.sibling) {
4283 if (!node.return || node.return === currentParent) {
4284 return null;
4285 }
4286 node = node.return;
4287 }
4288 node.sibling.return = node.return;
4289 node = node.sibling;
4290 }
4291 // Flow needs the return null here, but ESLint complains about it.
4292 // eslint-disable-next-line no-unreachable
4293 return null;
4294}
4295
4296function addEventBubbleListener(element, eventType, listener) {
4297 element.addEventListener(eventType, listener, false);
4298}
4299
4300function addEventCaptureListener(element, eventType, listener) {
4301 element.addEventListener(eventType, listener, true);
4302}
4303
4304/**
4305 * @interface Event
4306 * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
4307 * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
4308 */
4309var SyntheticAnimationEvent = SyntheticEvent.extend({
4310 animationName: null,
4311 elapsedTime: null,
4312 pseudoElement: null
4313});
4314
4315/**
4316 * @interface Event
4317 * @see http://www.w3.org/TR/clipboard-apis/
4318 */
4319var SyntheticClipboardEvent = SyntheticEvent.extend({
4320 clipboardData: function (event) {
4321 return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
4322 }
4323});
4324
4325/**
4326 * @interface FocusEvent
4327 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4328 */
4329var SyntheticFocusEvent = SyntheticUIEvent.extend({
4330 relatedTarget: null
4331});
4332
4333/**
4334 * `charCode` represents the actual "character code" and is safe to use with
4335 * `String.fromCharCode`. As such, only keys that correspond to printable
4336 * characters produce a valid `charCode`, the only exception to this is Enter.
4337 * The Tab-key is considered non-printable and does not have a `charCode`,
4338 * presumably because it does not produce a tab-character in browsers.
4339 *
4340 * @param {object} nativeEvent Native browser event.
4341 * @return {number} Normalized `charCode` property.
4342 */
4343function getEventCharCode(nativeEvent) {
4344 var charCode = void 0;
4345 var keyCode = nativeEvent.keyCode;
4346
4347 if ('charCode' in nativeEvent) {
4348 charCode = nativeEvent.charCode;
4349
4350 // FF does not set `charCode` for the Enter-key, check against `keyCode`.
4351 if (charCode === 0 && keyCode === 13) {
4352 charCode = 13;
4353 }
4354 } else {
4355 // IE8 does not implement `charCode`, but `keyCode` has the correct value.
4356 charCode = keyCode;
4357 }
4358
4359 // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
4360 // report Enter as charCode 10 when ctrl is pressed.
4361 if (charCode === 10) {
4362 charCode = 13;
4363 }
4364
4365 // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
4366 // Must not discard the (non-)printable Enter-key.
4367 if (charCode >= 32 || charCode === 13) {
4368 return charCode;
4369 }
4370
4371 return 0;
4372}
4373
4374/**
4375 * Normalization of deprecated HTML5 `key` values
4376 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
4377 */
4378var normalizeKey = {
4379 Esc: 'Escape',
4380 Spacebar: ' ',
4381 Left: 'ArrowLeft',
4382 Up: 'ArrowUp',
4383 Right: 'ArrowRight',
4384 Down: 'ArrowDown',
4385 Del: 'Delete',
4386 Win: 'OS',
4387 Menu: 'ContextMenu',
4388 Apps: 'ContextMenu',
4389 Scroll: 'ScrollLock',
4390 MozPrintableKey: 'Unidentified'
4391};
4392
4393/**
4394 * Translation from legacy `keyCode` to HTML5 `key`
4395 * Only special keys supported, all others depend on keyboard layout or browser
4396 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
4397 */
4398var translateToKey = {
4399 '8': 'Backspace',
4400 '9': 'Tab',
4401 '12': 'Clear',
4402 '13': 'Enter',
4403 '16': 'Shift',
4404 '17': 'Control',
4405 '18': 'Alt',
4406 '19': 'Pause',
4407 '20': 'CapsLock',
4408 '27': 'Escape',
4409 '32': ' ',
4410 '33': 'PageUp',
4411 '34': 'PageDown',
4412 '35': 'End',
4413 '36': 'Home',
4414 '37': 'ArrowLeft',
4415 '38': 'ArrowUp',
4416 '39': 'ArrowRight',
4417 '40': 'ArrowDown',
4418 '45': 'Insert',
4419 '46': 'Delete',
4420 '112': 'F1',
4421 '113': 'F2',
4422 '114': 'F3',
4423 '115': 'F4',
4424 '116': 'F5',
4425 '117': 'F6',
4426 '118': 'F7',
4427 '119': 'F8',
4428 '120': 'F9',
4429 '121': 'F10',
4430 '122': 'F11',
4431 '123': 'F12',
4432 '144': 'NumLock',
4433 '145': 'ScrollLock',
4434 '224': 'Meta'
4435};
4436
4437/**
4438 * @param {object} nativeEvent Native browser event.
4439 * @return {string} Normalized `key` property.
4440 */
4441function getEventKey(nativeEvent) {
4442 if (nativeEvent.key) {
4443 // Normalize inconsistent values reported by browsers due to
4444 // implementations of a working draft specification.
4445
4446 // FireFox implements `key` but returns `MozPrintableKey` for all
4447 // printable characters (normalized to `Unidentified`), ignore it.
4448 var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
4449 if (key !== 'Unidentified') {
4450 return key;
4451 }
4452 }
4453
4454 // Browser does not implement `key`, polyfill as much of it as we can.
4455 if (nativeEvent.type === 'keypress') {
4456 var charCode = getEventCharCode(nativeEvent);
4457
4458 // The enter-key is technically both printable and non-printable and can
4459 // thus be captured by `keypress`, no other non-printable key should.
4460 return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
4461 }
4462 if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
4463 // While user keyboard layout determines the actual meaning of each
4464 // `keyCode` value, almost all function keys have a universal value.
4465 return translateToKey[nativeEvent.keyCode] || 'Unidentified';
4466 }
4467 return '';
4468}
4469
4470/**
4471 * @interface KeyboardEvent
4472 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4473 */
4474var SyntheticKeyboardEvent = SyntheticUIEvent.extend({
4475 key: getEventKey,
4476 location: null,
4477 ctrlKey: null,
4478 shiftKey: null,
4479 altKey: null,
4480 metaKey: null,
4481 repeat: null,
4482 locale: null,
4483 getModifierState: getEventModifierState,
4484 // Legacy Interface
4485 charCode: function (event) {
4486 // `charCode` is the result of a KeyPress event and represents the value of
4487 // the actual printable character.
4488
4489 // KeyPress is deprecated, but its replacement is not yet final and not
4490 // implemented in any major browser. Only KeyPress has charCode.
4491 if (event.type === 'keypress') {
4492 return getEventCharCode(event);
4493 }
4494 return 0;
4495 },
4496 keyCode: function (event) {
4497 // `keyCode` is the result of a KeyDown/Up event and represents the value of
4498 // physical keyboard key.
4499
4500 // The actual meaning of the value depends on the users' keyboard layout
4501 // which cannot be detected. Assuming that it is a US keyboard layout
4502 // provides a surprisingly accurate mapping for US and European users.
4503 // Due to this, it is left to the user to implement at this time.
4504 if (event.type === 'keydown' || event.type === 'keyup') {
4505 return event.keyCode;
4506 }
4507 return 0;
4508 },
4509 which: function (event) {
4510 // `which` is an alias for either `keyCode` or `charCode` depending on the
4511 // type of the event.
4512 if (event.type === 'keypress') {
4513 return getEventCharCode(event);
4514 }
4515 if (event.type === 'keydown' || event.type === 'keyup') {
4516 return event.keyCode;
4517 }
4518 return 0;
4519 }
4520});
4521
4522/**
4523 * @interface DragEvent
4524 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4525 */
4526var SyntheticDragEvent = SyntheticMouseEvent.extend({
4527 dataTransfer: null
4528});
4529
4530/**
4531 * @interface TouchEvent
4532 * @see http://www.w3.org/TR/touch-events/
4533 */
4534var SyntheticTouchEvent = SyntheticUIEvent.extend({
4535 touches: null,
4536 targetTouches: null,
4537 changedTouches: null,
4538 altKey: null,
4539 metaKey: null,
4540 ctrlKey: null,
4541 shiftKey: null,
4542 getModifierState: getEventModifierState
4543});
4544
4545/**
4546 * @interface Event
4547 * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
4548 * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
4549 */
4550var SyntheticTransitionEvent = SyntheticEvent.extend({
4551 propertyName: null,
4552 elapsedTime: null,
4553 pseudoElement: null
4554});
4555
4556/**
4557 * @interface WheelEvent
4558 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4559 */
4560var SyntheticWheelEvent = SyntheticMouseEvent.extend({
4561 deltaX: function (event) {
4562 return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
4563 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
4564 },
4565 deltaY: function (event) {
4566 return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
4567 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
4568 'wheelDelta' in event ? -event.wheelDelta : 0;
4569 },
4570
4571 deltaZ: null,
4572
4573 // Browsers without "deltaMode" is reporting in raw wheel delta where one
4574 // notch on the scroll is always +/- 120, roughly equivalent to pixels.
4575 // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
4576 // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
4577 deltaMode: null
4578});
4579
4580/**
4581 * Turns
4582 * ['abort', ...]
4583 * into
4584 * eventTypes = {
4585 * 'abort': {
4586 * phasedRegistrationNames: {
4587 * bubbled: 'onAbort',
4588 * captured: 'onAbortCapture',
4589 * },
4590 * dependencies: [TOP_ABORT],
4591 * },
4592 * ...
4593 * };
4594 * topLevelEventsToDispatchConfig = new Map([
4595 * [TOP_ABORT, { sameConfig }],
4596 * ]);
4597 */
4598
4599var 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']];
4600var 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']];
4601
4602var eventTypes$4 = {};
4603var topLevelEventsToDispatchConfig = {};
4604
4605function addEventTypeNameToConfig(_ref, isInteractive) {
4606 var topEvent = _ref[0],
4607 event = _ref[1];
4608
4609 var capitalizedEvent = event[0].toUpperCase() + event.slice(1);
4610 var onEvent = 'on' + capitalizedEvent;
4611
4612 var type = {
4613 phasedRegistrationNames: {
4614 bubbled: onEvent,
4615 captured: onEvent + 'Capture'
4616 },
4617 dependencies: [topEvent],
4618 isInteractive: isInteractive
4619 };
4620 eventTypes$4[event] = type;
4621 topLevelEventsToDispatchConfig[topEvent] = type;
4622}
4623
4624interactiveEventTypeNames.forEach(function (eventTuple) {
4625 addEventTypeNameToConfig(eventTuple, true);
4626});
4627nonInteractiveEventTypeNames.forEach(function (eventTuple) {
4628 addEventTypeNameToConfig(eventTuple, false);
4629});
4630
4631// Only used in DEV for exhaustiveness validation.
4632var 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];
4633
4634var SimpleEventPlugin = {
4635 eventTypes: eventTypes$4,
4636
4637 isInteractiveTopLevelEventType: function (topLevelType) {
4638 var config = topLevelEventsToDispatchConfig[topLevelType];
4639 return config !== undefined && config.isInteractive === true;
4640 },
4641
4642
4643 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
4644 var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
4645 if (!dispatchConfig) {
4646 return null;
4647 }
4648 var EventConstructor = void 0;
4649 switch (topLevelType) {
4650 case TOP_KEY_PRESS:
4651 // Firefox creates a keypress event for function keys too. This removes
4652 // the unwanted keypress events. Enter is however both printable and
4653 // non-printable. One would expect Tab to be as well (but it isn't).
4654 if (getEventCharCode(nativeEvent) === 0) {
4655 return null;
4656 }
4657 /* falls through */
4658 case TOP_KEY_DOWN:
4659 case TOP_KEY_UP:
4660 EventConstructor = SyntheticKeyboardEvent;
4661 break;
4662 case TOP_BLUR:
4663 case TOP_FOCUS:
4664 EventConstructor = SyntheticFocusEvent;
4665 break;
4666 case TOP_CLICK:
4667 // Firefox creates a click event on right mouse clicks. This removes the
4668 // unwanted click events.
4669 if (nativeEvent.button === 2) {
4670 return null;
4671 }
4672 /* falls through */
4673 case TOP_AUX_CLICK:
4674 case TOP_DOUBLE_CLICK:
4675 case TOP_MOUSE_DOWN:
4676 case TOP_MOUSE_MOVE:
4677 case TOP_MOUSE_UP:
4678 // TODO: Disabled elements should not respond to mouse events
4679 /* falls through */
4680 case TOP_MOUSE_OUT:
4681 case TOP_MOUSE_OVER:
4682 case TOP_CONTEXT_MENU:
4683 EventConstructor = SyntheticMouseEvent;
4684 break;
4685 case TOP_DRAG:
4686 case TOP_DRAG_END:
4687 case TOP_DRAG_ENTER:
4688 case TOP_DRAG_EXIT:
4689 case TOP_DRAG_LEAVE:
4690 case TOP_DRAG_OVER:
4691 case TOP_DRAG_START:
4692 case TOP_DROP:
4693 EventConstructor = SyntheticDragEvent;
4694 break;
4695 case TOP_TOUCH_CANCEL:
4696 case TOP_TOUCH_END:
4697 case TOP_TOUCH_MOVE:
4698 case TOP_TOUCH_START:
4699 EventConstructor = SyntheticTouchEvent;
4700 break;
4701 case TOP_ANIMATION_END:
4702 case TOP_ANIMATION_ITERATION:
4703 case TOP_ANIMATION_START:
4704 EventConstructor = SyntheticAnimationEvent;
4705 break;
4706 case TOP_TRANSITION_END:
4707 EventConstructor = SyntheticTransitionEvent;
4708 break;
4709 case TOP_SCROLL:
4710 EventConstructor = SyntheticUIEvent;
4711 break;
4712 case TOP_WHEEL:
4713 EventConstructor = SyntheticWheelEvent;
4714 break;
4715 case TOP_COPY:
4716 case TOP_CUT:
4717 case TOP_PASTE:
4718 EventConstructor = SyntheticClipboardEvent;
4719 break;
4720 case TOP_GOT_POINTER_CAPTURE:
4721 case TOP_LOST_POINTER_CAPTURE:
4722 case TOP_POINTER_CANCEL:
4723 case TOP_POINTER_DOWN:
4724 case TOP_POINTER_MOVE:
4725 case TOP_POINTER_OUT:
4726 case TOP_POINTER_OVER:
4727 case TOP_POINTER_UP:
4728 EventConstructor = SyntheticPointerEvent;
4729 break;
4730 default:
4731 {
4732 if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {
4733 warningWithoutStack$1(false, 'SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType);
4734 }
4735 }
4736 // HTML Events
4737 // @see http://www.w3.org/TR/html5/index.html#events-0
4738 EventConstructor = SyntheticEvent;
4739 break;
4740 }
4741 var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
4742 accumulateTwoPhaseDispatches(event);
4743 return event;
4744 }
4745};
4746
4747var isInteractiveTopLevelEventType = SimpleEventPlugin.isInteractiveTopLevelEventType;
4748
4749
4750var CALLBACK_BOOKKEEPING_POOL_SIZE = 10;
4751var callbackBookkeepingPool = [];
4752
4753/**
4754 * Find the deepest React component completely containing the root of the
4755 * passed-in instance (for use when entire React trees are nested within each
4756 * other). If React trees are not nested, returns null.
4757 */
4758function findRootContainerNode(inst) {
4759 // TODO: It may be a good idea to cache this to prevent unnecessary DOM
4760 // traversal, but caching is difficult to do correctly without using a
4761 // mutation observer to listen for all DOM changes.
4762 while (inst.return) {
4763 inst = inst.return;
4764 }
4765 if (inst.tag !== HostRoot) {
4766 // This can happen if we're in a detached tree.
4767 return null;
4768 }
4769 return inst.stateNode.containerInfo;
4770}
4771
4772// Used to store ancestor hierarchy in top level callback
4773function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst) {
4774 if (callbackBookkeepingPool.length) {
4775 var instance = callbackBookkeepingPool.pop();
4776 instance.topLevelType = topLevelType;
4777 instance.nativeEvent = nativeEvent;
4778 instance.targetInst = targetInst;
4779 return instance;
4780 }
4781 return {
4782 topLevelType: topLevelType,
4783 nativeEvent: nativeEvent,
4784 targetInst: targetInst,
4785 ancestors: []
4786 };
4787}
4788
4789function releaseTopLevelCallbackBookKeeping(instance) {
4790 instance.topLevelType = null;
4791 instance.nativeEvent = null;
4792 instance.targetInst = null;
4793 instance.ancestors.length = 0;
4794 if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) {
4795 callbackBookkeepingPool.push(instance);
4796 }
4797}
4798
4799function handleTopLevel(bookKeeping) {
4800 var targetInst = bookKeeping.targetInst;
4801
4802 // Loop through the hierarchy, in case there's any nested components.
4803 // It's important that we build the array of ancestors before calling any
4804 // event handlers, because event handlers can modify the DOM, leading to
4805 // inconsistencies with ReactMount's node cache. See #1105.
4806 var ancestor = targetInst;
4807 do {
4808 if (!ancestor) {
4809 bookKeeping.ancestors.push(ancestor);
4810 break;
4811 }
4812 var root = findRootContainerNode(ancestor);
4813 if (!root) {
4814 break;
4815 }
4816 bookKeeping.ancestors.push(ancestor);
4817 ancestor = getClosestInstanceFromNode(root);
4818 } while (ancestor);
4819
4820 for (var i = 0; i < bookKeeping.ancestors.length; i++) {
4821 targetInst = bookKeeping.ancestors[i];
4822 runExtractedEventsInBatch(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
4823 }
4824}
4825
4826// TODO: can we stop exporting these?
4827var _enabled = true;
4828
4829function setEnabled(enabled) {
4830 _enabled = !!enabled;
4831}
4832
4833function isEnabled() {
4834 return _enabled;
4835}
4836
4837/**
4838 * Traps top-level events by using event bubbling.
4839 *
4840 * @param {number} topLevelType Number from `TopLevelEventTypes`.
4841 * @param {object} element Element on which to attach listener.
4842 * @return {?object} An object with a remove function which will forcefully
4843 * remove the listener.
4844 * @internal
4845 */
4846function trapBubbledEvent(topLevelType, element) {
4847 if (!element) {
4848 return null;
4849 }
4850 var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent;
4851
4852 addEventBubbleListener(element, getRawEventName(topLevelType),
4853 // Check if interactive and wrap in interactiveUpdates
4854 dispatch.bind(null, topLevelType));
4855}
4856
4857/**
4858 * Traps a top-level event by using event capturing.
4859 *
4860 * @param {number} topLevelType Number from `TopLevelEventTypes`.
4861 * @param {object} element Element on which to attach listener.
4862 * @return {?object} An object with a remove function which will forcefully
4863 * remove the listener.
4864 * @internal
4865 */
4866function trapCapturedEvent(topLevelType, element) {
4867 if (!element) {
4868 return null;
4869 }
4870 var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent;
4871
4872 addEventCaptureListener(element, getRawEventName(topLevelType),
4873 // Check if interactive and wrap in interactiveUpdates
4874 dispatch.bind(null, topLevelType));
4875}
4876
4877function dispatchInteractiveEvent(topLevelType, nativeEvent) {
4878 interactiveUpdates(dispatchEvent, topLevelType, nativeEvent);
4879}
4880
4881function dispatchEvent(topLevelType, nativeEvent) {
4882 if (!_enabled) {
4883 return;
4884 }
4885
4886 var nativeEventTarget = getEventTarget(nativeEvent);
4887 var targetInst = getClosestInstanceFromNode(nativeEventTarget);
4888 if (targetInst !== null && typeof targetInst.tag === 'number' && !isFiberMounted(targetInst)) {
4889 // If we get an event (ex: img onload) before committing that
4890 // component's mount, ignore it for now (that is, treat it as if it was an
4891 // event on a non-React tree). We might also consider queueing events and
4892 // dispatching them after the mount.
4893 targetInst = null;
4894 }
4895
4896 var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst);
4897
4898 try {
4899 // Event queue being processed in the same cycle allows
4900 // `preventDefault`.
4901 batchedUpdates(handleTopLevel, bookKeeping);
4902 } finally {
4903 releaseTopLevelCallbackBookKeeping(bookKeeping);
4904 }
4905}
4906
4907/**
4908 * Summary of `ReactBrowserEventEmitter` event handling:
4909 *
4910 * - Top-level delegation is used to trap most native browser events. This
4911 * may only occur in the main thread and is the responsibility of
4912 * ReactDOMEventListener, which is injected and can therefore support
4913 * pluggable event sources. This is the only work that occurs in the main
4914 * thread.
4915 *
4916 * - We normalize and de-duplicate events to account for browser quirks. This
4917 * may be done in the worker thread.
4918 *
4919 * - Forward these native events (with the associated top-level type used to
4920 * trap it) to `EventPluginHub`, which in turn will ask plugins if they want
4921 * to extract any synthetic events.
4922 *
4923 * - The `EventPluginHub` will then process each event by annotating them with
4924 * "dispatches", a sequence of listeners and IDs that care about that event.
4925 *
4926 * - The `EventPluginHub` then dispatches the events.
4927 *
4928 * Overview of React and the event system:
4929 *
4930 * +------------+ .
4931 * | DOM | .
4932 * +------------+ .
4933 * | .
4934 * v .
4935 * +------------+ .
4936 * | ReactEvent | .
4937 * | Listener | .
4938 * +------------+ . +-----------+
4939 * | . +--------+|SimpleEvent|
4940 * | . | |Plugin |
4941 * +-----|------+ . v +-----------+
4942 * | | | . +--------------+ +------------+
4943 * | +-----------.--->|EventPluginHub| | Event |
4944 * | | . | | +-----------+ | Propagators|
4945 * | ReactEvent | . | | |TapEvent | |------------|
4946 * | Emitter | . | |<---+|Plugin | |other plugin|
4947 * | | . | | +-----------+ | utilities |
4948 * | +-----------.--->| | +------------+
4949 * | | | . +--------------+
4950 * +-----|------+ . ^ +-----------+
4951 * | . | |Enter/Leave|
4952 * + . +-------+|Plugin |
4953 * +-------------+ . +-----------+
4954 * | application | .
4955 * |-------------| .
4956 * | | .
4957 * | | .
4958 * +-------------+ .
4959 * .
4960 * React Core . General Purpose Event Plugin System
4961 */
4962
4963var alreadyListeningTo = {};
4964var reactTopListenersCounter = 0;
4965
4966/**
4967 * To ensure no conflicts with other potential React instances on the page
4968 */
4969var topListenersIDKey = '_reactListenersID' + ('' + Math.random()).slice(2);
4970
4971function getListeningForDocument(mountAt) {
4972 // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
4973 // directly.
4974 if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) {
4975 mountAt[topListenersIDKey] = reactTopListenersCounter++;
4976 alreadyListeningTo[mountAt[topListenersIDKey]] = {};
4977 }
4978 return alreadyListeningTo[mountAt[topListenersIDKey]];
4979}
4980
4981/**
4982 * We listen for bubbled touch events on the document object.
4983 *
4984 * Firefox v8.01 (and possibly others) exhibited strange behavior when
4985 * mounting `onmousemove` events at some node that was not the document
4986 * element. The symptoms were that if your mouse is not moving over something
4987 * contained within that mount point (for example on the background) the
4988 * top-level listeners for `onmousemove` won't be called. However, if you
4989 * register the `mousemove` on the document object, then it will of course
4990 * catch all `mousemove`s. This along with iOS quirks, justifies restricting
4991 * top-level listeners to the document object only, at least for these
4992 * movement types of events and possibly all events.
4993 *
4994 * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
4995 *
4996 * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
4997 * they bubble to document.
4998 *
4999 * @param {string} registrationName Name of listener (e.g. `onClick`).
5000 * @param {object} mountAt Container where to mount the listener
5001 */
5002function listenTo(registrationName, mountAt) {
5003 var isListening = getListeningForDocument(mountAt);
5004 var dependencies = registrationNameDependencies[registrationName];
5005
5006 for (var i = 0; i < dependencies.length; i++) {
5007 var dependency = dependencies[i];
5008 if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
5009 switch (dependency) {
5010 case TOP_SCROLL:
5011 trapCapturedEvent(TOP_SCROLL, mountAt);
5012 break;
5013 case TOP_FOCUS:
5014 case TOP_BLUR:
5015 trapCapturedEvent(TOP_FOCUS, mountAt);
5016 trapCapturedEvent(TOP_BLUR, mountAt);
5017 // We set the flag for a single dependency later in this function,
5018 // but this ensures we mark both as attached rather than just one.
5019 isListening[TOP_BLUR] = true;
5020 isListening[TOP_FOCUS] = true;
5021 break;
5022 case TOP_CANCEL:
5023 case TOP_CLOSE:
5024 if (isEventSupported(getRawEventName(dependency))) {
5025 trapCapturedEvent(dependency, mountAt);
5026 }
5027 break;
5028 case TOP_INVALID:
5029 case TOP_SUBMIT:
5030 case TOP_RESET:
5031 // We listen to them on the target DOM elements.
5032 // Some of them bubble so we don't want them to fire twice.
5033 break;
5034 default:
5035 // By default, listen on the top level to all non-media events.
5036 // Media events don't bubble so adding the listener wouldn't do anything.
5037 var isMediaEvent = mediaEventTypes.indexOf(dependency) !== -1;
5038 if (!isMediaEvent) {
5039 trapBubbledEvent(dependency, mountAt);
5040 }
5041 break;
5042 }
5043 isListening[dependency] = true;
5044 }
5045 }
5046}
5047
5048function isListeningToAllDependencies(registrationName, mountAt) {
5049 var isListening = getListeningForDocument(mountAt);
5050 var dependencies = registrationNameDependencies[registrationName];
5051 for (var i = 0; i < dependencies.length; i++) {
5052 var dependency = dependencies[i];
5053 if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
5054 return false;
5055 }
5056 }
5057 return true;
5058}
5059
5060function getActiveElement(doc) {
5061 doc = doc || (typeof document !== 'undefined' ? document : undefined);
5062 if (typeof doc === 'undefined') {
5063 return null;
5064 }
5065 try {
5066 return doc.activeElement || doc.body;
5067 } catch (e) {
5068 return doc.body;
5069 }
5070}
5071
5072/**
5073 * Given any node return the first leaf node without children.
5074 *
5075 * @param {DOMElement|DOMTextNode} node
5076 * @return {DOMElement|DOMTextNode}
5077 */
5078function getLeafNode(node) {
5079 while (node && node.firstChild) {
5080 node = node.firstChild;
5081 }
5082 return node;
5083}
5084
5085/**
5086 * Get the next sibling within a container. This will walk up the
5087 * DOM if a node's siblings have been exhausted.
5088 *
5089 * @param {DOMElement|DOMTextNode} node
5090 * @return {?DOMElement|DOMTextNode}
5091 */
5092function getSiblingNode(node) {
5093 while (node) {
5094 if (node.nextSibling) {
5095 return node.nextSibling;
5096 }
5097 node = node.parentNode;
5098 }
5099}
5100
5101/**
5102 * Get object describing the nodes which contain characters at offset.
5103 *
5104 * @param {DOMElement|DOMTextNode} root
5105 * @param {number} offset
5106 * @return {?object}
5107 */
5108function getNodeForCharacterOffset(root, offset) {
5109 var node = getLeafNode(root);
5110 var nodeStart = 0;
5111 var nodeEnd = 0;
5112
5113 while (node) {
5114 if (node.nodeType === TEXT_NODE) {
5115 nodeEnd = nodeStart + node.textContent.length;
5116
5117 if (nodeStart <= offset && nodeEnd >= offset) {
5118 return {
5119 node: node,
5120 offset: offset - nodeStart
5121 };
5122 }
5123
5124 nodeStart = nodeEnd;
5125 }
5126
5127 node = getLeafNode(getSiblingNode(node));
5128 }
5129}
5130
5131/**
5132 * @param {DOMElement} outerNode
5133 * @return {?object}
5134 */
5135function getOffsets(outerNode) {
5136 var ownerDocument = outerNode.ownerDocument;
5137
5138 var win = ownerDocument && ownerDocument.defaultView || window;
5139 var selection = win.getSelection && win.getSelection();
5140
5141 if (!selection || selection.rangeCount === 0) {
5142 return null;
5143 }
5144
5145 var anchorNode = selection.anchorNode,
5146 anchorOffset = selection.anchorOffset,
5147 focusNode = selection.focusNode,
5148 focusOffset = selection.focusOffset;
5149
5150 // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
5151 // up/down buttons on an <input type="number">. Anonymous divs do not seem to
5152 // expose properties, triggering a "Permission denied error" if any of its
5153 // properties are accessed. The only seemingly possible way to avoid erroring
5154 // is to access a property that typically works for non-anonymous divs and
5155 // catch any error that may otherwise arise. See
5156 // https://bugzilla.mozilla.org/show_bug.cgi?id=208427
5157
5158 try {
5159 /* eslint-disable no-unused-expressions */
5160 anchorNode.nodeType;
5161 focusNode.nodeType;
5162 /* eslint-enable no-unused-expressions */
5163 } catch (e) {
5164 return null;
5165 }
5166
5167 return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
5168}
5169
5170/**
5171 * Returns {start, end} where `start` is the character/codepoint index of
5172 * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
5173 * `end` is the index of (focusNode, focusOffset).
5174 *
5175 * Returns null if you pass in garbage input but we should probably just crash.
5176 *
5177 * Exported only for testing.
5178 */
5179function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
5180 var length = 0;
5181 var start = -1;
5182 var end = -1;
5183 var indexWithinAnchor = 0;
5184 var indexWithinFocus = 0;
5185 var node = outerNode;
5186 var parentNode = null;
5187
5188 outer: while (true) {
5189 var next = null;
5190
5191 while (true) {
5192 if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
5193 start = length + anchorOffset;
5194 }
5195 if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
5196 end = length + focusOffset;
5197 }
5198
5199 if (node.nodeType === TEXT_NODE) {
5200 length += node.nodeValue.length;
5201 }
5202
5203 if ((next = node.firstChild) === null) {
5204 break;
5205 }
5206 // Moving from `node` to its first child `next`.
5207 parentNode = node;
5208 node = next;
5209 }
5210
5211 while (true) {
5212 if (node === outerNode) {
5213 // If `outerNode` has children, this is always the second time visiting
5214 // it. If it has no children, this is still the first loop, and the only
5215 // valid selection is anchorNode and focusNode both equal to this node
5216 // and both offsets 0, in which case we will have handled above.
5217 break outer;
5218 }
5219 if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
5220 start = length;
5221 }
5222 if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
5223 end = length;
5224 }
5225 if ((next = node.nextSibling) !== null) {
5226 break;
5227 }
5228 node = parentNode;
5229 parentNode = node.parentNode;
5230 }
5231
5232 // Moving from `node` to its next sibling `next`.
5233 node = next;
5234 }
5235
5236 if (start === -1 || end === -1) {
5237 // This should never happen. (Would happen if the anchor/focus nodes aren't
5238 // actually inside the passed-in node.)
5239 return null;
5240 }
5241
5242 return {
5243 start: start,
5244 end: end
5245 };
5246}
5247
5248/**
5249 * In modern non-IE browsers, we can support both forward and backward
5250 * selections.
5251 *
5252 * Note: IE10+ supports the Selection object, but it does not support
5253 * the `extend` method, which means that even in modern IE, it's not possible
5254 * to programmatically create a backward selection. Thus, for all IE
5255 * versions, we use the old IE API to create our selections.
5256 *
5257 * @param {DOMElement|DOMTextNode} node
5258 * @param {object} offsets
5259 */
5260function setOffsets(node, offsets) {
5261 var doc = node.ownerDocument || document;
5262 var win = doc && doc.defaultView || window;
5263
5264 // Edge fails with "Object expected" in some scenarios.
5265 // (For instance: TinyMCE editor used in a list component that supports pasting to add more,
5266 // fails when pasting 100+ items)
5267 if (!win.getSelection) {
5268 return;
5269 }
5270
5271 var selection = win.getSelection();
5272 var length = node.textContent.length;
5273 var start = Math.min(offsets.start, length);
5274 var end = offsets.end === undefined ? start : Math.min(offsets.end, length);
5275
5276 // IE 11 uses modern selection, but doesn't support the extend method.
5277 // Flip backward selections, so we can set with a single range.
5278 if (!selection.extend && start > end) {
5279 var temp = end;
5280 end = start;
5281 start = temp;
5282 }
5283
5284 var startMarker = getNodeForCharacterOffset(node, start);
5285 var endMarker = getNodeForCharacterOffset(node, end);
5286
5287 if (startMarker && endMarker) {
5288 if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
5289 return;
5290 }
5291 var range = doc.createRange();
5292 range.setStart(startMarker.node, startMarker.offset);
5293 selection.removeAllRanges();
5294
5295 if (start > end) {
5296 selection.addRange(range);
5297 selection.extend(endMarker.node, endMarker.offset);
5298 } else {
5299 range.setEnd(endMarker.node, endMarker.offset);
5300 selection.addRange(range);
5301 }
5302 }
5303}
5304
5305function isTextNode(node) {
5306 return node && node.nodeType === TEXT_NODE;
5307}
5308
5309function containsNode(outerNode, innerNode) {
5310 if (!outerNode || !innerNode) {
5311 return false;
5312 } else if (outerNode === innerNode) {
5313 return true;
5314 } else if (isTextNode(outerNode)) {
5315 return false;
5316 } else if (isTextNode(innerNode)) {
5317 return containsNode(outerNode, innerNode.parentNode);
5318 } else if ('contains' in outerNode) {
5319 return outerNode.contains(innerNode);
5320 } else if (outerNode.compareDocumentPosition) {
5321 return !!(outerNode.compareDocumentPosition(innerNode) & 16);
5322 } else {
5323 return false;
5324 }
5325}
5326
5327function isInDocument(node) {
5328 return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
5329}
5330
5331function getActiveElementDeep() {
5332 var win = window;
5333 var element = getActiveElement();
5334 while (element instanceof win.HTMLIFrameElement) {
5335 // Accessing the contentDocument of a HTMLIframeElement can cause the browser
5336 // to throw, e.g. if it has a cross-origin src attribute
5337 try {
5338 win = element.contentDocument.defaultView;
5339 } catch (e) {
5340 return element;
5341 }
5342 element = getActiveElement(win.document);
5343 }
5344 return element;
5345}
5346
5347/**
5348 * @ReactInputSelection: React input selection module. Based on Selection.js,
5349 * but modified to be suitable for react and has a couple of bug fixes (doesn't
5350 * assume buttons have range selections allowed).
5351 * Input selection module for React.
5352 */
5353
5354/**
5355 * @hasSelectionCapabilities: we get the element types that support selection
5356 * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
5357 * and `selectionEnd` rows.
5358 */
5359function hasSelectionCapabilities(elem) {
5360 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
5361 return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
5362}
5363
5364function getSelectionInformation() {
5365 var focusedElem = getActiveElementDeep();
5366 return {
5367 focusedElem: focusedElem,
5368 selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection$1(focusedElem) : null
5369 };
5370}
5371
5372/**
5373 * @restoreSelection: If any selection information was potentially lost,
5374 * restore it. This is useful when performing operations that could remove dom
5375 * nodes and place them back in, resulting in focus being lost.
5376 */
5377function restoreSelection(priorSelectionInformation) {
5378 var curFocusedElem = getActiveElementDeep();
5379 var priorFocusedElem = priorSelectionInformation.focusedElem;
5380 var priorSelectionRange = priorSelectionInformation.selectionRange;
5381 if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
5382 if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
5383 setSelection(priorFocusedElem, priorSelectionRange);
5384 }
5385
5386 // Focusing a node can change the scroll position, which is undesirable
5387 var ancestors = [];
5388 var ancestor = priorFocusedElem;
5389 while (ancestor = ancestor.parentNode) {
5390 if (ancestor.nodeType === ELEMENT_NODE) {
5391 ancestors.push({
5392 element: ancestor,
5393 left: ancestor.scrollLeft,
5394 top: ancestor.scrollTop
5395 });
5396 }
5397 }
5398
5399 if (typeof priorFocusedElem.focus === 'function') {
5400 priorFocusedElem.focus();
5401 }
5402
5403 for (var i = 0; i < ancestors.length; i++) {
5404 var info = ancestors[i];
5405 info.element.scrollLeft = info.left;
5406 info.element.scrollTop = info.top;
5407 }
5408 }
5409}
5410
5411/**
5412 * @getSelection: Gets the selection bounds of a focused textarea, input or
5413 * contentEditable node.
5414 * -@input: Look up selection bounds of this input
5415 * -@return {start: selectionStart, end: selectionEnd}
5416 */
5417function getSelection$1(input) {
5418 var selection = void 0;
5419
5420 if ('selectionStart' in input) {
5421 // Modern browser with input or textarea.
5422 selection = {
5423 start: input.selectionStart,
5424 end: input.selectionEnd
5425 };
5426 } else {
5427 // Content editable or old IE textarea.
5428 selection = getOffsets(input);
5429 }
5430
5431 return selection || { start: 0, end: 0 };
5432}
5433
5434/**
5435 * @setSelection: Sets the selection bounds of a textarea or input and focuses
5436 * the input.
5437 * -@input Set selection bounds of this input or textarea
5438 * -@offsets Object of same form that is returned from get*
5439 */
5440function setSelection(input, offsets) {
5441 var start = offsets.start,
5442 end = offsets.end;
5443
5444 if (end === undefined) {
5445 end = start;
5446 }
5447
5448 if ('selectionStart' in input) {
5449 input.selectionStart = start;
5450 input.selectionEnd = Math.min(end, input.value.length);
5451 } else {
5452 setOffsets(input, offsets);
5453 }
5454}
5455
5456var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;
5457
5458var eventTypes$3 = {
5459 select: {
5460 phasedRegistrationNames: {
5461 bubbled: 'onSelect',
5462 captured: 'onSelectCapture'
5463 },
5464 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]
5465 }
5466};
5467
5468var activeElement$1 = null;
5469var activeElementInst$1 = null;
5470var lastSelection = null;
5471var mouseDown = false;
5472
5473/**
5474 * Get an object which is a unique representation of the current selection.
5475 *
5476 * The return value will not be consistent across nodes or browsers, but
5477 * two identical selections on the same node will return identical objects.
5478 *
5479 * @param {DOMElement} node
5480 * @return {object}
5481 */
5482function getSelection(node) {
5483 if ('selectionStart' in node && hasSelectionCapabilities(node)) {
5484 return {
5485 start: node.selectionStart,
5486 end: node.selectionEnd
5487 };
5488 } else {
5489 var win = node.ownerDocument && node.ownerDocument.defaultView || window;
5490 var selection = win.getSelection();
5491 return {
5492 anchorNode: selection.anchorNode,
5493 anchorOffset: selection.anchorOffset,
5494 focusNode: selection.focusNode,
5495 focusOffset: selection.focusOffset
5496 };
5497 }
5498}
5499
5500/**
5501 * Get document associated with the event target.
5502 *
5503 * @param {object} nativeEventTarget
5504 * @return {Document}
5505 */
5506function getEventTargetDocument(eventTarget) {
5507 return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
5508}
5509
5510/**
5511 * Poll selection to see whether it's changed.
5512 *
5513 * @param {object} nativeEvent
5514 * @param {object} nativeEventTarget
5515 * @return {?SyntheticEvent}
5516 */
5517function constructSelectEvent(nativeEvent, nativeEventTarget) {
5518 // Ensure we have the right element, and that the user is not dragging a
5519 // selection (this matches native `select` event behavior). In HTML5, select
5520 // fires only on input and textarea thus if there's no focused element we
5521 // won't dispatch.
5522 var doc = getEventTargetDocument(nativeEventTarget);
5523
5524 if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
5525 return null;
5526 }
5527
5528 // Only fire when selection has actually changed.
5529 var currentSelection = getSelection(activeElement$1);
5530 if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
5531 lastSelection = currentSelection;
5532
5533 var syntheticEvent = SyntheticEvent.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget);
5534
5535 syntheticEvent.type = 'select';
5536 syntheticEvent.target = activeElement$1;
5537
5538 accumulateTwoPhaseDispatches(syntheticEvent);
5539
5540 return syntheticEvent;
5541 }
5542
5543 return null;
5544}
5545
5546/**
5547 * This plugin creates an `onSelect` event that normalizes select events
5548 * across form elements.
5549 *
5550 * Supported elements are:
5551 * - input (see `isTextInputElement`)
5552 * - textarea
5553 * - contentEditable
5554 *
5555 * This differs from native browser implementations in the following ways:
5556 * - Fires on contentEditable fields as well as inputs.
5557 * - Fires for collapsed selection.
5558 * - Fires after user input.
5559 */
5560var SelectEventPlugin = {
5561 eventTypes: eventTypes$3,
5562
5563 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
5564 var doc = getEventTargetDocument(nativeEventTarget);
5565 // Track whether all listeners exists for this plugin. If none exist, we do
5566 // not extract events. See #3639.
5567 if (!doc || !isListeningToAllDependencies('onSelect', doc)) {
5568 return null;
5569 }
5570
5571 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
5572
5573 switch (topLevelType) {
5574 // Track the input node that has focus.
5575 case TOP_FOCUS:
5576 if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
5577 activeElement$1 = targetNode;
5578 activeElementInst$1 = targetInst;
5579 lastSelection = null;
5580 }
5581 break;
5582 case TOP_BLUR:
5583 activeElement$1 = null;
5584 activeElementInst$1 = null;
5585 lastSelection = null;
5586 break;
5587 // Don't fire the event while the user is dragging. This matches the
5588 // semantics of the native select event.
5589 case TOP_MOUSE_DOWN:
5590 mouseDown = true;
5591 break;
5592 case TOP_CONTEXT_MENU:
5593 case TOP_MOUSE_UP:
5594 case TOP_DRAG_END:
5595 mouseDown = false;
5596 return constructSelectEvent(nativeEvent, nativeEventTarget);
5597 // Chrome and IE fire non-standard event when selection is changed (and
5598 // sometimes when it hasn't). IE's event fires out of order with respect
5599 // to key and input events on deletion, so we discard it.
5600 //
5601 // Firefox doesn't support selectionchange, so check selection status
5602 // after each key entry. The selection changes after keydown and before
5603 // keyup, but we check on keydown as well in the case of holding down a
5604 // key, when multiple keydown events are fired but only one keyup is.
5605 // This is also our approach for IE handling, for the reason above.
5606 case TOP_SELECTION_CHANGE:
5607 if (skipSelectionChangeEvent) {
5608 break;
5609 }
5610 // falls through
5611 case TOP_KEY_DOWN:
5612 case TOP_KEY_UP:
5613 return constructSelectEvent(nativeEvent, nativeEventTarget);
5614 }
5615
5616 return null;
5617 }
5618};
5619
5620/**
5621 * Inject modules for resolving DOM hierarchy and plugin ordering.
5622 */
5623injection.injectEventPluginOrder(DOMEventPluginOrder);
5624setComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);
5625
5626/**
5627 * Some important event plugins included by default (without having to require
5628 * them).
5629 */
5630injection.injectEventPluginsByName({
5631 SimpleEventPlugin: SimpleEventPlugin,
5632 EnterLeaveEventPlugin: EnterLeaveEventPlugin,
5633 ChangeEventPlugin: ChangeEventPlugin,
5634 SelectEventPlugin: SelectEventPlugin,
5635 BeforeInputEventPlugin: BeforeInputEventPlugin
5636});
5637
5638var didWarnSelectedSetOnOption = false;
5639var didWarnInvalidChild = false;
5640
5641function flattenChildren(children) {
5642 var content = '';
5643
5644 // Flatten children. We'll warn if they are invalid
5645 // during validateProps() which runs for hydration too.
5646 // Note that this would throw on non-element objects.
5647 // Elements are stringified (which is normally irrelevant
5648 // but matters for <fbt>).
5649 React.Children.forEach(children, function (child) {
5650 if (child == null) {
5651 return;
5652 }
5653 content += child;
5654 // Note: we don't warn about invalid children here.
5655 // Instead, this is done separately below so that
5656 // it happens during the hydration codepath too.
5657 });
5658
5659 return content;
5660}
5661
5662/**
5663 * Implements an <option> host component that warns when `selected` is set.
5664 */
5665
5666function validateProps(element, props) {
5667 {
5668 // This mirrors the codepath above, but runs for hydration too.
5669 // Warn about invalid children here so that client and hydration are consistent.
5670 // TODO: this seems like it could cause a DEV-only throw for hydration
5671 // if children contains a non-element object. We should try to avoid that.
5672 if (typeof props.children === 'object' && props.children !== null) {
5673 React.Children.forEach(props.children, function (child) {
5674 if (child == null) {
5675 return;
5676 }
5677 if (typeof child === 'string' || typeof child === 'number') {
5678 return;
5679 }
5680 if (typeof child.type !== 'string') {
5681 return;
5682 }
5683 if (!didWarnInvalidChild) {
5684 didWarnInvalidChild = true;
5685 warning$1(false, 'Only strings and numbers are supported as <option> children.');
5686 }
5687 });
5688 }
5689
5690 // TODO: Remove support for `selected` in <option>.
5691 if (props.selected != null && !didWarnSelectedSetOnOption) {
5692 warning$1(false, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
5693 didWarnSelectedSetOnOption = true;
5694 }
5695 }
5696}
5697
5698function postMountWrapper$1(element, props) {
5699 // value="" should make a value attribute (#6219)
5700 if (props.value != null) {
5701 element.setAttribute('value', toString(getToStringValue(props.value)));
5702 }
5703}
5704
5705function getHostProps$1(element, props) {
5706 var hostProps = _assign({ children: undefined }, props);
5707 var content = flattenChildren(props.children);
5708
5709 if (content) {
5710 hostProps.children = content;
5711 }
5712
5713 return hostProps;
5714}
5715
5716// TODO: direct imports like some-package/src/* are bad. Fix me.
5717var didWarnValueDefaultValue$1 = void 0;
5718
5719{
5720 didWarnValueDefaultValue$1 = false;
5721}
5722
5723function getDeclarationErrorAddendum() {
5724 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
5725 if (ownerName) {
5726 return '\n\nCheck the render method of `' + ownerName + '`.';
5727 }
5728 return '';
5729}
5730
5731var valuePropNames = ['value', 'defaultValue'];
5732
5733/**
5734 * Validation function for `value` and `defaultValue`.
5735 */
5736function checkSelectPropTypes(props) {
5737 ReactControlledValuePropTypes.checkPropTypes('select', props);
5738
5739 for (var i = 0; i < valuePropNames.length; i++) {
5740 var propName = valuePropNames[i];
5741 if (props[propName] == null) {
5742 continue;
5743 }
5744 var isArray = Array.isArray(props[propName]);
5745 if (props.multiple && !isArray) {
5746 warning$1(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
5747 } else if (!props.multiple && isArray) {
5748 warning$1(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
5749 }
5750 }
5751}
5752
5753function updateOptions(node, multiple, propValue, setDefaultSelected) {
5754 var options = node.options;
5755
5756 if (multiple) {
5757 var selectedValues = propValue;
5758 var selectedValue = {};
5759 for (var i = 0; i < selectedValues.length; i++) {
5760 // Prefix to avoid chaos with special keys.
5761 selectedValue['$' + selectedValues[i]] = true;
5762 }
5763 for (var _i = 0; _i < options.length; _i++) {
5764 var selected = selectedValue.hasOwnProperty('$' + options[_i].value);
5765 if (options[_i].selected !== selected) {
5766 options[_i].selected = selected;
5767 }
5768 if (selected && setDefaultSelected) {
5769 options[_i].defaultSelected = true;
5770 }
5771 }
5772 } else {
5773 // Do not set `select.value` as exact behavior isn't consistent across all
5774 // browsers for all cases.
5775 var _selectedValue = toString(getToStringValue(propValue));
5776 var defaultSelected = null;
5777 for (var _i2 = 0; _i2 < options.length; _i2++) {
5778 if (options[_i2].value === _selectedValue) {
5779 options[_i2].selected = true;
5780 if (setDefaultSelected) {
5781 options[_i2].defaultSelected = true;
5782 }
5783 return;
5784 }
5785 if (defaultSelected === null && !options[_i2].disabled) {
5786 defaultSelected = options[_i2];
5787 }
5788 }
5789 if (defaultSelected !== null) {
5790 defaultSelected.selected = true;
5791 }
5792 }
5793}
5794
5795/**
5796 * Implements a <select> host component that allows optionally setting the
5797 * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
5798 * stringable. If `multiple` is true, the prop must be an array of stringables.
5799 *
5800 * If `value` is not supplied (or null/undefined), user actions that change the
5801 * selected option will trigger updates to the rendered options.
5802 *
5803 * If it is supplied (and not null/undefined), the rendered options will not
5804 * update in response to user actions. Instead, the `value` prop must change in
5805 * order for the rendered options to update.
5806 *
5807 * If `defaultValue` is provided, any options with the supplied values will be
5808 * selected.
5809 */
5810
5811function getHostProps$2(element, props) {
5812 return _assign({}, props, {
5813 value: undefined
5814 });
5815}
5816
5817function initWrapperState$1(element, props) {
5818 var node = element;
5819 {
5820 checkSelectPropTypes(props);
5821 }
5822
5823 node._wrapperState = {
5824 wasMultiple: !!props.multiple
5825 };
5826
5827 {
5828 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
5829 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');
5830 didWarnValueDefaultValue$1 = true;
5831 }
5832 }
5833}
5834
5835function postMountWrapper$2(element, props) {
5836 var node = element;
5837 node.multiple = !!props.multiple;
5838 var value = props.value;
5839 if (value != null) {
5840 updateOptions(node, !!props.multiple, value, false);
5841 } else if (props.defaultValue != null) {
5842 updateOptions(node, !!props.multiple, props.defaultValue, true);
5843 }
5844}
5845
5846function postUpdateWrapper(element, props) {
5847 var node = element;
5848 var wasMultiple = node._wrapperState.wasMultiple;
5849 node._wrapperState.wasMultiple = !!props.multiple;
5850
5851 var value = props.value;
5852 if (value != null) {
5853 updateOptions(node, !!props.multiple, value, false);
5854 } else if (wasMultiple !== !!props.multiple) {
5855 // For simplicity, reapply `defaultValue` if `multiple` is toggled.
5856 if (props.defaultValue != null) {
5857 updateOptions(node, !!props.multiple, props.defaultValue, true);
5858 } else {
5859 // Revert the select back to its default unselected state.
5860 updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
5861 }
5862 }
5863}
5864
5865function restoreControlledState$2(element, props) {
5866 var node = element;
5867 var value = props.value;
5868
5869 if (value != null) {
5870 updateOptions(node, !!props.multiple, value, false);
5871 }
5872}
5873
5874var didWarnValDefaultVal = false;
5875
5876/**
5877 * Implements a <textarea> host component that allows setting `value`, and
5878 * `defaultValue`. This differs from the traditional DOM API because value is
5879 * usually set as PCDATA children.
5880 *
5881 * If `value` is not supplied (or null/undefined), user actions that affect the
5882 * value will trigger updates to the element.
5883 *
5884 * If `value` is supplied (and not null/undefined), the rendered element will
5885 * not trigger updates to the element. Instead, the `value` prop must change in
5886 * order for the rendered element to be updated.
5887 *
5888 * The rendered element will be initialized with an empty value, the prop
5889 * `defaultValue` if specified, or the children content (deprecated).
5890 */
5891
5892function getHostProps$3(element, props) {
5893 var node = element;
5894 !(props.dangerouslySetInnerHTML == null) ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : void 0;
5895
5896 // Always set children to the same thing. In IE9, the selection range will
5897 // get reset if `textContent` is mutated. We could add a check in setTextContent
5898 // to only set the value if/when the value differs from the node value (which would
5899 // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
5900 // solution. The value can be a boolean or object so that's why it's forced
5901 // to be a string.
5902 var hostProps = _assign({}, props, {
5903 value: undefined,
5904 defaultValue: undefined,
5905 children: toString(node._wrapperState.initialValue)
5906 });
5907
5908 return hostProps;
5909}
5910
5911function initWrapperState$2(element, props) {
5912 var node = element;
5913 {
5914 ReactControlledValuePropTypes.checkPropTypes('textarea', props);
5915 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
5916 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');
5917 didWarnValDefaultVal = true;
5918 }
5919 }
5920
5921 var initialValue = props.value;
5922
5923 // Only bother fetching default value if we're going to use it
5924 if (initialValue == null) {
5925 var defaultValue = props.defaultValue;
5926 // TODO (yungsters): Remove support for children content in <textarea>.
5927 var children = props.children;
5928 if (children != null) {
5929 {
5930 warning$1(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
5931 }
5932 !(defaultValue == null) ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : void 0;
5933 if (Array.isArray(children)) {
5934 !(children.length <= 1) ? invariant(false, '<textarea> can only have at most one child.') : void 0;
5935 children = children[0];
5936 }
5937
5938 defaultValue = children;
5939 }
5940 if (defaultValue == null) {
5941 defaultValue = '';
5942 }
5943 initialValue = defaultValue;
5944 }
5945
5946 node._wrapperState = {
5947 initialValue: getToStringValue(initialValue)
5948 };
5949}
5950
5951function updateWrapper$1(element, props) {
5952 var node = element;
5953 var value = getToStringValue(props.value);
5954 var defaultValue = getToStringValue(props.defaultValue);
5955 if (value != null) {
5956 // Cast `value` to a string to ensure the value is set correctly. While
5957 // browsers typically do this as necessary, jsdom doesn't.
5958 var newValue = toString(value);
5959 // To avoid side effects (such as losing text selection), only set value if changed
5960 if (newValue !== node.value) {
5961 node.value = newValue;
5962 }
5963 if (props.defaultValue == null && node.defaultValue !== newValue) {
5964 node.defaultValue = newValue;
5965 }
5966 }
5967 if (defaultValue != null) {
5968 node.defaultValue = toString(defaultValue);
5969 }
5970}
5971
5972function postMountWrapper$3(element, props) {
5973 var node = element;
5974 // This is in postMount because we need access to the DOM node, which is not
5975 // available until after the component has mounted.
5976 var textContent = node.textContent;
5977
5978 // Only set node.value if textContent is equal to the expected
5979 // initial value. In IE10/IE11 there is a bug where the placeholder attribute
5980 // will populate textContent as well.
5981 // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
5982 if (textContent === node._wrapperState.initialValue) {
5983 node.value = textContent;
5984 }
5985}
5986
5987function restoreControlledState$3(element, props) {
5988 // DOM component is still mounted; update
5989 updateWrapper$1(element, props);
5990}
5991
5992var HTML_NAMESPACE$1 = 'http://www.w3.org/1999/xhtml';
5993var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
5994var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
5995
5996var Namespaces = {
5997 html: HTML_NAMESPACE$1,
5998 mathml: MATH_NAMESPACE,
5999 svg: SVG_NAMESPACE
6000};
6001
6002// Assumes there is no parent namespace.
6003function getIntrinsicNamespace(type) {
6004 switch (type) {
6005 case 'svg':
6006 return SVG_NAMESPACE;
6007 case 'math':
6008 return MATH_NAMESPACE;
6009 default:
6010 return HTML_NAMESPACE$1;
6011 }
6012}
6013
6014function getChildNamespace(parentNamespace, type) {
6015 if (parentNamespace == null || parentNamespace === HTML_NAMESPACE$1) {
6016 // No (or default) parent namespace: potential entry point.
6017 return getIntrinsicNamespace(type);
6018 }
6019 if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
6020 // We're leaving SVG.
6021 return HTML_NAMESPACE$1;
6022 }
6023 // By default, pass namespace below.
6024 return parentNamespace;
6025}
6026
6027/* globals MSApp */
6028
6029/**
6030 * Create a function which has 'unsafe' privileges (required by windows8 apps)
6031 */
6032var createMicrosoftUnsafeLocalFunction = function (func) {
6033 if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
6034 return function (arg0, arg1, arg2, arg3) {
6035 MSApp.execUnsafeLocalFunction(function () {
6036 return func(arg0, arg1, arg2, arg3);
6037 });
6038 };
6039 } else {
6040 return func;
6041 }
6042};
6043
6044// SVG temp container for IE lacking innerHTML
6045var reusableSVGContainer = void 0;
6046
6047/**
6048 * Set the innerHTML property of a node
6049 *
6050 * @param {DOMElement} node
6051 * @param {string} html
6052 * @internal
6053 */
6054var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
6055 // IE does not have innerHTML for SVG nodes, so instead we inject the
6056 // new markup in a temp node and then move the child nodes across into
6057 // the target node
6058
6059 if (node.namespaceURI === Namespaces.svg && !('innerHTML' in node)) {
6060 reusableSVGContainer = reusableSVGContainer || document.createElement('div');
6061 reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
6062 var svgNode = reusableSVGContainer.firstChild;
6063 while (node.firstChild) {
6064 node.removeChild(node.firstChild);
6065 }
6066 while (svgNode.firstChild) {
6067 node.appendChild(svgNode.firstChild);
6068 }
6069 } else {
6070 node.innerHTML = html;
6071 }
6072});
6073
6074/**
6075 * Set the textContent property of a node. For text updates, it's faster
6076 * to set the `nodeValue` of the Text node directly instead of using
6077 * `.textContent` which will remove the existing node and create a new one.
6078 *
6079 * @param {DOMElement} node
6080 * @param {string} text
6081 * @internal
6082 */
6083var setTextContent = function (node, text) {
6084 if (text) {
6085 var firstChild = node.firstChild;
6086
6087 if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
6088 firstChild.nodeValue = text;
6089 return;
6090 }
6091 }
6092 node.textContent = text;
6093};
6094
6095// List derived from Gecko source code:
6096// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
6097var shorthandToLonghand = {
6098 animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
6099 background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
6100 backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
6101 border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6102 borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
6103 borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
6104 borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
6105 borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
6106 borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
6107 borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
6108 borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
6109 borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
6110 borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
6111 borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
6112 borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
6113 borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6114 borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
6115 columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
6116 columns: ['columnCount', 'columnWidth'],
6117 flex: ['flexBasis', 'flexGrow', 'flexShrink'],
6118 flexFlow: ['flexDirection', 'flexWrap'],
6119 font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
6120 fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
6121 gap: ['columnGap', 'rowGap'],
6122 grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6123 gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
6124 gridColumn: ['gridColumnEnd', 'gridColumnStart'],
6125 gridColumnGap: ['columnGap'],
6126 gridGap: ['columnGap', 'rowGap'],
6127 gridRow: ['gridRowEnd', 'gridRowStart'],
6128 gridRowGap: ['rowGap'],
6129 gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6130 listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
6131 margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
6132 marker: ['markerEnd', 'markerMid', 'markerStart'],
6133 mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
6134 maskPosition: ['maskPositionX', 'maskPositionY'],
6135 outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
6136 overflow: ['overflowX', 'overflowY'],
6137 padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
6138 placeContent: ['alignContent', 'justifyContent'],
6139 placeItems: ['alignItems', 'justifyItems'],
6140 placeSelf: ['alignSelf', 'justifySelf'],
6141 textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
6142 textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
6143 transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
6144 wordWrap: ['overflowWrap']
6145};
6146
6147/**
6148 * CSS properties which accept numbers but are not in units of "px".
6149 */
6150var isUnitlessNumber = {
6151 animationIterationCount: true,
6152 borderImageOutset: true,
6153 borderImageSlice: true,
6154 borderImageWidth: true,
6155 boxFlex: true,
6156 boxFlexGroup: true,
6157 boxOrdinalGroup: true,
6158 columnCount: true,
6159 columns: true,
6160 flex: true,
6161 flexGrow: true,
6162 flexPositive: true,
6163 flexShrink: true,
6164 flexNegative: true,
6165 flexOrder: true,
6166 gridArea: true,
6167 gridRow: true,
6168 gridRowEnd: true,
6169 gridRowSpan: true,
6170 gridRowStart: true,
6171 gridColumn: true,
6172 gridColumnEnd: true,
6173 gridColumnSpan: true,
6174 gridColumnStart: true,
6175 fontWeight: true,
6176 lineClamp: true,
6177 lineHeight: true,
6178 opacity: true,
6179 order: true,
6180 orphans: true,
6181 tabSize: true,
6182 widows: true,
6183 zIndex: true,
6184 zoom: true,
6185
6186 // SVG-related properties
6187 fillOpacity: true,
6188 floodOpacity: true,
6189 stopOpacity: true,
6190 strokeDasharray: true,
6191 strokeDashoffset: true,
6192 strokeMiterlimit: true,
6193 strokeOpacity: true,
6194 strokeWidth: true
6195};
6196
6197/**
6198 * @param {string} prefix vendor-specific prefix, eg: Webkit
6199 * @param {string} key style name, eg: transitionDuration
6200 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
6201 * WebkitTransitionDuration
6202 */
6203function prefixKey(prefix, key) {
6204 return prefix + key.charAt(0).toUpperCase() + key.substring(1);
6205}
6206
6207/**
6208 * Support style names that may come passed in prefixed by adding permutations
6209 * of vendor prefixes.
6210 */
6211var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
6212
6213// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
6214// infinite loop, because it iterates over the newly added props too.
6215Object.keys(isUnitlessNumber).forEach(function (prop) {
6216 prefixes.forEach(function (prefix) {
6217 isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
6218 });
6219});
6220
6221/**
6222 * Convert a value into the proper css writable value. The style name `name`
6223 * should be logical (no hyphens), as specified
6224 * in `CSSProperty.isUnitlessNumber`.
6225 *
6226 * @param {string} name CSS property name such as `topMargin`.
6227 * @param {*} value CSS property value such as `10px`.
6228 * @return {string} Normalized style value with dimensions applied.
6229 */
6230function dangerousStyleValue(name, value, isCustomProperty) {
6231 // Note that we've removed escapeTextForBrowser() calls here since the
6232 // whole string will be escaped when the attribute is injected into
6233 // the markup. If you provide unsafe user data here they can inject
6234 // arbitrary CSS which may be problematic (I couldn't repro this):
6235 // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
6236 // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
6237 // This is not an XSS hole but instead a potential CSS injection issue
6238 // which has lead to a greater discussion about how we're going to
6239 // trust URLs moving forward. See #2115901
6240
6241 var isEmpty = value == null || typeof value === 'boolean' || value === '';
6242 if (isEmpty) {
6243 return '';
6244 }
6245
6246 if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
6247 return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
6248 }
6249
6250 return ('' + value).trim();
6251}
6252
6253var uppercasePattern = /([A-Z])/g;
6254var msPattern = /^ms-/;
6255
6256/**
6257 * Hyphenates a camelcased CSS property name, for example:
6258 *
6259 * > hyphenateStyleName('backgroundColor')
6260 * < "background-color"
6261 * > hyphenateStyleName('MozTransition')
6262 * < "-moz-transition"
6263 * > hyphenateStyleName('msTransition')
6264 * < "-ms-transition"
6265 *
6266 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
6267 * is converted to `-ms-`.
6268 */
6269function hyphenateStyleName(name) {
6270 return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
6271}
6272
6273var warnValidStyle = function () {};
6274
6275{
6276 // 'msTransform' is correct, but the other prefixes should be capitalized
6277 var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
6278 var msPattern$1 = /^-ms-/;
6279 var hyphenPattern = /-(.)/g;
6280
6281 // style values shouldn't contain a semicolon
6282 var badStyleValueWithSemicolonPattern = /;\s*$/;
6283
6284 var warnedStyleNames = {};
6285 var warnedStyleValues = {};
6286 var warnedForNaNValue = false;
6287 var warnedForInfinityValue = false;
6288
6289 var camelize = function (string) {
6290 return string.replace(hyphenPattern, function (_, character) {
6291 return character.toUpperCase();
6292 });
6293 };
6294
6295 var warnHyphenatedStyleName = function (name) {
6296 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6297 return;
6298 }
6299
6300 warnedStyleNames[name] = true;
6301 warning$1(false, 'Unsupported style property %s. Did you mean %s?', name,
6302 // As Andi Smith suggests
6303 // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
6304 // is converted to lowercase `ms`.
6305 camelize(name.replace(msPattern$1, 'ms-')));
6306 };
6307
6308 var warnBadVendoredStyleName = function (name) {
6309 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6310 return;
6311 }
6312
6313 warnedStyleNames[name] = true;
6314 warning$1(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
6315 };
6316
6317 var warnStyleValueWithSemicolon = function (name, value) {
6318 if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
6319 return;
6320 }
6321
6322 warnedStyleValues[value] = true;
6323 warning$1(false, "Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
6324 };
6325
6326 var warnStyleValueIsNaN = function (name, value) {
6327 if (warnedForNaNValue) {
6328 return;
6329 }
6330
6331 warnedForNaNValue = true;
6332 warning$1(false, '`NaN` is an invalid value for the `%s` css style property.', name);
6333 };
6334
6335 var warnStyleValueIsInfinity = function (name, value) {
6336 if (warnedForInfinityValue) {
6337 return;
6338 }
6339
6340 warnedForInfinityValue = true;
6341 warning$1(false, '`Infinity` is an invalid value for the `%s` css style property.', name);
6342 };
6343
6344 warnValidStyle = function (name, value) {
6345 if (name.indexOf('-') > -1) {
6346 warnHyphenatedStyleName(name);
6347 } else if (badVendoredStyleNamePattern.test(name)) {
6348 warnBadVendoredStyleName(name);
6349 } else if (badStyleValueWithSemicolonPattern.test(value)) {
6350 warnStyleValueWithSemicolon(name, value);
6351 }
6352
6353 if (typeof value === 'number') {
6354 if (isNaN(value)) {
6355 warnStyleValueIsNaN(name, value);
6356 } else if (!isFinite(value)) {
6357 warnStyleValueIsInfinity(name, value);
6358 }
6359 }
6360 };
6361}
6362
6363var warnValidStyle$1 = warnValidStyle;
6364
6365/**
6366 * Operations for dealing with CSS properties.
6367 */
6368
6369/**
6370 * This creates a string that is expected to be equivalent to the style
6371 * attribute generated by server-side rendering. It by-passes warnings and
6372 * security checks so it's not safe to use this value for anything other than
6373 * comparison. It is only used in DEV for SSR validation.
6374 */
6375function createDangerousStringForStyles(styles) {
6376 {
6377 var serialized = '';
6378 var delimiter = '';
6379 for (var styleName in styles) {
6380 if (!styles.hasOwnProperty(styleName)) {
6381 continue;
6382 }
6383 var styleValue = styles[styleName];
6384 if (styleValue != null) {
6385 var isCustomProperty = styleName.indexOf('--') === 0;
6386 serialized += delimiter + hyphenateStyleName(styleName) + ':';
6387 serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
6388
6389 delimiter = ';';
6390 }
6391 }
6392 return serialized || null;
6393 }
6394}
6395
6396/**
6397 * Sets the value for multiple styles on a node. If a value is specified as
6398 * '' (empty string), the corresponding style property will be unset.
6399 *
6400 * @param {DOMElement} node
6401 * @param {object} styles
6402 */
6403function setValueForStyles(node, styles) {
6404 var style = node.style;
6405 for (var styleName in styles) {
6406 if (!styles.hasOwnProperty(styleName)) {
6407 continue;
6408 }
6409 var isCustomProperty = styleName.indexOf('--') === 0;
6410 {
6411 if (!isCustomProperty) {
6412 warnValidStyle$1(styleName, styles[styleName]);
6413 }
6414 }
6415 var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
6416 if (styleName === 'float') {
6417 styleName = 'cssFloat';
6418 }
6419 if (isCustomProperty) {
6420 style.setProperty(styleName, styleValue);
6421 } else {
6422 style[styleName] = styleValue;
6423 }
6424 }
6425}
6426
6427function isValueEmpty(value) {
6428 return value == null || typeof value === 'boolean' || value === '';
6429}
6430
6431/**
6432 * Given {color: 'red', overflow: 'hidden'} returns {
6433 * color: 'color',
6434 * overflowX: 'overflow',
6435 * overflowY: 'overflow',
6436 * }. This can be read as "the overflowY property was set by the overflow
6437 * shorthand". That is, the values are the property that each was derived from.
6438 */
6439function expandShorthandMap(styles) {
6440 var expanded = {};
6441 for (var key in styles) {
6442 var longhands = shorthandToLonghand[key] || [key];
6443 for (var i = 0; i < longhands.length; i++) {
6444 expanded[longhands[i]] = key;
6445 }
6446 }
6447 return expanded;
6448}
6449
6450/**
6451 * When mixing shorthand and longhand property names, we warn during updates if
6452 * we expect an incorrect result to occur. In particular, we warn for:
6453 *
6454 * Updating a shorthand property (longhand gets overwritten):
6455 * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
6456 * becomes .style.font = 'baz'
6457 * Removing a shorthand property (longhand gets lost too):
6458 * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
6459 * becomes .style.font = ''
6460 * Removing a longhand property (should revert to shorthand; doesn't):
6461 * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
6462 * becomes .style.fontVariant = ''
6463 */
6464function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
6465 if (!warnAboutShorthandPropertyCollision) {
6466 return;
6467 }
6468
6469 if (!nextStyles) {
6470 return;
6471 }
6472
6473 var expandedUpdates = expandShorthandMap(styleUpdates);
6474 var expandedStyles = expandShorthandMap(nextStyles);
6475 var warnedAbout = {};
6476 for (var key in expandedUpdates) {
6477 var originalKey = expandedUpdates[key];
6478 var correctOriginalKey = expandedStyles[key];
6479 if (correctOriginalKey && originalKey !== correctOriginalKey) {
6480 var warningKey = originalKey + ',' + correctOriginalKey;
6481 if (warnedAbout[warningKey]) {
6482 continue;
6483 }
6484 warnedAbout[warningKey] = true;
6485 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);
6486 }
6487 }
6488}
6489
6490// For HTML, certain tags should omit their close tag. We keep a whitelist for
6491// those special-case tags.
6492
6493var omittedCloseTags = {
6494 area: true,
6495 base: true,
6496 br: true,
6497 col: true,
6498 embed: true,
6499 hr: true,
6500 img: true,
6501 input: true,
6502 keygen: true,
6503 link: true,
6504 meta: true,
6505 param: true,
6506 source: true,
6507 track: true,
6508 wbr: true
6509 // NOTE: menuitem's close tag should be omitted, but that causes problems.
6510};
6511
6512// For HTML, certain tags cannot have children. This has the same purpose as
6513// `omittedCloseTags` except that `menuitem` should still have its closing tag.
6514
6515var voidElementTags = _assign({
6516 menuitem: true
6517}, omittedCloseTags);
6518
6519// TODO: We can remove this if we add invariantWithStack()
6520// or add stack by default to invariants where possible.
6521var HTML$1 = '__html';
6522
6523var ReactDebugCurrentFrame$2 = null;
6524{
6525 ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame;
6526}
6527
6528function assertValidProps(tag, props) {
6529 if (!props) {
6530 return;
6531 }
6532 // Note the use of `==` which checks for null or undefined.
6533 if (voidElementTags[tag]) {
6534 !(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;
6535 }
6536 if (props.dangerouslySetInnerHTML != null) {
6537 !(props.children == null) ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : void 0;
6538 !(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;
6539 }
6540 {
6541 !(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;
6542 }
6543 !(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;
6544}
6545
6546function isCustomComponent(tagName, props) {
6547 if (tagName.indexOf('-') === -1) {
6548 return typeof props.is === 'string';
6549 }
6550 switch (tagName) {
6551 // These are reserved SVG and MathML elements.
6552 // We don't mind this whitelist too much because we expect it to never grow.
6553 // The alternative is to track the namespace in a few places which is convoluted.
6554 // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
6555 case 'annotation-xml':
6556 case 'color-profile':
6557 case 'font-face':
6558 case 'font-face-src':
6559 case 'font-face-uri':
6560 case 'font-face-format':
6561 case 'font-face-name':
6562 case 'missing-glyph':
6563 return false;
6564 default:
6565 return true;
6566 }
6567}
6568
6569// When adding attributes to the HTML or SVG whitelist, be sure to
6570// also add them to this module to ensure casing and incorrect name
6571// warnings.
6572var possibleStandardNames = {
6573 // HTML
6574 accept: 'accept',
6575 acceptcharset: 'acceptCharset',
6576 'accept-charset': 'acceptCharset',
6577 accesskey: 'accessKey',
6578 action: 'action',
6579 allowfullscreen: 'allowFullScreen',
6580 alt: 'alt',
6581 as: 'as',
6582 async: 'async',
6583 autocapitalize: 'autoCapitalize',
6584 autocomplete: 'autoComplete',
6585 autocorrect: 'autoCorrect',
6586 autofocus: 'autoFocus',
6587 autoplay: 'autoPlay',
6588 autosave: 'autoSave',
6589 capture: 'capture',
6590 cellpadding: 'cellPadding',
6591 cellspacing: 'cellSpacing',
6592 challenge: 'challenge',
6593 charset: 'charSet',
6594 checked: 'checked',
6595 children: 'children',
6596 cite: 'cite',
6597 class: 'className',
6598 classid: 'classID',
6599 classname: 'className',
6600 cols: 'cols',
6601 colspan: 'colSpan',
6602 content: 'content',
6603 contenteditable: 'contentEditable',
6604 contextmenu: 'contextMenu',
6605 controls: 'controls',
6606 controlslist: 'controlsList',
6607 coords: 'coords',
6608 crossorigin: 'crossOrigin',
6609 dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
6610 data: 'data',
6611 datetime: 'dateTime',
6612 default: 'default',
6613 defaultchecked: 'defaultChecked',
6614 defaultvalue: 'defaultValue',
6615 defer: 'defer',
6616 dir: 'dir',
6617 disabled: 'disabled',
6618 download: 'download',
6619 draggable: 'draggable',
6620 enctype: 'encType',
6621 for: 'htmlFor',
6622 form: 'form',
6623 formmethod: 'formMethod',
6624 formaction: 'formAction',
6625 formenctype: 'formEncType',
6626 formnovalidate: 'formNoValidate',
6627 formtarget: 'formTarget',
6628 frameborder: 'frameBorder',
6629 headers: 'headers',
6630 height: 'height',
6631 hidden: 'hidden',
6632 high: 'high',
6633 href: 'href',
6634 hreflang: 'hrefLang',
6635 htmlfor: 'htmlFor',
6636 httpequiv: 'httpEquiv',
6637 'http-equiv': 'httpEquiv',
6638 icon: 'icon',
6639 id: 'id',
6640 innerhtml: 'innerHTML',
6641 inputmode: 'inputMode',
6642 integrity: 'integrity',
6643 is: 'is',
6644 itemid: 'itemID',
6645 itemprop: 'itemProp',
6646 itemref: 'itemRef',
6647 itemscope: 'itemScope',
6648 itemtype: 'itemType',
6649 keyparams: 'keyParams',
6650 keytype: 'keyType',
6651 kind: 'kind',
6652 label: 'label',
6653 lang: 'lang',
6654 list: 'list',
6655 loop: 'loop',
6656 low: 'low',
6657 manifest: 'manifest',
6658 marginwidth: 'marginWidth',
6659 marginheight: 'marginHeight',
6660 max: 'max',
6661 maxlength: 'maxLength',
6662 media: 'media',
6663 mediagroup: 'mediaGroup',
6664 method: 'method',
6665 min: 'min',
6666 minlength: 'minLength',
6667 multiple: 'multiple',
6668 muted: 'muted',
6669 name: 'name',
6670 nomodule: 'noModule',
6671 nonce: 'nonce',
6672 novalidate: 'noValidate',
6673 open: 'open',
6674 optimum: 'optimum',
6675 pattern: 'pattern',
6676 placeholder: 'placeholder',
6677 playsinline: 'playsInline',
6678 poster: 'poster',
6679 preload: 'preload',
6680 profile: 'profile',
6681 radiogroup: 'radioGroup',
6682 readonly: 'readOnly',
6683 referrerpolicy: 'referrerPolicy',
6684 rel: 'rel',
6685 required: 'required',
6686 reversed: 'reversed',
6687 role: 'role',
6688 rows: 'rows',
6689 rowspan: 'rowSpan',
6690 sandbox: 'sandbox',
6691 scope: 'scope',
6692 scoped: 'scoped',
6693 scrolling: 'scrolling',
6694 seamless: 'seamless',
6695 selected: 'selected',
6696 shape: 'shape',
6697 size: 'size',
6698 sizes: 'sizes',
6699 span: 'span',
6700 spellcheck: 'spellCheck',
6701 src: 'src',
6702 srcdoc: 'srcDoc',
6703 srclang: 'srcLang',
6704 srcset: 'srcSet',
6705 start: 'start',
6706 step: 'step',
6707 style: 'style',
6708 summary: 'summary',
6709 tabindex: 'tabIndex',
6710 target: 'target',
6711 title: 'title',
6712 type: 'type',
6713 usemap: 'useMap',
6714 value: 'value',
6715 width: 'width',
6716 wmode: 'wmode',
6717 wrap: 'wrap',
6718
6719 // SVG
6720 about: 'about',
6721 accentheight: 'accentHeight',
6722 'accent-height': 'accentHeight',
6723 accumulate: 'accumulate',
6724 additive: 'additive',
6725 alignmentbaseline: 'alignmentBaseline',
6726 'alignment-baseline': 'alignmentBaseline',
6727 allowreorder: 'allowReorder',
6728 alphabetic: 'alphabetic',
6729 amplitude: 'amplitude',
6730 arabicform: 'arabicForm',
6731 'arabic-form': 'arabicForm',
6732 ascent: 'ascent',
6733 attributename: 'attributeName',
6734 attributetype: 'attributeType',
6735 autoreverse: 'autoReverse',
6736 azimuth: 'azimuth',
6737 basefrequency: 'baseFrequency',
6738 baselineshift: 'baselineShift',
6739 'baseline-shift': 'baselineShift',
6740 baseprofile: 'baseProfile',
6741 bbox: 'bbox',
6742 begin: 'begin',
6743 bias: 'bias',
6744 by: 'by',
6745 calcmode: 'calcMode',
6746 capheight: 'capHeight',
6747 'cap-height': 'capHeight',
6748 clip: 'clip',
6749 clippath: 'clipPath',
6750 'clip-path': 'clipPath',
6751 clippathunits: 'clipPathUnits',
6752 cliprule: 'clipRule',
6753 'clip-rule': 'clipRule',
6754 color: 'color',
6755 colorinterpolation: 'colorInterpolation',
6756 'color-interpolation': 'colorInterpolation',
6757 colorinterpolationfilters: 'colorInterpolationFilters',
6758 'color-interpolation-filters': 'colorInterpolationFilters',
6759 colorprofile: 'colorProfile',
6760 'color-profile': 'colorProfile',
6761 colorrendering: 'colorRendering',
6762 'color-rendering': 'colorRendering',
6763 contentscripttype: 'contentScriptType',
6764 contentstyletype: 'contentStyleType',
6765 cursor: 'cursor',
6766 cx: 'cx',
6767 cy: 'cy',
6768 d: 'd',
6769 datatype: 'datatype',
6770 decelerate: 'decelerate',
6771 descent: 'descent',
6772 diffuseconstant: 'diffuseConstant',
6773 direction: 'direction',
6774 display: 'display',
6775 divisor: 'divisor',
6776 dominantbaseline: 'dominantBaseline',
6777 'dominant-baseline': 'dominantBaseline',
6778 dur: 'dur',
6779 dx: 'dx',
6780 dy: 'dy',
6781 edgemode: 'edgeMode',
6782 elevation: 'elevation',
6783 enablebackground: 'enableBackground',
6784 'enable-background': 'enableBackground',
6785 end: 'end',
6786 exponent: 'exponent',
6787 externalresourcesrequired: 'externalResourcesRequired',
6788 fill: 'fill',
6789 fillopacity: 'fillOpacity',
6790 'fill-opacity': 'fillOpacity',
6791 fillrule: 'fillRule',
6792 'fill-rule': 'fillRule',
6793 filter: 'filter',
6794 filterres: 'filterRes',
6795 filterunits: 'filterUnits',
6796 floodopacity: 'floodOpacity',
6797 'flood-opacity': 'floodOpacity',
6798 floodcolor: 'floodColor',
6799 'flood-color': 'floodColor',
6800 focusable: 'focusable',
6801 fontfamily: 'fontFamily',
6802 'font-family': 'fontFamily',
6803 fontsize: 'fontSize',
6804 'font-size': 'fontSize',
6805 fontsizeadjust: 'fontSizeAdjust',
6806 'font-size-adjust': 'fontSizeAdjust',
6807 fontstretch: 'fontStretch',
6808 'font-stretch': 'fontStretch',
6809 fontstyle: 'fontStyle',
6810 'font-style': 'fontStyle',
6811 fontvariant: 'fontVariant',
6812 'font-variant': 'fontVariant',
6813 fontweight: 'fontWeight',
6814 'font-weight': 'fontWeight',
6815 format: 'format',
6816 from: 'from',
6817 fx: 'fx',
6818 fy: 'fy',
6819 g1: 'g1',
6820 g2: 'g2',
6821 glyphname: 'glyphName',
6822 'glyph-name': 'glyphName',
6823 glyphorientationhorizontal: 'glyphOrientationHorizontal',
6824 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
6825 glyphorientationvertical: 'glyphOrientationVertical',
6826 'glyph-orientation-vertical': 'glyphOrientationVertical',
6827 glyphref: 'glyphRef',
6828 gradienttransform: 'gradientTransform',
6829 gradientunits: 'gradientUnits',
6830 hanging: 'hanging',
6831 horizadvx: 'horizAdvX',
6832 'horiz-adv-x': 'horizAdvX',
6833 horizoriginx: 'horizOriginX',
6834 'horiz-origin-x': 'horizOriginX',
6835 ideographic: 'ideographic',
6836 imagerendering: 'imageRendering',
6837 'image-rendering': 'imageRendering',
6838 in2: 'in2',
6839 in: 'in',
6840 inlist: 'inlist',
6841 intercept: 'intercept',
6842 k1: 'k1',
6843 k2: 'k2',
6844 k3: 'k3',
6845 k4: 'k4',
6846 k: 'k',
6847 kernelmatrix: 'kernelMatrix',
6848 kernelunitlength: 'kernelUnitLength',
6849 kerning: 'kerning',
6850 keypoints: 'keyPoints',
6851 keysplines: 'keySplines',
6852 keytimes: 'keyTimes',
6853 lengthadjust: 'lengthAdjust',
6854 letterspacing: 'letterSpacing',
6855 'letter-spacing': 'letterSpacing',
6856 lightingcolor: 'lightingColor',
6857 'lighting-color': 'lightingColor',
6858 limitingconeangle: 'limitingConeAngle',
6859 local: 'local',
6860 markerend: 'markerEnd',
6861 'marker-end': 'markerEnd',
6862 markerheight: 'markerHeight',
6863 markermid: 'markerMid',
6864 'marker-mid': 'markerMid',
6865 markerstart: 'markerStart',
6866 'marker-start': 'markerStart',
6867 markerunits: 'markerUnits',
6868 markerwidth: 'markerWidth',
6869 mask: 'mask',
6870 maskcontentunits: 'maskContentUnits',
6871 maskunits: 'maskUnits',
6872 mathematical: 'mathematical',
6873 mode: 'mode',
6874 numoctaves: 'numOctaves',
6875 offset: 'offset',
6876 opacity: 'opacity',
6877 operator: 'operator',
6878 order: 'order',
6879 orient: 'orient',
6880 orientation: 'orientation',
6881 origin: 'origin',
6882 overflow: 'overflow',
6883 overlineposition: 'overlinePosition',
6884 'overline-position': 'overlinePosition',
6885 overlinethickness: 'overlineThickness',
6886 'overline-thickness': 'overlineThickness',
6887 paintorder: 'paintOrder',
6888 'paint-order': 'paintOrder',
6889 panose1: 'panose1',
6890 'panose-1': 'panose1',
6891 pathlength: 'pathLength',
6892 patterncontentunits: 'patternContentUnits',
6893 patterntransform: 'patternTransform',
6894 patternunits: 'patternUnits',
6895 pointerevents: 'pointerEvents',
6896 'pointer-events': 'pointerEvents',
6897 points: 'points',
6898 pointsatx: 'pointsAtX',
6899 pointsaty: 'pointsAtY',
6900 pointsatz: 'pointsAtZ',
6901 prefix: 'prefix',
6902 preservealpha: 'preserveAlpha',
6903 preserveaspectratio: 'preserveAspectRatio',
6904 primitiveunits: 'primitiveUnits',
6905 property: 'property',
6906 r: 'r',
6907 radius: 'radius',
6908 refx: 'refX',
6909 refy: 'refY',
6910 renderingintent: 'renderingIntent',
6911 'rendering-intent': 'renderingIntent',
6912 repeatcount: 'repeatCount',
6913 repeatdur: 'repeatDur',
6914 requiredextensions: 'requiredExtensions',
6915 requiredfeatures: 'requiredFeatures',
6916 resource: 'resource',
6917 restart: 'restart',
6918 result: 'result',
6919 results: 'results',
6920 rotate: 'rotate',
6921 rx: 'rx',
6922 ry: 'ry',
6923 scale: 'scale',
6924 security: 'security',
6925 seed: 'seed',
6926 shaperendering: 'shapeRendering',
6927 'shape-rendering': 'shapeRendering',
6928 slope: 'slope',
6929 spacing: 'spacing',
6930 specularconstant: 'specularConstant',
6931 specularexponent: 'specularExponent',
6932 speed: 'speed',
6933 spreadmethod: 'spreadMethod',
6934 startoffset: 'startOffset',
6935 stddeviation: 'stdDeviation',
6936 stemh: 'stemh',
6937 stemv: 'stemv',
6938 stitchtiles: 'stitchTiles',
6939 stopcolor: 'stopColor',
6940 'stop-color': 'stopColor',
6941 stopopacity: 'stopOpacity',
6942 'stop-opacity': 'stopOpacity',
6943 strikethroughposition: 'strikethroughPosition',
6944 'strikethrough-position': 'strikethroughPosition',
6945 strikethroughthickness: 'strikethroughThickness',
6946 'strikethrough-thickness': 'strikethroughThickness',
6947 string: 'string',
6948 stroke: 'stroke',
6949 strokedasharray: 'strokeDasharray',
6950 'stroke-dasharray': 'strokeDasharray',
6951 strokedashoffset: 'strokeDashoffset',
6952 'stroke-dashoffset': 'strokeDashoffset',
6953 strokelinecap: 'strokeLinecap',
6954 'stroke-linecap': 'strokeLinecap',
6955 strokelinejoin: 'strokeLinejoin',
6956 'stroke-linejoin': 'strokeLinejoin',
6957 strokemiterlimit: 'strokeMiterlimit',
6958 'stroke-miterlimit': 'strokeMiterlimit',
6959 strokewidth: 'strokeWidth',
6960 'stroke-width': 'strokeWidth',
6961 strokeopacity: 'strokeOpacity',
6962 'stroke-opacity': 'strokeOpacity',
6963 suppresscontenteditablewarning: 'suppressContentEditableWarning',
6964 suppresshydrationwarning: 'suppressHydrationWarning',
6965 surfacescale: 'surfaceScale',
6966 systemlanguage: 'systemLanguage',
6967 tablevalues: 'tableValues',
6968 targetx: 'targetX',
6969 targety: 'targetY',
6970 textanchor: 'textAnchor',
6971 'text-anchor': 'textAnchor',
6972 textdecoration: 'textDecoration',
6973 'text-decoration': 'textDecoration',
6974 textlength: 'textLength',
6975 textrendering: 'textRendering',
6976 'text-rendering': 'textRendering',
6977 to: 'to',
6978 transform: 'transform',
6979 typeof: 'typeof',
6980 u1: 'u1',
6981 u2: 'u2',
6982 underlineposition: 'underlinePosition',
6983 'underline-position': 'underlinePosition',
6984 underlinethickness: 'underlineThickness',
6985 'underline-thickness': 'underlineThickness',
6986 unicode: 'unicode',
6987 unicodebidi: 'unicodeBidi',
6988 'unicode-bidi': 'unicodeBidi',
6989 unicoderange: 'unicodeRange',
6990 'unicode-range': 'unicodeRange',
6991 unitsperem: 'unitsPerEm',
6992 'units-per-em': 'unitsPerEm',
6993 unselectable: 'unselectable',
6994 valphabetic: 'vAlphabetic',
6995 'v-alphabetic': 'vAlphabetic',
6996 values: 'values',
6997 vectoreffect: 'vectorEffect',
6998 'vector-effect': 'vectorEffect',
6999 version: 'version',
7000 vertadvy: 'vertAdvY',
7001 'vert-adv-y': 'vertAdvY',
7002 vertoriginx: 'vertOriginX',
7003 'vert-origin-x': 'vertOriginX',
7004 vertoriginy: 'vertOriginY',
7005 'vert-origin-y': 'vertOriginY',
7006 vhanging: 'vHanging',
7007 'v-hanging': 'vHanging',
7008 videographic: 'vIdeographic',
7009 'v-ideographic': 'vIdeographic',
7010 viewbox: 'viewBox',
7011 viewtarget: 'viewTarget',
7012 visibility: 'visibility',
7013 vmathematical: 'vMathematical',
7014 'v-mathematical': 'vMathematical',
7015 vocab: 'vocab',
7016 widths: 'widths',
7017 wordspacing: 'wordSpacing',
7018 'word-spacing': 'wordSpacing',
7019 writingmode: 'writingMode',
7020 'writing-mode': 'writingMode',
7021 x1: 'x1',
7022 x2: 'x2',
7023 x: 'x',
7024 xchannelselector: 'xChannelSelector',
7025 xheight: 'xHeight',
7026 'x-height': 'xHeight',
7027 xlinkactuate: 'xlinkActuate',
7028 'xlink:actuate': 'xlinkActuate',
7029 xlinkarcrole: 'xlinkArcrole',
7030 'xlink:arcrole': 'xlinkArcrole',
7031 xlinkhref: 'xlinkHref',
7032 'xlink:href': 'xlinkHref',
7033 xlinkrole: 'xlinkRole',
7034 'xlink:role': 'xlinkRole',
7035 xlinkshow: 'xlinkShow',
7036 'xlink:show': 'xlinkShow',
7037 xlinktitle: 'xlinkTitle',
7038 'xlink:title': 'xlinkTitle',
7039 xlinktype: 'xlinkType',
7040 'xlink:type': 'xlinkType',
7041 xmlbase: 'xmlBase',
7042 'xml:base': 'xmlBase',
7043 xmllang: 'xmlLang',
7044 'xml:lang': 'xmlLang',
7045 xmlns: 'xmlns',
7046 'xml:space': 'xmlSpace',
7047 xmlnsxlink: 'xmlnsXlink',
7048 'xmlns:xlink': 'xmlnsXlink',
7049 xmlspace: 'xmlSpace',
7050 y1: 'y1',
7051 y2: 'y2',
7052 y: 'y',
7053 ychannelselector: 'yChannelSelector',
7054 z: 'z',
7055 zoomandpan: 'zoomAndPan'
7056};
7057
7058var ariaProperties = {
7059 'aria-current': 0, // state
7060 'aria-details': 0,
7061 'aria-disabled': 0, // state
7062 'aria-hidden': 0, // state
7063 'aria-invalid': 0, // state
7064 'aria-keyshortcuts': 0,
7065 'aria-label': 0,
7066 'aria-roledescription': 0,
7067 // Widget Attributes
7068 'aria-autocomplete': 0,
7069 'aria-checked': 0,
7070 'aria-expanded': 0,
7071 'aria-haspopup': 0,
7072 'aria-level': 0,
7073 'aria-modal': 0,
7074 'aria-multiline': 0,
7075 'aria-multiselectable': 0,
7076 'aria-orientation': 0,
7077 'aria-placeholder': 0,
7078 'aria-pressed': 0,
7079 'aria-readonly': 0,
7080 'aria-required': 0,
7081 'aria-selected': 0,
7082 'aria-sort': 0,
7083 'aria-valuemax': 0,
7084 'aria-valuemin': 0,
7085 'aria-valuenow': 0,
7086 'aria-valuetext': 0,
7087 // Live Region Attributes
7088 'aria-atomic': 0,
7089 'aria-busy': 0,
7090 'aria-live': 0,
7091 'aria-relevant': 0,
7092 // Drag-and-Drop Attributes
7093 'aria-dropeffect': 0,
7094 'aria-grabbed': 0,
7095 // Relationship Attributes
7096 'aria-activedescendant': 0,
7097 'aria-colcount': 0,
7098 'aria-colindex': 0,
7099 'aria-colspan': 0,
7100 'aria-controls': 0,
7101 'aria-describedby': 0,
7102 'aria-errormessage': 0,
7103 'aria-flowto': 0,
7104 'aria-labelledby': 0,
7105 'aria-owns': 0,
7106 'aria-posinset': 0,
7107 'aria-rowcount': 0,
7108 'aria-rowindex': 0,
7109 'aria-rowspan': 0,
7110 'aria-setsize': 0
7111};
7112
7113var warnedProperties = {};
7114var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7115var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7116
7117var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
7118
7119function validateProperty(tagName, name) {
7120 if (hasOwnProperty$2.call(warnedProperties, name) && warnedProperties[name]) {
7121 return true;
7122 }
7123
7124 if (rARIACamel.test(name)) {
7125 var ariaName = 'aria-' + name.slice(4).toLowerCase();
7126 var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null;
7127
7128 // If this is an aria-* attribute, but is not listed in the known DOM
7129 // DOM properties, then it is an invalid aria-* attribute.
7130 if (correctName == null) {
7131 warning$1(false, 'Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
7132 warnedProperties[name] = true;
7133 return true;
7134 }
7135 // aria-* attributes should be lowercase; suggest the lowercase version.
7136 if (name !== correctName) {
7137 warning$1(false, 'Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
7138 warnedProperties[name] = true;
7139 return true;
7140 }
7141 }
7142
7143 if (rARIA.test(name)) {
7144 var lowerCasedName = name.toLowerCase();
7145 var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null;
7146
7147 // If this is an aria-* attribute, but is not listed in the known DOM
7148 // DOM properties, then it is an invalid aria-* attribute.
7149 if (standardName == null) {
7150 warnedProperties[name] = true;
7151 return false;
7152 }
7153 // aria-* attributes should be lowercase; suggest the lowercase version.
7154 if (name !== standardName) {
7155 warning$1(false, 'Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
7156 warnedProperties[name] = true;
7157 return true;
7158 }
7159 }
7160
7161 return true;
7162}
7163
7164function warnInvalidARIAProps(type, props) {
7165 var invalidProps = [];
7166
7167 for (var key in props) {
7168 var isValid = validateProperty(type, key);
7169 if (!isValid) {
7170 invalidProps.push(key);
7171 }
7172 }
7173
7174 var unknownPropString = invalidProps.map(function (prop) {
7175 return '`' + prop + '`';
7176 }).join(', ');
7177
7178 if (invalidProps.length === 1) {
7179 warning$1(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7180 } else if (invalidProps.length > 1) {
7181 warning$1(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7182 }
7183}
7184
7185function validateProperties(type, props) {
7186 if (isCustomComponent(type, props)) {
7187 return;
7188 }
7189 warnInvalidARIAProps(type, props);
7190}
7191
7192var didWarnValueNull = false;
7193
7194function validateProperties$1(type, props) {
7195 if (type !== 'input' && type !== 'textarea' && type !== 'select') {
7196 return;
7197 }
7198
7199 if (props != null && props.value === null && !didWarnValueNull) {
7200 didWarnValueNull = true;
7201 if (type === 'select' && props.multiple) {
7202 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);
7203 } else {
7204 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);
7205 }
7206 }
7207}
7208
7209var validateProperty$1 = function () {};
7210
7211{
7212 var warnedProperties$1 = {};
7213 var _hasOwnProperty = Object.prototype.hasOwnProperty;
7214 var EVENT_NAME_REGEX = /^on./;
7215 var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
7216 var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7217 var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7218
7219 validateProperty$1 = function (tagName, name, value, canUseEventSystem) {
7220 if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
7221 return true;
7222 }
7223
7224 var lowerCasedName = name.toLowerCase();
7225 if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
7226 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.');
7227 warnedProperties$1[name] = true;
7228 return true;
7229 }
7230
7231 // We can't rely on the event system being injected on the server.
7232 if (canUseEventSystem) {
7233 if (registrationNameModules.hasOwnProperty(name)) {
7234 return true;
7235 }
7236 var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
7237 if (registrationName != null) {
7238 warning$1(false, 'Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
7239 warnedProperties$1[name] = true;
7240 return true;
7241 }
7242 if (EVENT_NAME_REGEX.test(name)) {
7243 warning$1(false, 'Unknown event handler property `%s`. It will be ignored.', name);
7244 warnedProperties$1[name] = true;
7245 return true;
7246 }
7247 } else if (EVENT_NAME_REGEX.test(name)) {
7248 // If no event plugins have been injected, we are in a server environment.
7249 // So we can't tell if the event name is correct for sure, but we can filter
7250 // out known bad ones like `onclick`. We can't suggest a specific replacement though.
7251 if (INVALID_EVENT_NAME_REGEX.test(name)) {
7252 warning$1(false, 'Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
7253 }
7254 warnedProperties$1[name] = true;
7255 return true;
7256 }
7257
7258 // Let the ARIA attribute hook validate ARIA attributes
7259 if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
7260 return true;
7261 }
7262
7263 if (lowerCasedName === 'innerhtml') {
7264 warning$1(false, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
7265 warnedProperties$1[name] = true;
7266 return true;
7267 }
7268
7269 if (lowerCasedName === 'aria') {
7270 warning$1(false, 'The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
7271 warnedProperties$1[name] = true;
7272 return true;
7273 }
7274
7275 if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
7276 warning$1(false, 'Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
7277 warnedProperties$1[name] = true;
7278 return true;
7279 }
7280
7281 if (typeof value === 'number' && isNaN(value)) {
7282 warning$1(false, 'Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
7283 warnedProperties$1[name] = true;
7284 return true;
7285 }
7286
7287 var propertyInfo = getPropertyInfo(name);
7288 var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED;
7289
7290 // Known attributes should match the casing specified in the property config.
7291 if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
7292 var standardName = possibleStandardNames[lowerCasedName];
7293 if (standardName !== name) {
7294 warning$1(false, 'Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
7295 warnedProperties$1[name] = true;
7296 return true;
7297 }
7298 } else if (!isReserved && name !== lowerCasedName) {
7299 // Unknown attributes should have lowercase casing since that's how they
7300 // will be cased anyway with server rendering.
7301 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);
7302 warnedProperties$1[name] = true;
7303 return true;
7304 }
7305
7306 if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7307 if (value) {
7308 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);
7309 } else {
7310 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);
7311 }
7312 warnedProperties$1[name] = true;
7313 return true;
7314 }
7315
7316 // Now that we've validated casing, do not validate
7317 // data types for reserved props
7318 if (isReserved) {
7319 return true;
7320 }
7321
7322 // Warn when a known attribute is a bad type
7323 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7324 warnedProperties$1[name] = true;
7325 return false;
7326 }
7327
7328 // Warn when passing the strings 'false' or 'true' into a boolean prop
7329 if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
7330 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);
7331 warnedProperties$1[name] = true;
7332 return true;
7333 }
7334
7335 return true;
7336 };
7337}
7338
7339var warnUnknownProperties = function (type, props, canUseEventSystem) {
7340 var unknownProps = [];
7341 for (var key in props) {
7342 var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);
7343 if (!isValid) {
7344 unknownProps.push(key);
7345 }
7346 }
7347
7348 var unknownPropString = unknownProps.map(function (prop) {
7349 return '`' + prop + '`';
7350 }).join(', ');
7351 if (unknownProps.length === 1) {
7352 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);
7353 } else if (unknownProps.length > 1) {
7354 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);
7355 }
7356};
7357
7358function validateProperties$2(type, props, canUseEventSystem) {
7359 if (isCustomComponent(type, props)) {
7360 return;
7361 }
7362 warnUnknownProperties(type, props, canUseEventSystem);
7363}
7364
7365// TODO: direct imports like some-package/src/* are bad. Fix me.
7366var didWarnInvalidHydration = false;
7367var didWarnShadyDOM = false;
7368
7369var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
7370var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
7371var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
7372var AUTOFOCUS = 'autoFocus';
7373var CHILDREN = 'children';
7374var STYLE$1 = 'style';
7375var HTML = '__html';
7376
7377var HTML_NAMESPACE = Namespaces.html;
7378
7379
7380var warnedUnknownTags = void 0;
7381var suppressHydrationWarning = void 0;
7382
7383var validatePropertiesInDevelopment = void 0;
7384var warnForTextDifference = void 0;
7385var warnForPropDifference = void 0;
7386var warnForExtraAttributes = void 0;
7387var warnForInvalidEventListener = void 0;
7388var canDiffStyleForHydrationWarning = void 0;
7389
7390var normalizeMarkupForTextOrAttribute = void 0;
7391var normalizeHTML = void 0;
7392
7393{
7394 warnedUnknownTags = {
7395 // Chrome is the only major browser not shipping <time>. But as of July
7396 // 2017 it intends to ship it due to widespread usage. We intentionally
7397 // *don't* warn for <time> even if it's unrecognized by Chrome because
7398 // it soon will be, and many apps have been using it anyway.
7399 time: true,
7400 // There are working polyfills for <dialog>. Let people use it.
7401 dialog: true,
7402 // Electron ships a custom <webview> tag to display external web content in
7403 // an isolated frame and process.
7404 // This tag is not present in non Electron environments such as JSDom which
7405 // is often used for testing purposes.
7406 // @see https://electronjs.org/docs/api/webview-tag
7407 webview: true
7408 };
7409
7410 validatePropertiesInDevelopment = function (type, props) {
7411 validateProperties(type, props);
7412 validateProperties$1(type, props);
7413 validateProperties$2(type, props, /* canUseEventSystem */true);
7414 };
7415
7416 // IE 11 parses & normalizes the style attribute as opposed to other
7417 // browsers. It adds spaces and sorts the properties in some
7418 // non-alphabetical order. Handling that would require sorting CSS
7419 // properties in the client & server versions or applying
7420 // `expectedStyle` to a temporary DOM node to read its `style` attribute
7421 // normalized. Since it only affects IE, we're skipping style warnings
7422 // in that browser completely in favor of doing all that work.
7423 // See https://github.com/facebook/react/issues/11807
7424 canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode;
7425
7426 // HTML parsing normalizes CR and CRLF to LF.
7427 // It also can turn \u0000 into \uFFFD inside attributes.
7428 // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
7429 // If we have a mismatch, it might be caused by that.
7430 // We will still patch up in this case but not fire the warning.
7431 var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
7432 var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
7433
7434 normalizeMarkupForTextOrAttribute = function (markup) {
7435 var markupString = typeof markup === 'string' ? markup : '' + markup;
7436 return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
7437 };
7438
7439 warnForTextDifference = function (serverText, clientText) {
7440 if (didWarnInvalidHydration) {
7441 return;
7442 }
7443 var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
7444 var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
7445 if (normalizedServerText === normalizedClientText) {
7446 return;
7447 }
7448 didWarnInvalidHydration = true;
7449 warningWithoutStack$1(false, 'Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
7450 };
7451
7452 warnForPropDifference = function (propName, serverValue, clientValue) {
7453 if (didWarnInvalidHydration) {
7454 return;
7455 }
7456 var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
7457 var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
7458 if (normalizedServerValue === normalizedClientValue) {
7459 return;
7460 }
7461 didWarnInvalidHydration = true;
7462 warningWithoutStack$1(false, 'Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
7463 };
7464
7465 warnForExtraAttributes = function (attributeNames) {
7466 if (didWarnInvalidHydration) {
7467 return;
7468 }
7469 didWarnInvalidHydration = true;
7470 var names = [];
7471 attributeNames.forEach(function (name) {
7472 names.push(name);
7473 });
7474 warningWithoutStack$1(false, 'Extra attributes from the server: %s', names);
7475 };
7476
7477 warnForInvalidEventListener = function (registrationName, listener) {
7478 if (listener === false) {
7479 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);
7480 } else {
7481 warning$1(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
7482 }
7483 };
7484
7485 // Parse the HTML and read it back to normalize the HTML string so that it
7486 // can be used for comparison.
7487 normalizeHTML = function (parent, html) {
7488 // We could have created a separate document here to avoid
7489 // re-initializing custom elements if they exist. But this breaks
7490 // how <noscript> is being handled. So we use the same document.
7491 // See the discussion in https://github.com/facebook/react/pull/11157.
7492 var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
7493 testElement.innerHTML = html;
7494 return testElement.innerHTML;
7495 };
7496}
7497
7498function ensureListeningTo(rootContainerElement, registrationName) {
7499 var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;
7500 var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;
7501 listenTo(registrationName, doc);
7502}
7503
7504function getOwnerDocumentFromRootContainer(rootContainerElement) {
7505 return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
7506}
7507
7508function noop() {}
7509
7510function trapClickOnNonInteractiveElement(node) {
7511 // Mobile Safari does not fire properly bubble click events on
7512 // non-interactive elements, which means delegated click listeners do not
7513 // fire. The workaround for this bug involves attaching an empty click
7514 // listener on the target node.
7515 // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
7516 // Just set it using the onclick property so that we don't have to manage any
7517 // bookkeeping for it. Not sure if we need to clear it when the listener is
7518 // removed.
7519 // TODO: Only do this for the relevant Safaris maybe?
7520 node.onclick = noop;
7521}
7522
7523function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
7524 for (var propKey in nextProps) {
7525 if (!nextProps.hasOwnProperty(propKey)) {
7526 continue;
7527 }
7528 var nextProp = nextProps[propKey];
7529 if (propKey === STYLE$1) {
7530 {
7531 if (nextProp) {
7532 // Freeze the next style object so that we can assume it won't be
7533 // mutated. We have already warned for this in the past.
7534 Object.freeze(nextProp);
7535 }
7536 }
7537 // Relies on `updateStylesByID` not mutating `styleUpdates`.
7538 setValueForStyles(domElement, nextProp);
7539 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7540 var nextHtml = nextProp ? nextProp[HTML] : undefined;
7541 if (nextHtml != null) {
7542 setInnerHTML(domElement, nextHtml);
7543 }
7544 } else if (propKey === CHILDREN) {
7545 if (typeof nextProp === 'string') {
7546 // Avoid setting initial textContent when the text is empty. In IE11 setting
7547 // textContent on a <textarea> will cause the placeholder to not
7548 // show within the <textarea> until it has been focused and blurred again.
7549 // https://github.com/facebook/react/issues/6731#issuecomment-254874553
7550 var canSetTextContent = tag !== 'textarea' || nextProp !== '';
7551 if (canSetTextContent) {
7552 setTextContent(domElement, nextProp);
7553 }
7554 } else if (typeof nextProp === 'number') {
7555 setTextContent(domElement, '' + nextProp);
7556 }
7557 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
7558 // Noop
7559 } else if (propKey === AUTOFOCUS) {
7560 // We polyfill it separately on the client during commit.
7561 // We could have excluded it in the property list instead of
7562 // adding a special case here, but then it wouldn't be emitted
7563 // on server rendering (but we *do* want to emit it in SSR).
7564 } else if (registrationNameModules.hasOwnProperty(propKey)) {
7565 if (nextProp != null) {
7566 if (true && typeof nextProp !== 'function') {
7567 warnForInvalidEventListener(propKey, nextProp);
7568 }
7569 ensureListeningTo(rootContainerElement, propKey);
7570 }
7571 } else if (nextProp != null) {
7572 setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
7573 }
7574 }
7575}
7576
7577function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
7578 // TODO: Handle wasCustomComponentTag
7579 for (var i = 0; i < updatePayload.length; i += 2) {
7580 var propKey = updatePayload[i];
7581 var propValue = updatePayload[i + 1];
7582 if (propKey === STYLE$1) {
7583 setValueForStyles(domElement, propValue);
7584 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7585 setInnerHTML(domElement, propValue);
7586 } else if (propKey === CHILDREN) {
7587 setTextContent(domElement, propValue);
7588 } else {
7589 setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
7590 }
7591 }
7592}
7593
7594function createElement(type, props, rootContainerElement, parentNamespace) {
7595 var isCustomComponentTag = void 0;
7596
7597 // We create tags in the namespace of their parent container, except HTML
7598 // tags get no namespace.
7599 var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
7600 var domElement = void 0;
7601 var namespaceURI = parentNamespace;
7602 if (namespaceURI === HTML_NAMESPACE) {
7603 namespaceURI = getIntrinsicNamespace(type);
7604 }
7605 if (namespaceURI === HTML_NAMESPACE) {
7606 {
7607 isCustomComponentTag = isCustomComponent(type, props);
7608 // Should this check be gated by parent namespace? Not sure we want to
7609 // allow <SVG> or <mATH>.
7610 !(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;
7611 }
7612
7613 if (type === 'script') {
7614 // Create the script via .innerHTML so its "parser-inserted" flag is
7615 // set to true and it does not execute
7616 var div = ownerDocument.createElement('div');
7617 div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
7618 // This is guaranteed to yield a script element.
7619 var firstChild = div.firstChild;
7620 domElement = div.removeChild(firstChild);
7621 } else if (typeof props.is === 'string') {
7622 // $FlowIssue `createElement` should be updated for Web Components
7623 domElement = ownerDocument.createElement(type, { is: props.is });
7624 } else {
7625 // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
7626 // See discussion in https://github.com/facebook/react/pull/6896
7627 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
7628 domElement = ownerDocument.createElement(type);
7629 // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple`
7630 // attribute on `select`s needs to be added before `option`s are inserted. This prevents
7631 // a bug where the `select` does not scroll to the correct option because singular
7632 // `select` elements automatically pick the first item.
7633 // See https://github.com/facebook/react/issues/13222
7634 if (type === 'select' && props.multiple) {
7635 var node = domElement;
7636 node.multiple = true;
7637 }
7638 }
7639 } else {
7640 domElement = ownerDocument.createElementNS(namespaceURI, type);
7641 }
7642
7643 {
7644 if (namespaceURI === HTML_NAMESPACE) {
7645 if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {
7646 warnedUnknownTags[type] = true;
7647 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);
7648 }
7649 }
7650 }
7651
7652 return domElement;
7653}
7654
7655function createTextNode(text, rootContainerElement) {
7656 return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
7657}
7658
7659function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
7660 var isCustomComponentTag = isCustomComponent(tag, rawProps);
7661 {
7662 validatePropertiesInDevelopment(tag, rawProps);
7663 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
7664 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
7665 didWarnShadyDOM = true;
7666 }
7667 }
7668
7669 // TODO: Make sure that we check isMounted before firing any of these events.
7670 var props = void 0;
7671 switch (tag) {
7672 case 'iframe':
7673 case 'object':
7674 trapBubbledEvent(TOP_LOAD, domElement);
7675 props = rawProps;
7676 break;
7677 case 'video':
7678 case 'audio':
7679 // Create listener for each media event
7680 for (var i = 0; i < mediaEventTypes.length; i++) {
7681 trapBubbledEvent(mediaEventTypes[i], domElement);
7682 }
7683 props = rawProps;
7684 break;
7685 case 'source':
7686 trapBubbledEvent(TOP_ERROR, domElement);
7687 props = rawProps;
7688 break;
7689 case 'img':
7690 case 'image':
7691 case 'link':
7692 trapBubbledEvent(TOP_ERROR, domElement);
7693 trapBubbledEvent(TOP_LOAD, domElement);
7694 props = rawProps;
7695 break;
7696 case 'form':
7697 trapBubbledEvent(TOP_RESET, domElement);
7698 trapBubbledEvent(TOP_SUBMIT, domElement);
7699 props = rawProps;
7700 break;
7701 case 'details':
7702 trapBubbledEvent(TOP_TOGGLE, domElement);
7703 props = rawProps;
7704 break;
7705 case 'input':
7706 initWrapperState(domElement, rawProps);
7707 props = getHostProps(domElement, rawProps);
7708 trapBubbledEvent(TOP_INVALID, domElement);
7709 // For controlled components we always need to ensure we're listening
7710 // to onChange. Even if there is no listener.
7711 ensureListeningTo(rootContainerElement, 'onChange');
7712 break;
7713 case 'option':
7714 validateProps(domElement, rawProps);
7715 props = getHostProps$1(domElement, rawProps);
7716 break;
7717 case 'select':
7718 initWrapperState$1(domElement, rawProps);
7719 props = getHostProps$2(domElement, rawProps);
7720 trapBubbledEvent(TOP_INVALID, domElement);
7721 // For controlled components we always need to ensure we're listening
7722 // to onChange. Even if there is no listener.
7723 ensureListeningTo(rootContainerElement, 'onChange');
7724 break;
7725 case 'textarea':
7726 initWrapperState$2(domElement, rawProps);
7727 props = getHostProps$3(domElement, rawProps);
7728 trapBubbledEvent(TOP_INVALID, domElement);
7729 // For controlled components we always need to ensure we're listening
7730 // to onChange. Even if there is no listener.
7731 ensureListeningTo(rootContainerElement, 'onChange');
7732 break;
7733 default:
7734 props = rawProps;
7735 }
7736
7737 assertValidProps(tag, props);
7738
7739 setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
7740
7741 switch (tag) {
7742 case 'input':
7743 // TODO: Make sure we check if this is still unmounted or do any clean
7744 // up necessary since we never stop tracking anymore.
7745 track(domElement);
7746 postMountWrapper(domElement, rawProps, false);
7747 break;
7748 case 'textarea':
7749 // TODO: Make sure we check if this is still unmounted or do any clean
7750 // up necessary since we never stop tracking anymore.
7751 track(domElement);
7752 postMountWrapper$3(domElement, rawProps);
7753 break;
7754 case 'option':
7755 postMountWrapper$1(domElement, rawProps);
7756 break;
7757 case 'select':
7758 postMountWrapper$2(domElement, rawProps);
7759 break;
7760 default:
7761 if (typeof props.onClick === 'function') {
7762 // TODO: This cast may not be sound for SVG, MathML or custom elements.
7763 trapClickOnNonInteractiveElement(domElement);
7764 }
7765 break;
7766 }
7767}
7768
7769// Calculate the diff between the two objects.
7770function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
7771 {
7772 validatePropertiesInDevelopment(tag, nextRawProps);
7773 }
7774
7775 var updatePayload = null;
7776
7777 var lastProps = void 0;
7778 var nextProps = void 0;
7779 switch (tag) {
7780 case 'input':
7781 lastProps = getHostProps(domElement, lastRawProps);
7782 nextProps = getHostProps(domElement, nextRawProps);
7783 updatePayload = [];
7784 break;
7785 case 'option':
7786 lastProps = getHostProps$1(domElement, lastRawProps);
7787 nextProps = getHostProps$1(domElement, nextRawProps);
7788 updatePayload = [];
7789 break;
7790 case 'select':
7791 lastProps = getHostProps$2(domElement, lastRawProps);
7792 nextProps = getHostProps$2(domElement, nextRawProps);
7793 updatePayload = [];
7794 break;
7795 case 'textarea':
7796 lastProps = getHostProps$3(domElement, lastRawProps);
7797 nextProps = getHostProps$3(domElement, nextRawProps);
7798 updatePayload = [];
7799 break;
7800 default:
7801 lastProps = lastRawProps;
7802 nextProps = nextRawProps;
7803 if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
7804 // TODO: This cast may not be sound for SVG, MathML or custom elements.
7805 trapClickOnNonInteractiveElement(domElement);
7806 }
7807 break;
7808 }
7809
7810 assertValidProps(tag, nextProps);
7811
7812 var propKey = void 0;
7813 var styleName = void 0;
7814 var styleUpdates = null;
7815 for (propKey in lastProps) {
7816 if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
7817 continue;
7818 }
7819 if (propKey === STYLE$1) {
7820 var lastStyle = lastProps[propKey];
7821 for (styleName in lastStyle) {
7822 if (lastStyle.hasOwnProperty(styleName)) {
7823 if (!styleUpdates) {
7824 styleUpdates = {};
7825 }
7826 styleUpdates[styleName] = '';
7827 }
7828 }
7829 } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) {
7830 // Noop. This is handled by the clear text mechanism.
7831 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
7832 // Noop
7833 } else if (propKey === AUTOFOCUS) {
7834 // Noop. It doesn't work on updates anyway.
7835 } else if (registrationNameModules.hasOwnProperty(propKey)) {
7836 // This is a special case. If any listener updates we need to ensure
7837 // that the "current" fiber pointer gets updated so we need a commit
7838 // to update this element.
7839 if (!updatePayload) {
7840 updatePayload = [];
7841 }
7842 } else {
7843 // For all other deleted properties we add it to the queue. We use
7844 // the whitelist in the commit phase instead.
7845 (updatePayload = updatePayload || []).push(propKey, null);
7846 }
7847 }
7848 for (propKey in nextProps) {
7849 var nextProp = nextProps[propKey];
7850 var lastProp = lastProps != null ? lastProps[propKey] : undefined;
7851 if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
7852 continue;
7853 }
7854 if (propKey === STYLE$1) {
7855 {
7856 if (nextProp) {
7857 // Freeze the next style object so that we can assume it won't be
7858 // mutated. We have already warned for this in the past.
7859 Object.freeze(nextProp);
7860 }
7861 }
7862 if (lastProp) {
7863 // Unset styles on `lastProp` but not on `nextProp`.
7864 for (styleName in lastProp) {
7865 if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
7866 if (!styleUpdates) {
7867 styleUpdates = {};
7868 }
7869 styleUpdates[styleName] = '';
7870 }
7871 }
7872 // Update styles that changed since `lastProp`.
7873 for (styleName in nextProp) {
7874 if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
7875 if (!styleUpdates) {
7876 styleUpdates = {};
7877 }
7878 styleUpdates[styleName] = nextProp[styleName];
7879 }
7880 }
7881 } else {
7882 // Relies on `updateStylesByID` not mutating `styleUpdates`.
7883 if (!styleUpdates) {
7884 if (!updatePayload) {
7885 updatePayload = [];
7886 }
7887 updatePayload.push(propKey, styleUpdates);
7888 }
7889 styleUpdates = nextProp;
7890 }
7891 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7892 var nextHtml = nextProp ? nextProp[HTML] : undefined;
7893 var lastHtml = lastProp ? lastProp[HTML] : undefined;
7894 if (nextHtml != null) {
7895 if (lastHtml !== nextHtml) {
7896 (updatePayload = updatePayload || []).push(propKey, '' + nextHtml);
7897 }
7898 } else {
7899 // TODO: It might be too late to clear this if we have children
7900 // inserted already.
7901 }
7902 } else if (propKey === CHILDREN) {
7903 if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {
7904 (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
7905 }
7906 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
7907 // Noop
7908 } else if (registrationNameModules.hasOwnProperty(propKey)) {
7909 if (nextProp != null) {
7910 // We eagerly listen to this even though we haven't committed yet.
7911 if (true && typeof nextProp !== 'function') {
7912 warnForInvalidEventListener(propKey, nextProp);
7913 }
7914 ensureListeningTo(rootContainerElement, propKey);
7915 }
7916 if (!updatePayload && lastProp !== nextProp) {
7917 // This is a special case. If any listener updates we need to ensure
7918 // that the "current" props pointer gets updated so we need a commit
7919 // to update this element.
7920 updatePayload = [];
7921 }
7922 } else {
7923 // For any other property we always add it to the queue and then we
7924 // filter it out using the whitelist during the commit.
7925 (updatePayload = updatePayload || []).push(propKey, nextProp);
7926 }
7927 }
7928 if (styleUpdates) {
7929 {
7930 validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE$1]);
7931 }
7932 (updatePayload = updatePayload || []).push(STYLE$1, styleUpdates);
7933 }
7934 return updatePayload;
7935}
7936
7937// Apply the diff.
7938function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
7939 // Update checked *before* name.
7940 // In the middle of an update, it is possible to have multiple checked.
7941 // When a checked radio tries to change name, browser makes another radio's checked false.
7942 if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
7943 updateChecked(domElement, nextRawProps);
7944 }
7945
7946 var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
7947 var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
7948 // Apply the diff.
7949 updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag);
7950
7951 // TODO: Ensure that an update gets scheduled if any of the special props
7952 // changed.
7953 switch (tag) {
7954 case 'input':
7955 // Update the wrapper around inputs *after* updating props. This has to
7956 // happen after `updateDOMProperties`. Otherwise HTML5 input validations
7957 // raise warnings and prevent the new value from being assigned.
7958 updateWrapper(domElement, nextRawProps);
7959 break;
7960 case 'textarea':
7961 updateWrapper$1(domElement, nextRawProps);
7962 break;
7963 case 'select':
7964 // <select> value update needs to occur after <option> children
7965 // reconciliation
7966 postUpdateWrapper(domElement, nextRawProps);
7967 break;
7968 }
7969}
7970
7971function getPossibleStandardName(propName) {
7972 {
7973 var lowerCasedName = propName.toLowerCase();
7974 if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
7975 return null;
7976 }
7977 return possibleStandardNames[lowerCasedName] || null;
7978 }
7979 return null;
7980}
7981
7982function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {
7983 var isCustomComponentTag = void 0;
7984 var extraAttributeNames = void 0;
7985
7986 {
7987 suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING$1] === true;
7988 isCustomComponentTag = isCustomComponent(tag, rawProps);
7989 validatePropertiesInDevelopment(tag, rawProps);
7990 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
7991 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
7992 didWarnShadyDOM = true;
7993 }
7994 }
7995
7996 // TODO: Make sure that we check isMounted before firing any of these events.
7997 switch (tag) {
7998 case 'iframe':
7999 case 'object':
8000 trapBubbledEvent(TOP_LOAD, domElement);
8001 break;
8002 case 'video':
8003 case 'audio':
8004 // Create listener for each media event
8005 for (var i = 0; i < mediaEventTypes.length; i++) {
8006 trapBubbledEvent(mediaEventTypes[i], domElement);
8007 }
8008 break;
8009 case 'source':
8010 trapBubbledEvent(TOP_ERROR, domElement);
8011 break;
8012 case 'img':
8013 case 'image':
8014 case 'link':
8015 trapBubbledEvent(TOP_ERROR, domElement);
8016 trapBubbledEvent(TOP_LOAD, domElement);
8017 break;
8018 case 'form':
8019 trapBubbledEvent(TOP_RESET, domElement);
8020 trapBubbledEvent(TOP_SUBMIT, domElement);
8021 break;
8022 case 'details':
8023 trapBubbledEvent(TOP_TOGGLE, domElement);
8024 break;
8025 case 'input':
8026 initWrapperState(domElement, rawProps);
8027 trapBubbledEvent(TOP_INVALID, domElement);
8028 // For controlled components we always need to ensure we're listening
8029 // to onChange. Even if there is no listener.
8030 ensureListeningTo(rootContainerElement, 'onChange');
8031 break;
8032 case 'option':
8033 validateProps(domElement, rawProps);
8034 break;
8035 case 'select':
8036 initWrapperState$1(domElement, rawProps);
8037 trapBubbledEvent(TOP_INVALID, domElement);
8038 // For controlled components we always need to ensure we're listening
8039 // to onChange. Even if there is no listener.
8040 ensureListeningTo(rootContainerElement, 'onChange');
8041 break;
8042 case 'textarea':
8043 initWrapperState$2(domElement, rawProps);
8044 trapBubbledEvent(TOP_INVALID, domElement);
8045 // For controlled components we always need to ensure we're listening
8046 // to onChange. Even if there is no listener.
8047 ensureListeningTo(rootContainerElement, 'onChange');
8048 break;
8049 }
8050
8051 assertValidProps(tag, rawProps);
8052
8053 {
8054 extraAttributeNames = new Set();
8055 var attributes = domElement.attributes;
8056 for (var _i = 0; _i < attributes.length; _i++) {
8057 var name = attributes[_i].name.toLowerCase();
8058 switch (name) {
8059 // Built-in SSR attribute is whitelisted
8060 case 'data-reactroot':
8061 break;
8062 // Controlled attributes are not validated
8063 // TODO: Only ignore them on controlled tags.
8064 case 'value':
8065 break;
8066 case 'checked':
8067 break;
8068 case 'selected':
8069 break;
8070 default:
8071 // Intentionally use the original name.
8072 // See discussion in https://github.com/facebook/react/pull/10676.
8073 extraAttributeNames.add(attributes[_i].name);
8074 }
8075 }
8076 }
8077
8078 var updatePayload = null;
8079 for (var propKey in rawProps) {
8080 if (!rawProps.hasOwnProperty(propKey)) {
8081 continue;
8082 }
8083 var nextProp = rawProps[propKey];
8084 if (propKey === CHILDREN) {
8085 // For text content children we compare against textContent. This
8086 // might match additional HTML that is hidden when we read it using
8087 // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
8088 // satisfies our requirement. Our requirement is not to produce perfect
8089 // HTML and attributes. Ideally we should preserve structure but it's
8090 // ok not to if the visible content is still enough to indicate what
8091 // even listeners these nodes might be wired up to.
8092 // TODO: Warn if there is more than a single textNode as a child.
8093 // TODO: Should we use domElement.firstChild.nodeValue to compare?
8094 if (typeof nextProp === 'string') {
8095 if (domElement.textContent !== nextProp) {
8096 if (true && !suppressHydrationWarning) {
8097 warnForTextDifference(domElement.textContent, nextProp);
8098 }
8099 updatePayload = [CHILDREN, nextProp];
8100 }
8101 } else if (typeof nextProp === 'number') {
8102 if (domElement.textContent !== '' + nextProp) {
8103 if (true && !suppressHydrationWarning) {
8104 warnForTextDifference(domElement.textContent, nextProp);
8105 }
8106 updatePayload = [CHILDREN, '' + nextProp];
8107 }
8108 }
8109 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8110 if (nextProp != null) {
8111 if (true && typeof nextProp !== 'function') {
8112 warnForInvalidEventListener(propKey, nextProp);
8113 }
8114 ensureListeningTo(rootContainerElement, propKey);
8115 }
8116 } else if (true &&
8117 // Convince Flow we've calculated it (it's DEV-only in this method.)
8118 typeof isCustomComponentTag === 'boolean') {
8119 // Validate that the properties correspond to their expected values.
8120 var serverValue = void 0;
8121 var propertyInfo = getPropertyInfo(propKey);
8122 if (suppressHydrationWarning) {
8123 // Don't bother comparing. We're ignoring all these warnings.
8124 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1 ||
8125 // Controlled attributes are not validated
8126 // TODO: Only ignore them on controlled tags.
8127 propKey === 'value' || propKey === 'checked' || propKey === 'selected') {
8128 // Noop
8129 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8130 var serverHTML = domElement.innerHTML;
8131 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8132 var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : '');
8133 if (expectedHTML !== serverHTML) {
8134 warnForPropDifference(propKey, serverHTML, expectedHTML);
8135 }
8136 } else if (propKey === STYLE$1) {
8137 // $FlowFixMe - Should be inferred as not undefined.
8138 extraAttributeNames.delete(propKey);
8139
8140 if (canDiffStyleForHydrationWarning) {
8141 var expectedStyle = createDangerousStringForStyles(nextProp);
8142 serverValue = domElement.getAttribute('style');
8143 if (expectedStyle !== serverValue) {
8144 warnForPropDifference(propKey, serverValue, expectedStyle);
8145 }
8146 }
8147 } else if (isCustomComponentTag) {
8148 // $FlowFixMe - Should be inferred as not undefined.
8149 extraAttributeNames.delete(propKey.toLowerCase());
8150 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8151
8152 if (nextProp !== serverValue) {
8153 warnForPropDifference(propKey, serverValue, nextProp);
8154 }
8155 } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
8156 var isMismatchDueToBadCasing = false;
8157 if (propertyInfo !== null) {
8158 // $FlowFixMe - Should be inferred as not undefined.
8159 extraAttributeNames.delete(propertyInfo.attributeName);
8160 serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
8161 } else {
8162 var ownNamespace = parentNamespace;
8163 if (ownNamespace === HTML_NAMESPACE) {
8164 ownNamespace = getIntrinsicNamespace(tag);
8165 }
8166 if (ownNamespace === HTML_NAMESPACE) {
8167 // $FlowFixMe - Should be inferred as not undefined.
8168 extraAttributeNames.delete(propKey.toLowerCase());
8169 } else {
8170 var standardName = getPossibleStandardName(propKey);
8171 if (standardName !== null && standardName !== propKey) {
8172 // If an SVG prop is supplied with bad casing, it will
8173 // be successfully parsed from HTML, but will produce a mismatch
8174 // (and would be incorrectly rendered on the client).
8175 // However, we already warn about bad casing elsewhere.
8176 // So we'll skip the misleading extra mismatch warning in this case.
8177 isMismatchDueToBadCasing = true;
8178 // $FlowFixMe - Should be inferred as not undefined.
8179 extraAttributeNames.delete(standardName);
8180 }
8181 // $FlowFixMe - Should be inferred as not undefined.
8182 extraAttributeNames.delete(propKey);
8183 }
8184 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8185 }
8186
8187 if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
8188 warnForPropDifference(propKey, serverValue, nextProp);
8189 }
8190 }
8191 }
8192 }
8193
8194 {
8195 // $FlowFixMe - Should be inferred as not undefined.
8196 if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
8197 // $FlowFixMe - Should be inferred as not undefined.
8198 warnForExtraAttributes(extraAttributeNames);
8199 }
8200 }
8201
8202 switch (tag) {
8203 case 'input':
8204 // TODO: Make sure we check if this is still unmounted or do any clean
8205 // up necessary since we never stop tracking anymore.
8206 track(domElement);
8207 postMountWrapper(domElement, rawProps, true);
8208 break;
8209 case 'textarea':
8210 // TODO: Make sure we check if this is still unmounted or do any clean
8211 // up necessary since we never stop tracking anymore.
8212 track(domElement);
8213 postMountWrapper$3(domElement, rawProps);
8214 break;
8215 case 'select':
8216 case 'option':
8217 // For input and textarea we current always set the value property at
8218 // post mount to force it to diverge from attributes. However, for
8219 // option and select we don't quite do the same thing and select
8220 // is not resilient to the DOM state changing so we don't do that here.
8221 // TODO: Consider not doing this for input and textarea.
8222 break;
8223 default:
8224 if (typeof rawProps.onClick === 'function') {
8225 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8226 trapClickOnNonInteractiveElement(domElement);
8227 }
8228 break;
8229 }
8230
8231 return updatePayload;
8232}
8233
8234function diffHydratedText(textNode, text) {
8235 var isDifferent = textNode.nodeValue !== text;
8236 return isDifferent;
8237}
8238
8239function warnForUnmatchedText(textNode, text) {
8240 {
8241 warnForTextDifference(textNode.nodeValue, text);
8242 }
8243}
8244
8245function warnForDeletedHydratableElement(parentNode, child) {
8246 {
8247 if (didWarnInvalidHydration) {
8248 return;
8249 }
8250 didWarnInvalidHydration = true;
8251 warningWithoutStack$1(false, 'Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
8252 }
8253}
8254
8255function warnForDeletedHydratableText(parentNode, child) {
8256 {
8257 if (didWarnInvalidHydration) {
8258 return;
8259 }
8260 didWarnInvalidHydration = true;
8261 warningWithoutStack$1(false, 'Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
8262 }
8263}
8264
8265function warnForInsertedHydratedElement(parentNode, tag, props) {
8266 {
8267 if (didWarnInvalidHydration) {
8268 return;
8269 }
8270 didWarnInvalidHydration = true;
8271 warningWithoutStack$1(false, 'Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
8272 }
8273}
8274
8275function warnForInsertedHydratedText(parentNode, text) {
8276 {
8277 if (text === '') {
8278 // We expect to insert empty text nodes since they're not represented in
8279 // the HTML.
8280 // TODO: Remove this special case if we can just avoid inserting empty
8281 // text nodes.
8282 return;
8283 }
8284 if (didWarnInvalidHydration) {
8285 return;
8286 }
8287 didWarnInvalidHydration = true;
8288 warningWithoutStack$1(false, 'Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
8289 }
8290}
8291
8292function restoreControlledState$1(domElement, tag, props) {
8293 switch (tag) {
8294 case 'input':
8295 restoreControlledState(domElement, props);
8296 return;
8297 case 'textarea':
8298 restoreControlledState$3(domElement, props);
8299 return;
8300 case 'select':
8301 restoreControlledState$2(domElement, props);
8302 return;
8303 }
8304}
8305
8306// TODO: direct imports like some-package/src/* are bad. Fix me.
8307var validateDOMNesting = function () {};
8308var updatedAncestorInfo = function () {};
8309
8310{
8311 // This validation code was written based on the HTML5 parsing spec:
8312 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
8313 //
8314 // Note: this does not catch all invalid nesting, nor does it try to (as it's
8315 // not clear what practical benefit doing so provides); instead, we warn only
8316 // for cases where the parser will give a parse tree differing from what React
8317 // intended. For example, <b><div></div></b> is invalid but we don't warn
8318 // because it still parses correctly; we do warn for other cases like nested
8319 // <p> tags where the beginning of the second element implicitly closes the
8320 // first, causing a confusing mess.
8321
8322 // https://html.spec.whatwg.org/multipage/syntax.html#special
8323 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'];
8324
8325 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
8326 var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template',
8327
8328 // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
8329 // TODO: Distinguish by namespace here -- for <title>, including it here
8330 // errs on the side of fewer warnings
8331 'foreignObject', 'desc', 'title'];
8332
8333 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
8334 var buttonScopeTags = inScopeTags.concat(['button']);
8335
8336 // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
8337 var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
8338
8339 var emptyAncestorInfo = {
8340 current: null,
8341
8342 formTag: null,
8343 aTagInScope: null,
8344 buttonTagInScope: null,
8345 nobrTagInScope: null,
8346 pTagInButtonScope: null,
8347
8348 listItemTagAutoclosing: null,
8349 dlItemTagAutoclosing: null
8350 };
8351
8352 updatedAncestorInfo = function (oldInfo, tag) {
8353 var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
8354 var info = { tag: tag };
8355
8356 if (inScopeTags.indexOf(tag) !== -1) {
8357 ancestorInfo.aTagInScope = null;
8358 ancestorInfo.buttonTagInScope = null;
8359 ancestorInfo.nobrTagInScope = null;
8360 }
8361 if (buttonScopeTags.indexOf(tag) !== -1) {
8362 ancestorInfo.pTagInButtonScope = null;
8363 }
8364
8365 // See rules for 'li', 'dd', 'dt' start tags in
8366 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
8367 if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
8368 ancestorInfo.listItemTagAutoclosing = null;
8369 ancestorInfo.dlItemTagAutoclosing = null;
8370 }
8371
8372 ancestorInfo.current = info;
8373
8374 if (tag === 'form') {
8375 ancestorInfo.formTag = info;
8376 }
8377 if (tag === 'a') {
8378 ancestorInfo.aTagInScope = info;
8379 }
8380 if (tag === 'button') {
8381 ancestorInfo.buttonTagInScope = info;
8382 }
8383 if (tag === 'nobr') {
8384 ancestorInfo.nobrTagInScope = info;
8385 }
8386 if (tag === 'p') {
8387 ancestorInfo.pTagInButtonScope = info;
8388 }
8389 if (tag === 'li') {
8390 ancestorInfo.listItemTagAutoclosing = info;
8391 }
8392 if (tag === 'dd' || tag === 'dt') {
8393 ancestorInfo.dlItemTagAutoclosing = info;
8394 }
8395
8396 return ancestorInfo;
8397 };
8398
8399 /**
8400 * Returns whether
8401 */
8402 var isTagValidWithParent = function (tag, parentTag) {
8403 // First, let's check if we're in an unusual parsing mode...
8404 switch (parentTag) {
8405 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
8406 case 'select':
8407 return tag === 'option' || tag === 'optgroup' || tag === '#text';
8408 case 'optgroup':
8409 return tag === 'option' || tag === '#text';
8410 // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
8411 // but
8412 case 'option':
8413 return tag === '#text';
8414 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
8415 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
8416 // No special behavior since these rules fall back to "in body" mode for
8417 // all except special table nodes which cause bad parsing behavior anyway.
8418
8419 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
8420 case 'tr':
8421 return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
8422 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
8423 case 'tbody':
8424 case 'thead':
8425 case 'tfoot':
8426 return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
8427 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
8428 case 'colgroup':
8429 return tag === 'col' || tag === 'template';
8430 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
8431 case 'table':
8432 return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
8433 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
8434 case 'head':
8435 return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
8436 // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
8437 case 'html':
8438 return tag === 'head' || tag === 'body';
8439 case '#document':
8440 return tag === 'html';
8441 }
8442
8443 // Probably in the "in body" parsing mode, so we outlaw only tag combos
8444 // where the parsing rules cause implicit opens or closes to be added.
8445 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
8446 switch (tag) {
8447 case 'h1':
8448 case 'h2':
8449 case 'h3':
8450 case 'h4':
8451 case 'h5':
8452 case 'h6':
8453 return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
8454
8455 case 'rp':
8456 case 'rt':
8457 return impliedEndTags.indexOf(parentTag) === -1;
8458
8459 case 'body':
8460 case 'caption':
8461 case 'col':
8462 case 'colgroup':
8463 case 'frame':
8464 case 'head':
8465 case 'html':
8466 case 'tbody':
8467 case 'td':
8468 case 'tfoot':
8469 case 'th':
8470 case 'thead':
8471 case 'tr':
8472 // These tags are only valid with a few parents that have special child
8473 // parsing rules -- if we're down here, then none of those matched and
8474 // so we allow it only if we don't know what the parent is, as all other
8475 // cases are invalid.
8476 return parentTag == null;
8477 }
8478
8479 return true;
8480 };
8481
8482 /**
8483 * Returns whether
8484 */
8485 var findInvalidAncestorForTag = function (tag, ancestorInfo) {
8486 switch (tag) {
8487 case 'address':
8488 case 'article':
8489 case 'aside':
8490 case 'blockquote':
8491 case 'center':
8492 case 'details':
8493 case 'dialog':
8494 case 'dir':
8495 case 'div':
8496 case 'dl':
8497 case 'fieldset':
8498 case 'figcaption':
8499 case 'figure':
8500 case 'footer':
8501 case 'header':
8502 case 'hgroup':
8503 case 'main':
8504 case 'menu':
8505 case 'nav':
8506 case 'ol':
8507 case 'p':
8508 case 'section':
8509 case 'summary':
8510 case 'ul':
8511 case 'pre':
8512 case 'listing':
8513 case 'table':
8514 case 'hr':
8515 case 'xmp':
8516 case 'h1':
8517 case 'h2':
8518 case 'h3':
8519 case 'h4':
8520 case 'h5':
8521 case 'h6':
8522 return ancestorInfo.pTagInButtonScope;
8523
8524 case 'form':
8525 return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
8526
8527 case 'li':
8528 return ancestorInfo.listItemTagAutoclosing;
8529
8530 case 'dd':
8531 case 'dt':
8532 return ancestorInfo.dlItemTagAutoclosing;
8533
8534 case 'button':
8535 return ancestorInfo.buttonTagInScope;
8536
8537 case 'a':
8538 // Spec says something about storing a list of markers, but it sounds
8539 // equivalent to this check.
8540 return ancestorInfo.aTagInScope;
8541
8542 case 'nobr':
8543 return ancestorInfo.nobrTagInScope;
8544 }
8545
8546 return null;
8547 };
8548
8549 var didWarn = {};
8550
8551 validateDOMNesting = function (childTag, childText, ancestorInfo) {
8552 ancestorInfo = ancestorInfo || emptyAncestorInfo;
8553 var parentInfo = ancestorInfo.current;
8554 var parentTag = parentInfo && parentInfo.tag;
8555
8556 if (childText != null) {
8557 !(childTag == null) ? warningWithoutStack$1(false, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0;
8558 childTag = '#text';
8559 }
8560
8561 var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
8562 var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
8563 var invalidParentOrAncestor = invalidParent || invalidAncestor;
8564 if (!invalidParentOrAncestor) {
8565 return;
8566 }
8567
8568 var ancestorTag = invalidParentOrAncestor.tag;
8569 var addendum = getCurrentFiberStackInDev();
8570
8571 var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;
8572 if (didWarn[warnKey]) {
8573 return;
8574 }
8575 didWarn[warnKey] = true;
8576
8577 var tagDisplayName = childTag;
8578 var whitespaceInfo = '';
8579 if (childTag === '#text') {
8580 if (/\S/.test(childText)) {
8581 tagDisplayName = 'Text nodes';
8582 } else {
8583 tagDisplayName = 'Whitespace text nodes';
8584 whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
8585 }
8586 } else {
8587 tagDisplayName = '<' + childTag + '>';
8588 }
8589
8590 if (invalidParent) {
8591 var info = '';
8592 if (ancestorTag === 'table' && childTag === 'tr') {
8593 info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.';
8594 }
8595 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info, addendum);
8596 } else {
8597 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.%s', tagDisplayName, ancestorTag, addendum);
8598 }
8599 };
8600}
8601
8602// Renderers that don't support persistence
8603// can re-export everything from this module.
8604
8605function shim() {
8606 invariant(false, 'The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.');
8607}
8608
8609// Persistence (when unsupported)
8610var supportsPersistence = false;
8611var cloneInstance = shim;
8612var createContainerChildSet = shim;
8613var appendChildToContainerChildSet = shim;
8614var finalizeContainerChildren = shim;
8615var replaceContainerChildren = shim;
8616var cloneHiddenInstance = shim;
8617var cloneUnhiddenInstance = shim;
8618var createHiddenTextInstance = shim;
8619
8620var SUPPRESS_HYDRATION_WARNING = void 0;
8621{
8622 SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
8623}
8624
8625var STYLE = 'style';
8626
8627var eventsEnabled = null;
8628var selectionInformation = null;
8629
8630function shouldAutoFocusHostComponent(type, props) {
8631 switch (type) {
8632 case 'button':
8633 case 'input':
8634 case 'select':
8635 case 'textarea':
8636 return !!props.autoFocus;
8637 }
8638 return false;
8639}
8640
8641function getRootHostContext(rootContainerInstance) {
8642 var type = void 0;
8643 var namespace = void 0;
8644 var nodeType = rootContainerInstance.nodeType;
8645 switch (nodeType) {
8646 case DOCUMENT_NODE:
8647 case DOCUMENT_FRAGMENT_NODE:
8648 {
8649 type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
8650 var root = rootContainerInstance.documentElement;
8651 namespace = root ? root.namespaceURI : getChildNamespace(null, '');
8652 break;
8653 }
8654 default:
8655 {
8656 var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
8657 var ownNamespace = container.namespaceURI || null;
8658 type = container.tagName;
8659 namespace = getChildNamespace(ownNamespace, type);
8660 break;
8661 }
8662 }
8663 {
8664 var validatedTag = type.toLowerCase();
8665 var _ancestorInfo = updatedAncestorInfo(null, validatedTag);
8666 return { namespace: namespace, ancestorInfo: _ancestorInfo };
8667 }
8668 return namespace;
8669}
8670
8671function getChildHostContext(parentHostContext, type, rootContainerInstance) {
8672 {
8673 var parentHostContextDev = parentHostContext;
8674 var _namespace = getChildNamespace(parentHostContextDev.namespace, type);
8675 var _ancestorInfo2 = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
8676 return { namespace: _namespace, ancestorInfo: _ancestorInfo2 };
8677 }
8678 var parentNamespace = parentHostContext;
8679 return getChildNamespace(parentNamespace, type);
8680}
8681
8682function getPublicInstance(instance) {
8683 return instance;
8684}
8685
8686function prepareForCommit(containerInfo) {
8687 eventsEnabled = isEnabled();
8688 selectionInformation = getSelectionInformation();
8689 setEnabled(false);
8690}
8691
8692function resetAfterCommit(containerInfo) {
8693 restoreSelection(selectionInformation);
8694 selectionInformation = null;
8695 setEnabled(eventsEnabled);
8696 eventsEnabled = null;
8697}
8698
8699function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
8700 var parentNamespace = void 0;
8701 {
8702 // TODO: take namespace into account when validating.
8703 var hostContextDev = hostContext;
8704 validateDOMNesting(type, null, hostContextDev.ancestorInfo);
8705 if (typeof props.children === 'string' || typeof props.children === 'number') {
8706 var string = '' + props.children;
8707 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
8708 validateDOMNesting(null, string, ownAncestorInfo);
8709 }
8710 parentNamespace = hostContextDev.namespace;
8711 }
8712 var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
8713 precacheFiberNode(internalInstanceHandle, domElement);
8714 updateFiberProps(domElement, props);
8715 return domElement;
8716}
8717
8718function appendInitialChild(parentInstance, child) {
8719 parentInstance.appendChild(child);
8720}
8721
8722function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
8723 setInitialProperties(domElement, type, props, rootContainerInstance);
8724 return shouldAutoFocusHostComponent(type, props);
8725}
8726
8727function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
8728 {
8729 var hostContextDev = hostContext;
8730 if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
8731 var string = '' + newProps.children;
8732 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
8733 validateDOMNesting(null, string, ownAncestorInfo);
8734 }
8735 }
8736 return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);
8737}
8738
8739function shouldSetTextContent(type, props) {
8740 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;
8741}
8742
8743function shouldDeprioritizeSubtree(type, props) {
8744 return !!props.hidden;
8745}
8746
8747function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
8748 {
8749 var hostContextDev = hostContext;
8750 validateDOMNesting(null, text, hostContextDev.ancestorInfo);
8751 }
8752 var textNode = createTextNode(text, rootContainerInstance);
8753 precacheFiberNode(internalInstanceHandle, textNode);
8754 return textNode;
8755}
8756
8757var isPrimaryRenderer = true;
8758// This initialization code may run even on server environments
8759// if a component just imports ReactDOM (e.g. for findDOMNode).
8760// Some environments might not have setTimeout or clearTimeout.
8761var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
8762var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
8763var noTimeout = -1;
8764var schedulePassiveEffects = scheduler.unstable_scheduleCallback;
8765var cancelPassiveEffects = scheduler.unstable_cancelCallback;
8766
8767// -------------------
8768// Mutation
8769// -------------------
8770
8771var supportsMutation = true;
8772
8773function commitMount(domElement, type, newProps, internalInstanceHandle) {
8774 // Despite the naming that might imply otherwise, this method only
8775 // fires if there is an `Update` effect scheduled during mounting.
8776 // This happens if `finalizeInitialChildren` returns `true` (which it
8777 // does to implement the `autoFocus` attribute on the client). But
8778 // there are also other cases when this might happen (such as patching
8779 // up text content during hydration mismatch). So we'll check this again.
8780 if (shouldAutoFocusHostComponent(type, newProps)) {
8781 domElement.focus();
8782 }
8783}
8784
8785function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
8786 // Update the props handle so that we know which props are the ones with
8787 // with current event handlers.
8788 updateFiberProps(domElement, newProps);
8789 // Apply the diff to the DOM node.
8790 updateProperties(domElement, updatePayload, type, oldProps, newProps);
8791}
8792
8793function resetTextContent(domElement) {
8794 setTextContent(domElement, '');
8795}
8796
8797function commitTextUpdate(textInstance, oldText, newText) {
8798 textInstance.nodeValue = newText;
8799}
8800
8801function appendChild(parentInstance, child) {
8802 parentInstance.appendChild(child);
8803}
8804
8805function appendChildToContainer(container, child) {
8806 var parentNode = void 0;
8807 if (container.nodeType === COMMENT_NODE) {
8808 parentNode = container.parentNode;
8809 parentNode.insertBefore(child, container);
8810 } else {
8811 parentNode = container;
8812 parentNode.appendChild(child);
8813 }
8814 // This container might be used for a portal.
8815 // If something inside a portal is clicked, that click should bubble
8816 // through the React tree. However, on Mobile Safari the click would
8817 // never bubble through the *DOM* tree unless an ancestor with onclick
8818 // event exists. So we wouldn't see it and dispatch it.
8819 // This is why we ensure that non React root containers have inline onclick
8820 // defined.
8821 // https://github.com/facebook/react/issues/11918
8822 var reactRootContainer = container._reactRootContainer;
8823 if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
8824 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8825 trapClickOnNonInteractiveElement(parentNode);
8826 }
8827}
8828
8829function insertBefore(parentInstance, child, beforeChild) {
8830 parentInstance.insertBefore(child, beforeChild);
8831}
8832
8833function insertInContainerBefore(container, child, beforeChild) {
8834 if (container.nodeType === COMMENT_NODE) {
8835 container.parentNode.insertBefore(child, beforeChild);
8836 } else {
8837 container.insertBefore(child, beforeChild);
8838 }
8839}
8840
8841function removeChild(parentInstance, child) {
8842 parentInstance.removeChild(child);
8843}
8844
8845function removeChildFromContainer(container, child) {
8846 if (container.nodeType === COMMENT_NODE) {
8847 container.parentNode.removeChild(child);
8848 } else {
8849 container.removeChild(child);
8850 }
8851}
8852
8853function hideInstance(instance) {
8854 // TODO: Does this work for all element types? What about MathML? Should we
8855 // pass host context to this method?
8856 instance = instance;
8857 instance.style.display = 'none';
8858}
8859
8860function hideTextInstance(textInstance) {
8861 textInstance.nodeValue = '';
8862}
8863
8864function unhideInstance(instance, props) {
8865 instance = instance;
8866 var styleProp = props[STYLE];
8867 var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
8868 instance.style.display = dangerousStyleValue('display', display);
8869}
8870
8871function unhideTextInstance(textInstance, text) {
8872 textInstance.nodeValue = text;
8873}
8874
8875// -------------------
8876// Hydration
8877// -------------------
8878
8879var supportsHydration = true;
8880
8881function canHydrateInstance(instance, type, props) {
8882 if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
8883 return null;
8884 }
8885 // This has now been refined to an element node.
8886 return instance;
8887}
8888
8889function canHydrateTextInstance(instance, text) {
8890 if (text === '' || instance.nodeType !== TEXT_NODE) {
8891 // Empty strings are not parsed by HTML so there won't be a correct match here.
8892 return null;
8893 }
8894 // This has now been refined to a text node.
8895 return instance;
8896}
8897
8898function getNextHydratableSibling(instance) {
8899 var node = instance.nextSibling;
8900 // Skip non-hydratable nodes.
8901 while (node && node.nodeType !== ELEMENT_NODE && node.nodeType !== TEXT_NODE) {
8902 node = node.nextSibling;
8903 }
8904 return node;
8905}
8906
8907function getFirstHydratableChild(parentInstance) {
8908 var next = parentInstance.firstChild;
8909 // Skip non-hydratable nodes.
8910 while (next && next.nodeType !== ELEMENT_NODE && next.nodeType !== TEXT_NODE) {
8911 next = next.nextSibling;
8912 }
8913 return next;
8914}
8915
8916function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
8917 precacheFiberNode(internalInstanceHandle, instance);
8918 // TODO: Possibly defer this until the commit phase where all the events
8919 // get attached.
8920 updateFiberProps(instance, props);
8921 var parentNamespace = void 0;
8922 {
8923 var hostContextDev = hostContext;
8924 parentNamespace = hostContextDev.namespace;
8925 }
8926 return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);
8927}
8928
8929function hydrateTextInstance(textInstance, text, internalInstanceHandle) {
8930 precacheFiberNode(internalInstanceHandle, textInstance);
8931 return diffHydratedText(textInstance, text);
8932}
8933
8934function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {
8935 {
8936 warnForUnmatchedText(textInstance, text);
8937 }
8938}
8939
8940function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {
8941 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
8942 warnForUnmatchedText(textInstance, text);
8943 }
8944}
8945
8946function didNotHydrateContainerInstance(parentContainer, instance) {
8947 {
8948 if (instance.nodeType === ELEMENT_NODE) {
8949 warnForDeletedHydratableElement(parentContainer, instance);
8950 } else {
8951 warnForDeletedHydratableText(parentContainer, instance);
8952 }
8953 }
8954}
8955
8956function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {
8957 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
8958 if (instance.nodeType === ELEMENT_NODE) {
8959 warnForDeletedHydratableElement(parentInstance, instance);
8960 } else {
8961 warnForDeletedHydratableText(parentInstance, instance);
8962 }
8963 }
8964}
8965
8966function didNotFindHydratableContainerInstance(parentContainer, type, props) {
8967 {
8968 warnForInsertedHydratedElement(parentContainer, type, props);
8969 }
8970}
8971
8972function didNotFindHydratableContainerTextInstance(parentContainer, text) {
8973 {
8974 warnForInsertedHydratedText(parentContainer, text);
8975 }
8976}
8977
8978function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {
8979 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
8980 warnForInsertedHydratedElement(parentInstance, type, props);
8981 }
8982}
8983
8984function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {
8985 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
8986 warnForInsertedHydratedText(parentInstance, text);
8987 }
8988}
8989
8990// Prefix measurements so that it's possible to filter them.
8991// Longer prefixes are hard to read in DevTools.
8992var reactEmoji = '\u269B';
8993var warningEmoji = '\u26D4';
8994var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function';
8995
8996// Keep track of current fiber so that we know the path to unwind on pause.
8997// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
8998var currentFiber = null;
8999// If we're in the middle of user code, which fiber and method is it?
9000// Reusing `currentFiber` would be confusing for this because user code fiber
9001// can change during commit phase too, but we don't need to unwind it (since
9002// lifecycles in the commit phase don't resemble a tree).
9003var currentPhase = null;
9004var currentPhaseFiber = null;
9005// Did lifecycle hook schedule an update? This is often a performance problem,
9006// so we will keep track of it, and include it in the report.
9007// Track commits caused by cascading updates.
9008var isCommitting = false;
9009var hasScheduledUpdateInCurrentCommit = false;
9010var hasScheduledUpdateInCurrentPhase = false;
9011var commitCountInCurrentWorkLoop = 0;
9012var effectCountInCurrentCommit = 0;
9013var isWaitingForCallback = false;
9014// During commits, we only show a measurement once per method name
9015// to avoid stretch the commit phase with measurement overhead.
9016var labelsInCurrentCommit = new Set();
9017
9018var formatMarkName = function (markName) {
9019 return reactEmoji + ' ' + markName;
9020};
9021
9022var formatLabel = function (label, warning) {
9023 var prefix = warning ? warningEmoji + ' ' : reactEmoji + ' ';
9024 var suffix = warning ? ' Warning: ' + warning : '';
9025 return '' + prefix + label + suffix;
9026};
9027
9028var beginMark = function (markName) {
9029 performance.mark(formatMarkName(markName));
9030};
9031
9032var clearMark = function (markName) {
9033 performance.clearMarks(formatMarkName(markName));
9034};
9035
9036var endMark = function (label, markName, warning) {
9037 var formattedMarkName = formatMarkName(markName);
9038 var formattedLabel = formatLabel(label, warning);
9039 try {
9040 performance.measure(formattedLabel, formattedMarkName);
9041 } catch (err) {}
9042 // If previous mark was missing for some reason, this will throw.
9043 // This could only happen if React crashed in an unexpected place earlier.
9044 // Don't pile on with more errors.
9045
9046 // Clear marks immediately to avoid growing buffer.
9047 performance.clearMarks(formattedMarkName);
9048 performance.clearMeasures(formattedLabel);
9049};
9050
9051var getFiberMarkName = function (label, debugID) {
9052 return label + ' (#' + debugID + ')';
9053};
9054
9055var getFiberLabel = function (componentName, isMounted, phase) {
9056 if (phase === null) {
9057 // These are composite component total time measurements.
9058 return componentName + ' [' + (isMounted ? 'update' : 'mount') + ']';
9059 } else {
9060 // Composite component methods.
9061 return componentName + '.' + phase;
9062 }
9063};
9064
9065var beginFiberMark = function (fiber, phase) {
9066 var componentName = getComponentName(fiber.type) || 'Unknown';
9067 var debugID = fiber._debugID;
9068 var isMounted = fiber.alternate !== null;
9069 var label = getFiberLabel(componentName, isMounted, phase);
9070
9071 if (isCommitting && labelsInCurrentCommit.has(label)) {
9072 // During the commit phase, we don't show duplicate labels because
9073 // there is a fixed overhead for every measurement, and we don't
9074 // want to stretch the commit phase beyond necessary.
9075 return false;
9076 }
9077 labelsInCurrentCommit.add(label);
9078
9079 var markName = getFiberMarkName(label, debugID);
9080 beginMark(markName);
9081 return true;
9082};
9083
9084var clearFiberMark = function (fiber, phase) {
9085 var componentName = getComponentName(fiber.type) || 'Unknown';
9086 var debugID = fiber._debugID;
9087 var isMounted = fiber.alternate !== null;
9088 var label = getFiberLabel(componentName, isMounted, phase);
9089 var markName = getFiberMarkName(label, debugID);
9090 clearMark(markName);
9091};
9092
9093var endFiberMark = function (fiber, phase, warning) {
9094 var componentName = getComponentName(fiber.type) || 'Unknown';
9095 var debugID = fiber._debugID;
9096 var isMounted = fiber.alternate !== null;
9097 var label = getFiberLabel(componentName, isMounted, phase);
9098 var markName = getFiberMarkName(label, debugID);
9099 endMark(label, markName, warning);
9100};
9101
9102var shouldIgnoreFiber = function (fiber) {
9103 // Host components should be skipped in the timeline.
9104 // We could check typeof fiber.type, but does this work with RN?
9105 switch (fiber.tag) {
9106 case HostRoot:
9107 case HostComponent:
9108 case HostText:
9109 case HostPortal:
9110 case Fragment:
9111 case ContextProvider:
9112 case ContextConsumer:
9113 case Mode:
9114 return true;
9115 default:
9116 return false;
9117 }
9118};
9119
9120var clearPendingPhaseMeasurement = function () {
9121 if (currentPhase !== null && currentPhaseFiber !== null) {
9122 clearFiberMark(currentPhaseFiber, currentPhase);
9123 }
9124 currentPhaseFiber = null;
9125 currentPhase = null;
9126 hasScheduledUpdateInCurrentPhase = false;
9127};
9128
9129var pauseTimers = function () {
9130 // Stops all currently active measurements so that they can be resumed
9131 // if we continue in a later deferred loop from the same unit of work.
9132 var fiber = currentFiber;
9133 while (fiber) {
9134 if (fiber._debugIsCurrentlyTiming) {
9135 endFiberMark(fiber, null, null);
9136 }
9137 fiber = fiber.return;
9138 }
9139};
9140
9141var resumeTimersRecursively = function (fiber) {
9142 if (fiber.return !== null) {
9143 resumeTimersRecursively(fiber.return);
9144 }
9145 if (fiber._debugIsCurrentlyTiming) {
9146 beginFiberMark(fiber, null);
9147 }
9148};
9149
9150var resumeTimers = function () {
9151 // Resumes all measurements that were active during the last deferred loop.
9152 if (currentFiber !== null) {
9153 resumeTimersRecursively(currentFiber);
9154 }
9155};
9156
9157function recordEffect() {
9158 if (enableUserTimingAPI) {
9159 effectCountInCurrentCommit++;
9160 }
9161}
9162
9163function recordScheduleUpdate() {
9164 if (enableUserTimingAPI) {
9165 if (isCommitting) {
9166 hasScheduledUpdateInCurrentCommit = true;
9167 }
9168 if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
9169 hasScheduledUpdateInCurrentPhase = true;
9170 }
9171 }
9172}
9173
9174function startRequestCallbackTimer() {
9175 if (enableUserTimingAPI) {
9176 if (supportsUserTiming && !isWaitingForCallback) {
9177 isWaitingForCallback = true;
9178 beginMark('(Waiting for async callback...)');
9179 }
9180 }
9181}
9182
9183function stopRequestCallbackTimer(didExpire, expirationTime) {
9184 if (enableUserTimingAPI) {
9185 if (supportsUserTiming) {
9186 isWaitingForCallback = false;
9187 var warning = didExpire ? 'React was blocked by main thread' : null;
9188 endMark('(Waiting for async callback... will force flush in ' + expirationTime + ' ms)', '(Waiting for async callback...)', warning);
9189 }
9190 }
9191}
9192
9193function startWorkTimer(fiber) {
9194 if (enableUserTimingAPI) {
9195 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9196 return;
9197 }
9198 // If we pause, this is the fiber to unwind from.
9199 currentFiber = fiber;
9200 if (!beginFiberMark(fiber, null)) {
9201 return;
9202 }
9203 fiber._debugIsCurrentlyTiming = true;
9204 }
9205}
9206
9207function cancelWorkTimer(fiber) {
9208 if (enableUserTimingAPI) {
9209 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9210 return;
9211 }
9212 // Remember we shouldn't complete measurement for this fiber.
9213 // Otherwise flamechart will be deep even for small updates.
9214 fiber._debugIsCurrentlyTiming = false;
9215 clearFiberMark(fiber, null);
9216 }
9217}
9218
9219function stopWorkTimer(fiber) {
9220 if (enableUserTimingAPI) {
9221 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9222 return;
9223 }
9224 // If we pause, its parent is the fiber to unwind from.
9225 currentFiber = fiber.return;
9226 if (!fiber._debugIsCurrentlyTiming) {
9227 return;
9228 }
9229 fiber._debugIsCurrentlyTiming = false;
9230 endFiberMark(fiber, null, null);
9231 }
9232}
9233
9234function stopFailedWorkTimer(fiber) {
9235 if (enableUserTimingAPI) {
9236 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
9237 return;
9238 }
9239 // If we pause, its parent is the fiber to unwind from.
9240 currentFiber = fiber.return;
9241 if (!fiber._debugIsCurrentlyTiming) {
9242 return;
9243 }
9244 fiber._debugIsCurrentlyTiming = false;
9245 var warning = fiber.tag === SuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
9246 endFiberMark(fiber, null, warning);
9247 }
9248}
9249
9250function startPhaseTimer(fiber, phase) {
9251 if (enableUserTimingAPI) {
9252 if (!supportsUserTiming) {
9253 return;
9254 }
9255 clearPendingPhaseMeasurement();
9256 if (!beginFiberMark(fiber, phase)) {
9257 return;
9258 }
9259 currentPhaseFiber = fiber;
9260 currentPhase = phase;
9261 }
9262}
9263
9264function stopPhaseTimer() {
9265 if (enableUserTimingAPI) {
9266 if (!supportsUserTiming) {
9267 return;
9268 }
9269 if (currentPhase !== null && currentPhaseFiber !== null) {
9270 var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
9271 endFiberMark(currentPhaseFiber, currentPhase, warning);
9272 }
9273 currentPhase = null;
9274 currentPhaseFiber = null;
9275 }
9276}
9277
9278function startWorkLoopTimer(nextUnitOfWork) {
9279 if (enableUserTimingAPI) {
9280 currentFiber = nextUnitOfWork;
9281 if (!supportsUserTiming) {
9282 return;
9283 }
9284 commitCountInCurrentWorkLoop = 0;
9285 // This is top level call.
9286 // Any other measurements are performed within.
9287 beginMark('(React Tree Reconciliation)');
9288 // Resume any measurements that were in progress during the last loop.
9289 resumeTimers();
9290 }
9291}
9292
9293function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
9294 if (enableUserTimingAPI) {
9295 if (!supportsUserTiming) {
9296 return;
9297 }
9298 var warning = null;
9299 if (interruptedBy !== null) {
9300 if (interruptedBy.tag === HostRoot) {
9301 warning = 'A top-level update interrupted the previous render';
9302 } else {
9303 var componentName = getComponentName(interruptedBy.type) || 'Unknown';
9304 warning = 'An update to ' + componentName + ' interrupted the previous render';
9305 }
9306 } else if (commitCountInCurrentWorkLoop > 1) {
9307 warning = 'There were cascading updates';
9308 }
9309 commitCountInCurrentWorkLoop = 0;
9310 var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)';
9311 // Pause any measurements until the next loop.
9312 pauseTimers();
9313 endMark(label, '(React Tree Reconciliation)', warning);
9314 }
9315}
9316
9317function startCommitTimer() {
9318 if (enableUserTimingAPI) {
9319 if (!supportsUserTiming) {
9320 return;
9321 }
9322 isCommitting = true;
9323 hasScheduledUpdateInCurrentCommit = false;
9324 labelsInCurrentCommit.clear();
9325 beginMark('(Committing Changes)');
9326 }
9327}
9328
9329function stopCommitTimer() {
9330 if (enableUserTimingAPI) {
9331 if (!supportsUserTiming) {
9332 return;
9333 }
9334
9335 var warning = null;
9336 if (hasScheduledUpdateInCurrentCommit) {
9337 warning = 'Lifecycle hook scheduled a cascading update';
9338 } else if (commitCountInCurrentWorkLoop > 0) {
9339 warning = 'Caused by a cascading update in earlier commit';
9340 }
9341 hasScheduledUpdateInCurrentCommit = false;
9342 commitCountInCurrentWorkLoop++;
9343 isCommitting = false;
9344 labelsInCurrentCommit.clear();
9345
9346 endMark('(Committing Changes)', '(Committing Changes)', warning);
9347 }
9348}
9349
9350function startCommitSnapshotEffectsTimer() {
9351 if (enableUserTimingAPI) {
9352 if (!supportsUserTiming) {
9353 return;
9354 }
9355 effectCountInCurrentCommit = 0;
9356 beginMark('(Committing Snapshot Effects)');
9357 }
9358}
9359
9360function stopCommitSnapshotEffectsTimer() {
9361 if (enableUserTimingAPI) {
9362 if (!supportsUserTiming) {
9363 return;
9364 }
9365 var count = effectCountInCurrentCommit;
9366 effectCountInCurrentCommit = 0;
9367 endMark('(Committing Snapshot Effects: ' + count + ' Total)', '(Committing Snapshot Effects)', null);
9368 }
9369}
9370
9371function startCommitHostEffectsTimer() {
9372 if (enableUserTimingAPI) {
9373 if (!supportsUserTiming) {
9374 return;
9375 }
9376 effectCountInCurrentCommit = 0;
9377 beginMark('(Committing Host Effects)');
9378 }
9379}
9380
9381function stopCommitHostEffectsTimer() {
9382 if (enableUserTimingAPI) {
9383 if (!supportsUserTiming) {
9384 return;
9385 }
9386 var count = effectCountInCurrentCommit;
9387 effectCountInCurrentCommit = 0;
9388 endMark('(Committing Host Effects: ' + count + ' Total)', '(Committing Host Effects)', null);
9389 }
9390}
9391
9392function startCommitLifeCyclesTimer() {
9393 if (enableUserTimingAPI) {
9394 if (!supportsUserTiming) {
9395 return;
9396 }
9397 effectCountInCurrentCommit = 0;
9398 beginMark('(Calling Lifecycle Methods)');
9399 }
9400}
9401
9402function stopCommitLifeCyclesTimer() {
9403 if (enableUserTimingAPI) {
9404 if (!supportsUserTiming) {
9405 return;
9406 }
9407 var count = effectCountInCurrentCommit;
9408 effectCountInCurrentCommit = 0;
9409 endMark('(Calling Lifecycle Methods: ' + count + ' Total)', '(Calling Lifecycle Methods)', null);
9410 }
9411}
9412
9413var valueStack = [];
9414
9415var fiberStack = void 0;
9416
9417{
9418 fiberStack = [];
9419}
9420
9421var index = -1;
9422
9423function createCursor(defaultValue) {
9424 return {
9425 current: defaultValue
9426 };
9427}
9428
9429function pop(cursor, fiber) {
9430 if (index < 0) {
9431 {
9432 warningWithoutStack$1(false, 'Unexpected pop.');
9433 }
9434 return;
9435 }
9436
9437 {
9438 if (fiber !== fiberStack[index]) {
9439 warningWithoutStack$1(false, 'Unexpected Fiber popped.');
9440 }
9441 }
9442
9443 cursor.current = valueStack[index];
9444
9445 valueStack[index] = null;
9446
9447 {
9448 fiberStack[index] = null;
9449 }
9450
9451 index--;
9452}
9453
9454function push(cursor, value, fiber) {
9455 index++;
9456
9457 valueStack[index] = cursor.current;
9458
9459 {
9460 fiberStack[index] = fiber;
9461 }
9462
9463 cursor.current = value;
9464}
9465
9466function checkThatStackIsEmpty() {
9467 {
9468 if (index !== -1) {
9469 warningWithoutStack$1(false, 'Expected an empty stack. Something was not reset properly.');
9470 }
9471 }
9472}
9473
9474function resetStackAfterFatalErrorInDev() {
9475 {
9476 index = -1;
9477 valueStack.length = 0;
9478 fiberStack.length = 0;
9479 }
9480}
9481
9482var warnedAboutMissingGetChildContext = void 0;
9483
9484{
9485 warnedAboutMissingGetChildContext = {};
9486}
9487
9488var emptyContextObject = {};
9489{
9490 Object.freeze(emptyContextObject);
9491}
9492
9493// A cursor to the current merged context object on the stack.
9494var contextStackCursor = createCursor(emptyContextObject);
9495// A cursor to a boolean indicating whether the context has changed.
9496var didPerformWorkStackCursor = createCursor(false);
9497// Keep track of the previous context object that was on the stack.
9498// We use this to get access to the parent context after we have already
9499// pushed the next context provider, and now need to merge their contexts.
9500var previousContext = emptyContextObject;
9501
9502function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
9503 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
9504 // If the fiber is a context provider itself, when we read its context
9505 // we may have already pushed its own child context on the stack. A context
9506 // provider should not "see" its own child context. Therefore we read the
9507 // previous (parent) context instead for a context provider.
9508 return previousContext;
9509 }
9510 return contextStackCursor.current;
9511}
9512
9513function cacheContext(workInProgress, unmaskedContext, maskedContext) {
9514 var instance = workInProgress.stateNode;
9515 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
9516 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
9517}
9518
9519function getMaskedContext(workInProgress, unmaskedContext) {
9520 var type = workInProgress.type;
9521 var contextTypes = type.contextTypes;
9522 if (!contextTypes) {
9523 return emptyContextObject;
9524 }
9525
9526 // Avoid recreating masked context unless unmasked context has changed.
9527 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
9528 // This may trigger infinite loops if componentWillReceiveProps calls setState.
9529 var instance = workInProgress.stateNode;
9530 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
9531 return instance.__reactInternalMemoizedMaskedChildContext;
9532 }
9533
9534 var context = {};
9535 for (var key in contextTypes) {
9536 context[key] = unmaskedContext[key];
9537 }
9538
9539 {
9540 var name = getComponentName(type) || 'Unknown';
9541 checkPropTypes(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
9542 }
9543
9544 // Cache unmasked context so we can avoid recreating masked context unless necessary.
9545 // Context is created before the class component is instantiated so check for instance.
9546 if (instance) {
9547 cacheContext(workInProgress, unmaskedContext, context);
9548 }
9549
9550 return context;
9551}
9552
9553function hasContextChanged() {
9554 return didPerformWorkStackCursor.current;
9555}
9556
9557function isContextProvider(type) {
9558 var childContextTypes = type.childContextTypes;
9559 return childContextTypes !== null && childContextTypes !== undefined;
9560}
9561
9562function popContext(fiber) {
9563 pop(didPerformWorkStackCursor, fiber);
9564 pop(contextStackCursor, fiber);
9565}
9566
9567function popTopLevelContextObject(fiber) {
9568 pop(didPerformWorkStackCursor, fiber);
9569 pop(contextStackCursor, fiber);
9570}
9571
9572function pushTopLevelContextObject(fiber, context, didChange) {
9573 !(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;
9574
9575 push(contextStackCursor, context, fiber);
9576 push(didPerformWorkStackCursor, didChange, fiber);
9577}
9578
9579function processChildContext(fiber, type, parentContext) {
9580 var instance = fiber.stateNode;
9581 var childContextTypes = type.childContextTypes;
9582
9583 // TODO (bvaughn) Replace this behavior with an invariant() in the future.
9584 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
9585 if (typeof instance.getChildContext !== 'function') {
9586 {
9587 var componentName = getComponentName(type) || 'Unknown';
9588
9589 if (!warnedAboutMissingGetChildContext[componentName]) {
9590 warnedAboutMissingGetChildContext[componentName] = true;
9591 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);
9592 }
9593 }
9594 return parentContext;
9595 }
9596
9597 var childContext = void 0;
9598 {
9599 setCurrentPhase('getChildContext');
9600 }
9601 startPhaseTimer(fiber, 'getChildContext');
9602 childContext = instance.getChildContext();
9603 stopPhaseTimer();
9604 {
9605 setCurrentPhase(null);
9606 }
9607 for (var contextKey in childContext) {
9608 !(contextKey in childContextTypes) ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName(type) || 'Unknown', contextKey) : void 0;
9609 }
9610 {
9611 var name = getComponentName(type) || 'Unknown';
9612 checkPropTypes(childContextTypes, childContext, 'child context', name,
9613 // In practice, there is one case in which we won't get a stack. It's when
9614 // somebody calls unstable_renderSubtreeIntoContainer() and we process
9615 // context from the parent component instance. The stack will be missing
9616 // because it's outside of the reconciliation, and so the pointer has not
9617 // been set. This is rare and doesn't matter. We'll also remove that API.
9618 getCurrentFiberStackInDev);
9619 }
9620
9621 return _assign({}, parentContext, childContext);
9622}
9623
9624function pushContextProvider(workInProgress) {
9625 var instance = workInProgress.stateNode;
9626 // We push the context as early as possible to ensure stack integrity.
9627 // If the instance does not exist yet, we will push null at first,
9628 // and replace it on the stack later when invalidating the context.
9629 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject;
9630
9631 // Remember the parent context so we can merge with it later.
9632 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
9633 previousContext = contextStackCursor.current;
9634 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
9635 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
9636
9637 return true;
9638}
9639
9640function invalidateContextProvider(workInProgress, type, didChange) {
9641 var instance = workInProgress.stateNode;
9642 !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;
9643
9644 if (didChange) {
9645 // Merge parent and own context.
9646 // Skip this if we're not updating due to sCU.
9647 // This avoids unnecessarily recomputing memoized values.
9648 var mergedContext = processChildContext(workInProgress, type, previousContext);
9649 instance.__reactInternalMemoizedMergedChildContext = mergedContext;
9650
9651 // Replace the old (or empty) context with the new one.
9652 // It is important to unwind the context in the reverse order.
9653 pop(didPerformWorkStackCursor, workInProgress);
9654 pop(contextStackCursor, workInProgress);
9655 // Now push the new context and mark that it has changed.
9656 push(contextStackCursor, mergedContext, workInProgress);
9657 push(didPerformWorkStackCursor, didChange, workInProgress);
9658 } else {
9659 pop(didPerformWorkStackCursor, workInProgress);
9660 push(didPerformWorkStackCursor, didChange, workInProgress);
9661 }
9662}
9663
9664function findCurrentUnmaskedContext(fiber) {
9665 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
9666 // makes sense elsewhere
9667 !(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;
9668
9669 var node = fiber;
9670 do {
9671 switch (node.tag) {
9672 case HostRoot:
9673 return node.stateNode.context;
9674 case ClassComponent:
9675 {
9676 var Component = node.type;
9677 if (isContextProvider(Component)) {
9678 return node.stateNode.__reactInternalMemoizedMergedChildContext;
9679 }
9680 break;
9681 }
9682 }
9683 node = node.return;
9684 } while (node !== null);
9685 invariant(false, 'Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.');
9686}
9687
9688var onCommitFiberRoot = null;
9689var onCommitFiberUnmount = null;
9690var hasLoggedError = false;
9691
9692function catchErrors(fn) {
9693 return function (arg) {
9694 try {
9695 return fn(arg);
9696 } catch (err) {
9697 if (true && !hasLoggedError) {
9698 hasLoggedError = true;
9699 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
9700 }
9701 }
9702 };
9703}
9704
9705var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
9706
9707function injectInternals(internals) {
9708 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
9709 // No DevTools
9710 return false;
9711 }
9712 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
9713 if (hook.isDisabled) {
9714 // This isn't a real property on the hook, but it can be set to opt out
9715 // of DevTools integration and associated warnings and logs.
9716 // https://github.com/facebook/react/issues/3877
9717 return true;
9718 }
9719 if (!hook.supportsFiber) {
9720 {
9721 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');
9722 }
9723 // DevTools exists, even though it doesn't support Fiber.
9724 return true;
9725 }
9726 try {
9727 var rendererID = hook.inject(internals);
9728 // We have successfully injected, so now it is safe to set up hooks.
9729 onCommitFiberRoot = catchErrors(function (root) {
9730 return hook.onCommitFiberRoot(rendererID, root);
9731 });
9732 onCommitFiberUnmount = catchErrors(function (fiber) {
9733 return hook.onCommitFiberUnmount(rendererID, fiber);
9734 });
9735 } catch (err) {
9736 // Catch all errors because it is unsafe to throw during initialization.
9737 {
9738 warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
9739 }
9740 }
9741 // DevTools exists
9742 return true;
9743}
9744
9745function onCommitRoot(root) {
9746 if (typeof onCommitFiberRoot === 'function') {
9747 onCommitFiberRoot(root);
9748 }
9749}
9750
9751function onCommitUnmount(fiber) {
9752 if (typeof onCommitFiberUnmount === 'function') {
9753 onCommitFiberUnmount(fiber);
9754 }
9755}
9756
9757// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
9758// Math.pow(2, 30) - 1
9759// 0b111111111111111111111111111111
9760var maxSigned31BitInt = 1073741823;
9761
9762var NoWork = 0;
9763var Never = 1;
9764var Sync = maxSigned31BitInt;
9765
9766var UNIT_SIZE = 10;
9767var MAGIC_NUMBER_OFFSET = maxSigned31BitInt - 1;
9768
9769// 1 unit of expiration time represents 10ms.
9770function msToExpirationTime(ms) {
9771 // Always add an offset so that we don't clash with the magic number for NoWork.
9772 return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
9773}
9774
9775function expirationTimeToMs(expirationTime) {
9776 return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
9777}
9778
9779function ceiling(num, precision) {
9780 return ((num / precision | 0) + 1) * precision;
9781}
9782
9783function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
9784 return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
9785}
9786
9787var LOW_PRIORITY_EXPIRATION = 5000;
9788var LOW_PRIORITY_BATCH_SIZE = 250;
9789
9790function computeAsyncExpiration(currentTime) {
9791 return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
9792}
9793
9794// We intentionally set a higher expiration time for interactive updates in
9795// dev than in production.
9796//
9797// If the main thread is being blocked so long that you hit the expiration,
9798// it's a problem that could be solved with better scheduling.
9799//
9800// People will be more likely to notice this and fix it with the long
9801// expiration time in development.
9802//
9803// In production we opt for better UX at the risk of masking scheduling
9804// problems, by expiring fast.
9805var HIGH_PRIORITY_EXPIRATION = 500;
9806var HIGH_PRIORITY_BATCH_SIZE = 100;
9807
9808function computeInteractiveExpiration(currentTime) {
9809 return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
9810}
9811
9812var NoContext = 0;
9813var ConcurrentMode = 1;
9814var StrictMode = 2;
9815var ProfileMode = 4;
9816
9817var hasBadMapPolyfill = void 0;
9818
9819{
9820 hasBadMapPolyfill = false;
9821 try {
9822 var nonExtensibleObject = Object.preventExtensions({});
9823 var testMap = new Map([[nonExtensibleObject, null]]);
9824 var testSet = new Set([nonExtensibleObject]);
9825 // This is necessary for Rollup to not consider these unused.
9826 // https://github.com/rollup/rollup/issues/1771
9827 // TODO: we can remove these if Rollup fixes the bug.
9828 testMap.set(0, 0);
9829 testSet.add(0);
9830 } catch (e) {
9831 // TODO: Consider warning about bad polyfills
9832 hasBadMapPolyfill = true;
9833 }
9834}
9835
9836// A Fiber is work on a Component that needs to be done or was done. There can
9837// be more than one per component.
9838
9839
9840var debugCounter = void 0;
9841
9842{
9843 debugCounter = 1;
9844}
9845
9846function FiberNode(tag, pendingProps, key, mode) {
9847 // Instance
9848 this.tag = tag;
9849 this.key = key;
9850 this.elementType = null;
9851 this.type = null;
9852 this.stateNode = null;
9853
9854 // Fiber
9855 this.return = null;
9856 this.child = null;
9857 this.sibling = null;
9858 this.index = 0;
9859
9860 this.ref = null;
9861
9862 this.pendingProps = pendingProps;
9863 this.memoizedProps = null;
9864 this.updateQueue = null;
9865 this.memoizedState = null;
9866 this.contextDependencies = null;
9867
9868 this.mode = mode;
9869
9870 // Effects
9871 this.effectTag = NoEffect;
9872 this.nextEffect = null;
9873
9874 this.firstEffect = null;
9875 this.lastEffect = null;
9876
9877 this.expirationTime = NoWork;
9878 this.childExpirationTime = NoWork;
9879
9880 this.alternate = null;
9881
9882 if (enableProfilerTimer) {
9883 // Note: The following is done to avoid a v8 performance cliff.
9884 //
9885 // Initializing the fields below to smis and later updating them with
9886 // double values will cause Fibers to end up having separate shapes.
9887 // This behavior/bug has something to do with Object.preventExtension().
9888 // Fortunately this only impacts DEV builds.
9889 // Unfortunately it makes React unusably slow for some applications.
9890 // To work around this, initialize the fields below with doubles.
9891 //
9892 // Learn more about this here:
9893 // https://github.com/facebook/react/issues/14365
9894 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
9895 this.actualDuration = Number.NaN;
9896 this.actualStartTime = Number.NaN;
9897 this.selfBaseDuration = Number.NaN;
9898 this.treeBaseDuration = Number.NaN;
9899
9900 // It's okay to replace the initial doubles with smis after initialization.
9901 // This won't trigger the performance cliff mentioned above,
9902 // and it simplifies other profiler code (including DevTools).
9903 this.actualDuration = 0;
9904 this.actualStartTime = -1;
9905 this.selfBaseDuration = 0;
9906 this.treeBaseDuration = 0;
9907 }
9908
9909 {
9910 this._debugID = debugCounter++;
9911 this._debugSource = null;
9912 this._debugOwner = null;
9913 this._debugIsCurrentlyTiming = false;
9914 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
9915 Object.preventExtensions(this);
9916 }
9917 }
9918}
9919
9920// This is a constructor function, rather than a POJO constructor, still
9921// please ensure we do the following:
9922// 1) Nobody should add any instance methods on this. Instance methods can be
9923// more difficult to predict when they get optimized and they are almost
9924// never inlined properly in static compilers.
9925// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
9926// always know when it is a fiber.
9927// 3) We might want to experiment with using numeric keys since they are easier
9928// to optimize in a non-JIT environment.
9929// 4) We can easily go from a constructor to a createFiber object literal if that
9930// is faster.
9931// 5) It should be easy to port this to a C struct and keep a C implementation
9932// compatible.
9933var createFiber = function (tag, pendingProps, key, mode) {
9934 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
9935 return new FiberNode(tag, pendingProps, key, mode);
9936};
9937
9938function shouldConstruct(Component) {
9939 var prototype = Component.prototype;
9940 return !!(prototype && prototype.isReactComponent);
9941}
9942
9943function isSimpleFunctionComponent(type) {
9944 return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
9945}
9946
9947function resolveLazyComponentTag(Component) {
9948 if (typeof Component === 'function') {
9949 return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
9950 } else if (Component !== undefined && Component !== null) {
9951 var $$typeof = Component.$$typeof;
9952 if ($$typeof === REACT_FORWARD_REF_TYPE) {
9953 return ForwardRef;
9954 }
9955 if ($$typeof === REACT_MEMO_TYPE) {
9956 return MemoComponent;
9957 }
9958 }
9959 return IndeterminateComponent;
9960}
9961
9962// This is used to create an alternate fiber to do work on.
9963function createWorkInProgress(current, pendingProps, expirationTime) {
9964 var workInProgress = current.alternate;
9965 if (workInProgress === null) {
9966 // We use a double buffering pooling technique because we know that we'll
9967 // only ever need at most two versions of a tree. We pool the "other" unused
9968 // node that we're free to reuse. This is lazily created to avoid allocating
9969 // extra objects for things that are never updated. It also allow us to
9970 // reclaim the extra memory if needed.
9971 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
9972 workInProgress.elementType = current.elementType;
9973 workInProgress.type = current.type;
9974 workInProgress.stateNode = current.stateNode;
9975
9976 {
9977 // DEV-only fields
9978 workInProgress._debugID = current._debugID;
9979 workInProgress._debugSource = current._debugSource;
9980 workInProgress._debugOwner = current._debugOwner;
9981 }
9982
9983 workInProgress.alternate = current;
9984 current.alternate = workInProgress;
9985 } else {
9986 workInProgress.pendingProps = pendingProps;
9987
9988 // We already have an alternate.
9989 // Reset the effect tag.
9990 workInProgress.effectTag = NoEffect;
9991
9992 // The effect list is no longer valid.
9993 workInProgress.nextEffect = null;
9994 workInProgress.firstEffect = null;
9995 workInProgress.lastEffect = null;
9996
9997 if (enableProfilerTimer) {
9998 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
9999 // This prevents time from endlessly accumulating in new commits.
10000 // This has the downside of resetting values for different priority renders,
10001 // But works for yielding (the common case) and should support resuming.
10002 workInProgress.actualDuration = 0;
10003 workInProgress.actualStartTime = -1;
10004 }
10005 }
10006
10007 workInProgress.childExpirationTime = current.childExpirationTime;
10008 workInProgress.expirationTime = current.expirationTime;
10009
10010 workInProgress.child = current.child;
10011 workInProgress.memoizedProps = current.memoizedProps;
10012 workInProgress.memoizedState = current.memoizedState;
10013 workInProgress.updateQueue = current.updateQueue;
10014 workInProgress.contextDependencies = current.contextDependencies;
10015
10016 // These will be overridden during the parent's reconciliation
10017 workInProgress.sibling = current.sibling;
10018 workInProgress.index = current.index;
10019 workInProgress.ref = current.ref;
10020
10021 if (enableProfilerTimer) {
10022 workInProgress.selfBaseDuration = current.selfBaseDuration;
10023 workInProgress.treeBaseDuration = current.treeBaseDuration;
10024 }
10025
10026 return workInProgress;
10027}
10028
10029function createHostRootFiber(isConcurrent) {
10030 var mode = isConcurrent ? ConcurrentMode | StrictMode : NoContext;
10031
10032 if (enableProfilerTimer && isDevToolsPresent) {
10033 // Always collect profile timings when DevTools are present.
10034 // This enables DevTools to start capturing timing at any point–
10035 // Without some nodes in the tree having empty base times.
10036 mode |= ProfileMode;
10037 }
10038
10039 return createFiber(HostRoot, null, null, mode);
10040}
10041
10042function createFiberFromTypeAndProps(type, // React$ElementType
10043key, pendingProps, owner, mode, expirationTime) {
10044 var fiber = void 0;
10045
10046 var fiberTag = IndeterminateComponent;
10047 // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
10048 var resolvedType = type;
10049 if (typeof type === 'function') {
10050 if (shouldConstruct(type)) {
10051 fiberTag = ClassComponent;
10052 }
10053 } else if (typeof type === 'string') {
10054 fiberTag = HostComponent;
10055 } else {
10056 getTag: switch (type) {
10057 case REACT_FRAGMENT_TYPE:
10058 return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
10059 case REACT_CONCURRENT_MODE_TYPE:
10060 return createFiberFromMode(pendingProps, mode | ConcurrentMode | StrictMode, expirationTime, key);
10061 case REACT_STRICT_MODE_TYPE:
10062 return createFiberFromMode(pendingProps, mode | StrictMode, expirationTime, key);
10063 case REACT_PROFILER_TYPE:
10064 return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
10065 case REACT_SUSPENSE_TYPE:
10066 return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
10067 default:
10068 {
10069 if (typeof type === 'object' && type !== null) {
10070 switch (type.$$typeof) {
10071 case REACT_PROVIDER_TYPE:
10072 fiberTag = ContextProvider;
10073 break getTag;
10074 case REACT_CONTEXT_TYPE:
10075 // This is a consumer
10076 fiberTag = ContextConsumer;
10077 break getTag;
10078 case REACT_FORWARD_REF_TYPE:
10079 fiberTag = ForwardRef;
10080 break getTag;
10081 case REACT_MEMO_TYPE:
10082 fiberTag = MemoComponent;
10083 break getTag;
10084 case REACT_LAZY_TYPE:
10085 fiberTag = LazyComponent;
10086 resolvedType = null;
10087 break getTag;
10088 }
10089 }
10090 var info = '';
10091 {
10092 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
10093 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.';
10094 }
10095 var ownerName = owner ? getComponentName(owner.type) : null;
10096 if (ownerName) {
10097 info += '\n\nCheck the render method of `' + ownerName + '`.';
10098 }
10099 }
10100 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);
10101 }
10102 }
10103 }
10104
10105 fiber = createFiber(fiberTag, pendingProps, key, mode);
10106 fiber.elementType = type;
10107 fiber.type = resolvedType;
10108 fiber.expirationTime = expirationTime;
10109
10110 return fiber;
10111}
10112
10113function createFiberFromElement(element, mode, expirationTime) {
10114 var owner = null;
10115 {
10116 owner = element._owner;
10117 }
10118 var type = element.type;
10119 var key = element.key;
10120 var pendingProps = element.props;
10121 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
10122 {
10123 fiber._debugSource = element._source;
10124 fiber._debugOwner = element._owner;
10125 }
10126 return fiber;
10127}
10128
10129function createFiberFromFragment(elements, mode, expirationTime, key) {
10130 var fiber = createFiber(Fragment, elements, key, mode);
10131 fiber.expirationTime = expirationTime;
10132 return fiber;
10133}
10134
10135function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
10136 {
10137 if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
10138 warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
10139 }
10140 }
10141
10142 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
10143 // TODO: The Profiler fiber shouldn't have a type. It has a tag.
10144 fiber.elementType = REACT_PROFILER_TYPE;
10145 fiber.type = REACT_PROFILER_TYPE;
10146 fiber.expirationTime = expirationTime;
10147
10148 return fiber;
10149}
10150
10151function createFiberFromMode(pendingProps, mode, expirationTime, key) {
10152 var fiber = createFiber(Mode, pendingProps, key, mode);
10153
10154 // TODO: The Mode fiber shouldn't have a type. It has a tag.
10155 var type = (mode & ConcurrentMode) === NoContext ? REACT_STRICT_MODE_TYPE : REACT_CONCURRENT_MODE_TYPE;
10156 fiber.elementType = type;
10157 fiber.type = type;
10158
10159 fiber.expirationTime = expirationTime;
10160 return fiber;
10161}
10162
10163function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
10164 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
10165
10166 // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
10167 var type = REACT_SUSPENSE_TYPE;
10168 fiber.elementType = type;
10169 fiber.type = type;
10170
10171 fiber.expirationTime = expirationTime;
10172 return fiber;
10173}
10174
10175function createFiberFromText(content, mode, expirationTime) {
10176 var fiber = createFiber(HostText, content, null, mode);
10177 fiber.expirationTime = expirationTime;
10178 return fiber;
10179}
10180
10181function createFiberFromHostInstanceForDeletion() {
10182 var fiber = createFiber(HostComponent, null, null, NoContext);
10183 // TODO: These should not need a type.
10184 fiber.elementType = 'DELETED';
10185 fiber.type = 'DELETED';
10186 return fiber;
10187}
10188
10189function createFiberFromPortal(portal, mode, expirationTime) {
10190 var pendingProps = portal.children !== null ? portal.children : [];
10191 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
10192 fiber.expirationTime = expirationTime;
10193 fiber.stateNode = {
10194 containerInfo: portal.containerInfo,
10195 pendingChildren: null, // Used by persistent updates
10196 implementation: portal.implementation
10197 };
10198 return fiber;
10199}
10200
10201// Used for stashing WIP properties to replay failed work in DEV.
10202function assignFiberPropertiesInDEV(target, source) {
10203 if (target === null) {
10204 // This Fiber's initial properties will always be overwritten.
10205 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
10206 target = createFiber(IndeterminateComponent, null, null, NoContext);
10207 }
10208
10209 // This is intentionally written as a list of all properties.
10210 // We tried to use Object.assign() instead but this is called in
10211 // the hottest path, and Object.assign() was too slow:
10212 // https://github.com/facebook/react/issues/12502
10213 // This code is DEV-only so size is not a concern.
10214
10215 target.tag = source.tag;
10216 target.key = source.key;
10217 target.elementType = source.elementType;
10218 target.type = source.type;
10219 target.stateNode = source.stateNode;
10220 target.return = source.return;
10221 target.child = source.child;
10222 target.sibling = source.sibling;
10223 target.index = source.index;
10224 target.ref = source.ref;
10225 target.pendingProps = source.pendingProps;
10226 target.memoizedProps = source.memoizedProps;
10227 target.updateQueue = source.updateQueue;
10228 target.memoizedState = source.memoizedState;
10229 target.contextDependencies = source.contextDependencies;
10230 target.mode = source.mode;
10231 target.effectTag = source.effectTag;
10232 target.nextEffect = source.nextEffect;
10233 target.firstEffect = source.firstEffect;
10234 target.lastEffect = source.lastEffect;
10235 target.expirationTime = source.expirationTime;
10236 target.childExpirationTime = source.childExpirationTime;
10237 target.alternate = source.alternate;
10238 if (enableProfilerTimer) {
10239 target.actualDuration = source.actualDuration;
10240 target.actualStartTime = source.actualStartTime;
10241 target.selfBaseDuration = source.selfBaseDuration;
10242 target.treeBaseDuration = source.treeBaseDuration;
10243 }
10244 target._debugID = source._debugID;
10245 target._debugSource = source._debugSource;
10246 target._debugOwner = source._debugOwner;
10247 target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
10248 return target;
10249}
10250
10251// TODO: This should be lifted into the renderer.
10252
10253
10254// The following attributes are only used by interaction tracing builds.
10255// They enable interactions to be associated with their async work,
10256// And expose interaction metadata to the React DevTools Profiler plugin.
10257// Note that these attributes are only defined when the enableSchedulerTracing flag is enabled.
10258
10259
10260// Exported FiberRoot type includes all properties,
10261// To avoid requiring potentially error-prone :any casts throughout the project.
10262// Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true).
10263// The types are defined separately within this file to ensure they stay in sync.
10264// (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.)
10265
10266
10267function createFiberRoot(containerInfo, isConcurrent, hydrate) {
10268 // Cyclic construction. This cheats the type system right now because
10269 // stateNode is any.
10270 var uninitializedFiber = createHostRootFiber(isConcurrent);
10271
10272 var root = void 0;
10273 if (enableSchedulerTracing) {
10274 root = {
10275 current: uninitializedFiber,
10276 containerInfo: containerInfo,
10277 pendingChildren: null,
10278
10279 earliestPendingTime: NoWork,
10280 latestPendingTime: NoWork,
10281 earliestSuspendedTime: NoWork,
10282 latestSuspendedTime: NoWork,
10283 latestPingedTime: NoWork,
10284
10285 pingCache: null,
10286
10287 didError: false,
10288
10289 pendingCommitExpirationTime: NoWork,
10290 finishedWork: null,
10291 timeoutHandle: noTimeout,
10292 context: null,
10293 pendingContext: null,
10294 hydrate: hydrate,
10295 nextExpirationTimeToWorkOn: NoWork,
10296 expirationTime: NoWork,
10297 firstBatch: null,
10298 nextScheduledRoot: null,
10299
10300 interactionThreadID: tracing.unstable_getThreadID(),
10301 memoizedInteractions: new Set(),
10302 pendingInteractionMap: new Map()
10303 };
10304 } else {
10305 root = {
10306 current: uninitializedFiber,
10307 containerInfo: containerInfo,
10308 pendingChildren: null,
10309
10310 pingCache: null,
10311
10312 earliestPendingTime: NoWork,
10313 latestPendingTime: NoWork,
10314 earliestSuspendedTime: NoWork,
10315 latestSuspendedTime: NoWork,
10316 latestPingedTime: NoWork,
10317
10318 didError: false,
10319
10320 pendingCommitExpirationTime: NoWork,
10321 finishedWork: null,
10322 timeoutHandle: noTimeout,
10323 context: null,
10324 pendingContext: null,
10325 hydrate: hydrate,
10326 nextExpirationTimeToWorkOn: NoWork,
10327 expirationTime: NoWork,
10328 firstBatch: null,
10329 nextScheduledRoot: null
10330 };
10331 }
10332
10333 uninitializedFiber.stateNode = root;
10334
10335 // The reason for the way the Flow types are structured in this file,
10336 // Is to avoid needing :any casts everywhere interaction tracing fields are used.
10337 // Unfortunately that requires an :any cast for non-interaction tracing capable builds.
10338 // $FlowFixMe Remove this :any cast and replace it with something better.
10339 return root;
10340}
10341
10342/**
10343 * Forked from fbjs/warning:
10344 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
10345 *
10346 * Only change is we use console.warn instead of console.error,
10347 * and do nothing when 'console' is not supported.
10348 * This really simplifies the code.
10349 * ---
10350 * Similar to invariant but only logs a warning if the condition is not met.
10351 * This can be used to log issues in development environments in critical
10352 * paths. Removing the logging code for production environments will keep the
10353 * same logic and follow the same code paths.
10354 */
10355
10356var lowPriorityWarning = function () {};
10357
10358{
10359 var printWarning = function (format) {
10360 for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
10361 args[_key - 1] = arguments[_key];
10362 }
10363
10364 var argIndex = 0;
10365 var message = 'Warning: ' + format.replace(/%s/g, function () {
10366 return args[argIndex++];
10367 });
10368 if (typeof console !== 'undefined') {
10369 console.warn(message);
10370 }
10371 try {
10372 // --- Welcome to debugging React ---
10373 // This error was thrown as a convenience so that you can use this stack
10374 // to find the callsite that caused this warning to fire.
10375 throw new Error(message);
10376 } catch (x) {}
10377 };
10378
10379 lowPriorityWarning = function (condition, format) {
10380 if (format === undefined) {
10381 throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
10382 }
10383 if (!condition) {
10384 for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
10385 args[_key2 - 2] = arguments[_key2];
10386 }
10387
10388 printWarning.apply(undefined, [format].concat(args));
10389 }
10390 };
10391}
10392
10393var lowPriorityWarning$1 = lowPriorityWarning;
10394
10395var ReactStrictModeWarnings = {
10396 discardPendingWarnings: function () {},
10397 flushPendingDeprecationWarnings: function () {},
10398 flushPendingUnsafeLifecycleWarnings: function () {},
10399 recordDeprecationWarnings: function (fiber, instance) {},
10400 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
10401 recordLegacyContextWarning: function (fiber, instance) {},
10402 flushLegacyContextWarning: function () {}
10403};
10404
10405{
10406 var LIFECYCLE_SUGGESTIONS = {
10407 UNSAFE_componentWillMount: 'componentDidMount',
10408 UNSAFE_componentWillReceiveProps: 'static getDerivedStateFromProps',
10409 UNSAFE_componentWillUpdate: 'componentDidUpdate'
10410 };
10411
10412 var pendingComponentWillMountWarnings = [];
10413 var pendingComponentWillReceivePropsWarnings = [];
10414 var pendingComponentWillUpdateWarnings = [];
10415 var pendingUnsafeLifecycleWarnings = new Map();
10416 var pendingLegacyContextWarning = new Map();
10417
10418 // Tracks components we have already warned about.
10419 var didWarnAboutDeprecatedLifecycles = new Set();
10420 var didWarnAboutUnsafeLifecycles = new Set();
10421 var didWarnAboutLegacyContext = new Set();
10422
10423 var setToSortedString = function (set) {
10424 var array = [];
10425 set.forEach(function (value) {
10426 array.push(value);
10427 });
10428 return array.sort().join(', ');
10429 };
10430
10431 ReactStrictModeWarnings.discardPendingWarnings = function () {
10432 pendingComponentWillMountWarnings = [];
10433 pendingComponentWillReceivePropsWarnings = [];
10434 pendingComponentWillUpdateWarnings = [];
10435 pendingUnsafeLifecycleWarnings = new Map();
10436 pendingLegacyContextWarning = new Map();
10437 };
10438
10439 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
10440 pendingUnsafeLifecycleWarnings.forEach(function (lifecycleWarningsMap, strictRoot) {
10441 var lifecyclesWarningMessages = [];
10442
10443 Object.keys(lifecycleWarningsMap).forEach(function (lifecycle) {
10444 var lifecycleWarnings = lifecycleWarningsMap[lifecycle];
10445 if (lifecycleWarnings.length > 0) {
10446 var componentNames = new Set();
10447 lifecycleWarnings.forEach(function (fiber) {
10448 componentNames.add(getComponentName(fiber.type) || 'Component');
10449 didWarnAboutUnsafeLifecycles.add(fiber.type);
10450 });
10451
10452 var formatted = lifecycle.replace('UNSAFE_', '');
10453 var suggestion = LIFECYCLE_SUGGESTIONS[lifecycle];
10454 var sortedComponentNames = setToSortedString(componentNames);
10455
10456 lifecyclesWarningMessages.push(formatted + ': Please update the following components to use ' + (suggestion + ' instead: ' + sortedComponentNames));
10457 }
10458 });
10459
10460 if (lifecyclesWarningMessages.length > 0) {
10461 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
10462
10463 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'));
10464 }
10465 });
10466
10467 pendingUnsafeLifecycleWarnings = new Map();
10468 };
10469
10470 var findStrictRoot = function (fiber) {
10471 var maybeStrictRoot = null;
10472
10473 var node = fiber;
10474 while (node !== null) {
10475 if (node.mode & StrictMode) {
10476 maybeStrictRoot = node;
10477 }
10478 node = node.return;
10479 }
10480
10481 return maybeStrictRoot;
10482 };
10483
10484 ReactStrictModeWarnings.flushPendingDeprecationWarnings = function () {
10485 if (pendingComponentWillMountWarnings.length > 0) {
10486 var uniqueNames = new Set();
10487 pendingComponentWillMountWarnings.forEach(function (fiber) {
10488 uniqueNames.add(getComponentName(fiber.type) || 'Component');
10489 didWarnAboutDeprecatedLifecycles.add(fiber.type);
10490 });
10491
10492 var sortedNames = setToSortedString(uniqueNames);
10493
10494 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);
10495
10496 pendingComponentWillMountWarnings = [];
10497 }
10498
10499 if (pendingComponentWillReceivePropsWarnings.length > 0) {
10500 var _uniqueNames = new Set();
10501 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
10502 _uniqueNames.add(getComponentName(fiber.type) || 'Component');
10503 didWarnAboutDeprecatedLifecycles.add(fiber.type);
10504 });
10505
10506 var _sortedNames = setToSortedString(_uniqueNames);
10507
10508 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);
10509
10510 pendingComponentWillReceivePropsWarnings = [];
10511 }
10512
10513 if (pendingComponentWillUpdateWarnings.length > 0) {
10514 var _uniqueNames2 = new Set();
10515 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
10516 _uniqueNames2.add(getComponentName(fiber.type) || 'Component');
10517 didWarnAboutDeprecatedLifecycles.add(fiber.type);
10518 });
10519
10520 var _sortedNames2 = setToSortedString(_uniqueNames2);
10521
10522 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);
10523
10524 pendingComponentWillUpdateWarnings = [];
10525 }
10526 };
10527
10528 ReactStrictModeWarnings.recordDeprecationWarnings = function (fiber, instance) {
10529 // Dedup strategy: Warn once per component.
10530 if (didWarnAboutDeprecatedLifecycles.has(fiber.type)) {
10531 return;
10532 }
10533
10534 // Don't warn about react-lifecycles-compat polyfilled components.
10535 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
10536 pendingComponentWillMountWarnings.push(fiber);
10537 }
10538 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
10539 pendingComponentWillReceivePropsWarnings.push(fiber);
10540 }
10541 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
10542 pendingComponentWillUpdateWarnings.push(fiber);
10543 }
10544 };
10545
10546 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
10547 var strictRoot = findStrictRoot(fiber);
10548 if (strictRoot === null) {
10549 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.');
10550 return;
10551 }
10552
10553 // Dedup strategy: Warn once per component.
10554 // This is difficult to track any other way since component names
10555 // are often vague and are likely to collide between 3rd party libraries.
10556 // An expand property is probably okay to use here since it's DEV-only,
10557 // and will only be set in the event of serious warnings.
10558 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
10559 return;
10560 }
10561
10562 var warningsForRoot = void 0;
10563 if (!pendingUnsafeLifecycleWarnings.has(strictRoot)) {
10564 warningsForRoot = {
10565 UNSAFE_componentWillMount: [],
10566 UNSAFE_componentWillReceiveProps: [],
10567 UNSAFE_componentWillUpdate: []
10568 };
10569
10570 pendingUnsafeLifecycleWarnings.set(strictRoot, warningsForRoot);
10571 } else {
10572 warningsForRoot = pendingUnsafeLifecycleWarnings.get(strictRoot);
10573 }
10574
10575 var unsafeLifecycles = [];
10576 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillMount === 'function') {
10577 unsafeLifecycles.push('UNSAFE_componentWillMount');
10578 }
10579 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
10580 unsafeLifecycles.push('UNSAFE_componentWillReceiveProps');
10581 }
10582 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillUpdate === 'function') {
10583 unsafeLifecycles.push('UNSAFE_componentWillUpdate');
10584 }
10585
10586 if (unsafeLifecycles.length > 0) {
10587 unsafeLifecycles.forEach(function (lifecycle) {
10588 warningsForRoot[lifecycle].push(fiber);
10589 });
10590 }
10591 };
10592
10593 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
10594 var strictRoot = findStrictRoot(fiber);
10595 if (strictRoot === null) {
10596 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.');
10597 return;
10598 }
10599
10600 // Dedup strategy: Warn once per component.
10601 if (didWarnAboutLegacyContext.has(fiber.type)) {
10602 return;
10603 }
10604
10605 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
10606
10607 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
10608 if (warningsForRoot === undefined) {
10609 warningsForRoot = [];
10610 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
10611 }
10612 warningsForRoot.push(fiber);
10613 }
10614 };
10615
10616 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
10617 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
10618 var uniqueNames = new Set();
10619 fiberArray.forEach(function (fiber) {
10620 uniqueNames.add(getComponentName(fiber.type) || 'Component');
10621 didWarnAboutLegacyContext.add(fiber.type);
10622 });
10623
10624 var sortedNames = setToSortedString(uniqueNames);
10625 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
10626
10627 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);
10628 });
10629 };
10630}
10631
10632// This lets us hook into Fiber to debug what it's doing.
10633// See https://github.com/facebook/react/pull/8033.
10634// This is not part of the public API, not even for React DevTools.
10635// You may only inject a debugTool if you work on React Fiber itself.
10636var ReactFiberInstrumentation = {
10637 debugTool: null
10638};
10639
10640var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
10641
10642// TODO: Offscreen updates should never suspend. However, a promise that
10643// suspended inside an offscreen subtree should be able to ping at the priority
10644// of the outer render.
10645
10646function markPendingPriorityLevel(root, expirationTime) {
10647 // If there's a gap between completing a failed root and retrying it,
10648 // additional updates may be scheduled. Clear `didError`, in case the update
10649 // is sufficient to fix the error.
10650 root.didError = false;
10651
10652 // Update the latest and earliest pending times
10653 var earliestPendingTime = root.earliestPendingTime;
10654 if (earliestPendingTime === NoWork) {
10655 // No other pending updates.
10656 root.earliestPendingTime = root.latestPendingTime = expirationTime;
10657 } else {
10658 if (earliestPendingTime < expirationTime) {
10659 // This is the earliest pending update.
10660 root.earliestPendingTime = expirationTime;
10661 } else {
10662 var latestPendingTime = root.latestPendingTime;
10663 if (latestPendingTime > expirationTime) {
10664 // This is the latest pending update
10665 root.latestPendingTime = expirationTime;
10666 }
10667 }
10668 }
10669 findNextExpirationTimeToWorkOn(expirationTime, root);
10670}
10671
10672function markCommittedPriorityLevels(root, earliestRemainingTime) {
10673 root.didError = false;
10674
10675 if (earliestRemainingTime === NoWork) {
10676 // Fast path. There's no remaining work. Clear everything.
10677 root.earliestPendingTime = NoWork;
10678 root.latestPendingTime = NoWork;
10679 root.earliestSuspendedTime = NoWork;
10680 root.latestSuspendedTime = NoWork;
10681 root.latestPingedTime = NoWork;
10682 findNextExpirationTimeToWorkOn(NoWork, root);
10683 return;
10684 }
10685
10686 if (earliestRemainingTime < root.latestPingedTime) {
10687 root.latestPingedTime = NoWork;
10688 }
10689
10690 // Let's see if the previous latest known pending level was just flushed.
10691 var latestPendingTime = root.latestPendingTime;
10692 if (latestPendingTime !== NoWork) {
10693 if (latestPendingTime > earliestRemainingTime) {
10694 // We've flushed all the known pending levels.
10695 root.earliestPendingTime = root.latestPendingTime = NoWork;
10696 } else {
10697 var earliestPendingTime = root.earliestPendingTime;
10698 if (earliestPendingTime > earliestRemainingTime) {
10699 // We've flushed the earliest known pending level. Set this to the
10700 // latest pending time.
10701 root.earliestPendingTime = root.latestPendingTime;
10702 }
10703 }
10704 }
10705
10706 // Now let's handle the earliest remaining level in the whole tree. We need to
10707 // decide whether to treat it as a pending level or as suspended. Check
10708 // it falls within the range of known suspended levels.
10709
10710 var earliestSuspendedTime = root.earliestSuspendedTime;
10711 if (earliestSuspendedTime === NoWork) {
10712 // There's no suspended work. Treat the earliest remaining level as a
10713 // pending level.
10714 markPendingPriorityLevel(root, earliestRemainingTime);
10715 findNextExpirationTimeToWorkOn(NoWork, root);
10716 return;
10717 }
10718
10719 var latestSuspendedTime = root.latestSuspendedTime;
10720 if (earliestRemainingTime < latestSuspendedTime) {
10721 // The earliest remaining level is later than all the suspended work. That
10722 // means we've flushed all the suspended work.
10723 root.earliestSuspendedTime = NoWork;
10724 root.latestSuspendedTime = NoWork;
10725 root.latestPingedTime = NoWork;
10726
10727 // There's no suspended work. Treat the earliest remaining level as a
10728 // pending level.
10729 markPendingPriorityLevel(root, earliestRemainingTime);
10730 findNextExpirationTimeToWorkOn(NoWork, root);
10731 return;
10732 }
10733
10734 if (earliestRemainingTime > earliestSuspendedTime) {
10735 // The earliest remaining time is earlier than all the suspended work.
10736 // Treat it as a pending update.
10737 markPendingPriorityLevel(root, earliestRemainingTime);
10738 findNextExpirationTimeToWorkOn(NoWork, root);
10739 return;
10740 }
10741
10742 // The earliest remaining time falls within the range of known suspended
10743 // levels. We should treat this as suspended work.
10744 findNextExpirationTimeToWorkOn(NoWork, root);
10745}
10746
10747function hasLowerPriorityWork(root, erroredExpirationTime) {
10748 var latestPendingTime = root.latestPendingTime;
10749 var latestSuspendedTime = root.latestSuspendedTime;
10750 var latestPingedTime = root.latestPingedTime;
10751 return latestPendingTime !== NoWork && latestPendingTime < erroredExpirationTime || latestSuspendedTime !== NoWork && latestSuspendedTime < erroredExpirationTime || latestPingedTime !== NoWork && latestPingedTime < erroredExpirationTime;
10752}
10753
10754function isPriorityLevelSuspended(root, expirationTime) {
10755 var earliestSuspendedTime = root.earliestSuspendedTime;
10756 var latestSuspendedTime = root.latestSuspendedTime;
10757 return earliestSuspendedTime !== NoWork && expirationTime <= earliestSuspendedTime && expirationTime >= latestSuspendedTime;
10758}
10759
10760function markSuspendedPriorityLevel(root, suspendedTime) {
10761 root.didError = false;
10762 clearPing(root, suspendedTime);
10763
10764 // First, check the known pending levels and update them if needed.
10765 var earliestPendingTime = root.earliestPendingTime;
10766 var latestPendingTime = root.latestPendingTime;
10767 if (earliestPendingTime === suspendedTime) {
10768 if (latestPendingTime === suspendedTime) {
10769 // Both known pending levels were suspended. Clear them.
10770 root.earliestPendingTime = root.latestPendingTime = NoWork;
10771 } else {
10772 // The earliest pending level was suspended. Clear by setting it to the
10773 // latest pending level.
10774 root.earliestPendingTime = latestPendingTime;
10775 }
10776 } else if (latestPendingTime === suspendedTime) {
10777 // The latest pending level was suspended. Clear by setting it to the
10778 // latest pending level.
10779 root.latestPendingTime = earliestPendingTime;
10780 }
10781
10782 // Finally, update the known suspended levels.
10783 var earliestSuspendedTime = root.earliestSuspendedTime;
10784 var latestSuspendedTime = root.latestSuspendedTime;
10785 if (earliestSuspendedTime === NoWork) {
10786 // No other suspended levels.
10787 root.earliestSuspendedTime = root.latestSuspendedTime = suspendedTime;
10788 } else {
10789 if (earliestSuspendedTime < suspendedTime) {
10790 // This is the earliest suspended level.
10791 root.earliestSuspendedTime = suspendedTime;
10792 } else if (latestSuspendedTime > suspendedTime) {
10793 // This is the latest suspended level
10794 root.latestSuspendedTime = suspendedTime;
10795 }
10796 }
10797
10798 findNextExpirationTimeToWorkOn(suspendedTime, root);
10799}
10800
10801function markPingedPriorityLevel(root, pingedTime) {
10802 root.didError = false;
10803
10804 // TODO: When we add back resuming, we need to ensure the progressed work
10805 // is thrown out and not reused during the restarted render. One way to
10806 // invalidate the progressed work is to restart at expirationTime + 1.
10807 var latestPingedTime = root.latestPingedTime;
10808 if (latestPingedTime === NoWork || latestPingedTime > pingedTime) {
10809 root.latestPingedTime = pingedTime;
10810 }
10811 findNextExpirationTimeToWorkOn(pingedTime, root);
10812}
10813
10814function clearPing(root, completedTime) {
10815 var latestPingedTime = root.latestPingedTime;
10816 if (latestPingedTime >= completedTime) {
10817 root.latestPingedTime = NoWork;
10818 }
10819}
10820
10821function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) {
10822 var earliestExpirationTime = renderExpirationTime;
10823
10824 var earliestPendingTime = root.earliestPendingTime;
10825 var earliestSuspendedTime = root.earliestSuspendedTime;
10826 if (earliestPendingTime > earliestExpirationTime) {
10827 earliestExpirationTime = earliestPendingTime;
10828 }
10829 if (earliestSuspendedTime > earliestExpirationTime) {
10830 earliestExpirationTime = earliestSuspendedTime;
10831 }
10832 return earliestExpirationTime;
10833}
10834
10835function didExpireAtExpirationTime(root, currentTime) {
10836 var expirationTime = root.expirationTime;
10837 if (expirationTime !== NoWork && currentTime <= expirationTime) {
10838 // The root has expired. Flush all work up to the current time.
10839 root.nextExpirationTimeToWorkOn = currentTime;
10840 }
10841}
10842
10843function findNextExpirationTimeToWorkOn(completedExpirationTime, root) {
10844 var earliestSuspendedTime = root.earliestSuspendedTime;
10845 var latestSuspendedTime = root.latestSuspendedTime;
10846 var earliestPendingTime = root.earliestPendingTime;
10847 var latestPingedTime = root.latestPingedTime;
10848
10849 // Work on the earliest pending time. Failing that, work on the latest
10850 // pinged time.
10851 var nextExpirationTimeToWorkOn = earliestPendingTime !== NoWork ? earliestPendingTime : latestPingedTime;
10852
10853 // If there is no pending or pinged work, check if there's suspended work
10854 // that's lower priority than what we just completed.
10855 if (nextExpirationTimeToWorkOn === NoWork && (completedExpirationTime === NoWork || latestSuspendedTime < completedExpirationTime)) {
10856 // The lowest priority suspended work is the work most likely to be
10857 // committed next. Let's start rendering it again, so that if it times out,
10858 // it's ready to commit.
10859 nextExpirationTimeToWorkOn = latestSuspendedTime;
10860 }
10861
10862 var expirationTime = nextExpirationTimeToWorkOn;
10863 if (expirationTime !== NoWork && earliestSuspendedTime > expirationTime) {
10864 // Expire using the earliest known expiration time.
10865 expirationTime = earliestSuspendedTime;
10866 }
10867
10868 root.nextExpirationTimeToWorkOn = nextExpirationTimeToWorkOn;
10869 root.expirationTime = expirationTime;
10870}
10871
10872function resolveDefaultProps(Component, baseProps) {
10873 if (Component && Component.defaultProps) {
10874 // Resolve default props. Taken from ReactElement
10875 var props = _assign({}, baseProps);
10876 var defaultProps = Component.defaultProps;
10877 for (var propName in defaultProps) {
10878 if (props[propName] === undefined) {
10879 props[propName] = defaultProps[propName];
10880 }
10881 }
10882 return props;
10883 }
10884 return baseProps;
10885}
10886
10887function readLazyComponentType(lazyComponent) {
10888 var status = lazyComponent._status;
10889 var result = lazyComponent._result;
10890 switch (status) {
10891 case Resolved:
10892 {
10893 var Component = result;
10894 return Component;
10895 }
10896 case Rejected:
10897 {
10898 var error = result;
10899 throw error;
10900 }
10901 case Pending:
10902 {
10903 var thenable = result;
10904 throw thenable;
10905 }
10906 default:
10907 {
10908 lazyComponent._status = Pending;
10909 var ctor = lazyComponent._ctor;
10910 var _thenable = ctor();
10911 _thenable.then(function (moduleObject) {
10912 if (lazyComponent._status === Pending) {
10913 var defaultExport = moduleObject.default;
10914 {
10915 if (defaultExport === undefined) {
10916 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);
10917 }
10918 }
10919 lazyComponent._status = Resolved;
10920 lazyComponent._result = defaultExport;
10921 }
10922 }, function (error) {
10923 if (lazyComponent._status === Pending) {
10924 lazyComponent._status = Rejected;
10925 lazyComponent._result = error;
10926 }
10927 });
10928 // Handle synchronous thenables.
10929 switch (lazyComponent._status) {
10930 case Resolved:
10931 return lazyComponent._result;
10932 case Rejected:
10933 throw lazyComponent._result;
10934 }
10935 lazyComponent._result = _thenable;
10936 throw _thenable;
10937 }
10938 }
10939}
10940
10941var fakeInternalInstance = {};
10942var isArray$1 = Array.isArray;
10943
10944// React.Component uses a shared frozen object by default.
10945// We'll use it to determine whether we need to initialize legacy refs.
10946var emptyRefsObject = new React.Component().refs;
10947
10948var didWarnAboutStateAssignmentForComponent = void 0;
10949var didWarnAboutUninitializedState = void 0;
10950var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0;
10951var didWarnAboutLegacyLifecyclesAndDerivedState = void 0;
10952var didWarnAboutUndefinedDerivedState = void 0;
10953var warnOnUndefinedDerivedState = void 0;
10954var warnOnInvalidCallback$1 = void 0;
10955var didWarnAboutDirectlyAssigningPropsToState = void 0;
10956var didWarnAboutContextTypeAndContextTypes = void 0;
10957var didWarnAboutInvalidateContextType = void 0;
10958
10959{
10960 didWarnAboutStateAssignmentForComponent = new Set();
10961 didWarnAboutUninitializedState = new Set();
10962 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
10963 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
10964 didWarnAboutDirectlyAssigningPropsToState = new Set();
10965 didWarnAboutUndefinedDerivedState = new Set();
10966 didWarnAboutContextTypeAndContextTypes = new Set();
10967 didWarnAboutInvalidateContextType = new Set();
10968
10969 var didWarnOnInvalidCallback = new Set();
10970
10971 warnOnInvalidCallback$1 = function (callback, callerName) {
10972 if (callback === null || typeof callback === 'function') {
10973 return;
10974 }
10975 var key = callerName + '_' + callback;
10976 if (!didWarnOnInvalidCallback.has(key)) {
10977 didWarnOnInvalidCallback.add(key);
10978 warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
10979 }
10980 };
10981
10982 warnOnUndefinedDerivedState = function (type, partialState) {
10983 if (partialState === undefined) {
10984 var componentName = getComponentName(type) || 'Component';
10985 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
10986 didWarnAboutUndefinedDerivedState.add(componentName);
10987 warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
10988 }
10989 }
10990 };
10991
10992 // This is so gross but it's at least non-critical and can be removed if
10993 // it causes problems. This is meant to give a nicer error message for
10994 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
10995 // ...)) which otherwise throws a "_processChildContext is not a function"
10996 // exception.
10997 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
10998 enumerable: false,
10999 value: function () {
11000 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).');
11001 }
11002 });
11003 Object.freeze(fakeInternalInstance);
11004}
11005
11006function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
11007 var prevState = workInProgress.memoizedState;
11008
11009 {
11010 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
11011 // Invoke the function an extra time to help detect side-effects.
11012 getDerivedStateFromProps(nextProps, prevState);
11013 }
11014 }
11015
11016 var partialState = getDerivedStateFromProps(nextProps, prevState);
11017
11018 {
11019 warnOnUndefinedDerivedState(ctor, partialState);
11020 }
11021 // Merge the partial state and the previous state.
11022 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
11023 workInProgress.memoizedState = memoizedState;
11024
11025 // Once the update queue is empty, persist the derived state onto the
11026 // base state.
11027 var updateQueue = workInProgress.updateQueue;
11028 if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
11029 updateQueue.baseState = memoizedState;
11030 }
11031}
11032
11033var classComponentUpdater = {
11034 isMounted: isMounted,
11035 enqueueSetState: function (inst, payload, callback) {
11036 var fiber = get(inst);
11037 var currentTime = requestCurrentTime();
11038 var expirationTime = computeExpirationForFiber(currentTime, fiber);
11039
11040 var update = createUpdate(expirationTime);
11041 update.payload = payload;
11042 if (callback !== undefined && callback !== null) {
11043 {
11044 warnOnInvalidCallback$1(callback, 'setState');
11045 }
11046 update.callback = callback;
11047 }
11048
11049 flushPassiveEffects();
11050 enqueueUpdate(fiber, update);
11051 scheduleWork(fiber, expirationTime);
11052 },
11053 enqueueReplaceState: function (inst, payload, callback) {
11054 var fiber = get(inst);
11055 var currentTime = requestCurrentTime();
11056 var expirationTime = computeExpirationForFiber(currentTime, fiber);
11057
11058 var update = createUpdate(expirationTime);
11059 update.tag = ReplaceState;
11060 update.payload = payload;
11061
11062 if (callback !== undefined && callback !== null) {
11063 {
11064 warnOnInvalidCallback$1(callback, 'replaceState');
11065 }
11066 update.callback = callback;
11067 }
11068
11069 flushPassiveEffects();
11070 enqueueUpdate(fiber, update);
11071 scheduleWork(fiber, expirationTime);
11072 },
11073 enqueueForceUpdate: function (inst, callback) {
11074 var fiber = get(inst);
11075 var currentTime = requestCurrentTime();
11076 var expirationTime = computeExpirationForFiber(currentTime, fiber);
11077
11078 var update = createUpdate(expirationTime);
11079 update.tag = ForceUpdate;
11080
11081 if (callback !== undefined && callback !== null) {
11082 {
11083 warnOnInvalidCallback$1(callback, 'forceUpdate');
11084 }
11085 update.callback = callback;
11086 }
11087
11088 flushPassiveEffects();
11089 enqueueUpdate(fiber, update);
11090 scheduleWork(fiber, expirationTime);
11091 }
11092};
11093
11094function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
11095 var instance = workInProgress.stateNode;
11096 if (typeof instance.shouldComponentUpdate === 'function') {
11097 startPhaseTimer(workInProgress, 'shouldComponentUpdate');
11098 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
11099 stopPhaseTimer();
11100
11101 {
11102 !(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;
11103 }
11104
11105 return shouldUpdate;
11106 }
11107
11108 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
11109 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
11110 }
11111
11112 return true;
11113}
11114
11115function checkClassInstance(workInProgress, ctor, newProps) {
11116 var instance = workInProgress.stateNode;
11117 {
11118 var name = getComponentName(ctor) || 'Component';
11119 var renderPresent = instance.render;
11120
11121 if (!renderPresent) {
11122 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
11123 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
11124 } else {
11125 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
11126 }
11127 }
11128
11129 var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
11130 !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;
11131 var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
11132 !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;
11133 var noInstancePropTypes = !instance.propTypes;
11134 !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
11135 var noInstanceContextType = !instance.contextType;
11136 !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0;
11137 var noInstanceContextTypes = !instance.contextTypes;
11138 !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
11139
11140 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
11141 didWarnAboutContextTypeAndContextTypes.add(ctor);
11142 warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
11143 }
11144
11145 var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
11146 !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;
11147 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
11148 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');
11149 }
11150 var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
11151 !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
11152 var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
11153 !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;
11154 var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
11155 !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
11156 var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
11157 !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
11158 var hasMutatedProps = instance.props !== newProps;
11159 !(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;
11160 var noInstanceDefaultProps = !instance.defaultProps;
11161 !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;
11162
11163 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
11164 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
11165 warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
11166 }
11167
11168 var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
11169 !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;
11170 var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function';
11171 !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;
11172 var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function';
11173 !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;
11174 var _state = instance.state;
11175 if (_state && (typeof _state !== 'object' || isArray$1(_state))) {
11176 warningWithoutStack$1(false, '%s.state: must be set to an object or null', name);
11177 }
11178 if (typeof instance.getChildContext === 'function') {
11179 !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
11180 }
11181 }
11182}
11183
11184function adoptClassInstance(workInProgress, instance) {
11185 instance.updater = classComponentUpdater;
11186 workInProgress.stateNode = instance;
11187 // The instance needs access to the fiber so that it can schedule updates
11188 set(instance, workInProgress);
11189 {
11190 instance._reactInternalInstance = fakeInternalInstance;
11191 }
11192}
11193
11194function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) {
11195 var isLegacyContextConsumer = false;
11196 var unmaskedContext = emptyContextObject;
11197 var context = null;
11198 var contextType = ctor.contextType;
11199 if (typeof contextType === 'object' && contextType !== null) {
11200 {
11201 if (contextType.$$typeof !== REACT_CONTEXT_TYPE && !didWarnAboutInvalidateContextType.has(ctor)) {
11202 didWarnAboutInvalidateContextType.add(ctor);
11203 warningWithoutStack$1(false, '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext(). ' + 'Did you accidentally pass the Context.Provider instead?', getComponentName(ctor) || 'Component');
11204 }
11205 }
11206
11207 context = readContext(contextType);
11208 } else {
11209 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11210 var contextTypes = ctor.contextTypes;
11211 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
11212 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
11213 }
11214
11215 // Instantiate twice to help detect side-effects.
11216 {
11217 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
11218 new ctor(props, context); // eslint-disable-line no-new
11219 }
11220 }
11221
11222 var instance = new ctor(props, context);
11223 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
11224 adoptClassInstance(workInProgress, instance);
11225
11226 {
11227 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
11228 var componentName = getComponentName(ctor) || 'Component';
11229 if (!didWarnAboutUninitializedState.has(componentName)) {
11230 didWarnAboutUninitializedState.add(componentName);
11231 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);
11232 }
11233 }
11234
11235 // If new component APIs are defined, "unsafe" lifecycles won't be called.
11236 // Warn about these lifecycles if they are present.
11237 // Don't warn about react-lifecycles-compat polyfilled methods though.
11238 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
11239 var foundWillMountName = null;
11240 var foundWillReceivePropsName = null;
11241 var foundWillUpdateName = null;
11242 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
11243 foundWillMountName = 'componentWillMount';
11244 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
11245 foundWillMountName = 'UNSAFE_componentWillMount';
11246 }
11247 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
11248 foundWillReceivePropsName = 'componentWillReceiveProps';
11249 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
11250 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
11251 }
11252 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
11253 foundWillUpdateName = 'componentWillUpdate';
11254 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
11255 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
11256 }
11257 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
11258 var _componentName = getComponentName(ctor) || 'Component';
11259 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
11260 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
11261 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
11262 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 : '');
11263 }
11264 }
11265 }
11266 }
11267
11268 // Cache unmasked context so we can avoid recreating masked context unless necessary.
11269 // ReactFiberContext usually updates this cache but can't for newly-created instances.
11270 if (isLegacyContextConsumer) {
11271 cacheContext(workInProgress, unmaskedContext, context);
11272 }
11273
11274 return instance;
11275}
11276
11277function callComponentWillMount(workInProgress, instance) {
11278 startPhaseTimer(workInProgress, 'componentWillMount');
11279 var oldState = instance.state;
11280
11281 if (typeof instance.componentWillMount === 'function') {
11282 instance.componentWillMount();
11283 }
11284 if (typeof instance.UNSAFE_componentWillMount === 'function') {
11285 instance.UNSAFE_componentWillMount();
11286 }
11287
11288 stopPhaseTimer();
11289
11290 if (oldState !== instance.state) {
11291 {
11292 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');
11293 }
11294 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
11295 }
11296}
11297
11298function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
11299 var oldState = instance.state;
11300 startPhaseTimer(workInProgress, 'componentWillReceiveProps');
11301 if (typeof instance.componentWillReceiveProps === 'function') {
11302 instance.componentWillReceiveProps(newProps, nextContext);
11303 }
11304 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
11305 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
11306 }
11307 stopPhaseTimer();
11308
11309 if (instance.state !== oldState) {
11310 {
11311 var componentName = getComponentName(workInProgress.type) || 'Component';
11312 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
11313 didWarnAboutStateAssignmentForComponent.add(componentName);
11314 warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
11315 }
11316 }
11317 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
11318 }
11319}
11320
11321// Invokes the mount life-cycles on a previously never rendered instance.
11322function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
11323 {
11324 checkClassInstance(workInProgress, ctor, newProps);
11325 }
11326
11327 var instance = workInProgress.stateNode;
11328 instance.props = newProps;
11329 instance.state = workInProgress.memoizedState;
11330 instance.refs = emptyRefsObject;
11331
11332 var contextType = ctor.contextType;
11333 if (typeof contextType === 'object' && contextType !== null) {
11334 instance.context = readContext(contextType);
11335 } else {
11336 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11337 instance.context = getMaskedContext(workInProgress, unmaskedContext);
11338 }
11339
11340 {
11341 if (instance.state === newProps) {
11342 var componentName = getComponentName(ctor) || 'Component';
11343 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
11344 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
11345 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);
11346 }
11347 }
11348
11349 if (workInProgress.mode & StrictMode) {
11350 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
11351
11352 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
11353 }
11354
11355 if (warnAboutDeprecatedLifecycles) {
11356 ReactStrictModeWarnings.recordDeprecationWarnings(workInProgress, instance);
11357 }
11358 }
11359
11360 var updateQueue = workInProgress.updateQueue;
11361 if (updateQueue !== null) {
11362 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11363 instance.state = workInProgress.memoizedState;
11364 }
11365
11366 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
11367 if (typeof getDerivedStateFromProps === 'function') {
11368 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
11369 instance.state = workInProgress.memoizedState;
11370 }
11371
11372 // In order to support react-lifecycles-compat polyfilled components,
11373 // Unsafe lifecycles should not be invoked for components using the new APIs.
11374 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
11375 callComponentWillMount(workInProgress, instance);
11376 // If we had additional state updates during this life-cycle, let's
11377 // process them now.
11378 updateQueue = workInProgress.updateQueue;
11379 if (updateQueue !== null) {
11380 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11381 instance.state = workInProgress.memoizedState;
11382 }
11383 }
11384
11385 if (typeof instance.componentDidMount === 'function') {
11386 workInProgress.effectTag |= Update;
11387 }
11388}
11389
11390function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
11391 var instance = workInProgress.stateNode;
11392
11393 var oldProps = workInProgress.memoizedProps;
11394 instance.props = oldProps;
11395
11396 var oldContext = instance.context;
11397 var contextType = ctor.contextType;
11398 var nextContext = void 0;
11399 if (typeof contextType === 'object' && contextType !== null) {
11400 nextContext = readContext(contextType);
11401 } else {
11402 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11403 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
11404 }
11405
11406 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
11407 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
11408
11409 // Note: During these life-cycles, instance.props/instance.state are what
11410 // ever the previously attempted to render - not the "current". However,
11411 // during componentDidUpdate we pass the "current" props.
11412
11413 // In order to support react-lifecycles-compat polyfilled components,
11414 // Unsafe lifecycles should not be invoked for components using the new APIs.
11415 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
11416 if (oldProps !== newProps || oldContext !== nextContext) {
11417 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
11418 }
11419 }
11420
11421 resetHasForceUpdateBeforeProcessing();
11422
11423 var oldState = workInProgress.memoizedState;
11424 var newState = instance.state = oldState;
11425 var updateQueue = workInProgress.updateQueue;
11426 if (updateQueue !== null) {
11427 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11428 newState = workInProgress.memoizedState;
11429 }
11430 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
11431 // If an update was already in progress, we should schedule an Update
11432 // effect even though we're bailing out, so that cWU/cDU are called.
11433 if (typeof instance.componentDidMount === 'function') {
11434 workInProgress.effectTag |= Update;
11435 }
11436 return false;
11437 }
11438
11439 if (typeof getDerivedStateFromProps === 'function') {
11440 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
11441 newState = workInProgress.memoizedState;
11442 }
11443
11444 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
11445
11446 if (shouldUpdate) {
11447 // In order to support react-lifecycles-compat polyfilled components,
11448 // Unsafe lifecycles should not be invoked for components using the new APIs.
11449 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
11450 startPhaseTimer(workInProgress, 'componentWillMount');
11451 if (typeof instance.componentWillMount === 'function') {
11452 instance.componentWillMount();
11453 }
11454 if (typeof instance.UNSAFE_componentWillMount === 'function') {
11455 instance.UNSAFE_componentWillMount();
11456 }
11457 stopPhaseTimer();
11458 }
11459 if (typeof instance.componentDidMount === 'function') {
11460 workInProgress.effectTag |= Update;
11461 }
11462 } else {
11463 // If an update was already in progress, we should schedule an Update
11464 // effect even though we're bailing out, so that cWU/cDU are called.
11465 if (typeof instance.componentDidMount === 'function') {
11466 workInProgress.effectTag |= Update;
11467 }
11468
11469 // If shouldComponentUpdate returned false, we should still update the
11470 // memoized state to indicate that this work can be reused.
11471 workInProgress.memoizedProps = newProps;
11472 workInProgress.memoizedState = newState;
11473 }
11474
11475 // Update the existing instance's state, props, and context pointers even
11476 // if shouldComponentUpdate returns false.
11477 instance.props = newProps;
11478 instance.state = newState;
11479 instance.context = nextContext;
11480
11481 return shouldUpdate;
11482}
11483
11484// Invokes the update life-cycles and returns false if it shouldn't rerender.
11485function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
11486 var instance = workInProgress.stateNode;
11487
11488 var oldProps = workInProgress.memoizedProps;
11489 instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
11490
11491 var oldContext = instance.context;
11492 var contextType = ctor.contextType;
11493 var nextContext = void 0;
11494 if (typeof contextType === 'object' && contextType !== null) {
11495 nextContext = readContext(contextType);
11496 } else {
11497 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
11498 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
11499 }
11500
11501 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
11502 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
11503
11504 // Note: During these life-cycles, instance.props/instance.state are what
11505 // ever the previously attempted to render - not the "current". However,
11506 // during componentDidUpdate we pass the "current" props.
11507
11508 // In order to support react-lifecycles-compat polyfilled components,
11509 // Unsafe lifecycles should not be invoked for components using the new APIs.
11510 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
11511 if (oldProps !== newProps || oldContext !== nextContext) {
11512 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
11513 }
11514 }
11515
11516 resetHasForceUpdateBeforeProcessing();
11517
11518 var oldState = workInProgress.memoizedState;
11519 var newState = instance.state = oldState;
11520 var updateQueue = workInProgress.updateQueue;
11521 if (updateQueue !== null) {
11522 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
11523 newState = workInProgress.memoizedState;
11524 }
11525
11526 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
11527 // If an update was already in progress, we should schedule an Update
11528 // effect even though we're bailing out, so that cWU/cDU are called.
11529 if (typeof instance.componentDidUpdate === 'function') {
11530 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11531 workInProgress.effectTag |= Update;
11532 }
11533 }
11534 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
11535 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11536 workInProgress.effectTag |= Snapshot;
11537 }
11538 }
11539 return false;
11540 }
11541
11542 if (typeof getDerivedStateFromProps === 'function') {
11543 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
11544 newState = workInProgress.memoizedState;
11545 }
11546
11547 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
11548
11549 if (shouldUpdate) {
11550 // In order to support react-lifecycles-compat polyfilled components,
11551 // Unsafe lifecycles should not be invoked for components using the new APIs.
11552 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
11553 startPhaseTimer(workInProgress, 'componentWillUpdate');
11554 if (typeof instance.componentWillUpdate === 'function') {
11555 instance.componentWillUpdate(newProps, newState, nextContext);
11556 }
11557 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
11558 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
11559 }
11560 stopPhaseTimer();
11561 }
11562 if (typeof instance.componentDidUpdate === 'function') {
11563 workInProgress.effectTag |= Update;
11564 }
11565 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
11566 workInProgress.effectTag |= Snapshot;
11567 }
11568 } else {
11569 // If an update was already in progress, we should schedule an Update
11570 // effect even though we're bailing out, so that cWU/cDU are called.
11571 if (typeof instance.componentDidUpdate === 'function') {
11572 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11573 workInProgress.effectTag |= Update;
11574 }
11575 }
11576 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
11577 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
11578 workInProgress.effectTag |= Snapshot;
11579 }
11580 }
11581
11582 // If shouldComponentUpdate returned false, we should still update the
11583 // memoized props/state to indicate that this work can be reused.
11584 workInProgress.memoizedProps = newProps;
11585 workInProgress.memoizedState = newState;
11586 }
11587
11588 // Update the existing instance's state, props, and context pointers even
11589 // if shouldComponentUpdate returns false.
11590 instance.props = newProps;
11591 instance.state = newState;
11592 instance.context = nextContext;
11593
11594 return shouldUpdate;
11595}
11596
11597var didWarnAboutMaps = void 0;
11598var didWarnAboutGenerators = void 0;
11599var didWarnAboutStringRefInStrictMode = void 0;
11600var ownerHasKeyUseWarning = void 0;
11601var ownerHasFunctionTypeWarning = void 0;
11602var warnForMissingKey = function (child) {};
11603
11604{
11605 didWarnAboutMaps = false;
11606 didWarnAboutGenerators = false;
11607 didWarnAboutStringRefInStrictMode = {};
11608
11609 /**
11610 * Warn if there's no key explicitly set on dynamic arrays of children or
11611 * object keys are not valid. This allows us to keep track of children between
11612 * updates.
11613 */
11614 ownerHasKeyUseWarning = {};
11615 ownerHasFunctionTypeWarning = {};
11616
11617 warnForMissingKey = function (child) {
11618 if (child === null || typeof child !== 'object') {
11619 return;
11620 }
11621 if (!child._store || child._store.validated || child.key != null) {
11622 return;
11623 }
11624 !(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;
11625 child._store.validated = true;
11626
11627 var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
11628 if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
11629 return;
11630 }
11631 ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
11632
11633 warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
11634 };
11635}
11636
11637var isArray = Array.isArray;
11638
11639function coerceRef(returnFiber, current$$1, element) {
11640 var mixedRef = element.ref;
11641 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
11642 {
11643 if (returnFiber.mode & StrictMode) {
11644 var componentName = getComponentName(returnFiber.type) || 'Component';
11645 if (!didWarnAboutStringRefInStrictMode[componentName]) {
11646 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));
11647 didWarnAboutStringRefInStrictMode[componentName] = true;
11648 }
11649 }
11650 }
11651
11652 if (element._owner) {
11653 var owner = element._owner;
11654 var inst = void 0;
11655 if (owner) {
11656 var ownerFiber = owner;
11657 !(ownerFiber.tag === ClassComponent) ? invariant(false, 'Function components cannot have refs. Did you mean to use React.forwardRef()?') : void 0;
11658 inst = ownerFiber.stateNode;
11659 }
11660 !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;
11661 var stringRef = '' + mixedRef;
11662 // Check if previous string ref matches new string ref
11663 if (current$$1 !== null && current$$1.ref !== null && typeof current$$1.ref === 'function' && current$$1.ref._stringRef === stringRef) {
11664 return current$$1.ref;
11665 }
11666 var ref = function (value) {
11667 var refs = inst.refs;
11668 if (refs === emptyRefsObject) {
11669 // This is a lazy pooled frozen object, so we need to initialize.
11670 refs = inst.refs = {};
11671 }
11672 if (value === null) {
11673 delete refs[stringRef];
11674 } else {
11675 refs[stringRef] = value;
11676 }
11677 };
11678 ref._stringRef = stringRef;
11679 return ref;
11680 } else {
11681 !(typeof mixedRef === 'string') ? invariant(false, 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.') : void 0;
11682 !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;
11683 }
11684 }
11685 return mixedRef;
11686}
11687
11688function throwOnInvalidObjectType(returnFiber, newChild) {
11689 if (returnFiber.type !== 'textarea') {
11690 var addendum = '';
11691 {
11692 addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
11693 }
11694 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);
11695 }
11696}
11697
11698function warnOnFunctionType() {
11699 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();
11700
11701 if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
11702 return;
11703 }
11704 ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
11705
11706 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.');
11707}
11708
11709// This wrapper function exists because I expect to clone the code in each path
11710// to be able to optimize each path individually by branching early. This needs
11711// a compiler or we can do it manually. Helpers that don't need this branching
11712// live outside of this function.
11713function ChildReconciler(shouldTrackSideEffects) {
11714 function deleteChild(returnFiber, childToDelete) {
11715 if (!shouldTrackSideEffects) {
11716 // Noop.
11717 return;
11718 }
11719 // Deletions are added in reversed order so we add it to the front.
11720 // At this point, the return fiber's effect list is empty except for
11721 // deletions, so we can just append the deletion to the list. The remaining
11722 // effects aren't added until the complete phase. Once we implement
11723 // resuming, this may not be true.
11724 var last = returnFiber.lastEffect;
11725 if (last !== null) {
11726 last.nextEffect = childToDelete;
11727 returnFiber.lastEffect = childToDelete;
11728 } else {
11729 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
11730 }
11731 childToDelete.nextEffect = null;
11732 childToDelete.effectTag = Deletion;
11733 }
11734
11735 function deleteRemainingChildren(returnFiber, currentFirstChild) {
11736 if (!shouldTrackSideEffects) {
11737 // Noop.
11738 return null;
11739 }
11740
11741 // TODO: For the shouldClone case, this could be micro-optimized a bit by
11742 // assuming that after the first child we've already added everything.
11743 var childToDelete = currentFirstChild;
11744 while (childToDelete !== null) {
11745 deleteChild(returnFiber, childToDelete);
11746 childToDelete = childToDelete.sibling;
11747 }
11748 return null;
11749 }
11750
11751 function mapRemainingChildren(returnFiber, currentFirstChild) {
11752 // Add the remaining children to a temporary map so that we can find them by
11753 // keys quickly. Implicit (null) keys get added to this set with their index
11754 var existingChildren = new Map();
11755
11756 var existingChild = currentFirstChild;
11757 while (existingChild !== null) {
11758 if (existingChild.key !== null) {
11759 existingChildren.set(existingChild.key, existingChild);
11760 } else {
11761 existingChildren.set(existingChild.index, existingChild);
11762 }
11763 existingChild = existingChild.sibling;
11764 }
11765 return existingChildren;
11766 }
11767
11768 function useFiber(fiber, pendingProps, expirationTime) {
11769 // We currently set sibling to null and index to 0 here because it is easy
11770 // to forget to do before returning it. E.g. for the single child case.
11771 var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
11772 clone.index = 0;
11773 clone.sibling = null;
11774 return clone;
11775 }
11776
11777 function placeChild(newFiber, lastPlacedIndex, newIndex) {
11778 newFiber.index = newIndex;
11779 if (!shouldTrackSideEffects) {
11780 // Noop.
11781 return lastPlacedIndex;
11782 }
11783 var current$$1 = newFiber.alternate;
11784 if (current$$1 !== null) {
11785 var oldIndex = current$$1.index;
11786 if (oldIndex < lastPlacedIndex) {
11787 // This is a move.
11788 newFiber.effectTag = Placement;
11789 return lastPlacedIndex;
11790 } else {
11791 // This item can stay in place.
11792 return oldIndex;
11793 }
11794 } else {
11795 // This is an insertion.
11796 newFiber.effectTag = Placement;
11797 return lastPlacedIndex;
11798 }
11799 }
11800
11801 function placeSingleChild(newFiber) {
11802 // This is simpler for the single child case. We only need to do a
11803 // placement for inserting new children.
11804 if (shouldTrackSideEffects && newFiber.alternate === null) {
11805 newFiber.effectTag = Placement;
11806 }
11807 return newFiber;
11808 }
11809
11810 function updateTextNode(returnFiber, current$$1, textContent, expirationTime) {
11811 if (current$$1 === null || current$$1.tag !== HostText) {
11812 // Insert
11813 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
11814 created.return = returnFiber;
11815 return created;
11816 } else {
11817 // Update
11818 var existing = useFiber(current$$1, textContent, expirationTime);
11819 existing.return = returnFiber;
11820 return existing;
11821 }
11822 }
11823
11824 function updateElement(returnFiber, current$$1, element, expirationTime) {
11825 if (current$$1 !== null && current$$1.elementType === element.type) {
11826 // Move based on index
11827 var existing = useFiber(current$$1, element.props, expirationTime);
11828 existing.ref = coerceRef(returnFiber, current$$1, element);
11829 existing.return = returnFiber;
11830 {
11831 existing._debugSource = element._source;
11832 existing._debugOwner = element._owner;
11833 }
11834 return existing;
11835 } else {
11836 // Insert
11837 var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
11838 created.ref = coerceRef(returnFiber, current$$1, element);
11839 created.return = returnFiber;
11840 return created;
11841 }
11842 }
11843
11844 function updatePortal(returnFiber, current$$1, portal, expirationTime) {
11845 if (current$$1 === null || current$$1.tag !== HostPortal || current$$1.stateNode.containerInfo !== portal.containerInfo || current$$1.stateNode.implementation !== portal.implementation) {
11846 // Insert
11847 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
11848 created.return = returnFiber;
11849 return created;
11850 } else {
11851 // Update
11852 var existing = useFiber(current$$1, portal.children || [], expirationTime);
11853 existing.return = returnFiber;
11854 return existing;
11855 }
11856 }
11857
11858 function updateFragment(returnFiber, current$$1, fragment, expirationTime, key) {
11859 if (current$$1 === null || current$$1.tag !== Fragment) {
11860 // Insert
11861 var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
11862 created.return = returnFiber;
11863 return created;
11864 } else {
11865 // Update
11866 var existing = useFiber(current$$1, fragment, expirationTime);
11867 existing.return = returnFiber;
11868 return existing;
11869 }
11870 }
11871
11872 function createChild(returnFiber, newChild, expirationTime) {
11873 if (typeof newChild === 'string' || typeof newChild === 'number') {
11874 // Text nodes don't have keys. If the previous node is implicitly keyed
11875 // we can continue to replace it without aborting even if it is not a text
11876 // node.
11877 var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
11878 created.return = returnFiber;
11879 return created;
11880 }
11881
11882 if (typeof newChild === 'object' && newChild !== null) {
11883 switch (newChild.$$typeof) {
11884 case REACT_ELEMENT_TYPE:
11885 {
11886 var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
11887 _created.ref = coerceRef(returnFiber, null, newChild);
11888 _created.return = returnFiber;
11889 return _created;
11890 }
11891 case REACT_PORTAL_TYPE:
11892 {
11893 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
11894 _created2.return = returnFiber;
11895 return _created2;
11896 }
11897 }
11898
11899 if (isArray(newChild) || getIteratorFn(newChild)) {
11900 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
11901 _created3.return = returnFiber;
11902 return _created3;
11903 }
11904
11905 throwOnInvalidObjectType(returnFiber, newChild);
11906 }
11907
11908 {
11909 if (typeof newChild === 'function') {
11910 warnOnFunctionType();
11911 }
11912 }
11913
11914 return null;
11915 }
11916
11917 function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
11918 // Update the fiber if the keys match, otherwise return null.
11919
11920 var key = oldFiber !== null ? oldFiber.key : null;
11921
11922 if (typeof newChild === 'string' || typeof newChild === 'number') {
11923 // Text nodes don't have keys. If the previous node is implicitly keyed
11924 // we can continue to replace it without aborting even if it is not a text
11925 // node.
11926 if (key !== null) {
11927 return null;
11928 }
11929 return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
11930 }
11931
11932 if (typeof newChild === 'object' && newChild !== null) {
11933 switch (newChild.$$typeof) {
11934 case REACT_ELEMENT_TYPE:
11935 {
11936 if (newChild.key === key) {
11937 if (newChild.type === REACT_FRAGMENT_TYPE) {
11938 return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
11939 }
11940 return updateElement(returnFiber, oldFiber, newChild, expirationTime);
11941 } else {
11942 return null;
11943 }
11944 }
11945 case REACT_PORTAL_TYPE:
11946 {
11947 if (newChild.key === key) {
11948 return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
11949 } else {
11950 return null;
11951 }
11952 }
11953 }
11954
11955 if (isArray(newChild) || getIteratorFn(newChild)) {
11956 if (key !== null) {
11957 return null;
11958 }
11959
11960 return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
11961 }
11962
11963 throwOnInvalidObjectType(returnFiber, newChild);
11964 }
11965
11966 {
11967 if (typeof newChild === 'function') {
11968 warnOnFunctionType();
11969 }
11970 }
11971
11972 return null;
11973 }
11974
11975 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
11976 if (typeof newChild === 'string' || typeof newChild === 'number') {
11977 // Text nodes don't have keys, so we neither have to check the old nor
11978 // new node for the key. If both are text nodes, they match.
11979 var matchedFiber = existingChildren.get(newIdx) || null;
11980 return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
11981 }
11982
11983 if (typeof newChild === 'object' && newChild !== null) {
11984 switch (newChild.$$typeof) {
11985 case REACT_ELEMENT_TYPE:
11986 {
11987 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
11988 if (newChild.type === REACT_FRAGMENT_TYPE) {
11989 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
11990 }
11991 return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
11992 }
11993 case REACT_PORTAL_TYPE:
11994 {
11995 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
11996 return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
11997 }
11998 }
11999
12000 if (isArray(newChild) || getIteratorFn(newChild)) {
12001 var _matchedFiber3 = existingChildren.get(newIdx) || null;
12002 return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
12003 }
12004
12005 throwOnInvalidObjectType(returnFiber, newChild);
12006 }
12007
12008 {
12009 if (typeof newChild === 'function') {
12010 warnOnFunctionType();
12011 }
12012 }
12013
12014 return null;
12015 }
12016
12017 /**
12018 * Warns if there is a duplicate or missing key
12019 */
12020 function warnOnInvalidKey(child, knownKeys) {
12021 {
12022 if (typeof child !== 'object' || child === null) {
12023 return knownKeys;
12024 }
12025 switch (child.$$typeof) {
12026 case REACT_ELEMENT_TYPE:
12027 case REACT_PORTAL_TYPE:
12028 warnForMissingKey(child);
12029 var key = child.key;
12030 if (typeof key !== 'string') {
12031 break;
12032 }
12033 if (knownKeys === null) {
12034 knownKeys = new Set();
12035 knownKeys.add(key);
12036 break;
12037 }
12038 if (!knownKeys.has(key)) {
12039 knownKeys.add(key);
12040 break;
12041 }
12042 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);
12043 break;
12044 default:
12045 break;
12046 }
12047 }
12048 return knownKeys;
12049 }
12050
12051 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
12052 // This algorithm can't optimize by searching from boths ends since we
12053 // don't have backpointers on fibers. I'm trying to see how far we can get
12054 // with that model. If it ends up not being worth the tradeoffs, we can
12055 // add it later.
12056
12057 // Even with a two ended optimization, we'd want to optimize for the case
12058 // where there are few changes and brute force the comparison instead of
12059 // going for the Map. It'd like to explore hitting that path first in
12060 // forward-only mode and only go for the Map once we notice that we need
12061 // lots of look ahead. This doesn't handle reversal as well as two ended
12062 // search but that's unusual. Besides, for the two ended optimization to
12063 // work on Iterables, we'd need to copy the whole set.
12064
12065 // In this first iteration, we'll just live with hitting the bad case
12066 // (adding everything to a Map) in for every insert/move.
12067
12068 // If you change this code, also update reconcileChildrenIterator() which
12069 // uses the same algorithm.
12070
12071 {
12072 // First, validate keys.
12073 var knownKeys = null;
12074 for (var i = 0; i < newChildren.length; i++) {
12075 var child = newChildren[i];
12076 knownKeys = warnOnInvalidKey(child, knownKeys);
12077 }
12078 }
12079
12080 var resultingFirstChild = null;
12081 var previousNewFiber = null;
12082
12083 var oldFiber = currentFirstChild;
12084 var lastPlacedIndex = 0;
12085 var newIdx = 0;
12086 var nextOldFiber = null;
12087 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
12088 if (oldFiber.index > newIdx) {
12089 nextOldFiber = oldFiber;
12090 oldFiber = null;
12091 } else {
12092 nextOldFiber = oldFiber.sibling;
12093 }
12094 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
12095 if (newFiber === null) {
12096 // TODO: This breaks on empty slots like null children. That's
12097 // unfortunate because it triggers the slow path all the time. We need
12098 // a better way to communicate whether this was a miss or null,
12099 // boolean, undefined, etc.
12100 if (oldFiber === null) {
12101 oldFiber = nextOldFiber;
12102 }
12103 break;
12104 }
12105 if (shouldTrackSideEffects) {
12106 if (oldFiber && newFiber.alternate === null) {
12107 // We matched the slot, but we didn't reuse the existing fiber, so we
12108 // need to delete the existing child.
12109 deleteChild(returnFiber, oldFiber);
12110 }
12111 }
12112 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
12113 if (previousNewFiber === null) {
12114 // TODO: Move out of the loop. This only happens for the first run.
12115 resultingFirstChild = newFiber;
12116 } else {
12117 // TODO: Defer siblings if we're not at the right index for this slot.
12118 // I.e. if we had null values before, then we want to defer this
12119 // for each null value. However, we also don't want to call updateSlot
12120 // with the previous one.
12121 previousNewFiber.sibling = newFiber;
12122 }
12123 previousNewFiber = newFiber;
12124 oldFiber = nextOldFiber;
12125 }
12126
12127 if (newIdx === newChildren.length) {
12128 // We've reached the end of the new children. We can delete the rest.
12129 deleteRemainingChildren(returnFiber, oldFiber);
12130 return resultingFirstChild;
12131 }
12132
12133 if (oldFiber === null) {
12134 // If we don't have any more existing children we can choose a fast path
12135 // since the rest will all be insertions.
12136 for (; newIdx < newChildren.length; newIdx++) {
12137 var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
12138 if (!_newFiber) {
12139 continue;
12140 }
12141 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
12142 if (previousNewFiber === null) {
12143 // TODO: Move out of the loop. This only happens for the first run.
12144 resultingFirstChild = _newFiber;
12145 } else {
12146 previousNewFiber.sibling = _newFiber;
12147 }
12148 previousNewFiber = _newFiber;
12149 }
12150 return resultingFirstChild;
12151 }
12152
12153 // Add all children to a key map for quick lookups.
12154 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
12155
12156 // Keep scanning and use the map to restore deleted items as moves.
12157 for (; newIdx < newChildren.length; newIdx++) {
12158 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
12159 if (_newFiber2) {
12160 if (shouldTrackSideEffects) {
12161 if (_newFiber2.alternate !== null) {
12162 // The new fiber is a work in progress, but if there exists a
12163 // current, that means that we reused the fiber. We need to delete
12164 // it from the child list so that we don't add it to the deletion
12165 // list.
12166 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
12167 }
12168 }
12169 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
12170 if (previousNewFiber === null) {
12171 resultingFirstChild = _newFiber2;
12172 } else {
12173 previousNewFiber.sibling = _newFiber2;
12174 }
12175 previousNewFiber = _newFiber2;
12176 }
12177 }
12178
12179 if (shouldTrackSideEffects) {
12180 // Any existing children that weren't consumed above were deleted. We need
12181 // to add them to the deletion list.
12182 existingChildren.forEach(function (child) {
12183 return deleteChild(returnFiber, child);
12184 });
12185 }
12186
12187 return resultingFirstChild;
12188 }
12189
12190 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
12191 // This is the same implementation as reconcileChildrenArray(),
12192 // but using the iterator instead.
12193
12194 var iteratorFn = getIteratorFn(newChildrenIterable);
12195 !(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;
12196
12197 {
12198 // We don't support rendering Generators because it's a mutation.
12199 // See https://github.com/facebook/react/issues/12995
12200 if (typeof Symbol === 'function' &&
12201 // $FlowFixMe Flow doesn't know about toStringTag
12202 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
12203 !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;
12204 didWarnAboutGenerators = true;
12205 }
12206
12207 // Warn about using Maps as children
12208 if (newChildrenIterable.entries === iteratorFn) {
12209 !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;
12210 didWarnAboutMaps = true;
12211 }
12212
12213 // First, validate keys.
12214 // We'll get a different iterator later for the main pass.
12215 var _newChildren = iteratorFn.call(newChildrenIterable);
12216 if (_newChildren) {
12217 var knownKeys = null;
12218 var _step = _newChildren.next();
12219 for (; !_step.done; _step = _newChildren.next()) {
12220 var child = _step.value;
12221 knownKeys = warnOnInvalidKey(child, knownKeys);
12222 }
12223 }
12224 }
12225
12226 var newChildren = iteratorFn.call(newChildrenIterable);
12227 !(newChildren != null) ? invariant(false, 'An iterable object provided no iterator.') : void 0;
12228
12229 var resultingFirstChild = null;
12230 var previousNewFiber = null;
12231
12232 var oldFiber = currentFirstChild;
12233 var lastPlacedIndex = 0;
12234 var newIdx = 0;
12235 var nextOldFiber = null;
12236
12237 var step = newChildren.next();
12238 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
12239 if (oldFiber.index > newIdx) {
12240 nextOldFiber = oldFiber;
12241 oldFiber = null;
12242 } else {
12243 nextOldFiber = oldFiber.sibling;
12244 }
12245 var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
12246 if (newFiber === null) {
12247 // TODO: This breaks on empty slots like null children. That's
12248 // unfortunate because it triggers the slow path all the time. We need
12249 // a better way to communicate whether this was a miss or null,
12250 // boolean, undefined, etc.
12251 if (!oldFiber) {
12252 oldFiber = nextOldFiber;
12253 }
12254 break;
12255 }
12256 if (shouldTrackSideEffects) {
12257 if (oldFiber && newFiber.alternate === null) {
12258 // We matched the slot, but we didn't reuse the existing fiber, so we
12259 // need to delete the existing child.
12260 deleteChild(returnFiber, oldFiber);
12261 }
12262 }
12263 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
12264 if (previousNewFiber === null) {
12265 // TODO: Move out of the loop. This only happens for the first run.
12266 resultingFirstChild = newFiber;
12267 } else {
12268 // TODO: Defer siblings if we're not at the right index for this slot.
12269 // I.e. if we had null values before, then we want to defer this
12270 // for each null value. However, we also don't want to call updateSlot
12271 // with the previous one.
12272 previousNewFiber.sibling = newFiber;
12273 }
12274 previousNewFiber = newFiber;
12275 oldFiber = nextOldFiber;
12276 }
12277
12278 if (step.done) {
12279 // We've reached the end of the new children. We can delete the rest.
12280 deleteRemainingChildren(returnFiber, oldFiber);
12281 return resultingFirstChild;
12282 }
12283
12284 if (oldFiber === null) {
12285 // If we don't have any more existing children we can choose a fast path
12286 // since the rest will all be insertions.
12287 for (; !step.done; newIdx++, step = newChildren.next()) {
12288 var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
12289 if (_newFiber3 === null) {
12290 continue;
12291 }
12292 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
12293 if (previousNewFiber === null) {
12294 // TODO: Move out of the loop. This only happens for the first run.
12295 resultingFirstChild = _newFiber3;
12296 } else {
12297 previousNewFiber.sibling = _newFiber3;
12298 }
12299 previousNewFiber = _newFiber3;
12300 }
12301 return resultingFirstChild;
12302 }
12303
12304 // Add all children to a key map for quick lookups.
12305 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
12306
12307 // Keep scanning and use the map to restore deleted items as moves.
12308 for (; !step.done; newIdx++, step = newChildren.next()) {
12309 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
12310 if (_newFiber4 !== null) {
12311 if (shouldTrackSideEffects) {
12312 if (_newFiber4.alternate !== null) {
12313 // The new fiber is a work in progress, but if there exists a
12314 // current, that means that we reused the fiber. We need to delete
12315 // it from the child list so that we don't add it to the deletion
12316 // list.
12317 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
12318 }
12319 }
12320 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
12321 if (previousNewFiber === null) {
12322 resultingFirstChild = _newFiber4;
12323 } else {
12324 previousNewFiber.sibling = _newFiber4;
12325 }
12326 previousNewFiber = _newFiber4;
12327 }
12328 }
12329
12330 if (shouldTrackSideEffects) {
12331 // Any existing children that weren't consumed above were deleted. We need
12332 // to add them to the deletion list.
12333 existingChildren.forEach(function (child) {
12334 return deleteChild(returnFiber, child);
12335 });
12336 }
12337
12338 return resultingFirstChild;
12339 }
12340
12341 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
12342 // There's no need to check for keys on text nodes since we don't have a
12343 // way to define them.
12344 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
12345 // We already have an existing node so let's just update it and delete
12346 // the rest.
12347 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
12348 var existing = useFiber(currentFirstChild, textContent, expirationTime);
12349 existing.return = returnFiber;
12350 return existing;
12351 }
12352 // The existing first child is not a text node so we need to create one
12353 // and delete the existing ones.
12354 deleteRemainingChildren(returnFiber, currentFirstChild);
12355 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
12356 created.return = returnFiber;
12357 return created;
12358 }
12359
12360 function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
12361 var key = element.key;
12362 var child = currentFirstChild;
12363 while (child !== null) {
12364 // TODO: If key === null and child.key === null, then this only applies to
12365 // the first item in the list.
12366 if (child.key === key) {
12367 if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.elementType === element.type) {
12368 deleteRemainingChildren(returnFiber, child.sibling);
12369 var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
12370 existing.ref = coerceRef(returnFiber, child, element);
12371 existing.return = returnFiber;
12372 {
12373 existing._debugSource = element._source;
12374 existing._debugOwner = element._owner;
12375 }
12376 return existing;
12377 } else {
12378 deleteRemainingChildren(returnFiber, child);
12379 break;
12380 }
12381 } else {
12382 deleteChild(returnFiber, child);
12383 }
12384 child = child.sibling;
12385 }
12386
12387 if (element.type === REACT_FRAGMENT_TYPE) {
12388 var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
12389 created.return = returnFiber;
12390 return created;
12391 } else {
12392 var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
12393 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
12394 _created4.return = returnFiber;
12395 return _created4;
12396 }
12397 }
12398
12399 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
12400 var key = portal.key;
12401 var child = currentFirstChild;
12402 while (child !== null) {
12403 // TODO: If key === null and child.key === null, then this only applies to
12404 // the first item in the list.
12405 if (child.key === key) {
12406 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
12407 deleteRemainingChildren(returnFiber, child.sibling);
12408 var existing = useFiber(child, portal.children || [], expirationTime);
12409 existing.return = returnFiber;
12410 return existing;
12411 } else {
12412 deleteRemainingChildren(returnFiber, child);
12413 break;
12414 }
12415 } else {
12416 deleteChild(returnFiber, child);
12417 }
12418 child = child.sibling;
12419 }
12420
12421 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
12422 created.return = returnFiber;
12423 return created;
12424 }
12425
12426 // This API will tag the children with the side-effect of the reconciliation
12427 // itself. They will be added to the side-effect list as we pass through the
12428 // children and the parent.
12429 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
12430 // This function is not recursive.
12431 // If the top level item is an array, we treat it as a set of children,
12432 // not as a fragment. Nested arrays on the other hand will be treated as
12433 // fragment nodes. Recursion happens at the normal flow.
12434
12435 // Handle top level unkeyed fragments as if they were arrays.
12436 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
12437 // We treat the ambiguous cases above the same.
12438 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
12439 if (isUnkeyedTopLevelFragment) {
12440 newChild = newChild.props.children;
12441 }
12442
12443 // Handle object types
12444 var isObject = typeof newChild === 'object' && newChild !== null;
12445
12446 if (isObject) {
12447 switch (newChild.$$typeof) {
12448 case REACT_ELEMENT_TYPE:
12449 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
12450 case REACT_PORTAL_TYPE:
12451 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
12452 }
12453 }
12454
12455 if (typeof newChild === 'string' || typeof newChild === 'number') {
12456 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
12457 }
12458
12459 if (isArray(newChild)) {
12460 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
12461 }
12462
12463 if (getIteratorFn(newChild)) {
12464 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
12465 }
12466
12467 if (isObject) {
12468 throwOnInvalidObjectType(returnFiber, newChild);
12469 }
12470
12471 {
12472 if (typeof newChild === 'function') {
12473 warnOnFunctionType();
12474 }
12475 }
12476 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
12477 // If the new child is undefined, and the return fiber is a composite
12478 // component, throw an error. If Fiber return types are disabled,
12479 // we already threw above.
12480 switch (returnFiber.tag) {
12481 case ClassComponent:
12482 {
12483 {
12484 var instance = returnFiber.stateNode;
12485 if (instance.render._isMockFunction) {
12486 // We allow auto-mocks to proceed as if they're returning null.
12487 break;
12488 }
12489 }
12490 }
12491 // Intentionally fall through to the next case, which handles both
12492 // functions and classes
12493 // eslint-disable-next-lined no-fallthrough
12494 case FunctionComponent:
12495 {
12496 var Component = returnFiber.type;
12497 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');
12498 }
12499 }
12500 }
12501
12502 // Remaining cases are all treated as empty.
12503 return deleteRemainingChildren(returnFiber, currentFirstChild);
12504 }
12505
12506 return reconcileChildFibers;
12507}
12508
12509var reconcileChildFibers = ChildReconciler(true);
12510var mountChildFibers = ChildReconciler(false);
12511
12512function cloneChildFibers(current$$1, workInProgress) {
12513 !(current$$1 === null || workInProgress.child === current$$1.child) ? invariant(false, 'Resuming work not yet implemented.') : void 0;
12514
12515 if (workInProgress.child === null) {
12516 return;
12517 }
12518
12519 var currentChild = workInProgress.child;
12520 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
12521 workInProgress.child = newChild;
12522
12523 newChild.return = workInProgress;
12524 while (currentChild.sibling !== null) {
12525 currentChild = currentChild.sibling;
12526 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
12527 newChild.return = workInProgress;
12528 }
12529 newChild.sibling = null;
12530}
12531
12532var NO_CONTEXT = {};
12533
12534var contextStackCursor$1 = createCursor(NO_CONTEXT);
12535var contextFiberStackCursor = createCursor(NO_CONTEXT);
12536var rootInstanceStackCursor = createCursor(NO_CONTEXT);
12537
12538function requiredContext(c) {
12539 !(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;
12540 return c;
12541}
12542
12543function getRootHostContainer() {
12544 var rootInstance = requiredContext(rootInstanceStackCursor.current);
12545 return rootInstance;
12546}
12547
12548function pushHostContainer(fiber, nextRootInstance) {
12549 // Push current root instance onto the stack;
12550 // This allows us to reset root when portals are popped.
12551 push(rootInstanceStackCursor, nextRootInstance, fiber);
12552 // Track the context and the Fiber that provided it.
12553 // This enables us to pop only Fibers that provide unique contexts.
12554 push(contextFiberStackCursor, fiber, fiber);
12555
12556 // Finally, we need to push the host context to the stack.
12557 // However, we can't just call getRootHostContext() and push it because
12558 // we'd have a different number of entries on the stack depending on
12559 // whether getRootHostContext() throws somewhere in renderer code or not.
12560 // So we push an empty value first. This lets us safely unwind on errors.
12561 push(contextStackCursor$1, NO_CONTEXT, fiber);
12562 var nextRootContext = getRootHostContext(nextRootInstance);
12563 // Now that we know this function doesn't throw, replace it.
12564 pop(contextStackCursor$1, fiber);
12565 push(contextStackCursor$1, nextRootContext, fiber);
12566}
12567
12568function popHostContainer(fiber) {
12569 pop(contextStackCursor$1, fiber);
12570 pop(contextFiberStackCursor, fiber);
12571 pop(rootInstanceStackCursor, fiber);
12572}
12573
12574function getHostContext() {
12575 var context = requiredContext(contextStackCursor$1.current);
12576 return context;
12577}
12578
12579function pushHostContext(fiber) {
12580 var rootInstance = requiredContext(rootInstanceStackCursor.current);
12581 var context = requiredContext(contextStackCursor$1.current);
12582 var nextContext = getChildHostContext(context, fiber.type, rootInstance);
12583
12584 // Don't push this Fiber's context unless it's unique.
12585 if (context === nextContext) {
12586 return;
12587 }
12588
12589 // Track the context and the Fiber that provided it.
12590 // This enables us to pop only Fibers that provide unique contexts.
12591 push(contextFiberStackCursor, fiber, fiber);
12592 push(contextStackCursor$1, nextContext, fiber);
12593}
12594
12595function popHostContext(fiber) {
12596 // Do not pop unless this Fiber provided the current context.
12597 // pushHostContext() only pushes Fibers that provide unique contexts.
12598 if (contextFiberStackCursor.current !== fiber) {
12599 return;
12600 }
12601
12602 pop(contextStackCursor$1, fiber);
12603 pop(contextFiberStackCursor, fiber);
12604}
12605
12606var NoEffect$1 = /* */0;
12607var UnmountSnapshot = /* */2;
12608var UnmountMutation = /* */4;
12609var MountMutation = /* */8;
12610var UnmountLayout = /* */16;
12611var MountLayout = /* */32;
12612var MountPassive = /* */64;
12613var UnmountPassive = /* */128;
12614
12615var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
12616
12617
12618var didWarnAboutMismatchedHooksForComponent = void 0;
12619{
12620 didWarnAboutMismatchedHooksForComponent = new Set();
12621}
12622
12623// These are set right before calling the component.
12624var renderExpirationTime = NoWork;
12625// The work-in-progress fiber. I've named it differently to distinguish it from
12626// the work-in-progress hook.
12627var currentlyRenderingFiber$1 = null;
12628
12629// Hooks are stored as a linked list on the fiber's memoizedState field. The
12630// current hook list is the list that belongs to the current fiber. The
12631// work-in-progress hook list is a new list that will be added to the
12632// work-in-progress fiber.
12633var firstCurrentHook = null;
12634var currentHook = null;
12635var nextCurrentHook = null;
12636var firstWorkInProgressHook = null;
12637var workInProgressHook = null;
12638var nextWorkInProgressHook = null;
12639
12640var remainingExpirationTime = NoWork;
12641var componentUpdateQueue = null;
12642var sideEffectTag = 0;
12643
12644// Updates scheduled during render will trigger an immediate re-render at the
12645// end of the current pass. We can't store these updates on the normal queue,
12646// because if the work is aborted, they should be discarded. Because this is
12647// a relatively rare case, we also don't want to add an additional field to
12648// either the hook or queue object types. So we store them in a lazily create
12649// map of queue -> render-phase updates, which are discarded once the component
12650// completes without re-rendering.
12651
12652// Whether an update was scheduled during the currently executing render pass.
12653var didScheduleRenderPhaseUpdate = false;
12654// Lazily created map of render-phase updates
12655var renderPhaseUpdates = null;
12656// Counter to prevent infinite loops.
12657var numberOfReRenders = 0;
12658var RE_RENDER_LIMIT = 25;
12659
12660// In DEV, this is the name of the currently executing primitive hook
12661var currentHookNameInDev = null;
12662
12663function warnOnHookMismatchInDev() {
12664 {
12665 var componentName = getComponentName(currentlyRenderingFiber$1.type);
12666 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
12667 didWarnAboutMismatchedHooksForComponent.add(componentName);
12668
12669 var secondColumnStart = 22;
12670
12671 var table = '';
12672 var prevHook = firstCurrentHook;
12673 var nextHook = firstWorkInProgressHook;
12674 var n = 1;
12675 while (prevHook !== null && nextHook !== null) {
12676 var oldHookName = prevHook._debugType;
12677 var newHookName = nextHook._debugType;
12678
12679 var row = n + '. ' + oldHookName;
12680
12681 // Extra space so second column lines up
12682 // lol @ IE not supporting String#repeat
12683 while (row.length < secondColumnStart) {
12684 row += ' ';
12685 }
12686
12687 row += newHookName + '\n';
12688
12689 table += row;
12690 prevHook = prevHook.next;
12691 nextHook = nextHook.next;
12692 n++;
12693 }
12694
12695 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);
12696 }
12697 }
12698}
12699
12700function throwInvalidHookError() {
12701 invariant(false, 'Hooks can only be called inside the body of a function component. (https://fb.me/react-invalid-hook-call)');
12702}
12703
12704function areHookInputsEqual(nextDeps, prevDeps) {
12705 if (prevDeps === null) {
12706 {
12707 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);
12708 }
12709 return false;
12710 }
12711
12712 {
12713 // Don't bother comparing lengths in prod because these arrays should be
12714 // passed inline.
12715 if (nextDeps.length !== prevDeps.length) {
12716 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(', ') + ']');
12717 }
12718 }
12719 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
12720 if (is(nextDeps[i], prevDeps[i])) {
12721 continue;
12722 }
12723 return false;
12724 }
12725 return true;
12726}
12727
12728function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) {
12729 renderExpirationTime = nextRenderExpirationTime;
12730 currentlyRenderingFiber$1 = workInProgress;
12731 firstCurrentHook = nextCurrentHook = current !== null ? current.memoizedState : null;
12732
12733 // The following should have already been reset
12734 // currentHook = null;
12735 // workInProgressHook = null;
12736
12737 // remainingExpirationTime = NoWork;
12738 // componentUpdateQueue = null;
12739
12740 // didScheduleRenderPhaseUpdate = false;
12741 // renderPhaseUpdates = null;
12742 // numberOfReRenders = 0;
12743 // sideEffectTag = 0;
12744
12745 {
12746 ReactCurrentDispatcher$1.current = nextCurrentHook === null ? HooksDispatcherOnMountInDEV : HooksDispatcherOnUpdateInDEV;
12747 }
12748
12749 var children = Component(props, refOrContext);
12750
12751 if (didScheduleRenderPhaseUpdate) {
12752 do {
12753 didScheduleRenderPhaseUpdate = false;
12754 numberOfReRenders += 1;
12755
12756 // Start over from the beginning of the list
12757 firstCurrentHook = nextCurrentHook = current !== null ? current.memoizedState : null;
12758 nextWorkInProgressHook = firstWorkInProgressHook;
12759
12760 currentHook = null;
12761 workInProgressHook = null;
12762 componentUpdateQueue = null;
12763
12764 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
12765
12766 children = Component(props, refOrContext);
12767 } while (didScheduleRenderPhaseUpdate);
12768
12769 renderPhaseUpdates = null;
12770 numberOfReRenders = 0;
12771 }
12772
12773 {
12774 currentHookNameInDev = null;
12775 }
12776
12777 // We can assume the previous dispatcher is always this one, since we set it
12778 // at the beginning of the render phase and there's no re-entrancy.
12779 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
12780
12781 var renderedWork = currentlyRenderingFiber$1;
12782
12783 renderedWork.memoizedState = firstWorkInProgressHook;
12784 renderedWork.expirationTime = remainingExpirationTime;
12785 renderedWork.updateQueue = componentUpdateQueue;
12786 renderedWork.effectTag |= sideEffectTag;
12787
12788 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
12789
12790 renderExpirationTime = NoWork;
12791 currentlyRenderingFiber$1 = null;
12792
12793 firstCurrentHook = null;
12794 currentHook = null;
12795 nextCurrentHook = null;
12796 firstWorkInProgressHook = null;
12797 workInProgressHook = null;
12798 nextWorkInProgressHook = null;
12799
12800 remainingExpirationTime = NoWork;
12801 componentUpdateQueue = null;
12802 sideEffectTag = 0;
12803
12804 // These were reset above
12805 // didScheduleRenderPhaseUpdate = false;
12806 // renderPhaseUpdates = null;
12807 // numberOfReRenders = 0;
12808
12809 !!didRenderTooFewHooks ? invariant(false, 'Rendered fewer hooks than expected. This may be caused by an accidental early return statement.') : void 0;
12810
12811 return children;
12812}
12813
12814function bailoutHooks(current, workInProgress, expirationTime) {
12815 workInProgress.updateQueue = current.updateQueue;
12816 workInProgress.effectTag &= ~(Passive | Update);
12817 if (current.expirationTime <= expirationTime) {
12818 current.expirationTime = NoWork;
12819 }
12820}
12821
12822function resetHooks() {
12823 // We can assume the previous dispatcher is always this one, since we set it
12824 // at the beginning of the render phase and there's no re-entrancy.
12825 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
12826
12827 // This is used to reset the state of this module when a component throws.
12828 // It's also called inside mountIndeterminateComponent if we determine the
12829 // component is a module-style component.
12830 renderExpirationTime = NoWork;
12831 currentlyRenderingFiber$1 = null;
12832
12833 firstCurrentHook = null;
12834 currentHook = null;
12835 nextCurrentHook = null;
12836 firstWorkInProgressHook = null;
12837 workInProgressHook = null;
12838 nextWorkInProgressHook = null;
12839
12840 remainingExpirationTime = NoWork;
12841 componentUpdateQueue = null;
12842 sideEffectTag = 0;
12843
12844 {
12845 currentHookNameInDev = null;
12846 }
12847
12848 didScheduleRenderPhaseUpdate = false;
12849 renderPhaseUpdates = null;
12850 numberOfReRenders = 0;
12851}
12852
12853function mountWorkInProgressHook() {
12854 var hook = {
12855 memoizedState: null,
12856
12857 baseState: null,
12858 queue: null,
12859 baseUpdate: null,
12860
12861 next: null
12862 };
12863
12864 {
12865 hook._debugType = currentHookNameInDev;
12866 if (currentlyRenderingFiber$1 !== null && currentlyRenderingFiber$1.alternate !== null) {
12867 warning$1(false, '%s: Rendered more hooks than during the previous render. This is ' + 'not currently supported and may lead to unexpected behavior.', getComponentName(currentlyRenderingFiber$1.type));
12868 }
12869 }
12870 if (workInProgressHook === null) {
12871 // This is the first hook in the list
12872 firstWorkInProgressHook = workInProgressHook = hook;
12873 } else {
12874 // Append to the end of the list
12875 workInProgressHook = workInProgressHook.next = hook;
12876 }
12877 return workInProgressHook;
12878}
12879
12880function updateWorkInProgressHook() {
12881 // This function is used both for updates and for re-renders triggered by a
12882 // render phase update. It assumes there is either a current hook we can
12883 // clone, or a work-in-progress hook from a previous render pass that we can
12884 // use as a base. When we reach the end of the base list, we must switch to
12885 // the dispatcher used for mounts.
12886 if (nextWorkInProgressHook !== null) {
12887 // There's already a work-in-progress. Reuse it.
12888 workInProgressHook = nextWorkInProgressHook;
12889 nextWorkInProgressHook = workInProgressHook.next;
12890
12891 currentHook = nextCurrentHook;
12892 nextCurrentHook = currentHook !== null ? currentHook.next : null;
12893 } else {
12894 // Clone from the current hook.
12895 !(nextCurrentHook !== null) ? invariant(false, 'Rendered more hooks than during the previous render.') : void 0;
12896 currentHook = nextCurrentHook;
12897
12898 var newHook = {
12899 memoizedState: currentHook.memoizedState,
12900
12901 baseState: currentHook.baseState,
12902 queue: currentHook.queue,
12903 baseUpdate: currentHook.baseUpdate,
12904
12905 next: null
12906 };
12907
12908 if (workInProgressHook === null) {
12909 // This is the first hook in the list.
12910 workInProgressHook = firstWorkInProgressHook = newHook;
12911 } else {
12912 // Append to the end of the list.
12913 workInProgressHook = workInProgressHook.next = newHook;
12914 }
12915 nextCurrentHook = currentHook.next;
12916
12917 {
12918 newHook._debugType = currentHookNameInDev;
12919 if (currentHookNameInDev !== currentHook._debugType) {
12920 warnOnHookMismatchInDev();
12921 }
12922 }
12923 }
12924 return workInProgressHook;
12925}
12926
12927function createFunctionComponentUpdateQueue() {
12928 return {
12929 lastEffect: null
12930 };
12931}
12932
12933function basicStateReducer(state, action) {
12934 return typeof action === 'function' ? action(state) : action;
12935}
12936
12937function mountContext(context, observedBits) {
12938 {
12939 mountWorkInProgressHook();
12940 }
12941 return readContext(context, observedBits);
12942}
12943
12944function updateContext(context, observedBits) {
12945 {
12946 updateWorkInProgressHook();
12947 }
12948 return readContext(context, observedBits);
12949}
12950
12951function mountReducer(reducer, initialArg, init) {
12952 var hook = mountWorkInProgressHook();
12953 var initialState = void 0;
12954 if (init !== undefined) {
12955 initialState = init(initialArg);
12956 } else {
12957 initialState = initialArg;
12958 }
12959 hook.memoizedState = hook.baseState = initialState;
12960 var queue = hook.queue = {
12961 last: null,
12962 dispatch: null,
12963 eagerReducer: reducer,
12964 eagerState: initialState
12965 };
12966 var dispatch = queue.dispatch = dispatchAction.bind(null,
12967 // Flow doesn't know this is non-null, but we do.
12968 currentlyRenderingFiber$1, queue);
12969 return [hook.memoizedState, dispatch];
12970}
12971
12972function updateReducer(reducer, initialArg, init) {
12973 var hook = updateWorkInProgressHook();
12974 var queue = hook.queue;
12975 !(queue !== null) ? invariant(false, 'Should have a queue. This is likely a bug in React. Please file an issue.') : void 0;
12976
12977 if (numberOfReRenders > 0) {
12978 // This is a re-render. Apply the new render phase updates to the previous
12979 var _dispatch = queue.dispatch;
12980 if (renderPhaseUpdates !== null) {
12981 // Render phase updates are stored in a map of queue -> linked list
12982 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
12983 if (firstRenderPhaseUpdate !== undefined) {
12984 renderPhaseUpdates.delete(queue);
12985 var newState = hook.memoizedState;
12986 var update = firstRenderPhaseUpdate;
12987 do {
12988 // Process this render phase update. We don't have to check the
12989 // priority because it will always be the same as the current
12990 // render's.
12991 var _action = update.action;
12992 newState = reducer(newState, _action);
12993 update = update.next;
12994 } while (update !== null);
12995
12996 // Mark that the fiber performed work, but only if the new state is
12997 // different from the current state.
12998 if (!is(newState, hook.memoizedState)) {
12999 markWorkInProgressReceivedUpdate();
13000 }
13001
13002 hook.memoizedState = newState;
13003
13004 // Don't persist the state accumlated from the render phase updates to
13005 // the base state unless the queue is empty.
13006 // TODO: Not sure if this is the desired semantics, but it's what we
13007 // do for gDSFP. I can't remember why.
13008 if (hook.baseUpdate === queue.last) {
13009 hook.baseState = newState;
13010 }
13011
13012 return [newState, _dispatch];
13013 }
13014 }
13015 return [hook.memoizedState, _dispatch];
13016 }
13017
13018 // The last update in the entire queue
13019 var last = queue.last;
13020 // The last update that is part of the base state.
13021 var baseUpdate = hook.baseUpdate;
13022 var baseState = hook.baseState;
13023
13024 // Find the first unprocessed update.
13025 var first = void 0;
13026 if (baseUpdate !== null) {
13027 if (last !== null) {
13028 // For the first update, the queue is a circular linked list where
13029 // `queue.last.next = queue.first`. Once the first update commits, and
13030 // the `baseUpdate` is no longer empty, we can unravel the list.
13031 last.next = null;
13032 }
13033 first = baseUpdate.next;
13034 } else {
13035 first = last !== null ? last.next : null;
13036 }
13037 if (first !== null) {
13038 var _newState = baseState;
13039 var newBaseState = null;
13040 var newBaseUpdate = null;
13041 var prevUpdate = baseUpdate;
13042 var _update = first;
13043 var didSkip = false;
13044 do {
13045 var updateExpirationTime = _update.expirationTime;
13046 if (updateExpirationTime < renderExpirationTime) {
13047 // Priority is insufficient. Skip this update. If this is the first
13048 // skipped update, the previous update/state is the new base
13049 // update/state.
13050 if (!didSkip) {
13051 didSkip = true;
13052 newBaseUpdate = prevUpdate;
13053 newBaseState = _newState;
13054 }
13055 // Update the remaining priority in the queue.
13056 if (updateExpirationTime > remainingExpirationTime) {
13057 remainingExpirationTime = updateExpirationTime;
13058 }
13059 } else {
13060 // Process this update.
13061 if (_update.eagerReducer === reducer) {
13062 // If this update was processed eagerly, and its reducer matches the
13063 // current reducer, we can use the eagerly computed state.
13064 _newState = _update.eagerState;
13065 } else {
13066 var _action2 = _update.action;
13067 _newState = reducer(_newState, _action2);
13068 }
13069 }
13070 prevUpdate = _update;
13071 _update = _update.next;
13072 } while (_update !== null && _update !== first);
13073
13074 if (!didSkip) {
13075 newBaseUpdate = prevUpdate;
13076 newBaseState = _newState;
13077 }
13078
13079 // Mark that the fiber performed work, but only if the new state is
13080 // different from the current state.
13081 if (!is(_newState, hook.memoizedState)) {
13082 markWorkInProgressReceivedUpdate();
13083 }
13084
13085 hook.memoizedState = _newState;
13086 hook.baseUpdate = newBaseUpdate;
13087 hook.baseState = newBaseState;
13088
13089 queue.eagerReducer = reducer;
13090 queue.eagerState = _newState;
13091 }
13092
13093 var dispatch = queue.dispatch;
13094 return [hook.memoizedState, dispatch];
13095}
13096
13097function mountState(initialState) {
13098 var hook = mountWorkInProgressHook();
13099 if (typeof initialState === 'function') {
13100 initialState = initialState();
13101 }
13102 hook.memoizedState = hook.baseState = initialState;
13103 var queue = hook.queue = {
13104 last: null,
13105 dispatch: null,
13106 eagerReducer: basicStateReducer,
13107 eagerState: initialState
13108 };
13109 var dispatch = queue.dispatch = dispatchAction.bind(null,
13110 // Flow doesn't know this is non-null, but we do.
13111 currentlyRenderingFiber$1, queue);
13112 return [hook.memoizedState, dispatch];
13113}
13114
13115function updateState(initialState) {
13116 return updateReducer(basicStateReducer, initialState);
13117}
13118
13119function pushEffect(tag, create, destroy, deps) {
13120 var effect = {
13121 tag: tag,
13122 create: create,
13123 destroy: destroy,
13124 deps: deps,
13125 // Circular
13126 next: null
13127 };
13128 if (componentUpdateQueue === null) {
13129 componentUpdateQueue = createFunctionComponentUpdateQueue();
13130 componentUpdateQueue.lastEffect = effect.next = effect;
13131 } else {
13132 var _lastEffect = componentUpdateQueue.lastEffect;
13133 if (_lastEffect === null) {
13134 componentUpdateQueue.lastEffect = effect.next = effect;
13135 } else {
13136 var firstEffect = _lastEffect.next;
13137 _lastEffect.next = effect;
13138 effect.next = firstEffect;
13139 componentUpdateQueue.lastEffect = effect;
13140 }
13141 }
13142 return effect;
13143}
13144
13145function mountRef(initialValue) {
13146 var hook = mountWorkInProgressHook();
13147 var ref = { current: initialValue };
13148 {
13149 Object.seal(ref);
13150 }
13151 hook.memoizedState = ref;
13152 return ref;
13153}
13154
13155function updateRef(initialValue) {
13156 var hook = updateWorkInProgressHook();
13157 return hook.memoizedState;
13158}
13159
13160function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
13161 var hook = mountWorkInProgressHook();
13162 var nextDeps = deps === undefined ? null : deps;
13163 sideEffectTag |= fiberEffectTag;
13164 hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps);
13165}
13166
13167function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
13168 var hook = updateWorkInProgressHook();
13169 var nextDeps = deps === undefined ? null : deps;
13170 var destroy = undefined;
13171
13172 if (currentHook !== null) {
13173 var prevEffect = currentHook.memoizedState;
13174 destroy = prevEffect.destroy;
13175 if (nextDeps !== null) {
13176 var prevDeps = prevEffect.deps;
13177 if (areHookInputsEqual(nextDeps, prevDeps)) {
13178 pushEffect(NoEffect$1, create, destroy, nextDeps);
13179 return;
13180 }
13181 }
13182 }
13183
13184 sideEffectTag |= fiberEffectTag;
13185 hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps);
13186}
13187
13188function mountEffect(create, deps) {
13189 return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
13190}
13191
13192function updateEffect(create, deps) {
13193 return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
13194}
13195
13196function mountLayoutEffect(create, deps) {
13197 return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
13198}
13199
13200function updateLayoutEffect(create, deps) {
13201 return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
13202}
13203
13204function imperativeHandleEffect(create, ref) {
13205 if (typeof ref === 'function') {
13206 var refCallback = ref;
13207 var _inst = create();
13208 refCallback(_inst);
13209 return function () {
13210 refCallback(null);
13211 };
13212 } else if (ref !== null && ref !== undefined) {
13213 var refObject = ref;
13214 {
13215 !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;
13216 }
13217 var _inst2 = create();
13218 refObject.current = _inst2;
13219 return function () {
13220 refObject.current = null;
13221 };
13222 }
13223}
13224
13225function mountImperativeHandle(ref, create, deps) {
13226 {
13227 !(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;
13228 }
13229
13230 // TODO: If deps are provided, should we skip comparing the ref itself?
13231 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : [ref];
13232
13233 return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
13234}
13235
13236function updateImperativeHandle(ref, create, deps) {
13237 {
13238 !(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;
13239 }
13240
13241 // TODO: If deps are provided, should we skip comparing the ref itself?
13242 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : [ref];
13243
13244 return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
13245}
13246
13247function mountDebugValue(value, formatterFn) {
13248 // This hook is normally a no-op.
13249 // The react-debug-hooks package injects its own implementation
13250 // so that e.g. DevTools can display custom hook values.
13251}
13252
13253var updateDebugValue = mountDebugValue;
13254
13255function mountCallback(callback, deps) {
13256 var hook = mountWorkInProgressHook();
13257 var nextDeps = deps === undefined ? null : deps;
13258 hook.memoizedState = [callback, nextDeps];
13259 return callback;
13260}
13261
13262function updateCallback(callback, deps) {
13263 var hook = updateWorkInProgressHook();
13264 var nextDeps = deps === undefined ? null : deps;
13265 var prevState = hook.memoizedState;
13266 if (prevState !== null) {
13267 if (nextDeps !== null) {
13268 var prevDeps = prevState[1];
13269 if (areHookInputsEqual(nextDeps, prevDeps)) {
13270 return prevState[0];
13271 }
13272 }
13273 }
13274 hook.memoizedState = [callback, nextDeps];
13275 return callback;
13276}
13277
13278function mountMemo(nextCreate, deps) {
13279 var hook = mountWorkInProgressHook();
13280 var nextDeps = deps === undefined ? null : deps;
13281 var nextValue = nextCreate();
13282 hook.memoizedState = [nextValue, nextDeps];
13283 return nextValue;
13284}
13285
13286function updateMemo(nextCreate, deps) {
13287 var hook = updateWorkInProgressHook();
13288 var nextDeps = deps === undefined ? null : deps;
13289 var prevState = hook.memoizedState;
13290 if (prevState !== null) {
13291 // Assume these are defined. If they're not, areHookInputsEqual will warn.
13292 if (nextDeps !== null) {
13293 var prevDeps = prevState[1];
13294 if (areHookInputsEqual(nextDeps, prevDeps)) {
13295 return prevState[0];
13296 }
13297 }
13298 }
13299 var nextValue = nextCreate();
13300 hook.memoizedState = [nextValue, nextDeps];
13301 return nextValue;
13302}
13303
13304// in a test-like environment, we want to warn if dispatchAction()
13305// is called outside of a batchedUpdates/TestUtils.act(...) call.
13306var shouldWarnForUnbatchedSetState = false;
13307
13308{
13309 // jest isnt' a 'global', it's just exposed to tests via a wrapped function
13310 // further, this isn't a test file, so flow doesn't recognize the symbol. So...
13311 // $FlowExpectedError - because requirements don't give a damn about your type sigs.
13312 if ('undefined' !== typeof jest) {
13313 shouldWarnForUnbatchedSetState = true;
13314 }
13315}
13316
13317function dispatchAction(fiber, queue, action) {
13318 !(numberOfReRenders < RE_RENDER_LIMIT) ? invariant(false, 'Too many re-renders. React limits the number of renders to prevent an infinite loop.') : void 0;
13319
13320 {
13321 !(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;
13322 }
13323
13324 var alternate = fiber.alternate;
13325 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
13326 // This is a render phase update. Stash it in a lazily-created map of
13327 // queue -> linked list of updates. After this render pass, we'll restart
13328 // and apply the stashed updates on top of the work-in-progress hook.
13329 didScheduleRenderPhaseUpdate = true;
13330 var update = {
13331 expirationTime: renderExpirationTime,
13332 action: action,
13333 eagerReducer: null,
13334 eagerState: null,
13335 next: null
13336 };
13337 if (renderPhaseUpdates === null) {
13338 renderPhaseUpdates = new Map();
13339 }
13340 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
13341 if (firstRenderPhaseUpdate === undefined) {
13342 renderPhaseUpdates.set(queue, update);
13343 } else {
13344 // Append the update to the end of the list.
13345 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
13346 while (lastRenderPhaseUpdate.next !== null) {
13347 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
13348 }
13349 lastRenderPhaseUpdate.next = update;
13350 }
13351 } else {
13352 flushPassiveEffects();
13353
13354 var currentTime = requestCurrentTime();
13355 var _expirationTime = computeExpirationForFiber(currentTime, fiber);
13356
13357 var _update2 = {
13358 expirationTime: _expirationTime,
13359 action: action,
13360 eagerReducer: null,
13361 eagerState: null,
13362 next: null
13363 };
13364
13365 // Append the update to the end of the list.
13366 var _last = queue.last;
13367 if (_last === null) {
13368 // This is the first update. Create a circular list.
13369 _update2.next = _update2;
13370 } else {
13371 var first = _last.next;
13372 if (first !== null) {
13373 // Still circular.
13374 _update2.next = first;
13375 }
13376 _last.next = _update2;
13377 }
13378 queue.last = _update2;
13379
13380 if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
13381 // The queue is currently empty, which means we can eagerly compute the
13382 // next state before entering the render phase. If the new state is the
13383 // same as the current state, we may be able to bail out entirely.
13384 var _eagerReducer = queue.eagerReducer;
13385 if (_eagerReducer !== null) {
13386 var prevDispatcher = void 0;
13387 {
13388 prevDispatcher = ReactCurrentDispatcher$1.current;
13389 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13390 }
13391 try {
13392 var currentState = queue.eagerState;
13393 var _eagerState = _eagerReducer(currentState, action);
13394 // Stash the eagerly computed state, and the reducer used to compute
13395 // it, on the update object. If the reducer hasn't changed by the
13396 // time we enter the render phase, then the eager state can be used
13397 // without calling the reducer again.
13398 _update2.eagerReducer = _eagerReducer;
13399 _update2.eagerState = _eagerState;
13400 if (is(_eagerState, currentState)) {
13401 // Fast path. We can bail out without scheduling React to re-render.
13402 // It's still possible that we'll need to rebase this update later,
13403 // if the component re-renders for a different reason and by that
13404 // time the reducer has changed.
13405 return;
13406 }
13407 } catch (error) {
13408 // Suppress the error. It will throw again in the render phase.
13409 } finally {
13410 {
13411 ReactCurrentDispatcher$1.current = prevDispatcher;
13412 }
13413 }
13414 }
13415 }
13416 {
13417 if (shouldWarnForUnbatchedSetState === true) {
13418 warnIfNotCurrentlyBatchingInDev(fiber);
13419 }
13420 }
13421 scheduleWork(fiber, _expirationTime);
13422 }
13423}
13424
13425var ContextOnlyDispatcher = {
13426 readContext: readContext,
13427
13428 useCallback: throwInvalidHookError,
13429 useContext: throwInvalidHookError,
13430 useEffect: throwInvalidHookError,
13431 useImperativeHandle: throwInvalidHookError,
13432 useLayoutEffect: throwInvalidHookError,
13433 useMemo: throwInvalidHookError,
13434 useReducer: throwInvalidHookError,
13435 useRef: throwInvalidHookError,
13436 useState: throwInvalidHookError,
13437 useDebugValue: throwInvalidHookError
13438};
13439
13440var HooksDispatcherOnMountInDEV = null;
13441var HooksDispatcherOnUpdateInDEV = null;
13442var InvalidNestedHooksDispatcherOnMountInDEV = null;
13443var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
13444
13445{
13446 var warnInvalidContextAccess = function () {
13447 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().');
13448 };
13449
13450 var warnInvalidHookAccess = function () {
13451 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');
13452 };
13453
13454 HooksDispatcherOnMountInDEV = {
13455 readContext: function (context, observedBits) {
13456 return readContext(context, observedBits);
13457 },
13458 useCallback: function (callback, deps) {
13459 currentHookNameInDev = 'useCallback';
13460 return mountCallback(callback, deps);
13461 },
13462 useContext: function (context, observedBits) {
13463 currentHookNameInDev = 'useContext';
13464 return mountContext(context, observedBits);
13465 },
13466 useEffect: function (create, deps) {
13467 currentHookNameInDev = 'useEffect';
13468 return mountEffect(create, deps);
13469 },
13470 useImperativeHandle: function (ref, create, deps) {
13471 currentHookNameInDev = 'useImperativeHandle';
13472 return mountImperativeHandle(ref, create, deps);
13473 },
13474 useLayoutEffect: function (create, deps) {
13475 currentHookNameInDev = 'useLayoutEffect';
13476 return mountLayoutEffect(create, deps);
13477 },
13478 useMemo: function (create, deps) {
13479 currentHookNameInDev = 'useMemo';
13480 var prevDispatcher = ReactCurrentDispatcher$1.current;
13481 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13482 try {
13483 return mountMemo(create, deps);
13484 } finally {
13485 ReactCurrentDispatcher$1.current = prevDispatcher;
13486 }
13487 },
13488 useReducer: function (reducer, initialArg, init) {
13489 currentHookNameInDev = 'useReducer';
13490 var prevDispatcher = ReactCurrentDispatcher$1.current;
13491 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13492 try {
13493 return mountReducer(reducer, initialArg, init);
13494 } finally {
13495 ReactCurrentDispatcher$1.current = prevDispatcher;
13496 }
13497 },
13498 useRef: function (initialValue) {
13499 currentHookNameInDev = 'useRef';
13500 return mountRef(initialValue);
13501 },
13502 useState: function (initialState) {
13503 currentHookNameInDev = 'useState';
13504 var prevDispatcher = ReactCurrentDispatcher$1.current;
13505 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13506 try {
13507 return mountState(initialState);
13508 } finally {
13509 ReactCurrentDispatcher$1.current = prevDispatcher;
13510 }
13511 },
13512 useDebugValue: function (value, formatterFn) {
13513 currentHookNameInDev = 'useDebugValue';
13514 return mountDebugValue(value, formatterFn);
13515 }
13516 };
13517
13518 HooksDispatcherOnUpdateInDEV = {
13519 readContext: function (context, observedBits) {
13520 return readContext(context, observedBits);
13521 },
13522 useCallback: function (callback, deps) {
13523 currentHookNameInDev = 'useCallback';
13524 return updateCallback(callback, deps);
13525 },
13526 useContext: function (context, observedBits) {
13527 currentHookNameInDev = 'useContext';
13528 return updateContext(context, observedBits);
13529 },
13530 useEffect: function (create, deps) {
13531 currentHookNameInDev = 'useEffect';
13532 return updateEffect(create, deps);
13533 },
13534 useImperativeHandle: function (ref, create, deps) {
13535 currentHookNameInDev = 'useImperativeHandle';
13536 return updateImperativeHandle(ref, create, deps);
13537 },
13538 useLayoutEffect: function (create, deps) {
13539 currentHookNameInDev = 'useLayoutEffect';
13540 return updateLayoutEffect(create, deps);
13541 },
13542 useMemo: function (create, deps) {
13543 currentHookNameInDev = 'useMemo';
13544 var prevDispatcher = ReactCurrentDispatcher$1.current;
13545 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13546 try {
13547 return updateMemo(create, deps);
13548 } finally {
13549 ReactCurrentDispatcher$1.current = prevDispatcher;
13550 }
13551 },
13552 useReducer: function (reducer, initialArg, init) {
13553 currentHookNameInDev = 'useReducer';
13554 var prevDispatcher = ReactCurrentDispatcher$1.current;
13555 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13556 try {
13557 return updateReducer(reducer, initialArg, init);
13558 } finally {
13559 ReactCurrentDispatcher$1.current = prevDispatcher;
13560 }
13561 },
13562 useRef: function (initialValue) {
13563 currentHookNameInDev = 'useRef';
13564 return updateRef(initialValue);
13565 },
13566 useState: function (initialState) {
13567 currentHookNameInDev = 'useState';
13568 var prevDispatcher = ReactCurrentDispatcher$1.current;
13569 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13570 try {
13571 return updateState(initialState);
13572 } finally {
13573 ReactCurrentDispatcher$1.current = prevDispatcher;
13574 }
13575 },
13576 useDebugValue: function (value, formatterFn) {
13577 currentHookNameInDev = 'useDebugValue';
13578 return updateDebugValue(value, formatterFn);
13579 }
13580 };
13581
13582 InvalidNestedHooksDispatcherOnMountInDEV = {
13583 readContext: function (context, observedBits) {
13584 warnInvalidContextAccess();
13585 return readContext(context, observedBits);
13586 },
13587 useCallback: function (callback, deps) {
13588 currentHookNameInDev = 'useCallback';
13589 warnInvalidHookAccess();
13590 return mountCallback(callback, deps);
13591 },
13592 useContext: function (context, observedBits) {
13593 currentHookNameInDev = 'useContext';
13594 warnInvalidHookAccess();
13595 return mountContext(context, observedBits);
13596 },
13597 useEffect: function (create, deps) {
13598 currentHookNameInDev = 'useEffect';
13599 warnInvalidHookAccess();
13600 return mountEffect(create, deps);
13601 },
13602 useImperativeHandle: function (ref, create, deps) {
13603 currentHookNameInDev = 'useImperativeHandle';
13604 warnInvalidHookAccess();
13605 return mountImperativeHandle(ref, create, deps);
13606 },
13607 useLayoutEffect: function (create, deps) {
13608 currentHookNameInDev = 'useLayoutEffect';
13609 warnInvalidHookAccess();
13610 return mountLayoutEffect(create, deps);
13611 },
13612 useMemo: function (create, deps) {
13613 currentHookNameInDev = 'useMemo';
13614 warnInvalidHookAccess();
13615 var prevDispatcher = ReactCurrentDispatcher$1.current;
13616 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13617 try {
13618 return mountMemo(create, deps);
13619 } finally {
13620 ReactCurrentDispatcher$1.current = prevDispatcher;
13621 }
13622 },
13623 useReducer: function (reducer, initialArg, init) {
13624 currentHookNameInDev = 'useReducer';
13625 warnInvalidHookAccess();
13626 var prevDispatcher = ReactCurrentDispatcher$1.current;
13627 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13628 try {
13629 return mountReducer(reducer, initialArg, init);
13630 } finally {
13631 ReactCurrentDispatcher$1.current = prevDispatcher;
13632 }
13633 },
13634 useRef: function (initialValue) {
13635 currentHookNameInDev = 'useRef';
13636 warnInvalidHookAccess();
13637 return mountRef(initialValue);
13638 },
13639 useState: function (initialState) {
13640 currentHookNameInDev = 'useState';
13641 warnInvalidHookAccess();
13642 var prevDispatcher = ReactCurrentDispatcher$1.current;
13643 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
13644 try {
13645 return mountState(initialState);
13646 } finally {
13647 ReactCurrentDispatcher$1.current = prevDispatcher;
13648 }
13649 },
13650 useDebugValue: function (value, formatterFn) {
13651 currentHookNameInDev = 'useDebugValue';
13652 warnInvalidHookAccess();
13653 return mountDebugValue(value, formatterFn);
13654 }
13655 };
13656
13657 InvalidNestedHooksDispatcherOnUpdateInDEV = {
13658 readContext: function (context, observedBits) {
13659 warnInvalidContextAccess();
13660 return readContext(context, observedBits);
13661 },
13662 useCallback: function (callback, deps) {
13663 currentHookNameInDev = 'useCallback';
13664 warnInvalidHookAccess();
13665 return updateCallback(callback, deps);
13666 },
13667 useContext: function (context, observedBits) {
13668 currentHookNameInDev = 'useContext';
13669 warnInvalidHookAccess();
13670 return updateContext(context, observedBits);
13671 },
13672 useEffect: function (create, deps) {
13673 currentHookNameInDev = 'useEffect';
13674 warnInvalidHookAccess();
13675 return updateEffect(create, deps);
13676 },
13677 useImperativeHandle: function (ref, create, deps) {
13678 currentHookNameInDev = 'useImperativeHandle';
13679 warnInvalidHookAccess();
13680 return updateImperativeHandle(ref, create, deps);
13681 },
13682 useLayoutEffect: function (create, deps) {
13683 currentHookNameInDev = 'useLayoutEffect';
13684 warnInvalidHookAccess();
13685 return updateLayoutEffect(create, deps);
13686 },
13687 useMemo: function (create, deps) {
13688 currentHookNameInDev = 'useMemo';
13689 warnInvalidHookAccess();
13690 var prevDispatcher = ReactCurrentDispatcher$1.current;
13691 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13692 try {
13693 return updateMemo(create, deps);
13694 } finally {
13695 ReactCurrentDispatcher$1.current = prevDispatcher;
13696 }
13697 },
13698 useReducer: function (reducer, initialArg, init) {
13699 currentHookNameInDev = 'useReducer';
13700 warnInvalidHookAccess();
13701 var prevDispatcher = ReactCurrentDispatcher$1.current;
13702 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13703 try {
13704 return updateReducer(reducer, initialArg, init);
13705 } finally {
13706 ReactCurrentDispatcher$1.current = prevDispatcher;
13707 }
13708 },
13709 useRef: function (initialValue) {
13710 currentHookNameInDev = 'useRef';
13711 warnInvalidHookAccess();
13712 return updateRef(initialValue);
13713 },
13714 useState: function (initialState) {
13715 currentHookNameInDev = 'useState';
13716 warnInvalidHookAccess();
13717 var prevDispatcher = ReactCurrentDispatcher$1.current;
13718 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
13719 try {
13720 return updateState(initialState);
13721 } finally {
13722 ReactCurrentDispatcher$1.current = prevDispatcher;
13723 }
13724 },
13725 useDebugValue: function (value, formatterFn) {
13726 currentHookNameInDev = 'useDebugValue';
13727 warnInvalidHookAccess();
13728 return updateDebugValue(value, formatterFn);
13729 }
13730 };
13731}
13732
13733var commitTime = 0;
13734var profilerStartTime = -1;
13735
13736function getCommitTime() {
13737 return commitTime;
13738}
13739
13740function recordCommitTime() {
13741 if (!enableProfilerTimer) {
13742 return;
13743 }
13744 commitTime = scheduler.unstable_now();
13745}
13746
13747function startProfilerTimer(fiber) {
13748 if (!enableProfilerTimer) {
13749 return;
13750 }
13751
13752 profilerStartTime = scheduler.unstable_now();
13753
13754 if (fiber.actualStartTime < 0) {
13755 fiber.actualStartTime = scheduler.unstable_now();
13756 }
13757}
13758
13759function stopProfilerTimerIfRunning(fiber) {
13760 if (!enableProfilerTimer) {
13761 return;
13762 }
13763 profilerStartTime = -1;
13764}
13765
13766function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
13767 if (!enableProfilerTimer) {
13768 return;
13769 }
13770
13771 if (profilerStartTime >= 0) {
13772 var elapsedTime = scheduler.unstable_now() - profilerStartTime;
13773 fiber.actualDuration += elapsedTime;
13774 if (overrideBaseTime) {
13775 fiber.selfBaseDuration = elapsedTime;
13776 }
13777 profilerStartTime = -1;
13778 }
13779}
13780
13781// The deepest Fiber on the stack involved in a hydration context.
13782// This may have been an insertion or a hydration.
13783var hydrationParentFiber = null;
13784var nextHydratableInstance = null;
13785var isHydrating = false;
13786
13787function enterHydrationState(fiber) {
13788 if (!supportsHydration) {
13789 return false;
13790 }
13791
13792 var parentInstance = fiber.stateNode.containerInfo;
13793 nextHydratableInstance = getFirstHydratableChild(parentInstance);
13794 hydrationParentFiber = fiber;
13795 isHydrating = true;
13796 return true;
13797}
13798
13799function deleteHydratableInstance(returnFiber, instance) {
13800 {
13801 switch (returnFiber.tag) {
13802 case HostRoot:
13803 didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
13804 break;
13805 case HostComponent:
13806 didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
13807 break;
13808 }
13809 }
13810
13811 var childToDelete = createFiberFromHostInstanceForDeletion();
13812 childToDelete.stateNode = instance;
13813 childToDelete.return = returnFiber;
13814 childToDelete.effectTag = Deletion;
13815
13816 // This might seem like it belongs on progressedFirstDeletion. However,
13817 // these children are not part of the reconciliation list of children.
13818 // Even if we abort and rereconcile the children, that will try to hydrate
13819 // again and the nodes are still in the host tree so these will be
13820 // recreated.
13821 if (returnFiber.lastEffect !== null) {
13822 returnFiber.lastEffect.nextEffect = childToDelete;
13823 returnFiber.lastEffect = childToDelete;
13824 } else {
13825 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
13826 }
13827}
13828
13829function insertNonHydratedInstance(returnFiber, fiber) {
13830 fiber.effectTag |= Placement;
13831 {
13832 switch (returnFiber.tag) {
13833 case HostRoot:
13834 {
13835 var parentContainer = returnFiber.stateNode.containerInfo;
13836 switch (fiber.tag) {
13837 case HostComponent:
13838 var type = fiber.type;
13839 var props = fiber.pendingProps;
13840 didNotFindHydratableContainerInstance(parentContainer, type, props);
13841 break;
13842 case HostText:
13843 var text = fiber.pendingProps;
13844 didNotFindHydratableContainerTextInstance(parentContainer, text);
13845 break;
13846 }
13847 break;
13848 }
13849 case HostComponent:
13850 {
13851 var parentType = returnFiber.type;
13852 var parentProps = returnFiber.memoizedProps;
13853 var parentInstance = returnFiber.stateNode;
13854 switch (fiber.tag) {
13855 case HostComponent:
13856 var _type = fiber.type;
13857 var _props = fiber.pendingProps;
13858 didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
13859 break;
13860 case HostText:
13861 var _text = fiber.pendingProps;
13862 didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
13863 break;
13864 }
13865 break;
13866 }
13867 default:
13868 return;
13869 }
13870 }
13871}
13872
13873function tryHydrate(fiber, nextInstance) {
13874 switch (fiber.tag) {
13875 case HostComponent:
13876 {
13877 var type = fiber.type;
13878 var props = fiber.pendingProps;
13879 var instance = canHydrateInstance(nextInstance, type, props);
13880 if (instance !== null) {
13881 fiber.stateNode = instance;
13882 return true;
13883 }
13884 return false;
13885 }
13886 case HostText:
13887 {
13888 var text = fiber.pendingProps;
13889 var textInstance = canHydrateTextInstance(nextInstance, text);
13890 if (textInstance !== null) {
13891 fiber.stateNode = textInstance;
13892 return true;
13893 }
13894 return false;
13895 }
13896 default:
13897 return false;
13898 }
13899}
13900
13901function tryToClaimNextHydratableInstance(fiber) {
13902 if (!isHydrating) {
13903 return;
13904 }
13905 var nextInstance = nextHydratableInstance;
13906 if (!nextInstance) {
13907 // Nothing to hydrate. Make it an insertion.
13908 insertNonHydratedInstance(hydrationParentFiber, fiber);
13909 isHydrating = false;
13910 hydrationParentFiber = fiber;
13911 return;
13912 }
13913 var firstAttemptedInstance = nextInstance;
13914 if (!tryHydrate(fiber, nextInstance)) {
13915 // If we can't hydrate this instance let's try the next one.
13916 // We use this as a heuristic. It's based on intuition and not data so it
13917 // might be flawed or unnecessary.
13918 nextInstance = getNextHydratableSibling(firstAttemptedInstance);
13919 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
13920 // Nothing to hydrate. Make it an insertion.
13921 insertNonHydratedInstance(hydrationParentFiber, fiber);
13922 isHydrating = false;
13923 hydrationParentFiber = fiber;
13924 return;
13925 }
13926 // We matched the next one, we'll now assume that the first one was
13927 // superfluous and we'll delete it. Since we can't eagerly delete it
13928 // we'll have to schedule a deletion. To do that, this node needs a dummy
13929 // fiber associated with it.
13930 deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
13931 }
13932 hydrationParentFiber = fiber;
13933 nextHydratableInstance = getFirstHydratableChild(nextInstance);
13934}
13935
13936function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
13937 if (!supportsHydration) {
13938 invariant(false, 'Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
13939 }
13940
13941 var instance = fiber.stateNode;
13942 var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber);
13943 // TODO: Type this specific to this type of component.
13944 fiber.updateQueue = updatePayload;
13945 // If the update payload indicates that there is a change or if there
13946 // is a new ref we mark this as an update.
13947 if (updatePayload !== null) {
13948 return true;
13949 }
13950 return false;
13951}
13952
13953function prepareToHydrateHostTextInstance(fiber) {
13954 if (!supportsHydration) {
13955 invariant(false, 'Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
13956 }
13957
13958 var textInstance = fiber.stateNode;
13959 var textContent = fiber.memoizedProps;
13960 var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
13961 {
13962 if (shouldUpdate) {
13963 // We assume that prepareToHydrateHostTextInstance is called in a context where the
13964 // hydration parent is the parent host component of this host text.
13965 var returnFiber = hydrationParentFiber;
13966 if (returnFiber !== null) {
13967 switch (returnFiber.tag) {
13968 case HostRoot:
13969 {
13970 var parentContainer = returnFiber.stateNode.containerInfo;
13971 didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
13972 break;
13973 }
13974 case HostComponent:
13975 {
13976 var parentType = returnFiber.type;
13977 var parentProps = returnFiber.memoizedProps;
13978 var parentInstance = returnFiber.stateNode;
13979 didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
13980 break;
13981 }
13982 }
13983 }
13984 }
13985 }
13986 return shouldUpdate;
13987}
13988
13989function popToNextHostParent(fiber) {
13990 var parent = fiber.return;
13991 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot) {
13992 parent = parent.return;
13993 }
13994 hydrationParentFiber = parent;
13995}
13996
13997function popHydrationState(fiber) {
13998 if (!supportsHydration) {
13999 return false;
14000 }
14001 if (fiber !== hydrationParentFiber) {
14002 // We're deeper than the current hydration context, inside an inserted
14003 // tree.
14004 return false;
14005 }
14006 if (!isHydrating) {
14007 // If we're not currently hydrating but we're in a hydration context, then
14008 // we were an insertion and now need to pop up reenter hydration of our
14009 // siblings.
14010 popToNextHostParent(fiber);
14011 isHydrating = true;
14012 return false;
14013 }
14014
14015 var type = fiber.type;
14016
14017 // If we have any remaining hydratable nodes, we need to delete them now.
14018 // We only do this deeper than head and body since they tend to have random
14019 // other nodes in them. We also ignore components with pure text content in
14020 // side of them.
14021 // TODO: Better heuristic.
14022 if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
14023 var nextInstance = nextHydratableInstance;
14024 while (nextInstance) {
14025 deleteHydratableInstance(fiber, nextInstance);
14026 nextInstance = getNextHydratableSibling(nextInstance);
14027 }
14028 }
14029
14030 popToNextHostParent(fiber);
14031 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
14032 return true;
14033}
14034
14035function resetHydrationState() {
14036 if (!supportsHydration) {
14037 return;
14038 }
14039
14040 hydrationParentFiber = null;
14041 nextHydratableInstance = null;
14042 isHydrating = false;
14043}
14044
14045var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
14046
14047var didReceiveUpdate = false;
14048
14049var didWarnAboutBadClass = void 0;
14050var didWarnAboutContextTypeOnFunctionComponent = void 0;
14051var didWarnAboutGetDerivedStateOnFunctionComponent = void 0;
14052var didWarnAboutFunctionRefs = void 0;
14053var didWarnAboutReassigningProps = void 0;
14054
14055{
14056 didWarnAboutBadClass = {};
14057 didWarnAboutContextTypeOnFunctionComponent = {};
14058 didWarnAboutGetDerivedStateOnFunctionComponent = {};
14059 didWarnAboutFunctionRefs = {};
14060 didWarnAboutReassigningProps = false;
14061}
14062
14063function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) {
14064 if (current$$1 === null) {
14065 // If this is a fresh new component that hasn't been rendered yet, we
14066 // won't update its child set by applying minimal side-effects. Instead,
14067 // we will add them all to the child before it gets rendered. That means
14068 // we can optimize this reconciliation pass by not tracking side-effects.
14069 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
14070 } else {
14071 // If the current child is the same as the work in progress, it means that
14072 // we haven't yet started any work on these children. Therefore, we use
14073 // the clone algorithm to create a copy of all the current children.
14074
14075 // If we had any progressed work already, that is invalid at this point so
14076 // let's throw it out.
14077 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime);
14078 }
14079}
14080
14081function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) {
14082 // This function is fork of reconcileChildren. It's used in cases where we
14083 // want to reconcile without matching against the existing set. This has the
14084 // effect of all current children being unmounted; even if the type and key
14085 // are the same, the old child is unmounted and a new child is created.
14086 //
14087 // To do this, we're going to go through the reconcile algorithm twice. In
14088 // the first pass, we schedule a deletion for all the current children by
14089 // passing null.
14090 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime);
14091 // In the second pass, we mount the new children. The trick here is that we
14092 // pass null in place of where we usually pass the current child set. This has
14093 // the effect of remounting all children regardless of whether their their
14094 // identity matches.
14095 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
14096}
14097
14098function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
14099 {
14100 if (workInProgress.type !== workInProgress.elementType) {
14101 // Lazy component props can't be validated in createElement
14102 // because they're only guaranteed to be resolved here.
14103 var innerPropTypes = Component.propTypes;
14104 if (innerPropTypes) {
14105 checkPropTypes(innerPropTypes, nextProps, // Resolved props
14106 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14107 }
14108 }
14109 }
14110
14111 var render = Component.render;
14112 var ref = workInProgress.ref;
14113
14114 // The rest is a fork of updateFunctionComponent
14115 var nextChildren = void 0;
14116 prepareToReadContext(workInProgress, renderExpirationTime);
14117 {
14118 ReactCurrentOwner$3.current = workInProgress;
14119 setCurrentPhase('render');
14120 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
14121 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14122 // Only double-render components with Hooks
14123 if (workInProgress.memoizedState !== null) {
14124 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
14125 }
14126 }
14127 setCurrentPhase(null);
14128 }
14129
14130 if (current$$1 !== null && !didReceiveUpdate) {
14131 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
14132 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14133 }
14134
14135 // React DevTools reads this flag.
14136 workInProgress.effectTag |= PerformedWork;
14137 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14138 return workInProgress.child;
14139}
14140
14141function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
14142 if (current$$1 === null) {
14143 var type = Component.type;
14144 if (isSimpleFunctionComponent(type) && Component.compare === null &&
14145 // SimpleMemoComponent codepath doesn't resolve outer props either.
14146 Component.defaultProps === undefined) {
14147 // If this is a plain function component without default props,
14148 // and with only the default shallow comparison, we upgrade it
14149 // to a SimpleMemoComponent to allow fast path updates.
14150 workInProgress.tag = SimpleMemoComponent;
14151 workInProgress.type = type;
14152 {
14153 validateFunctionComponentInDev(workInProgress, type);
14154 }
14155 return updateSimpleMemoComponent(current$$1, workInProgress, type, nextProps, updateExpirationTime, renderExpirationTime);
14156 }
14157 {
14158 var innerPropTypes = type.propTypes;
14159 if (innerPropTypes) {
14160 // Inner memo component props aren't currently validated in createElement.
14161 // We could move it there, but we'd still need this for lazy code path.
14162 checkPropTypes(innerPropTypes, nextProps, // Resolved props
14163 'prop', getComponentName(type), getCurrentFiberStackInDev);
14164 }
14165 }
14166 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
14167 child.ref = workInProgress.ref;
14168 child.return = workInProgress;
14169 workInProgress.child = child;
14170 return child;
14171 }
14172 {
14173 var _type = Component.type;
14174 var _innerPropTypes = _type.propTypes;
14175 if (_innerPropTypes) {
14176 // Inner memo component props aren't currently validated in createElement.
14177 // We could move it there, but we'd still need this for lazy code path.
14178 checkPropTypes(_innerPropTypes, nextProps, // Resolved props
14179 'prop', getComponentName(_type), getCurrentFiberStackInDev);
14180 }
14181 }
14182 var currentChild = current$$1.child; // This is always exactly one child
14183 if (updateExpirationTime < renderExpirationTime) {
14184 // This will be the props with resolved defaultProps,
14185 // unlike current.memoizedProps which will be the unresolved ones.
14186 var prevProps = currentChild.memoizedProps;
14187 // Default to shallow comparison
14188 var compare = Component.compare;
14189 compare = compare !== null ? compare : shallowEqual;
14190 if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
14191 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14192 }
14193 }
14194 // React DevTools reads this flag.
14195 workInProgress.effectTag |= PerformedWork;
14196 var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
14197 newChild.ref = workInProgress.ref;
14198 newChild.return = workInProgress;
14199 workInProgress.child = newChild;
14200 return newChild;
14201}
14202
14203function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
14204 {
14205 if (workInProgress.type !== workInProgress.elementType) {
14206 // Lazy component props can't be validated in createElement
14207 // because they're only guaranteed to be resolved here.
14208 var outerMemoType = workInProgress.elementType;
14209 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
14210 // We warn when you define propTypes on lazy()
14211 // so let's just skip over it to find memo() outer wrapper.
14212 // Inner props for memo are validated later.
14213 outerMemoType = refineResolvedLazyComponent(outerMemoType);
14214 }
14215 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
14216 if (outerPropTypes) {
14217 checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
14218 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
14219 }
14220 // Inner propTypes will be validated in the function component path.
14221 }
14222 }
14223 if (current$$1 !== null) {
14224 var prevProps = current$$1.memoizedProps;
14225 if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
14226 didReceiveUpdate = false;
14227 if (updateExpirationTime < renderExpirationTime) {
14228 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14229 }
14230 }
14231 }
14232 return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
14233}
14234
14235function updateFragment(current$$1, workInProgress, renderExpirationTime) {
14236 var nextChildren = workInProgress.pendingProps;
14237 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14238 return workInProgress.child;
14239}
14240
14241function updateMode(current$$1, workInProgress, renderExpirationTime) {
14242 var nextChildren = workInProgress.pendingProps.children;
14243 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14244 return workInProgress.child;
14245}
14246
14247function updateProfiler(current$$1, workInProgress, renderExpirationTime) {
14248 if (enableProfilerTimer) {
14249 workInProgress.effectTag |= Update;
14250 }
14251 var nextProps = workInProgress.pendingProps;
14252 var nextChildren = nextProps.children;
14253 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14254 return workInProgress.child;
14255}
14256
14257function markRef(current$$1, workInProgress) {
14258 var ref = workInProgress.ref;
14259 if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) {
14260 // Schedule a Ref effect
14261 workInProgress.effectTag |= Ref;
14262 }
14263}
14264
14265function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
14266 {
14267 if (workInProgress.type !== workInProgress.elementType) {
14268 // Lazy component props can't be validated in createElement
14269 // because they're only guaranteed to be resolved here.
14270 var innerPropTypes = Component.propTypes;
14271 if (innerPropTypes) {
14272 checkPropTypes(innerPropTypes, nextProps, // Resolved props
14273 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14274 }
14275 }
14276 }
14277
14278 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
14279 var context = getMaskedContext(workInProgress, unmaskedContext);
14280
14281 var nextChildren = void 0;
14282 prepareToReadContext(workInProgress, renderExpirationTime);
14283 {
14284 ReactCurrentOwner$3.current = workInProgress;
14285 setCurrentPhase('render');
14286 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
14287 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14288 // Only double-render components with Hooks
14289 if (workInProgress.memoizedState !== null) {
14290 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
14291 }
14292 }
14293 setCurrentPhase(null);
14294 }
14295
14296 if (current$$1 !== null && !didReceiveUpdate) {
14297 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
14298 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14299 }
14300
14301 // React DevTools reads this flag.
14302 workInProgress.effectTag |= PerformedWork;
14303 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14304 return workInProgress.child;
14305}
14306
14307function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
14308 {
14309 if (workInProgress.type !== workInProgress.elementType) {
14310 // Lazy component props can't be validated in createElement
14311 // because they're only guaranteed to be resolved here.
14312 var innerPropTypes = Component.propTypes;
14313 if (innerPropTypes) {
14314 checkPropTypes(innerPropTypes, nextProps, // Resolved props
14315 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14316 }
14317 }
14318 }
14319
14320 // Push context providers early to prevent context stack mismatches.
14321 // During mounting we don't know the child context yet as the instance doesn't exist.
14322 // We will invalidate the child context in finishClassComponent() right after rendering.
14323 var hasContext = void 0;
14324 if (isContextProvider(Component)) {
14325 hasContext = true;
14326 pushContextProvider(workInProgress);
14327 } else {
14328 hasContext = false;
14329 }
14330 prepareToReadContext(workInProgress, renderExpirationTime);
14331
14332 var instance = workInProgress.stateNode;
14333 var shouldUpdate = void 0;
14334 if (instance === null) {
14335 if (current$$1 !== null) {
14336 // An class component without an instance only mounts if it suspended
14337 // inside a non- concurrent tree, in an inconsistent state. We want to
14338 // tree it like a new mount, even though an empty version of it already
14339 // committed. Disconnect the alternate pointers.
14340 current$$1.alternate = null;
14341 workInProgress.alternate = null;
14342 // Since this is conceptually a new fiber, schedule a Placement effect
14343 workInProgress.effectTag |= Placement;
14344 }
14345 // In the initial pass we might need to construct the instance.
14346 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14347 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14348 shouldUpdate = true;
14349 } else if (current$$1 === null) {
14350 // In a resume, we'll already have an instance we can reuse.
14351 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14352 } else {
14353 shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
14354 }
14355 var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
14356 {
14357 var inst = workInProgress.stateNode;
14358 if (inst.props !== nextProps) {
14359 !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;
14360 didWarnAboutReassigningProps = true;
14361 }
14362 }
14363 return nextUnitOfWork;
14364}
14365
14366function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
14367 // Refs should update even if shouldComponentUpdate returns false
14368 markRef(current$$1, workInProgress);
14369
14370 var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
14371
14372 if (!shouldUpdate && !didCaptureError) {
14373 // Context providers should defer to sCU for rendering
14374 if (hasContext) {
14375 invalidateContextProvider(workInProgress, Component, false);
14376 }
14377
14378 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14379 }
14380
14381 var instance = workInProgress.stateNode;
14382
14383 // Rerender
14384 ReactCurrentOwner$3.current = workInProgress;
14385 var nextChildren = void 0;
14386 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
14387 // If we captured an error, but getDerivedStateFrom catch is not defined,
14388 // unmount all the children. componentDidCatch will schedule an update to
14389 // re-render a fallback. This is temporary until we migrate everyone to
14390 // the new API.
14391 // TODO: Warn in a future release.
14392 nextChildren = null;
14393
14394 if (enableProfilerTimer) {
14395 stopProfilerTimerIfRunning(workInProgress);
14396 }
14397 } else {
14398 {
14399 setCurrentPhase('render');
14400 nextChildren = instance.render();
14401 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14402 instance.render();
14403 }
14404 setCurrentPhase(null);
14405 }
14406 }
14407
14408 // React DevTools reads this flag.
14409 workInProgress.effectTag |= PerformedWork;
14410 if (current$$1 !== null && didCaptureError) {
14411 // If we're recovering from an error, reconcile without reusing any of
14412 // the existing children. Conceptually, the normal children and the children
14413 // that are shown on error are two different sets, so we shouldn't reuse
14414 // normal children even if their identities match.
14415 forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime);
14416 } else {
14417 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14418 }
14419
14420 // Memoize state using the values we just used to render.
14421 // TODO: Restructure so we never read values from the instance.
14422 workInProgress.memoizedState = instance.state;
14423
14424 // The context might have changed so we need to recalculate it.
14425 if (hasContext) {
14426 invalidateContextProvider(workInProgress, Component, true);
14427 }
14428
14429 return workInProgress.child;
14430}
14431
14432function pushHostRootContext(workInProgress) {
14433 var root = workInProgress.stateNode;
14434 if (root.pendingContext) {
14435 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
14436 } else if (root.context) {
14437 // Should always be set
14438 pushTopLevelContextObject(workInProgress, root.context, false);
14439 }
14440 pushHostContainer(workInProgress, root.containerInfo);
14441}
14442
14443function updateHostRoot(current$$1, workInProgress, renderExpirationTime) {
14444 pushHostRootContext(workInProgress);
14445 var updateQueue = workInProgress.updateQueue;
14446 !(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;
14447 var nextProps = workInProgress.pendingProps;
14448 var prevState = workInProgress.memoizedState;
14449 var prevChildren = prevState !== null ? prevState.element : null;
14450 processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
14451 var nextState = workInProgress.memoizedState;
14452 // Caution: React DevTools currently depends on this property
14453 // being called "element".
14454 var nextChildren = nextState.element;
14455 if (nextChildren === prevChildren) {
14456 // If the state is the same as before, that's a bailout because we had
14457 // no work that expires at this time.
14458 resetHydrationState();
14459 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
14460 }
14461 var root = workInProgress.stateNode;
14462 if ((current$$1 === null || current$$1.child === null) && root.hydrate && enterHydrationState(workInProgress)) {
14463 // If we don't have any current children this might be the first pass.
14464 // We always try to hydrate. If this isn't a hydration pass there won't
14465 // be any children to hydrate which is effectively the same thing as
14466 // not hydrating.
14467
14468 // This is a bit of a hack. We track the host root as a placement to
14469 // know that we're currently in a mounting state. That way isMounted
14470 // works as expected. We must reset this before committing.
14471 // TODO: Delete this when we delete isMounted and findDOMNode.
14472 workInProgress.effectTag |= Placement;
14473
14474 // Ensure that children mount into this root without tracking
14475 // side-effects. This ensures that we don't store Placement effects on
14476 // nodes that will be hydrated.
14477 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
14478 } else {
14479 // Otherwise reset hydration state in case we aborted and resumed another
14480 // root.
14481 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14482 resetHydrationState();
14483 }
14484 return workInProgress.child;
14485}
14486
14487function updateHostComponent(current$$1, workInProgress, renderExpirationTime) {
14488 pushHostContext(workInProgress);
14489
14490 if (current$$1 === null) {
14491 tryToClaimNextHydratableInstance(workInProgress);
14492 }
14493
14494 var type = workInProgress.type;
14495 var nextProps = workInProgress.pendingProps;
14496 var prevProps = current$$1 !== null ? current$$1.memoizedProps : null;
14497
14498 var nextChildren = nextProps.children;
14499 var isDirectTextChild = shouldSetTextContent(type, nextProps);
14500
14501 if (isDirectTextChild) {
14502 // We special case a direct text child of a host node. This is a common
14503 // case. We won't handle it as a reified child. We will instead handle
14504 // this in the host environment that also have access to this prop. That
14505 // avoids allocating another HostText fiber and traversing it.
14506 nextChildren = null;
14507 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
14508 // If we're switching from a direct text child to a normal child, or to
14509 // empty, we need to schedule the text content to be reset.
14510 workInProgress.effectTag |= ContentReset;
14511 }
14512
14513 markRef(current$$1, workInProgress);
14514
14515 // Check the host config to see if the children are offscreen/hidden.
14516 if (renderExpirationTime !== Never && workInProgress.mode & ConcurrentMode && shouldDeprioritizeSubtree(type, nextProps)) {
14517 // Schedule this fiber to re-render at offscreen priority. Then bailout.
14518 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
14519 return null;
14520 }
14521
14522 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14523 return workInProgress.child;
14524}
14525
14526function updateHostText(current$$1, workInProgress) {
14527 if (current$$1 === null) {
14528 tryToClaimNextHydratableInstance(workInProgress);
14529 }
14530 // Nothing to do here. This is terminal. We'll do the completion step
14531 // immediately after.
14532 return null;
14533}
14534
14535function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
14536 if (_current !== null) {
14537 // An lazy component only mounts if it suspended inside a non-
14538 // concurrent tree, in an inconsistent state. We want to treat it like
14539 // a new mount, even though an empty version of it already committed.
14540 // Disconnect the alternate pointers.
14541 _current.alternate = null;
14542 workInProgress.alternate = null;
14543 // Since this is conceptually a new fiber, schedule a Placement effect
14544 workInProgress.effectTag |= Placement;
14545 }
14546
14547 var props = workInProgress.pendingProps;
14548 // We can't start a User Timing measurement with correct label yet.
14549 // Cancel and resume right after we know the tag.
14550 cancelWorkTimer(workInProgress);
14551 var Component = readLazyComponentType(elementType);
14552 // Store the unwrapped component in the type.
14553 workInProgress.type = Component;
14554 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
14555 startWorkTimer(workInProgress);
14556 var resolvedProps = resolveDefaultProps(Component, props);
14557 var child = void 0;
14558 switch (resolvedTag) {
14559 case FunctionComponent:
14560 {
14561 {
14562 validateFunctionComponentInDev(workInProgress, Component);
14563 }
14564 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
14565 break;
14566 }
14567 case ClassComponent:
14568 {
14569 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
14570 break;
14571 }
14572 case ForwardRef:
14573 {
14574 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
14575 break;
14576 }
14577 case MemoComponent:
14578 {
14579 {
14580 if (workInProgress.type !== workInProgress.elementType) {
14581 var outerPropTypes = Component.propTypes;
14582 if (outerPropTypes) {
14583 checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only
14584 'prop', getComponentName(Component), getCurrentFiberStackInDev);
14585 }
14586 }
14587 }
14588 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
14589 updateExpirationTime, renderExpirationTime);
14590 break;
14591 }
14592 default:
14593 {
14594 var hint = '';
14595 {
14596 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
14597 hint = ' Did you wrap a component in React.lazy() more than once?';
14598 }
14599 }
14600 // This message intentionally doesn't mention ForwardRef or MemoComponent
14601 // because the fact that it's a separate type of work is an
14602 // implementation detail.
14603 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);
14604 }
14605 }
14606 return child;
14607}
14608
14609function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
14610 if (_current !== null) {
14611 // An incomplete component only mounts if it suspended inside a non-
14612 // concurrent tree, in an inconsistent state. We want to treat it like
14613 // a new mount, even though an empty version of it already committed.
14614 // Disconnect the alternate pointers.
14615 _current.alternate = null;
14616 workInProgress.alternate = null;
14617 // Since this is conceptually a new fiber, schedule a Placement effect
14618 workInProgress.effectTag |= Placement;
14619 }
14620
14621 // Promote the fiber to a class and try rendering again.
14622 workInProgress.tag = ClassComponent;
14623
14624 // The rest of this function is a fork of `updateClassComponent`
14625
14626 // Push context providers early to prevent context stack mismatches.
14627 // During mounting we don't know the child context yet as the instance doesn't exist.
14628 // We will invalidate the child context in finishClassComponent() right after rendering.
14629 var hasContext = void 0;
14630 if (isContextProvider(Component)) {
14631 hasContext = true;
14632 pushContextProvider(workInProgress);
14633 } else {
14634 hasContext = false;
14635 }
14636 prepareToReadContext(workInProgress, renderExpirationTime);
14637
14638 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14639 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
14640
14641 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
14642}
14643
14644function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
14645 if (_current !== null) {
14646 // An indeterminate component only mounts if it suspended inside a non-
14647 // concurrent tree, in an inconsistent state. We want to treat it like
14648 // a new mount, even though an empty version of it already committed.
14649 // Disconnect the alternate pointers.
14650 _current.alternate = null;
14651 workInProgress.alternate = null;
14652 // Since this is conceptually a new fiber, schedule a Placement effect
14653 workInProgress.effectTag |= Placement;
14654 }
14655
14656 var props = workInProgress.pendingProps;
14657 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
14658 var context = getMaskedContext(workInProgress, unmaskedContext);
14659
14660 prepareToReadContext(workInProgress, renderExpirationTime);
14661
14662 var value = void 0;
14663
14664 {
14665 if (Component.prototype && typeof Component.prototype.render === 'function') {
14666 var componentName = getComponentName(Component) || 'Unknown';
14667
14668 if (!didWarnAboutBadClass[componentName]) {
14669 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);
14670 didWarnAboutBadClass[componentName] = true;
14671 }
14672 }
14673
14674 if (workInProgress.mode & StrictMode) {
14675 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
14676 }
14677
14678 ReactCurrentOwner$3.current = workInProgress;
14679 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
14680 }
14681 // React DevTools reads this flag.
14682 workInProgress.effectTag |= PerformedWork;
14683
14684 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
14685 // Proceed under the assumption that this is a class instance
14686 workInProgress.tag = ClassComponent;
14687
14688 // Throw out any hooks that were used.
14689 resetHooks();
14690
14691 // Push context providers early to prevent context stack mismatches.
14692 // During mounting we don't know the child context yet as the instance doesn't exist.
14693 // We will invalidate the child context in finishClassComponent() right after rendering.
14694 var hasContext = false;
14695 if (isContextProvider(Component)) {
14696 hasContext = true;
14697 pushContextProvider(workInProgress);
14698 } else {
14699 hasContext = false;
14700 }
14701
14702 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
14703
14704 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
14705 if (typeof getDerivedStateFromProps === 'function') {
14706 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
14707 }
14708
14709 adoptClassInstance(workInProgress, value);
14710 mountClassInstance(workInProgress, Component, props, renderExpirationTime);
14711 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
14712 } else {
14713 // Proceed under the assumption that this is a function component
14714 workInProgress.tag = FunctionComponent;
14715 {
14716 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14717 // Only double-render components with Hooks
14718 if (workInProgress.memoizedState !== null) {
14719 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
14720 }
14721 }
14722 }
14723 reconcileChildren(null, workInProgress, value, renderExpirationTime);
14724 {
14725 validateFunctionComponentInDev(workInProgress, Component);
14726 }
14727 return workInProgress.child;
14728 }
14729}
14730
14731function validateFunctionComponentInDev(workInProgress, Component) {
14732 if (Component) {
14733 !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
14734 }
14735 if (workInProgress.ref !== null) {
14736 var info = '';
14737 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
14738 if (ownerName) {
14739 info += '\n\nCheck the render method of `' + ownerName + '`.';
14740 }
14741
14742 var warningKey = ownerName || workInProgress._debugID || '';
14743 var debugSource = workInProgress._debugSource;
14744 if (debugSource) {
14745 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
14746 }
14747 if (!didWarnAboutFunctionRefs[warningKey]) {
14748 didWarnAboutFunctionRefs[warningKey] = true;
14749 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);
14750 }
14751 }
14752
14753 if (typeof Component.getDerivedStateFromProps === 'function') {
14754 var componentName = getComponentName(Component) || 'Unknown';
14755
14756 if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) {
14757 warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', componentName);
14758 didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true;
14759 }
14760 }
14761
14762 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
14763 var _componentName = getComponentName(Component) || 'Unknown';
14764
14765 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName]) {
14766 warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName);
14767 didWarnAboutContextTypeOnFunctionComponent[_componentName] = true;
14768 }
14769 }
14770}
14771
14772function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
14773 var mode = workInProgress.mode;
14774 var nextProps = workInProgress.pendingProps;
14775
14776 // We should attempt to render the primary children unless this boundary
14777 // already suspended during this render (`alreadyCaptured` is true).
14778 var nextState = workInProgress.memoizedState;
14779
14780 var nextDidTimeout = void 0;
14781 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
14782 // This is the first attempt.
14783 nextState = null;
14784 nextDidTimeout = false;
14785 } else {
14786 // Something in this boundary's subtree already suspended. Switch to
14787 // rendering the fallback children.
14788 nextState = {
14789 timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork
14790 };
14791 nextDidTimeout = true;
14792 workInProgress.effectTag &= ~DidCapture;
14793 }
14794
14795 // This next part is a bit confusing. If the children timeout, we switch to
14796 // showing the fallback children in place of the "primary" children.
14797 // However, we don't want to delete the primary children because then their
14798 // state will be lost (both the React state and the host state, e.g.
14799 // uncontrolled form inputs). Instead we keep them mounted and hide them.
14800 // Both the fallback children AND the primary children are rendered at the
14801 // same time. Once the primary children are un-suspended, we can delete
14802 // the fallback children — don't need to preserve their state.
14803 //
14804 // The two sets of children are siblings in the host environment, but
14805 // semantically, for purposes of reconciliation, they are two separate sets.
14806 // So we store them using two fragment fibers.
14807 //
14808 // However, we want to avoid allocating extra fibers for every placeholder.
14809 // They're only necessary when the children time out, because that's the
14810 // only time when both sets are mounted.
14811 //
14812 // So, the extra fragment fibers are only used if the children time out.
14813 // Otherwise, we render the primary children directly. This requires some
14814 // custom reconciliation logic to preserve the state of the primary
14815 // children. It's essentially a very basic form of re-parenting.
14816
14817 // `child` points to the child fiber. In the normal case, this is the first
14818 // fiber of the primary children set. In the timed-out case, it's a
14819 // a fragment fiber containing the primary children.
14820 var child = void 0;
14821 // `next` points to the next fiber React should render. In the normal case,
14822 // it's the same as `child`: the first fiber of the primary children set.
14823 // In the timed-out case, it's a fragment fiber containing the *fallback*
14824 // children -- we skip over the primary children entirely.
14825 var next = void 0;
14826 if (current$$1 === null) {
14827 // This is the initial mount. This branch is pretty simple because there's
14828 // no previous state that needs to be preserved.
14829 if (nextDidTimeout) {
14830 // Mount separate fragments for primary and fallback children.
14831 var nextFallbackChildren = nextProps.fallback;
14832 var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
14833
14834 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
14835 // Outside of concurrent mode, we commit the effects from the
14836 var progressedState = workInProgress.memoizedState;
14837 var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
14838 primaryChildFragment.child = progressedPrimaryChild;
14839 }
14840
14841 var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
14842 primaryChildFragment.sibling = fallbackChildFragment;
14843 child = primaryChildFragment;
14844 // Skip the primary children, and continue working on the
14845 // fallback children.
14846 next = fallbackChildFragment;
14847 child.return = next.return = workInProgress;
14848 } else {
14849 // Mount the primary children without an intermediate fragment fiber.
14850 var nextPrimaryChildren = nextProps.children;
14851 child = next = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
14852 }
14853 } else {
14854 // This is an update. This branch is more complicated because we need to
14855 // ensure the state of the primary children is preserved.
14856 var prevState = current$$1.memoizedState;
14857 var prevDidTimeout = prevState !== null;
14858 if (prevDidTimeout) {
14859 // The current tree already timed out. That means each child set is
14860 var currentPrimaryChildFragment = current$$1.child;
14861 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
14862 if (nextDidTimeout) {
14863 // Still timed out. Reuse the current primary children by cloning
14864 // its fragment. We're going to skip over these entirely.
14865 var _nextFallbackChildren = nextProps.fallback;
14866 var _primaryChildFragment = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
14867
14868 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
14869 // Outside of concurrent mode, we commit the effects from the
14870 var _progressedState = workInProgress.memoizedState;
14871 var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
14872 if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
14873 _primaryChildFragment.child = _progressedPrimaryChild;
14874 }
14875 }
14876
14877 // Because primaryChildFragment is a new fiber that we're inserting as the
14878 // parent of a new tree, we need to set its treeBaseDuration.
14879 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
14880 // treeBaseDuration is the sum of all the child tree base durations.
14881 var treeBaseDuration = 0;
14882 var hiddenChild = _primaryChildFragment.child;
14883 while (hiddenChild !== null) {
14884 treeBaseDuration += hiddenChild.treeBaseDuration;
14885 hiddenChild = hiddenChild.sibling;
14886 }
14887 _primaryChildFragment.treeBaseDuration = treeBaseDuration;
14888 }
14889
14890 // Clone the fallback child fragment, too. These we'll continue
14891 // working on.
14892 var _fallbackChildFragment = _primaryChildFragment.sibling = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren, currentFallbackChildFragment.expirationTime);
14893 child = _primaryChildFragment;
14894 _primaryChildFragment.childExpirationTime = NoWork;
14895 // Skip the primary children, and continue working on the
14896 // fallback children.
14897 next = _fallbackChildFragment;
14898 child.return = next.return = workInProgress;
14899 } else {
14900 // No longer suspended. Switch back to showing the primary children,
14901 // and remove the intermediate fragment fiber.
14902 var _nextPrimaryChildren = nextProps.children;
14903 var currentPrimaryChild = currentPrimaryChildFragment.child;
14904 var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime);
14905
14906 // If this render doesn't suspend, we need to delete the fallback
14907 // children. Wait until the complete phase, after we've confirmed the
14908 // fallback is no longer needed.
14909 // TODO: Would it be better to store the fallback fragment on
14910 // the stateNode?
14911
14912 // Continue rendering the children, like we normally do.
14913 child = next = primaryChild;
14914 }
14915 } else {
14916 // The current tree has not already timed out. That means the primary
14917 // children are not wrapped in a fragment fiber.
14918 var _currentPrimaryChild = current$$1.child;
14919 if (nextDidTimeout) {
14920 // Timed out. Wrap the children in a fragment fiber to keep them
14921 // separate from the fallback children.
14922 var _nextFallbackChildren2 = nextProps.fallback;
14923 var _primaryChildFragment2 = createFiberFromFragment(
14924 // It shouldn't matter what the pending props are because we aren't
14925 // going to render this fragment.
14926 null, mode, NoWork, null);
14927 _primaryChildFragment2.child = _currentPrimaryChild;
14928
14929 // Even though we're creating a new fiber, there are no new children,
14930 // because we're reusing an already mounted tree. So we don't need to
14931 // schedule a placement.
14932 // primaryChildFragment.effectTag |= Placement;
14933
14934 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
14935 // Outside of concurrent mode, we commit the effects from the
14936 var _progressedState2 = workInProgress.memoizedState;
14937 var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
14938 _primaryChildFragment2.child = _progressedPrimaryChild2;
14939 }
14940
14941 // Because primaryChildFragment is a new fiber that we're inserting as the
14942 // parent of a new tree, we need to set its treeBaseDuration.
14943 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
14944 // treeBaseDuration is the sum of all the child tree base durations.
14945 var _treeBaseDuration = 0;
14946 var _hiddenChild = _primaryChildFragment2.child;
14947 while (_hiddenChild !== null) {
14948 _treeBaseDuration += _hiddenChild.treeBaseDuration;
14949 _hiddenChild = _hiddenChild.sibling;
14950 }
14951 _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
14952 }
14953
14954 // Create a fragment from the fallback children, too.
14955 var _fallbackChildFragment2 = _primaryChildFragment2.sibling = createFiberFromFragment(_nextFallbackChildren2, mode, renderExpirationTime, null);
14956 _fallbackChildFragment2.effectTag |= Placement;
14957 child = _primaryChildFragment2;
14958 _primaryChildFragment2.childExpirationTime = NoWork;
14959 // Skip the primary children, and continue working on the
14960 // fallback children.
14961 next = _fallbackChildFragment2;
14962 child.return = next.return = workInProgress;
14963 } else {
14964 // Still haven't timed out. Continue rendering the children, like we
14965 // normally do.
14966 var _nextPrimaryChildren2 = nextProps.children;
14967 next = child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
14968 }
14969 }
14970 workInProgress.stateNode = current$$1.stateNode;
14971 }
14972
14973 workInProgress.memoizedState = nextState;
14974 workInProgress.child = child;
14975 return next;
14976}
14977
14978function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) {
14979 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
14980 var nextChildren = workInProgress.pendingProps;
14981 if (current$$1 === null) {
14982 // Portals are special because we don't append the children during mount
14983 // but at commit. Therefore we need to track insertions which the normal
14984 // flow doesn't do during mount. This doesn't happen at the root because
14985 // the root always starts with a "current" with a null child.
14986 // TODO: Consider unifying this with how the root works.
14987 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
14988 } else {
14989 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
14990 }
14991 return workInProgress.child;
14992}
14993
14994function updateContextProvider(current$$1, workInProgress, renderExpirationTime) {
14995 var providerType = workInProgress.type;
14996 var context = providerType._context;
14997
14998 var newProps = workInProgress.pendingProps;
14999 var oldProps = workInProgress.memoizedProps;
15000
15001 var newValue = newProps.value;
15002
15003 {
15004 var providerPropTypes = workInProgress.type.propTypes;
15005
15006 if (providerPropTypes) {
15007 checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
15008 }
15009 }
15010
15011 pushProvider(workInProgress, newValue);
15012
15013 if (oldProps !== null) {
15014 var oldValue = oldProps.value;
15015 var changedBits = calculateChangedBits(context, newValue, oldValue);
15016 if (changedBits === 0) {
15017 // No change. Bailout early if children are the same.
15018 if (oldProps.children === newProps.children && !hasContextChanged()) {
15019 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15020 }
15021 } else {
15022 // The context value changed. Search for matching consumers and schedule
15023 // them to update.
15024 propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
15025 }
15026 }
15027
15028 var newChildren = newProps.children;
15029 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
15030 return workInProgress.child;
15031}
15032
15033var hasWarnedAboutUsingContextAsConsumer = false;
15034
15035function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) {
15036 var context = workInProgress.type;
15037 // The logic below for Context differs depending on PROD or DEV mode. In
15038 // DEV mode, we create a separate object for Context.Consumer that acts
15039 // like a proxy to Context. This proxy object adds unnecessary code in PROD
15040 // so we use the old behaviour (Context.Consumer references Context) to
15041 // reduce size and overhead. The separate object references context via
15042 // a property called "_context", which also gives us the ability to check
15043 // in DEV mode if this property exists or not and warn if it does not.
15044 {
15045 if (context._context === undefined) {
15046 // This may be because it's a Context (rather than a Consumer).
15047 // Or it may be because it's older React where they're the same thing.
15048 // We only want to warn if we're sure it's a new React.
15049 if (context !== context.Consumer) {
15050 if (!hasWarnedAboutUsingContextAsConsumer) {
15051 hasWarnedAboutUsingContextAsConsumer = true;
15052 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?');
15053 }
15054 }
15055 } else {
15056 context = context._context;
15057 }
15058 }
15059 var newProps = workInProgress.pendingProps;
15060 var render = newProps.children;
15061
15062 {
15063 !(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;
15064 }
15065
15066 prepareToReadContext(workInProgress, renderExpirationTime);
15067 var newValue = readContext(context, newProps.unstable_observedBits);
15068 var newChildren = void 0;
15069 {
15070 ReactCurrentOwner$3.current = workInProgress;
15071 setCurrentPhase('render');
15072 newChildren = render(newValue);
15073 setCurrentPhase(null);
15074 }
15075
15076 // React DevTools reads this flag.
15077 workInProgress.effectTag |= PerformedWork;
15078 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
15079 return workInProgress.child;
15080}
15081
15082function markWorkInProgressReceivedUpdate() {
15083 didReceiveUpdate = true;
15084}
15085
15086function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) {
15087 cancelWorkTimer(workInProgress);
15088
15089 if (current$$1 !== null) {
15090 // Reuse previous context list
15091 workInProgress.contextDependencies = current$$1.contextDependencies;
15092 }
15093
15094 if (enableProfilerTimer) {
15095 // Don't update "base" render times for bailouts.
15096 stopProfilerTimerIfRunning(workInProgress);
15097 }
15098
15099 // Check if the children have any pending work.
15100 var childExpirationTime = workInProgress.childExpirationTime;
15101 if (childExpirationTime < renderExpirationTime) {
15102 // The children don't have any work either. We can skip them.
15103 // TODO: Once we add back resuming, we should check if the children are
15104 // a work-in-progress set. If so, we need to transfer their effects.
15105 return null;
15106 } else {
15107 // This fiber doesn't have work, but its subtree does. Clone the child
15108 // fibers and continue.
15109 cloneChildFibers(current$$1, workInProgress);
15110 return workInProgress.child;
15111 }
15112}
15113
15114function beginWork(current$$1, workInProgress, renderExpirationTime) {
15115 var updateExpirationTime = workInProgress.expirationTime;
15116
15117 if (current$$1 !== null) {
15118 var oldProps = current$$1.memoizedProps;
15119 var newProps = workInProgress.pendingProps;
15120
15121 if (oldProps !== newProps || hasContextChanged()) {
15122 // If props or context changed, mark the fiber as having performed work.
15123 // This may be unset if the props are determined to be equal later (memo).
15124 didReceiveUpdate = true;
15125 } else if (updateExpirationTime < renderExpirationTime) {
15126 didReceiveUpdate = false;
15127 // This fiber does not have any pending work. Bailout without entering
15128 // the begin phase. There's still some bookkeeping we that needs to be done
15129 // in this optimized path, mostly pushing stuff onto the stack.
15130 switch (workInProgress.tag) {
15131 case HostRoot:
15132 pushHostRootContext(workInProgress);
15133 resetHydrationState();
15134 break;
15135 case HostComponent:
15136 pushHostContext(workInProgress);
15137 break;
15138 case ClassComponent:
15139 {
15140 var Component = workInProgress.type;
15141 if (isContextProvider(Component)) {
15142 pushContextProvider(workInProgress);
15143 }
15144 break;
15145 }
15146 case HostPortal:
15147 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
15148 break;
15149 case ContextProvider:
15150 {
15151 var newValue = workInProgress.memoizedProps.value;
15152 pushProvider(workInProgress, newValue);
15153 break;
15154 }
15155 case Profiler:
15156 if (enableProfilerTimer) {
15157 workInProgress.effectTag |= Update;
15158 }
15159 break;
15160 case SuspenseComponent:
15161 {
15162 var state = workInProgress.memoizedState;
15163 var didTimeout = state !== null;
15164 if (didTimeout) {
15165 // If this boundary is currently timed out, we need to decide
15166 // whether to retry the primary children, or to skip over it and
15167 // go straight to the fallback. Check the priority of the primary
15168 var primaryChildFragment = workInProgress.child;
15169 var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
15170 if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
15171 // The primary children have pending work. Use the normal path
15172 // to attempt to render the primary children again.
15173 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
15174 } else {
15175 // The primary children do not have pending work with sufficient
15176 // priority. Bailout.
15177 var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15178 if (child !== null) {
15179 // The fallback children have pending work. Skip over the
15180 // primary children and work on the fallback.
15181 return child.sibling;
15182 } else {
15183 return null;
15184 }
15185 }
15186 }
15187 break;
15188 }
15189 }
15190 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15191 }
15192 } else {
15193 didReceiveUpdate = false;
15194 }
15195
15196 // Before entering the begin phase, clear the expiration time.
15197 workInProgress.expirationTime = NoWork;
15198
15199 switch (workInProgress.tag) {
15200 case IndeterminateComponent:
15201 {
15202 var elementType = workInProgress.elementType;
15203 return mountIndeterminateComponent(current$$1, workInProgress, elementType, renderExpirationTime);
15204 }
15205 case LazyComponent:
15206 {
15207 var _elementType = workInProgress.elementType;
15208 return mountLazyComponent(current$$1, workInProgress, _elementType, updateExpirationTime, renderExpirationTime);
15209 }
15210 case FunctionComponent:
15211 {
15212 var _Component = workInProgress.type;
15213 var unresolvedProps = workInProgress.pendingProps;
15214 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
15215 return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime);
15216 }
15217 case ClassComponent:
15218 {
15219 var _Component2 = workInProgress.type;
15220 var _unresolvedProps = workInProgress.pendingProps;
15221 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
15222 return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
15223 }
15224 case HostRoot:
15225 return updateHostRoot(current$$1, workInProgress, renderExpirationTime);
15226 case HostComponent:
15227 return updateHostComponent(current$$1, workInProgress, renderExpirationTime);
15228 case HostText:
15229 return updateHostText(current$$1, workInProgress);
15230 case SuspenseComponent:
15231 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
15232 case HostPortal:
15233 return updatePortalComponent(current$$1, workInProgress, renderExpirationTime);
15234 case ForwardRef:
15235 {
15236 var type = workInProgress.type;
15237 var _unresolvedProps2 = workInProgress.pendingProps;
15238 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
15239 return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime);
15240 }
15241 case Fragment:
15242 return updateFragment(current$$1, workInProgress, renderExpirationTime);
15243 case Mode:
15244 return updateMode(current$$1, workInProgress, renderExpirationTime);
15245 case Profiler:
15246 return updateProfiler(current$$1, workInProgress, renderExpirationTime);
15247 case ContextProvider:
15248 return updateContextProvider(current$$1, workInProgress, renderExpirationTime);
15249 case ContextConsumer:
15250 return updateContextConsumer(current$$1, workInProgress, renderExpirationTime);
15251 case MemoComponent:
15252 {
15253 var _type2 = workInProgress.type;
15254 var _unresolvedProps3 = workInProgress.pendingProps;
15255 // Resolve outer props first, then resolve inner props.
15256 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
15257 {
15258 if (workInProgress.type !== workInProgress.elementType) {
15259 var outerPropTypes = _type2.propTypes;
15260 if (outerPropTypes) {
15261 checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only
15262 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
15263 }
15264 }
15265 }
15266 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
15267 return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
15268 }
15269 case SimpleMemoComponent:
15270 {
15271 return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
15272 }
15273 case IncompleteClassComponent:
15274 {
15275 var _Component3 = workInProgress.type;
15276 var _unresolvedProps4 = workInProgress.pendingProps;
15277 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
15278 return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
15279 }
15280 default:
15281 invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
15282 }
15283}
15284
15285var valueCursor = createCursor(null);
15286
15287var rendererSigil = void 0;
15288{
15289 // Use this to detect multiple renderers using the same context
15290 rendererSigil = {};
15291}
15292
15293var currentlyRenderingFiber = null;
15294var lastContextDependency = null;
15295var lastContextWithAllBitsObserved = null;
15296
15297var isDisallowedContextReadInDEV = false;
15298
15299function resetContextDependences() {
15300 // This is called right before React yields execution, to ensure `readContext`
15301 // cannot be called outside the render phase.
15302 currentlyRenderingFiber = null;
15303 lastContextDependency = null;
15304 lastContextWithAllBitsObserved = null;
15305 {
15306 isDisallowedContextReadInDEV = false;
15307 }
15308}
15309
15310function enterDisallowedContextReadInDEV() {
15311 {
15312 isDisallowedContextReadInDEV = true;
15313 }
15314}
15315
15316function exitDisallowedContextReadInDEV() {
15317 {
15318 isDisallowedContextReadInDEV = false;
15319 }
15320}
15321
15322function pushProvider(providerFiber, nextValue) {
15323 var context = providerFiber.type._context;
15324
15325 if (isPrimaryRenderer) {
15326 push(valueCursor, context._currentValue, providerFiber);
15327
15328 context._currentValue = nextValue;
15329 {
15330 !(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;
15331 context._currentRenderer = rendererSigil;
15332 }
15333 } else {
15334 push(valueCursor, context._currentValue2, providerFiber);
15335
15336 context._currentValue2 = nextValue;
15337 {
15338 !(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;
15339 context._currentRenderer2 = rendererSigil;
15340 }
15341 }
15342}
15343
15344function popProvider(providerFiber) {
15345 var currentValue = valueCursor.current;
15346
15347 pop(valueCursor, providerFiber);
15348
15349 var context = providerFiber.type._context;
15350 if (isPrimaryRenderer) {
15351 context._currentValue = currentValue;
15352 } else {
15353 context._currentValue2 = currentValue;
15354 }
15355}
15356
15357function calculateChangedBits(context, newValue, oldValue) {
15358 if (is(oldValue, newValue)) {
15359 // No change
15360 return 0;
15361 } else {
15362 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : maxSigned31BitInt;
15363
15364 {
15365 !((changedBits & maxSigned31BitInt) === changedBits) ? warning$1(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0;
15366 }
15367 return changedBits | 0;
15368 }
15369}
15370
15371function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
15372 var fiber = workInProgress.child;
15373 if (fiber !== null) {
15374 // Set the return pointer of the child to the work-in-progress fiber.
15375 fiber.return = workInProgress;
15376 }
15377 while (fiber !== null) {
15378 var nextFiber = void 0;
15379
15380 // Visit this fiber.
15381 var list = fiber.contextDependencies;
15382 if (list !== null) {
15383 nextFiber = fiber.child;
15384
15385 var dependency = list.first;
15386 while (dependency !== null) {
15387 // Check if the context matches.
15388 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
15389 // Match! Schedule an update on this fiber.
15390
15391 if (fiber.tag === ClassComponent) {
15392 // Schedule a force update on the work-in-progress.
15393 var update = createUpdate(renderExpirationTime);
15394 update.tag = ForceUpdate;
15395 // TODO: Because we don't have a work-in-progress, this will add the
15396 // update to the current fiber, too, which means it will persist even if
15397 // this render is thrown away. Since it's a race condition, not sure it's
15398 // worth fixing.
15399 enqueueUpdate(fiber, update);
15400 }
15401
15402 if (fiber.expirationTime < renderExpirationTime) {
15403 fiber.expirationTime = renderExpirationTime;
15404 }
15405 var alternate = fiber.alternate;
15406 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
15407 alternate.expirationTime = renderExpirationTime;
15408 }
15409 // Update the child expiration time of all the ancestors, including
15410 // the alternates.
15411 var node = fiber.return;
15412 while (node !== null) {
15413 alternate = node.alternate;
15414 if (node.childExpirationTime < renderExpirationTime) {
15415 node.childExpirationTime = renderExpirationTime;
15416 if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
15417 alternate.childExpirationTime = renderExpirationTime;
15418 }
15419 } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
15420 alternate.childExpirationTime = renderExpirationTime;
15421 } else {
15422 // Neither alternate was updated, which means the rest of the
15423 // ancestor path already has sufficient priority.
15424 break;
15425 }
15426 node = node.return;
15427 }
15428
15429 // Mark the expiration time on the list, too.
15430 if (list.expirationTime < renderExpirationTime) {
15431 list.expirationTime = renderExpirationTime;
15432 }
15433
15434 // Since we already found a match, we can stop traversing the
15435 // dependency list.
15436 break;
15437 }
15438 dependency = dependency.next;
15439 }
15440 } else if (fiber.tag === ContextProvider) {
15441 // Don't scan deeper if this is a matching provider
15442 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
15443 } else {
15444 // Traverse down.
15445 nextFiber = fiber.child;
15446 }
15447
15448 if (nextFiber !== null) {
15449 // Set the return pointer of the child to the work-in-progress fiber.
15450 nextFiber.return = fiber;
15451 } else {
15452 // No child. Traverse to next sibling.
15453 nextFiber = fiber;
15454 while (nextFiber !== null) {
15455 if (nextFiber === workInProgress) {
15456 // We're back to the root of this subtree. Exit.
15457 nextFiber = null;
15458 break;
15459 }
15460 var sibling = nextFiber.sibling;
15461 if (sibling !== null) {
15462 // Set the return pointer of the sibling to the work-in-progress fiber.
15463 sibling.return = nextFiber.return;
15464 nextFiber = sibling;
15465 break;
15466 }
15467 // No more siblings. Traverse up.
15468 nextFiber = nextFiber.return;
15469 }
15470 }
15471 fiber = nextFiber;
15472 }
15473}
15474
15475function prepareToReadContext(workInProgress, renderExpirationTime) {
15476 currentlyRenderingFiber = workInProgress;
15477 lastContextDependency = null;
15478 lastContextWithAllBitsObserved = null;
15479
15480 var currentDependencies = workInProgress.contextDependencies;
15481 if (currentDependencies !== null && currentDependencies.expirationTime >= renderExpirationTime) {
15482 // Context list has a pending update. Mark that this fiber performed work.
15483 markWorkInProgressReceivedUpdate();
15484 }
15485
15486 // Reset the work-in-progress list
15487 workInProgress.contextDependencies = null;
15488}
15489
15490function readContext(context, observedBits) {
15491 {
15492 // This warning would fire if you read context inside a Hook like useMemo.
15493 // Unlike the class check below, it's not enforced in production for perf.
15494 !!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;
15495 }
15496
15497 if (lastContextWithAllBitsObserved === context) {
15498 // Nothing to do. We already observe everything in this context.
15499 } else if (observedBits === false || observedBits === 0) {
15500 // Do not observe any updates.
15501 } else {
15502 var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types.
15503 if (typeof observedBits !== 'number' || observedBits === maxSigned31BitInt) {
15504 // Observe all updates.
15505 lastContextWithAllBitsObserved = context;
15506 resolvedObservedBits = maxSigned31BitInt;
15507 } else {
15508 resolvedObservedBits = observedBits;
15509 }
15510
15511 var contextItem = {
15512 context: context,
15513 observedBits: resolvedObservedBits,
15514 next: null
15515 };
15516
15517 if (lastContextDependency === null) {
15518 !(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;
15519
15520 // This is the first dependency for this component. Create a new list.
15521 lastContextDependency = contextItem;
15522 currentlyRenderingFiber.contextDependencies = {
15523 first: contextItem,
15524 expirationTime: NoWork
15525 };
15526 } else {
15527 // Append a new context item.
15528 lastContextDependency = lastContextDependency.next = contextItem;
15529 }
15530 }
15531 return isPrimaryRenderer ? context._currentValue : context._currentValue2;
15532}
15533
15534// UpdateQueue is a linked list of prioritized updates.
15535//
15536// Like fibers, update queues come in pairs: a current queue, which represents
15537// the visible state of the screen, and a work-in-progress queue, which can be
15538// mutated and processed asynchronously before it is committed — a form of
15539// double buffering. If a work-in-progress render is discarded before finishing,
15540// we create a new work-in-progress by cloning the current queue.
15541//
15542// Both queues share a persistent, singly-linked list structure. To schedule an
15543// update, we append it to the end of both queues. Each queue maintains a
15544// pointer to first update in the persistent list that hasn't been processed.
15545// The work-in-progress pointer always has a position equal to or greater than
15546// the current queue, since we always work on that one. The current queue's
15547// pointer is only updated during the commit phase, when we swap in the
15548// work-in-progress.
15549//
15550// For example:
15551//
15552// Current pointer: A - B - C - D - E - F
15553// Work-in-progress pointer: D - E - F
15554// ^
15555// The work-in-progress queue has
15556// processed more updates than current.
15557//
15558// The reason we append to both queues is because otherwise we might drop
15559// updates without ever processing them. For example, if we only add updates to
15560// the work-in-progress queue, some updates could be lost whenever a work-in
15561// -progress render restarts by cloning from current. Similarly, if we only add
15562// updates to the current queue, the updates will be lost whenever an already
15563// in-progress queue commits and swaps with the current queue. However, by
15564// adding to both queues, we guarantee that the update will be part of the next
15565// work-in-progress. (And because the work-in-progress queue becomes the
15566// current queue once it commits, there's no danger of applying the same
15567// update twice.)
15568//
15569// Prioritization
15570// --------------
15571//
15572// Updates are not sorted by priority, but by insertion; new updates are always
15573// appended to the end of the list.
15574//
15575// The priority is still important, though. When processing the update queue
15576// during the render phase, only the updates with sufficient priority are
15577// included in the result. If we skip an update because it has insufficient
15578// priority, it remains in the queue to be processed later, during a lower
15579// priority render. Crucially, all updates subsequent to a skipped update also
15580// remain in the queue *regardless of their priority*. That means high priority
15581// updates are sometimes processed twice, at two separate priorities. We also
15582// keep track of a base state, that represents the state before the first
15583// update in the queue is applied.
15584//
15585// For example:
15586//
15587// Given a base state of '', and the following queue of updates
15588//
15589// A1 - B2 - C1 - D2
15590//
15591// where the number indicates the priority, and the update is applied to the
15592// previous state by appending a letter, React will process these updates as
15593// two separate renders, one per distinct priority level:
15594//
15595// First render, at priority 1:
15596// Base state: ''
15597// Updates: [A1, C1]
15598// Result state: 'AC'
15599//
15600// Second render, at priority 2:
15601// Base state: 'A' <- The base state does not include C1,
15602// because B2 was skipped.
15603// Updates: [B2, C1, D2] <- C1 was rebased on top of B2
15604// Result state: 'ABCD'
15605//
15606// Because we process updates in insertion order, and rebase high priority
15607// updates when preceding updates are skipped, the final result is deterministic
15608// regardless of priority. Intermediate state may vary according to system
15609// resources, but the final state is always the same.
15610
15611var UpdateState = 0;
15612var ReplaceState = 1;
15613var ForceUpdate = 2;
15614var CaptureUpdate = 3;
15615
15616// Global state that is reset at the beginning of calling `processUpdateQueue`.
15617// It should only be read right after calling `processUpdateQueue`, via
15618// `checkHasForceUpdateAfterProcessing`.
15619var hasForceUpdate = false;
15620
15621var didWarnUpdateInsideUpdate = void 0;
15622var currentlyProcessingQueue = void 0;
15623var resetCurrentlyProcessingQueue = void 0;
15624{
15625 didWarnUpdateInsideUpdate = false;
15626 currentlyProcessingQueue = null;
15627 resetCurrentlyProcessingQueue = function () {
15628 currentlyProcessingQueue = null;
15629 };
15630}
15631
15632function createUpdateQueue(baseState) {
15633 var queue = {
15634 baseState: baseState,
15635 firstUpdate: null,
15636 lastUpdate: null,
15637 firstCapturedUpdate: null,
15638 lastCapturedUpdate: null,
15639 firstEffect: null,
15640 lastEffect: null,
15641 firstCapturedEffect: null,
15642 lastCapturedEffect: null
15643 };
15644 return queue;
15645}
15646
15647function cloneUpdateQueue(currentQueue) {
15648 var queue = {
15649 baseState: currentQueue.baseState,
15650 firstUpdate: currentQueue.firstUpdate,
15651 lastUpdate: currentQueue.lastUpdate,
15652
15653 // TODO: With resuming, if we bail out and resuse the child tree, we should
15654 // keep these effects.
15655 firstCapturedUpdate: null,
15656 lastCapturedUpdate: null,
15657
15658 firstEffect: null,
15659 lastEffect: null,
15660
15661 firstCapturedEffect: null,
15662 lastCapturedEffect: null
15663 };
15664 return queue;
15665}
15666
15667function createUpdate(expirationTime) {
15668 return {
15669 expirationTime: expirationTime,
15670
15671 tag: UpdateState,
15672 payload: null,
15673 callback: null,
15674
15675 next: null,
15676 nextEffect: null
15677 };
15678}
15679
15680function appendUpdateToQueue(queue, update) {
15681 // Append the update to the end of the list.
15682 if (queue.lastUpdate === null) {
15683 // Queue is empty
15684 queue.firstUpdate = queue.lastUpdate = update;
15685 } else {
15686 queue.lastUpdate.next = update;
15687 queue.lastUpdate = update;
15688 }
15689}
15690
15691function enqueueUpdate(fiber, update) {
15692 // Update queues are created lazily.
15693 var alternate = fiber.alternate;
15694 var queue1 = void 0;
15695 var queue2 = void 0;
15696 if (alternate === null) {
15697 // There's only one fiber.
15698 queue1 = fiber.updateQueue;
15699 queue2 = null;
15700 if (queue1 === null) {
15701 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
15702 }
15703 } else {
15704 // There are two owners.
15705 queue1 = fiber.updateQueue;
15706 queue2 = alternate.updateQueue;
15707 if (queue1 === null) {
15708 if (queue2 === null) {
15709 // Neither fiber has an update queue. Create new ones.
15710 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
15711 queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
15712 } else {
15713 // Only one fiber has an update queue. Clone to create a new one.
15714 queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
15715 }
15716 } else {
15717 if (queue2 === null) {
15718 // Only one fiber has an update queue. Clone to create a new one.
15719 queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
15720 } else {
15721 // Both owners have an update queue.
15722 }
15723 }
15724 }
15725 if (queue2 === null || queue1 === queue2) {
15726 // There's only a single queue.
15727 appendUpdateToQueue(queue1, update);
15728 } else {
15729 // There are two queues. We need to append the update to both queues,
15730 // while accounting for the persistent structure of the list — we don't
15731 // want the same update to be added multiple times.
15732 if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
15733 // One of the queues is not empty. We must add the update to both queues.
15734 appendUpdateToQueue(queue1, update);
15735 appendUpdateToQueue(queue2, update);
15736 } else {
15737 // Both queues are non-empty. The last update is the same in both lists,
15738 // because of structural sharing. So, only append to one of the lists.
15739 appendUpdateToQueue(queue1, update);
15740 // But we still need to update the `lastUpdate` pointer of queue2.
15741 queue2.lastUpdate = update;
15742 }
15743 }
15744
15745 {
15746 if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
15747 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.');
15748 didWarnUpdateInsideUpdate = true;
15749 }
15750 }
15751}
15752
15753function enqueueCapturedUpdate(workInProgress, update) {
15754 // Captured updates go into a separate list, and only on the work-in-
15755 // progress queue.
15756 var workInProgressQueue = workInProgress.updateQueue;
15757 if (workInProgressQueue === null) {
15758 workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
15759 } else {
15760 // TODO: I put this here rather than createWorkInProgress so that we don't
15761 // clone the queue unnecessarily. There's probably a better way to
15762 // structure this.
15763 workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
15764 }
15765
15766 // Append the update to the end of the list.
15767 if (workInProgressQueue.lastCapturedUpdate === null) {
15768 // This is the first render phase update
15769 workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
15770 } else {
15771 workInProgressQueue.lastCapturedUpdate.next = update;
15772 workInProgressQueue.lastCapturedUpdate = update;
15773 }
15774}
15775
15776function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
15777 var current = workInProgress.alternate;
15778 if (current !== null) {
15779 // If the work-in-progress queue is equal to the current queue,
15780 // we need to clone it first.
15781 if (queue === current.updateQueue) {
15782 queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
15783 }
15784 }
15785 return queue;
15786}
15787
15788function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
15789 switch (update.tag) {
15790 case ReplaceState:
15791 {
15792 var _payload = update.payload;
15793 if (typeof _payload === 'function') {
15794 // Updater function
15795 {
15796 enterDisallowedContextReadInDEV();
15797 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
15798 _payload.call(instance, prevState, nextProps);
15799 }
15800 }
15801 var nextState = _payload.call(instance, prevState, nextProps);
15802 {
15803 exitDisallowedContextReadInDEV();
15804 }
15805 return nextState;
15806 }
15807 // State object
15808 return _payload;
15809 }
15810 case CaptureUpdate:
15811 {
15812 workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
15813 }
15814 // Intentional fallthrough
15815 case UpdateState:
15816 {
15817 var _payload2 = update.payload;
15818 var partialState = void 0;
15819 if (typeof _payload2 === 'function') {
15820 // Updater function
15821 {
15822 enterDisallowedContextReadInDEV();
15823 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
15824 _payload2.call(instance, prevState, nextProps);
15825 }
15826 }
15827 partialState = _payload2.call(instance, prevState, nextProps);
15828 {
15829 exitDisallowedContextReadInDEV();
15830 }
15831 } else {
15832 // Partial state object
15833 partialState = _payload2;
15834 }
15835 if (partialState === null || partialState === undefined) {
15836 // Null and undefined are treated as no-ops.
15837 return prevState;
15838 }
15839 // Merge the partial state and the previous state.
15840 return _assign({}, prevState, partialState);
15841 }
15842 case ForceUpdate:
15843 {
15844 hasForceUpdate = true;
15845 return prevState;
15846 }
15847 }
15848 return prevState;
15849}
15850
15851function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
15852 hasForceUpdate = false;
15853
15854 queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
15855
15856 {
15857 currentlyProcessingQueue = queue;
15858 }
15859
15860 // These values may change as we process the queue.
15861 var newBaseState = queue.baseState;
15862 var newFirstUpdate = null;
15863 var newExpirationTime = NoWork;
15864
15865 // Iterate through the list of updates to compute the result.
15866 var update = queue.firstUpdate;
15867 var resultState = newBaseState;
15868 while (update !== null) {
15869 var updateExpirationTime = update.expirationTime;
15870 if (updateExpirationTime < renderExpirationTime) {
15871 // This update does not have sufficient priority. Skip it.
15872 if (newFirstUpdate === null) {
15873 // This is the first skipped update. It will be the first update in
15874 // the new list.
15875 newFirstUpdate = update;
15876 // Since this is the first update that was skipped, the current result
15877 // is the new base state.
15878 newBaseState = resultState;
15879 }
15880 // Since this update will remain in the list, update the remaining
15881 // expiration time.
15882 if (newExpirationTime < updateExpirationTime) {
15883 newExpirationTime = updateExpirationTime;
15884 }
15885 } else {
15886 // This update does have sufficient priority. Process it and compute
15887 // a new result.
15888 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
15889 var _callback = update.callback;
15890 if (_callback !== null) {
15891 workInProgress.effectTag |= Callback;
15892 // Set this to null, in case it was mutated during an aborted render.
15893 update.nextEffect = null;
15894 if (queue.lastEffect === null) {
15895 queue.firstEffect = queue.lastEffect = update;
15896 } else {
15897 queue.lastEffect.nextEffect = update;
15898 queue.lastEffect = update;
15899 }
15900 }
15901 }
15902 // Continue to the next update.
15903 update = update.next;
15904 }
15905
15906 // Separately, iterate though the list of captured updates.
15907 var newFirstCapturedUpdate = null;
15908 update = queue.firstCapturedUpdate;
15909 while (update !== null) {
15910 var _updateExpirationTime = update.expirationTime;
15911 if (_updateExpirationTime < renderExpirationTime) {
15912 // This update does not have sufficient priority. Skip it.
15913 if (newFirstCapturedUpdate === null) {
15914 // This is the first skipped captured update. It will be the first
15915 // update in the new list.
15916 newFirstCapturedUpdate = update;
15917 // If this is the first update that was skipped, the current result is
15918 // the new base state.
15919 if (newFirstUpdate === null) {
15920 newBaseState = resultState;
15921 }
15922 }
15923 // Since this update will remain in the list, update the remaining
15924 // expiration time.
15925 if (newExpirationTime < _updateExpirationTime) {
15926 newExpirationTime = _updateExpirationTime;
15927 }
15928 } else {
15929 // This update does have sufficient priority. Process it and compute
15930 // a new result.
15931 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
15932 var _callback2 = update.callback;
15933 if (_callback2 !== null) {
15934 workInProgress.effectTag |= Callback;
15935 // Set this to null, in case it was mutated during an aborted render.
15936 update.nextEffect = null;
15937 if (queue.lastCapturedEffect === null) {
15938 queue.firstCapturedEffect = queue.lastCapturedEffect = update;
15939 } else {
15940 queue.lastCapturedEffect.nextEffect = update;
15941 queue.lastCapturedEffect = update;
15942 }
15943 }
15944 }
15945 update = update.next;
15946 }
15947
15948 if (newFirstUpdate === null) {
15949 queue.lastUpdate = null;
15950 }
15951 if (newFirstCapturedUpdate === null) {
15952 queue.lastCapturedUpdate = null;
15953 } else {
15954 workInProgress.effectTag |= Callback;
15955 }
15956 if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
15957 // We processed every update, without skipping. That means the new base
15958 // state is the same as the result state.
15959 newBaseState = resultState;
15960 }
15961
15962 queue.baseState = newBaseState;
15963 queue.firstUpdate = newFirstUpdate;
15964 queue.firstCapturedUpdate = newFirstCapturedUpdate;
15965
15966 // Set the remaining expiration time to be whatever is remaining in the queue.
15967 // This should be fine because the only two other things that contribute to
15968 // expiration time are props and context. We're already in the middle of the
15969 // begin phase by the time we start processing the queue, so we've already
15970 // dealt with the props. Context in components that specify
15971 // shouldComponentUpdate is tricky; but we'll have to account for
15972 // that regardless.
15973 workInProgress.expirationTime = newExpirationTime;
15974 workInProgress.memoizedState = resultState;
15975
15976 {
15977 currentlyProcessingQueue = null;
15978 }
15979}
15980
15981function callCallback(callback, context) {
15982 !(typeof callback === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', callback) : void 0;
15983 callback.call(context);
15984}
15985
15986function resetHasForceUpdateBeforeProcessing() {
15987 hasForceUpdate = false;
15988}
15989
15990function checkHasForceUpdateAfterProcessing() {
15991 return hasForceUpdate;
15992}
15993
15994function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
15995 // If the finished render included captured updates, and there are still
15996 // lower priority updates left over, we need to keep the captured updates
15997 // in the queue so that they are rebased and not dropped once we process the
15998 // queue again at the lower priority.
15999 if (finishedQueue.firstCapturedUpdate !== null) {
16000 // Join the captured update list to the end of the normal list.
16001 if (finishedQueue.lastUpdate !== null) {
16002 finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
16003 finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
16004 }
16005 // Clear the list of captured updates.
16006 finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
16007 }
16008
16009 // Commit the effects
16010 commitUpdateEffects(finishedQueue.firstEffect, instance);
16011 finishedQueue.firstEffect = finishedQueue.lastEffect = null;
16012
16013 commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
16014 finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
16015}
16016
16017function commitUpdateEffects(effect, instance) {
16018 while (effect !== null) {
16019 var _callback3 = effect.callback;
16020 if (_callback3 !== null) {
16021 effect.callback = null;
16022 callCallback(_callback3, instance);
16023 }
16024 effect = effect.nextEffect;
16025 }
16026}
16027
16028function createCapturedValue(value, source) {
16029 // If the value is an error, call this function immediately after it is thrown
16030 // so the stack is accurate.
16031 return {
16032 value: value,
16033 source: source,
16034 stack: getStackByFiberInDevAndProd(source)
16035 };
16036}
16037
16038function markUpdate(workInProgress) {
16039 // Tag the fiber with an update effect. This turns a Placement into
16040 // a PlacementAndUpdate.
16041 workInProgress.effectTag |= Update;
16042}
16043
16044function markRef$1(workInProgress) {
16045 workInProgress.effectTag |= Ref;
16046}
16047
16048var appendAllChildren = void 0;
16049var updateHostContainer = void 0;
16050var updateHostComponent$1 = void 0;
16051var updateHostText$1 = void 0;
16052if (supportsMutation) {
16053 // Mutation mode
16054
16055 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
16056 // We only have the top Fiber that was created but we need recurse down its
16057 // children to find all the terminal nodes.
16058 var node = workInProgress.child;
16059 while (node !== null) {
16060 if (node.tag === HostComponent || node.tag === HostText) {
16061 appendInitialChild(parent, node.stateNode);
16062 } else if (node.tag === HostPortal) {
16063 // If we have a portal child, then we don't want to traverse
16064 // down its children. Instead, we'll get insertions from each child in
16065 // the portal directly.
16066 } else if (node.child !== null) {
16067 node.child.return = node;
16068 node = node.child;
16069 continue;
16070 }
16071 if (node === workInProgress) {
16072 return;
16073 }
16074 while (node.sibling === null) {
16075 if (node.return === null || node.return === workInProgress) {
16076 return;
16077 }
16078 node = node.return;
16079 }
16080 node.sibling.return = node.return;
16081 node = node.sibling;
16082 }
16083 };
16084
16085 updateHostContainer = function (workInProgress) {
16086 // Noop
16087 };
16088 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
16089 // If we have an alternate, that means this is an update and we need to
16090 // schedule a side-effect to do the updates.
16091 var oldProps = current.memoizedProps;
16092 if (oldProps === newProps) {
16093 // In mutation mode, this is sufficient for a bailout because
16094 // we won't touch this node even if children changed.
16095 return;
16096 }
16097
16098 // If we get updated because one of our children updated, we don't
16099 // have newProps so we'll have to reuse them.
16100 // TODO: Split the update API as separate for the props vs. children.
16101 // Even better would be if children weren't special cased at all tho.
16102 var instance = workInProgress.stateNode;
16103 var currentHostContext = getHostContext();
16104 // TODO: Experiencing an error where oldProps is null. Suggests a host
16105 // component is hitting the resume path. Figure out why. Possibly
16106 // related to `hidden`.
16107 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
16108 // TODO: Type this specific to this type of component.
16109 workInProgress.updateQueue = updatePayload;
16110 // If the update payload indicates that there is a change or if there
16111 // is a new ref we mark this as an update. All the work is done in commitWork.
16112 if (updatePayload) {
16113 markUpdate(workInProgress);
16114 }
16115 };
16116 updateHostText$1 = function (current, workInProgress, oldText, newText) {
16117 // If the text differs, mark it as an update. All the work in done in commitWork.
16118 if (oldText !== newText) {
16119 markUpdate(workInProgress);
16120 }
16121 };
16122} else if (supportsPersistence) {
16123 // Persistent host tree mode
16124
16125 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
16126 // We only have the top Fiber that was created but we need recurse down its
16127 // children to find all the terminal nodes.
16128 var node = workInProgress.child;
16129 while (node !== null) {
16130 // eslint-disable-next-line no-labels
16131 branches: if (node.tag === HostComponent) {
16132 var instance = node.stateNode;
16133 if (needsVisibilityToggle) {
16134 var props = node.memoizedProps;
16135 var type = node.type;
16136 if (isHidden) {
16137 // This child is inside a timed out tree. Hide it.
16138 instance = cloneHiddenInstance(instance, type, props, node);
16139 } else {
16140 // This child was previously inside a timed out tree. If it was not
16141 // updated during this render, it may need to be unhidden. Clone
16142 // again to be sure.
16143 instance = cloneUnhiddenInstance(instance, type, props, node);
16144 }
16145 node.stateNode = instance;
16146 }
16147 appendInitialChild(parent, instance);
16148 } else if (node.tag === HostText) {
16149 var _instance = node.stateNode;
16150 if (needsVisibilityToggle) {
16151 var text = node.memoizedProps;
16152 var rootContainerInstance = getRootHostContainer();
16153 var currentHostContext = getHostContext();
16154 if (isHidden) {
16155 _instance = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16156 } else {
16157 _instance = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16158 }
16159 node.stateNode = _instance;
16160 }
16161 appendInitialChild(parent, _instance);
16162 } else if (node.tag === HostPortal) {
16163 // If we have a portal child, then we don't want to traverse
16164 // down its children. Instead, we'll get insertions from each child in
16165 // the portal directly.
16166 } else if (node.tag === SuspenseComponent) {
16167 var current = node.alternate;
16168 if (current !== null) {
16169 var oldState = current.memoizedState;
16170 var newState = node.memoizedState;
16171 var oldIsHidden = oldState !== null;
16172 var newIsHidden = newState !== null;
16173 if (oldIsHidden !== newIsHidden) {
16174 // The placeholder either just timed out or switched back to the normal
16175 // children after having previously timed out. Toggle the visibility of
16176 // the direct host children.
16177 var primaryChildParent = newIsHidden ? node.child : node;
16178 if (primaryChildParent !== null) {
16179 appendAllChildren(parent, primaryChildParent, true, newIsHidden);
16180 }
16181 // eslint-disable-next-line no-labels
16182 break branches;
16183 }
16184 }
16185 if (node.child !== null) {
16186 // Continue traversing like normal
16187 node.child.return = node;
16188 node = node.child;
16189 continue;
16190 }
16191 } else if (node.child !== null) {
16192 node.child.return = node;
16193 node = node.child;
16194 continue;
16195 }
16196 // $FlowFixMe This is correct but Flow is confused by the labeled break.
16197 node = node;
16198 if (node === workInProgress) {
16199 return;
16200 }
16201 while (node.sibling === null) {
16202 if (node.return === null || node.return === workInProgress) {
16203 return;
16204 }
16205 node = node.return;
16206 }
16207 node.sibling.return = node.return;
16208 node = node.sibling;
16209 }
16210 };
16211
16212 // An unfortunate fork of appendAllChildren because we have two different parent types.
16213 var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
16214 // We only have the top Fiber that was created but we need recurse down its
16215 // children to find all the terminal nodes.
16216 var node = workInProgress.child;
16217 while (node !== null) {
16218 // eslint-disable-next-line no-labels
16219 branches: if (node.tag === HostComponent) {
16220 var instance = node.stateNode;
16221 if (needsVisibilityToggle) {
16222 var props = node.memoizedProps;
16223 var type = node.type;
16224 if (isHidden) {
16225 // This child is inside a timed out tree. Hide it.
16226 instance = cloneHiddenInstance(instance, type, props, node);
16227 } else {
16228 // This child was previously inside a timed out tree. If it was not
16229 // updated during this render, it may need to be unhidden. Clone
16230 // again to be sure.
16231 instance = cloneUnhiddenInstance(instance, type, props, node);
16232 }
16233 node.stateNode = instance;
16234 }
16235 appendChildToContainerChildSet(containerChildSet, instance);
16236 } else if (node.tag === HostText) {
16237 var _instance2 = node.stateNode;
16238 if (needsVisibilityToggle) {
16239 var text = node.memoizedProps;
16240 var rootContainerInstance = getRootHostContainer();
16241 var currentHostContext = getHostContext();
16242 if (isHidden) {
16243 _instance2 = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16244 } else {
16245 _instance2 = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
16246 }
16247 node.stateNode = _instance2;
16248 }
16249 appendChildToContainerChildSet(containerChildSet, _instance2);
16250 } else if (node.tag === HostPortal) {
16251 // If we have a portal child, then we don't want to traverse
16252 // down its children. Instead, we'll get insertions from each child in
16253 // the portal directly.
16254 } else if (node.tag === SuspenseComponent) {
16255 var current = node.alternate;
16256 if (current !== null) {
16257 var oldState = current.memoizedState;
16258 var newState = node.memoizedState;
16259 var oldIsHidden = oldState !== null;
16260 var newIsHidden = newState !== null;
16261 if (oldIsHidden !== newIsHidden) {
16262 // The placeholder either just timed out or switched back to the normal
16263 // children after having previously timed out. Toggle the visibility of
16264 // the direct host children.
16265 var primaryChildParent = newIsHidden ? node.child : node;
16266 if (primaryChildParent !== null) {
16267 appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
16268 }
16269 // eslint-disable-next-line no-labels
16270 break branches;
16271 }
16272 }
16273 if (node.child !== null) {
16274 // Continue traversing like normal
16275 node.child.return = node;
16276 node = node.child;
16277 continue;
16278 }
16279 } else if (node.child !== null) {
16280 node.child.return = node;
16281 node = node.child;
16282 continue;
16283 }
16284 // $FlowFixMe This is correct but Flow is confused by the labeled break.
16285 node = node;
16286 if (node === workInProgress) {
16287 return;
16288 }
16289 while (node.sibling === null) {
16290 if (node.return === null || node.return === workInProgress) {
16291 return;
16292 }
16293 node = node.return;
16294 }
16295 node.sibling.return = node.return;
16296 node = node.sibling;
16297 }
16298 };
16299 updateHostContainer = function (workInProgress) {
16300 var portalOrRoot = workInProgress.stateNode;
16301 var childrenUnchanged = workInProgress.firstEffect === null;
16302 if (childrenUnchanged) {
16303 // No changes, just reuse the existing instance.
16304 } else {
16305 var container = portalOrRoot.containerInfo;
16306 var newChildSet = createContainerChildSet(container);
16307 // If children might have changed, we have to add them all to the set.
16308 appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
16309 portalOrRoot.pendingChildren = newChildSet;
16310 // Schedule an update on the container to swap out the container.
16311 markUpdate(workInProgress);
16312 finalizeContainerChildren(container, newChildSet);
16313 }
16314 };
16315 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
16316 var currentInstance = current.stateNode;
16317 var oldProps = current.memoizedProps;
16318 // If there are no effects associated with this node, then none of our children had any updates.
16319 // This guarantees that we can reuse all of them.
16320 var childrenUnchanged = workInProgress.firstEffect === null;
16321 if (childrenUnchanged && oldProps === newProps) {
16322 // No changes, just reuse the existing instance.
16323 // Note that this might release a previous clone.
16324 workInProgress.stateNode = currentInstance;
16325 return;
16326 }
16327 var recyclableInstance = workInProgress.stateNode;
16328 var currentHostContext = getHostContext();
16329 var updatePayload = null;
16330 if (oldProps !== newProps) {
16331 updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
16332 }
16333 if (childrenUnchanged && updatePayload === null) {
16334 // No changes, just reuse the existing instance.
16335 // Note that this might release a previous clone.
16336 workInProgress.stateNode = currentInstance;
16337 return;
16338 }
16339 var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
16340 if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
16341 markUpdate(workInProgress);
16342 }
16343 workInProgress.stateNode = newInstance;
16344 if (childrenUnchanged) {
16345 // If there are no other effects in this tree, we need to flag this node as having one.
16346 // Even though we're not going to use it for anything.
16347 // Otherwise parents won't know that there are new children to propagate upwards.
16348 markUpdate(workInProgress);
16349 } else {
16350 // If children might have changed, we have to add them all to the set.
16351 appendAllChildren(newInstance, workInProgress, false, false);
16352 }
16353 };
16354 updateHostText$1 = function (current, workInProgress, oldText, newText) {
16355 if (oldText !== newText) {
16356 // If the text content differs, we'll create a new text instance for it.
16357 var rootContainerInstance = getRootHostContainer();
16358 var currentHostContext = getHostContext();
16359 workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress);
16360 // We'll have to mark it as having an effect, even though we won't use the effect for anything.
16361 // This lets the parents know that at least one of their children has changed.
16362 markUpdate(workInProgress);
16363 }
16364 };
16365} else {
16366 // No host operations
16367 updateHostContainer = function (workInProgress) {
16368 // Noop
16369 };
16370 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
16371 // Noop
16372 };
16373 updateHostText$1 = function (current, workInProgress, oldText, newText) {
16374 // Noop
16375 };
16376}
16377
16378function completeWork(current, workInProgress, renderExpirationTime) {
16379 var newProps = workInProgress.pendingProps;
16380
16381 switch (workInProgress.tag) {
16382 case IndeterminateComponent:
16383 break;
16384 case LazyComponent:
16385 break;
16386 case SimpleMemoComponent:
16387 case FunctionComponent:
16388 break;
16389 case ClassComponent:
16390 {
16391 var Component = workInProgress.type;
16392 if (isContextProvider(Component)) {
16393 popContext(workInProgress);
16394 }
16395 break;
16396 }
16397 case HostRoot:
16398 {
16399 popHostContainer(workInProgress);
16400 popTopLevelContextObject(workInProgress);
16401 var fiberRoot = workInProgress.stateNode;
16402 if (fiberRoot.pendingContext) {
16403 fiberRoot.context = fiberRoot.pendingContext;
16404 fiberRoot.pendingContext = null;
16405 }
16406 if (current === null || current.child === null) {
16407 // If we hydrated, pop so that we can delete any remaining children
16408 // that weren't hydrated.
16409 popHydrationState(workInProgress);
16410 // This resets the hacky state to fix isMounted before committing.
16411 // TODO: Delete this when we delete isMounted and findDOMNode.
16412 workInProgress.effectTag &= ~Placement;
16413 }
16414 updateHostContainer(workInProgress);
16415 break;
16416 }
16417 case HostComponent:
16418 {
16419 popHostContext(workInProgress);
16420 var rootContainerInstance = getRootHostContainer();
16421 var type = workInProgress.type;
16422 if (current !== null && workInProgress.stateNode != null) {
16423 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
16424
16425 if (current.ref !== workInProgress.ref) {
16426 markRef$1(workInProgress);
16427 }
16428 } else {
16429 if (!newProps) {
16430 !(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;
16431 // This can happen when we abort work.
16432 break;
16433 }
16434
16435 var currentHostContext = getHostContext();
16436 // TODO: Move createInstance to beginWork and keep it on a context
16437 // "stack" as the parent. Then append children as we go in beginWork
16438 // or completeWork depending on we want to add then top->down or
16439 // bottom->up. Top->down is faster in IE11.
16440 var wasHydrated = popHydrationState(workInProgress);
16441 if (wasHydrated) {
16442 // TODO: Move this and createInstance step into the beginPhase
16443 // to consolidate.
16444 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
16445 // If changes to the hydrated node needs to be applied at the
16446 // commit-phase we mark this as such.
16447 markUpdate(workInProgress);
16448 }
16449 } else {
16450 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
16451
16452 appendAllChildren(instance, workInProgress, false, false);
16453
16454 // Certain renderers require commit-time effects for initial mount.
16455 // (eg DOM renderer supports auto-focus for certain elements).
16456 // Make sure such renderers get scheduled for later work.
16457 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
16458 markUpdate(workInProgress);
16459 }
16460 workInProgress.stateNode = instance;
16461 }
16462
16463 if (workInProgress.ref !== null) {
16464 // If there is a ref on a host node we need to schedule a callback
16465 markRef$1(workInProgress);
16466 }
16467 }
16468 break;
16469 }
16470 case HostText:
16471 {
16472 var newText = newProps;
16473 if (current && workInProgress.stateNode != null) {
16474 var oldText = current.memoizedProps;
16475 // If we have an alternate, that means this is an update and we need
16476 // to schedule a side-effect to do the updates.
16477 updateHostText$1(current, workInProgress, oldText, newText);
16478 } else {
16479 if (typeof newText !== 'string') {
16480 !(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;
16481 // This can happen when we abort work.
16482 }
16483 var _rootContainerInstance = getRootHostContainer();
16484 var _currentHostContext = getHostContext();
16485 var _wasHydrated = popHydrationState(workInProgress);
16486 if (_wasHydrated) {
16487 if (prepareToHydrateHostTextInstance(workInProgress)) {
16488 markUpdate(workInProgress);
16489 }
16490 } else {
16491 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
16492 }
16493 }
16494 break;
16495 }
16496 case ForwardRef:
16497 break;
16498 case SuspenseComponent:
16499 {
16500 var nextState = workInProgress.memoizedState;
16501 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
16502 // Something suspended. Re-render with the fallback children.
16503 workInProgress.expirationTime = renderExpirationTime;
16504 // Do not reset the effect list.
16505 return workInProgress;
16506 }
16507
16508 var nextDidTimeout = nextState !== null;
16509 var prevDidTimeout = current !== null && current.memoizedState !== null;
16510
16511 if (current !== null && !nextDidTimeout && prevDidTimeout) {
16512 // We just switched from the fallback to the normal children. Delete
16513 // the fallback.
16514 // TODO: Would it be better to store the fallback fragment on
16515 var currentFallbackChild = current.child.sibling;
16516 if (currentFallbackChild !== null) {
16517 // Deletions go at the beginning of the return fiber's effect list
16518 var first = workInProgress.firstEffect;
16519 if (first !== null) {
16520 workInProgress.firstEffect = currentFallbackChild;
16521 currentFallbackChild.nextEffect = first;
16522 } else {
16523 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
16524 currentFallbackChild.nextEffect = null;
16525 }
16526 currentFallbackChild.effectTag = Deletion;
16527 }
16528 }
16529
16530 if (nextDidTimeout || prevDidTimeout) {
16531 // If the children are hidden, or if they were previous hidden, schedule
16532 // an effect to toggle their visibility. This is also used to attach a
16533 // retry listener to the promise.
16534 workInProgress.effectTag |= Update;
16535 }
16536 break;
16537 }
16538 case Fragment:
16539 break;
16540 case Mode:
16541 break;
16542 case Profiler:
16543 break;
16544 case HostPortal:
16545 popHostContainer(workInProgress);
16546 updateHostContainer(workInProgress);
16547 break;
16548 case ContextProvider:
16549 // Pop provider fiber
16550 popProvider(workInProgress);
16551 break;
16552 case ContextConsumer:
16553 break;
16554 case MemoComponent:
16555 break;
16556 case IncompleteClassComponent:
16557 {
16558 // Same as class component case. I put it down here so that the tags are
16559 // sequential to ensure this switch is compiled to a jump table.
16560 var _Component = workInProgress.type;
16561 if (isContextProvider(_Component)) {
16562 popContext(workInProgress);
16563 }
16564 break;
16565 }
16566 default:
16567 invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
16568 }
16569
16570 return null;
16571}
16572
16573function shouldCaptureSuspense(workInProgress) {
16574 // In order to capture, the Suspense component must have a fallback prop.
16575 if (workInProgress.memoizedProps.fallback === undefined) {
16576 return false;
16577 }
16578 // If it was the primary children that just suspended, capture and render the
16579 // fallback. Otherwise, don't capture and bubble to the next boundary.
16580 var nextState = workInProgress.memoizedState;
16581 return nextState === null;
16582}
16583
16584// This module is forked in different environments.
16585// By default, return `true` to log errors to the console.
16586// Forks can return `false` if this isn't desirable.
16587function showErrorDialog(capturedError) {
16588 return true;
16589}
16590
16591function logCapturedError(capturedError) {
16592 var logError = showErrorDialog(capturedError);
16593
16594 // Allow injected showErrorDialog() to prevent default console.error logging.
16595 // This enables renderers like ReactNative to better manage redbox behavior.
16596 if (logError === false) {
16597 return;
16598 }
16599
16600 var error = capturedError.error;
16601 {
16602 var componentName = capturedError.componentName,
16603 componentStack = capturedError.componentStack,
16604 errorBoundaryName = capturedError.errorBoundaryName,
16605 errorBoundaryFound = capturedError.errorBoundaryFound,
16606 willRetry = capturedError.willRetry;
16607
16608 // Browsers support silencing uncaught errors by calling
16609 // `preventDefault()` in window `error` handler.
16610 // We record this information as an expando on the error.
16611
16612 if (error != null && error._suppressLogging) {
16613 if (errorBoundaryFound && willRetry) {
16614 // The error is recoverable and was silenced.
16615 // Ignore it and don't print the stack addendum.
16616 // This is handy for testing error boundaries without noise.
16617 return;
16618 }
16619 // The error is fatal. Since the silencing might have
16620 // been accidental, we'll surface it anyway.
16621 // However, the browser would have silenced the original error
16622 // so we'll print it first, and then print the stack addendum.
16623 console.error(error);
16624 // For a more detailed description of this block, see:
16625 // https://github.com/facebook/react/pull/13384
16626 }
16627
16628 var componentNameMessage = componentName ? 'The above error occurred in the <' + componentName + '> component:' : 'The above error occurred in one of your React components:';
16629
16630 var errorBoundaryMessage = void 0;
16631 // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
16632 if (errorBoundaryFound && errorBoundaryName) {
16633 if (willRetry) {
16634 errorBoundaryMessage = 'React will try to recreate this component tree from scratch ' + ('using the error boundary you provided, ' + errorBoundaryName + '.');
16635 } else {
16636 errorBoundaryMessage = 'This error was initially handled by the error boundary ' + errorBoundaryName + '.\n' + 'Recreating the tree from scratch failed so React will unmount the tree.';
16637 }
16638 } else {
16639 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.';
16640 }
16641 var combinedMessage = '' + componentNameMessage + componentStack + '\n\n' + ('' + errorBoundaryMessage);
16642
16643 // In development, we provide our own message with just the component stack.
16644 // We don't include the original error message and JS stack because the browser
16645 // has already printed it. Even if the application swallows the error, it is still
16646 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
16647 console.error(combinedMessage);
16648 }
16649}
16650
16651var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
16652{
16653 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
16654}
16655
16656var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
16657
16658function logError(boundary, errorInfo) {
16659 var source = errorInfo.source;
16660 var stack = errorInfo.stack;
16661 if (stack === null && source !== null) {
16662 stack = getStackByFiberInDevAndProd(source);
16663 }
16664
16665 var capturedError = {
16666 componentName: source !== null ? getComponentName(source.type) : null,
16667 componentStack: stack !== null ? stack : '',
16668 error: errorInfo.value,
16669 errorBoundary: null,
16670 errorBoundaryName: null,
16671 errorBoundaryFound: false,
16672 willRetry: false
16673 };
16674
16675 if (boundary !== null && boundary.tag === ClassComponent) {
16676 capturedError.errorBoundary = boundary.stateNode;
16677 capturedError.errorBoundaryName = getComponentName(boundary.type);
16678 capturedError.errorBoundaryFound = true;
16679 capturedError.willRetry = true;
16680 }
16681
16682 try {
16683 logCapturedError(capturedError);
16684 } catch (e) {
16685 // This method must not throw, or React internal state will get messed up.
16686 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
16687 // we want to report this error outside of the normal stack as a last resort.
16688 // https://github.com/facebook/react/issues/13188
16689 setTimeout(function () {
16690 throw e;
16691 });
16692 }
16693}
16694
16695var callComponentWillUnmountWithTimer = function (current$$1, instance) {
16696 startPhaseTimer(current$$1, 'componentWillUnmount');
16697 instance.props = current$$1.memoizedProps;
16698 instance.state = current$$1.memoizedState;
16699 instance.componentWillUnmount();
16700 stopPhaseTimer();
16701};
16702
16703// Capture errors so they don't interrupt unmounting.
16704function safelyCallComponentWillUnmount(current$$1, instance) {
16705 {
16706 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
16707 if (hasCaughtError()) {
16708 var unmountError = clearCaughtError();
16709 captureCommitPhaseError(current$$1, unmountError);
16710 }
16711 }
16712}
16713
16714function safelyDetachRef(current$$1) {
16715 var ref = current$$1.ref;
16716 if (ref !== null) {
16717 if (typeof ref === 'function') {
16718 {
16719 invokeGuardedCallback(null, ref, null, null);
16720 if (hasCaughtError()) {
16721 var refError = clearCaughtError();
16722 captureCommitPhaseError(current$$1, refError);
16723 }
16724 }
16725 } else {
16726 ref.current = null;
16727 }
16728 }
16729}
16730
16731function safelyCallDestroy(current$$1, destroy) {
16732 {
16733 invokeGuardedCallback(null, destroy, null);
16734 if (hasCaughtError()) {
16735 var error = clearCaughtError();
16736 captureCommitPhaseError(current$$1, error);
16737 }
16738 }
16739}
16740
16741function commitBeforeMutationLifeCycles(current$$1, finishedWork) {
16742 switch (finishedWork.tag) {
16743 case FunctionComponent:
16744 case ForwardRef:
16745 case SimpleMemoComponent:
16746 {
16747 commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
16748 return;
16749 }
16750 case ClassComponent:
16751 {
16752 if (finishedWork.effectTag & Snapshot) {
16753 if (current$$1 !== null) {
16754 var prevProps = current$$1.memoizedProps;
16755 var prevState = current$$1.memoizedState;
16756 startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
16757 var instance = finishedWork.stateNode;
16758 // We could update instance props and state here,
16759 // but instead we rely on them being set during last render.
16760 // TODO: revisit this when we implement resuming.
16761 {
16762 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
16763 !(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;
16764 !(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;
16765 }
16766 }
16767 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
16768 {
16769 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
16770 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
16771 didWarnSet.add(finishedWork.type);
16772 warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
16773 }
16774 }
16775 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
16776 stopPhaseTimer();
16777 }
16778 }
16779 return;
16780 }
16781 case HostRoot:
16782 case HostComponent:
16783 case HostText:
16784 case HostPortal:
16785 case IncompleteClassComponent:
16786 // Nothing to do for these component types
16787 return;
16788 default:
16789 {
16790 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.');
16791 }
16792 }
16793}
16794
16795function commitHookEffectList(unmountTag, mountTag, finishedWork) {
16796 var updateQueue = finishedWork.updateQueue;
16797 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
16798 if (lastEffect !== null) {
16799 var firstEffect = lastEffect.next;
16800 var effect = firstEffect;
16801 do {
16802 if ((effect.tag & unmountTag) !== NoEffect$1) {
16803 // Unmount
16804 var destroy = effect.destroy;
16805 effect.destroy = undefined;
16806 if (destroy !== undefined) {
16807 destroy();
16808 }
16809 }
16810 if ((effect.tag & mountTag) !== NoEffect$1) {
16811 // Mount
16812 var create = effect.create;
16813 effect.destroy = create();
16814
16815 {
16816 var _destroy = effect.destroy;
16817 if (_destroy !== undefined && typeof _destroy !== 'function') {
16818 var addendum = void 0;
16819 if (_destroy === null) {
16820 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
16821 } else if (typeof _destroy.then === 'function') {
16822 addendum = '\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, you may write an async function separately ' + 'and then call it from inside the effect:\n\n' + 'async function fetchComment(commentId) {\n' + ' // You can await here\n' + '}\n\n' + 'useEffect(() => {\n' + ' fetchComment(commentId);\n' + '}, [commentId]);\n\n' + 'In the future, React will provide a more idiomatic solution for data fetching ' + "that doesn't involve writing effects manually.";
16823 } else {
16824 addendum = ' You returned: ' + _destroy;
16825 }
16826 warningWithoutStack$1(false, 'An Effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
16827 }
16828 }
16829 }
16830 effect = effect.next;
16831 } while (effect !== firstEffect);
16832 }
16833}
16834
16835function commitPassiveHookEffects(finishedWork) {
16836 commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
16837 commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
16838}
16839
16840function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) {
16841 switch (finishedWork.tag) {
16842 case FunctionComponent:
16843 case ForwardRef:
16844 case SimpleMemoComponent:
16845 {
16846 commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
16847 break;
16848 }
16849 case ClassComponent:
16850 {
16851 var instance = finishedWork.stateNode;
16852 if (finishedWork.effectTag & Update) {
16853 if (current$$1 === null) {
16854 startPhaseTimer(finishedWork, 'componentDidMount');
16855 // We could update instance props and state here,
16856 // but instead we rely on them being set during last render.
16857 // TODO: revisit this when we implement resuming.
16858 {
16859 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
16860 !(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;
16861 !(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;
16862 }
16863 }
16864 instance.componentDidMount();
16865 stopPhaseTimer();
16866 } else {
16867 var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);
16868 var prevState = current$$1.memoizedState;
16869 startPhaseTimer(finishedWork, 'componentDidUpdate');
16870 // We could update instance props and state here,
16871 // but instead we rely on them being set during last render.
16872 // TODO: revisit this when we implement resuming.
16873 {
16874 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
16875 !(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;
16876 !(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;
16877 }
16878 }
16879 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
16880 stopPhaseTimer();
16881 }
16882 }
16883 var updateQueue = finishedWork.updateQueue;
16884 if (updateQueue !== null) {
16885 {
16886 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
16887 !(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;
16888 !(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;
16889 }
16890 }
16891 // We could update instance props and state here,
16892 // but instead we rely on them being set during last render.
16893 // TODO: revisit this when we implement resuming.
16894 commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
16895 }
16896 return;
16897 }
16898 case HostRoot:
16899 {
16900 var _updateQueue = finishedWork.updateQueue;
16901 if (_updateQueue !== null) {
16902 var _instance = null;
16903 if (finishedWork.child !== null) {
16904 switch (finishedWork.child.tag) {
16905 case HostComponent:
16906 _instance = getPublicInstance(finishedWork.child.stateNode);
16907 break;
16908 case ClassComponent:
16909 _instance = finishedWork.child.stateNode;
16910 break;
16911 }
16912 }
16913 commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
16914 }
16915 return;
16916 }
16917 case HostComponent:
16918 {
16919 var _instance2 = finishedWork.stateNode;
16920
16921 // Renderers may schedule work to be done after host components are mounted
16922 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
16923 // These effects should only be committed when components are first mounted,
16924 // aka when there is no current/alternate.
16925 if (current$$1 === null && finishedWork.effectTag & Update) {
16926 var type = finishedWork.type;
16927 var props = finishedWork.memoizedProps;
16928 commitMount(_instance2, type, props, finishedWork);
16929 }
16930
16931 return;
16932 }
16933 case HostText:
16934 {
16935 // We have no life-cycles associated with text.
16936 return;
16937 }
16938 case HostPortal:
16939 {
16940 // We have no life-cycles associated with portals.
16941 return;
16942 }
16943 case Profiler:
16944 {
16945 if (enableProfilerTimer) {
16946 var onRender = finishedWork.memoizedProps.onRender;
16947
16948 if (enableSchedulerTracing) {
16949 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
16950 } else {
16951 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
16952 }
16953 }
16954 return;
16955 }
16956 case SuspenseComponent:
16957 break;
16958 case IncompleteClassComponent:
16959 break;
16960 default:
16961 {
16962 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.');
16963 }
16964 }
16965}
16966
16967function hideOrUnhideAllChildren(finishedWork, isHidden) {
16968 if (supportsMutation) {
16969 // We only have the top Fiber that was inserted but we need recurse down its
16970 var node = finishedWork;
16971 while (true) {
16972 if (node.tag === HostComponent) {
16973 var instance = node.stateNode;
16974 if (isHidden) {
16975 hideInstance(instance);
16976 } else {
16977 unhideInstance(node.stateNode, node.memoizedProps);
16978 }
16979 } else if (node.tag === HostText) {
16980 var _instance3 = node.stateNode;
16981 if (isHidden) {
16982 hideTextInstance(_instance3);
16983 } else {
16984 unhideTextInstance(_instance3, node.memoizedProps);
16985 }
16986 } else if (node.tag === SuspenseComponent && node.memoizedState !== null) {
16987 // Found a nested Suspense component that timed out. Skip over the
16988 var fallbackChildFragment = node.child.sibling;
16989 fallbackChildFragment.return = node;
16990 node = fallbackChildFragment;
16991 continue;
16992 } else if (node.child !== null) {
16993 node.child.return = node;
16994 node = node.child;
16995 continue;
16996 }
16997 if (node === finishedWork) {
16998 return;
16999 }
17000 while (node.sibling === null) {
17001 if (node.return === null || node.return === finishedWork) {
17002 return;
17003 }
17004 node = node.return;
17005 }
17006 node.sibling.return = node.return;
17007 node = node.sibling;
17008 }
17009 }
17010}
17011
17012function commitAttachRef(finishedWork) {
17013 var ref = finishedWork.ref;
17014 if (ref !== null) {
17015 var instance = finishedWork.stateNode;
17016 var instanceToUse = void 0;
17017 switch (finishedWork.tag) {
17018 case HostComponent:
17019 instanceToUse = getPublicInstance(instance);
17020 break;
17021 default:
17022 instanceToUse = instance;
17023 }
17024 if (typeof ref === 'function') {
17025 ref(instanceToUse);
17026 } else {
17027 {
17028 if (!ref.hasOwnProperty('current')) {
17029 warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
17030 }
17031 }
17032
17033 ref.current = instanceToUse;
17034 }
17035 }
17036}
17037
17038function commitDetachRef(current$$1) {
17039 var currentRef = current$$1.ref;
17040 if (currentRef !== null) {
17041 if (typeof currentRef === 'function') {
17042 currentRef(null);
17043 } else {
17044 currentRef.current = null;
17045 }
17046 }
17047}
17048
17049// User-originating errors (lifecycles and refs) should not interrupt
17050// deletion, so don't let them throw. Host-originating errors should
17051// interrupt deletion, so it's okay
17052function commitUnmount(current$$1) {
17053 onCommitUnmount(current$$1);
17054
17055 switch (current$$1.tag) {
17056 case FunctionComponent:
17057 case ForwardRef:
17058 case MemoComponent:
17059 case SimpleMemoComponent:
17060 {
17061 var updateQueue = current$$1.updateQueue;
17062 if (updateQueue !== null) {
17063 var lastEffect = updateQueue.lastEffect;
17064 if (lastEffect !== null) {
17065 var firstEffect = lastEffect.next;
17066 var effect = firstEffect;
17067 do {
17068 var destroy = effect.destroy;
17069 if (destroy !== undefined) {
17070 safelyCallDestroy(current$$1, destroy);
17071 }
17072 effect = effect.next;
17073 } while (effect !== firstEffect);
17074 }
17075 }
17076 break;
17077 }
17078 case ClassComponent:
17079 {
17080 safelyDetachRef(current$$1);
17081 var instance = current$$1.stateNode;
17082 if (typeof instance.componentWillUnmount === 'function') {
17083 safelyCallComponentWillUnmount(current$$1, instance);
17084 }
17085 return;
17086 }
17087 case HostComponent:
17088 {
17089 safelyDetachRef(current$$1);
17090 return;
17091 }
17092 case HostPortal:
17093 {
17094 // TODO: this is recursive.
17095 // We are also not using this parent because
17096 // the portal will get pushed immediately.
17097 if (supportsMutation) {
17098 unmountHostComponents(current$$1);
17099 } else if (supportsPersistence) {
17100 emptyPortalContainer(current$$1);
17101 }
17102 return;
17103 }
17104 }
17105}
17106
17107function commitNestedUnmounts(root) {
17108 // While we're inside a removed host node we don't want to call
17109 // removeChild on the inner nodes because they're removed by the top
17110 // call anyway. We also want to call componentWillUnmount on all
17111 // composites before this host node is removed from the tree. Therefore
17112 var node = root;
17113 while (true) {
17114 commitUnmount(node);
17115 // Visit children because they may contain more composite or host nodes.
17116 // Skip portals because commitUnmount() currently visits them recursively.
17117 if (node.child !== null && (
17118 // If we use mutation we drill down into portals using commitUnmount above.
17119 // If we don't use mutation we drill down into portals here instead.
17120 !supportsMutation || node.tag !== HostPortal)) {
17121 node.child.return = node;
17122 node = node.child;
17123 continue;
17124 }
17125 if (node === root) {
17126 return;
17127 }
17128 while (node.sibling === null) {
17129 if (node.return === null || node.return === root) {
17130 return;
17131 }
17132 node = node.return;
17133 }
17134 node.sibling.return = node.return;
17135 node = node.sibling;
17136 }
17137}
17138
17139function detachFiber(current$$1) {
17140 // Cut off the return pointers to disconnect it from the tree. Ideally, we
17141 // should clear the child pointer of the parent alternate to let this
17142 // get GC:ed but we don't know which for sure which parent is the current
17143 // one so we'll settle for GC:ing the subtree of this child. This child
17144 // itself will be GC:ed when the parent updates the next time.
17145 current$$1.return = null;
17146 current$$1.child = null;
17147 current$$1.memoizedState = null;
17148 current$$1.updateQueue = null;
17149 var alternate = current$$1.alternate;
17150 if (alternate !== null) {
17151 alternate.return = null;
17152 alternate.child = null;
17153 alternate.memoizedState = null;
17154 alternate.updateQueue = null;
17155 }
17156}
17157
17158function emptyPortalContainer(current$$1) {
17159 if (!supportsPersistence) {
17160 return;
17161 }
17162
17163 var portal = current$$1.stateNode;
17164 var containerInfo = portal.containerInfo;
17165
17166 var emptyChildSet = createContainerChildSet(containerInfo);
17167 replaceContainerChildren(containerInfo, emptyChildSet);
17168}
17169
17170function commitContainer(finishedWork) {
17171 if (!supportsPersistence) {
17172 return;
17173 }
17174
17175 switch (finishedWork.tag) {
17176 case ClassComponent:
17177 {
17178 return;
17179 }
17180 case HostComponent:
17181 {
17182 return;
17183 }
17184 case HostText:
17185 {
17186 return;
17187 }
17188 case HostRoot:
17189 case HostPortal:
17190 {
17191 var portalOrRoot = finishedWork.stateNode;
17192 var containerInfo = portalOrRoot.containerInfo,
17193 _pendingChildren = portalOrRoot.pendingChildren;
17194
17195 replaceContainerChildren(containerInfo, _pendingChildren);
17196 return;
17197 }
17198 default:
17199 {
17200 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.');
17201 }
17202 }
17203}
17204
17205function getHostParentFiber(fiber) {
17206 var parent = fiber.return;
17207 while (parent !== null) {
17208 if (isHostParent(parent)) {
17209 return parent;
17210 }
17211 parent = parent.return;
17212 }
17213 invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.');
17214}
17215
17216function isHostParent(fiber) {
17217 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
17218}
17219
17220function getHostSibling(fiber) {
17221 // We're going to search forward into the tree until we find a sibling host
17222 // node. Unfortunately, if multiple insertions are done in a row we have to
17223 // search past them. This leads to exponential search for the next sibling.
17224 var node = fiber;
17225 siblings: while (true) {
17226 // If we didn't find anything, let's try the next sibling.
17227 while (node.sibling === null) {
17228 if (node.return === null || isHostParent(node.return)) {
17229 // If we pop out of the root or hit the parent the fiber we are the
17230 // last sibling.
17231 return null;
17232 }
17233 node = node.return;
17234 }
17235 node.sibling.return = node.return;
17236 node = node.sibling;
17237 while (node.tag !== HostComponent && node.tag !== HostText) {
17238 // If it is not host node and, we might have a host node inside it.
17239 // Try to search down until we find one.
17240 if (node.effectTag & Placement) {
17241 // If we don't have a child, try the siblings instead.
17242 continue siblings;
17243 }
17244 // If we don't have a child, try the siblings instead.
17245 // We also skip portals because they are not part of this host tree.
17246 if (node.child === null || node.tag === HostPortal) {
17247 continue siblings;
17248 } else {
17249 node.child.return = node;
17250 node = node.child;
17251 }
17252 }
17253 // Check if this host node is stable or about to be placed.
17254 if (!(node.effectTag & Placement)) {
17255 // Found it!
17256 return node.stateNode;
17257 }
17258 }
17259}
17260
17261function commitPlacement(finishedWork) {
17262 if (!supportsMutation) {
17263 return;
17264 }
17265
17266 // Recursively insert all host nodes into the parent.
17267 var parentFiber = getHostParentFiber(finishedWork);
17268
17269 // Note: these two variables *must* always be updated together.
17270 var parent = void 0;
17271 var isContainer = void 0;
17272
17273 switch (parentFiber.tag) {
17274 case HostComponent:
17275 parent = parentFiber.stateNode;
17276 isContainer = false;
17277 break;
17278 case HostRoot:
17279 parent = parentFiber.stateNode.containerInfo;
17280 isContainer = true;
17281 break;
17282 case HostPortal:
17283 parent = parentFiber.stateNode.containerInfo;
17284 isContainer = true;
17285 break;
17286 default:
17287 invariant(false, 'Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.');
17288 }
17289 if (parentFiber.effectTag & ContentReset) {
17290 // Reset the text content of the parent before doing any insertions
17291 resetTextContent(parent);
17292 // Clear ContentReset from the effect tag
17293 parentFiber.effectTag &= ~ContentReset;
17294 }
17295
17296 var before = getHostSibling(finishedWork);
17297 // We only have the top Fiber that was inserted but we need recurse down its
17298 // children to find all the terminal nodes.
17299 var node = finishedWork;
17300 while (true) {
17301 if (node.tag === HostComponent || node.tag === HostText) {
17302 if (before) {
17303 if (isContainer) {
17304 insertInContainerBefore(parent, node.stateNode, before);
17305 } else {
17306 insertBefore(parent, node.stateNode, before);
17307 }
17308 } else {
17309 if (isContainer) {
17310 appendChildToContainer(parent, node.stateNode);
17311 } else {
17312 appendChild(parent, node.stateNode);
17313 }
17314 }
17315 } else if (node.tag === HostPortal) {
17316 // If the insertion itself is a portal, then we don't want to traverse
17317 // down its children. Instead, we'll get insertions from each child in
17318 // the portal directly.
17319 } else if (node.child !== null) {
17320 node.child.return = node;
17321 node = node.child;
17322 continue;
17323 }
17324 if (node === finishedWork) {
17325 return;
17326 }
17327 while (node.sibling === null) {
17328 if (node.return === null || node.return === finishedWork) {
17329 return;
17330 }
17331 node = node.return;
17332 }
17333 node.sibling.return = node.return;
17334 node = node.sibling;
17335 }
17336}
17337
17338function unmountHostComponents(current$$1) {
17339 // We only have the top Fiber that was deleted but we need recurse down its
17340 var node = current$$1;
17341
17342 // Each iteration, currentParent is populated with node's host parent if not
17343 // currentParentIsValid.
17344 var currentParentIsValid = false;
17345
17346 // Note: these two variables *must* always be updated together.
17347 var currentParent = void 0;
17348 var currentParentIsContainer = void 0;
17349
17350 while (true) {
17351 if (!currentParentIsValid) {
17352 var parent = node.return;
17353 findParent: while (true) {
17354 !(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;
17355 switch (parent.tag) {
17356 case HostComponent:
17357 currentParent = parent.stateNode;
17358 currentParentIsContainer = false;
17359 break findParent;
17360 case HostRoot:
17361 currentParent = parent.stateNode.containerInfo;
17362 currentParentIsContainer = true;
17363 break findParent;
17364 case HostPortal:
17365 currentParent = parent.stateNode.containerInfo;
17366 currentParentIsContainer = true;
17367 break findParent;
17368 }
17369 parent = parent.return;
17370 }
17371 currentParentIsValid = true;
17372 }
17373
17374 if (node.tag === HostComponent || node.tag === HostText) {
17375 commitNestedUnmounts(node);
17376 // After all the children have unmounted, it is now safe to remove the
17377 // node from the tree.
17378 if (currentParentIsContainer) {
17379 removeChildFromContainer(currentParent, node.stateNode);
17380 } else {
17381 removeChild(currentParent, node.stateNode);
17382 }
17383 // Don't visit children because we already visited them.
17384 } else if (node.tag === HostPortal) {
17385 // When we go into a portal, it becomes the parent to remove from.
17386 // We will reassign it back when we pop the portal on the way up.
17387 currentParent = node.stateNode.containerInfo;
17388 currentParentIsContainer = true;
17389 // Visit children because portals might contain host components.
17390 if (node.child !== null) {
17391 node.child.return = node;
17392 node = node.child;
17393 continue;
17394 }
17395 } else {
17396 commitUnmount(node);
17397 // Visit children because we may find more host components below.
17398 if (node.child !== null) {
17399 node.child.return = node;
17400 node = node.child;
17401 continue;
17402 }
17403 }
17404 if (node === current$$1) {
17405 return;
17406 }
17407 while (node.sibling === null) {
17408 if (node.return === null || node.return === current$$1) {
17409 return;
17410 }
17411 node = node.return;
17412 if (node.tag === HostPortal) {
17413 // When we go out of the portal, we need to restore the parent.
17414 // Since we don't keep a stack of them, we will search for it.
17415 currentParentIsValid = false;
17416 }
17417 }
17418 node.sibling.return = node.return;
17419 node = node.sibling;
17420 }
17421}
17422
17423function commitDeletion(current$$1) {
17424 if (supportsMutation) {
17425 // Recursively delete all host nodes from the parent.
17426 // Detach refs and call componentWillUnmount() on the whole subtree.
17427 unmountHostComponents(current$$1);
17428 } else {
17429 // Detach refs and call componentWillUnmount() on the whole subtree.
17430 commitNestedUnmounts(current$$1);
17431 }
17432 detachFiber(current$$1);
17433}
17434
17435function commitWork(current$$1, finishedWork) {
17436 if (!supportsMutation) {
17437 switch (finishedWork.tag) {
17438 case FunctionComponent:
17439 case ForwardRef:
17440 case MemoComponent:
17441 case SimpleMemoComponent:
17442 {
17443 // Note: We currently never use MountMutation, but useLayout uses
17444 // UnmountMutation.
17445 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
17446 return;
17447 }
17448 }
17449
17450 commitContainer(finishedWork);
17451 return;
17452 }
17453
17454 switch (finishedWork.tag) {
17455 case FunctionComponent:
17456 case ForwardRef:
17457 case MemoComponent:
17458 case SimpleMemoComponent:
17459 {
17460 // Note: We currently never use MountMutation, but useLayout uses
17461 // UnmountMutation.
17462 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
17463 return;
17464 }
17465 case ClassComponent:
17466 {
17467 return;
17468 }
17469 case HostComponent:
17470 {
17471 var instance = finishedWork.stateNode;
17472 if (instance != null) {
17473 // Commit the work prepared earlier.
17474 var newProps = finishedWork.memoizedProps;
17475 // For hydration we reuse the update path but we treat the oldProps
17476 // as the newProps. The updatePayload will contain the real change in
17477 // this case.
17478 var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps;
17479 var type = finishedWork.type;
17480 // TODO: Type the updateQueue to be specific to host components.
17481 var updatePayload = finishedWork.updateQueue;
17482 finishedWork.updateQueue = null;
17483 if (updatePayload !== null) {
17484 commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
17485 }
17486 }
17487 return;
17488 }
17489 case HostText:
17490 {
17491 !(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;
17492 var textInstance = finishedWork.stateNode;
17493 var newText = finishedWork.memoizedProps;
17494 // For hydration we reuse the update path but we treat the oldProps
17495 // as the newProps. The updatePayload will contain the real change in
17496 // this case.
17497 var oldText = current$$1 !== null ? current$$1.memoizedProps : newText;
17498 commitTextUpdate(textInstance, oldText, newText);
17499 return;
17500 }
17501 case HostRoot:
17502 {
17503 return;
17504 }
17505 case Profiler:
17506 {
17507 return;
17508 }
17509 case SuspenseComponent:
17510 {
17511 var newState = finishedWork.memoizedState;
17512
17513 var newDidTimeout = void 0;
17514 var primaryChildParent = finishedWork;
17515 if (newState === null) {
17516 newDidTimeout = false;
17517 } else {
17518 newDidTimeout = true;
17519 primaryChildParent = finishedWork.child;
17520 if (newState.timedOutAt === NoWork) {
17521 // If the children had not already timed out, record the time.
17522 // This is used to compute the elapsed time during subsequent
17523 // attempts to render the children.
17524 newState.timedOutAt = requestCurrentTime();
17525 }
17526 }
17527
17528 if (primaryChildParent !== null) {
17529 hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
17530 }
17531
17532 // If this boundary just timed out, then it will have a set of thenables.
17533 // For each thenable, attach a listener so that when it resolves, React
17534 // attempts to re-render the boundary in the primary (pre-timeout) state.
17535 var thenables = finishedWork.updateQueue;
17536 if (thenables !== null) {
17537 finishedWork.updateQueue = null;
17538 var retryCache = finishedWork.stateNode;
17539 if (retryCache === null) {
17540 retryCache = finishedWork.stateNode = new PossiblyWeakSet();
17541 }
17542 thenables.forEach(function (thenable) {
17543 // Memoize using the boundary fiber to prevent redundant listeners.
17544 var retry = retryTimedOutBoundary.bind(null, finishedWork, thenable);
17545 if (enableSchedulerTracing) {
17546 retry = tracing.unstable_wrap(retry);
17547 }
17548 if (!retryCache.has(thenable)) {
17549 retryCache.add(thenable);
17550 thenable.then(retry, retry);
17551 }
17552 });
17553 }
17554
17555 return;
17556 }
17557 case IncompleteClassComponent:
17558 {
17559 return;
17560 }
17561 default:
17562 {
17563 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.');
17564 }
17565 }
17566}
17567
17568function commitResetTextContent(current$$1) {
17569 if (!supportsMutation) {
17570 return;
17571 }
17572 resetTextContent(current$$1.stateNode);
17573}
17574
17575var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
17576
17577function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
17578 var update = createUpdate(expirationTime);
17579 // Unmount the root by rendering null.
17580 update.tag = CaptureUpdate;
17581 // Caution: React DevTools currently depends on this property
17582 // being called "element".
17583 update.payload = { element: null };
17584 var error = errorInfo.value;
17585 update.callback = function () {
17586 onUncaughtError(error);
17587 logError(fiber, errorInfo);
17588 };
17589 return update;
17590}
17591
17592function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
17593 var update = createUpdate(expirationTime);
17594 update.tag = CaptureUpdate;
17595 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
17596 if (typeof getDerivedStateFromError === 'function') {
17597 var error = errorInfo.value;
17598 update.payload = function () {
17599 return getDerivedStateFromError(error);
17600 };
17601 }
17602
17603 var inst = fiber.stateNode;
17604 if (inst !== null && typeof inst.componentDidCatch === 'function') {
17605 update.callback = function callback() {
17606 if (typeof getDerivedStateFromError !== 'function') {
17607 // To preserve the preexisting retry behavior of error boundaries,
17608 // we keep track of which ones already failed during this batch.
17609 // This gets reset before we yield back to the browser.
17610 // TODO: Warn in strict mode if getDerivedStateFromError is
17611 // not defined.
17612 markLegacyErrorBoundaryAsFailed(this);
17613 }
17614 var error = errorInfo.value;
17615 var stack = errorInfo.stack;
17616 logError(fiber, errorInfo);
17617 this.componentDidCatch(error, {
17618 componentStack: stack !== null ? stack : ''
17619 });
17620 {
17621 if (typeof getDerivedStateFromError !== 'function') {
17622 // If componentDidCatch is the only error boundary method defined,
17623 // then it needs to call setState to recover from errors.
17624 // If no state update is scheduled then the boundary will swallow the error.
17625 !(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;
17626 }
17627 }
17628 };
17629 }
17630 return update;
17631}
17632
17633function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
17634 // The source fiber did not complete.
17635 sourceFiber.effectTag |= Incomplete;
17636 // Its effect list is no longer valid.
17637 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
17638
17639 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
17640 // This is a thenable.
17641 var thenable = value;
17642
17643 // Find the earliest timeout threshold of all the placeholders in the
17644 // ancestor path. We could avoid this traversal by storing the thresholds on
17645 // the stack, but we choose not to because we only hit this path if we're
17646 // IO-bound (i.e. if something suspends). Whereas the stack is used even in
17647 // the non-IO- bound case.
17648 var _workInProgress = returnFiber;
17649 var earliestTimeoutMs = -1;
17650 var startTimeMs = -1;
17651 do {
17652 if (_workInProgress.tag === SuspenseComponent) {
17653 var current$$1 = _workInProgress.alternate;
17654 if (current$$1 !== null) {
17655 var currentState = current$$1.memoizedState;
17656 if (currentState !== null) {
17657 // Reached a boundary that already timed out. Do not search
17658 // any further.
17659 var timedOutAt = currentState.timedOutAt;
17660 startTimeMs = expirationTimeToMs(timedOutAt);
17661 // Do not search any further.
17662 break;
17663 }
17664 }
17665 var timeoutPropMs = _workInProgress.pendingProps.maxDuration;
17666 if (typeof timeoutPropMs === 'number') {
17667 if (timeoutPropMs <= 0) {
17668 earliestTimeoutMs = 0;
17669 } else if (earliestTimeoutMs === -1 || timeoutPropMs < earliestTimeoutMs) {
17670 earliestTimeoutMs = timeoutPropMs;
17671 }
17672 }
17673 }
17674 _workInProgress = _workInProgress.return;
17675 } while (_workInProgress !== null);
17676
17677 // Schedule the nearest Suspense to re-render the timed out view.
17678 _workInProgress = returnFiber;
17679 do {
17680 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress)) {
17681 // Found the nearest boundary.
17682
17683 // Stash the promise on the boundary fiber. If the boundary times out, we'll
17684 var thenables = _workInProgress.updateQueue;
17685 if (thenables === null) {
17686 var updateQueue = new Set();
17687 updateQueue.add(thenable);
17688 _workInProgress.updateQueue = updateQueue;
17689 } else {
17690 thenables.add(thenable);
17691 }
17692
17693 // If the boundary is outside of concurrent mode, we should *not*
17694 // suspend the commit. Pretend as if the suspended component rendered
17695 // null and keep rendering. In the commit phase, we'll schedule a
17696 // subsequent synchronous update to re-render the Suspense.
17697 //
17698 // Note: It doesn't matter whether the component that suspended was
17699 // inside a concurrent mode tree. If the Suspense is outside of it, we
17700 // should *not* suspend the commit.
17701 if ((_workInProgress.mode & ConcurrentMode) === NoEffect) {
17702 _workInProgress.effectTag |= DidCapture;
17703
17704 // We're going to commit this fiber even though it didn't complete.
17705 // But we shouldn't call any lifecycle methods or callbacks. Remove
17706 // all lifecycle effect tags.
17707 sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
17708
17709 if (sourceFiber.tag === ClassComponent) {
17710 var currentSourceFiber = sourceFiber.alternate;
17711 if (currentSourceFiber === null) {
17712 // This is a new mount. Change the tag so it's not mistaken for a
17713 // completed class component. For example, we should not call
17714 // componentWillUnmount if it is deleted.
17715 sourceFiber.tag = IncompleteClassComponent;
17716 } else {
17717 // When we try rendering again, we should not reuse the current fiber,
17718 // since it's known to be in an inconsistent state. Use a force updte to
17719 // prevent a bail out.
17720 var update = createUpdate(Sync);
17721 update.tag = ForceUpdate;
17722 enqueueUpdate(sourceFiber, update);
17723 }
17724 }
17725
17726 // The source fiber did not complete. Mark it with Sync priority to
17727 // indicate that it still has pending work.
17728 sourceFiber.expirationTime = Sync;
17729
17730 // Exit without suspending.
17731 return;
17732 }
17733
17734 // Confirmed that the boundary is in a concurrent mode tree. Continue
17735 // with the normal suspend path.
17736
17737 // Attach a listener to the promise to "ping" the root and retry. But
17738 // only if one does not already exist for the current render expiration
17739 // time (which acts like a "thread ID" here).
17740 var pingCache = root.pingCache;
17741 var threadIDs = void 0;
17742 if (pingCache === null) {
17743 pingCache = root.pingCache = new PossiblyWeakMap();
17744 threadIDs = new Set();
17745 pingCache.set(thenable, threadIDs);
17746 } else {
17747 threadIDs = pingCache.get(thenable);
17748 if (threadIDs === undefined) {
17749 threadIDs = new Set();
17750 pingCache.set(thenable, threadIDs);
17751 }
17752 }
17753 if (!threadIDs.has(renderExpirationTime)) {
17754 // Memoize using the thread ID to prevent redundant listeners.
17755 threadIDs.add(renderExpirationTime);
17756 var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);
17757 if (enableSchedulerTracing) {
17758 ping = tracing.unstable_wrap(ping);
17759 }
17760 thenable.then(ping, ping);
17761 }
17762
17763 var absoluteTimeoutMs = void 0;
17764 if (earliestTimeoutMs === -1) {
17765 // If no explicit threshold is given, default to an arbitrarily large
17766 // value. The actual size doesn't matter because the threshold for the
17767 // whole tree will be clamped to the expiration time.
17768 absoluteTimeoutMs = maxSigned31BitInt;
17769 } else {
17770 if (startTimeMs === -1) {
17771 // This suspend happened outside of any already timed-out
17772 // placeholders. We don't know exactly when the update was
17773 // scheduled, but we can infer an approximate start time from the
17774 // expiration time. First, find the earliest uncommitted expiration
17775 // time in the tree, including work that is suspended. Then subtract
17776 // the offset used to compute an async update's expiration time.
17777 // This will cause high priority (interactive) work to expire
17778 // earlier than necessary, but we can account for this by adjusting
17779 // for the Just Noticeable Difference.
17780 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, renderExpirationTime);
17781 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
17782 startTimeMs = earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
17783 }
17784 absoluteTimeoutMs = startTimeMs + earliestTimeoutMs;
17785 }
17786
17787 // Mark the earliest timeout in the suspended fiber's ancestor path.
17788 // After completing the root, we'll take the largest of all the
17789 // suspended fiber's timeouts and use it to compute a timeout for the
17790 // whole tree.
17791 renderDidSuspend(root, absoluteTimeoutMs, renderExpirationTime);
17792
17793 _workInProgress.effectTag |= ShouldCapture;
17794 _workInProgress.expirationTime = renderExpirationTime;
17795 return;
17796 }
17797 // This boundary already captured during this render. Continue to the next
17798 // boundary.
17799 _workInProgress = _workInProgress.return;
17800 } while (_workInProgress !== null);
17801 // No boundary was found. Fallthrough to error mode.
17802 // TODO: Use invariant so the message is stripped in prod?
17803 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));
17804 }
17805
17806 // We didn't find a boundary that could handle this type of exception. Start
17807 // over and traverse parent path again, this time treating the exception
17808 // as an error.
17809 renderDidError();
17810 value = createCapturedValue(value, sourceFiber);
17811 var workInProgress = returnFiber;
17812 do {
17813 switch (workInProgress.tag) {
17814 case HostRoot:
17815 {
17816 var _errorInfo = value;
17817 workInProgress.effectTag |= ShouldCapture;
17818 workInProgress.expirationTime = renderExpirationTime;
17819 var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
17820 enqueueCapturedUpdate(workInProgress, _update);
17821 return;
17822 }
17823 case ClassComponent:
17824 // Capture and retry
17825 var errorInfo = value;
17826 var ctor = workInProgress.type;
17827 var instance = workInProgress.stateNode;
17828 if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
17829 workInProgress.effectTag |= ShouldCapture;
17830 workInProgress.expirationTime = renderExpirationTime;
17831 // Schedule the error boundary to re-render using updated state
17832 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
17833 enqueueCapturedUpdate(workInProgress, _update2);
17834 return;
17835 }
17836 break;
17837 default:
17838 break;
17839 }
17840 workInProgress = workInProgress.return;
17841 } while (workInProgress !== null);
17842}
17843
17844function unwindWork(workInProgress, renderExpirationTime) {
17845 switch (workInProgress.tag) {
17846 case ClassComponent:
17847 {
17848 var Component = workInProgress.type;
17849 if (isContextProvider(Component)) {
17850 popContext(workInProgress);
17851 }
17852 var effectTag = workInProgress.effectTag;
17853 if (effectTag & ShouldCapture) {
17854 workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
17855 return workInProgress;
17856 }
17857 return null;
17858 }
17859 case HostRoot:
17860 {
17861 popHostContainer(workInProgress);
17862 popTopLevelContextObject(workInProgress);
17863 var _effectTag = workInProgress.effectTag;
17864 !((_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;
17865 workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
17866 return workInProgress;
17867 }
17868 case HostComponent:
17869 {
17870 popHostContext(workInProgress);
17871 return null;
17872 }
17873 case SuspenseComponent:
17874 {
17875 var _effectTag2 = workInProgress.effectTag;
17876 if (_effectTag2 & ShouldCapture) {
17877 workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture;
17878 // Captured a suspense effect. Re-render the boundary.
17879 return workInProgress;
17880 }
17881 return null;
17882 }
17883 case HostPortal:
17884 popHostContainer(workInProgress);
17885 return null;
17886 case ContextProvider:
17887 popProvider(workInProgress);
17888 return null;
17889 default:
17890 return null;
17891 }
17892}
17893
17894function unwindInterruptedWork(interruptedWork) {
17895 switch (interruptedWork.tag) {
17896 case ClassComponent:
17897 {
17898 var childContextTypes = interruptedWork.type.childContextTypes;
17899 if (childContextTypes !== null && childContextTypes !== undefined) {
17900 popContext(interruptedWork);
17901 }
17902 break;
17903 }
17904 case HostRoot:
17905 {
17906 popHostContainer(interruptedWork);
17907 popTopLevelContextObject(interruptedWork);
17908 break;
17909 }
17910 case HostComponent:
17911 {
17912 popHostContext(interruptedWork);
17913 break;
17914 }
17915 case HostPortal:
17916 popHostContainer(interruptedWork);
17917 break;
17918 case ContextProvider:
17919 popProvider(interruptedWork);
17920 break;
17921 default:
17922 break;
17923 }
17924}
17925
17926var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
17927var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
17928
17929
17930var didWarnAboutStateTransition = void 0;
17931var didWarnSetStateChildContext = void 0;
17932var warnAboutUpdateOnUnmounted = void 0;
17933var warnAboutInvalidUpdates = void 0;
17934
17935if (enableSchedulerTracing) {
17936 // Provide explicit error message when production+profiling bundle of e.g. react-dom
17937 // is used with production (non-profiling) bundle of scheduler/tracing
17938 !(tracing.__interactionsRef != null && tracing.__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;
17939}
17940
17941{
17942 didWarnAboutStateTransition = false;
17943 didWarnSetStateChildContext = false;
17944 var didWarnStateUpdateForUnmountedComponent = {};
17945
17946 warnAboutUpdateOnUnmounted = function (fiber, isClass) {
17947 // We show the whole stack but dedupe on the top component's name because
17948 // the problematic code almost always lies inside that component.
17949 var componentName = getComponentName(fiber.type) || 'ReactComponent';
17950 if (didWarnStateUpdateForUnmountedComponent[componentName]) {
17951 return;
17952 }
17953 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));
17954 didWarnStateUpdateForUnmountedComponent[componentName] = true;
17955 };
17956
17957 warnAboutInvalidUpdates = function (instance) {
17958 switch (phase) {
17959 case 'getChildContext':
17960 if (didWarnSetStateChildContext) {
17961 return;
17962 }
17963 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
17964 didWarnSetStateChildContext = true;
17965 break;
17966 case 'render':
17967 if (didWarnAboutStateTransition) {
17968 return;
17969 }
17970 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.');
17971 didWarnAboutStateTransition = true;
17972 break;
17973 }
17974 };
17975}
17976
17977// Used to ensure computeUniqueAsyncExpiration is monotonically decreasing.
17978var lastUniqueAsyncExpiration = Sync - 1;
17979
17980// Represents the expiration time that incoming updates should use. (If this
17981// is NoWork, use the default strategy: async updates in async mode, sync
17982// updates in sync mode.)
17983var expirationContext = NoWork;
17984
17985var isWorking = false;
17986
17987// The next work in progress fiber that we're currently working on.
17988var nextUnitOfWork = null;
17989var nextRoot = null;
17990// The time at which we're currently rendering work.
17991var nextRenderExpirationTime = NoWork;
17992var nextLatestAbsoluteTimeoutMs = -1;
17993var nextRenderDidError = false;
17994
17995// The next fiber with an effect that we're currently committing.
17996var nextEffect = null;
17997
17998var isCommitting$1 = false;
17999var rootWithPendingPassiveEffects = null;
18000var passiveEffectCallbackHandle = null;
18001var passiveEffectCallback = null;
18002
18003var legacyErrorBoundariesThatAlreadyFailed = null;
18004
18005// Used for performance tracking.
18006var interruptedBy = null;
18007
18008var stashedWorkInProgressProperties = void 0;
18009var replayUnitOfWork = void 0;
18010var mayReplayFailedUnitOfWork = void 0;
18011var isReplayingFailedUnitOfWork = void 0;
18012var originalReplayError = void 0;
18013var rethrowOriginalError = void 0;
18014if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
18015 stashedWorkInProgressProperties = null;
18016 mayReplayFailedUnitOfWork = true;
18017 isReplayingFailedUnitOfWork = false;
18018 originalReplayError = null;
18019 replayUnitOfWork = function (failedUnitOfWork, thrownValue, isYieldy) {
18020 if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
18021 // Don't replay promises. Treat everything else like an error.
18022 // TODO: Need to figure out a different strategy if/when we add
18023 // support for catching other types.
18024 return;
18025 }
18026
18027 // Restore the original state of the work-in-progress
18028 if (stashedWorkInProgressProperties === null) {
18029 // This should never happen. Don't throw because this code is DEV-only.
18030 warningWithoutStack$1(false, 'Could not replay rendering after an error. This is likely a bug in React. ' + 'Please file an issue.');
18031 return;
18032 }
18033 assignFiberPropertiesInDEV(failedUnitOfWork, stashedWorkInProgressProperties);
18034
18035 switch (failedUnitOfWork.tag) {
18036 case HostRoot:
18037 popHostContainer(failedUnitOfWork);
18038 popTopLevelContextObject(failedUnitOfWork);
18039 break;
18040 case HostComponent:
18041 popHostContext(failedUnitOfWork);
18042 break;
18043 case ClassComponent:
18044 {
18045 var Component = failedUnitOfWork.type;
18046 if (isContextProvider(Component)) {
18047 popContext(failedUnitOfWork);
18048 }
18049 break;
18050 }
18051 case HostPortal:
18052 popHostContainer(failedUnitOfWork);
18053 break;
18054 case ContextProvider:
18055 popProvider(failedUnitOfWork);
18056 break;
18057 }
18058 // Replay the begin phase.
18059 isReplayingFailedUnitOfWork = true;
18060 originalReplayError = thrownValue;
18061 invokeGuardedCallback(null, workLoop, null, isYieldy);
18062 isReplayingFailedUnitOfWork = false;
18063 originalReplayError = null;
18064 if (hasCaughtError()) {
18065 var replayError = clearCaughtError();
18066 if (replayError != null && thrownValue != null) {
18067 try {
18068 // Reading the expando property is intentionally
18069 // inside `try` because it might be a getter or Proxy.
18070 if (replayError._suppressLogging) {
18071 // Also suppress logging for the original error.
18072 thrownValue._suppressLogging = true;
18073 }
18074 } catch (inner) {
18075 // Ignore.
18076 }
18077 }
18078 } else {
18079 // If the begin phase did not fail the second time, set this pointer
18080 // back to the original value.
18081 nextUnitOfWork = failedUnitOfWork;
18082 }
18083 };
18084 rethrowOriginalError = function () {
18085 throw originalReplayError;
18086 };
18087}
18088
18089function resetStack() {
18090 if (nextUnitOfWork !== null) {
18091 var interruptedWork = nextUnitOfWork.return;
18092 while (interruptedWork !== null) {
18093 unwindInterruptedWork(interruptedWork);
18094 interruptedWork = interruptedWork.return;
18095 }
18096 }
18097
18098 {
18099 ReactStrictModeWarnings.discardPendingWarnings();
18100 checkThatStackIsEmpty();
18101 }
18102
18103 nextRoot = null;
18104 nextRenderExpirationTime = NoWork;
18105 nextLatestAbsoluteTimeoutMs = -1;
18106 nextRenderDidError = false;
18107 nextUnitOfWork = null;
18108}
18109
18110function commitAllHostEffects() {
18111 while (nextEffect !== null) {
18112 {
18113 setCurrentFiber(nextEffect);
18114 }
18115 recordEffect();
18116
18117 var effectTag = nextEffect.effectTag;
18118
18119 if (effectTag & ContentReset) {
18120 commitResetTextContent(nextEffect);
18121 }
18122
18123 if (effectTag & Ref) {
18124 var current$$1 = nextEffect.alternate;
18125 if (current$$1 !== null) {
18126 commitDetachRef(current$$1);
18127 }
18128 }
18129
18130 // The following switch statement is only concerned about placement,
18131 // updates, and deletions. To avoid needing to add a case for every
18132 // possible bitmap value, we remove the secondary effects from the
18133 // effect tag and switch on that value.
18134 var primaryEffectTag = effectTag & (Placement | Update | Deletion);
18135 switch (primaryEffectTag) {
18136 case Placement:
18137 {
18138 commitPlacement(nextEffect);
18139 // Clear the "placement" from effect tag so that we know that this is inserted, before
18140 // any life-cycles like componentDidMount gets called.
18141 // TODO: findDOMNode doesn't rely on this any more but isMounted
18142 // does and isMounted is deprecated anyway so we should be able
18143 // to kill this.
18144 nextEffect.effectTag &= ~Placement;
18145 break;
18146 }
18147 case PlacementAndUpdate:
18148 {
18149 // Placement
18150 commitPlacement(nextEffect);
18151 // Clear the "placement" from effect tag so that we know that this is inserted, before
18152 // any life-cycles like componentDidMount gets called.
18153 nextEffect.effectTag &= ~Placement;
18154
18155 // Update
18156 var _current = nextEffect.alternate;
18157 commitWork(_current, nextEffect);
18158 break;
18159 }
18160 case Update:
18161 {
18162 var _current2 = nextEffect.alternate;
18163 commitWork(_current2, nextEffect);
18164 break;
18165 }
18166 case Deletion:
18167 {
18168 commitDeletion(nextEffect);
18169 break;
18170 }
18171 }
18172 nextEffect = nextEffect.nextEffect;
18173 }
18174
18175 {
18176 resetCurrentFiber();
18177 }
18178}
18179
18180function commitBeforeMutationLifecycles() {
18181 while (nextEffect !== null) {
18182 {
18183 setCurrentFiber(nextEffect);
18184 }
18185
18186 var effectTag = nextEffect.effectTag;
18187 if (effectTag & Snapshot) {
18188 recordEffect();
18189 var current$$1 = nextEffect.alternate;
18190 commitBeforeMutationLifeCycles(current$$1, nextEffect);
18191 }
18192
18193 nextEffect = nextEffect.nextEffect;
18194 }
18195
18196 {
18197 resetCurrentFiber();
18198 }
18199}
18200
18201function commitAllLifeCycles(finishedRoot, committedExpirationTime) {
18202 {
18203 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
18204 ReactStrictModeWarnings.flushLegacyContextWarning();
18205
18206 if (warnAboutDeprecatedLifecycles) {
18207 ReactStrictModeWarnings.flushPendingDeprecationWarnings();
18208 }
18209 }
18210 while (nextEffect !== null) {
18211 {
18212 setCurrentFiber(nextEffect);
18213 }
18214 var effectTag = nextEffect.effectTag;
18215
18216 if (effectTag & (Update | Callback)) {
18217 recordEffect();
18218 var current$$1 = nextEffect.alternate;
18219 commitLifeCycles(finishedRoot, current$$1, nextEffect, committedExpirationTime);
18220 }
18221
18222 if (effectTag & Ref) {
18223 recordEffect();
18224 commitAttachRef(nextEffect);
18225 }
18226
18227 if (effectTag & Passive) {
18228 rootWithPendingPassiveEffects = finishedRoot;
18229 }
18230
18231 nextEffect = nextEffect.nextEffect;
18232 }
18233 {
18234 resetCurrentFiber();
18235 }
18236}
18237
18238function commitPassiveEffects(root, firstEffect) {
18239 rootWithPendingPassiveEffects = null;
18240 passiveEffectCallbackHandle = null;
18241 passiveEffectCallback = null;
18242
18243 // Set this to true to prevent re-entrancy
18244 var previousIsRendering = isRendering;
18245 isRendering = true;
18246
18247 var effect = firstEffect;
18248 do {
18249 {
18250 setCurrentFiber(effect);
18251 }
18252
18253 if (effect.effectTag & Passive) {
18254 var didError = false;
18255 var error = void 0;
18256 {
18257 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
18258 if (hasCaughtError()) {
18259 didError = true;
18260 error = clearCaughtError();
18261 }
18262 }
18263 if (didError) {
18264 captureCommitPhaseError(effect, error);
18265 }
18266 }
18267 effect = effect.nextEffect;
18268 } while (effect !== null);
18269 {
18270 resetCurrentFiber();
18271 }
18272
18273 isRendering = previousIsRendering;
18274
18275 // Check if work was scheduled by one of the effects
18276 var rootExpirationTime = root.expirationTime;
18277 if (rootExpirationTime !== NoWork) {
18278 requestWork(root, rootExpirationTime);
18279 }
18280}
18281
18282function isAlreadyFailedLegacyErrorBoundary(instance) {
18283 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
18284}
18285
18286function markLegacyErrorBoundaryAsFailed(instance) {
18287 if (legacyErrorBoundariesThatAlreadyFailed === null) {
18288 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
18289 } else {
18290 legacyErrorBoundariesThatAlreadyFailed.add(instance);
18291 }
18292}
18293
18294function flushPassiveEffects() {
18295 if (passiveEffectCallbackHandle !== null) {
18296 cancelPassiveEffects(passiveEffectCallbackHandle);
18297 }
18298 if (passiveEffectCallback !== null) {
18299 // We call the scheduled callback instead of commitPassiveEffects directly
18300 // to ensure tracing works correctly.
18301 passiveEffectCallback();
18302 }
18303}
18304
18305function commitRoot(root, finishedWork) {
18306 isWorking = true;
18307 isCommitting$1 = true;
18308 startCommitTimer();
18309
18310 !(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;
18311 var committedExpirationTime = root.pendingCommitExpirationTime;
18312 !(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;
18313 root.pendingCommitExpirationTime = NoWork;
18314
18315 // Update the pending priority levels to account for the work that we are
18316 // about to commit. This needs to happen before calling the lifecycles, since
18317 // they may schedule additional updates.
18318 var updateExpirationTimeBeforeCommit = finishedWork.expirationTime;
18319 var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime;
18320 var earliestRemainingTimeBeforeCommit = childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit ? childExpirationTimeBeforeCommit : updateExpirationTimeBeforeCommit;
18321 markCommittedPriorityLevels(root, earliestRemainingTimeBeforeCommit);
18322
18323 var prevInteractions = null;
18324 if (enableSchedulerTracing) {
18325 // Restore any pending interactions at this point,
18326 // So that cascading work triggered during the render phase will be accounted for.
18327 prevInteractions = tracing.__interactionsRef.current;
18328 tracing.__interactionsRef.current = root.memoizedInteractions;
18329 }
18330
18331 // Reset this to null before calling lifecycles
18332 ReactCurrentOwner$2.current = null;
18333
18334 var firstEffect = void 0;
18335 if (finishedWork.effectTag > PerformedWork) {
18336 // A fiber's effect list consists only of its children, not itself. So if
18337 // the root has an effect, we need to add it to the end of the list. The
18338 // resulting list is the set that would belong to the root's parent, if
18339 // it had one; that is, all the effects in the tree including the root.
18340 if (finishedWork.lastEffect !== null) {
18341 finishedWork.lastEffect.nextEffect = finishedWork;
18342 firstEffect = finishedWork.firstEffect;
18343 } else {
18344 firstEffect = finishedWork;
18345 }
18346 } else {
18347 // There is no effect on the root.
18348 firstEffect = finishedWork.firstEffect;
18349 }
18350
18351 prepareForCommit(root.containerInfo);
18352
18353 // Invoke instances of getSnapshotBeforeUpdate before mutation.
18354 nextEffect = firstEffect;
18355 startCommitSnapshotEffectsTimer();
18356 while (nextEffect !== null) {
18357 var didError = false;
18358 var error = void 0;
18359 {
18360 invokeGuardedCallback(null, commitBeforeMutationLifecycles, null);
18361 if (hasCaughtError()) {
18362 didError = true;
18363 error = clearCaughtError();
18364 }
18365 }
18366 if (didError) {
18367 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
18368 captureCommitPhaseError(nextEffect, error);
18369 // Clean-up
18370 if (nextEffect !== null) {
18371 nextEffect = nextEffect.nextEffect;
18372 }
18373 }
18374 }
18375 stopCommitSnapshotEffectsTimer();
18376
18377 if (enableProfilerTimer) {
18378 // Mark the current commit time to be shared by all Profilers in this batch.
18379 // This enables them to be grouped later.
18380 recordCommitTime();
18381 }
18382
18383 // Commit all the side-effects within a tree. We'll do this in two passes.
18384 // The first pass performs all the host insertions, updates, deletions and
18385 // ref unmounts.
18386 nextEffect = firstEffect;
18387 startCommitHostEffectsTimer();
18388 while (nextEffect !== null) {
18389 var _didError = false;
18390 var _error = void 0;
18391 {
18392 invokeGuardedCallback(null, commitAllHostEffects, null);
18393 if (hasCaughtError()) {
18394 _didError = true;
18395 _error = clearCaughtError();
18396 }
18397 }
18398 if (_didError) {
18399 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
18400 captureCommitPhaseError(nextEffect, _error);
18401 // Clean-up
18402 if (nextEffect !== null) {
18403 nextEffect = nextEffect.nextEffect;
18404 }
18405 }
18406 }
18407 stopCommitHostEffectsTimer();
18408
18409 resetAfterCommit(root.containerInfo);
18410
18411 // The work-in-progress tree is now the current tree. This must come after
18412 // the first pass of the commit phase, so that the previous tree is still
18413 // current during componentWillUnmount, but before the second pass, so that
18414 // the finished work is current during componentDidMount/Update.
18415 root.current = finishedWork;
18416
18417 // In the second pass we'll perform all life-cycles and ref callbacks.
18418 // Life-cycles happen as a separate pass so that all placements, updates,
18419 // and deletions in the entire tree have already been invoked.
18420 // This pass also triggers any renderer-specific initial effects.
18421 nextEffect = firstEffect;
18422 startCommitLifeCyclesTimer();
18423 while (nextEffect !== null) {
18424 var _didError2 = false;
18425 var _error2 = void 0;
18426 {
18427 invokeGuardedCallback(null, commitAllLifeCycles, null, root, committedExpirationTime);
18428 if (hasCaughtError()) {
18429 _didError2 = true;
18430 _error2 = clearCaughtError();
18431 }
18432 }
18433 if (_didError2) {
18434 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
18435 captureCommitPhaseError(nextEffect, _error2);
18436 if (nextEffect !== null) {
18437 nextEffect = nextEffect.nextEffect;
18438 }
18439 }
18440 }
18441
18442 if (firstEffect !== null && rootWithPendingPassiveEffects !== null) {
18443 // This commit included a passive effect. These do not need to fire until
18444 // after the next paint. Schedule an callback to fire them in an async
18445 // event. To ensure serial execution, the callback will be flushed early if
18446 // we enter rootWithPendingPassiveEffects commit phase before then.
18447 var callback = commitPassiveEffects.bind(null, root, firstEffect);
18448 if (enableSchedulerTracing) {
18449 // TODO: Avoid this extra callback by mutating the tracing ref directly,
18450 // like we do at the beginning of commitRoot. I've opted not to do that
18451 // here because that code is still in flux.
18452 callback = tracing.unstable_wrap(callback);
18453 }
18454 passiveEffectCallbackHandle = schedulePassiveEffects(callback);
18455 passiveEffectCallback = callback;
18456 }
18457
18458 isCommitting$1 = false;
18459 isWorking = false;
18460 stopCommitLifeCyclesTimer();
18461 stopCommitTimer();
18462 onCommitRoot(finishedWork.stateNode);
18463 if (true && ReactFiberInstrumentation_1.debugTool) {
18464 ReactFiberInstrumentation_1.debugTool.onCommitWork(finishedWork);
18465 }
18466
18467 var updateExpirationTimeAfterCommit = finishedWork.expirationTime;
18468 var childExpirationTimeAfterCommit = finishedWork.childExpirationTime;
18469 var earliestRemainingTimeAfterCommit = childExpirationTimeAfterCommit > updateExpirationTimeAfterCommit ? childExpirationTimeAfterCommit : updateExpirationTimeAfterCommit;
18470 if (earliestRemainingTimeAfterCommit === NoWork) {
18471 // If there's no remaining work, we can clear the set of already failed
18472 // error boundaries.
18473 legacyErrorBoundariesThatAlreadyFailed = null;
18474 }
18475 onCommit(root, earliestRemainingTimeAfterCommit);
18476
18477 if (enableSchedulerTracing) {
18478 tracing.__interactionsRef.current = prevInteractions;
18479
18480 var subscriber = void 0;
18481
18482 try {
18483 subscriber = tracing.__subscriberRef.current;
18484 if (subscriber !== null && root.memoizedInteractions.size > 0) {
18485 var threadID = computeThreadID(committedExpirationTime, root.interactionThreadID);
18486 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
18487 }
18488 } catch (error) {
18489 // It's not safe for commitRoot() to throw.
18490 // Store the error for now and we'll re-throw in finishRendering().
18491 if (!hasUnhandledError) {
18492 hasUnhandledError = true;
18493 unhandledError = error;
18494 }
18495 } finally {
18496 // Clear completed interactions from the pending Map.
18497 // Unless the render was suspended or cascading work was scheduled,
18498 // In which case– leave pending interactions until the subsequent render.
18499 var pendingInteractionMap = root.pendingInteractionMap;
18500 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
18501 // Only decrement the pending interaction count if we're done.
18502 // If there's still work at the current priority,
18503 // That indicates that we are waiting for suspense data.
18504 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
18505 pendingInteractionMap.delete(scheduledExpirationTime);
18506
18507 scheduledInteractions.forEach(function (interaction) {
18508 interaction.__count--;
18509
18510 if (subscriber !== null && interaction.__count === 0) {
18511 try {
18512 subscriber.onInteractionScheduledWorkCompleted(interaction);
18513 } catch (error) {
18514 // It's not safe for commitRoot() to throw.
18515 // Store the error for now and we'll re-throw in finishRendering().
18516 if (!hasUnhandledError) {
18517 hasUnhandledError = true;
18518 unhandledError = error;
18519 }
18520 }
18521 }
18522 });
18523 }
18524 });
18525 }
18526 }
18527}
18528
18529function resetChildExpirationTime(workInProgress, renderTime) {
18530 if (renderTime !== Never && workInProgress.childExpirationTime === Never) {
18531 // The children of this component are hidden. Don't bubble their
18532 // expiration times.
18533 return;
18534 }
18535
18536 var newChildExpirationTime = NoWork;
18537
18538 // Bubble up the earliest expiration time.
18539 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
18540 // We're in profiling mode.
18541 // Let's use this same traversal to update the render durations.
18542 var actualDuration = workInProgress.actualDuration;
18543 var treeBaseDuration = workInProgress.selfBaseDuration;
18544
18545 // When a fiber is cloned, its actualDuration is reset to 0.
18546 // This value will only be updated if work is done on the fiber (i.e. it doesn't bailout).
18547 // When work is done, it should bubble to the parent's actualDuration.
18548 // If the fiber has not been cloned though, (meaning no work was done),
18549 // Then this value will reflect the amount of time spent working on a previous render.
18550 // In that case it should not bubble.
18551 // We determine whether it was cloned by comparing the child pointer.
18552 var shouldBubbleActualDurations = workInProgress.alternate === null || workInProgress.child !== workInProgress.alternate.child;
18553
18554 var child = workInProgress.child;
18555 while (child !== null) {
18556 var childUpdateExpirationTime = child.expirationTime;
18557 var childChildExpirationTime = child.childExpirationTime;
18558 if (childUpdateExpirationTime > newChildExpirationTime) {
18559 newChildExpirationTime = childUpdateExpirationTime;
18560 }
18561 if (childChildExpirationTime > newChildExpirationTime) {
18562 newChildExpirationTime = childChildExpirationTime;
18563 }
18564 if (shouldBubbleActualDurations) {
18565 actualDuration += child.actualDuration;
18566 }
18567 treeBaseDuration += child.treeBaseDuration;
18568 child = child.sibling;
18569 }
18570 workInProgress.actualDuration = actualDuration;
18571 workInProgress.treeBaseDuration = treeBaseDuration;
18572 } else {
18573 var _child = workInProgress.child;
18574 while (_child !== null) {
18575 var _childUpdateExpirationTime = _child.expirationTime;
18576 var _childChildExpirationTime = _child.childExpirationTime;
18577 if (_childUpdateExpirationTime > newChildExpirationTime) {
18578 newChildExpirationTime = _childUpdateExpirationTime;
18579 }
18580 if (_childChildExpirationTime > newChildExpirationTime) {
18581 newChildExpirationTime = _childChildExpirationTime;
18582 }
18583 _child = _child.sibling;
18584 }
18585 }
18586
18587 workInProgress.childExpirationTime = newChildExpirationTime;
18588}
18589
18590function completeUnitOfWork(workInProgress) {
18591 // Attempt to complete the current unit of work, then move to the
18592 // next sibling. If there are no more siblings, return to the
18593 // parent fiber.
18594 while (true) {
18595 // The current, flushed, state of this fiber is the alternate.
18596 // Ideally nothing should rely on this, but relying on it here
18597 // means that we don't need an additional field on the work in
18598 // progress.
18599 var current$$1 = workInProgress.alternate;
18600 {
18601 setCurrentFiber(workInProgress);
18602 }
18603
18604 var returnFiber = workInProgress.return;
18605 var siblingFiber = workInProgress.sibling;
18606
18607 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
18608 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
18609 // Don't replay if it fails during completion phase.
18610 mayReplayFailedUnitOfWork = false;
18611 }
18612 // This fiber completed.
18613 // Remember we're completing this unit so we can find a boundary if it fails.
18614 nextUnitOfWork = workInProgress;
18615 if (enableProfilerTimer) {
18616 if (workInProgress.mode & ProfileMode) {
18617 startProfilerTimer(workInProgress);
18618 }
18619 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
18620 if (workInProgress.mode & ProfileMode) {
18621 // Update render duration assuming we didn't error.
18622 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
18623 }
18624 } else {
18625 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
18626 }
18627 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
18628 // We're out of completion phase so replaying is fine now.
18629 mayReplayFailedUnitOfWork = true;
18630 }
18631 stopWorkTimer(workInProgress);
18632 resetChildExpirationTime(workInProgress, nextRenderExpirationTime);
18633 {
18634 resetCurrentFiber();
18635 }
18636
18637 if (nextUnitOfWork !== null) {
18638 // Completing this fiber spawned new work. Work on that next.
18639 return nextUnitOfWork;
18640 }
18641
18642 if (returnFiber !== null &&
18643 // Do not append effects to parents if a sibling failed to complete
18644 (returnFiber.effectTag & Incomplete) === NoEffect) {
18645 // Append all the effects of the subtree and this fiber onto the effect
18646 // list of the parent. The completion order of the children affects the
18647 // side-effect order.
18648 if (returnFiber.firstEffect === null) {
18649 returnFiber.firstEffect = workInProgress.firstEffect;
18650 }
18651 if (workInProgress.lastEffect !== null) {
18652 if (returnFiber.lastEffect !== null) {
18653 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
18654 }
18655 returnFiber.lastEffect = workInProgress.lastEffect;
18656 }
18657
18658 // If this fiber had side-effects, we append it AFTER the children's
18659 // side-effects. We can perform certain side-effects earlier if
18660 // needed, by doing multiple passes over the effect list. We don't want
18661 // to schedule our own side-effect on our own list because if end up
18662 // reusing children we'll schedule this effect onto itself since we're
18663 // at the end.
18664 var effectTag = workInProgress.effectTag;
18665 // Skip both NoWork and PerformedWork tags when creating the effect list.
18666 // PerformedWork effect is read by React DevTools but shouldn't be committed.
18667 if (effectTag > PerformedWork) {
18668 if (returnFiber.lastEffect !== null) {
18669 returnFiber.lastEffect.nextEffect = workInProgress;
18670 } else {
18671 returnFiber.firstEffect = workInProgress;
18672 }
18673 returnFiber.lastEffect = workInProgress;
18674 }
18675 }
18676
18677 if (true && ReactFiberInstrumentation_1.debugTool) {
18678 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
18679 }
18680
18681 if (siblingFiber !== null) {
18682 // If there is more work to do in this returnFiber, do that next.
18683 return siblingFiber;
18684 } else if (returnFiber !== null) {
18685 // If there's no more work in this returnFiber. Complete the returnFiber.
18686 workInProgress = returnFiber;
18687 continue;
18688 } else {
18689 // We've reached the root.
18690 return null;
18691 }
18692 } else {
18693 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
18694 // Record the render duration for the fiber that errored.
18695 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
18696
18697 // Include the time spent working on failed children before continuing.
18698 var actualDuration = workInProgress.actualDuration;
18699 var child = workInProgress.child;
18700 while (child !== null) {
18701 actualDuration += child.actualDuration;
18702 child = child.sibling;
18703 }
18704 workInProgress.actualDuration = actualDuration;
18705 }
18706
18707 // This fiber did not complete because something threw. Pop values off
18708 // the stack without entering the complete phase. If this is a boundary,
18709 // capture values if possible.
18710 var next = unwindWork(workInProgress, nextRenderExpirationTime);
18711 // Because this fiber did not complete, don't reset its expiration time.
18712 if (workInProgress.effectTag & DidCapture) {
18713 // Restarting an error boundary
18714 stopFailedWorkTimer(workInProgress);
18715 } else {
18716 stopWorkTimer(workInProgress);
18717 }
18718
18719 {
18720 resetCurrentFiber();
18721 }
18722
18723 if (next !== null) {
18724 stopWorkTimer(workInProgress);
18725 if (true && ReactFiberInstrumentation_1.debugTool) {
18726 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
18727 }
18728
18729 // If completing this work spawned new work, do that next. We'll come
18730 // back here again.
18731 // Since we're restarting, remove anything that is not a host effect
18732 // from the effect tag.
18733 next.effectTag &= HostEffectMask;
18734 return next;
18735 }
18736
18737 if (returnFiber !== null) {
18738 // Mark the parent fiber as incomplete and clear its effect list.
18739 returnFiber.firstEffect = returnFiber.lastEffect = null;
18740 returnFiber.effectTag |= Incomplete;
18741 }
18742
18743 if (true && ReactFiberInstrumentation_1.debugTool) {
18744 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
18745 }
18746
18747 if (siblingFiber !== null) {
18748 // If there is more work to do in this returnFiber, do that next.
18749 return siblingFiber;
18750 } else if (returnFiber !== null) {
18751 // If there's no more work in this returnFiber. Complete the returnFiber.
18752 workInProgress = returnFiber;
18753 continue;
18754 } else {
18755 return null;
18756 }
18757 }
18758 }
18759
18760 // Without this explicit null return Flow complains of invalid return type
18761 // TODO Remove the above while(true) loop
18762 // eslint-disable-next-line no-unreachable
18763 return null;
18764}
18765
18766function performUnitOfWork(workInProgress) {
18767 // The current, flushed, state of this fiber is the alternate.
18768 // Ideally nothing should rely on this, but relying on it here
18769 // means that we don't need an additional field on the work in
18770 // progress.
18771 var current$$1 = workInProgress.alternate;
18772
18773 // See if beginning this work spawns more work.
18774 startWorkTimer(workInProgress);
18775 {
18776 setCurrentFiber(workInProgress);
18777 }
18778
18779 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
18780 stashedWorkInProgressProperties = assignFiberPropertiesInDEV(stashedWorkInProgressProperties, workInProgress);
18781 }
18782
18783 var next = void 0;
18784 if (enableProfilerTimer) {
18785 if (workInProgress.mode & ProfileMode) {
18786 startProfilerTimer(workInProgress);
18787 }
18788
18789 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
18790 workInProgress.memoizedProps = workInProgress.pendingProps;
18791
18792 if (workInProgress.mode & ProfileMode) {
18793 // Record the render duration assuming we didn't bailout (or error).
18794 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
18795 }
18796 } else {
18797 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
18798 workInProgress.memoizedProps = workInProgress.pendingProps;
18799 }
18800
18801 {
18802 resetCurrentFiber();
18803 if (isReplayingFailedUnitOfWork) {
18804 // Currently replaying a failed unit of work. This should be unreachable,
18805 // because the render phase is meant to be idempotent, and it should
18806 // have thrown again. Since it didn't, rethrow the original error, so
18807 // React's internal stack is not misaligned.
18808 rethrowOriginalError();
18809 }
18810 }
18811 if (true && ReactFiberInstrumentation_1.debugTool) {
18812 ReactFiberInstrumentation_1.debugTool.onBeginWork(workInProgress);
18813 }
18814
18815 if (next === null) {
18816 // If this doesn't spawn new work, complete the current work.
18817 next = completeUnitOfWork(workInProgress);
18818 }
18819
18820 ReactCurrentOwner$2.current = null;
18821
18822 return next;
18823}
18824
18825function workLoop(isYieldy) {
18826 if (!isYieldy) {
18827 // Flush work without yielding
18828 while (nextUnitOfWork !== null) {
18829 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
18830 }
18831 } else {
18832 // Flush asynchronous work until there's a higher priority event
18833 while (nextUnitOfWork !== null && !shouldYieldToRenderer()) {
18834 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
18835 }
18836 }
18837}
18838
18839function renderRoot(root, isYieldy) {
18840 !!isWorking ? invariant(false, 'renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;
18841
18842 flushPassiveEffects();
18843
18844 isWorking = true;
18845 var previousDispatcher = ReactCurrentDispatcher.current;
18846 ReactCurrentDispatcher.current = ContextOnlyDispatcher;
18847
18848 var expirationTime = root.nextExpirationTimeToWorkOn;
18849
18850 // Check if we're starting from a fresh stack, or if we're resuming from
18851 // previously yielded work.
18852 if (expirationTime !== nextRenderExpirationTime || root !== nextRoot || nextUnitOfWork === null) {
18853 // Reset the stack and start working from the root.
18854 resetStack();
18855 nextRoot = root;
18856 nextRenderExpirationTime = expirationTime;
18857 nextUnitOfWork = createWorkInProgress(nextRoot.current, null, nextRenderExpirationTime);
18858 root.pendingCommitExpirationTime = NoWork;
18859
18860 if (enableSchedulerTracing) {
18861 // Determine which interactions this batch of work currently includes,
18862 // So that we can accurately attribute time spent working on it,
18863 var interactions = new Set();
18864 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
18865 if (scheduledExpirationTime >= expirationTime) {
18866 scheduledInteractions.forEach(function (interaction) {
18867 return interactions.add(interaction);
18868 });
18869 }
18870 });
18871
18872 // Store the current set of interactions on the FiberRoot for a few reasons:
18873 // We can re-use it in hot functions like renderRoot() without having to recalculate it.
18874 // We will also use it in commitWork() to pass to any Profiler onRender() hooks.
18875 // This also provides DevTools with a way to access it when the onCommitRoot() hook is called.
18876 root.memoizedInteractions = interactions;
18877
18878 if (interactions.size > 0) {
18879 var subscriber = tracing.__subscriberRef.current;
18880 if (subscriber !== null) {
18881 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
18882 try {
18883 subscriber.onWorkStarted(interactions, threadID);
18884 } catch (error) {
18885 // Work thrown by an interaction tracing subscriber should be rethrown,
18886 // But only once it's safe (to avoid leaving the scheduler in an invalid state).
18887 // Store the error for now and we'll re-throw in finishRendering().
18888 if (!hasUnhandledError) {
18889 hasUnhandledError = true;
18890 unhandledError = error;
18891 }
18892 }
18893 }
18894 }
18895 }
18896 }
18897
18898 var prevInteractions = null;
18899 if (enableSchedulerTracing) {
18900 // We're about to start new traced work.
18901 // Restore pending interactions so cascading work triggered during the render phase will be accounted for.
18902 prevInteractions = tracing.__interactionsRef.current;
18903 tracing.__interactionsRef.current = root.memoizedInteractions;
18904 }
18905
18906 var didFatal = false;
18907
18908 startWorkLoopTimer(nextUnitOfWork);
18909
18910 do {
18911 try {
18912 workLoop(isYieldy);
18913 } catch (thrownValue) {
18914 resetContextDependences();
18915 resetHooks();
18916
18917 // Reset in case completion throws.
18918 // This is only used in DEV and when replaying is on.
18919 var mayReplay = void 0;
18920 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
18921 mayReplay = mayReplayFailedUnitOfWork;
18922 mayReplayFailedUnitOfWork = true;
18923 }
18924
18925 if (nextUnitOfWork === null) {
18926 // This is a fatal error.
18927 didFatal = true;
18928 onUncaughtError(thrownValue);
18929 } else {
18930 if (enableProfilerTimer && nextUnitOfWork.mode & ProfileMode) {
18931 // Record the time spent rendering before an error was thrown.
18932 // This avoids inaccurate Profiler durations in the case of a suspended render.
18933 stopProfilerTimerIfRunningAndRecordDelta(nextUnitOfWork, true);
18934 }
18935
18936 {
18937 // Reset global debug state
18938 // We assume this is defined in DEV
18939 resetCurrentlyProcessingQueue();
18940 }
18941
18942 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
18943 if (mayReplay) {
18944 var failedUnitOfWork = nextUnitOfWork;
18945 replayUnitOfWork(failedUnitOfWork, thrownValue, isYieldy);
18946 }
18947 }
18948
18949 // TODO: we already know this isn't true in some cases.
18950 // At least this shows a nicer error message until we figure out the cause.
18951 // https://github.com/facebook/react/issues/12449#issuecomment-386727431
18952 !(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;
18953
18954 var sourceFiber = nextUnitOfWork;
18955 var returnFiber = sourceFiber.return;
18956 if (returnFiber === null) {
18957 // This is the root. The root could capture its own errors. However,
18958 // we don't know if it errors before or after we pushed the host
18959 // context. This information is needed to avoid a stack mismatch.
18960 // Because we're not sure, treat this as a fatal error. We could track
18961 // which phase it fails in, but doesn't seem worth it. At least
18962 // for now.
18963 didFatal = true;
18964 onUncaughtError(thrownValue);
18965 } else {
18966 throwException(root, returnFiber, sourceFiber, thrownValue, nextRenderExpirationTime);
18967 nextUnitOfWork = completeUnitOfWork(sourceFiber);
18968 continue;
18969 }
18970 }
18971 }
18972 break;
18973 } while (true);
18974
18975 if (enableSchedulerTracing) {
18976 // Traced work is done for now; restore the previous interactions.
18977 tracing.__interactionsRef.current = prevInteractions;
18978 }
18979
18980 // We're done performing work. Time to clean up.
18981 isWorking = false;
18982 ReactCurrentDispatcher.current = previousDispatcher;
18983 resetContextDependences();
18984 resetHooks();
18985
18986 // Yield back to main thread.
18987 if (didFatal) {
18988 var _didCompleteRoot = false;
18989 stopWorkLoopTimer(interruptedBy, _didCompleteRoot);
18990 interruptedBy = null;
18991 // There was a fatal error.
18992 {
18993 resetStackAfterFatalErrorInDev();
18994 }
18995 // `nextRoot` points to the in-progress root. A non-null value indicates
18996 // that we're in the middle of an async render. Set it to null to indicate
18997 // there's no more work to be done in the current batch.
18998 nextRoot = null;
18999 onFatal(root);
19000 return;
19001 }
19002
19003 if (nextUnitOfWork !== null) {
19004 // There's still remaining async work in this tree, but we ran out of time
19005 // in the current frame. Yield back to the renderer. Unless we're
19006 // interrupted by a higher priority update, we'll continue later from where
19007 // we left off.
19008 var _didCompleteRoot2 = false;
19009 stopWorkLoopTimer(interruptedBy, _didCompleteRoot2);
19010 interruptedBy = null;
19011 onYield(root);
19012 return;
19013 }
19014
19015 // We completed the whole tree.
19016 var didCompleteRoot = true;
19017 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
19018 var rootWorkInProgress = root.current.alternate;
19019 !(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;
19020
19021 // `nextRoot` points to the in-progress root. A non-null value indicates
19022 // that we're in the middle of an async render. Set it to null to indicate
19023 // there's no more work to be done in the current batch.
19024 nextRoot = null;
19025 interruptedBy = null;
19026
19027 if (nextRenderDidError) {
19028 // There was an error
19029 if (hasLowerPriorityWork(root, expirationTime)) {
19030 // There's lower priority work. If so, it may have the effect of fixing
19031 // the exception that was just thrown. Exit without committing. This is
19032 // similar to a suspend, but without a timeout because we're not waiting
19033 // for a promise to resolve. React will restart at the lower
19034 // priority level.
19035 markSuspendedPriorityLevel(root, expirationTime);
19036 var suspendedExpirationTime = expirationTime;
19037 var rootExpirationTime = root.expirationTime;
19038 onSuspend(root, rootWorkInProgress, suspendedExpirationTime, rootExpirationTime, -1 // Indicates no timeout
19039 );
19040 return;
19041 } else if (
19042 // There's no lower priority work, but we're rendering asynchronously.
19043 // Synchronsouly attempt to render the same level one more time. This is
19044 // similar to a suspend, but without a timeout because we're not waiting
19045 // for a promise to resolve.
19046 !root.didError && isYieldy) {
19047 root.didError = true;
19048 var _suspendedExpirationTime = root.nextExpirationTimeToWorkOn = expirationTime;
19049 var _rootExpirationTime = root.expirationTime = Sync;
19050 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime, _rootExpirationTime, -1 // Indicates no timeout
19051 );
19052 return;
19053 }
19054 }
19055
19056 if (isYieldy && nextLatestAbsoluteTimeoutMs !== -1) {
19057 // The tree was suspended.
19058 var _suspendedExpirationTime2 = expirationTime;
19059 markSuspendedPriorityLevel(root, _suspendedExpirationTime2);
19060
19061 // Find the earliest uncommitted expiration time in the tree, including
19062 // work that is suspended. The timeout threshold cannot be longer than
19063 // the overall expiration.
19064 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, expirationTime);
19065 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
19066 if (earliestExpirationTimeMs < nextLatestAbsoluteTimeoutMs) {
19067 nextLatestAbsoluteTimeoutMs = earliestExpirationTimeMs;
19068 }
19069
19070 // Subtract the current time from the absolute timeout to get the number
19071 // of milliseconds until the timeout. In other words, convert an absolute
19072 // timestamp to a relative time. This is the value that is passed
19073 // to `setTimeout`.
19074 var currentTimeMs = expirationTimeToMs(requestCurrentTime());
19075 var msUntilTimeout = nextLatestAbsoluteTimeoutMs - currentTimeMs;
19076 msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout;
19077
19078 // TODO: Account for the Just Noticeable Difference
19079
19080 var _rootExpirationTime2 = root.expirationTime;
19081 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime2, _rootExpirationTime2, msUntilTimeout);
19082 return;
19083 }
19084
19085 // Ready to commit.
19086 onComplete(root, rootWorkInProgress, expirationTime);
19087}
19088
19089function captureCommitPhaseError(sourceFiber, value) {
19090 var expirationTime = Sync;
19091 var fiber = sourceFiber.return;
19092 while (fiber !== null) {
19093 switch (fiber.tag) {
19094 case ClassComponent:
19095 var ctor = fiber.type;
19096 var instance = fiber.stateNode;
19097 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
19098 var errorInfo = createCapturedValue(value, sourceFiber);
19099 var update = createClassErrorUpdate(fiber, errorInfo, expirationTime);
19100 enqueueUpdate(fiber, update);
19101 scheduleWork(fiber, expirationTime);
19102 return;
19103 }
19104 break;
19105 case HostRoot:
19106 {
19107 var _errorInfo = createCapturedValue(value, sourceFiber);
19108 var _update = createRootErrorUpdate(fiber, _errorInfo, expirationTime);
19109 enqueueUpdate(fiber, _update);
19110 scheduleWork(fiber, expirationTime);
19111 return;
19112 }
19113 }
19114 fiber = fiber.return;
19115 }
19116
19117 if (sourceFiber.tag === HostRoot) {
19118 // Error was thrown at the root. There is no parent, so the root
19119 // itself should capture it.
19120 var rootFiber = sourceFiber;
19121 var _errorInfo2 = createCapturedValue(value, rootFiber);
19122 var _update2 = createRootErrorUpdate(rootFiber, _errorInfo2, expirationTime);
19123 enqueueUpdate(rootFiber, _update2);
19124 scheduleWork(rootFiber, expirationTime);
19125 }
19126}
19127
19128function computeThreadID(expirationTime, interactionThreadID) {
19129 // Interaction threads are unique per root and expiration time.
19130 return expirationTime * 1000 + interactionThreadID;
19131}
19132
19133// Creates a unique async expiration time.
19134function computeUniqueAsyncExpiration() {
19135 var currentTime = requestCurrentTime();
19136 var result = computeAsyncExpiration(currentTime);
19137 if (result >= lastUniqueAsyncExpiration) {
19138 // Since we assume the current time monotonically increases, we only hit
19139 // this branch when computeUniqueAsyncExpiration is fired multiple times
19140 // within a 200ms window (or whatever the async bucket size is).
19141 result = lastUniqueAsyncExpiration - 1;
19142 }
19143 lastUniqueAsyncExpiration = result;
19144 return lastUniqueAsyncExpiration;
19145}
19146
19147function computeExpirationForFiber(currentTime, fiber) {
19148 var expirationTime = void 0;
19149 if (expirationContext !== NoWork) {
19150 // An explicit expiration context was set;
19151 expirationTime = expirationContext;
19152 } else if (isWorking) {
19153 if (isCommitting$1) {
19154 // Updates that occur during the commit phase should have sync priority
19155 // by default.
19156 expirationTime = Sync;
19157 } else {
19158 // Updates during the render phase should expire at the same time as
19159 // the work that is being rendered.
19160 expirationTime = nextRenderExpirationTime;
19161 }
19162 } else {
19163 // No explicit expiration context was set, and we're not currently
19164 // performing work. Calculate a new expiration time.
19165 if (fiber.mode & ConcurrentMode) {
19166 if (isBatchingInteractiveUpdates) {
19167 // This is an interactive update
19168 expirationTime = computeInteractiveExpiration(currentTime);
19169 } else {
19170 // This is an async update
19171 expirationTime = computeAsyncExpiration(currentTime);
19172 }
19173 // If we're in the middle of rendering a tree, do not update at the same
19174 // expiration time that is already rendering.
19175 if (nextRoot !== null && expirationTime === nextRenderExpirationTime) {
19176 expirationTime -= 1;
19177 }
19178 } else {
19179 // This is a sync update
19180 expirationTime = Sync;
19181 }
19182 }
19183 if (isBatchingInteractiveUpdates) {
19184 // This is an interactive update. Keep track of the lowest pending
19185 // interactive expiration time. This allows us to synchronously flush
19186 // all interactive updates when needed.
19187 if (lowestPriorityPendingInteractiveExpirationTime === NoWork || expirationTime < lowestPriorityPendingInteractiveExpirationTime) {
19188 lowestPriorityPendingInteractiveExpirationTime = expirationTime;
19189 }
19190 }
19191 return expirationTime;
19192}
19193
19194function renderDidSuspend(root, absoluteTimeoutMs, suspendedTime) {
19195 // Schedule the timeout.
19196 if (absoluteTimeoutMs >= 0 && nextLatestAbsoluteTimeoutMs < absoluteTimeoutMs) {
19197 nextLatestAbsoluteTimeoutMs = absoluteTimeoutMs;
19198 }
19199}
19200
19201function renderDidError() {
19202 nextRenderDidError = true;
19203}
19204
19205function pingSuspendedRoot(root, thenable, pingTime) {
19206 // A promise that previously suspended React from committing has resolved.
19207 // If React is still suspended, try again at the previous level (pingTime).
19208
19209 var pingCache = root.pingCache;
19210 if (pingCache !== null) {
19211 // The thenable resolved, so we no longer need to memoize, because it will
19212 // never be thrown again.
19213 pingCache.delete(thenable);
19214 }
19215
19216 if (nextRoot !== null && nextRenderExpirationTime === pingTime) {
19217 // Received a ping at the same priority level at which we're currently
19218 // rendering. Restart from the root.
19219 nextRoot = null;
19220 } else {
19221 // Confirm that the root is still suspended at this level. Otherwise exit.
19222 if (isPriorityLevelSuspended(root, pingTime)) {
19223 // Ping at the original level
19224 markPingedPriorityLevel(root, pingTime);
19225 var rootExpirationTime = root.expirationTime;
19226 if (rootExpirationTime !== NoWork) {
19227 requestWork(root, rootExpirationTime);
19228 }
19229 }
19230 }
19231}
19232
19233function retryTimedOutBoundary(boundaryFiber, thenable) {
19234 // The boundary fiber (a Suspense component) previously timed out and was
19235 // rendered in its fallback state. One of the promises that suspended it has
19236 // resolved, which means at least part of the tree was likely unblocked. Try
19237 var retryCache = boundaryFiber.stateNode;
19238 if (retryCache !== null) {
19239 // The thenable resolved, so we no longer need to memoize, because it will
19240 // never be thrown again.
19241 retryCache.delete(thenable);
19242 }
19243
19244 var currentTime = requestCurrentTime();
19245 var retryTime = computeExpirationForFiber(currentTime, boundaryFiber);
19246 var root = scheduleWorkToRoot(boundaryFiber, retryTime);
19247 if (root !== null) {
19248 markPendingPriorityLevel(root, retryTime);
19249 var rootExpirationTime = root.expirationTime;
19250 if (rootExpirationTime !== NoWork) {
19251 requestWork(root, rootExpirationTime);
19252 }
19253 }
19254}
19255
19256function scheduleWorkToRoot(fiber, expirationTime) {
19257 recordScheduleUpdate();
19258
19259 {
19260 if (fiber.tag === ClassComponent) {
19261 var instance = fiber.stateNode;
19262 warnAboutInvalidUpdates(instance);
19263 }
19264 }
19265
19266 // Update the source fiber's expiration time
19267 if (fiber.expirationTime < expirationTime) {
19268 fiber.expirationTime = expirationTime;
19269 }
19270 var alternate = fiber.alternate;
19271 if (alternate !== null && alternate.expirationTime < expirationTime) {
19272 alternate.expirationTime = expirationTime;
19273 }
19274 // Walk the parent path to the root and update the child expiration time.
19275 var node = fiber.return;
19276 var root = null;
19277 if (node === null && fiber.tag === HostRoot) {
19278 root = fiber.stateNode;
19279 } else {
19280 while (node !== null) {
19281 alternate = node.alternate;
19282 if (node.childExpirationTime < expirationTime) {
19283 node.childExpirationTime = expirationTime;
19284 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
19285 alternate.childExpirationTime = expirationTime;
19286 }
19287 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
19288 alternate.childExpirationTime = expirationTime;
19289 }
19290 if (node.return === null && node.tag === HostRoot) {
19291 root = node.stateNode;
19292 break;
19293 }
19294 node = node.return;
19295 }
19296 }
19297
19298 if (enableSchedulerTracing) {
19299 if (root !== null) {
19300 var interactions = tracing.__interactionsRef.current;
19301 if (interactions.size > 0) {
19302 var pendingInteractionMap = root.pendingInteractionMap;
19303 var pendingInteractions = pendingInteractionMap.get(expirationTime);
19304 if (pendingInteractions != null) {
19305 interactions.forEach(function (interaction) {
19306 if (!pendingInteractions.has(interaction)) {
19307 // Update the pending async work count for previously unscheduled interaction.
19308 interaction.__count++;
19309 }
19310
19311 pendingInteractions.add(interaction);
19312 });
19313 } else {
19314 pendingInteractionMap.set(expirationTime, new Set(interactions));
19315
19316 // Update the pending async work count for the current interactions.
19317 interactions.forEach(function (interaction) {
19318 interaction.__count++;
19319 });
19320 }
19321
19322 var subscriber = tracing.__subscriberRef.current;
19323 if (subscriber !== null) {
19324 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
19325 subscriber.onWorkScheduled(interactions, threadID);
19326 }
19327 }
19328 }
19329 }
19330 return root;
19331}
19332
19333function warnIfNotCurrentlyBatchingInDev(fiber) {
19334 {
19335 if (isRendering === false && isBatchingUpdates === false) {
19336 warningWithoutStack$1(false, 'An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see in the browser." + ' Learn more at https://fb.me/react-wrap-tests-with-act', getComponentName(fiber.type));
19337 }
19338 }
19339}
19340
19341function scheduleWork(fiber, expirationTime) {
19342 var root = scheduleWorkToRoot(fiber, expirationTime);
19343 if (root === null) {
19344 {
19345 switch (fiber.tag) {
19346 case ClassComponent:
19347 warnAboutUpdateOnUnmounted(fiber, true);
19348 break;
19349 case FunctionComponent:
19350 case ForwardRef:
19351 case MemoComponent:
19352 case SimpleMemoComponent:
19353 warnAboutUpdateOnUnmounted(fiber, false);
19354 break;
19355 }
19356 }
19357 return;
19358 }
19359
19360 if (!isWorking && nextRenderExpirationTime !== NoWork && expirationTime > nextRenderExpirationTime) {
19361 // This is an interruption. (Used for performance tracking.)
19362 interruptedBy = fiber;
19363 resetStack();
19364 }
19365 markPendingPriorityLevel(root, expirationTime);
19366 if (
19367 // If we're in the render phase, we don't need to schedule this root
19368 // for an update, because we'll do it before we exit...
19369 !isWorking || isCommitting$1 ||
19370 // ...unless this is a different root than the one we're rendering.
19371 nextRoot !== root) {
19372 var rootExpirationTime = root.expirationTime;
19373 requestWork(root, rootExpirationTime);
19374 }
19375 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
19376 // Reset this back to zero so subsequent updates don't throw.
19377 nestedUpdateCount = 0;
19378 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.');
19379 }
19380}
19381
19382function syncUpdates(fn, a, b, c, d) {
19383 var previousExpirationContext = expirationContext;
19384 expirationContext = Sync;
19385 try {
19386 return fn(a, b, c, d);
19387 } finally {
19388 expirationContext = previousExpirationContext;
19389 }
19390}
19391
19392// TODO: Everything below this is written as if it has been lifted to the
19393// renderers. I'll do this in a follow-up.
19394
19395// Linked-list of roots
19396var firstScheduledRoot = null;
19397var lastScheduledRoot = null;
19398
19399var callbackExpirationTime = NoWork;
19400var callbackID = void 0;
19401var isRendering = false;
19402var nextFlushedRoot = null;
19403var nextFlushedExpirationTime = NoWork;
19404var lowestPriorityPendingInteractiveExpirationTime = NoWork;
19405var hasUnhandledError = false;
19406var unhandledError = null;
19407
19408var isBatchingUpdates = false;
19409var isUnbatchingUpdates = false;
19410var isBatchingInteractiveUpdates = false;
19411
19412var completedBatches = null;
19413
19414var originalStartTimeMs = scheduler.unstable_now();
19415var currentRendererTime = msToExpirationTime(originalStartTimeMs);
19416var currentSchedulerTime = currentRendererTime;
19417
19418// Use these to prevent an infinite loop of nested updates
19419var NESTED_UPDATE_LIMIT = 50;
19420var nestedUpdateCount = 0;
19421var lastCommittedRootDuringThisBatch = null;
19422
19423function recomputeCurrentRendererTime() {
19424 var currentTimeMs = scheduler.unstable_now() - originalStartTimeMs;
19425 currentRendererTime = msToExpirationTime(currentTimeMs);
19426}
19427
19428function scheduleCallbackWithExpirationTime(root, expirationTime) {
19429 if (callbackExpirationTime !== NoWork) {
19430 // A callback is already scheduled. Check its expiration time (timeout).
19431 if (expirationTime < callbackExpirationTime) {
19432 // Existing callback has sufficient timeout. Exit.
19433 return;
19434 } else {
19435 if (callbackID !== null) {
19436 // Existing callback has insufficient timeout. Cancel and schedule a
19437 // new one.
19438 scheduler.unstable_cancelCallback(callbackID);
19439 }
19440 }
19441 // The request callback timer is already running. Don't start a new one.
19442 } else {
19443 startRequestCallbackTimer();
19444 }
19445
19446 callbackExpirationTime = expirationTime;
19447 var currentMs = scheduler.unstable_now() - originalStartTimeMs;
19448 var expirationTimeMs = expirationTimeToMs(expirationTime);
19449 var timeout = expirationTimeMs - currentMs;
19450 callbackID = scheduler.unstable_scheduleCallback(performAsyncWork, { timeout: timeout });
19451}
19452
19453// For every call to renderRoot, one of onFatal, onComplete, onSuspend, and
19454// onYield is called upon exiting. We use these in lieu of returning a tuple.
19455// I've also chosen not to inline them into renderRoot because these will
19456// eventually be lifted into the renderer.
19457function onFatal(root) {
19458 root.finishedWork = null;
19459}
19460
19461function onComplete(root, finishedWork, expirationTime) {
19462 root.pendingCommitExpirationTime = expirationTime;
19463 root.finishedWork = finishedWork;
19464}
19465
19466function onSuspend(root, finishedWork, suspendedExpirationTime, rootExpirationTime, msUntilTimeout) {
19467 root.expirationTime = rootExpirationTime;
19468 if (msUntilTimeout === 0 && !shouldYieldToRenderer()) {
19469 // Don't wait an additional tick. Commit the tree immediately.
19470 root.pendingCommitExpirationTime = suspendedExpirationTime;
19471 root.finishedWork = finishedWork;
19472 } else if (msUntilTimeout > 0) {
19473 // Wait `msUntilTimeout` milliseconds before committing.
19474 root.timeoutHandle = scheduleTimeout(onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), msUntilTimeout);
19475 }
19476}
19477
19478function onYield(root) {
19479 root.finishedWork = null;
19480}
19481
19482function onTimeout(root, finishedWork, suspendedExpirationTime) {
19483 // The root timed out. Commit it.
19484 root.pendingCommitExpirationTime = suspendedExpirationTime;
19485 root.finishedWork = finishedWork;
19486 // Read the current time before entering the commit phase. We can be
19487 // certain this won't cause tearing related to batching of event updates
19488 // because we're at the top of a timer event.
19489 recomputeCurrentRendererTime();
19490 currentSchedulerTime = currentRendererTime;
19491 flushRoot(root, suspendedExpirationTime);
19492}
19493
19494function onCommit(root, expirationTime) {
19495 root.expirationTime = expirationTime;
19496 root.finishedWork = null;
19497}
19498
19499function requestCurrentTime() {
19500 // requestCurrentTime is called by the scheduler to compute an expiration
19501 // time.
19502 //
19503 // Expiration times are computed by adding to the current time (the start
19504 // time). However, if two updates are scheduled within the same event, we
19505 // should treat their start times as simultaneous, even if the actual clock
19506 // time has advanced between the first and second call.
19507
19508 // In other words, because expiration times determine how updates are batched,
19509 // we want all updates of like priority that occur within the same event to
19510 // receive the same expiration time. Otherwise we get tearing.
19511 //
19512 // We keep track of two separate times: the current "renderer" time and the
19513 // current "scheduler" time. The renderer time can be updated whenever; it
19514 // only exists to minimize the calls performance.now.
19515 //
19516 // But the scheduler time can only be updated if there's no pending work, or
19517 // if we know for certain that we're not in the middle of an event.
19518
19519 if (isRendering) {
19520 // We're already rendering. Return the most recently read time.
19521 return currentSchedulerTime;
19522 }
19523 // Check if there's pending work.
19524 findHighestPriorityRoot();
19525 if (nextFlushedExpirationTime === NoWork || nextFlushedExpirationTime === Never) {
19526 // If there's no pending work, or if the pending work is offscreen, we can
19527 // read the current time without risk of tearing.
19528 recomputeCurrentRendererTime();
19529 currentSchedulerTime = currentRendererTime;
19530 return currentSchedulerTime;
19531 }
19532 // There's already pending work. We might be in the middle of a browser
19533 // event. If we were to read the current time, it could cause multiple updates
19534 // within the same event to receive different expiration times, leading to
19535 // tearing. Return the last read time. During the next idle callback, the
19536 // time will be updated.
19537 return currentSchedulerTime;
19538}
19539
19540// requestWork is called by the scheduler whenever a root receives an update.
19541// It's up to the renderer to call renderRoot at some point in the future.
19542function requestWork(root, expirationTime) {
19543 addRootToSchedule(root, expirationTime);
19544 if (isRendering) {
19545 // Prevent reentrancy. Remaining work will be scheduled at the end of
19546 // the currently rendering batch.
19547 return;
19548 }
19549
19550 if (isBatchingUpdates) {
19551 // Flush work at the end of the batch.
19552 if (isUnbatchingUpdates) {
19553 // ...unless we're inside unbatchedUpdates, in which case we should
19554 // flush it now.
19555 nextFlushedRoot = root;
19556 nextFlushedExpirationTime = Sync;
19557 performWorkOnRoot(root, Sync, false);
19558 }
19559 return;
19560 }
19561
19562 // TODO: Get rid of Sync and use current time?
19563 if (expirationTime === Sync) {
19564 performSyncWork();
19565 } else {
19566 scheduleCallbackWithExpirationTime(root, expirationTime);
19567 }
19568}
19569
19570function addRootToSchedule(root, expirationTime) {
19571 // Add the root to the schedule.
19572 // Check if this root is already part of the schedule.
19573 if (root.nextScheduledRoot === null) {
19574 // This root is not already scheduled. Add it.
19575 root.expirationTime = expirationTime;
19576 if (lastScheduledRoot === null) {
19577 firstScheduledRoot = lastScheduledRoot = root;
19578 root.nextScheduledRoot = root;
19579 } else {
19580 lastScheduledRoot.nextScheduledRoot = root;
19581 lastScheduledRoot = root;
19582 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
19583 }
19584 } else {
19585 // This root is already scheduled, but its priority may have increased.
19586 var remainingExpirationTime = root.expirationTime;
19587 if (expirationTime > remainingExpirationTime) {
19588 // Update the priority.
19589 root.expirationTime = expirationTime;
19590 }
19591 }
19592}
19593
19594function findHighestPriorityRoot() {
19595 var highestPriorityWork = NoWork;
19596 var highestPriorityRoot = null;
19597 if (lastScheduledRoot !== null) {
19598 var previousScheduledRoot = lastScheduledRoot;
19599 var root = firstScheduledRoot;
19600 while (root !== null) {
19601 var remainingExpirationTime = root.expirationTime;
19602 if (remainingExpirationTime === NoWork) {
19603 // This root no longer has work. Remove it from the scheduler.
19604
19605 // TODO: This check is redudant, but Flow is confused by the branch
19606 // below where we set lastScheduledRoot to null, even though we break
19607 // from the loop right after.
19608 !(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;
19609 if (root === root.nextScheduledRoot) {
19610 // This is the only root in the list.
19611 root.nextScheduledRoot = null;
19612 firstScheduledRoot = lastScheduledRoot = null;
19613 break;
19614 } else if (root === firstScheduledRoot) {
19615 // This is the first root in the list.
19616 var next = root.nextScheduledRoot;
19617 firstScheduledRoot = next;
19618 lastScheduledRoot.nextScheduledRoot = next;
19619 root.nextScheduledRoot = null;
19620 } else if (root === lastScheduledRoot) {
19621 // This is the last root in the list.
19622 lastScheduledRoot = previousScheduledRoot;
19623 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
19624 root.nextScheduledRoot = null;
19625 break;
19626 } else {
19627 previousScheduledRoot.nextScheduledRoot = root.nextScheduledRoot;
19628 root.nextScheduledRoot = null;
19629 }
19630 root = previousScheduledRoot.nextScheduledRoot;
19631 } else {
19632 if (remainingExpirationTime > highestPriorityWork) {
19633 // Update the priority, if it's higher
19634 highestPriorityWork = remainingExpirationTime;
19635 highestPriorityRoot = root;
19636 }
19637 if (root === lastScheduledRoot) {
19638 break;
19639 }
19640 if (highestPriorityWork === Sync) {
19641 // Sync is highest priority by definition so
19642 // we can stop searching.
19643 break;
19644 }
19645 previousScheduledRoot = root;
19646 root = root.nextScheduledRoot;
19647 }
19648 }
19649 }
19650
19651 nextFlushedRoot = highestPriorityRoot;
19652 nextFlushedExpirationTime = highestPriorityWork;
19653}
19654
19655// TODO: This wrapper exists because many of the older tests (the ones that use
19656// flushDeferredPri) rely on the number of times `shouldYield` is called. We
19657// should get rid of it.
19658var didYield = false;
19659function shouldYieldToRenderer() {
19660 if (didYield) {
19661 return true;
19662 }
19663 if (scheduler.unstable_shouldYield()) {
19664 didYield = true;
19665 return true;
19666 }
19667 return false;
19668}
19669
19670function performAsyncWork() {
19671 try {
19672 if (!shouldYieldToRenderer()) {
19673 // The callback timed out. That means at least one update has expired.
19674 // Iterate through the root schedule. If they contain expired work, set
19675 // the next render expiration time to the current time. This has the effect
19676 // of flushing all expired work in a single batch, instead of flushing each
19677 // level one at a time.
19678 if (firstScheduledRoot !== null) {
19679 recomputeCurrentRendererTime();
19680 var root = firstScheduledRoot;
19681 do {
19682 didExpireAtExpirationTime(root, currentRendererTime);
19683 // The root schedule is circular, so this is never null.
19684 root = root.nextScheduledRoot;
19685 } while (root !== firstScheduledRoot);
19686 }
19687 }
19688 performWork(NoWork, true);
19689 } finally {
19690 didYield = false;
19691 }
19692}
19693
19694function performSyncWork() {
19695 performWork(Sync, false);
19696}
19697
19698function performWork(minExpirationTime, isYieldy) {
19699 // Keep working on roots until there's no more work, or until there's a higher
19700 // priority event.
19701 findHighestPriorityRoot();
19702
19703 if (isYieldy) {
19704 recomputeCurrentRendererTime();
19705 currentSchedulerTime = currentRendererTime;
19706
19707 if (enableUserTimingAPI) {
19708 var didExpire = nextFlushedExpirationTime > currentRendererTime;
19709 var timeout = expirationTimeToMs(nextFlushedExpirationTime);
19710 stopRequestCallbackTimer(didExpire, timeout);
19711 }
19712
19713 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime && !(didYield && currentRendererTime > nextFlushedExpirationTime)) {
19714 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, currentRendererTime > nextFlushedExpirationTime);
19715 findHighestPriorityRoot();
19716 recomputeCurrentRendererTime();
19717 currentSchedulerTime = currentRendererTime;
19718 }
19719 } else {
19720 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime) {
19721 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false);
19722 findHighestPriorityRoot();
19723 }
19724 }
19725
19726 // We're done flushing work. Either we ran out of time in this callback,
19727 // or there's no more work left with sufficient priority.
19728
19729 // If we're inside a callback, set this to false since we just completed it.
19730 if (isYieldy) {
19731 callbackExpirationTime = NoWork;
19732 callbackID = null;
19733 }
19734 // If there's work left over, schedule a new callback.
19735 if (nextFlushedExpirationTime !== NoWork) {
19736 scheduleCallbackWithExpirationTime(nextFlushedRoot, nextFlushedExpirationTime);
19737 }
19738
19739 // Clean-up.
19740 finishRendering();
19741}
19742
19743function flushRoot(root, expirationTime) {
19744 !!isRendering ? invariant(false, 'work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.') : void 0;
19745 // Perform work on root as if the given expiration time is the current time.
19746 // This has the effect of synchronously flushing all work up to and
19747 // including the given time.
19748 nextFlushedRoot = root;
19749 nextFlushedExpirationTime = expirationTime;
19750 performWorkOnRoot(root, expirationTime, false);
19751 // Flush any sync work that was scheduled by lifecycles
19752 performSyncWork();
19753}
19754
19755function finishRendering() {
19756 nestedUpdateCount = 0;
19757 lastCommittedRootDuringThisBatch = null;
19758
19759 if (completedBatches !== null) {
19760 var batches = completedBatches;
19761 completedBatches = null;
19762 for (var i = 0; i < batches.length; i++) {
19763 var batch = batches[i];
19764 try {
19765 batch._onComplete();
19766 } catch (error) {
19767 if (!hasUnhandledError) {
19768 hasUnhandledError = true;
19769 unhandledError = error;
19770 }
19771 }
19772 }
19773 }
19774
19775 if (hasUnhandledError) {
19776 var error = unhandledError;
19777 unhandledError = null;
19778 hasUnhandledError = false;
19779 throw error;
19780 }
19781}
19782
19783function performWorkOnRoot(root, expirationTime, isYieldy) {
19784 !!isRendering ? invariant(false, 'performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;
19785
19786 isRendering = true;
19787
19788 // Check if this is async work or sync/expired work.
19789 if (!isYieldy) {
19790 // Flush work without yielding.
19791 // TODO: Non-yieldy work does not necessarily imply expired work. A renderer
19792 // may want to perform some work without yielding, but also without
19793 // requiring the root to complete (by triggering placeholders).
19794
19795 var finishedWork = root.finishedWork;
19796 if (finishedWork !== null) {
19797 // This root is already complete. We can commit it.
19798 completeRoot(root, finishedWork, expirationTime);
19799 } else {
19800 root.finishedWork = null;
19801 // If this root previously suspended, clear its existing timeout, since
19802 // we're about to try rendering again.
19803 var timeoutHandle = root.timeoutHandle;
19804 if (timeoutHandle !== noTimeout) {
19805 root.timeoutHandle = noTimeout;
19806 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
19807 cancelTimeout(timeoutHandle);
19808 }
19809 renderRoot(root, isYieldy);
19810 finishedWork = root.finishedWork;
19811 if (finishedWork !== null) {
19812 // We've completed the root. Commit it.
19813 completeRoot(root, finishedWork, expirationTime);
19814 }
19815 }
19816 } else {
19817 // Flush async work.
19818 var _finishedWork = root.finishedWork;
19819 if (_finishedWork !== null) {
19820 // This root is already complete. We can commit it.
19821 completeRoot(root, _finishedWork, expirationTime);
19822 } else {
19823 root.finishedWork = null;
19824 // If this root previously suspended, clear its existing timeout, since
19825 // we're about to try rendering again.
19826 var _timeoutHandle = root.timeoutHandle;
19827 if (_timeoutHandle !== noTimeout) {
19828 root.timeoutHandle = noTimeout;
19829 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
19830 cancelTimeout(_timeoutHandle);
19831 }
19832 renderRoot(root, isYieldy);
19833 _finishedWork = root.finishedWork;
19834 if (_finishedWork !== null) {
19835 // We've completed the root. Check the if we should yield one more time
19836 // before committing.
19837 if (!shouldYieldToRenderer()) {
19838 // Still time left. Commit the root.
19839 completeRoot(root, _finishedWork, expirationTime);
19840 } else {
19841 // There's no time left. Mark this root as complete. We'll come
19842 // back and commit it later.
19843 root.finishedWork = _finishedWork;
19844 }
19845 }
19846 }
19847 }
19848
19849 isRendering = false;
19850}
19851
19852function completeRoot(root, finishedWork, expirationTime) {
19853 // Check if there's a batch that matches this expiration time.
19854 var firstBatch = root.firstBatch;
19855 if (firstBatch !== null && firstBatch._expirationTime >= expirationTime) {
19856 if (completedBatches === null) {
19857 completedBatches = [firstBatch];
19858 } else {
19859 completedBatches.push(firstBatch);
19860 }
19861 if (firstBatch._defer) {
19862 // This root is blocked from committing by a batch. Unschedule it until
19863 // we receive another update.
19864 root.finishedWork = finishedWork;
19865 root.expirationTime = NoWork;
19866 return;
19867 }
19868 }
19869
19870 // Commit the root.
19871 root.finishedWork = null;
19872
19873 // Check if this is a nested update (a sync update scheduled during the
19874 // commit phase).
19875 if (root === lastCommittedRootDuringThisBatch) {
19876 // If the next root is the same as the previous root, this is a nested
19877 // update. To prevent an infinite loop, increment the nested update count.
19878 nestedUpdateCount++;
19879 } else {
19880 // Reset whenever we switch roots.
19881 lastCommittedRootDuringThisBatch = root;
19882 nestedUpdateCount = 0;
19883 }
19884 commitRoot(root, finishedWork);
19885}
19886
19887function onUncaughtError(error) {
19888 !(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;
19889 // Unschedule this root so we don't work on it again until there's
19890 // another update.
19891 nextFlushedRoot.expirationTime = NoWork;
19892 if (!hasUnhandledError) {
19893 hasUnhandledError = true;
19894 unhandledError = error;
19895 }
19896}
19897
19898// TODO: Batching should be implemented at the renderer level, not inside
19899// the reconciler.
19900function batchedUpdates$1(fn, a) {
19901 var previousIsBatchingUpdates = isBatchingUpdates;
19902 isBatchingUpdates = true;
19903 try {
19904 return fn(a);
19905 } finally {
19906 isBatchingUpdates = previousIsBatchingUpdates;
19907 if (!isBatchingUpdates && !isRendering) {
19908 performSyncWork();
19909 }
19910 }
19911}
19912
19913// TODO: Batching should be implemented at the renderer level, not inside
19914// the reconciler.
19915function unbatchedUpdates(fn, a) {
19916 if (isBatchingUpdates && !isUnbatchingUpdates) {
19917 isUnbatchingUpdates = true;
19918 try {
19919 return fn(a);
19920 } finally {
19921 isUnbatchingUpdates = false;
19922 }
19923 }
19924 return fn(a);
19925}
19926
19927// TODO: Batching should be implemented at the renderer level, not within
19928// the reconciler.
19929function flushSync(fn, a) {
19930 !!isRendering ? invariant(false, 'flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.') : void 0;
19931 var previousIsBatchingUpdates = isBatchingUpdates;
19932 isBatchingUpdates = true;
19933 try {
19934 return syncUpdates(fn, a);
19935 } finally {
19936 isBatchingUpdates = previousIsBatchingUpdates;
19937 performSyncWork();
19938 }
19939}
19940
19941function interactiveUpdates$1(fn, a, b) {
19942 if (isBatchingInteractiveUpdates) {
19943 return fn(a, b);
19944 }
19945 // If there are any pending interactive updates, synchronously flush them.
19946 // This needs to happen before we read any handlers, because the effect of
19947 // the previous event may influence which handlers are called during
19948 // this event.
19949 if (!isBatchingUpdates && !isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) {
19950 // Synchronously flush pending interactive updates.
19951 performWork(lowestPriorityPendingInteractiveExpirationTime, false);
19952 lowestPriorityPendingInteractiveExpirationTime = NoWork;
19953 }
19954 var previousIsBatchingInteractiveUpdates = isBatchingInteractiveUpdates;
19955 var previousIsBatchingUpdates = isBatchingUpdates;
19956 isBatchingInteractiveUpdates = true;
19957 isBatchingUpdates = true;
19958 try {
19959 return fn(a, b);
19960 } finally {
19961 isBatchingInteractiveUpdates = previousIsBatchingInteractiveUpdates;
19962 isBatchingUpdates = previousIsBatchingUpdates;
19963 if (!isBatchingUpdates && !isRendering) {
19964 performSyncWork();
19965 }
19966 }
19967}
19968
19969function flushInteractiveUpdates$1() {
19970 if (!isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) {
19971 // Synchronously flush pending interactive updates.
19972 performWork(lowestPriorityPendingInteractiveExpirationTime, false);
19973 lowestPriorityPendingInteractiveExpirationTime = NoWork;
19974 }
19975}
19976
19977function flushControlled(fn) {
19978 var previousIsBatchingUpdates = isBatchingUpdates;
19979 isBatchingUpdates = true;
19980 try {
19981 syncUpdates(fn);
19982 } finally {
19983 isBatchingUpdates = previousIsBatchingUpdates;
19984 if (!isBatchingUpdates && !isRendering) {
19985 performSyncWork();
19986 }
19987 }
19988}
19989
19990// 0 is PROD, 1 is DEV.
19991// Might add PROFILE later.
19992
19993
19994var didWarnAboutNestedUpdates = void 0;
19995var didWarnAboutFindNodeInStrictMode = void 0;
19996
19997{
19998 didWarnAboutNestedUpdates = false;
19999 didWarnAboutFindNodeInStrictMode = {};
20000}
20001
20002function getContextForSubtree(parentComponent) {
20003 if (!parentComponent) {
20004 return emptyContextObject;
20005 }
20006
20007 var fiber = get(parentComponent);
20008 var parentContext = findCurrentUnmaskedContext(fiber);
20009
20010 if (fiber.tag === ClassComponent) {
20011 var Component = fiber.type;
20012 if (isContextProvider(Component)) {
20013 return processChildContext(fiber, Component, parentContext);
20014 }
20015 }
20016
20017 return parentContext;
20018}
20019
20020function scheduleRootUpdate(current$$1, element, expirationTime, callback) {
20021 {
20022 if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) {
20023 didWarnAboutNestedUpdates = true;
20024 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');
20025 }
20026 }
20027
20028 var update = createUpdate(expirationTime);
20029 // Caution: React DevTools currently depends on this property
20030 // being called "element".
20031 update.payload = { element: element };
20032
20033 callback = callback === undefined ? null : callback;
20034 if (callback !== null) {
20035 !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
20036 update.callback = callback;
20037 }
20038
20039 flushPassiveEffects();
20040 enqueueUpdate(current$$1, update);
20041 scheduleWork(current$$1, expirationTime);
20042
20043 return expirationTime;
20044}
20045
20046function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback) {
20047 // TODO: If this is a nested container, this won't be the root.
20048 var current$$1 = container.current;
20049
20050 {
20051 if (ReactFiberInstrumentation_1.debugTool) {
20052 if (current$$1.alternate === null) {
20053 ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
20054 } else if (element === null) {
20055 ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
20056 } else {
20057 ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
20058 }
20059 }
20060 }
20061
20062 var context = getContextForSubtree(parentComponent);
20063 if (container.context === null) {
20064 container.context = context;
20065 } else {
20066 container.pendingContext = context;
20067 }
20068
20069 return scheduleRootUpdate(current$$1, element, expirationTime, callback);
20070}
20071
20072function findHostInstance(component) {
20073 var fiber = get(component);
20074 if (fiber === undefined) {
20075 if (typeof component.render === 'function') {
20076 invariant(false, 'Unable to find node on an unmounted component.');
20077 } else {
20078 invariant(false, 'Argument appears to not be a ReactComponent. Keys: %s', Object.keys(component));
20079 }
20080 }
20081 var hostFiber = findCurrentHostFiber(fiber);
20082 if (hostFiber === null) {
20083 return null;
20084 }
20085 return hostFiber.stateNode;
20086}
20087
20088function findHostInstanceWithWarning(component, methodName) {
20089 {
20090 var fiber = get(component);
20091 if (fiber === undefined) {
20092 if (typeof component.render === 'function') {
20093 invariant(false, 'Unable to find node on an unmounted component.');
20094 } else {
20095 invariant(false, 'Argument appears to not be a ReactComponent. Keys: %s', Object.keys(component));
20096 }
20097 }
20098 var hostFiber = findCurrentHostFiber(fiber);
20099 if (hostFiber === null) {
20100 return null;
20101 }
20102 if (hostFiber.mode & StrictMode) {
20103 var componentName = getComponentName(fiber.type) || 'Component';
20104 if (!didWarnAboutFindNodeInStrictMode[componentName]) {
20105 didWarnAboutFindNodeInStrictMode[componentName] = true;
20106 if (fiber.mode & StrictMode) {
20107 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));
20108 } else {
20109 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));
20110 }
20111 }
20112 }
20113 return hostFiber.stateNode;
20114 }
20115 return findHostInstance(component);
20116}
20117
20118function createContainer(containerInfo, isConcurrent, hydrate) {
20119 return createFiberRoot(containerInfo, isConcurrent, hydrate);
20120}
20121
20122function updateContainer(element, container, parentComponent, callback) {
20123 var current$$1 = container.current;
20124 var currentTime = requestCurrentTime();
20125 var expirationTime = computeExpirationForFiber(currentTime, current$$1);
20126 return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback);
20127}
20128
20129function getPublicRootInstance(container) {
20130 var containerFiber = container.current;
20131 if (!containerFiber.child) {
20132 return null;
20133 }
20134 switch (containerFiber.child.tag) {
20135 case HostComponent:
20136 return getPublicInstance(containerFiber.child.stateNode);
20137 default:
20138 return containerFiber.child.stateNode;
20139 }
20140}
20141
20142function findHostInstanceWithNoPortals(fiber) {
20143 var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
20144 if (hostFiber === null) {
20145 return null;
20146 }
20147 return hostFiber.stateNode;
20148}
20149
20150var overrideProps = null;
20151
20152{
20153 var copyWithSetImpl = function (obj, path, idx, value) {
20154 if (idx >= path.length) {
20155 return value;
20156 }
20157 var key = path[idx];
20158 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
20159 // $FlowFixMe number or string is fine here
20160 updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
20161 return updated;
20162 };
20163
20164 var copyWithSet = function (obj, path, value) {
20165 return copyWithSetImpl(obj, path, 0, value);
20166 };
20167
20168 // Support DevTools props for function components, forwardRef, memo, host components, etc.
20169 overrideProps = function (fiber, path, value) {
20170 flushPassiveEffects();
20171 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
20172 if (fiber.alternate) {
20173 fiber.alternate.pendingProps = fiber.pendingProps;
20174 }
20175 scheduleWork(fiber, Sync);
20176 };
20177}
20178
20179function injectIntoDevTools(devToolsConfig) {
20180 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
20181 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
20182
20183
20184 return injectInternals(_assign({}, devToolsConfig, {
20185 overrideProps: overrideProps,
20186 currentDispatcherRef: ReactCurrentDispatcher,
20187 findHostInstanceByFiber: function (fiber) {
20188 var hostFiber = findCurrentHostFiber(fiber);
20189 if (hostFiber === null) {
20190 return null;
20191 }
20192 return hostFiber.stateNode;
20193 },
20194 findFiberByHostInstance: function (instance) {
20195 if (!findFiberByHostInstance) {
20196 // Might not be implemented by the renderer.
20197 return null;
20198 }
20199 return findFiberByHostInstance(instance);
20200 }
20201 }));
20202}
20203
20204// This file intentionally does *not* have the Flow annotation.
20205// Don't add it. See `./inline-typed.js` for an explanation.
20206
20207function createPortal$1(children, containerInfo,
20208// TODO: figure out the API for cross-renderer implementation.
20209implementation) {
20210 var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
20211
20212 return {
20213 // This tag allow us to uniquely identify this as a React Portal
20214 $$typeof: REACT_PORTAL_TYPE,
20215 key: key == null ? null : '' + key,
20216 children: children,
20217 containerInfo: containerInfo,
20218 implementation: implementation
20219 };
20220}
20221
20222// TODO: this is special because it gets imported during build.
20223
20224var ReactVersion = '16.8.1';
20225
20226// TODO: This type is shared between the reconciler and ReactDOM, but will
20227// eventually be lifted out to the renderer.
20228
20229var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
20230
20231var topLevelUpdateWarnings = void 0;
20232var warnOnInvalidCallback = void 0;
20233var didWarnAboutUnstableCreatePortal = false;
20234
20235{
20236 if (typeof Map !== 'function' ||
20237 // $FlowIssue Flow incorrectly thinks Map has no prototype
20238 Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' ||
20239 // $FlowIssue Flow incorrectly thinks Set has no prototype
20240 Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
20241 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');
20242 }
20243
20244 topLevelUpdateWarnings = function (container) {
20245 if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
20246 var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
20247 if (hostInstance) {
20248 !(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;
20249 }
20250 }
20251
20252 var isRootRenderedBySomeReact = !!container._reactRootContainer;
20253 var rootEl = getReactRootElementInContainer(container);
20254 var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));
20255
20256 !(!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;
20257
20258 !(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;
20259 };
20260
20261 warnOnInvalidCallback = function (callback, callerName) {
20262 !(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;
20263 };
20264}
20265
20266setRestoreImplementation(restoreControlledState$1);
20267
20268function ReactBatch(root) {
20269 var expirationTime = computeUniqueAsyncExpiration();
20270 this._expirationTime = expirationTime;
20271 this._root = root;
20272 this._next = null;
20273 this._callbacks = null;
20274 this._didComplete = false;
20275 this._hasChildren = false;
20276 this._children = null;
20277 this._defer = true;
20278}
20279ReactBatch.prototype.render = function (children) {
20280 !this._defer ? invariant(false, 'batch.render: Cannot render a batch that already committed.') : void 0;
20281 this._hasChildren = true;
20282 this._children = children;
20283 var internalRoot = this._root._internalRoot;
20284 var expirationTime = this._expirationTime;
20285 var work = new ReactWork();
20286 updateContainerAtExpirationTime(children, internalRoot, null, expirationTime, work._onCommit);
20287 return work;
20288};
20289ReactBatch.prototype.then = function (onComplete) {
20290 if (this._didComplete) {
20291 onComplete();
20292 return;
20293 }
20294 var callbacks = this._callbacks;
20295 if (callbacks === null) {
20296 callbacks = this._callbacks = [];
20297 }
20298 callbacks.push(onComplete);
20299};
20300ReactBatch.prototype.commit = function () {
20301 var internalRoot = this._root._internalRoot;
20302 var firstBatch = internalRoot.firstBatch;
20303 !(this._defer && firstBatch !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0;
20304
20305 if (!this._hasChildren) {
20306 // This batch is empty. Return.
20307 this._next = null;
20308 this._defer = false;
20309 return;
20310 }
20311
20312 var expirationTime = this._expirationTime;
20313
20314 // Ensure this is the first batch in the list.
20315 if (firstBatch !== this) {
20316 // This batch is not the earliest batch. We need to move it to the front.
20317 // Update its expiration time to be the expiration time of the earliest
20318 // batch, so that we can flush it without flushing the other batches.
20319 if (this._hasChildren) {
20320 expirationTime = this._expirationTime = firstBatch._expirationTime;
20321 // Rendering this batch again ensures its children will be the final state
20322 // when we flush (updates are processed in insertion order: last
20323 // update wins).
20324 // TODO: This forces a restart. Should we print a warning?
20325 this.render(this._children);
20326 }
20327
20328 // Remove the batch from the list.
20329 var previous = null;
20330 var batch = firstBatch;
20331 while (batch !== this) {
20332 previous = batch;
20333 batch = batch._next;
20334 }
20335 !(previous !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0;
20336 previous._next = batch._next;
20337
20338 // Add it to the front.
20339 this._next = firstBatch;
20340 firstBatch = internalRoot.firstBatch = this;
20341 }
20342
20343 // Synchronously flush all the work up to this batch's expiration time.
20344 this._defer = false;
20345 flushRoot(internalRoot, expirationTime);
20346
20347 // Pop the batch from the list.
20348 var next = this._next;
20349 this._next = null;
20350 firstBatch = internalRoot.firstBatch = next;
20351
20352 // Append the next earliest batch's children to the update queue.
20353 if (firstBatch !== null && firstBatch._hasChildren) {
20354 firstBatch.render(firstBatch._children);
20355 }
20356};
20357ReactBatch.prototype._onComplete = function () {
20358 if (this._didComplete) {
20359 return;
20360 }
20361 this._didComplete = true;
20362 var callbacks = this._callbacks;
20363 if (callbacks === null) {
20364 return;
20365 }
20366 // TODO: Error handling.
20367 for (var i = 0; i < callbacks.length; i++) {
20368 var _callback = callbacks[i];
20369 _callback();
20370 }
20371};
20372
20373function ReactWork() {
20374 this._callbacks = null;
20375 this._didCommit = false;
20376 // TODO: Avoid need to bind by replacing callbacks in the update queue with
20377 // list of Work objects.
20378 this._onCommit = this._onCommit.bind(this);
20379}
20380ReactWork.prototype.then = function (onCommit) {
20381 if (this._didCommit) {
20382 onCommit();
20383 return;
20384 }
20385 var callbacks = this._callbacks;
20386 if (callbacks === null) {
20387 callbacks = this._callbacks = [];
20388 }
20389 callbacks.push(onCommit);
20390};
20391ReactWork.prototype._onCommit = function () {
20392 if (this._didCommit) {
20393 return;
20394 }
20395 this._didCommit = true;
20396 var callbacks = this._callbacks;
20397 if (callbacks === null) {
20398 return;
20399 }
20400 // TODO: Error handling.
20401 for (var i = 0; i < callbacks.length; i++) {
20402 var _callback2 = callbacks[i];
20403 !(typeof _callback2 === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', _callback2) : void 0;
20404 _callback2();
20405 }
20406};
20407
20408function ReactRoot(container, isConcurrent, hydrate) {
20409 var root = createContainer(container, isConcurrent, hydrate);
20410 this._internalRoot = root;
20411}
20412ReactRoot.prototype.render = function (children, callback) {
20413 var root = this._internalRoot;
20414 var work = new ReactWork();
20415 callback = callback === undefined ? null : callback;
20416 {
20417 warnOnInvalidCallback(callback, 'render');
20418 }
20419 if (callback !== null) {
20420 work.then(callback);
20421 }
20422 updateContainer(children, root, null, work._onCommit);
20423 return work;
20424};
20425ReactRoot.prototype.unmount = function (callback) {
20426 var root = this._internalRoot;
20427 var work = new ReactWork();
20428 callback = callback === undefined ? null : callback;
20429 {
20430 warnOnInvalidCallback(callback, 'render');
20431 }
20432 if (callback !== null) {
20433 work.then(callback);
20434 }
20435 updateContainer(null, root, null, work._onCommit);
20436 return work;
20437};
20438ReactRoot.prototype.legacy_renderSubtreeIntoContainer = function (parentComponent, children, callback) {
20439 var root = this._internalRoot;
20440 var work = new ReactWork();
20441 callback = callback === undefined ? null : callback;
20442 {
20443 warnOnInvalidCallback(callback, 'render');
20444 }
20445 if (callback !== null) {
20446 work.then(callback);
20447 }
20448 updateContainer(children, root, parentComponent, work._onCommit);
20449 return work;
20450};
20451ReactRoot.prototype.createBatch = function () {
20452 var batch = new ReactBatch(this);
20453 var expirationTime = batch._expirationTime;
20454
20455 var internalRoot = this._internalRoot;
20456 var firstBatch = internalRoot.firstBatch;
20457 if (firstBatch === null) {
20458 internalRoot.firstBatch = batch;
20459 batch._next = null;
20460 } else {
20461 // Insert sorted by expiration time then insertion order
20462 var insertAfter = null;
20463 var insertBefore = firstBatch;
20464 while (insertBefore !== null && insertBefore._expirationTime >= expirationTime) {
20465 insertAfter = insertBefore;
20466 insertBefore = insertBefore._next;
20467 }
20468 batch._next = insertBefore;
20469 if (insertAfter !== null) {
20470 insertAfter._next = batch;
20471 }
20472 }
20473
20474 return batch;
20475};
20476
20477/**
20478 * True if the supplied DOM node is a valid node element.
20479 *
20480 * @param {?DOMElement} node The candidate DOM node.
20481 * @return {boolean} True if the DOM is a valid DOM node.
20482 * @internal
20483 */
20484function isValidContainer(node) {
20485 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 '));
20486}
20487
20488function getReactRootElementInContainer(container) {
20489 if (!container) {
20490 return null;
20491 }
20492
20493 if (container.nodeType === DOCUMENT_NODE) {
20494 return container.documentElement;
20495 } else {
20496 return container.firstChild;
20497 }
20498}
20499
20500function shouldHydrateDueToLegacyHeuristic(container) {
20501 var rootElement = getReactRootElementInContainer(container);
20502 return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
20503}
20504
20505setBatchingImplementation(batchedUpdates$1, interactiveUpdates$1, flushInteractiveUpdates$1);
20506
20507var warnedAboutHydrateAPI = false;
20508
20509function legacyCreateRootFromDOMContainer(container, forceHydrate) {
20510 var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container);
20511 // First clear any existing content.
20512 if (!shouldHydrate) {
20513 var warned = false;
20514 var rootSibling = void 0;
20515 while (rootSibling = container.lastChild) {
20516 {
20517 if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
20518 warned = true;
20519 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.');
20520 }
20521 }
20522 container.removeChild(rootSibling);
20523 }
20524 }
20525 {
20526 if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
20527 warnedAboutHydrateAPI = true;
20528 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.');
20529 }
20530 }
20531 // Legacy roots are not async by default.
20532 var isConcurrent = false;
20533 return new ReactRoot(container, isConcurrent, shouldHydrate);
20534}
20535
20536function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
20537 {
20538 topLevelUpdateWarnings(container);
20539 }
20540
20541 // TODO: Without `any` type, Flow says "Property cannot be accessed on any
20542 // member of intersection type." Whyyyyyy.
20543 var root = container._reactRootContainer;
20544 if (!root) {
20545 // Initial mount
20546 root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
20547 if (typeof callback === 'function') {
20548 var originalCallback = callback;
20549 callback = function () {
20550 var instance = getPublicRootInstance(root._internalRoot);
20551 originalCallback.call(instance);
20552 };
20553 }
20554 // Initial mount should not be batched.
20555 unbatchedUpdates(function () {
20556 if (parentComponent != null) {
20557 root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
20558 } else {
20559 root.render(children, callback);
20560 }
20561 });
20562 } else {
20563 if (typeof callback === 'function') {
20564 var _originalCallback = callback;
20565 callback = function () {
20566 var instance = getPublicRootInstance(root._internalRoot);
20567 _originalCallback.call(instance);
20568 };
20569 }
20570 // Update
20571 if (parentComponent != null) {
20572 root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
20573 } else {
20574 root.render(children, callback);
20575 }
20576 }
20577 return getPublicRootInstance(root._internalRoot);
20578}
20579
20580function createPortal$$1(children, container) {
20581 var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
20582
20583 !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;
20584 // TODO: pass ReactDOM portal implementation as third argument
20585 return createPortal$1(children, container, null, key);
20586}
20587
20588var ReactDOM = {
20589 createPortal: createPortal$$1,
20590
20591 findDOMNode: function (componentOrElement) {
20592 {
20593 var owner = ReactCurrentOwner.current;
20594 if (owner !== null && owner.stateNode !== null) {
20595 var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
20596 !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;
20597 owner.stateNode._warnedAboutRefsInRender = true;
20598 }
20599 }
20600 if (componentOrElement == null) {
20601 return null;
20602 }
20603 if (componentOrElement.nodeType === ELEMENT_NODE) {
20604 return componentOrElement;
20605 }
20606 {
20607 return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
20608 }
20609 return findHostInstance(componentOrElement);
20610 },
20611 hydrate: function (element, container, callback) {
20612 !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;
20613 {
20614 !!container._reactHasBeenPassedToCreateRootDEV ? warningWithoutStack$1(false, 'You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOM.%s(). This is not supported. ' + 'Did you mean to call root.render(element, {hydrate: true})?', enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot') : void 0;
20615 }
20616 // TODO: throw or warn if we couldn't hydrate?
20617 return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
20618 },
20619 render: function (element, container, callback) {
20620 !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0;
20621 {
20622 !!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;
20623 }
20624 return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
20625 },
20626 unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) {
20627 !isValidContainer(containerNode) ? invariant(false, 'Target container is not a DOM element.') : void 0;
20628 !(parentComponent != null && has(parentComponent)) ? invariant(false, 'parentComponent must be a valid React Component') : void 0;
20629 return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
20630 },
20631 unmountComponentAtNode: function (container) {
20632 !isValidContainer(container) ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : void 0;
20633
20634 {
20635 !!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;
20636 }
20637
20638 if (container._reactRootContainer) {
20639 {
20640 var rootEl = getReactRootElementInContainer(container);
20641 var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);
20642 !!renderedByDifferentReact ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0;
20643 }
20644
20645 // Unmount should not be batched.
20646 unbatchedUpdates(function () {
20647 legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
20648 container._reactRootContainer = null;
20649 });
20650 });
20651 // If you call unmountComponentAtNode twice in quick succession, you'll
20652 // get `true` twice. That's probably fine?
20653 return true;
20654 } else {
20655 {
20656 var _rootEl = getReactRootElementInContainer(container);
20657 var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl));
20658
20659 // Check if the container itself is a React root node.
20660 var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;
20661
20662 !!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;
20663 }
20664
20665 return false;
20666 }
20667 },
20668
20669
20670 // Temporary alias since we already shipped React 16 RC with it.
20671 // TODO: remove in React 17.
20672 unstable_createPortal: function () {
20673 if (!didWarnAboutUnstableCreatePortal) {
20674 didWarnAboutUnstableCreatePortal = true;
20675 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.');
20676 }
20677 return createPortal$$1.apply(undefined, arguments);
20678 },
20679
20680
20681 unstable_batchedUpdates: batchedUpdates$1,
20682
20683 unstable_interactiveUpdates: interactiveUpdates$1,
20684
20685 flushSync: flushSync,
20686
20687 unstable_createRoot: createRoot,
20688 unstable_flushControlled: flushControlled,
20689
20690 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
20691 // Keep in sync with ReactDOMUnstableNativeDependencies.js
20692 // and ReactTestUtils.js. This is an array for better minification.
20693 Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injection.injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch]
20694 }
20695};
20696
20697function createRoot(container, options) {
20698 var functionName = enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot';
20699 !isValidContainer(container) ? invariant(false, '%s(...): Target container is not a DOM element.', functionName) : void 0;
20700 {
20701 !!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;
20702 container._reactHasBeenPassedToCreateRootDEV = true;
20703 }
20704 var hydrate = options != null && options.hydrate === true;
20705 return new ReactRoot(container, true, hydrate);
20706}
20707
20708if (enableStableConcurrentModeAPIs) {
20709 ReactDOM.createRoot = createRoot;
20710 ReactDOM.unstable_createRoot = undefined;
20711}
20712
20713var foundDevTools = injectIntoDevTools({
20714 findFiberByHostInstance: getClosestInstanceFromNode,
20715 bundleType: 1,
20716 version: ReactVersion,
20717 rendererPackageName: 'react-dom'
20718});
20719
20720{
20721 if (!foundDevTools && canUseDOM && window.top === window.self) {
20722 // If we're in Chrome or Firefox, provide a download link if not installed.
20723 if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
20724 var protocol = window.location.protocol;
20725 // Don't warn in exotic cases like chrome-extension://.
20726 if (/^(https?|file):$/.test(protocol)) {
20727 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');
20728 }
20729 }
20730 }
20731}
20732
20733
20734
20735var ReactDOM$2 = Object.freeze({
20736 default: ReactDOM
20737});
20738
20739var ReactDOM$3 = ( ReactDOM$2 && ReactDOM ) || ReactDOM$2;
20740
20741// TODO: decide on the top-level export form.
20742// This is hacky but makes it work with both Rollup and Jest.
20743var reactDom = ReactDOM$3.default || ReactDOM$3;
20744
20745module.exports = reactDom;
20746 })();
20747}