UNPKG

907 kBJavaScriptView Raw
1/** @license React v16.9.0-alpha.0
2 * react-dom.development.js
3 *
4 * Copyright (c) Facebook, Inc. and its affiliates.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE file in the root directory of this source tree.
8 */
9
10'use strict';
11
12(function (global, factory) {
13 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) :
14 typeof define === 'function' && define.amd ? define(['react'], factory) :
15 (global.ReactDOM = factory(global.React));
16}(this, (function (React) { 'use strict';
17
18// Do not require this module directly! Use a normal error constructor with
19// template literal strings. The messages will be converted to ReactError during
20// build, and in production they will be minified.
21
22// Do not require this module directly! Use a normal error constructor with
23// template literal strings. The messages will be converted to ReactError during
24// build, and in production they will be minified.
25
26function ReactError(message) {
27 var error = new Error(message);
28 error.name = 'Invariant Violation';
29 return error;
30}
31
32/**
33 * Use invariant() to assert state which your program assumes to be true.
34 *
35 * Provide sprintf-style format (only %s is supported) and arguments
36 * to provide information about what broke and what you were
37 * expecting.
38 *
39 * The invariant message will be stripped in production, but the invariant
40 * will remain to ensure logic does not differ in production.
41 */
42
43(function () {
44 if (!React) {
45 {
46 throw ReactError('ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.');
47 }
48 }
49})();
50
51/**
52 * Injectable ordering of event plugins.
53 */
54var eventPluginOrder = null;
55
56/**
57 * Injectable mapping from names to event plugin modules.
58 */
59var namesToPlugins = {};
60
61/**
62 * Recomputes the plugin list using the injected plugins and plugin ordering.
63 *
64 * @private
65 */
66function recomputePluginOrdering() {
67 if (!eventPluginOrder) {
68 // Wait until an `eventPluginOrder` is injected.
69 return;
70 }
71 for (var pluginName in namesToPlugins) {
72 var pluginModule = namesToPlugins[pluginName];
73 var pluginIndex = eventPluginOrder.indexOf(pluginName);
74 (function () {
75 if (!(pluginIndex > -1)) {
76 {
77 throw ReactError('EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `' + pluginName + '`.');
78 }
79 }
80 })();
81 if (plugins[pluginIndex]) {
82 continue;
83 }
84 (function () {
85 if (!pluginModule.extractEvents) {
86 {
87 throw ReactError('EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `' + pluginName + '` does not.');
88 }
89 }
90 })();
91 plugins[pluginIndex] = pluginModule;
92 var publishedEvents = pluginModule.eventTypes;
93 for (var eventName in publishedEvents) {
94 (function () {
95 if (!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName)) {
96 {
97 throw ReactError('EventPluginRegistry: Failed to publish event `' + eventName + '` for plugin `' + pluginName + '`.');
98 }
99 }
100 })();
101 }
102 }
103}
104
105/**
106 * Publishes an event so that it can be dispatched by the supplied plugin.
107 *
108 * @param {object} dispatchConfig Dispatch configuration for the event.
109 * @param {object} PluginModule Plugin publishing the event.
110 * @return {boolean} True if the event was successfully published.
111 * @private
112 */
113function publishEventForPlugin(dispatchConfig, pluginModule, eventName) {
114 (function () {
115 if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) {
116 {
117 throw ReactError('EventPluginHub: More than one plugin attempted to publish the same event name, `' + eventName + '`.');
118 }
119 }
120 })();
121 eventNameDispatchConfigs[eventName] = dispatchConfig;
122
123 var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
124 if (phasedRegistrationNames) {
125 for (var phaseName in phasedRegistrationNames) {
126 if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
127 var phasedRegistrationName = phasedRegistrationNames[phaseName];
128 publishRegistrationName(phasedRegistrationName, pluginModule, eventName);
129 }
130 }
131 return true;
132 } else if (dispatchConfig.registrationName) {
133 publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);
134 return true;
135 }
136 return false;
137}
138
139/**
140 * Publishes a registration name that is used to identify dispatched events.
141 *
142 * @param {string} registrationName Registration name to add.
143 * @param {object} PluginModule Plugin publishing the event.
144 * @private
145 */
146function publishRegistrationName(registrationName, pluginModule, eventName) {
147 (function () {
148 if (!!registrationNameModules[registrationName]) {
149 {
150 throw ReactError('EventPluginHub: More than one plugin attempted to publish the same registration name, `' + registrationName + '`.');
151 }
152 }
153 })();
154 registrationNameModules[registrationName] = pluginModule;
155 registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;
156
157 {
158 var lowerCasedName = registrationName.toLowerCase();
159 possibleRegistrationNames[lowerCasedName] = registrationName;
160
161 if (registrationName === 'onDoubleClick') {
162 possibleRegistrationNames.ondblclick = registrationName;
163 }
164 }
165}
166
167/**
168 * Registers plugins so that they can extract and dispatch events.
169 *
170 * @see {EventPluginHub}
171 */
172
173/**
174 * Ordered list of injected plugins.
175 */
176var plugins = [];
177
178/**
179 * Mapping from event name to dispatch config
180 */
181var eventNameDispatchConfigs = {};
182
183/**
184 * Mapping from registration name to plugin module
185 */
186var registrationNameModules = {};
187
188/**
189 * Mapping from registration name to event name
190 */
191var registrationNameDependencies = {};
192
193/**
194 * Mapping from lowercase registration names to the properly cased version,
195 * used to warn in the case of missing event handlers. Available
196 * only in true.
197 * @type {Object}
198 */
199var possibleRegistrationNames = {};
200// Trust the developer to only use possibleRegistrationNames in true
201
202/**
203 * Injects an ordering of plugins (by plugin name). This allows the ordering
204 * to be decoupled from injection of the actual plugins so that ordering is
205 * always deterministic regardless of packaging, on-the-fly injection, etc.
206 *
207 * @param {array} InjectedEventPluginOrder
208 * @internal
209 * @see {EventPluginHub.injection.injectEventPluginOrder}
210 */
211function injectEventPluginOrder(injectedEventPluginOrder) {
212 (function () {
213 if (!!eventPluginOrder) {
214 {
215 throw ReactError('EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.');
216 }
217 }
218 })();
219 // Clone the ordering so it cannot be dynamically mutated.
220 eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
221 recomputePluginOrdering();
222}
223
224/**
225 * Injects plugins to be used by `EventPluginHub`. The plugin names must be
226 * in the ordering injected by `injectEventPluginOrder`.
227 *
228 * Plugins can be injected as part of page initialization or on-the-fly.
229 *
230 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
231 * @internal
232 * @see {EventPluginHub.injection.injectEventPluginsByName}
233 */
234function injectEventPluginsByName(injectedNamesToPlugins) {
235 var isOrderingDirty = false;
236 for (var pluginName in injectedNamesToPlugins) {
237 if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
238 continue;
239 }
240 var pluginModule = injectedNamesToPlugins[pluginName];
241 if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {
242 (function () {
243 if (!!namesToPlugins[pluginName]) {
244 {
245 throw ReactError('EventPluginRegistry: Cannot inject two different event plugins using the same name, `' + pluginName + '`.');
246 }
247 }
248 })();
249 namesToPlugins[pluginName] = pluginModule;
250 isOrderingDirty = true;
251 }
252 }
253 if (isOrderingDirty) {
254 recomputePluginOrdering();
255 }
256}
257
258var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {
259 var funcArgs = Array.prototype.slice.call(arguments, 3);
260 try {
261 func.apply(context, funcArgs);
262 } catch (error) {
263 this.onError(error);
264 }
265};
266
267{
268 // In DEV mode, we swap out invokeGuardedCallback for a special version
269 // that plays more nicely with the browser's DevTools. The idea is to preserve
270 // "Pause on exceptions" behavior. Because React wraps all user-provided
271 // functions in invokeGuardedCallback, and the production version of
272 // invokeGuardedCallback uses a try-catch, all user exceptions are treated
273 // like caught exceptions, and the DevTools won't pause unless the developer
274 // takes the extra step of enabling pause on caught exceptions. This is
275 // unintuitive, though, because even though React has caught the error, from
276 // the developer's perspective, the error is uncaught.
277 //
278 // To preserve the expected "Pause on exceptions" behavior, we don't use a
279 // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
280 // DOM node, and call the user-provided callback from inside an event handler
281 // for that fake event. If the callback throws, the error is "captured" using
282 // a global event handler. But because the error happens in a different
283 // event loop context, it does not interrupt the normal program flow.
284 // Effectively, this gives us try-catch behavior without actually using
285 // try-catch. Neat!
286
287 // Check that the browser supports the APIs we need to implement our special
288 // DEV version of invokeGuardedCallback
289 if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
290 var fakeNode = document.createElement('react');
291
292 var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {
293 // If document doesn't exist we know for sure we will crash in this method
294 // when we call document.createEvent(). However this can cause confusing
295 // errors: https://github.com/facebookincubator/create-react-app/issues/3482
296 // So we preemptively throw with a better message instead.
297 (function () {
298 if (!(typeof document !== 'undefined')) {
299 {
300 throw ReactError('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.');
301 }
302 }
303 })();
304 var evt = document.createEvent('Event');
305
306 // Keeps track of whether the user-provided callback threw an error. We
307 // set this to true at the beginning, then set it to false right after
308 // calling the function. If the function errors, `didError` will never be
309 // set to false. This strategy works even if the browser is flaky and
310 // fails to call our global error handler, because it doesn't rely on
311 // the error event at all.
312 var didError = true;
313
314 // Keeps track of the value of window.event so that we can reset it
315 // during the callback to let user code access window.event in the
316 // browsers that support it.
317 var windowEvent = window.event;
318
319 // Keeps track of the descriptor of window.event to restore it after event
320 // dispatching: https://github.com/facebook/react/issues/13688
321 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');
322
323 // Create an event handler for our fake event. We will synchronously
324 // dispatch our fake event using `dispatchEvent`. Inside the handler, we
325 // call the user-provided callback.
326 var funcArgs = Array.prototype.slice.call(arguments, 3);
327 function callCallback() {
328 // We immediately remove the callback from event listeners so that
329 // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
330 // nested call would trigger the fake event handlers of any call higher
331 // in the stack.
332 fakeNode.removeEventListener(evtType, callCallback, false);
333
334 // We check for window.hasOwnProperty('event') to prevent the
335 // window.event assignment in both IE <= 10 as they throw an error
336 // "Member not found" in strict mode, and in Firefox which does not
337 // support window.event.
338 if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
339 window.event = windowEvent;
340 }
341
342 func.apply(context, funcArgs);
343 didError = false;
344 }
345
346 // Create a global error event handler. We use this to capture the value
347 // that was thrown. It's possible that this error handler will fire more
348 // than once; for example, if non-React code also calls `dispatchEvent`
349 // and a handler for that event throws. We should be resilient to most of
350 // those cases. Even if our error event handler fires more than once, the
351 // last error event is always used. If the callback actually does error,
352 // we know that the last error event is the correct one, because it's not
353 // possible for anything else to have happened in between our callback
354 // erroring and the code that follows the `dispatchEvent` call below. If
355 // the callback doesn't error, but the error event was fired, we know to
356 // ignore it because `didError` will be false, as described above.
357 var error = void 0;
358 // Use this to track whether the error event is ever called.
359 var didSetError = false;
360 var isCrossOriginError = false;
361
362 function handleWindowError(event) {
363 error = event.error;
364 didSetError = true;
365 if (error === null && event.colno === 0 && event.lineno === 0) {
366 isCrossOriginError = true;
367 }
368 if (event.defaultPrevented) {
369 // Some other error handler has prevented default.
370 // Browsers silence the error report if this happens.
371 // We'll remember this to later decide whether to log it or not.
372 if (error != null && typeof error === 'object') {
373 try {
374 error._suppressLogging = true;
375 } catch (inner) {
376 // Ignore.
377 }
378 }
379 }
380 }
381
382 // Create a fake event type.
383 var evtType = 'react-' + (name ? name : 'invokeguardedcallback');
384
385 // Attach our event handlers
386 window.addEventListener('error', handleWindowError);
387 fakeNode.addEventListener(evtType, callCallback, false);
388
389 // Synchronously dispatch our fake event. If the user-provided function
390 // errors, it will trigger our global error handler.
391 evt.initEvent(evtType, false, false);
392 fakeNode.dispatchEvent(evt);
393
394 if (windowEventDescriptor) {
395 Object.defineProperty(window, 'event', windowEventDescriptor);
396 }
397
398 if (didError) {
399 if (!didSetError) {
400 // The callback errored, but the error event never fired.
401 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.');
402 } else if (isCrossOriginError) {
403 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.');
404 }
405 this.onError(error);
406 }
407
408 // Remove our event listeners
409 window.removeEventListener('error', handleWindowError);
410 };
411
412 invokeGuardedCallbackImpl = invokeGuardedCallbackDev;
413 }
414}
415
416var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
417
418// Used by Fiber to simulate a try-catch.
419var hasError = false;
420var caughtError = null;
421
422// Used by event system to capture/rethrow the first error.
423var hasRethrowError = false;
424var rethrowError = null;
425
426var reporter = {
427 onError: function (error) {
428 hasError = true;
429 caughtError = error;
430 }
431};
432
433/**
434 * Call a function while guarding against errors that happens within it.
435 * Returns an error if it throws, otherwise null.
436 *
437 * In production, this is implemented using a try-catch. The reason we don't
438 * use a try-catch directly is so that we can swap out a different
439 * implementation in DEV mode.
440 *
441 * @param {String} name of the guard to use for logging or debugging
442 * @param {Function} func The function to invoke
443 * @param {*} context The context to use when calling the function
444 * @param {...*} args Arguments for function
445 */
446function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
447 hasError = false;
448 caughtError = null;
449 invokeGuardedCallbackImpl$1.apply(reporter, arguments);
450}
451
452/**
453 * Same as invokeGuardedCallback, but instead of returning an error, it stores
454 * it in a global so it can be rethrown by `rethrowCaughtError` later.
455 * TODO: See if caughtError and rethrowError can be unified.
456 *
457 * @param {String} name of the guard to use for logging or debugging
458 * @param {Function} func The function to invoke
459 * @param {*} context The context to use when calling the function
460 * @param {...*} args Arguments for function
461 */
462function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
463 invokeGuardedCallback.apply(this, arguments);
464 if (hasError) {
465 var error = clearCaughtError();
466 if (!hasRethrowError) {
467 hasRethrowError = true;
468 rethrowError = error;
469 }
470 }
471}
472
473/**
474 * During execution of guarded functions we will capture the first error which
475 * we will rethrow to be handled by the top level error handler.
476 */
477function rethrowCaughtError() {
478 if (hasRethrowError) {
479 var error = rethrowError;
480 hasRethrowError = false;
481 rethrowError = null;
482 throw error;
483 }
484}
485
486function hasCaughtError() {
487 return hasError;
488}
489
490function clearCaughtError() {
491 if (hasError) {
492 var error = caughtError;
493 hasError = false;
494 caughtError = null;
495 return error;
496 } else {
497 (function () {
498 {
499 {
500 throw ReactError('clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.');
501 }
502 }
503 })();
504 }
505}
506
507/**
508 * Similar to invariant but only logs a warning if the condition is not met.
509 * This can be used to log issues in development environments in critical
510 * paths. Removing the logging code for production environments will keep the
511 * same logic and follow the same code paths.
512 */
513
514var warningWithoutStack = function () {};
515
516{
517 warningWithoutStack = function (condition, format) {
518 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
519 args[_key - 2] = arguments[_key];
520 }
521
522 if (format === undefined) {
523 throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
524 }
525 if (args.length > 8) {
526 // Check before the condition to catch violations early.
527 throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
528 }
529 if (condition) {
530 return;
531 }
532 if (typeof console !== 'undefined') {
533 var argsWithFormat = args.map(function (item) {
534 return '' + item;
535 });
536 argsWithFormat.unshift('Warning: ' + format);
537
538 // We intentionally don't use spread (or .apply) directly because it
539 // breaks IE9: https://github.com/facebook/react/issues/13610
540 Function.prototype.apply.call(console.error, console, argsWithFormat);
541 }
542 try {
543 // --- Welcome to debugging React ---
544 // This error was thrown as a convenience so that you can use this stack
545 // to find the callsite that caused this warning to fire.
546 var argIndex = 0;
547 var message = 'Warning: ' + format.replace(/%s/g, function () {
548 return args[argIndex++];
549 });
550 throw new Error(message);
551 } catch (x) {}
552 };
553}
554
555var warningWithoutStack$1 = warningWithoutStack;
556
557var getFiberCurrentPropsFromNode = null;
558var getInstanceFromNode = null;
559var getNodeFromInstance = null;
560
561function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) {
562 getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;
563 getInstanceFromNode = getInstanceFromNodeImpl;
564 getNodeFromInstance = getNodeFromInstanceImpl;
565 {
566 !(getNodeFromInstance && getInstanceFromNode) ? warningWithoutStack$1(false, 'EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0;
567 }
568}
569
570var validateEventDispatches = void 0;
571{
572 validateEventDispatches = function (event) {
573 var dispatchListeners = event._dispatchListeners;
574 var dispatchInstances = event._dispatchInstances;
575
576 var listenersIsArr = Array.isArray(dispatchListeners);
577 var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
578
579 var instancesIsArr = Array.isArray(dispatchInstances);
580 var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
581
582 !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, 'EventPluginUtils: Invalid `event`.') : void 0;
583 };
584}
585
586/**
587 * Dispatch the event to the listener.
588 * @param {SyntheticEvent} event SyntheticEvent to handle
589 * @param {function} listener Application-level callback
590 * @param {*} inst Internal component instance
591 */
592function executeDispatch(event, listener, inst) {
593 var type = event.type || 'unknown-event';
594 event.currentTarget = getNodeFromInstance(inst);
595 invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
596 event.currentTarget = null;
597}
598
599/**
600 * Standard/simple iteration through an event's collected dispatches.
601 */
602function executeDispatchesInOrder(event) {
603 var dispatchListeners = event._dispatchListeners;
604 var dispatchInstances = event._dispatchInstances;
605 {
606 validateEventDispatches(event);
607 }
608 if (Array.isArray(dispatchListeners)) {
609 for (var i = 0; i < dispatchListeners.length; i++) {
610 if (event.isPropagationStopped()) {
611 break;
612 }
613 // Listeners and Instances are two parallel arrays that are always in sync.
614 executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
615 }
616 } else if (dispatchListeners) {
617 executeDispatch(event, dispatchListeners, dispatchInstances);
618 }
619 event._dispatchListeners = null;
620 event._dispatchInstances = null;
621}
622
623/**
624 * @see executeDispatchesInOrderStopAtTrueImpl
625 */
626
627
628/**
629 * Execution of a "direct" dispatch - there must be at most one dispatch
630 * accumulated on the event or it is considered an error. It doesn't really make
631 * sense for an event with multiple dispatches (bubbled) to keep track of the
632 * return values at each dispatch execution, but it does tend to make sense when
633 * dealing with "direct" dispatches.
634 *
635 * @return {*} The return value of executing the single dispatch.
636 */
637
638
639/**
640 * @param {SyntheticEvent} event
641 * @return {boolean} True iff number of dispatches accumulated is greater than 0.
642 */
643
644/**
645 * Accumulates items that must not be null or undefined into the first one. This
646 * is used to conserve memory by avoiding array allocations, and thus sacrifices
647 * API cleanness. Since `current` can be null before being passed in and not
648 * null after this function, make sure to assign it back to `current`:
649 *
650 * `a = accumulateInto(a, b);`
651 *
652 * This API should be sparingly used. Try `accumulate` for something cleaner.
653 *
654 * @return {*|array<*>} An accumulation of items.
655 */
656
657function accumulateInto(current, next) {
658 (function () {
659 if (!(next != null)) {
660 {
661 throw ReactError('accumulateInto(...): Accumulated items must not be null or undefined.');
662 }
663 }
664 })();
665
666 if (current == null) {
667 return next;
668 }
669
670 // Both are not empty. Warning: Never call x.concat(y) when you are not
671 // certain that x is an Array (x could be a string with concat method).
672 if (Array.isArray(current)) {
673 if (Array.isArray(next)) {
674 current.push.apply(current, next);
675 return current;
676 }
677 current.push(next);
678 return current;
679 }
680
681 if (Array.isArray(next)) {
682 // A bit too dangerous to mutate `next`.
683 return [current].concat(next);
684 }
685
686 return [current, next];
687}
688
689/**
690 * @param {array} arr an "accumulation" of items which is either an Array or
691 * a single item. Useful when paired with the `accumulate` module. This is a
692 * simple utility that allows us to reason about a collection of items, but
693 * handling the case when there is exactly one item (and we do not need to
694 * allocate an array).
695 * @param {function} cb Callback invoked with each element or a collection.
696 * @param {?} [scope] Scope used as `this` in a callback.
697 */
698function forEachAccumulated(arr, cb, scope) {
699 if (Array.isArray(arr)) {
700 arr.forEach(cb, scope);
701 } else if (arr) {
702 cb.call(scope, arr);
703 }
704}
705
706/**
707 * Internal queue of events that have accumulated their dispatches and are
708 * waiting to have their dispatches executed.
709 */
710var eventQueue = null;
711
712/**
713 * Dispatches an event and releases it back into the pool, unless persistent.
714 *
715 * @param {?object} event Synthetic event to be dispatched.
716 * @private
717 */
718var executeDispatchesAndRelease = function (event) {
719 if (event) {
720 executeDispatchesInOrder(event);
721
722 if (!event.isPersistent()) {
723 event.constructor.release(event);
724 }
725 }
726};
727var executeDispatchesAndReleaseTopLevel = function (e) {
728 return executeDispatchesAndRelease(e);
729};
730
731function runEventsInBatch(events) {
732 if (events !== null) {
733 eventQueue = accumulateInto(eventQueue, events);
734 }
735
736 // Set `eventQueue` to null before processing it so that we can tell if more
737 // events get enqueued while processing.
738 var processingEventQueue = eventQueue;
739 eventQueue = null;
740
741 if (!processingEventQueue) {
742 return;
743 }
744
745 forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
746 (function () {
747 if (!!eventQueue) {
748 {
749 throw ReactError('processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.');
750 }
751 }
752 })();
753 // This would be a good time to rethrow if any of the event handlers threw.
754 rethrowCaughtError();
755}
756
757function isInteractive(tag) {
758 return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
759}
760
761function shouldPreventMouseEvent(name, type, props) {
762 switch (name) {
763 case 'onClick':
764 case 'onClickCapture':
765 case 'onDoubleClick':
766 case 'onDoubleClickCapture':
767 case 'onMouseDown':
768 case 'onMouseDownCapture':
769 case 'onMouseMove':
770 case 'onMouseMoveCapture':
771 case 'onMouseUp':
772 case 'onMouseUpCapture':
773 return !!(props.disabled && isInteractive(type));
774 default:
775 return false;
776 }
777}
778
779/**
780 * This is a unified interface for event plugins to be installed and configured.
781 *
782 * Event plugins can implement the following properties:
783 *
784 * `extractEvents` {function(string, DOMEventTarget, string, object): *}
785 * Required. When a top-level event is fired, this method is expected to
786 * extract synthetic events that will in turn be queued and dispatched.
787 *
788 * `eventTypes` {object}
789 * Optional, plugins that fire events must publish a mapping of registration
790 * names that are used to register listeners. Values of this mapping must
791 * be objects that contain `registrationName` or `phasedRegistrationNames`.
792 *
793 * `executeDispatch` {function(object, function, string)}
794 * Optional, allows plugins to override how an event gets dispatched. By
795 * default, the listener is simply invoked.
796 *
797 * Each plugin that is injected into `EventsPluginHub` is immediately operable.
798 *
799 * @public
800 */
801
802/**
803 * Methods for injecting dependencies.
804 */
805var injection = {
806 /**
807 * @param {array} InjectedEventPluginOrder
808 * @public
809 */
810 injectEventPluginOrder: injectEventPluginOrder,
811
812 /**
813 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
814 */
815 injectEventPluginsByName: injectEventPluginsByName
816};
817
818/**
819 * @param {object} inst The instance, which is the source of events.
820 * @param {string} registrationName Name of listener (e.g. `onClick`).
821 * @return {?function} The stored callback.
822 */
823function getListener(inst, registrationName) {
824 var listener = void 0;
825
826 // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
827 // live here; needs to be moved to a better place soon
828 var stateNode = inst.stateNode;
829 if (!stateNode) {
830 // Work in progress (ex: onload events in incremental mode).
831 return null;
832 }
833 var props = getFiberCurrentPropsFromNode(stateNode);
834 if (!props) {
835 // Work in progress.
836 return null;
837 }
838 listener = props[registrationName];
839 if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
840 return null;
841 }
842 (function () {
843 if (!(!listener || typeof listener === 'function')) {
844 {
845 throw ReactError('Expected `' + registrationName + '` listener to be a function, instead got a value of `' + typeof listener + '` type.');
846 }
847 }
848 })();
849 return listener;
850}
851
852/**
853 * Allows registered plugins an opportunity to extract events from top-level
854 * native browser events.
855 *
856 * @return {*} An accumulation of synthetic events.
857 * @internal
858 */
859function extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
860 var events = null;
861 for (var i = 0; i < plugins.length; i++) {
862 // Not every plugin in the ordering may be loaded at runtime.
863 var possiblePlugin = plugins[i];
864 if (possiblePlugin) {
865 var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
866 if (extractedEvents) {
867 events = accumulateInto(events, extractedEvents);
868 }
869 }
870 }
871 return events;
872}
873
874function runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
875 var events = extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
876 runEventsInBatch(events);
877}
878
879var FunctionComponent = 0;
880var ClassComponent = 1;
881var IndeterminateComponent = 2; // Before we know whether it is function or class
882var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
883var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
884var HostComponent = 5;
885var HostText = 6;
886var Fragment = 7;
887var Mode = 8;
888var ContextConsumer = 9;
889var ContextProvider = 10;
890var ForwardRef = 11;
891var Profiler = 12;
892var SuspenseComponent = 13;
893var MemoComponent = 14;
894var SimpleMemoComponent = 15;
895var LazyComponent = 16;
896var IncompleteClassComponent = 17;
897var DehydratedSuspenseComponent = 18;
898var EventComponent = 19;
899var EventTarget = 20;
900
901var randomKey = Math.random().toString(36).slice(2);
902var internalInstanceKey = '__reactInternalInstance$' + randomKey;
903var internalEventHandlersKey = '__reactEventHandlers$' + randomKey;
904
905function precacheFiberNode(hostInst, node) {
906 node[internalInstanceKey] = hostInst;
907}
908
909/**
910 * Given a DOM node, return the closest ReactDOMComponent or
911 * ReactDOMTextComponent instance ancestor.
912 */
913function getClosestInstanceFromNode(node) {
914 if (node[internalInstanceKey]) {
915 return node[internalInstanceKey];
916 }
917
918 while (!node[internalInstanceKey]) {
919 if (node.parentNode) {
920 node = node.parentNode;
921 } else {
922 // Top of the tree. This node must not be part of a React tree (or is
923 // unmounted, potentially).
924 return null;
925 }
926 }
927
928 var inst = node[internalInstanceKey];
929 if (inst.tag === HostComponent || inst.tag === HostText) {
930 // In Fiber, this will always be the deepest root.
931 return inst;
932 }
933
934 return null;
935}
936
937/**
938 * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
939 * instance, or null if the node was not rendered by this React.
940 */
941function getInstanceFromNode$1(node) {
942 var inst = node[internalInstanceKey];
943 if (inst) {
944 if (inst.tag === HostComponent || inst.tag === HostText) {
945 return inst;
946 } else {
947 return null;
948 }
949 }
950 return null;
951}
952
953/**
954 * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
955 * DOM node.
956 */
957function getNodeFromInstance$1(inst) {
958 if (inst.tag === HostComponent || inst.tag === HostText) {
959 // In Fiber this, is just the state node right now. We assume it will be
960 // a host component or host text.
961 return inst.stateNode;
962 }
963
964 // Without this first invariant, passing a non-DOM-component triggers the next
965 // invariant for a missing parent, which is super confusing.
966 (function () {
967 {
968 {
969 throw ReactError('getNodeFromInstance: Invalid argument.');
970 }
971 }
972 })();
973}
974
975function getFiberCurrentPropsFromNode$1(node) {
976 return node[internalEventHandlersKey] || null;
977}
978
979function updateFiberProps(node, props) {
980 node[internalEventHandlersKey] = props;
981}
982
983function getParent(inst) {
984 do {
985 inst = inst.return;
986 // TODO: If this is a HostRoot we might want to bail out.
987 // That is depending on if we want nested subtrees (layers) to bubble
988 // events to their parent. We could also go through parentNode on the
989 // host node but that wouldn't work for React Native and doesn't let us
990 // do the portal feature.
991 } while (inst && inst.tag !== HostComponent);
992 if (inst) {
993 return inst;
994 }
995 return null;
996}
997
998/**
999 * Return the lowest common ancestor of A and B, or null if they are in
1000 * different trees.
1001 */
1002function getLowestCommonAncestor(instA, instB) {
1003 var depthA = 0;
1004 for (var tempA = instA; tempA; tempA = getParent(tempA)) {
1005 depthA++;
1006 }
1007 var depthB = 0;
1008 for (var tempB = instB; tempB; tempB = getParent(tempB)) {
1009 depthB++;
1010 }
1011
1012 // If A is deeper, crawl up.
1013 while (depthA - depthB > 0) {
1014 instA = getParent(instA);
1015 depthA--;
1016 }
1017
1018 // If B is deeper, crawl up.
1019 while (depthB - depthA > 0) {
1020 instB = getParent(instB);
1021 depthB--;
1022 }
1023
1024 // Walk in lockstep until we find a match.
1025 var depth = depthA;
1026 while (depth--) {
1027 if (instA === instB || instA === instB.alternate) {
1028 return instA;
1029 }
1030 instA = getParent(instA);
1031 instB = getParent(instB);
1032 }
1033 return null;
1034}
1035
1036/**
1037 * Return if A is an ancestor of B.
1038 */
1039
1040
1041/**
1042 * Return the parent instance of the passed-in instance.
1043 */
1044
1045
1046/**
1047 * Simulates the traversal of a two-phase, capture/bubble event dispatch.
1048 */
1049function traverseTwoPhase(inst, fn, arg) {
1050 var path = [];
1051 while (inst) {
1052 path.push(inst);
1053 inst = getParent(inst);
1054 }
1055 var i = void 0;
1056 for (i = path.length; i-- > 0;) {
1057 fn(path[i], 'captured', arg);
1058 }
1059 for (i = 0; i < path.length; i++) {
1060 fn(path[i], 'bubbled', arg);
1061 }
1062}
1063
1064/**
1065 * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
1066 * should would receive a `mouseEnter` or `mouseLeave` event.
1067 *
1068 * Does not invoke the callback on the nearest common ancestor because nothing
1069 * "entered" or "left" that element.
1070 */
1071function traverseEnterLeave(from, to, fn, argFrom, argTo) {
1072 var common = from && to ? getLowestCommonAncestor(from, to) : null;
1073 var pathFrom = [];
1074 while (true) {
1075 if (!from) {
1076 break;
1077 }
1078 if (from === common) {
1079 break;
1080 }
1081 var alternate = from.alternate;
1082 if (alternate !== null && alternate === common) {
1083 break;
1084 }
1085 pathFrom.push(from);
1086 from = getParent(from);
1087 }
1088 var pathTo = [];
1089 while (true) {
1090 if (!to) {
1091 break;
1092 }
1093 if (to === common) {
1094 break;
1095 }
1096 var _alternate = to.alternate;
1097 if (_alternate !== null && _alternate === common) {
1098 break;
1099 }
1100 pathTo.push(to);
1101 to = getParent(to);
1102 }
1103 for (var i = 0; i < pathFrom.length; i++) {
1104 fn(pathFrom[i], 'bubbled', argFrom);
1105 }
1106 for (var _i = pathTo.length; _i-- > 0;) {
1107 fn(pathTo[_i], 'captured', argTo);
1108 }
1109}
1110
1111/**
1112 * Some event types have a notion of different registration names for different
1113 * "phases" of propagation. This finds listeners by a given phase.
1114 */
1115function listenerAtPhase(inst, event, propagationPhase) {
1116 var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
1117 return getListener(inst, registrationName);
1118}
1119
1120/**
1121 * A small set of propagation patterns, each of which will accept a small amount
1122 * of information, and generate a set of "dispatch ready event objects" - which
1123 * are sets of events that have already been annotated with a set of dispatched
1124 * listener functions/ids. The API is designed this way to discourage these
1125 * propagation strategies from actually executing the dispatches, since we
1126 * always want to collect the entire set of dispatches before executing even a
1127 * single one.
1128 */
1129
1130/**
1131 * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
1132 * here, allows us to not have to bind or create functions for each event.
1133 * Mutating the event's members allows us to not have to create a wrapping
1134 * "dispatch" object that pairs the event with the listener.
1135 */
1136function accumulateDirectionalDispatches(inst, phase, event) {
1137 {
1138 !inst ? warningWithoutStack$1(false, 'Dispatching inst must not be null') : void 0;
1139 }
1140 var listener = listenerAtPhase(inst, event, phase);
1141 if (listener) {
1142 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
1143 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
1144 }
1145}
1146
1147/**
1148 * Collect dispatches (must be entirely collected before dispatching - see unit
1149 * tests). Lazily allocate the array to conserve memory. We must loop through
1150 * each event and perform the traversal for each one. We cannot perform a
1151 * single traversal for the entire collection of events because each event may
1152 * have a different target.
1153 */
1154function accumulateTwoPhaseDispatchesSingle(event) {
1155 if (event && event.dispatchConfig.phasedRegistrationNames) {
1156 traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
1157 }
1158}
1159
1160/**
1161 * Accumulates without regard to direction, does not look for phased
1162 * registration names. Same as `accumulateDirectDispatchesSingle` but without
1163 * requiring that the `dispatchMarker` be the same as the dispatched ID.
1164 */
1165function accumulateDispatches(inst, ignoredDirection, event) {
1166 if (inst && event && event.dispatchConfig.registrationName) {
1167 var registrationName = event.dispatchConfig.registrationName;
1168 var listener = getListener(inst, registrationName);
1169 if (listener) {
1170 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
1171 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
1172 }
1173 }
1174}
1175
1176/**
1177 * Accumulates dispatches on an `SyntheticEvent`, but only for the
1178 * `dispatchMarker`.
1179 * @param {SyntheticEvent} event
1180 */
1181function accumulateDirectDispatchesSingle(event) {
1182 if (event && event.dispatchConfig.registrationName) {
1183 accumulateDispatches(event._targetInst, null, event);
1184 }
1185}
1186
1187function accumulateTwoPhaseDispatches(events) {
1188 forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
1189}
1190
1191
1192
1193function accumulateEnterLeaveDispatches(leave, enter, from, to) {
1194 traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
1195}
1196
1197function accumulateDirectDispatches(events) {
1198 forEachAccumulated(events, accumulateDirectDispatchesSingle);
1199}
1200
1201var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
1202
1203// Do not uses the below two methods directly!
1204// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.
1205// (It is the only module that is allowed to access these methods.)
1206
1207function unsafeCastStringToDOMTopLevelType(topLevelType) {
1208 return topLevelType;
1209}
1210
1211function unsafeCastDOMTopLevelTypeToString(topLevelType) {
1212 return topLevelType;
1213}
1214
1215/**
1216 * Generate a mapping of standard vendor prefixes using the defined style property and event name.
1217 *
1218 * @param {string} styleProp
1219 * @param {string} eventName
1220 * @returns {object}
1221 */
1222function makePrefixMap(styleProp, eventName) {
1223 var prefixes = {};
1224
1225 prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
1226 prefixes['Webkit' + styleProp] = 'webkit' + eventName;
1227 prefixes['Moz' + styleProp] = 'moz' + eventName;
1228
1229 return prefixes;
1230}
1231
1232/**
1233 * A list of event names to a configurable list of vendor prefixes.
1234 */
1235var vendorPrefixes = {
1236 animationend: makePrefixMap('Animation', 'AnimationEnd'),
1237 animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
1238 animationstart: makePrefixMap('Animation', 'AnimationStart'),
1239 transitionend: makePrefixMap('Transition', 'TransitionEnd')
1240};
1241
1242/**
1243 * Event names that have already been detected and prefixed (if applicable).
1244 */
1245var prefixedEventNames = {};
1246
1247/**
1248 * Element to check for prefixes on.
1249 */
1250var style = {};
1251
1252/**
1253 * Bootstrap if a DOM exists.
1254 */
1255if (canUseDOM) {
1256 style = document.createElement('div').style;
1257
1258 // On some platforms, in particular some releases of Android 4.x,
1259 // the un-prefixed "animation" and "transition" properties are defined on the
1260 // style object but the events that fire will still be prefixed, so we need
1261 // to check if the un-prefixed events are usable, and if not remove them from the map.
1262 if (!('AnimationEvent' in window)) {
1263 delete vendorPrefixes.animationend.animation;
1264 delete vendorPrefixes.animationiteration.animation;
1265 delete vendorPrefixes.animationstart.animation;
1266 }
1267
1268 // Same as above
1269 if (!('TransitionEvent' in window)) {
1270 delete vendorPrefixes.transitionend.transition;
1271 }
1272}
1273
1274/**
1275 * Attempts to determine the correct vendor prefixed event name.
1276 *
1277 * @param {string} eventName
1278 * @returns {string}
1279 */
1280function getVendorPrefixedEventName(eventName) {
1281 if (prefixedEventNames[eventName]) {
1282 return prefixedEventNames[eventName];
1283 } else if (!vendorPrefixes[eventName]) {
1284 return eventName;
1285 }
1286
1287 var prefixMap = vendorPrefixes[eventName];
1288
1289 for (var styleProp in prefixMap) {
1290 if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
1291 return prefixedEventNames[eventName] = prefixMap[styleProp];
1292 }
1293 }
1294
1295 return eventName;
1296}
1297
1298/**
1299 * To identify top level events in ReactDOM, we use constants defined by this
1300 * module. This is the only module that uses the unsafe* methods to express
1301 * that the constants actually correspond to the browser event names. This lets
1302 * us save some bundle size by avoiding a top level type -> event name map.
1303 * The rest of ReactDOM code should import top level types from this file.
1304 */
1305var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
1306var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
1307var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));
1308var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
1309var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
1310var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
1311var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
1312var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
1313var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
1314var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
1315var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
1316var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
1317var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');
1318var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');
1319var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
1320var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
1321var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
1322var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
1323var TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick');
1324var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
1325var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
1326var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
1327var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
1328var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
1329var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
1330var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
1331var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
1332var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
1333var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
1334var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
1335var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
1336var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
1337var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
1338var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture');
1339var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
1340var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid');
1341var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
1342var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
1343var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
1344var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
1345var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
1346var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
1347var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
1348var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture');
1349var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
1350var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
1351var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
1352var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
1353var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
1354var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
1355var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
1356var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
1357var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
1358var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel');
1359var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown');
1360
1361
1362var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove');
1363var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout');
1364var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover');
1365var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup');
1366var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
1367var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
1368var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset');
1369var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
1370var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
1371var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
1372var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
1373var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
1374var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit');
1375var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
1376var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
1377var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
1378var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
1379var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
1380var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
1381var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
1382var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
1383var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
1384var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
1385var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
1386var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel');
1387
1388// List of events that need to be individually attached to media elements.
1389// Note that events in this list will *not* be listened to at the top level
1390// unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.
1391var 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];
1392
1393function getRawEventName(topLevelType) {
1394 return unsafeCastDOMTopLevelTypeToString(topLevelType);
1395}
1396
1397/**
1398 * These variables store information about text content of a target node,
1399 * allowing comparison of content before and after a given event.
1400 *
1401 * Identify the node where selection currently begins, then observe
1402 * both its text content and its current position in the DOM. Since the
1403 * browser may natively replace the target node during composition, we can
1404 * use its position to find its replacement.
1405 *
1406 *
1407 */
1408
1409var root = null;
1410var startText = null;
1411var fallbackText = null;
1412
1413function initialize(nativeEventTarget) {
1414 root = nativeEventTarget;
1415 startText = getText();
1416 return true;
1417}
1418
1419function reset() {
1420 root = null;
1421 startText = null;
1422 fallbackText = null;
1423}
1424
1425function getData() {
1426 if (fallbackText) {
1427 return fallbackText;
1428 }
1429
1430 var start = void 0;
1431 var startValue = startText;
1432 var startLength = startValue.length;
1433 var end = void 0;
1434 var endValue = getText();
1435 var endLength = endValue.length;
1436
1437 for (start = 0; start < startLength; start++) {
1438 if (startValue[start] !== endValue[start]) {
1439 break;
1440 }
1441 }
1442
1443 var minEnd = startLength - start;
1444 for (end = 1; end <= minEnd; end++) {
1445 if (startValue[startLength - end] !== endValue[endLength - end]) {
1446 break;
1447 }
1448 }
1449
1450 var sliceTail = end > 1 ? 1 - end : undefined;
1451 fallbackText = endValue.slice(start, sliceTail);
1452 return fallbackText;
1453}
1454
1455function getText() {
1456 if ('value' in root) {
1457 return root.value;
1458 }
1459 return root.textContent;
1460}
1461
1462var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1463
1464var _assign = ReactInternals.assign;
1465
1466/* eslint valid-typeof: 0 */
1467
1468var EVENT_POOL_SIZE = 10;
1469
1470/**
1471 * @interface Event
1472 * @see http://www.w3.org/TR/DOM-Level-3-Events/
1473 */
1474var EventInterface = {
1475 type: null,
1476 target: null,
1477 // currentTarget is set when dispatching; no use in copying it here
1478 currentTarget: function () {
1479 return null;
1480 },
1481 eventPhase: null,
1482 bubbles: null,
1483 cancelable: null,
1484 timeStamp: function (event) {
1485 return event.timeStamp || Date.now();
1486 },
1487 defaultPrevented: null,
1488 isTrusted: null
1489};
1490
1491function functionThatReturnsTrue() {
1492 return true;
1493}
1494
1495function functionThatReturnsFalse() {
1496 return false;
1497}
1498
1499/**
1500 * Synthetic events are dispatched by event plugins, typically in response to a
1501 * top-level event delegation handler.
1502 *
1503 * These systems should generally use pooling to reduce the frequency of garbage
1504 * collection. The system should check `isPersistent` to determine whether the
1505 * event should be released into the pool after being dispatched. Users that
1506 * need a persisted event should invoke `persist`.
1507 *
1508 * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
1509 * normalizing browser quirks. Subclasses do not necessarily have to implement a
1510 * DOM interface; custom application-specific events can also subclass this.
1511 *
1512 * @param {object} dispatchConfig Configuration used to dispatch this event.
1513 * @param {*} targetInst Marker identifying the event target.
1514 * @param {object} nativeEvent Native browser event.
1515 * @param {DOMEventTarget} nativeEventTarget Target node.
1516 */
1517function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
1518 {
1519 // these have a getter/setter for warnings
1520 delete this.nativeEvent;
1521 delete this.preventDefault;
1522 delete this.stopPropagation;
1523 delete this.isDefaultPrevented;
1524 delete this.isPropagationStopped;
1525 }
1526
1527 this.dispatchConfig = dispatchConfig;
1528 this._targetInst = targetInst;
1529 this.nativeEvent = nativeEvent;
1530
1531 var Interface = this.constructor.Interface;
1532 for (var propName in Interface) {
1533 if (!Interface.hasOwnProperty(propName)) {
1534 continue;
1535 }
1536 {
1537 delete this[propName]; // this has a getter/setter for warnings
1538 }
1539 var normalize = Interface[propName];
1540 if (normalize) {
1541 this[propName] = normalize(nativeEvent);
1542 } else {
1543 if (propName === 'target') {
1544 this.target = nativeEventTarget;
1545 } else {
1546 this[propName] = nativeEvent[propName];
1547 }
1548 }
1549 }
1550
1551 var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
1552 if (defaultPrevented) {
1553 this.isDefaultPrevented = functionThatReturnsTrue;
1554 } else {
1555 this.isDefaultPrevented = functionThatReturnsFalse;
1556 }
1557 this.isPropagationStopped = functionThatReturnsFalse;
1558 return this;
1559}
1560
1561_assign(SyntheticEvent.prototype, {
1562 preventDefault: function () {
1563 this.defaultPrevented = true;
1564 var event = this.nativeEvent;
1565 if (!event) {
1566 return;
1567 }
1568
1569 if (event.preventDefault) {
1570 event.preventDefault();
1571 } else if (typeof event.returnValue !== 'unknown') {
1572 event.returnValue = false;
1573 }
1574 this.isDefaultPrevented = functionThatReturnsTrue;
1575 },
1576
1577 stopPropagation: function () {
1578 var event = this.nativeEvent;
1579 if (!event) {
1580 return;
1581 }
1582
1583 if (event.stopPropagation) {
1584 event.stopPropagation();
1585 } else if (typeof event.cancelBubble !== 'unknown') {
1586 // The ChangeEventPlugin registers a "propertychange" event for
1587 // IE. This event does not support bubbling or cancelling, and
1588 // any references to cancelBubble throw "Member not found". A
1589 // typeof check of "unknown" circumvents this issue (and is also
1590 // IE specific).
1591 event.cancelBubble = true;
1592 }
1593
1594 this.isPropagationStopped = functionThatReturnsTrue;
1595 },
1596
1597 /**
1598 * We release all dispatched `SyntheticEvent`s after each event loop, adding
1599 * them back into the pool. This allows a way to hold onto a reference that
1600 * won't be added back into the pool.
1601 */
1602 persist: function () {
1603 this.isPersistent = functionThatReturnsTrue;
1604 },
1605
1606 /**
1607 * Checks if this event should be released back into the pool.
1608 *
1609 * @return {boolean} True if this should not be released, false otherwise.
1610 */
1611 isPersistent: functionThatReturnsFalse,
1612
1613 /**
1614 * `PooledClass` looks for `destructor` on each instance it releases.
1615 */
1616 destructor: function () {
1617 var Interface = this.constructor.Interface;
1618 for (var propName in Interface) {
1619 {
1620 Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
1621 }
1622 }
1623 this.dispatchConfig = null;
1624 this._targetInst = null;
1625 this.nativeEvent = null;
1626 this.isDefaultPrevented = functionThatReturnsFalse;
1627 this.isPropagationStopped = functionThatReturnsFalse;
1628 this._dispatchListeners = null;
1629 this._dispatchInstances = null;
1630 {
1631 Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
1632 Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
1633 Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
1634 Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
1635 Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
1636 }
1637 }
1638});
1639
1640SyntheticEvent.Interface = EventInterface;
1641
1642/**
1643 * Helper to reduce boilerplate when creating subclasses.
1644 */
1645SyntheticEvent.extend = function (Interface) {
1646 var Super = this;
1647
1648 var E = function () {};
1649 E.prototype = Super.prototype;
1650 var prototype = new E();
1651
1652 function Class() {
1653 return Super.apply(this, arguments);
1654 }
1655 _assign(prototype, Class.prototype);
1656 Class.prototype = prototype;
1657 Class.prototype.constructor = Class;
1658
1659 Class.Interface = _assign({}, Super.Interface, Interface);
1660 Class.extend = Super.extend;
1661 addEventPoolingTo(Class);
1662
1663 return Class;
1664};
1665
1666addEventPoolingTo(SyntheticEvent);
1667
1668/**
1669 * Helper to nullify syntheticEvent instance properties when destructing
1670 *
1671 * @param {String} propName
1672 * @param {?object} getVal
1673 * @return {object} defineProperty object
1674 */
1675function getPooledWarningPropertyDefinition(propName, getVal) {
1676 var isFunction = typeof getVal === 'function';
1677 return {
1678 configurable: true,
1679 set: set,
1680 get: get
1681 };
1682
1683 function set(val) {
1684 var action = isFunction ? 'setting the method' : 'setting the property';
1685 warn(action, 'This is effectively a no-op');
1686 return val;
1687 }
1688
1689 function get() {
1690 var action = isFunction ? 'accessing the method' : 'accessing the property';
1691 var result = isFunction ? 'This is a no-op function' : 'This is set to null';
1692 warn(action, result);
1693 return getVal;
1694 }
1695
1696 function warn(action, result) {
1697 var warningCondition = false;
1698 !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;
1699 }
1700}
1701
1702function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
1703 var EventConstructor = this;
1704 if (EventConstructor.eventPool.length) {
1705 var instance = EventConstructor.eventPool.pop();
1706 EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
1707 return instance;
1708 }
1709 return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
1710}
1711
1712function releasePooledEvent(event) {
1713 var EventConstructor = this;
1714 (function () {
1715 if (!(event instanceof EventConstructor)) {
1716 {
1717 throw ReactError('Trying to release an event instance into a pool of a different type.');
1718 }
1719 }
1720 })();
1721 event.destructor();
1722 if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
1723 EventConstructor.eventPool.push(event);
1724 }
1725}
1726
1727function addEventPoolingTo(EventConstructor) {
1728 EventConstructor.eventPool = [];
1729 EventConstructor.getPooled = getPooledEvent;
1730 EventConstructor.release = releasePooledEvent;
1731}
1732
1733/**
1734 * @interface Event
1735 * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
1736 */
1737var SyntheticCompositionEvent = SyntheticEvent.extend({
1738 data: null
1739});
1740
1741/**
1742 * @interface Event
1743 * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
1744 * /#events-inputevents
1745 */
1746var SyntheticInputEvent = SyntheticEvent.extend({
1747 data: null
1748});
1749
1750var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
1751var START_KEYCODE = 229;
1752
1753var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
1754
1755var documentMode = null;
1756if (canUseDOM && 'documentMode' in document) {
1757 documentMode = document.documentMode;
1758}
1759
1760// Webkit offers a very useful `textInput` event that can be used to
1761// directly represent `beforeInput`. The IE `textinput` event is not as
1762// useful, so we don't use it.
1763var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode;
1764
1765// In IE9+, we have access to composition events, but the data supplied
1766// by the native compositionend event may be incorrect. Japanese ideographic
1767// spaces, for instance (\u3000) are not recorded correctly.
1768var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
1769
1770var SPACEBAR_CODE = 32;
1771var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
1772
1773// Events and their corresponding property names.
1774var eventTypes = {
1775 beforeInput: {
1776 phasedRegistrationNames: {
1777 bubbled: 'onBeforeInput',
1778 captured: 'onBeforeInputCapture'
1779 },
1780 dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]
1781 },
1782 compositionEnd: {
1783 phasedRegistrationNames: {
1784 bubbled: 'onCompositionEnd',
1785 captured: 'onCompositionEndCapture'
1786 },
1787 dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
1788 },
1789 compositionStart: {
1790 phasedRegistrationNames: {
1791 bubbled: 'onCompositionStart',
1792 captured: 'onCompositionStartCapture'
1793 },
1794 dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
1795 },
1796 compositionUpdate: {
1797 phasedRegistrationNames: {
1798 bubbled: 'onCompositionUpdate',
1799 captured: 'onCompositionUpdateCapture'
1800 },
1801 dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
1802 }
1803};
1804
1805// Track whether we've ever handled a keypress on the space key.
1806var hasSpaceKeypress = false;
1807
1808/**
1809 * Return whether a native keypress event is assumed to be a command.
1810 * This is required because Firefox fires `keypress` events for key commands
1811 * (cut, copy, select-all, etc.) even though no character is inserted.
1812 */
1813function isKeypressCommand(nativeEvent) {
1814 return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
1815 // ctrlKey && altKey is equivalent to AltGr, and is not a command.
1816 !(nativeEvent.ctrlKey && nativeEvent.altKey);
1817}
1818
1819/**
1820 * Translate native top level events into event types.
1821 *
1822 * @param {string} topLevelType
1823 * @return {object}
1824 */
1825function getCompositionEventType(topLevelType) {
1826 switch (topLevelType) {
1827 case TOP_COMPOSITION_START:
1828 return eventTypes.compositionStart;
1829 case TOP_COMPOSITION_END:
1830 return eventTypes.compositionEnd;
1831 case TOP_COMPOSITION_UPDATE:
1832 return eventTypes.compositionUpdate;
1833 }
1834}
1835
1836/**
1837 * Does our fallback best-guess model think this event signifies that
1838 * composition has begun?
1839 *
1840 * @param {string} topLevelType
1841 * @param {object} nativeEvent
1842 * @return {boolean}
1843 */
1844function isFallbackCompositionStart(topLevelType, nativeEvent) {
1845 return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;
1846}
1847
1848/**
1849 * Does our fallback mode think that this event is the end of composition?
1850 *
1851 * @param {string} topLevelType
1852 * @param {object} nativeEvent
1853 * @return {boolean}
1854 */
1855function isFallbackCompositionEnd(topLevelType, nativeEvent) {
1856 switch (topLevelType) {
1857 case TOP_KEY_UP:
1858 // Command keys insert or clear IME input.
1859 return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
1860 case TOP_KEY_DOWN:
1861 // Expect IME keyCode on each keydown. If we get any other
1862 // code we must have exited earlier.
1863 return nativeEvent.keyCode !== START_KEYCODE;
1864 case TOP_KEY_PRESS:
1865 case TOP_MOUSE_DOWN:
1866 case TOP_BLUR:
1867 // Events are not possible without cancelling IME.
1868 return true;
1869 default:
1870 return false;
1871 }
1872}
1873
1874/**
1875 * Google Input Tools provides composition data via a CustomEvent,
1876 * with the `data` property populated in the `detail` object. If this
1877 * is available on the event object, use it. If not, this is a plain
1878 * composition event and we have nothing special to extract.
1879 *
1880 * @param {object} nativeEvent
1881 * @return {?string}
1882 */
1883function getDataFromCustomEvent(nativeEvent) {
1884 var detail = nativeEvent.detail;
1885 if (typeof detail === 'object' && 'data' in detail) {
1886 return detail.data;
1887 }
1888 return null;
1889}
1890
1891/**
1892 * Check if a composition event was triggered by Korean IME.
1893 * Our fallback mode does not work well with IE's Korean IME,
1894 * so just use native composition events when Korean IME is used.
1895 * Although CompositionEvent.locale property is deprecated,
1896 * it is available in IE, where our fallback mode is enabled.
1897 *
1898 * @param {object} nativeEvent
1899 * @return {boolean}
1900 */
1901function isUsingKoreanIME(nativeEvent) {
1902 return nativeEvent.locale === 'ko';
1903}
1904
1905// Track the current IME composition status, if any.
1906var isComposing = false;
1907
1908/**
1909 * @return {?object} A SyntheticCompositionEvent.
1910 */
1911function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
1912 var eventType = void 0;
1913 var fallbackData = void 0;
1914
1915 if (canUseCompositionEvent) {
1916 eventType = getCompositionEventType(topLevelType);
1917 } else if (!isComposing) {
1918 if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
1919 eventType = eventTypes.compositionStart;
1920 }
1921 } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
1922 eventType = eventTypes.compositionEnd;
1923 }
1924
1925 if (!eventType) {
1926 return null;
1927 }
1928
1929 if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
1930 // The current composition is stored statically and must not be
1931 // overwritten while composition continues.
1932 if (!isComposing && eventType === eventTypes.compositionStart) {
1933 isComposing = initialize(nativeEventTarget);
1934 } else if (eventType === eventTypes.compositionEnd) {
1935 if (isComposing) {
1936 fallbackData = getData();
1937 }
1938 }
1939 }
1940
1941 var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
1942
1943 if (fallbackData) {
1944 // Inject data generated from fallback path into the synthetic event.
1945 // This matches the property of native CompositionEventInterface.
1946 event.data = fallbackData;
1947 } else {
1948 var customData = getDataFromCustomEvent(nativeEvent);
1949 if (customData !== null) {
1950 event.data = customData;
1951 }
1952 }
1953
1954 accumulateTwoPhaseDispatches(event);
1955 return event;
1956}
1957
1958/**
1959 * @param {TopLevelType} topLevelType Number from `TopLevelType`.
1960 * @param {object} nativeEvent Native browser event.
1961 * @return {?string} The string corresponding to this `beforeInput` event.
1962 */
1963function getNativeBeforeInputChars(topLevelType, nativeEvent) {
1964 switch (topLevelType) {
1965 case TOP_COMPOSITION_END:
1966 return getDataFromCustomEvent(nativeEvent);
1967 case TOP_KEY_PRESS:
1968 /**
1969 * If native `textInput` events are available, our goal is to make
1970 * use of them. However, there is a special case: the spacebar key.
1971 * In Webkit, preventing default on a spacebar `textInput` event
1972 * cancels character insertion, but it *also* causes the browser
1973 * to fall back to its default spacebar behavior of scrolling the
1974 * page.
1975 *
1976 * Tracking at:
1977 * https://code.google.com/p/chromium/issues/detail?id=355103
1978 *
1979 * To avoid this issue, use the keypress event as if no `textInput`
1980 * event is available.
1981 */
1982 var which = nativeEvent.which;
1983 if (which !== SPACEBAR_CODE) {
1984 return null;
1985 }
1986
1987 hasSpaceKeypress = true;
1988 return SPACEBAR_CHAR;
1989
1990 case TOP_TEXT_INPUT:
1991 // Record the characters to be added to the DOM.
1992 var chars = nativeEvent.data;
1993
1994 // If it's a spacebar character, assume that we have already handled
1995 // it at the keypress level and bail immediately. Android Chrome
1996 // doesn't give us keycodes, so we need to ignore it.
1997 if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
1998 return null;
1999 }
2000
2001 return chars;
2002
2003 default:
2004 // For other native event types, do nothing.
2005 return null;
2006 }
2007}
2008
2009/**
2010 * For browsers that do not provide the `textInput` event, extract the
2011 * appropriate string to use for SyntheticInputEvent.
2012 *
2013 * @param {number} topLevelType Number from `TopLevelEventTypes`.
2014 * @param {object} nativeEvent Native browser event.
2015 * @return {?string} The fallback string for this `beforeInput` event.
2016 */
2017function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
2018 // If we are currently composing (IME) and using a fallback to do so,
2019 // try to extract the composed characters from the fallback object.
2020 // If composition event is available, we extract a string only at
2021 // compositionevent, otherwise extract it at fallback events.
2022 if (isComposing) {
2023 if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {
2024 var chars = getData();
2025 reset();
2026 isComposing = false;
2027 return chars;
2028 }
2029 return null;
2030 }
2031
2032 switch (topLevelType) {
2033 case TOP_PASTE:
2034 // If a paste event occurs after a keypress, throw out the input
2035 // chars. Paste events should not lead to BeforeInput events.
2036 return null;
2037 case TOP_KEY_PRESS:
2038 /**
2039 * As of v27, Firefox may fire keypress events even when no character
2040 * will be inserted. A few possibilities:
2041 *
2042 * - `which` is `0`. Arrow keys, Esc key, etc.
2043 *
2044 * - `which` is the pressed key code, but no char is available.
2045 * Ex: 'AltGr + d` in Polish. There is no modified character for
2046 * this key combination and no character is inserted into the
2047 * document, but FF fires the keypress for char code `100` anyway.
2048 * No `input` event will occur.
2049 *
2050 * - `which` is the pressed key code, but a command combination is
2051 * being used. Ex: `Cmd+C`. No character is inserted, and no
2052 * `input` event will occur.
2053 */
2054 if (!isKeypressCommand(nativeEvent)) {
2055 // IE fires the `keypress` event when a user types an emoji via
2056 // Touch keyboard of Windows. In such a case, the `char` property
2057 // holds an emoji character like `\uD83D\uDE0A`. Because its length
2058 // is 2, the property `which` does not represent an emoji correctly.
2059 // In such a case, we directly return the `char` property instead of
2060 // using `which`.
2061 if (nativeEvent.char && nativeEvent.char.length > 1) {
2062 return nativeEvent.char;
2063 } else if (nativeEvent.which) {
2064 return String.fromCharCode(nativeEvent.which);
2065 }
2066 }
2067 return null;
2068 case TOP_COMPOSITION_END:
2069 return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
2070 default:
2071 return null;
2072 }
2073}
2074
2075/**
2076 * Extract a SyntheticInputEvent for `beforeInput`, based on either native
2077 * `textInput` or fallback behavior.
2078 *
2079 * @return {?object} A SyntheticInputEvent.
2080 */
2081function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
2082 var chars = void 0;
2083
2084 if (canUseTextInputEvent) {
2085 chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
2086 } else {
2087 chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
2088 }
2089
2090 // If no characters are being inserted, no BeforeInput event should
2091 // be fired.
2092 if (!chars) {
2093 return null;
2094 }
2095
2096 var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);
2097
2098 event.data = chars;
2099 accumulateTwoPhaseDispatches(event);
2100 return event;
2101}
2102
2103/**
2104 * Create an `onBeforeInput` event to match
2105 * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
2106 *
2107 * This event plugin is based on the native `textInput` event
2108 * available in Chrome, Safari, Opera, and IE. This event fires after
2109 * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
2110 *
2111 * `beforeInput` is spec'd but not implemented in any browsers, and
2112 * the `input` event does not provide any useful information about what has
2113 * actually been added, contrary to the spec. Thus, `textInput` is the best
2114 * available event to identify the characters that have actually been inserted
2115 * into the target node.
2116 *
2117 * This plugin is also responsible for emitting `composition` events, thus
2118 * allowing us to share composition fallback code for both `beforeInput` and
2119 * `composition` event types.
2120 */
2121var BeforeInputEventPlugin = {
2122 eventTypes: eventTypes,
2123
2124 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
2125 var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
2126
2127 var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
2128
2129 if (composition === null) {
2130 return beforeInput;
2131 }
2132
2133 if (beforeInput === null) {
2134 return composition;
2135 }
2136
2137 return [composition, beforeInput];
2138 }
2139};
2140
2141// Use to restore controlled state after a change event has fired.
2142
2143var restoreImpl = null;
2144var restoreTarget = null;
2145var restoreQueue = null;
2146
2147function restoreStateOfTarget(target) {
2148 // We perform this translation at the end of the event loop so that we
2149 // always receive the correct fiber here
2150 var internalInstance = getInstanceFromNode(target);
2151 if (!internalInstance) {
2152 // Unmounted
2153 return;
2154 }
2155 (function () {
2156 if (!(typeof restoreImpl === 'function')) {
2157 {
2158 throw ReactError('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.');
2159 }
2160 }
2161 })();
2162 var props = getFiberCurrentPropsFromNode(internalInstance.stateNode);
2163 restoreImpl(internalInstance.stateNode, internalInstance.type, props);
2164}
2165
2166function setRestoreImplementation(impl) {
2167 restoreImpl = impl;
2168}
2169
2170function enqueueStateRestore(target) {
2171 if (restoreTarget) {
2172 if (restoreQueue) {
2173 restoreQueue.push(target);
2174 } else {
2175 restoreQueue = [target];
2176 }
2177 } else {
2178 restoreTarget = target;
2179 }
2180}
2181
2182function needsStateRestore() {
2183 return restoreTarget !== null || restoreQueue !== null;
2184}
2185
2186function restoreStateIfNeeded() {
2187 if (!restoreTarget) {
2188 return;
2189 }
2190 var target = restoreTarget;
2191 var queuedTargets = restoreQueue;
2192 restoreTarget = null;
2193 restoreQueue = null;
2194
2195 restoreStateOfTarget(target);
2196 if (queuedTargets) {
2197 for (var i = 0; i < queuedTargets.length; i++) {
2198 restoreStateOfTarget(queuedTargets[i]);
2199 }
2200 }
2201}
2202
2203// Used as a way to call batchedUpdates when we don't have a reference to
2204// the renderer. Such as when we're dispatching events or if third party
2205// libraries need to call batchedUpdates. Eventually, this API will go away when
2206// everything is batched by default. We'll then have a similar API to opt-out of
2207// scheduled work and instead do synchronous work.
2208
2209// Defaults
2210var _batchedUpdatesImpl = function (fn, bookkeeping) {
2211 return fn(bookkeeping);
2212};
2213var _interactiveUpdatesImpl = function (fn, a, b, c) {
2214 return fn(a, b, c);
2215};
2216var _flushInteractiveUpdatesImpl = function () {};
2217
2218var isBatching = false;
2219function batchedUpdates(fn, bookkeeping) {
2220 if (isBatching) {
2221 // If we are currently inside another batch, we need to wait until it
2222 // fully completes before restoring state.
2223 return fn(bookkeeping);
2224 }
2225 isBatching = true;
2226 try {
2227 return _batchedUpdatesImpl(fn, bookkeeping);
2228 } finally {
2229 // Here we wait until all updates have propagated, which is important
2230 // when using controlled components within layers:
2231 // https://github.com/facebook/react/issues/1698
2232 // Then we restore state of any controlled component.
2233 isBatching = false;
2234 var controlledComponentsHavePendingUpdates = needsStateRestore();
2235 if (controlledComponentsHavePendingUpdates) {
2236 // If a controlled event was fired, we may need to restore the state of
2237 // the DOM node back to the controlled value. This is necessary when React
2238 // bails out of the update without touching the DOM.
2239 _flushInteractiveUpdatesImpl();
2240 restoreStateIfNeeded();
2241 }
2242 }
2243}
2244
2245function interactiveUpdates(fn, a, b, c) {
2246 return _interactiveUpdatesImpl(fn, a, b, c);
2247}
2248
2249
2250
2251function setBatchingImplementation(batchedUpdatesImpl, interactiveUpdatesImpl, flushInteractiveUpdatesImpl) {
2252 _batchedUpdatesImpl = batchedUpdatesImpl;
2253 _interactiveUpdatesImpl = interactiveUpdatesImpl;
2254 _flushInteractiveUpdatesImpl = flushInteractiveUpdatesImpl;
2255}
2256
2257/**
2258 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
2259 */
2260var supportedInputTypes = {
2261 color: true,
2262 date: true,
2263 datetime: true,
2264 'datetime-local': true,
2265 email: true,
2266 month: true,
2267 number: true,
2268 password: true,
2269 range: true,
2270 search: true,
2271 tel: true,
2272 text: true,
2273 time: true,
2274 url: true,
2275 week: true
2276};
2277
2278function isTextInputElement(elem) {
2279 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
2280
2281 if (nodeName === 'input') {
2282 return !!supportedInputTypes[elem.type];
2283 }
2284
2285 if (nodeName === 'textarea') {
2286 return true;
2287 }
2288
2289 return false;
2290}
2291
2292/**
2293 * HTML nodeType values that represent the type of the node
2294 */
2295
2296var ELEMENT_NODE = 1;
2297var TEXT_NODE = 3;
2298var COMMENT_NODE = 8;
2299var DOCUMENT_NODE = 9;
2300var DOCUMENT_FRAGMENT_NODE = 11;
2301
2302/**
2303 * Gets the target node from a native browser event by accounting for
2304 * inconsistencies in browser DOM APIs.
2305 *
2306 * @param {object} nativeEvent Native browser event.
2307 * @return {DOMEventTarget} Target node.
2308 */
2309function getEventTarget(nativeEvent) {
2310 // Fallback to nativeEvent.srcElement for IE9
2311 // https://github.com/facebook/react/issues/12506
2312 var target = nativeEvent.target || nativeEvent.srcElement || window;
2313
2314 // Normalize SVG <use> element events #4963
2315 if (target.correspondingUseElement) {
2316 target = target.correspondingUseElement;
2317 }
2318
2319 // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
2320 // @see http://www.quirksmode.org/js/events_properties.html
2321 return target.nodeType === TEXT_NODE ? target.parentNode : target;
2322}
2323
2324/**
2325 * Checks if an event is supported in the current execution environment.
2326 *
2327 * NOTE: This will not work correctly for non-generic events such as `change`,
2328 * `reset`, `load`, `error`, and `select`.
2329 *
2330 * Borrows from Modernizr.
2331 *
2332 * @param {string} eventNameSuffix Event name, e.g. "click".
2333 * @return {boolean} True if the event is supported.
2334 * @internal
2335 * @license Modernizr 3.0.0pre (Custom Build) | MIT
2336 */
2337function isEventSupported(eventNameSuffix) {
2338 if (!canUseDOM) {
2339 return false;
2340 }
2341
2342 var eventName = 'on' + eventNameSuffix;
2343 var isSupported = eventName in document;
2344
2345 if (!isSupported) {
2346 var element = document.createElement('div');
2347 element.setAttribute(eventName, 'return;');
2348 isSupported = typeof element[eventName] === 'function';
2349 }
2350
2351 return isSupported;
2352}
2353
2354function isCheckable(elem) {
2355 var type = elem.type;
2356 var nodeName = elem.nodeName;
2357 return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
2358}
2359
2360function getTracker(node) {
2361 return node._valueTracker;
2362}
2363
2364function detachTracker(node) {
2365 node._valueTracker = null;
2366}
2367
2368function getValueFromNode(node) {
2369 var value = '';
2370 if (!node) {
2371 return value;
2372 }
2373
2374 if (isCheckable(node)) {
2375 value = node.checked ? 'true' : 'false';
2376 } else {
2377 value = node.value;
2378 }
2379
2380 return value;
2381}
2382
2383function trackValueOnNode(node) {
2384 var valueField = isCheckable(node) ? 'checked' : 'value';
2385 var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
2386
2387 var currentValue = '' + node[valueField];
2388
2389 // if someone has already defined a value or Safari, then bail
2390 // and don't track value will cause over reporting of changes,
2391 // but it's better then a hard failure
2392 // (needed for certain tests that spyOn input values and Safari)
2393 if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
2394 return;
2395 }
2396 var get = descriptor.get,
2397 set = descriptor.set;
2398
2399 Object.defineProperty(node, valueField, {
2400 configurable: true,
2401 get: function () {
2402 return get.call(this);
2403 },
2404 set: function (value) {
2405 currentValue = '' + value;
2406 set.call(this, value);
2407 }
2408 });
2409 // We could've passed this the first time
2410 // but it triggers a bug in IE11 and Edge 14/15.
2411 // Calling defineProperty() again should be equivalent.
2412 // https://github.com/facebook/react/issues/11768
2413 Object.defineProperty(node, valueField, {
2414 enumerable: descriptor.enumerable
2415 });
2416
2417 var tracker = {
2418 getValue: function () {
2419 return currentValue;
2420 },
2421 setValue: function (value) {
2422 currentValue = '' + value;
2423 },
2424 stopTracking: function () {
2425 detachTracker(node);
2426 delete node[valueField];
2427 }
2428 };
2429 return tracker;
2430}
2431
2432function track(node) {
2433 if (getTracker(node)) {
2434 return;
2435 }
2436
2437 // TODO: Once it's just Fiber we can move this to node._wrapperState
2438 node._valueTracker = trackValueOnNode(node);
2439}
2440
2441function updateValueIfChanged(node) {
2442 if (!node) {
2443 return false;
2444 }
2445
2446 var tracker = getTracker(node);
2447 // if there is no tracker at this point it's unlikely
2448 // that trying again will succeed
2449 if (!tracker) {
2450 return true;
2451 }
2452
2453 var lastValue = tracker.getValue();
2454 var nextValue = getValueFromNode(node);
2455 if (nextValue !== lastValue) {
2456 tracker.setValue(nextValue);
2457 return true;
2458 }
2459 return false;
2460}
2461
2462var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
2463
2464// Prevent newer renderers from RTE when used with older react package versions.
2465// Current owner and dispatcher used to share the same ref,
2466// but PR #14548 split them out to better support the react-debug-tools package.
2467if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
2468 ReactSharedInternals.ReactCurrentDispatcher = {
2469 current: null
2470 };
2471}
2472
2473var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
2474
2475var describeComponentFrame = function (name, source, ownerName) {
2476 var sourceInfo = '';
2477 if (source) {
2478 var path = source.fileName;
2479 var fileName = path.replace(BEFORE_SLASH_RE, '');
2480 {
2481 // In DEV, include code for a common special case:
2482 // prefer "folder/index.js" instead of just "index.js".
2483 if (/^index\./.test(fileName)) {
2484 var match = path.match(BEFORE_SLASH_RE);
2485 if (match) {
2486 var pathBeforeSlash = match[1];
2487 if (pathBeforeSlash) {
2488 var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
2489 fileName = folderName + '/' + fileName;
2490 }
2491 }
2492 }
2493 }
2494 sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
2495 } else if (ownerName) {
2496 sourceInfo = ' (created by ' + ownerName + ')';
2497 }
2498 return '\n in ' + (name || 'Unknown') + sourceInfo;
2499};
2500
2501// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
2502// nor polyfill, then a plain number is used for performance.
2503var hasSymbol = typeof Symbol === 'function' && Symbol.for;
2504
2505var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
2506var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
2507var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
2508var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
2509var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
2510var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
2511var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
2512
2513var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
2514var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
2515var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
2516var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
2517var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
2518var REACT_EVENT_COMPONENT_TYPE = hasSymbol ? Symbol.for('react.event_component') : 0xead5;
2519var REACT_EVENT_TARGET_TYPE = hasSymbol ? Symbol.for('react.event_target') : 0xead6;
2520
2521// React event targets
2522var REACT_EVENT_TARGET_TOUCH_HIT = hasSymbol ? Symbol.for('react.event_target.touch_hit') : 0xead7;
2523
2524var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
2525var FAUX_ITERATOR_SYMBOL = '@@iterator';
2526
2527function getIteratorFn(maybeIterable) {
2528 if (maybeIterable === null || typeof maybeIterable !== 'object') {
2529 return null;
2530 }
2531 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
2532 if (typeof maybeIterator === 'function') {
2533 return maybeIterator;
2534 }
2535 return null;
2536}
2537
2538var Pending = 0;
2539var Resolved = 1;
2540var Rejected = 2;
2541
2542function refineResolvedLazyComponent(lazyComponent) {
2543 return lazyComponent._status === Resolved ? lazyComponent._result : null;
2544}
2545
2546function getWrappedName(outerType, innerType, wrapperName) {
2547 var functionName = innerType.displayName || innerType.name || '';
2548 return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName);
2549}
2550
2551function getComponentName(type) {
2552 if (type == null) {
2553 // Host root, text node or just invalid type.
2554 return null;
2555 }
2556 {
2557 if (typeof type.tag === 'number') {
2558 warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
2559 }
2560 }
2561 if (typeof type === 'function') {
2562 return type.displayName || type.name || null;
2563 }
2564 if (typeof type === 'string') {
2565 return type;
2566 }
2567 switch (type) {
2568 case REACT_CONCURRENT_MODE_TYPE:
2569 return 'ConcurrentMode';
2570 case REACT_FRAGMENT_TYPE:
2571 return 'Fragment';
2572 case REACT_PORTAL_TYPE:
2573 return 'Portal';
2574 case REACT_PROFILER_TYPE:
2575 return 'Profiler';
2576 case REACT_STRICT_MODE_TYPE:
2577 return 'StrictMode';
2578 case REACT_SUSPENSE_TYPE:
2579 return 'Suspense';
2580 }
2581 if (typeof type === 'object') {
2582 switch (type.$$typeof) {
2583 case REACT_CONTEXT_TYPE:
2584 return 'Context.Consumer';
2585 case REACT_PROVIDER_TYPE:
2586 return 'Context.Provider';
2587 case REACT_FORWARD_REF_TYPE:
2588 return getWrappedName(type, type.render, 'ForwardRef');
2589 case REACT_MEMO_TYPE:
2590 return getComponentName(type.type);
2591 case REACT_LAZY_TYPE:
2592 {
2593 var thenable = type;
2594 var resolvedThenable = refineResolvedLazyComponent(thenable);
2595 if (resolvedThenable) {
2596 return getComponentName(resolvedThenable);
2597 }
2598 break;
2599 }
2600 case REACT_EVENT_COMPONENT_TYPE:
2601 {
2602 var eventComponent = type;
2603 var displayName = eventComponent.displayName;
2604 if (displayName !== undefined) {
2605 return displayName;
2606 }
2607 break;
2608 }
2609 case REACT_EVENT_TARGET_TYPE:
2610 {
2611 var eventTarget = type;
2612 if (eventTarget.type === REACT_EVENT_TARGET_TOUCH_HIT) {
2613 return 'TouchHitTarget';
2614 }
2615 var _displayName = eventTarget.displayName;
2616 if (_displayName !== undefined) {
2617 return _displayName;
2618 }
2619 }
2620 }
2621 }
2622 return null;
2623}
2624
2625var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
2626
2627function describeFiber(fiber) {
2628 switch (fiber.tag) {
2629 case HostRoot:
2630 case HostPortal:
2631 case HostText:
2632 case Fragment:
2633 case ContextProvider:
2634 case ContextConsumer:
2635 return '';
2636 default:
2637 var owner = fiber._debugOwner;
2638 var source = fiber._debugSource;
2639 var name = getComponentName(fiber.type);
2640 var ownerName = null;
2641 if (owner) {
2642 ownerName = getComponentName(owner.type);
2643 }
2644 return describeComponentFrame(name, source, ownerName);
2645 }
2646}
2647
2648function getStackByFiberInDevAndProd(workInProgress) {
2649 var info = '';
2650 var node = workInProgress;
2651 do {
2652 info += describeFiber(node);
2653 node = node.return;
2654 } while (node);
2655 return info;
2656}
2657
2658var current = null;
2659var phase = null;
2660
2661function getCurrentFiberOwnerNameInDevOrNull() {
2662 {
2663 if (current === null) {
2664 return null;
2665 }
2666 var owner = current._debugOwner;
2667 if (owner !== null && typeof owner !== 'undefined') {
2668 return getComponentName(owner.type);
2669 }
2670 }
2671 return null;
2672}
2673
2674function getCurrentFiberStackInDev() {
2675 {
2676 if (current === null) {
2677 return '';
2678 }
2679 // Safe because if current fiber exists, we are reconciling,
2680 // and it is guaranteed to be the work-in-progress version.
2681 return getStackByFiberInDevAndProd(current);
2682 }
2683 return '';
2684}
2685
2686function resetCurrentFiber() {
2687 {
2688 ReactDebugCurrentFrame.getCurrentStack = null;
2689 current = null;
2690 phase = null;
2691 }
2692}
2693
2694function setCurrentFiber(fiber) {
2695 {
2696 ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev;
2697 current = fiber;
2698 phase = null;
2699 }
2700}
2701
2702function setCurrentPhase(lifeCyclePhase) {
2703 {
2704 phase = lifeCyclePhase;
2705 }
2706}
2707
2708/**
2709 * Similar to invariant but only logs a warning if the condition is not met.
2710 * This can be used to log issues in development environments in critical
2711 * paths. Removing the logging code for production environments will keep the
2712 * same logic and follow the same code paths.
2713 */
2714
2715var warning = warningWithoutStack$1;
2716
2717{
2718 warning = function (condition, format) {
2719 if (condition) {
2720 return;
2721 }
2722 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
2723 var stack = ReactDebugCurrentFrame.getStackAddendum();
2724 // eslint-disable-next-line react-internal/warning-and-invariant-args
2725
2726 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
2727 args[_key - 2] = arguments[_key];
2728 }
2729
2730 warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack]));
2731 };
2732}
2733
2734var warning$1 = warning;
2735
2736// A reserved attribute.
2737// It is handled by React separately and shouldn't be written to the DOM.
2738var RESERVED = 0;
2739
2740// A simple string attribute.
2741// Attributes that aren't in the whitelist are presumed to have this type.
2742var STRING = 1;
2743
2744// A string attribute that accepts booleans in React. In HTML, these are called
2745// "enumerated" attributes with "true" and "false" as possible values.
2746// When true, it should be set to a "true" string.
2747// When false, it should be set to a "false" string.
2748var BOOLEANISH_STRING = 2;
2749
2750// A real boolean attribute.
2751// When true, it should be present (set either to an empty string or its name).
2752// When false, it should be omitted.
2753var BOOLEAN = 3;
2754
2755// An attribute that can be used as a flag as well as with a value.
2756// When true, it should be present (set either to an empty string or its name).
2757// When false, it should be omitted.
2758// For any other value, should be present with that value.
2759var OVERLOADED_BOOLEAN = 4;
2760
2761// An attribute that must be numeric or parse as a numeric.
2762// When falsy, it should be removed.
2763var NUMERIC = 5;
2764
2765// An attribute that must be positive numeric or parse as a positive numeric.
2766// When falsy, it should be removed.
2767var POSITIVE_NUMERIC = 6;
2768
2769/* eslint-disable max-len */
2770var 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';
2771/* eslint-enable max-len */
2772var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040';
2773
2774
2775var ROOT_ATTRIBUTE_NAME = 'data-reactroot';
2776var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
2777
2778var hasOwnProperty = Object.prototype.hasOwnProperty;
2779var illegalAttributeNameCache = {};
2780var validatedAttributeNameCache = {};
2781
2782function isAttributeNameSafe(attributeName) {
2783 if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
2784 return true;
2785 }
2786 if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
2787 return false;
2788 }
2789 if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
2790 validatedAttributeNameCache[attributeName] = true;
2791 return true;
2792 }
2793 illegalAttributeNameCache[attributeName] = true;
2794 {
2795 warning$1(false, 'Invalid attribute name: `%s`', attributeName);
2796 }
2797 return false;
2798}
2799
2800function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
2801 if (propertyInfo !== null) {
2802 return propertyInfo.type === RESERVED;
2803 }
2804 if (isCustomComponentTag) {
2805 return false;
2806 }
2807 if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
2808 return true;
2809 }
2810 return false;
2811}
2812
2813function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
2814 if (propertyInfo !== null && propertyInfo.type === RESERVED) {
2815 return false;
2816 }
2817 switch (typeof value) {
2818 case 'function':
2819 // $FlowIssue symbol is perfectly valid here
2820 case 'symbol':
2821 // eslint-disable-line
2822 return true;
2823 case 'boolean':
2824 {
2825 if (isCustomComponentTag) {
2826 return false;
2827 }
2828 if (propertyInfo !== null) {
2829 return !propertyInfo.acceptsBooleans;
2830 } else {
2831 var prefix = name.toLowerCase().slice(0, 5);
2832 return prefix !== 'data-' && prefix !== 'aria-';
2833 }
2834 }
2835 default:
2836 return false;
2837 }
2838}
2839
2840function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
2841 if (value === null || typeof value === 'undefined') {
2842 return true;
2843 }
2844 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
2845 return true;
2846 }
2847 if (isCustomComponentTag) {
2848 return false;
2849 }
2850 if (propertyInfo !== null) {
2851 switch (propertyInfo.type) {
2852 case BOOLEAN:
2853 return !value;
2854 case OVERLOADED_BOOLEAN:
2855 return value === false;
2856 case NUMERIC:
2857 return isNaN(value);
2858 case POSITIVE_NUMERIC:
2859 return isNaN(value) || value < 1;
2860 }
2861 }
2862 return false;
2863}
2864
2865function getPropertyInfo(name) {
2866 return properties.hasOwnProperty(name) ? properties[name] : null;
2867}
2868
2869function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL) {
2870 this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
2871 this.attributeName = attributeName;
2872 this.attributeNamespace = attributeNamespace;
2873 this.mustUseProperty = mustUseProperty;
2874 this.propertyName = name;
2875 this.type = type;
2876 this.sanitizeURL = sanitizeURL;
2877}
2878
2879// When adding attributes to this list, be sure to also add them to
2880// the `possibleStandardNames` module to ensure casing and incorrect
2881// name warnings.
2882var properties = {};
2883
2884// These props are reserved by React. They shouldn't be written to the DOM.
2885['children', 'dangerouslySetInnerHTML',
2886// TODO: This prevents the assignment of defaultValue to regular
2887// elements (not just inputs). Now that ReactDOMInput assigns to the
2888// defaultValue property -- do we need this?
2889'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'].forEach(function (name) {
2890 properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
2891 name, // attributeName
2892 null, // attributeNamespace
2893 false);
2894} // sanitizeURL
2895);
2896
2897// A few React string attributes have a different name.
2898// This is a mapping from React prop names to the attribute names.
2899[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
2900 var name = _ref[0],
2901 attributeName = _ref[1];
2902
2903 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2904 attributeName, // attributeName
2905 null, // attributeNamespace
2906 false);
2907} // sanitizeURL
2908);
2909
2910// These are "enumerated" HTML attributes that accept "true" and "false".
2911// In React, we let users pass `true` and `false` even though technically
2912// these aren't boolean attributes (they are coerced to strings).
2913['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
2914 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2915 name.toLowerCase(), // attributeName
2916 null, // attributeNamespace
2917 false);
2918} // sanitizeURL
2919);
2920
2921// These are "enumerated" SVG attributes that accept "true" and "false".
2922// In React, we let users pass `true` and `false` even though technically
2923// these aren't boolean attributes (they are coerced to strings).
2924// Since these are SVG attributes, their attribute names are case-sensitive.
2925['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
2926 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2927 name, // attributeName
2928 null, // attributeNamespace
2929 false);
2930} // sanitizeURL
2931);
2932
2933// These are HTML boolean attributes.
2934['allowFullScreen', 'async',
2935// Note: there is a special case that prevents it from being written to the DOM
2936// on the client side because the browsers are inconsistent. Instead we call focus().
2937'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless',
2938// Microdata
2939'itemScope'].forEach(function (name) {
2940 properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
2941 name.toLowerCase(), // attributeName
2942 null, // attributeNamespace
2943 false);
2944} // sanitizeURL
2945);
2946
2947// These are the few React props that we set as DOM properties
2948// rather than attributes. These are all booleans.
2949['checked',
2950// Note: `option.selected` is not updated if `select.multiple` is
2951// disabled with `removeAttribute`. We have special logic for handling this.
2952'multiple', 'muted', 'selected'].forEach(function (name) {
2953 properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
2954 name, // attributeName
2955 null, // attributeNamespace
2956 false);
2957} // sanitizeURL
2958);
2959
2960// These are HTML attributes that are "overloaded booleans": they behave like
2961// booleans, but can also accept a string value.
2962['capture', 'download'].forEach(function (name) {
2963 properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
2964 name, // attributeName
2965 null, // attributeNamespace
2966 false);
2967} // sanitizeURL
2968);
2969
2970// These are HTML attributes that must be positive numbers.
2971['cols', 'rows', 'size', 'span'].forEach(function (name) {
2972 properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
2973 name, // attributeName
2974 null, // attributeNamespace
2975 false);
2976} // sanitizeURL
2977);
2978
2979// These are HTML attributes that must be numbers.
2980['rowSpan', 'start'].forEach(function (name) {
2981 properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
2982 name.toLowerCase(), // attributeName
2983 null, // attributeNamespace
2984 false);
2985} // sanitizeURL
2986);
2987
2988var CAMELIZE = /[\-\:]([a-z])/g;
2989var capitalize = function (token) {
2990 return token[1].toUpperCase();
2991};
2992
2993// This is a list of all SVG attributes that need special casing, namespacing,
2994// or boolean value assignment. Regular attributes that just accept strings
2995// and have the same names are omitted, just like in the HTML whitelist.
2996// Some of these attributes can be hard to find. This list was created by
2997// scrapping the MDN documentation.
2998['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) {
2999 var name = attributeName.replace(CAMELIZE, capitalize);
3000 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
3001 attributeName, null, // attributeNamespace
3002 false);
3003} // sanitizeURL
3004);
3005
3006// String SVG attributes with the xlink namespace.
3007['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type'].forEach(function (attributeName) {
3008 var name = attributeName.replace(CAMELIZE, capitalize);
3009 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
3010 attributeName, 'http://www.w3.org/1999/xlink', false);
3011} // sanitizeURL
3012);
3013
3014// String SVG attributes with the xml namespace.
3015['xml:base', 'xml:lang', 'xml:space'].forEach(function (attributeName) {
3016 var name = attributeName.replace(CAMELIZE, capitalize);
3017 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
3018 attributeName, 'http://www.w3.org/XML/1998/namespace', false);
3019} // sanitizeURL
3020);
3021
3022// These attribute exists both in HTML and SVG.
3023// The attribute name is case-sensitive in SVG so we can't just use
3024// the React name like we do for attributes that exist only in HTML.
3025['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
3026 properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
3027 attributeName.toLowerCase(), // attributeName
3028 null, // attributeNamespace
3029 false);
3030} // sanitizeURL
3031);
3032
3033// These attributes accept URLs. These must not allow javascript: URLS.
3034// These will also need to accept Trusted Types object in the future.
3035var xlinkHref = 'xlinkHref';
3036properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
3037'xlink:href', 'http://www.w3.org/1999/xlink', true);
3038
3039['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
3040 properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
3041 attributeName.toLowerCase(), // attributeName
3042 null, // attributeNamespace
3043 true);
3044} // sanitizeURL
3045);
3046
3047var enableUserTimingAPI = true;
3048
3049// Helps identify side effects in begin-phase lifecycle hooks and setState reducers:
3050var debugRenderPhaseSideEffects = false;
3051
3052// In some cases, StrictMode should also double-render lifecycles.
3053// This can be confusing for tests though,
3054// And it can be bad for performance in production.
3055// This feature flag can be used to control the behavior:
3056var debugRenderPhaseSideEffectsForStrictMode = true;
3057
3058// To preserve the "Pause on caught exceptions" behavior of the debugger, we
3059// replay the begin phase of a failed component inside invokeGuardedCallback.
3060var replayFailedUnitOfWorkWithInvokeGuardedCallback = true;
3061
3062// Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:
3063var warnAboutDeprecatedLifecycles = true;
3064
3065// Gather advanced timing metrics for Profiler subtrees.
3066var enableProfilerTimer = true;
3067
3068// Trace which interactions trigger each commit.
3069var enableSchedulerTracing = true;
3070
3071// Only used in www builds.
3072var enableSuspenseServerRenderer = false; // TODO: true? Here it might just be false.
3073
3074// Only used in www builds.
3075
3076
3077// Only used in www builds.
3078
3079
3080// Disable javascript: URL strings in href for XSS protection.
3081var disableJavaScriptURLs = false;
3082
3083// Disables yielding during render in Concurrent Mode. Used for debugging only.
3084var disableYielding = false;
3085
3086// React Fire: prevent the value and checked attributes from syncing
3087// with their related DOM properties
3088var disableInputAttributeSyncing = false;
3089
3090// These APIs will no longer be "unstable" in the upcoming 16.7 release,
3091// Control this behavior with a flag to support 16.6 minor releases in the meanwhile.
3092var enableStableConcurrentModeAPIs = false;
3093
3094var warnAboutShorthandPropertyCollision = false;
3095
3096// See https://github.com/react-native-community/discussions-and-proposals/issues/72 for more information
3097// This is a flag so we can fix warnings in RN core before turning it on
3098
3099
3100// Experimental React Events support. Only used in www builds for now.
3101var enableEventAPI = false;
3102
3103// Enables rewritten version of ReactFiberScheduler. Added in case we need to
3104// quickly revert it.
3105var enableNewScheduler = false;
3106
3107var ReactDebugCurrentFrame$1 = null;
3108{
3109 ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
3110}
3111
3112// A javascript: URL can contain leading C0 control or \u0020 SPACE,
3113// and any newline or tab are filtered out as if they're not part of the URL.
3114// https://url.spec.whatwg.org/#url-parsing
3115// Tab or newline are defined as \r\n\t:
3116// https://infra.spec.whatwg.org/#ascii-tab-or-newline
3117// A C0 control is a code point in the range \u0000 NULL to \u001F
3118// INFORMATION SEPARATOR ONE, inclusive:
3119// https://infra.spec.whatwg.org/#c0-control-or-space
3120
3121/* eslint-disable max-len */
3122var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
3123
3124var didWarn = false;
3125
3126function sanitizeURL(url) {
3127 if (disableJavaScriptURLs) {
3128 (function () {
3129 if (!!isJavaScriptProtocol.test(url)) {
3130 {
3131 throw ReactError('React has blocked a javascript: URL as a security precaution.' + (ReactDebugCurrentFrame$1.getStackAddendum()));
3132 }
3133 }
3134 })();
3135 } else if (true && !didWarn && isJavaScriptProtocol.test(url)) {
3136 didWarn = true;
3137 warning$1(false, 'A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
3138 }
3139}
3140
3141/**
3142 * Get the value for a property on a node. Only used in DEV for SSR validation.
3143 * The "expected" argument is used as a hint of what the expected value is.
3144 * Some properties have multiple equivalent values.
3145 */
3146function getValueForProperty(node, name, expected, propertyInfo) {
3147 {
3148 if (propertyInfo.mustUseProperty) {
3149 var propertyName = propertyInfo.propertyName;
3150
3151 return node[propertyName];
3152 } else {
3153 if (!disableJavaScriptURLs && propertyInfo.sanitizeURL) {
3154 // If we haven't fully disabled javascript: URLs, and if
3155 // the hydration is successful of a javascript: URL, we
3156 // still want to warn on the client.
3157 sanitizeURL('' + expected);
3158 }
3159
3160 var attributeName = propertyInfo.attributeName;
3161
3162 var stringValue = null;
3163
3164 if (propertyInfo.type === OVERLOADED_BOOLEAN) {
3165 if (node.hasAttribute(attributeName)) {
3166 var value = node.getAttribute(attributeName);
3167 if (value === '') {
3168 return true;
3169 }
3170 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
3171 return value;
3172 }
3173 if (value === '' + expected) {
3174 return expected;
3175 }
3176 return value;
3177 }
3178 } else if (node.hasAttribute(attributeName)) {
3179 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
3180 // We had an attribute but shouldn't have had one, so read it
3181 // for the error message.
3182 return node.getAttribute(attributeName);
3183 }
3184 if (propertyInfo.type === BOOLEAN) {
3185 // If this was a boolean, it doesn't matter what the value is
3186 // the fact that we have it is the same as the expected.
3187 return expected;
3188 }
3189 // Even if this property uses a namespace we use getAttribute
3190 // because we assume its namespaced name is the same as our config.
3191 // To use getAttributeNS we need the local name which we don't have
3192 // in our config atm.
3193 stringValue = node.getAttribute(attributeName);
3194 }
3195
3196 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
3197 return stringValue === null ? expected : stringValue;
3198 } else if (stringValue === '' + expected) {
3199 return expected;
3200 } else {
3201 return stringValue;
3202 }
3203 }
3204 }
3205}
3206
3207/**
3208 * Get the value for a attribute on a node. Only used in DEV for SSR validation.
3209 * The third argument is used as a hint of what the expected value is. Some
3210 * attributes have multiple equivalent values.
3211 */
3212function getValueForAttribute(node, name, expected) {
3213 {
3214 if (!isAttributeNameSafe(name)) {
3215 return;
3216 }
3217 if (!node.hasAttribute(name)) {
3218 return expected === undefined ? undefined : null;
3219 }
3220 var value = node.getAttribute(name);
3221 if (value === '' + expected) {
3222 return expected;
3223 }
3224 return value;
3225 }
3226}
3227
3228/**
3229 * Sets the value for a property on a node.
3230 *
3231 * @param {DOMElement} node
3232 * @param {string} name
3233 * @param {*} value
3234 */
3235function setValueForProperty(node, name, value, isCustomComponentTag) {
3236 var propertyInfo = getPropertyInfo(name);
3237 if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
3238 return;
3239 }
3240 if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
3241 value = null;
3242 }
3243 // If the prop isn't in the special list, treat it as a simple attribute.
3244 if (isCustomComponentTag || propertyInfo === null) {
3245 if (isAttributeNameSafe(name)) {
3246 var _attributeName = name;
3247 if (value === null) {
3248 node.removeAttribute(_attributeName);
3249 } else {
3250 node.setAttribute(_attributeName, '' + value);
3251 }
3252 }
3253 return;
3254 }
3255 var mustUseProperty = propertyInfo.mustUseProperty;
3256
3257 if (mustUseProperty) {
3258 var propertyName = propertyInfo.propertyName;
3259
3260 if (value === null) {
3261 var type = propertyInfo.type;
3262
3263 node[propertyName] = type === BOOLEAN ? false : '';
3264 } else {
3265 // Contrary to `setAttribute`, object properties are properly
3266 // `toString`ed by IE8/9.
3267 node[propertyName] = value;
3268 }
3269 return;
3270 }
3271 // The rest are treated as attributes with special cases.
3272 var attributeName = propertyInfo.attributeName,
3273 attributeNamespace = propertyInfo.attributeNamespace;
3274
3275 if (value === null) {
3276 node.removeAttribute(attributeName);
3277 } else {
3278 var _type = propertyInfo.type;
3279
3280 var attributeValue = void 0;
3281 if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
3282 attributeValue = '';
3283 } else {
3284 // `setAttribute` with objects becomes only `[object]` in IE8/9,
3285 // ('' + value) makes it output the correct toString()-value.
3286 attributeValue = '' + value;
3287 if (propertyInfo.sanitizeURL) {
3288 sanitizeURL(attributeValue);
3289 }
3290 }
3291 if (attributeNamespace) {
3292 node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
3293 } else {
3294 node.setAttribute(attributeName, attributeValue);
3295 }
3296 }
3297}
3298
3299// Flow does not allow string concatenation of most non-string types. To work
3300// around this limitation, we use an opaque type that can only be obtained by
3301// passing the value through getToStringValue first.
3302function toString(value) {
3303 return '' + value;
3304}
3305
3306function getToStringValue(value) {
3307 switch (typeof value) {
3308 case 'boolean':
3309 case 'number':
3310 case 'object':
3311 case 'string':
3312 case 'undefined':
3313 return value;
3314 default:
3315 // function, symbol are assigned as empty strings
3316 return '';
3317 }
3318}
3319
3320/**
3321 * Copyright (c) 2013-present, Facebook, Inc.
3322 *
3323 * This source code is licensed under the MIT license found in the
3324 * LICENSE file in the root directory of this source tree.
3325 */
3326
3327
3328
3329var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
3330
3331var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
3332
3333/**
3334 * Copyright (c) 2013-present, Facebook, Inc.
3335 *
3336 * This source code is licensed under the MIT license found in the
3337 * LICENSE file in the root directory of this source tree.
3338 */
3339
3340
3341
3342var printWarning = function() {};
3343
3344{
3345 var ReactPropTypesSecret = ReactPropTypesSecret_1;
3346 var loggedTypeFailures = {};
3347
3348 printWarning = function(text) {
3349 var message = 'Warning: ' + text;
3350 if (typeof console !== 'undefined') {
3351 console.error(message);
3352 }
3353 try {
3354 // --- Welcome to debugging React ---
3355 // This error was thrown as a convenience so that you can use this stack
3356 // to find the callsite that caused this warning to fire.
3357 throw new Error(message);
3358 } catch (x) {}
3359 };
3360}
3361
3362/**
3363 * Assert that the values match with the type specs.
3364 * Error messages are memorized and will only be shown once.
3365 *
3366 * @param {object} typeSpecs Map of name to a ReactPropType
3367 * @param {object} values Runtime values that need to be type-checked
3368 * @param {string} location e.g. "prop", "context", "child context"
3369 * @param {string} componentName Name of the component for error messages.
3370 * @param {?Function} getStack Returns the component stack.
3371 * @private
3372 */
3373function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
3374 {
3375 for (var typeSpecName in typeSpecs) {
3376 if (typeSpecs.hasOwnProperty(typeSpecName)) {
3377 var error;
3378 // Prop type validation may throw. In case they do, we don't want to
3379 // fail the render phase where it didn't fail before. So we log it.
3380 // After these have been cleaned up, we'll let them throw.
3381 try {
3382 // This is intentionally an invariant that gets caught. It's the same
3383 // behavior as without this statement except with a better message.
3384 if (typeof typeSpecs[typeSpecName] !== 'function') {
3385 var err = Error(
3386 (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
3387 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
3388 );
3389 err.name = 'Invariant Violation';
3390 throw err;
3391 }
3392 error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
3393 } catch (ex) {
3394 error = ex;
3395 }
3396 if (error && !(error instanceof Error)) {
3397 printWarning(
3398 (componentName || 'React class') + ': type specification of ' +
3399 location + ' `' + typeSpecName + '` is invalid; the type checker ' +
3400 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
3401 'You may have forgotten to pass an argument to the type checker ' +
3402 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
3403 'shape all require an argument).'
3404 );
3405
3406 }
3407 if (error instanceof Error && !(error.message in loggedTypeFailures)) {
3408 // Only monitor this failure once because there tends to be a lot of the
3409 // same error.
3410 loggedTypeFailures[error.message] = true;
3411
3412 var stack = getStack ? getStack() : '';
3413
3414 printWarning(
3415 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
3416 );
3417 }
3418 }
3419 }
3420 }
3421}
3422
3423var checkPropTypes_1 = checkPropTypes;
3424
3425var ReactDebugCurrentFrame$2 = null;
3426
3427var ReactControlledValuePropTypes = {
3428 checkPropTypes: null
3429};
3430
3431{
3432 ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame;
3433
3434 var hasReadOnlyValue = {
3435 button: true,
3436 checkbox: true,
3437 image: true,
3438 hidden: true,
3439 radio: true,
3440 reset: true,
3441 submit: true
3442 };
3443
3444 var propTypes = {
3445 value: function (props, propName, componentName) {
3446 if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null) {
3447 return null;
3448 }
3449 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`.');
3450 },
3451 checked: function (props, propName, componentName) {
3452 if (props.onChange || props.readOnly || props.disabled || props[propName] == null) {
3453 return null;
3454 }
3455 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`.');
3456 }
3457 };
3458
3459 /**
3460 * Provide a linked `value` attribute for controlled forms. You should not use
3461 * this outside of the ReactDOM controlled form components.
3462 */
3463 ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) {
3464 checkPropTypes_1(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$2.getStackAddendum);
3465 };
3466}
3467
3468// TODO: direct imports like some-package/src/* are bad. Fix me.
3469var didWarnValueDefaultValue = false;
3470var didWarnCheckedDefaultChecked = false;
3471var didWarnControlledToUncontrolled = false;
3472var didWarnUncontrolledToControlled = false;
3473
3474function isControlled(props) {
3475 var usesChecked = props.type === 'checkbox' || props.type === 'radio';
3476 return usesChecked ? props.checked != null : props.value != null;
3477}
3478
3479/**
3480 * Implements an <input> host component that allows setting these optional
3481 * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
3482 *
3483 * If `checked` or `value` are not supplied (or null/undefined), user actions
3484 * that affect the checked state or value will trigger updates to the element.
3485 *
3486 * If they are supplied (and not null/undefined), the rendered element will not
3487 * trigger updates to the element. Instead, the props must change in order for
3488 * the rendered element to be updated.
3489 *
3490 * The rendered element will be initialized as unchecked (or `defaultChecked`)
3491 * with an empty value (or `defaultValue`).
3492 *
3493 * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
3494 */
3495
3496function getHostProps(element, props) {
3497 var node = element;
3498 var checked = props.checked;
3499
3500 var hostProps = _assign({}, props, {
3501 defaultChecked: undefined,
3502 defaultValue: undefined,
3503 value: undefined,
3504 checked: checked != null ? checked : node._wrapperState.initialChecked
3505 });
3506
3507 return hostProps;
3508}
3509
3510function initWrapperState(element, props) {
3511 {
3512 ReactControlledValuePropTypes.checkPropTypes('input', props);
3513
3514 if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
3515 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);
3516 didWarnCheckedDefaultChecked = true;
3517 }
3518 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
3519 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);
3520 didWarnValueDefaultValue = true;
3521 }
3522 }
3523
3524 var node = element;
3525 var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
3526
3527 node._wrapperState = {
3528 initialChecked: props.checked != null ? props.checked : props.defaultChecked,
3529 initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
3530 controlled: isControlled(props)
3531 };
3532}
3533
3534function updateChecked(element, props) {
3535 var node = element;
3536 var checked = props.checked;
3537 if (checked != null) {
3538 setValueForProperty(node, 'checked', checked, false);
3539 }
3540}
3541
3542function updateWrapper(element, props) {
3543 var node = element;
3544 {
3545 var _controlled = isControlled(props);
3546
3547 if (!node._wrapperState.controlled && _controlled && !didWarnUncontrolledToControlled) {
3548 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);
3549 didWarnUncontrolledToControlled = true;
3550 }
3551 if (node._wrapperState.controlled && !_controlled && !didWarnControlledToUncontrolled) {
3552 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);
3553 didWarnControlledToUncontrolled = true;
3554 }
3555 }
3556
3557 updateChecked(element, props);
3558
3559 var value = getToStringValue(props.value);
3560 var type = props.type;
3561
3562 if (value != null) {
3563 if (type === 'number') {
3564 if (value === 0 && node.value === '' ||
3565 // We explicitly want to coerce to number here if possible.
3566 // eslint-disable-next-line
3567 node.value != value) {
3568 node.value = toString(value);
3569 }
3570 } else if (node.value !== toString(value)) {
3571 node.value = toString(value);
3572 }
3573 } else if (type === 'submit' || type === 'reset') {
3574 // Submit/reset inputs need the attribute removed completely to avoid
3575 // blank-text buttons.
3576 node.removeAttribute('value');
3577 return;
3578 }
3579
3580 if (disableInputAttributeSyncing) {
3581 // When not syncing the value attribute, React only assigns a new value
3582 // whenever the defaultValue React prop has changed. When not present,
3583 // React does nothing
3584 if (props.hasOwnProperty('defaultValue')) {
3585 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
3586 }
3587 } else {
3588 // When syncing the value attribute, the value comes from a cascade of
3589 // properties:
3590 // 1. The value React property
3591 // 2. The defaultValue React property
3592 // 3. Otherwise there should be no change
3593 if (props.hasOwnProperty('value')) {
3594 setDefaultValue(node, props.type, value);
3595 } else if (props.hasOwnProperty('defaultValue')) {
3596 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
3597 }
3598 }
3599
3600 if (disableInputAttributeSyncing) {
3601 // When not syncing the checked attribute, the attribute is directly
3602 // controllable from the defaultValue React property. It needs to be
3603 // updated as new props come in.
3604 if (props.defaultChecked == null) {
3605 node.removeAttribute('checked');
3606 } else {
3607 node.defaultChecked = !!props.defaultChecked;
3608 }
3609 } else {
3610 // When syncing the checked attribute, it only changes when it needs
3611 // to be removed, such as transitioning from a checkbox into a text input
3612 if (props.checked == null && props.defaultChecked != null) {
3613 node.defaultChecked = !!props.defaultChecked;
3614 }
3615 }
3616}
3617
3618function postMountWrapper(element, props, isHydrating) {
3619 var node = element;
3620
3621 // Do not assign value if it is already set. This prevents user text input
3622 // from being lost during SSR hydration.
3623 if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
3624 var type = props.type;
3625 var isButton = type === 'submit' || type === 'reset';
3626
3627 // Avoid setting value attribute on submit/reset inputs as it overrides the
3628 // default value provided by the browser. See: #12872
3629 if (isButton && (props.value === undefined || props.value === null)) {
3630 return;
3631 }
3632
3633 var _initialValue = toString(node._wrapperState.initialValue);
3634
3635 // Do not assign value if it is already set. This prevents user text input
3636 // from being lost during SSR hydration.
3637 if (!isHydrating) {
3638 if (disableInputAttributeSyncing) {
3639 var value = getToStringValue(props.value);
3640
3641 // When not syncing the value attribute, the value property points
3642 // directly to the React prop. Only assign it if it exists.
3643 if (value != null) {
3644 // Always assign on buttons so that it is possible to assign an
3645 // empty string to clear button text.
3646 //
3647 // Otherwise, do not re-assign the value property if is empty. This
3648 // potentially avoids a DOM write and prevents Firefox (~60.0.1) from
3649 // prematurely marking required inputs as invalid. Equality is compared
3650 // to the current value in case the browser provided value is not an
3651 // empty string.
3652 if (isButton || value !== node.value) {
3653 node.value = toString(value);
3654 }
3655 }
3656 } else {
3657 // When syncing the value attribute, the value property should use
3658 // the wrapperState._initialValue property. This uses:
3659 //
3660 // 1. The value React property when present
3661 // 2. The defaultValue React property when present
3662 // 3. An empty string
3663 if (_initialValue !== node.value) {
3664 node.value = _initialValue;
3665 }
3666 }
3667 }
3668
3669 if (disableInputAttributeSyncing) {
3670 // When not syncing the value attribute, assign the value attribute
3671 // directly from the defaultValue React property (when present)
3672 var defaultValue = getToStringValue(props.defaultValue);
3673 if (defaultValue != null) {
3674 node.defaultValue = toString(defaultValue);
3675 }
3676 } else {
3677 // Otherwise, the value attribute is synchronized to the property,
3678 // so we assign defaultValue to the same thing as the value property
3679 // assignment step above.
3680 node.defaultValue = _initialValue;
3681 }
3682 }
3683
3684 // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
3685 // this is needed to work around a chrome bug where setting defaultChecked
3686 // will sometimes influence the value of checked (even after detachment).
3687 // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
3688 // We need to temporarily unset name to avoid disrupting radio button groups.
3689 var name = node.name;
3690 if (name !== '') {
3691 node.name = '';
3692 }
3693
3694 if (disableInputAttributeSyncing) {
3695 // When not syncing the checked attribute, the checked property
3696 // never gets assigned. It must be manually set. We don't want
3697 // to do this when hydrating so that existing user input isn't
3698 // modified
3699 if (!isHydrating) {
3700 updateChecked(element, props);
3701 }
3702
3703 // Only assign the checked attribute if it is defined. This saves
3704 // a DOM write when controlling the checked attribute isn't needed
3705 // (text inputs, submit/reset)
3706 if (props.hasOwnProperty('defaultChecked')) {
3707 node.defaultChecked = !node.defaultChecked;
3708 node.defaultChecked = !!props.defaultChecked;
3709 }
3710 } else {
3711 // When syncing the checked attribute, both the checked property and
3712 // attribute are assigned at the same time using defaultChecked. This uses:
3713 //
3714 // 1. The checked React property when present
3715 // 2. The defaultChecked React property when present
3716 // 3. Otherwise, false
3717 node.defaultChecked = !node.defaultChecked;
3718 node.defaultChecked = !!node._wrapperState.initialChecked;
3719 }
3720
3721 if (name !== '') {
3722 node.name = name;
3723 }
3724}
3725
3726function restoreControlledState(element, props) {
3727 var node = element;
3728 updateWrapper(node, props);
3729 updateNamedCousins(node, props);
3730}
3731
3732function updateNamedCousins(rootNode, props) {
3733 var name = props.name;
3734 if (props.type === 'radio' && name != null) {
3735 var queryRoot = rootNode;
3736
3737 while (queryRoot.parentNode) {
3738 queryRoot = queryRoot.parentNode;
3739 }
3740
3741 // If `rootNode.form` was non-null, then we could try `form.elements`,
3742 // but that sometimes behaves strangely in IE8. We could also try using
3743 // `form.getElementsByName`, but that will only return direct children
3744 // and won't include inputs that use the HTML5 `form=` attribute. Since
3745 // the input might not even be in a form. It might not even be in the
3746 // document. Let's just use the local `querySelectorAll` to ensure we don't
3747 // miss anything.
3748 var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
3749
3750 for (var i = 0; i < group.length; i++) {
3751 var otherNode = group[i];
3752 if (otherNode === rootNode || otherNode.form !== rootNode.form) {
3753 continue;
3754 }
3755 // This will throw if radio buttons rendered by different copies of React
3756 // and the same name are rendered into the same form (same as #1939).
3757 // That's probably okay; we don't support it just as we don't support
3758 // mixing React radio buttons with non-React ones.
3759 var otherProps = getFiberCurrentPropsFromNode$1(otherNode);
3760 (function () {
3761 if (!otherProps) {
3762 {
3763 throw ReactError('ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.');
3764 }
3765 }
3766 })();
3767
3768 // We need update the tracked value on the named cousin since the value
3769 // was changed but the input saw no event or value set
3770 updateValueIfChanged(otherNode);
3771
3772 // If this is a controlled radio button group, forcing the input that
3773 // was previously checked to update will cause it to be come re-checked
3774 // as appropriate.
3775 updateWrapper(otherNode, otherProps);
3776 }
3777 }
3778}
3779
3780// In Chrome, assigning defaultValue to certain input types triggers input validation.
3781// For number inputs, the display value loses trailing decimal points. For email inputs,
3782// Chrome raises "The specified value <x> is not a valid email address".
3783//
3784// Here we check to see if the defaultValue has actually changed, avoiding these problems
3785// when the user is inputting text
3786//
3787// https://github.com/facebook/react/issues/7253
3788function setDefaultValue(node, type, value) {
3789 if (
3790 // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
3791 type !== 'number' || node.ownerDocument.activeElement !== node) {
3792 if (value == null) {
3793 node.defaultValue = toString(node._wrapperState.initialValue);
3794 } else if (node.defaultValue !== toString(value)) {
3795 node.defaultValue = toString(value);
3796 }
3797 }
3798}
3799
3800var eventTypes$1 = {
3801 change: {
3802 phasedRegistrationNames: {
3803 bubbled: 'onChange',
3804 captured: 'onChangeCapture'
3805 },
3806 dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE]
3807 }
3808};
3809
3810function createAndAccumulateChangeEvent(inst, nativeEvent, target) {
3811 var event = SyntheticEvent.getPooled(eventTypes$1.change, inst, nativeEvent, target);
3812 event.type = 'change';
3813 // Flag this event loop as needing state restore.
3814 enqueueStateRestore(target);
3815 accumulateTwoPhaseDispatches(event);
3816 return event;
3817}
3818/**
3819 * For IE shims
3820 */
3821var activeElement = null;
3822var activeElementInst = null;
3823
3824/**
3825 * SECTION: handle `change` event
3826 */
3827function shouldUseChangeEvent(elem) {
3828 var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
3829 return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
3830}
3831
3832function manualDispatchChangeEvent(nativeEvent) {
3833 var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent));
3834
3835 // If change and propertychange bubbled, we'd just bind to it like all the
3836 // other events and have it go through ReactBrowserEventEmitter. Since it
3837 // doesn't, we manually listen for the events and so we have to enqueue and
3838 // process the abstract event manually.
3839 //
3840 // Batching is necessary here in order to ensure that all event handlers run
3841 // before the next rerender (including event handlers attached to ancestor
3842 // elements instead of directly on the input). Without this, controlled
3843 // components don't work properly in conjunction with event bubbling because
3844 // the component is rerendered and the value reverted before all the event
3845 // handlers can run. See https://github.com/facebook/react/issues/708.
3846 batchedUpdates(runEventInBatch, event);
3847}
3848
3849function runEventInBatch(event) {
3850 runEventsInBatch(event);
3851}
3852
3853function getInstIfValueChanged(targetInst) {
3854 var targetNode = getNodeFromInstance$1(targetInst);
3855 if (updateValueIfChanged(targetNode)) {
3856 return targetInst;
3857 }
3858}
3859
3860function getTargetInstForChangeEvent(topLevelType, targetInst) {
3861 if (topLevelType === TOP_CHANGE) {
3862 return targetInst;
3863 }
3864}
3865
3866/**
3867 * SECTION: handle `input` event
3868 */
3869var isInputEventSupported = false;
3870if (canUseDOM) {
3871 // IE9 claims to support the input event but fails to trigger it when
3872 // deleting text, so we ignore its input events.
3873 isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
3874}
3875
3876/**
3877 * (For IE <=9) Starts tracking propertychange events on the passed-in element
3878 * and override the value property so that we can distinguish user events from
3879 * value changes in JS.
3880 */
3881function startWatchingForValueChange(target, targetInst) {
3882 activeElement = target;
3883 activeElementInst = targetInst;
3884 activeElement.attachEvent('onpropertychange', handlePropertyChange);
3885}
3886
3887/**
3888 * (For IE <=9) Removes the event listeners from the currently-tracked element,
3889 * if any exists.
3890 */
3891function stopWatchingForValueChange() {
3892 if (!activeElement) {
3893 return;
3894 }
3895 activeElement.detachEvent('onpropertychange', handlePropertyChange);
3896 activeElement = null;
3897 activeElementInst = null;
3898}
3899
3900/**
3901 * (For IE <=9) Handles a propertychange event, sending a `change` event if
3902 * the value of the active element has changed.
3903 */
3904function handlePropertyChange(nativeEvent) {
3905 if (nativeEvent.propertyName !== 'value') {
3906 return;
3907 }
3908 if (getInstIfValueChanged(activeElementInst)) {
3909 manualDispatchChangeEvent(nativeEvent);
3910 }
3911}
3912
3913function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
3914 if (topLevelType === TOP_FOCUS) {
3915 // In IE9, propertychange fires for most input events but is buggy and
3916 // doesn't fire when text is deleted, but conveniently, selectionchange
3917 // appears to fire in all of the remaining cases so we catch those and
3918 // forward the event if the value has changed
3919 // In either case, we don't want to call the event handler if the value
3920 // is changed from JS so we redefine a setter for `.value` that updates
3921 // our activeElementValue variable, allowing us to ignore those changes
3922 //
3923 // stopWatching() should be a noop here but we call it just in case we
3924 // missed a blur event somehow.
3925 stopWatchingForValueChange();
3926 startWatchingForValueChange(target, targetInst);
3927 } else if (topLevelType === TOP_BLUR) {
3928 stopWatchingForValueChange();
3929 }
3930}
3931
3932// For IE8 and IE9.
3933function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {
3934 if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {
3935 // On the selectionchange event, the target is just document which isn't
3936 // helpful for us so just check activeElement instead.
3937 //
3938 // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
3939 // propertychange on the first input event after setting `value` from a
3940 // script and fires only keydown, keypress, keyup. Catching keyup usually
3941 // gets it and catching keydown lets us fire an event for the first
3942 // keystroke if user does a key repeat (it'll be a little delayed: right
3943 // before the second keystroke). Other input methods (e.g., paste) seem to
3944 // fire selectionchange normally.
3945 return getInstIfValueChanged(activeElementInst);
3946 }
3947}
3948
3949/**
3950 * SECTION: handle `click` event
3951 */
3952function shouldUseClickEvent(elem) {
3953 // Use the `click` event to detect changes to checkbox and radio inputs.
3954 // This approach works across all browsers, whereas `change` does not fire
3955 // until `blur` in IE8.
3956 var nodeName = elem.nodeName;
3957 return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
3958}
3959
3960function getTargetInstForClickEvent(topLevelType, targetInst) {
3961 if (topLevelType === TOP_CLICK) {
3962 return getInstIfValueChanged(targetInst);
3963 }
3964}
3965
3966function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {
3967 if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) {
3968 return getInstIfValueChanged(targetInst);
3969 }
3970}
3971
3972function handleControlledInputBlur(node) {
3973 var state = node._wrapperState;
3974
3975 if (!state || !state.controlled || node.type !== 'number') {
3976 return;
3977 }
3978
3979 if (!disableInputAttributeSyncing) {
3980 // If controlled, assign the value attribute to the current value on blur
3981 setDefaultValue(node, 'number', node.value);
3982 }
3983}
3984
3985/**
3986 * This plugin creates an `onChange` event that normalizes change events
3987 * across form elements. This event fires at a time when it's possible to
3988 * change the element's value without seeing a flicker.
3989 *
3990 * Supported elements are:
3991 * - input (see `isTextInputElement`)
3992 * - textarea
3993 * - select
3994 */
3995var ChangeEventPlugin = {
3996 eventTypes: eventTypes$1,
3997
3998 _isInputEventSupported: isInputEventSupported,
3999
4000 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
4001 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
4002
4003 var getTargetInstFunc = void 0,
4004 handleEventFunc = void 0;
4005 if (shouldUseChangeEvent(targetNode)) {
4006 getTargetInstFunc = getTargetInstForChangeEvent;
4007 } else if (isTextInputElement(targetNode)) {
4008 if (isInputEventSupported) {
4009 getTargetInstFunc = getTargetInstForInputOrChangeEvent;
4010 } else {
4011 getTargetInstFunc = getTargetInstForInputEventPolyfill;
4012 handleEventFunc = handleEventsForInputEventPolyfill;
4013 }
4014 } else if (shouldUseClickEvent(targetNode)) {
4015 getTargetInstFunc = getTargetInstForClickEvent;
4016 }
4017
4018 if (getTargetInstFunc) {
4019 var inst = getTargetInstFunc(topLevelType, targetInst);
4020 if (inst) {
4021 var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget);
4022 return event;
4023 }
4024 }
4025
4026 if (handleEventFunc) {
4027 handleEventFunc(topLevelType, targetNode, targetInst);
4028 }
4029
4030 // When blurring, set the value attribute for number inputs
4031 if (topLevelType === TOP_BLUR) {
4032 handleControlledInputBlur(targetNode);
4033 }
4034 }
4035};
4036
4037/**
4038 * Module that is injectable into `EventPluginHub`, that specifies a
4039 * deterministic ordering of `EventPlugin`s. A convenient way to reason about
4040 * plugins, without having to package every one of them. This is better than
4041 * having plugins be ordered in the same order that they are injected because
4042 * that ordering would be influenced by the packaging order.
4043 * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
4044 * preventing default on events is convenient in `SimpleEventPlugin` handlers.
4045 */
4046var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];
4047
4048var SyntheticUIEvent = SyntheticEvent.extend({
4049 view: null,
4050 detail: null
4051});
4052
4053var modifierKeyToProp = {
4054 Alt: 'altKey',
4055 Control: 'ctrlKey',
4056 Meta: 'metaKey',
4057 Shift: 'shiftKey'
4058};
4059
4060// Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
4061// getModifierState. If getModifierState is not supported, we map it to a set of
4062// modifier keys exposed by the event. In this case, Lock-keys are not supported.
4063/**
4064 * Translation from modifier key to the associated property in the event.
4065 * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
4066 */
4067
4068function modifierStateGetter(keyArg) {
4069 var syntheticEvent = this;
4070 var nativeEvent = syntheticEvent.nativeEvent;
4071 if (nativeEvent.getModifierState) {
4072 return nativeEvent.getModifierState(keyArg);
4073 }
4074 var keyProp = modifierKeyToProp[keyArg];
4075 return keyProp ? !!nativeEvent[keyProp] : false;
4076}
4077
4078function getEventModifierState(nativeEvent) {
4079 return modifierStateGetter;
4080}
4081
4082var previousScreenX = 0;
4083var previousScreenY = 0;
4084// Use flags to signal movementX/Y has already been set
4085var isMovementXSet = false;
4086var isMovementYSet = false;
4087
4088/**
4089 * @interface MouseEvent
4090 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4091 */
4092var SyntheticMouseEvent = SyntheticUIEvent.extend({
4093 screenX: null,
4094 screenY: null,
4095 clientX: null,
4096 clientY: null,
4097 pageX: null,
4098 pageY: null,
4099 ctrlKey: null,
4100 shiftKey: null,
4101 altKey: null,
4102 metaKey: null,
4103 getModifierState: getEventModifierState,
4104 button: null,
4105 buttons: null,
4106 relatedTarget: function (event) {
4107 return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
4108 },
4109 movementX: function (event) {
4110 if ('movementX' in event) {
4111 return event.movementX;
4112 }
4113
4114 var screenX = previousScreenX;
4115 previousScreenX = event.screenX;
4116
4117 if (!isMovementXSet) {
4118 isMovementXSet = true;
4119 return 0;
4120 }
4121
4122 return event.type === 'mousemove' ? event.screenX - screenX : 0;
4123 },
4124 movementY: function (event) {
4125 if ('movementY' in event) {
4126 return event.movementY;
4127 }
4128
4129 var screenY = previousScreenY;
4130 previousScreenY = event.screenY;
4131
4132 if (!isMovementYSet) {
4133 isMovementYSet = true;
4134 return 0;
4135 }
4136
4137 return event.type === 'mousemove' ? event.screenY - screenY : 0;
4138 }
4139});
4140
4141/**
4142 * @interface PointerEvent
4143 * @see http://www.w3.org/TR/pointerevents/
4144 */
4145var SyntheticPointerEvent = SyntheticMouseEvent.extend({
4146 pointerId: null,
4147 width: null,
4148 height: null,
4149 pressure: null,
4150 tangentialPressure: null,
4151 tiltX: null,
4152 tiltY: null,
4153 twist: null,
4154 pointerType: null,
4155 isPrimary: null
4156});
4157
4158var eventTypes$2 = {
4159 mouseEnter: {
4160 registrationName: 'onMouseEnter',
4161 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
4162 },
4163 mouseLeave: {
4164 registrationName: 'onMouseLeave',
4165 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
4166 },
4167 pointerEnter: {
4168 registrationName: 'onPointerEnter',
4169 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
4170 },
4171 pointerLeave: {
4172 registrationName: 'onPointerLeave',
4173 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
4174 }
4175};
4176
4177var EnterLeaveEventPlugin = {
4178 eventTypes: eventTypes$2,
4179
4180 /**
4181 * For almost every interaction we care about, there will be both a top-level
4182 * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
4183 * we do not extract duplicate events. However, moving the mouse into the
4184 * browser from outside will not fire a `mouseout` event. In this case, we use
4185 * the `mouseover` top-level event.
4186 */
4187 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
4188 var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
4189 var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;
4190
4191 if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
4192 return null;
4193 }
4194
4195 if (!isOutEvent && !isOverEvent) {
4196 // Must not be a mouse or pointer in or out - ignoring.
4197 return null;
4198 }
4199
4200 var win = void 0;
4201 if (nativeEventTarget.window === nativeEventTarget) {
4202 // `nativeEventTarget` is probably a window object.
4203 win = nativeEventTarget;
4204 } else {
4205 // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
4206 var doc = nativeEventTarget.ownerDocument;
4207 if (doc) {
4208 win = doc.defaultView || doc.parentWindow;
4209 } else {
4210 win = window;
4211 }
4212 }
4213
4214 var from = void 0;
4215 var to = void 0;
4216 if (isOutEvent) {
4217 from = targetInst;
4218 var related = nativeEvent.relatedTarget || nativeEvent.toElement;
4219 to = related ? getClosestInstanceFromNode(related) : null;
4220 } else {
4221 // Moving to a node from outside the window.
4222 from = null;
4223 to = targetInst;
4224 }
4225
4226 if (from === to) {
4227 // Nothing pertains to our managed components.
4228 return null;
4229 }
4230
4231 var eventInterface = void 0,
4232 leaveEventType = void 0,
4233 enterEventType = void 0,
4234 eventTypePrefix = void 0;
4235
4236 if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
4237 eventInterface = SyntheticMouseEvent;
4238 leaveEventType = eventTypes$2.mouseLeave;
4239 enterEventType = eventTypes$2.mouseEnter;
4240 eventTypePrefix = 'mouse';
4241 } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {
4242 eventInterface = SyntheticPointerEvent;
4243 leaveEventType = eventTypes$2.pointerLeave;
4244 enterEventType = eventTypes$2.pointerEnter;
4245 eventTypePrefix = 'pointer';
4246 }
4247
4248 var fromNode = from == null ? win : getNodeFromInstance$1(from);
4249 var toNode = to == null ? win : getNodeFromInstance$1(to);
4250
4251 var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);
4252 leave.type = eventTypePrefix + 'leave';
4253 leave.target = fromNode;
4254 leave.relatedTarget = toNode;
4255
4256 var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);
4257 enter.type = eventTypePrefix + 'enter';
4258 enter.target = toNode;
4259 enter.relatedTarget = fromNode;
4260
4261 accumulateEnterLeaveDispatches(leave, enter, from, to);
4262
4263 return [leave, enter];
4264 }
4265};
4266
4267/**
4268 * inlined Object.is polyfill to avoid requiring consumers ship their own
4269 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
4270 */
4271function is(x, y) {
4272 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
4273 ;
4274}
4275
4276var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
4277
4278/**
4279 * Performs equality by iterating through keys on an object and returning false
4280 * when any key has values which are not strictly equal between the arguments.
4281 * Returns true when the values of all keys are strictly equal.
4282 */
4283function shallowEqual(objA, objB) {
4284 if (is(objA, objB)) {
4285 return true;
4286 }
4287
4288 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
4289 return false;
4290 }
4291
4292 var keysA = Object.keys(objA);
4293 var keysB = Object.keys(objB);
4294
4295 if (keysA.length !== keysB.length) {
4296 return false;
4297 }
4298
4299 // Test for A's keys different from B.
4300 for (var i = 0; i < keysA.length; i++) {
4301 if (!hasOwnProperty$1.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
4302 return false;
4303 }
4304 }
4305
4306 return true;
4307}
4308
4309var PLUGIN_EVENT_SYSTEM = 1;
4310var RESPONDER_EVENT_SYSTEM = 1 << 1;
4311var IS_PASSIVE = 1 << 2;
4312var IS_ACTIVE = 1 << 3;
4313var PASSIVE_NOT_SUPPORTED = 1 << 4;
4314
4315var listenToResponderEventTypesImpl = void 0;
4316
4317function setListenToResponderEventTypes(_listenToResponderEventTypesImpl) {
4318 listenToResponderEventTypesImpl = _listenToResponderEventTypesImpl;
4319}
4320
4321var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
4322
4323var rootEventTypesToEventComponents = new Map();
4324var targetEventTypeCached = new Map();
4325var targetOwnership = new Map();
4326var eventsWithStopPropagation = new PossiblyWeakSet();
4327
4328function createEventQueue() {
4329 return {
4330 bubble: null,
4331 capture: null,
4332 discrete: false
4333 };
4334}
4335
4336function processEvent(event) {
4337 var type = event.type;
4338 var listener = event.listener;
4339 invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
4340}
4341
4342function processEvents(bubble, capture) {
4343 var i = void 0,
4344 length = void 0;
4345
4346 if (capture !== null) {
4347 for (i = capture.length; i-- > 0;) {
4348 var event = capture[i];
4349 processEvent(capture[i]);
4350 if (eventsWithStopPropagation.has(event)) {
4351 return;
4352 }
4353 }
4354 }
4355 if (bubble !== null) {
4356 for (i = 0, length = bubble.length; i < length; ++i) {
4357 var _event = bubble[i];
4358 processEvent(_event);
4359 if (eventsWithStopPropagation.has(_event)) {
4360 return;
4361 }
4362 }
4363 }
4364}
4365
4366function processEventQueue(eventQueue) {
4367 var bubble = eventQueue.bubble,
4368 capture = eventQueue.capture,
4369 discrete = eventQueue.discrete;
4370
4371
4372 if (discrete) {
4373 interactiveUpdates(function () {
4374 processEvents(bubble, capture);
4375 });
4376 } else {
4377 processEvents(bubble, capture);
4378 }
4379}
4380
4381// TODO add context methods for dispatching events
4382function DOMEventResponderContext(topLevelType, nativeEvent, nativeEventTarget, eventSystemFlags) {
4383 this.event = nativeEvent;
4384 this.eventTarget = nativeEventTarget;
4385 this.eventType = topLevelType;
4386 this._flags = eventSystemFlags;
4387 this._fiber = null;
4388 this._responder = null;
4389 this._discreteEvents = null;
4390 this._nonDiscreteEvents = null;
4391 this._isBatching = true;
4392 this._eventQueue = createEventQueue();
4393}
4394
4395DOMEventResponderContext.prototype.isPassive = function () {
4396 return (this._flags & IS_PASSIVE) !== 0;
4397};
4398
4399DOMEventResponderContext.prototype.isPassiveSupported = function () {
4400 return (this._flags & PASSIVE_NOT_SUPPORTED) === 0;
4401};
4402
4403DOMEventResponderContext.prototype.dispatchEvent = function (possibleEventObject, _ref) {
4404 var capture = _ref.capture,
4405 discrete = _ref.discrete,
4406 stopPropagation = _ref.stopPropagation;
4407
4408 var eventQueue = this._eventQueue;
4409 var listener = possibleEventObject.listener,
4410 target = possibleEventObject.target,
4411 type = possibleEventObject.type;
4412
4413
4414 if (listener == null || target == null || type == null) {
4415 throw new Error('context.dispatchEvent: "listener", "target" and "type" fields on event object are required.');
4416 }
4417 {
4418 possibleEventObject.preventDefault = function () {
4419 // Update this warning when we have a story around dealing with preventDefault
4420 warning$1(false, 'preventDefault() is no longer available on event objects created from event responder modules.');
4421 };
4422 possibleEventObject.stopPropagation = function () {
4423 // Update this warning when we have a story around dealing with stopPropgation
4424 warning$1(false, 'stopPropagation() is no longer available on event objects created from event responder modules.');
4425 };
4426 }
4427 var eventObject = possibleEventObject;
4428 var events = void 0;
4429
4430 if (capture) {
4431 events = eventQueue.capture;
4432 if (events === null) {
4433 events = eventQueue.capture = [];
4434 }
4435 } else {
4436 events = eventQueue.bubble;
4437 if (events === null) {
4438 events = eventQueue.bubble = [];
4439 }
4440 }
4441 if (discrete) {
4442 eventQueue.discrete = true;
4443 }
4444 events.push(eventObject);
4445
4446 if (stopPropagation) {
4447 eventsWithStopPropagation.add(eventObject);
4448 }
4449};
4450
4451DOMEventResponderContext.prototype.isTargetWithinEventComponent = function (target) {
4452 var eventFiber = this._fiber;
4453
4454 if (target != null) {
4455 var fiber = getClosestInstanceFromNode(target);
4456 while (fiber !== null) {
4457 if (fiber === eventFiber || fiber === eventFiber.alternate) {
4458 return true;
4459 }
4460 fiber = fiber.return;
4461 }
4462 }
4463 return false;
4464};
4465
4466DOMEventResponderContext.prototype.isTargetWithinElement = function (childTarget, parentTarget) {
4467 var childFiber = getClosestInstanceFromNode(childTarget);
4468 var parentFiber = getClosestInstanceFromNode(parentTarget);
4469
4470 var currentFiber = childFiber;
4471 while (currentFiber !== null) {
4472 if (currentFiber === parentFiber) {
4473 return true;
4474 }
4475 currentFiber = currentFiber.return;
4476 }
4477 return false;
4478};
4479
4480DOMEventResponderContext.prototype.addRootEventTypes = function (rootEventTypes) {
4481 var element = this.eventTarget.ownerDocument;
4482 listenToResponderEventTypesImpl(rootEventTypes, element);
4483 var eventComponent = this._fiber;
4484 for (var i = 0; i < rootEventTypes.length; i++) {
4485 var rootEventType = rootEventTypes[i];
4486 var topLevelEventType = typeof rootEventType === 'string' ? rootEventType : rootEventType.name;
4487 var rootEventComponents = rootEventTypesToEventComponents.get(topLevelEventType);
4488 if (rootEventComponents === undefined) {
4489 rootEventComponents = new Set();
4490 rootEventTypesToEventComponents.set(topLevelEventType, rootEventComponents);
4491 }
4492 rootEventComponents.add(eventComponent);
4493 }
4494};
4495
4496DOMEventResponderContext.prototype.removeRootEventTypes = function (rootEventTypes) {
4497 var eventComponent = this._fiber;
4498 for (var i = 0; i < rootEventTypes.length; i++) {
4499 var rootEventType = rootEventTypes[i];
4500 var topLevelEventType = typeof rootEventType === 'string' ? rootEventType : rootEventType.name;
4501 var rootEventComponents = rootEventTypesToEventComponents.get(topLevelEventType);
4502 if (rootEventComponents !== undefined) {
4503 rootEventComponents.delete(eventComponent);
4504 }
4505 }
4506};
4507
4508DOMEventResponderContext.prototype.isPositionWithinTouchHitTarget = function () {
4509 // TODO
4510};
4511
4512DOMEventResponderContext.prototype.isTargetOwned = function (targetElement) {
4513 var targetDoc = targetElement.ownerDocument;
4514 return targetOwnership.has(targetDoc);
4515};
4516
4517DOMEventResponderContext.prototype.requestOwnership = function (targetElement) {
4518 var targetDoc = targetElement.ownerDocument;
4519 if (targetOwnership.has(targetDoc)) {
4520 return false;
4521 }
4522 targetOwnership.set(targetDoc, this._fiber);
4523 return true;
4524};
4525
4526DOMEventResponderContext.prototype.releaseOwnership = function (targetElement) {
4527 var targetDoc = targetElement.ownerDocument;
4528 if (!targetOwnership.has(targetDoc)) {
4529 return false;
4530 }
4531 var owner = targetOwnership.get(targetDoc);
4532 if (owner === this._fiber || owner === this._fiber.alternate) {
4533 targetOwnership.delete(targetDoc);
4534 return true;
4535 }
4536 return false;
4537};
4538
4539DOMEventResponderContext.prototype.withAsyncDispatching = function (func) {
4540 var previousEventQueue = this._eventQueue;
4541 this._eventQueue = createEventQueue();
4542 try {
4543 func();
4544 batchedUpdates(processEventQueue, this._eventQueue);
4545 } finally {
4546 this._eventQueue = previousEventQueue;
4547 }
4548};
4549
4550function getTargetEventTypes(eventTypes) {
4551 var cachedSet = targetEventTypeCached.get(eventTypes);
4552
4553 if (cachedSet === undefined) {
4554 cachedSet = new Set();
4555 for (var i = 0; i < eventTypes.length; i++) {
4556 var eventType = eventTypes[i];
4557 var topLevelEventType = typeof eventType === 'string' ? eventType : eventType.name;
4558 cachedSet.add(topLevelEventType);
4559 }
4560 targetEventTypeCached.set(eventTypes, cachedSet);
4561 }
4562 return cachedSet;
4563}
4564
4565function handleTopLevelType(topLevelType, fiber, context, isRootLevelEvent) {
4566 var responder = fiber.type.responder;
4567 if (!isRootLevelEvent) {
4568 // Validate the target event type exists on the responder
4569 var targetEventTypes = getTargetEventTypes(responder.targetEventTypes);
4570 if (!targetEventTypes.has(topLevelType)) {
4571 return;
4572 }
4573 }
4574 var _fiber$stateNode = fiber.stateNode,
4575 props = _fiber$stateNode.props,
4576 state = _fiber$stateNode.state;
4577
4578 if (state === null && responder.createInitialState !== undefined) {
4579 state = fiber.stateNode.state = responder.createInitialState(props);
4580 }
4581 context._fiber = fiber;
4582 context._responder = responder;
4583 responder.handleEvent(context, props, state);
4584}
4585
4586function runResponderEventsInBatch(topLevelType, targetFiber, nativeEvent, nativeEventTarget, eventSystemFlags) {
4587 if (enableEventAPI) {
4588 var context = new DOMEventResponderContext(topLevelType, nativeEvent, nativeEventTarget, eventSystemFlags);
4589 var node = targetFiber;
4590 // Traverse up the fiber tree till we find event component fibers.
4591 while (node !== null) {
4592 if (node.tag === EventComponent) {
4593 handleTopLevelType(topLevelType, node, context, false);
4594 }
4595 node = node.return;
4596 }
4597 // Handle root level events
4598 var rootEventComponents = rootEventTypesToEventComponents.get(topLevelType);
4599 if (rootEventComponents !== undefined) {
4600 var rootEventComponentFibers = Array.from(rootEventComponents);
4601
4602 for (var i = 0; i < rootEventComponentFibers.length; i++) {
4603 var rootEventComponentFiber = rootEventComponentFibers[i];
4604 handleTopLevelType(topLevelType, rootEventComponentFiber, context, true);
4605 }
4606 }
4607 processEventQueue(context._eventQueue);
4608 }
4609}
4610
4611/**
4612 * `ReactInstanceMap` maintains a mapping from a public facing stateful
4613 * instance (key) and the internal representation (value). This allows public
4614 * methods to accept the user facing instance as an argument and map them back
4615 * to internal methods.
4616 *
4617 * Note that this module is currently shared and assumed to be stateless.
4618 * If this becomes an actual Map, that will break.
4619 */
4620
4621/**
4622 * This API should be called `delete` but we'd have to make sure to always
4623 * transform these to strings for IE support. When this transform is fully
4624 * supported we can rename it.
4625 */
4626
4627
4628function get(key) {
4629 return key._reactInternalFiber;
4630}
4631
4632function has(key) {
4633 return key._reactInternalFiber !== undefined;
4634}
4635
4636function set(key, value) {
4637 key._reactInternalFiber = value;
4638}
4639
4640// Don't change these two values. They're used by React Dev Tools.
4641var NoEffect = /* */0;
4642var PerformedWork = /* */1;
4643
4644// You can change the rest (and add more).
4645var Placement = /* */2;
4646var Update = /* */4;
4647var PlacementAndUpdate = /* */6;
4648var Deletion = /* */8;
4649var ContentReset = /* */16;
4650var Callback = /* */32;
4651var DidCapture = /* */64;
4652var Ref = /* */128;
4653var Snapshot = /* */256;
4654var Passive = /* */512;
4655
4656// Passive & Update & Callback & Ref & Snapshot
4657var LifecycleEffectMask = /* */932;
4658
4659// Union of all host effects
4660var HostEffectMask = /* */1023;
4661
4662var Incomplete = /* */1024;
4663var ShouldCapture = /* */2048;
4664
4665var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
4666
4667var MOUNTING = 1;
4668var MOUNTED = 2;
4669var UNMOUNTED = 3;
4670
4671function isFiberMountedImpl(fiber) {
4672 var node = fiber;
4673 if (!fiber.alternate) {
4674 // If there is no alternate, this might be a new tree that isn't inserted
4675 // yet. If it is, then it will have a pending insertion effect on it.
4676 if ((node.effectTag & Placement) !== NoEffect) {
4677 return MOUNTING;
4678 }
4679 while (node.return) {
4680 node = node.return;
4681 if ((node.effectTag & Placement) !== NoEffect) {
4682 return MOUNTING;
4683 }
4684 }
4685 } else {
4686 while (node.return) {
4687 node = node.return;
4688 }
4689 }
4690 if (node.tag === HostRoot) {
4691 // TODO: Check if this was a nested HostRoot when used with
4692 // renderContainerIntoSubtree.
4693 return MOUNTED;
4694 }
4695 // If we didn't hit the root, that means that we're in an disconnected tree
4696 // that has been unmounted.
4697 return UNMOUNTED;
4698}
4699
4700function isFiberMounted(fiber) {
4701 return isFiberMountedImpl(fiber) === MOUNTED;
4702}
4703
4704function isMounted(component) {
4705 {
4706 var owner = ReactCurrentOwner$1.current;
4707 if (owner !== null && owner.tag === ClassComponent) {
4708 var ownerFiber = owner;
4709 var instance = ownerFiber.stateNode;
4710 !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;
4711 instance._warnedAboutRefsInRender = true;
4712 }
4713 }
4714
4715 var fiber = get(component);
4716 if (!fiber) {
4717 return false;
4718 }
4719 return isFiberMountedImpl(fiber) === MOUNTED;
4720}
4721
4722function assertIsMounted(fiber) {
4723 (function () {
4724 if (!(isFiberMountedImpl(fiber) === MOUNTED)) {
4725 {
4726 throw ReactError('Unable to find node on an unmounted component.');
4727 }
4728 }
4729 })();
4730}
4731
4732function findCurrentFiberUsingSlowPath(fiber) {
4733 var alternate = fiber.alternate;
4734 if (!alternate) {
4735 // If there is no alternate, then we only need to check if it is mounted.
4736 var state = isFiberMountedImpl(fiber);
4737 (function () {
4738 if (!(state !== UNMOUNTED)) {
4739 {
4740 throw ReactError('Unable to find node on an unmounted component.');
4741 }
4742 }
4743 })();
4744 if (state === MOUNTING) {
4745 return null;
4746 }
4747 return fiber;
4748 }
4749 // If we have two possible branches, we'll walk backwards up to the root
4750 // to see what path the root points to. On the way we may hit one of the
4751 // special cases and we'll deal with them.
4752 var a = fiber;
4753 var b = alternate;
4754 while (true) {
4755 var parentA = a.return;
4756 var parentB = parentA ? parentA.alternate : null;
4757 if (!parentA || !parentB) {
4758 // We're at the root.
4759 break;
4760 }
4761
4762 // If both copies of the parent fiber point to the same child, we can
4763 // assume that the child is current. This happens when we bailout on low
4764 // priority: the bailed out fiber's child reuses the current child.
4765 if (parentA.child === parentB.child) {
4766 var child = parentA.child;
4767 while (child) {
4768 if (child === a) {
4769 // We've determined that A is the current branch.
4770 assertIsMounted(parentA);
4771 return fiber;
4772 }
4773 if (child === b) {
4774 // We've determined that B is the current branch.
4775 assertIsMounted(parentA);
4776 return alternate;
4777 }
4778 child = child.sibling;
4779 }
4780 // We should never have an alternate for any mounting node. So the only
4781 // way this could possibly happen is if this was unmounted, if at all.
4782 (function () {
4783 {
4784 {
4785 throw ReactError('Unable to find node on an unmounted component.');
4786 }
4787 }
4788 })();
4789 }
4790
4791 if (a.return !== b.return) {
4792 // The return pointer of A and the return pointer of B point to different
4793 // fibers. We assume that return pointers never criss-cross, so A must
4794 // belong to the child set of A.return, and B must belong to the child
4795 // set of B.return.
4796 a = parentA;
4797 b = parentB;
4798 } else {
4799 // The return pointers point to the same fiber. We'll have to use the
4800 // default, slow path: scan the child sets of each parent alternate to see
4801 // which child belongs to which set.
4802 //
4803 // Search parent A's child set
4804 var didFindChild = false;
4805 var _child = parentA.child;
4806 while (_child) {
4807 if (_child === a) {
4808 didFindChild = true;
4809 a = parentA;
4810 b = parentB;
4811 break;
4812 }
4813 if (_child === b) {
4814 didFindChild = true;
4815 b = parentA;
4816 a = parentB;
4817 break;
4818 }
4819 _child = _child.sibling;
4820 }
4821 if (!didFindChild) {
4822 // Search parent B's child set
4823 _child = parentB.child;
4824 while (_child) {
4825 if (_child === a) {
4826 didFindChild = true;
4827 a = parentB;
4828 b = parentA;
4829 break;
4830 }
4831 if (_child === b) {
4832 didFindChild = true;
4833 b = parentB;
4834 a = parentA;
4835 break;
4836 }
4837 _child = _child.sibling;
4838 }
4839 (function () {
4840 if (!didFindChild) {
4841 {
4842 throw ReactError('Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.');
4843 }
4844 }
4845 })();
4846 }
4847 }
4848
4849 (function () {
4850 if (!(a.alternate === b)) {
4851 {
4852 throw ReactError('Return fibers should always be each others\' alternates. This error is likely caused by a bug in React. Please file an issue.');
4853 }
4854 }
4855 })();
4856 }
4857 // If the root is not a host container, we're in a disconnected tree. I.e.
4858 // unmounted.
4859 (function () {
4860 if (!(a.tag === HostRoot)) {
4861 {
4862 throw ReactError('Unable to find node on an unmounted component.');
4863 }
4864 }
4865 })();
4866 if (a.stateNode.current === a) {
4867 // We've determined that A is the current branch.
4868 return fiber;
4869 }
4870 // Otherwise B has to be current branch.
4871 return alternate;
4872}
4873
4874function findCurrentHostFiber(parent) {
4875 var currentParent = findCurrentFiberUsingSlowPath(parent);
4876 if (!currentParent) {
4877 return null;
4878 }
4879
4880 // Next we'll drill down this component to find the first HostComponent/Text.
4881 var node = currentParent;
4882 while (true) {
4883 if (node.tag === HostComponent || node.tag === HostText) {
4884 return node;
4885 } else if (node.child) {
4886 node.child.return = node;
4887 node = node.child;
4888 continue;
4889 }
4890 if (node === currentParent) {
4891 return null;
4892 }
4893 while (!node.sibling) {
4894 if (!node.return || node.return === currentParent) {
4895 return null;
4896 }
4897 node = node.return;
4898 }
4899 node.sibling.return = node.return;
4900 node = node.sibling;
4901 }
4902 // Flow needs the return null here, but ESLint complains about it.
4903 // eslint-disable-next-line no-unreachable
4904 return null;
4905}
4906
4907function findCurrentHostFiberWithNoPortals(parent) {
4908 var currentParent = findCurrentFiberUsingSlowPath(parent);
4909 if (!currentParent) {
4910 return null;
4911 }
4912
4913 // Next we'll drill down this component to find the first HostComponent/Text.
4914 var node = currentParent;
4915 while (true) {
4916 if (node.tag === HostComponent || node.tag === HostText) {
4917 return node;
4918 } else if (node.child && node.tag !== HostPortal) {
4919 node.child.return = node;
4920 node = node.child;
4921 continue;
4922 }
4923 if (node === currentParent) {
4924 return null;
4925 }
4926 while (!node.sibling) {
4927 if (!node.return || node.return === currentParent) {
4928 return null;
4929 }
4930 node = node.return;
4931 }
4932 node.sibling.return = node.return;
4933 node = node.sibling;
4934 }
4935 // Flow needs the return null here, but ESLint complains about it.
4936 // eslint-disable-next-line no-unreachable
4937 return null;
4938}
4939
4940function addEventBubbleListener(element, eventType, listener) {
4941 element.addEventListener(eventType, listener, false);
4942}
4943
4944function addEventCaptureListener(element, eventType, listener) {
4945 element.addEventListener(eventType, listener, true);
4946}
4947
4948function addEventListener(element, eventType, listener, options) {
4949 element.addEventListener(eventType, listener, options);
4950}
4951
4952/**
4953 * @interface Event
4954 * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
4955 * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
4956 */
4957var SyntheticAnimationEvent = SyntheticEvent.extend({
4958 animationName: null,
4959 elapsedTime: null,
4960 pseudoElement: null
4961});
4962
4963/**
4964 * @interface Event
4965 * @see http://www.w3.org/TR/clipboard-apis/
4966 */
4967var SyntheticClipboardEvent = SyntheticEvent.extend({
4968 clipboardData: function (event) {
4969 return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
4970 }
4971});
4972
4973/**
4974 * @interface FocusEvent
4975 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4976 */
4977var SyntheticFocusEvent = SyntheticUIEvent.extend({
4978 relatedTarget: null
4979});
4980
4981/**
4982 * `charCode` represents the actual "character code" and is safe to use with
4983 * `String.fromCharCode`. As such, only keys that correspond to printable
4984 * characters produce a valid `charCode`, the only exception to this is Enter.
4985 * The Tab-key is considered non-printable and does not have a `charCode`,
4986 * presumably because it does not produce a tab-character in browsers.
4987 *
4988 * @param {object} nativeEvent Native browser event.
4989 * @return {number} Normalized `charCode` property.
4990 */
4991function getEventCharCode(nativeEvent) {
4992 var charCode = void 0;
4993 var keyCode = nativeEvent.keyCode;
4994
4995 if ('charCode' in nativeEvent) {
4996 charCode = nativeEvent.charCode;
4997
4998 // FF does not set `charCode` for the Enter-key, check against `keyCode`.
4999 if (charCode === 0 && keyCode === 13) {
5000 charCode = 13;
5001 }
5002 } else {
5003 // IE8 does not implement `charCode`, but `keyCode` has the correct value.
5004 charCode = keyCode;
5005 }
5006
5007 // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
5008 // report Enter as charCode 10 when ctrl is pressed.
5009 if (charCode === 10) {
5010 charCode = 13;
5011 }
5012
5013 // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
5014 // Must not discard the (non-)printable Enter-key.
5015 if (charCode >= 32 || charCode === 13) {
5016 return charCode;
5017 }
5018
5019 return 0;
5020}
5021
5022/**
5023 * Normalization of deprecated HTML5 `key` values
5024 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
5025 */
5026var normalizeKey = {
5027 Esc: 'Escape',
5028 Spacebar: ' ',
5029 Left: 'ArrowLeft',
5030 Up: 'ArrowUp',
5031 Right: 'ArrowRight',
5032 Down: 'ArrowDown',
5033 Del: 'Delete',
5034 Win: 'OS',
5035 Menu: 'ContextMenu',
5036 Apps: 'ContextMenu',
5037 Scroll: 'ScrollLock',
5038 MozPrintableKey: 'Unidentified'
5039};
5040
5041/**
5042 * Translation from legacy `keyCode` to HTML5 `key`
5043 * Only special keys supported, all others depend on keyboard layout or browser
5044 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
5045 */
5046var translateToKey = {
5047 '8': 'Backspace',
5048 '9': 'Tab',
5049 '12': 'Clear',
5050 '13': 'Enter',
5051 '16': 'Shift',
5052 '17': 'Control',
5053 '18': 'Alt',
5054 '19': 'Pause',
5055 '20': 'CapsLock',
5056 '27': 'Escape',
5057 '32': ' ',
5058 '33': 'PageUp',
5059 '34': 'PageDown',
5060 '35': 'End',
5061 '36': 'Home',
5062 '37': 'ArrowLeft',
5063 '38': 'ArrowUp',
5064 '39': 'ArrowRight',
5065 '40': 'ArrowDown',
5066 '45': 'Insert',
5067 '46': 'Delete',
5068 '112': 'F1',
5069 '113': 'F2',
5070 '114': 'F3',
5071 '115': 'F4',
5072 '116': 'F5',
5073 '117': 'F6',
5074 '118': 'F7',
5075 '119': 'F8',
5076 '120': 'F9',
5077 '121': 'F10',
5078 '122': 'F11',
5079 '123': 'F12',
5080 '144': 'NumLock',
5081 '145': 'ScrollLock',
5082 '224': 'Meta'
5083};
5084
5085/**
5086 * @param {object} nativeEvent Native browser event.
5087 * @return {string} Normalized `key` property.
5088 */
5089function getEventKey(nativeEvent) {
5090 if (nativeEvent.key) {
5091 // Normalize inconsistent values reported by browsers due to
5092 // implementations of a working draft specification.
5093
5094 // FireFox implements `key` but returns `MozPrintableKey` for all
5095 // printable characters (normalized to `Unidentified`), ignore it.
5096 var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
5097 if (key !== 'Unidentified') {
5098 return key;
5099 }
5100 }
5101
5102 // Browser does not implement `key`, polyfill as much of it as we can.
5103 if (nativeEvent.type === 'keypress') {
5104 var charCode = getEventCharCode(nativeEvent);
5105
5106 // The enter-key is technically both printable and non-printable and can
5107 // thus be captured by `keypress`, no other non-printable key should.
5108 return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
5109 }
5110 if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
5111 // While user keyboard layout determines the actual meaning of each
5112 // `keyCode` value, almost all function keys have a universal value.
5113 return translateToKey[nativeEvent.keyCode] || 'Unidentified';
5114 }
5115 return '';
5116}
5117
5118/**
5119 * @interface KeyboardEvent
5120 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5121 */
5122var SyntheticKeyboardEvent = SyntheticUIEvent.extend({
5123 key: getEventKey,
5124 location: null,
5125 ctrlKey: null,
5126 shiftKey: null,
5127 altKey: null,
5128 metaKey: null,
5129 repeat: null,
5130 locale: null,
5131 getModifierState: getEventModifierState,
5132 // Legacy Interface
5133 charCode: function (event) {
5134 // `charCode` is the result of a KeyPress event and represents the value of
5135 // the actual printable character.
5136
5137 // KeyPress is deprecated, but its replacement is not yet final and not
5138 // implemented in any major browser. Only KeyPress has charCode.
5139 if (event.type === 'keypress') {
5140 return getEventCharCode(event);
5141 }
5142 return 0;
5143 },
5144 keyCode: function (event) {
5145 // `keyCode` is the result of a KeyDown/Up event and represents the value of
5146 // physical keyboard key.
5147
5148 // The actual meaning of the value depends on the users' keyboard layout
5149 // which cannot be detected. Assuming that it is a US keyboard layout
5150 // provides a surprisingly accurate mapping for US and European users.
5151 // Due to this, it is left to the user to implement at this time.
5152 if (event.type === 'keydown' || event.type === 'keyup') {
5153 return event.keyCode;
5154 }
5155 return 0;
5156 },
5157 which: function (event) {
5158 // `which` is an alias for either `keyCode` or `charCode` depending on the
5159 // type of the event.
5160 if (event.type === 'keypress') {
5161 return getEventCharCode(event);
5162 }
5163 if (event.type === 'keydown' || event.type === 'keyup') {
5164 return event.keyCode;
5165 }
5166 return 0;
5167 }
5168});
5169
5170/**
5171 * @interface DragEvent
5172 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5173 */
5174var SyntheticDragEvent = SyntheticMouseEvent.extend({
5175 dataTransfer: null
5176});
5177
5178/**
5179 * @interface TouchEvent
5180 * @see http://www.w3.org/TR/touch-events/
5181 */
5182var SyntheticTouchEvent = SyntheticUIEvent.extend({
5183 touches: null,
5184 targetTouches: null,
5185 changedTouches: null,
5186 altKey: null,
5187 metaKey: null,
5188 ctrlKey: null,
5189 shiftKey: null,
5190 getModifierState: getEventModifierState
5191});
5192
5193/**
5194 * @interface Event
5195 * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
5196 * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
5197 */
5198var SyntheticTransitionEvent = SyntheticEvent.extend({
5199 propertyName: null,
5200 elapsedTime: null,
5201 pseudoElement: null
5202});
5203
5204/**
5205 * @interface WheelEvent
5206 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5207 */
5208var SyntheticWheelEvent = SyntheticMouseEvent.extend({
5209 deltaX: function (event) {
5210 return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
5211 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
5212 },
5213 deltaY: function (event) {
5214 return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
5215 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
5216 'wheelDelta' in event ? -event.wheelDelta : 0;
5217 },
5218
5219 deltaZ: null,
5220
5221 // Browsers without "deltaMode" is reporting in raw wheel delta where one
5222 // notch on the scroll is always +/- 120, roughly equivalent to pixels.
5223 // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
5224 // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
5225 deltaMode: null
5226});
5227
5228/**
5229 * Turns
5230 * ['abort', ...]
5231 * into
5232 * eventTypes = {
5233 * 'abort': {
5234 * phasedRegistrationNames: {
5235 * bubbled: 'onAbort',
5236 * captured: 'onAbortCapture',
5237 * },
5238 * dependencies: [TOP_ABORT],
5239 * },
5240 * ...
5241 * };
5242 * topLevelEventsToDispatchConfig = new Map([
5243 * [TOP_ABORT, { sameConfig }],
5244 * ]);
5245 */
5246
5247var 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']];
5248var 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']];
5249
5250var eventTypes$4 = {};
5251var topLevelEventsToDispatchConfig = {};
5252
5253function addEventTypeNameToConfig(_ref, isInteractive) {
5254 var topEvent = _ref[0],
5255 event = _ref[1];
5256
5257 var capitalizedEvent = event[0].toUpperCase() + event.slice(1);
5258 var onEvent = 'on' + capitalizedEvent;
5259
5260 var type = {
5261 phasedRegistrationNames: {
5262 bubbled: onEvent,
5263 captured: onEvent + 'Capture'
5264 },
5265 dependencies: [topEvent],
5266 isInteractive: isInteractive
5267 };
5268 eventTypes$4[event] = type;
5269 topLevelEventsToDispatchConfig[topEvent] = type;
5270}
5271
5272interactiveEventTypeNames.forEach(function (eventTuple) {
5273 addEventTypeNameToConfig(eventTuple, true);
5274});
5275nonInteractiveEventTypeNames.forEach(function (eventTuple) {
5276 addEventTypeNameToConfig(eventTuple, false);
5277});
5278
5279// Only used in DEV for exhaustiveness validation.
5280var 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];
5281
5282var SimpleEventPlugin = {
5283 eventTypes: eventTypes$4,
5284
5285 isInteractiveTopLevelEventType: function (topLevelType) {
5286 var config = topLevelEventsToDispatchConfig[topLevelType];
5287 return config !== undefined && config.isInteractive === true;
5288 },
5289
5290
5291 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
5292 var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
5293 if (!dispatchConfig) {
5294 return null;
5295 }
5296 var EventConstructor = void 0;
5297 switch (topLevelType) {
5298 case TOP_KEY_PRESS:
5299 // Firefox creates a keypress event for function keys too. This removes
5300 // the unwanted keypress events. Enter is however both printable and
5301 // non-printable. One would expect Tab to be as well (but it isn't).
5302 if (getEventCharCode(nativeEvent) === 0) {
5303 return null;
5304 }
5305 /* falls through */
5306 case TOP_KEY_DOWN:
5307 case TOP_KEY_UP:
5308 EventConstructor = SyntheticKeyboardEvent;
5309 break;
5310 case TOP_BLUR:
5311 case TOP_FOCUS:
5312 EventConstructor = SyntheticFocusEvent;
5313 break;
5314 case TOP_CLICK:
5315 // Firefox creates a click event on right mouse clicks. This removes the
5316 // unwanted click events.
5317 if (nativeEvent.button === 2) {
5318 return null;
5319 }
5320 /* falls through */
5321 case TOP_AUX_CLICK:
5322 case TOP_DOUBLE_CLICK:
5323 case TOP_MOUSE_DOWN:
5324 case TOP_MOUSE_MOVE:
5325 case TOP_MOUSE_UP:
5326 // TODO: Disabled elements should not respond to mouse events
5327 /* falls through */
5328 case TOP_MOUSE_OUT:
5329 case TOP_MOUSE_OVER:
5330 case TOP_CONTEXT_MENU:
5331 EventConstructor = SyntheticMouseEvent;
5332 break;
5333 case TOP_DRAG:
5334 case TOP_DRAG_END:
5335 case TOP_DRAG_ENTER:
5336 case TOP_DRAG_EXIT:
5337 case TOP_DRAG_LEAVE:
5338 case TOP_DRAG_OVER:
5339 case TOP_DRAG_START:
5340 case TOP_DROP:
5341 EventConstructor = SyntheticDragEvent;
5342 break;
5343 case TOP_TOUCH_CANCEL:
5344 case TOP_TOUCH_END:
5345 case TOP_TOUCH_MOVE:
5346 case TOP_TOUCH_START:
5347 EventConstructor = SyntheticTouchEvent;
5348 break;
5349 case TOP_ANIMATION_END:
5350 case TOP_ANIMATION_ITERATION:
5351 case TOP_ANIMATION_START:
5352 EventConstructor = SyntheticAnimationEvent;
5353 break;
5354 case TOP_TRANSITION_END:
5355 EventConstructor = SyntheticTransitionEvent;
5356 break;
5357 case TOP_SCROLL:
5358 EventConstructor = SyntheticUIEvent;
5359 break;
5360 case TOP_WHEEL:
5361 EventConstructor = SyntheticWheelEvent;
5362 break;
5363 case TOP_COPY:
5364 case TOP_CUT:
5365 case TOP_PASTE:
5366 EventConstructor = SyntheticClipboardEvent;
5367 break;
5368 case TOP_GOT_POINTER_CAPTURE:
5369 case TOP_LOST_POINTER_CAPTURE:
5370 case TOP_POINTER_CANCEL:
5371 case TOP_POINTER_DOWN:
5372 case TOP_POINTER_MOVE:
5373 case TOP_POINTER_OUT:
5374 case TOP_POINTER_OVER:
5375 case TOP_POINTER_UP:
5376 EventConstructor = SyntheticPointerEvent;
5377 break;
5378 default:
5379 {
5380 if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {
5381 warningWithoutStack$1(false, 'SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType);
5382 }
5383 }
5384 // HTML Events
5385 // @see http://www.w3.org/TR/html5/index.html#events-0
5386 EventConstructor = SyntheticEvent;
5387 break;
5388 }
5389 var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
5390 accumulateTwoPhaseDispatches(event);
5391 return event;
5392 }
5393};
5394
5395var passiveBrowserEventsSupported = false;
5396
5397// Check if browser support events with passive listeners
5398// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
5399if (enableEventAPI && canUseDOM) {
5400 try {
5401 var options = {};
5402 // $FlowFixMe: Ignore Flow complaining about needing a value
5403 Object.defineProperty(options, 'passive', {
5404 get: function () {
5405 passiveBrowserEventsSupported = true;
5406 }
5407 });
5408 window.addEventListener('test', options, options);
5409 window.removeEventListener('test', options, options);
5410 } catch (e) {
5411 passiveBrowserEventsSupported = false;
5412 }
5413}
5414
5415var isInteractiveTopLevelEventType = SimpleEventPlugin.isInteractiveTopLevelEventType;
5416
5417
5418var CALLBACK_BOOKKEEPING_POOL_SIZE = 10;
5419var callbackBookkeepingPool = [];
5420
5421/**
5422 * Find the deepest React component completely containing the root of the
5423 * passed-in instance (for use when entire React trees are nested within each
5424 * other). If React trees are not nested, returns null.
5425 */
5426function findRootContainerNode(inst) {
5427 // TODO: It may be a good idea to cache this to prevent unnecessary DOM
5428 // traversal, but caching is difficult to do correctly without using a
5429 // mutation observer to listen for all DOM changes.
5430 while (inst.return) {
5431 inst = inst.return;
5432 }
5433 if (inst.tag !== HostRoot) {
5434 // This can happen if we're in a detached tree.
5435 return null;
5436 }
5437 return inst.stateNode.containerInfo;
5438}
5439
5440// Used to store ancestor hierarchy in top level callback
5441function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags) {
5442 if (callbackBookkeepingPool.length) {
5443 var instance = callbackBookkeepingPool.pop();
5444 instance.topLevelType = topLevelType;
5445 instance.nativeEvent = nativeEvent;
5446 instance.targetInst = targetInst;
5447 instance.eventSystemFlags = eventSystemFlags;
5448 return instance;
5449 }
5450 return {
5451 topLevelType: topLevelType,
5452 nativeEvent: nativeEvent,
5453 targetInst: targetInst,
5454 ancestors: [],
5455 eventSystemFlags: eventSystemFlags
5456 };
5457}
5458
5459function releaseTopLevelCallbackBookKeeping(instance) {
5460 instance.topLevelType = null;
5461 instance.nativeEvent = null;
5462 instance.targetInst = null;
5463 instance.ancestors.length = 0;
5464 instance.eventSystemFlags = 0;
5465 if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) {
5466 callbackBookkeepingPool.push(instance);
5467 }
5468}
5469
5470function handleTopLevel(bookKeeping) {
5471 var targetInst = bookKeeping.targetInst;
5472
5473 // Loop through the hierarchy, in case there's any nested components.
5474 // It's important that we build the array of ancestors before calling any
5475 // event handlers, because event handlers can modify the DOM, leading to
5476 // inconsistencies with ReactMount's node cache. See #1105.
5477 var ancestor = targetInst;
5478 do {
5479 if (!ancestor) {
5480 var _ancestors = bookKeeping.ancestors;
5481 _ancestors.push(ancestor);
5482 break;
5483 }
5484 var root = findRootContainerNode(ancestor);
5485 if (!root) {
5486 break;
5487 }
5488 bookKeeping.ancestors.push(ancestor);
5489 ancestor = getClosestInstanceFromNode(root);
5490 } while (ancestor);
5491
5492 for (var i = 0; i < bookKeeping.ancestors.length; i++) {
5493 targetInst = bookKeeping.ancestors[i];
5494 var _eventSystemFlags = bookKeeping.eventSystemFlags;
5495 var eventTarget = getEventTarget(bookKeeping.nativeEvent);
5496 var _topLevelType = bookKeeping.topLevelType;
5497 var _nativeEvent = bookKeeping.nativeEvent;
5498
5499 if (_eventSystemFlags === PLUGIN_EVENT_SYSTEM) {
5500 runExtractedPluginEventsInBatch(_topLevelType, targetInst, _nativeEvent, eventTarget);
5501 } else if (enableEventAPI) {
5502 // Responder event system (experimental event API)
5503 runResponderEventsInBatch(_topLevelType, targetInst, _nativeEvent, eventTarget, _eventSystemFlags);
5504 }
5505 }
5506}
5507
5508// TODO: can we stop exporting these?
5509var _enabled = true;
5510
5511function setEnabled(enabled) {
5512 _enabled = !!enabled;
5513}
5514
5515function isEnabled() {
5516 return _enabled;
5517}
5518
5519function trapBubbledEvent(topLevelType, element) {
5520 trapEventForPluginEventSystem(element, topLevelType, false);
5521}
5522
5523function trapCapturedEvent(topLevelType, element) {
5524 trapEventForPluginEventSystem(element, topLevelType, true);
5525}
5526
5527function trapEventForResponderEventSystem(element, topLevelType, capture, passive) {
5528 if (enableEventAPI) {
5529 var rawEventName = getRawEventName(topLevelType);
5530 var eventFlags = RESPONDER_EVENT_SYSTEM;
5531
5532 // If passive option is not supported, then the event will be
5533 // active and not passive, but we flag it as using not being
5534 // supported too. This way the responder event plugins know,
5535 // and can provide polyfills if needed.
5536 if (passive) {
5537 if (passiveBrowserEventsSupported) {
5538 eventFlags |= IS_PASSIVE;
5539 } else {
5540 eventFlags |= IS_ACTIVE;
5541 eventFlags |= PASSIVE_NOT_SUPPORTED;
5542 passive = false;
5543 }
5544 } else {
5545 eventFlags |= IS_ACTIVE;
5546 }
5547 // Check if interactive and wrap in interactiveUpdates
5548 var listener = dispatchEvent.bind(null, topLevelType, eventFlags);
5549 addEventListener(element, rawEventName, listener, {
5550 capture: capture,
5551 passive: passive
5552 });
5553 }
5554}
5555
5556function trapEventForPluginEventSystem(element, topLevelType, capture) {
5557 var dispatch = isInteractiveTopLevelEventType(topLevelType) ? dispatchInteractiveEvent : dispatchEvent;
5558 var rawEventName = getRawEventName(topLevelType);
5559 // Check if interactive and wrap in interactiveUpdates
5560 var listener = dispatch.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
5561 if (capture) {
5562 addEventCaptureListener(element, rawEventName, listener);
5563 } else {
5564 addEventBubbleListener(element, rawEventName, listener);
5565 }
5566}
5567
5568function dispatchInteractiveEvent(topLevelType, eventSystemFlags, nativeEvent) {
5569 interactiveUpdates(dispatchEvent, topLevelType, eventSystemFlags, nativeEvent);
5570}
5571
5572function dispatchEvent(topLevelType, eventSystemFlags, nativeEvent) {
5573 if (!_enabled) {
5574 return;
5575 }
5576
5577 var nativeEventTarget = getEventTarget(nativeEvent);
5578 var targetInst = getClosestInstanceFromNode(nativeEventTarget);
5579 if (targetInst !== null && typeof targetInst.tag === 'number' && !isFiberMounted(targetInst)) {
5580 // If we get an event (ex: img onload) before committing that
5581 // component's mount, ignore it for now (that is, treat it as if it was an
5582 // event on a non-React tree). We might also consider queueing events and
5583 // dispatching them after the mount.
5584 targetInst = null;
5585 }
5586
5587 var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags);
5588
5589 try {
5590 // Event queue being processed in the same cycle allows
5591 // `preventDefault`.
5592 batchedUpdates(handleTopLevel, bookKeeping);
5593 } finally {
5594 releaseTopLevelCallbackBookKeeping(bookKeeping);
5595 }
5596}
5597
5598/**
5599 * Summary of `ReactBrowserEventEmitter` event handling:
5600 *
5601 * - Top-level delegation is used to trap most native browser events. This
5602 * may only occur in the main thread and is the responsibility of
5603 * ReactDOMEventListener, which is injected and can therefore support
5604 * pluggable event sources. This is the only work that occurs in the main
5605 * thread.
5606 *
5607 * - We normalize and de-duplicate events to account for browser quirks. This
5608 * may be done in the worker thread.
5609 *
5610 * - Forward these native events (with the associated top-level type used to
5611 * trap it) to `EventPluginHub`, which in turn will ask plugins if they want
5612 * to extract any synthetic events.
5613 *
5614 * - The `EventPluginHub` will then process each event by annotating them with
5615 * "dispatches", a sequence of listeners and IDs that care about that event.
5616 *
5617 * - The `EventPluginHub` then dispatches the events.
5618 *
5619 * Overview of React and the event system:
5620 *
5621 * +------------+ .
5622 * | DOM | .
5623 * +------------+ .
5624 * | .
5625 * v .
5626 * +------------+ .
5627 * | ReactEvent | .
5628 * | Listener | .
5629 * +------------+ . +-----------+
5630 * | . +--------+|SimpleEvent|
5631 * | . | |Plugin |
5632 * +-----|------+ . v +-----------+
5633 * | | | . +--------------+ +------------+
5634 * | +-----------.--->|EventPluginHub| | Event |
5635 * | | . | | +-----------+ | Propagators|
5636 * | ReactEvent | . | | |TapEvent | |------------|
5637 * | Emitter | . | |<---+|Plugin | |other plugin|
5638 * | | . | | +-----------+ | utilities |
5639 * | +-----------.--->| | +------------+
5640 * | | | . +--------------+
5641 * +-----|------+ . ^ +-----------+
5642 * | . | |Enter/Leave|
5643 * + . +-------+|Plugin |
5644 * +-------------+ . +-----------+
5645 * | application | .
5646 * |-------------| .
5647 * | | .
5648 * | | .
5649 * +-------------+ .
5650 * .
5651 * React Core . General Purpose Event Plugin System
5652 */
5653
5654var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
5655var elementListeningSets = new PossiblyWeakMap();
5656
5657function getListeningSetForElement(element) {
5658 var listeningSet = elementListeningSets.get(element);
5659 if (listeningSet === undefined) {
5660 listeningSet = new Set();
5661 elementListeningSets.set(element, listeningSet);
5662 }
5663 return listeningSet;
5664}
5665
5666/**
5667 * We listen for bubbled touch events on the document object.
5668 *
5669 * Firefox v8.01 (and possibly others) exhibited strange behavior when
5670 * mounting `onmousemove` events at some node that was not the document
5671 * element. The symptoms were that if your mouse is not moving over something
5672 * contained within that mount point (for example on the background) the
5673 * top-level listeners for `onmousemove` won't be called. However, if you
5674 * register the `mousemove` on the document object, then it will of course
5675 * catch all `mousemove`s. This along with iOS quirks, justifies restricting
5676 * top-level listeners to the document object only, at least for these
5677 * movement types of events and possibly all events.
5678 *
5679 * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
5680 *
5681 * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
5682 * they bubble to document.
5683 *
5684 * @param {string} registrationName Name of listener (e.g. `onClick`).
5685 * @param {object} mountAt Container where to mount the listener
5686 */
5687function listenTo(registrationName, mountAt) {
5688 var listeningSet = getListeningSetForElement(mountAt);
5689 var dependencies = registrationNameDependencies[registrationName];
5690
5691 for (var i = 0; i < dependencies.length; i++) {
5692 var dependency = dependencies[i];
5693 if (!listeningSet.has(dependency)) {
5694 switch (dependency) {
5695 case TOP_SCROLL:
5696 trapCapturedEvent(TOP_SCROLL, mountAt);
5697 break;
5698 case TOP_FOCUS:
5699 case TOP_BLUR:
5700 trapCapturedEvent(TOP_FOCUS, mountAt);
5701 trapCapturedEvent(TOP_BLUR, mountAt);
5702 // We set the flag for a single dependency later in this function,
5703 // but this ensures we mark both as attached rather than just one.
5704 listeningSet.add(TOP_BLUR);
5705 listeningSet.add(TOP_FOCUS);
5706 break;
5707 case TOP_CANCEL:
5708 case TOP_CLOSE:
5709 if (isEventSupported(getRawEventName(dependency))) {
5710 trapCapturedEvent(dependency, mountAt);
5711 }
5712 break;
5713 case TOP_INVALID:
5714 case TOP_SUBMIT:
5715 case TOP_RESET:
5716 // We listen to them on the target DOM elements.
5717 // Some of them bubble so we don't want them to fire twice.
5718 break;
5719 default:
5720 // By default, listen on the top level to all non-media events.
5721 // Media events don't bubble so adding the listener wouldn't do anything.
5722 var isMediaEvent = mediaEventTypes.indexOf(dependency) !== -1;
5723 if (!isMediaEvent) {
5724 trapBubbledEvent(dependency, mountAt);
5725 }
5726 break;
5727 }
5728 listeningSet.add(dependency);
5729 }
5730 }
5731}
5732
5733function isListeningToAllDependencies(registrationName, mountAt) {
5734 var listeningSet = getListeningSetForElement(mountAt);
5735 var dependencies = registrationNameDependencies[registrationName];
5736
5737 for (var i = 0; i < dependencies.length; i++) {
5738 var dependency = dependencies[i];
5739 if (!listeningSet.has(dependency)) {
5740 return false;
5741 }
5742 }
5743 return true;
5744}
5745
5746function getActiveElement(doc) {
5747 doc = doc || (typeof document !== 'undefined' ? document : undefined);
5748 if (typeof doc === 'undefined') {
5749 return null;
5750 }
5751 try {
5752 return doc.activeElement || doc.body;
5753 } catch (e) {
5754 return doc.body;
5755 }
5756}
5757
5758/**
5759 * Given any node return the first leaf node without children.
5760 *
5761 * @param {DOMElement|DOMTextNode} node
5762 * @return {DOMElement|DOMTextNode}
5763 */
5764function getLeafNode(node) {
5765 while (node && node.firstChild) {
5766 node = node.firstChild;
5767 }
5768 return node;
5769}
5770
5771/**
5772 * Get the next sibling within a container. This will walk up the
5773 * DOM if a node's siblings have been exhausted.
5774 *
5775 * @param {DOMElement|DOMTextNode} node
5776 * @return {?DOMElement|DOMTextNode}
5777 */
5778function getSiblingNode(node) {
5779 while (node) {
5780 if (node.nextSibling) {
5781 return node.nextSibling;
5782 }
5783 node = node.parentNode;
5784 }
5785}
5786
5787/**
5788 * Get object describing the nodes which contain characters at offset.
5789 *
5790 * @param {DOMElement|DOMTextNode} root
5791 * @param {number} offset
5792 * @return {?object}
5793 */
5794function getNodeForCharacterOffset(root, offset) {
5795 var node = getLeafNode(root);
5796 var nodeStart = 0;
5797 var nodeEnd = 0;
5798
5799 while (node) {
5800 if (node.nodeType === TEXT_NODE) {
5801 nodeEnd = nodeStart + node.textContent.length;
5802
5803 if (nodeStart <= offset && nodeEnd >= offset) {
5804 return {
5805 node: node,
5806 offset: offset - nodeStart
5807 };
5808 }
5809
5810 nodeStart = nodeEnd;
5811 }
5812
5813 node = getLeafNode(getSiblingNode(node));
5814 }
5815}
5816
5817/**
5818 * @param {DOMElement} outerNode
5819 * @return {?object}
5820 */
5821function getOffsets(outerNode) {
5822 var ownerDocument = outerNode.ownerDocument;
5823
5824 var win = ownerDocument && ownerDocument.defaultView || window;
5825 var selection = win.getSelection && win.getSelection();
5826
5827 if (!selection || selection.rangeCount === 0) {
5828 return null;
5829 }
5830
5831 var anchorNode = selection.anchorNode,
5832 anchorOffset = selection.anchorOffset,
5833 focusNode = selection.focusNode,
5834 focusOffset = selection.focusOffset;
5835
5836 // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
5837 // up/down buttons on an <input type="number">. Anonymous divs do not seem to
5838 // expose properties, triggering a "Permission denied error" if any of its
5839 // properties are accessed. The only seemingly possible way to avoid erroring
5840 // is to access a property that typically works for non-anonymous divs and
5841 // catch any error that may otherwise arise. See
5842 // https://bugzilla.mozilla.org/show_bug.cgi?id=208427
5843
5844 try {
5845 /* eslint-disable no-unused-expressions */
5846 anchorNode.nodeType;
5847 focusNode.nodeType;
5848 /* eslint-enable no-unused-expressions */
5849 } catch (e) {
5850 return null;
5851 }
5852
5853 return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
5854}
5855
5856/**
5857 * Returns {start, end} where `start` is the character/codepoint index of
5858 * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
5859 * `end` is the index of (focusNode, focusOffset).
5860 *
5861 * Returns null if you pass in garbage input but we should probably just crash.
5862 *
5863 * Exported only for testing.
5864 */
5865function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
5866 var length = 0;
5867 var start = -1;
5868 var end = -1;
5869 var indexWithinAnchor = 0;
5870 var indexWithinFocus = 0;
5871 var node = outerNode;
5872 var parentNode = null;
5873
5874 outer: while (true) {
5875 var next = null;
5876
5877 while (true) {
5878 if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
5879 start = length + anchorOffset;
5880 }
5881 if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
5882 end = length + focusOffset;
5883 }
5884
5885 if (node.nodeType === TEXT_NODE) {
5886 length += node.nodeValue.length;
5887 }
5888
5889 if ((next = node.firstChild) === null) {
5890 break;
5891 }
5892 // Moving from `node` to its first child `next`.
5893 parentNode = node;
5894 node = next;
5895 }
5896
5897 while (true) {
5898 if (node === outerNode) {
5899 // If `outerNode` has children, this is always the second time visiting
5900 // it. If it has no children, this is still the first loop, and the only
5901 // valid selection is anchorNode and focusNode both equal to this node
5902 // and both offsets 0, in which case we will have handled above.
5903 break outer;
5904 }
5905 if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
5906 start = length;
5907 }
5908 if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
5909 end = length;
5910 }
5911 if ((next = node.nextSibling) !== null) {
5912 break;
5913 }
5914 node = parentNode;
5915 parentNode = node.parentNode;
5916 }
5917
5918 // Moving from `node` to its next sibling `next`.
5919 node = next;
5920 }
5921
5922 if (start === -1 || end === -1) {
5923 // This should never happen. (Would happen if the anchor/focus nodes aren't
5924 // actually inside the passed-in node.)
5925 return null;
5926 }
5927
5928 return {
5929 start: start,
5930 end: end
5931 };
5932}
5933
5934/**
5935 * In modern non-IE browsers, we can support both forward and backward
5936 * selections.
5937 *
5938 * Note: IE10+ supports the Selection object, but it does not support
5939 * the `extend` method, which means that even in modern IE, it's not possible
5940 * to programmatically create a backward selection. Thus, for all IE
5941 * versions, we use the old IE API to create our selections.
5942 *
5943 * @param {DOMElement|DOMTextNode} node
5944 * @param {object} offsets
5945 */
5946function setOffsets(node, offsets) {
5947 var doc = node.ownerDocument || document;
5948 var win = doc && doc.defaultView || window;
5949
5950 // Edge fails with "Object expected" in some scenarios.
5951 // (For instance: TinyMCE editor used in a list component that supports pasting to add more,
5952 // fails when pasting 100+ items)
5953 if (!win.getSelection) {
5954 return;
5955 }
5956
5957 var selection = win.getSelection();
5958 var length = node.textContent.length;
5959 var start = Math.min(offsets.start, length);
5960 var end = offsets.end === undefined ? start : Math.min(offsets.end, length);
5961
5962 // IE 11 uses modern selection, but doesn't support the extend method.
5963 // Flip backward selections, so we can set with a single range.
5964 if (!selection.extend && start > end) {
5965 var temp = end;
5966 end = start;
5967 start = temp;
5968 }
5969
5970 var startMarker = getNodeForCharacterOffset(node, start);
5971 var endMarker = getNodeForCharacterOffset(node, end);
5972
5973 if (startMarker && endMarker) {
5974 if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
5975 return;
5976 }
5977 var range = doc.createRange();
5978 range.setStart(startMarker.node, startMarker.offset);
5979 selection.removeAllRanges();
5980
5981 if (start > end) {
5982 selection.addRange(range);
5983 selection.extend(endMarker.node, endMarker.offset);
5984 } else {
5985 range.setEnd(endMarker.node, endMarker.offset);
5986 selection.addRange(range);
5987 }
5988 }
5989}
5990
5991function isTextNode(node) {
5992 return node && node.nodeType === TEXT_NODE;
5993}
5994
5995function containsNode(outerNode, innerNode) {
5996 if (!outerNode || !innerNode) {
5997 return false;
5998 } else if (outerNode === innerNode) {
5999 return true;
6000 } else if (isTextNode(outerNode)) {
6001 return false;
6002 } else if (isTextNode(innerNode)) {
6003 return containsNode(outerNode, innerNode.parentNode);
6004 } else if ('contains' in outerNode) {
6005 return outerNode.contains(innerNode);
6006 } else if (outerNode.compareDocumentPosition) {
6007 return !!(outerNode.compareDocumentPosition(innerNode) & 16);
6008 } else {
6009 return false;
6010 }
6011}
6012
6013function isInDocument(node) {
6014 return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
6015}
6016
6017function isSameOriginFrame(iframe) {
6018 try {
6019 // Accessing the contentDocument of a HTMLIframeElement can cause the browser
6020 // to throw, e.g. if it has a cross-origin src attribute.
6021 // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
6022 // iframe.contentDocument.defaultView;
6023 // A safety way is to access one of the cross origin properties: Window or Location
6024 // Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
6025 // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
6026
6027 return typeof iframe.contentWindow.location.href === 'string';
6028 } catch (err) {
6029 return false;
6030 }
6031}
6032
6033function getActiveElementDeep() {
6034 var win = window;
6035 var element = getActiveElement();
6036 while (element instanceof win.HTMLIFrameElement) {
6037 if (isSameOriginFrame(element)) {
6038 win = element.contentWindow;
6039 } else {
6040 return element;
6041 }
6042 element = getActiveElement(win.document);
6043 }
6044 return element;
6045}
6046
6047/**
6048 * @ReactInputSelection: React input selection module. Based on Selection.js,
6049 * but modified to be suitable for react and has a couple of bug fixes (doesn't
6050 * assume buttons have range selections allowed).
6051 * Input selection module for React.
6052 */
6053
6054/**
6055 * @hasSelectionCapabilities: we get the element types that support selection
6056 * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
6057 * and `selectionEnd` rows.
6058 */
6059function hasSelectionCapabilities(elem) {
6060 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
6061 return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
6062}
6063
6064function getSelectionInformation() {
6065 var focusedElem = getActiveElementDeep();
6066 return {
6067 focusedElem: focusedElem,
6068 selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection$1(focusedElem) : null
6069 };
6070}
6071
6072/**
6073 * @restoreSelection: If any selection information was potentially lost,
6074 * restore it. This is useful when performing operations that could remove dom
6075 * nodes and place them back in, resulting in focus being lost.
6076 */
6077function restoreSelection(priorSelectionInformation) {
6078 var curFocusedElem = getActiveElementDeep();
6079 var priorFocusedElem = priorSelectionInformation.focusedElem;
6080 var priorSelectionRange = priorSelectionInformation.selectionRange;
6081 if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
6082 if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
6083 setSelection(priorFocusedElem, priorSelectionRange);
6084 }
6085
6086 // Focusing a node can change the scroll position, which is undesirable
6087 var ancestors = [];
6088 var ancestor = priorFocusedElem;
6089 while (ancestor = ancestor.parentNode) {
6090 if (ancestor.nodeType === ELEMENT_NODE) {
6091 ancestors.push({
6092 element: ancestor,
6093 left: ancestor.scrollLeft,
6094 top: ancestor.scrollTop
6095 });
6096 }
6097 }
6098
6099 if (typeof priorFocusedElem.focus === 'function') {
6100 priorFocusedElem.focus();
6101 }
6102
6103 for (var i = 0; i < ancestors.length; i++) {
6104 var info = ancestors[i];
6105 info.element.scrollLeft = info.left;
6106 info.element.scrollTop = info.top;
6107 }
6108 }
6109}
6110
6111/**
6112 * @getSelection: Gets the selection bounds of a focused textarea, input or
6113 * contentEditable node.
6114 * -@input: Look up selection bounds of this input
6115 * -@return {start: selectionStart, end: selectionEnd}
6116 */
6117function getSelection$1(input) {
6118 var selection = void 0;
6119
6120 if ('selectionStart' in input) {
6121 // Modern browser with input or textarea.
6122 selection = {
6123 start: input.selectionStart,
6124 end: input.selectionEnd
6125 };
6126 } else {
6127 // Content editable or old IE textarea.
6128 selection = getOffsets(input);
6129 }
6130
6131 return selection || { start: 0, end: 0 };
6132}
6133
6134/**
6135 * @setSelection: Sets the selection bounds of a textarea or input and focuses
6136 * the input.
6137 * -@input Set selection bounds of this input or textarea
6138 * -@offsets Object of same form that is returned from get*
6139 */
6140function setSelection(input, offsets) {
6141 var start = offsets.start,
6142 end = offsets.end;
6143
6144 if (end === undefined) {
6145 end = start;
6146 }
6147
6148 if ('selectionStart' in input) {
6149 input.selectionStart = start;
6150 input.selectionEnd = Math.min(end, input.value.length);
6151 } else {
6152 setOffsets(input, offsets);
6153 }
6154}
6155
6156var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;
6157
6158var eventTypes$3 = {
6159 select: {
6160 phasedRegistrationNames: {
6161 bubbled: 'onSelect',
6162 captured: 'onSelectCapture'
6163 },
6164 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]
6165 }
6166};
6167
6168var activeElement$1 = null;
6169var activeElementInst$1 = null;
6170var lastSelection = null;
6171var mouseDown = false;
6172
6173/**
6174 * Get an object which is a unique representation of the current selection.
6175 *
6176 * The return value will not be consistent across nodes or browsers, but
6177 * two identical selections on the same node will return identical objects.
6178 *
6179 * @param {DOMElement} node
6180 * @return {object}
6181 */
6182function getSelection(node) {
6183 if ('selectionStart' in node && hasSelectionCapabilities(node)) {
6184 return {
6185 start: node.selectionStart,
6186 end: node.selectionEnd
6187 };
6188 } else {
6189 var win = node.ownerDocument && node.ownerDocument.defaultView || window;
6190 var selection = win.getSelection();
6191 return {
6192 anchorNode: selection.anchorNode,
6193 anchorOffset: selection.anchorOffset,
6194 focusNode: selection.focusNode,
6195 focusOffset: selection.focusOffset
6196 };
6197 }
6198}
6199
6200/**
6201 * Get document associated with the event target.
6202 *
6203 * @param {object} nativeEventTarget
6204 * @return {Document}
6205 */
6206function getEventTargetDocument(eventTarget) {
6207 return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
6208}
6209
6210/**
6211 * Poll selection to see whether it's changed.
6212 *
6213 * @param {object} nativeEvent
6214 * @param {object} nativeEventTarget
6215 * @return {?SyntheticEvent}
6216 */
6217function constructSelectEvent(nativeEvent, nativeEventTarget) {
6218 // Ensure we have the right element, and that the user is not dragging a
6219 // selection (this matches native `select` event behavior). In HTML5, select
6220 // fires only on input and textarea thus if there's no focused element we
6221 // won't dispatch.
6222 var doc = getEventTargetDocument(nativeEventTarget);
6223
6224 if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
6225 return null;
6226 }
6227
6228 // Only fire when selection has actually changed.
6229 var currentSelection = getSelection(activeElement$1);
6230 if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
6231 lastSelection = currentSelection;
6232
6233 var syntheticEvent = SyntheticEvent.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget);
6234
6235 syntheticEvent.type = 'select';
6236 syntheticEvent.target = activeElement$1;
6237
6238 accumulateTwoPhaseDispatches(syntheticEvent);
6239
6240 return syntheticEvent;
6241 }
6242
6243 return null;
6244}
6245
6246/**
6247 * This plugin creates an `onSelect` event that normalizes select events
6248 * across form elements.
6249 *
6250 * Supported elements are:
6251 * - input (see `isTextInputElement`)
6252 * - textarea
6253 * - contentEditable
6254 *
6255 * This differs from native browser implementations in the following ways:
6256 * - Fires on contentEditable fields as well as inputs.
6257 * - Fires for collapsed selection.
6258 * - Fires after user input.
6259 */
6260var SelectEventPlugin = {
6261 eventTypes: eventTypes$3,
6262
6263 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
6264 var doc = getEventTargetDocument(nativeEventTarget);
6265 // Track whether all listeners exists for this plugin. If none exist, we do
6266 // not extract events. See #3639.
6267 if (!doc || !isListeningToAllDependencies('onSelect', doc)) {
6268 return null;
6269 }
6270
6271 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
6272
6273 switch (topLevelType) {
6274 // Track the input node that has focus.
6275 case TOP_FOCUS:
6276 if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
6277 activeElement$1 = targetNode;
6278 activeElementInst$1 = targetInst;
6279 lastSelection = null;
6280 }
6281 break;
6282 case TOP_BLUR:
6283 activeElement$1 = null;
6284 activeElementInst$1 = null;
6285 lastSelection = null;
6286 break;
6287 // Don't fire the event while the user is dragging. This matches the
6288 // semantics of the native select event.
6289 case TOP_MOUSE_DOWN:
6290 mouseDown = true;
6291 break;
6292 case TOP_CONTEXT_MENU:
6293 case TOP_MOUSE_UP:
6294 case TOP_DRAG_END:
6295 mouseDown = false;
6296 return constructSelectEvent(nativeEvent, nativeEventTarget);
6297 // Chrome and IE fire non-standard event when selection is changed (and
6298 // sometimes when it hasn't). IE's event fires out of order with respect
6299 // to key and input events on deletion, so we discard it.
6300 //
6301 // Firefox doesn't support selectionchange, so check selection status
6302 // after each key entry. The selection changes after keydown and before
6303 // keyup, but we check on keydown as well in the case of holding down a
6304 // key, when multiple keydown events are fired but only one keyup is.
6305 // This is also our approach for IE handling, for the reason above.
6306 case TOP_SELECTION_CHANGE:
6307 if (skipSelectionChangeEvent) {
6308 break;
6309 }
6310 // falls through
6311 case TOP_KEY_DOWN:
6312 case TOP_KEY_UP:
6313 return constructSelectEvent(nativeEvent, nativeEventTarget);
6314 }
6315
6316 return null;
6317 }
6318};
6319
6320/**
6321 * Inject modules for resolving DOM hierarchy and plugin ordering.
6322 */
6323injection.injectEventPluginOrder(DOMEventPluginOrder);
6324setComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);
6325
6326/**
6327 * Some important event plugins included by default (without having to require
6328 * them).
6329 */
6330injection.injectEventPluginsByName({
6331 SimpleEventPlugin: SimpleEventPlugin,
6332 EnterLeaveEventPlugin: EnterLeaveEventPlugin,
6333 ChangeEventPlugin: ChangeEventPlugin,
6334 SelectEventPlugin: SelectEventPlugin,
6335 BeforeInputEventPlugin: BeforeInputEventPlugin
6336});
6337
6338var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
6339
6340var _ReactInternals$Sched = ReactInternals$1.Scheduler;
6341var unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback;
6342var unstable_now = _ReactInternals$Sched.unstable_now;
6343var unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback;
6344var unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield;
6345var unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode;
6346var unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority;
6347var unstable_next = _ReactInternals$Sched.unstable_next;
6348var unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution;
6349var unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution;
6350var unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel;
6351var unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority;
6352var unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority;
6353var unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority;
6354var unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority;
6355var unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority;
6356
6357var didWarnSelectedSetOnOption = false;
6358var didWarnInvalidChild = false;
6359
6360function flattenChildren(children) {
6361 var content = '';
6362
6363 // Flatten children. We'll warn if they are invalid
6364 // during validateProps() which runs for hydration too.
6365 // Note that this would throw on non-element objects.
6366 // Elements are stringified (which is normally irrelevant
6367 // but matters for <fbt>).
6368 React.Children.forEach(children, function (child) {
6369 if (child == null) {
6370 return;
6371 }
6372 content += child;
6373 // Note: we don't warn about invalid children here.
6374 // Instead, this is done separately below so that
6375 // it happens during the hydration codepath too.
6376 });
6377
6378 return content;
6379}
6380
6381/**
6382 * Implements an <option> host component that warns when `selected` is set.
6383 */
6384
6385function validateProps(element, props) {
6386 {
6387 // This mirrors the codepath above, but runs for hydration too.
6388 // Warn about invalid children here so that client and hydration are consistent.
6389 // TODO: this seems like it could cause a DEV-only throw for hydration
6390 // if children contains a non-element object. We should try to avoid that.
6391 if (typeof props.children === 'object' && props.children !== null) {
6392 React.Children.forEach(props.children, function (child) {
6393 if (child == null) {
6394 return;
6395 }
6396 if (typeof child === 'string' || typeof child === 'number') {
6397 return;
6398 }
6399 if (typeof child.type !== 'string') {
6400 return;
6401 }
6402 if (!didWarnInvalidChild) {
6403 didWarnInvalidChild = true;
6404 warning$1(false, 'Only strings and numbers are supported as <option> children.');
6405 }
6406 });
6407 }
6408
6409 // TODO: Remove support for `selected` in <option>.
6410 if (props.selected != null && !didWarnSelectedSetOnOption) {
6411 warning$1(false, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
6412 didWarnSelectedSetOnOption = true;
6413 }
6414 }
6415}
6416
6417function postMountWrapper$1(element, props) {
6418 // value="" should make a value attribute (#6219)
6419 if (props.value != null) {
6420 element.setAttribute('value', toString(getToStringValue(props.value)));
6421 }
6422}
6423
6424function getHostProps$1(element, props) {
6425 var hostProps = _assign({ children: undefined }, props);
6426 var content = flattenChildren(props.children);
6427
6428 if (content) {
6429 hostProps.children = content;
6430 }
6431
6432 return hostProps;
6433}
6434
6435// TODO: direct imports like some-package/src/* are bad. Fix me.
6436var didWarnValueDefaultValue$1 = void 0;
6437
6438{
6439 didWarnValueDefaultValue$1 = false;
6440}
6441
6442function getDeclarationErrorAddendum() {
6443 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
6444 if (ownerName) {
6445 return '\n\nCheck the render method of `' + ownerName + '`.';
6446 }
6447 return '';
6448}
6449
6450var valuePropNames = ['value', 'defaultValue'];
6451
6452/**
6453 * Validation function for `value` and `defaultValue`.
6454 */
6455function checkSelectPropTypes(props) {
6456 ReactControlledValuePropTypes.checkPropTypes('select', props);
6457
6458 for (var i = 0; i < valuePropNames.length; i++) {
6459 var propName = valuePropNames[i];
6460 if (props[propName] == null) {
6461 continue;
6462 }
6463 var isArray = Array.isArray(props[propName]);
6464 if (props.multiple && !isArray) {
6465 warning$1(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
6466 } else if (!props.multiple && isArray) {
6467 warning$1(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
6468 }
6469 }
6470}
6471
6472function updateOptions(node, multiple, propValue, setDefaultSelected) {
6473 var options = node.options;
6474
6475 if (multiple) {
6476 var selectedValues = propValue;
6477 var selectedValue = {};
6478 for (var i = 0; i < selectedValues.length; i++) {
6479 // Prefix to avoid chaos with special keys.
6480 selectedValue['$' + selectedValues[i]] = true;
6481 }
6482 for (var _i = 0; _i < options.length; _i++) {
6483 var selected = selectedValue.hasOwnProperty('$' + options[_i].value);
6484 if (options[_i].selected !== selected) {
6485 options[_i].selected = selected;
6486 }
6487 if (selected && setDefaultSelected) {
6488 options[_i].defaultSelected = true;
6489 }
6490 }
6491 } else {
6492 // Do not set `select.value` as exact behavior isn't consistent across all
6493 // browsers for all cases.
6494 var _selectedValue = toString(getToStringValue(propValue));
6495 var defaultSelected = null;
6496 for (var _i2 = 0; _i2 < options.length; _i2++) {
6497 if (options[_i2].value === _selectedValue) {
6498 options[_i2].selected = true;
6499 if (setDefaultSelected) {
6500 options[_i2].defaultSelected = true;
6501 }
6502 return;
6503 }
6504 if (defaultSelected === null && !options[_i2].disabled) {
6505 defaultSelected = options[_i2];
6506 }
6507 }
6508 if (defaultSelected !== null) {
6509 defaultSelected.selected = true;
6510 }
6511 }
6512}
6513
6514/**
6515 * Implements a <select> host component that allows optionally setting the
6516 * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
6517 * stringable. If `multiple` is true, the prop must be an array of stringables.
6518 *
6519 * If `value` is not supplied (or null/undefined), user actions that change the
6520 * selected option will trigger updates to the rendered options.
6521 *
6522 * If it is supplied (and not null/undefined), the rendered options will not
6523 * update in response to user actions. Instead, the `value` prop must change in
6524 * order for the rendered options to update.
6525 *
6526 * If `defaultValue` is provided, any options with the supplied values will be
6527 * selected.
6528 */
6529
6530function getHostProps$2(element, props) {
6531 return _assign({}, props, {
6532 value: undefined
6533 });
6534}
6535
6536function initWrapperState$1(element, props) {
6537 var node = element;
6538 {
6539 checkSelectPropTypes(props);
6540 }
6541
6542 node._wrapperState = {
6543 wasMultiple: !!props.multiple
6544 };
6545
6546 {
6547 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
6548 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');
6549 didWarnValueDefaultValue$1 = true;
6550 }
6551 }
6552}
6553
6554function postMountWrapper$2(element, props) {
6555 var node = element;
6556 node.multiple = !!props.multiple;
6557 var value = props.value;
6558 if (value != null) {
6559 updateOptions(node, !!props.multiple, value, false);
6560 } else if (props.defaultValue != null) {
6561 updateOptions(node, !!props.multiple, props.defaultValue, true);
6562 }
6563}
6564
6565function postUpdateWrapper(element, props) {
6566 var node = element;
6567 var wasMultiple = node._wrapperState.wasMultiple;
6568 node._wrapperState.wasMultiple = !!props.multiple;
6569
6570 var value = props.value;
6571 if (value != null) {
6572 updateOptions(node, !!props.multiple, value, false);
6573 } else if (wasMultiple !== !!props.multiple) {
6574 // For simplicity, reapply `defaultValue` if `multiple` is toggled.
6575 if (props.defaultValue != null) {
6576 updateOptions(node, !!props.multiple, props.defaultValue, true);
6577 } else {
6578 // Revert the select back to its default unselected state.
6579 updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
6580 }
6581 }
6582}
6583
6584function restoreControlledState$2(element, props) {
6585 var node = element;
6586 var value = props.value;
6587
6588 if (value != null) {
6589 updateOptions(node, !!props.multiple, value, false);
6590 }
6591}
6592
6593var didWarnValDefaultVal = false;
6594
6595/**
6596 * Implements a <textarea> host component that allows setting `value`, and
6597 * `defaultValue`. This differs from the traditional DOM API because value is
6598 * usually set as PCDATA children.
6599 *
6600 * If `value` is not supplied (or null/undefined), user actions that affect the
6601 * value will trigger updates to the element.
6602 *
6603 * If `value` is supplied (and not null/undefined), the rendered element will
6604 * not trigger updates to the element. Instead, the `value` prop must change in
6605 * order for the rendered element to be updated.
6606 *
6607 * The rendered element will be initialized with an empty value, the prop
6608 * `defaultValue` if specified, or the children content (deprecated).
6609 */
6610
6611function getHostProps$3(element, props) {
6612 var node = element;
6613 (function () {
6614 if (!(props.dangerouslySetInnerHTML == null)) {
6615 {
6616 throw ReactError('`dangerouslySetInnerHTML` does not make sense on <textarea>.');
6617 }
6618 }
6619 })();
6620
6621 // Always set children to the same thing. In IE9, the selection range will
6622 // get reset if `textContent` is mutated. We could add a check in setTextContent
6623 // to only set the value if/when the value differs from the node value (which would
6624 // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
6625 // solution. The value can be a boolean or object so that's why it's forced
6626 // to be a string.
6627 var hostProps = _assign({}, props, {
6628 value: undefined,
6629 defaultValue: undefined,
6630 children: toString(node._wrapperState.initialValue)
6631 });
6632
6633 return hostProps;
6634}
6635
6636function initWrapperState$2(element, props) {
6637 var node = element;
6638 {
6639 ReactControlledValuePropTypes.checkPropTypes('textarea', props);
6640 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
6641 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');
6642 didWarnValDefaultVal = true;
6643 }
6644 }
6645
6646 var initialValue = props.value;
6647
6648 // Only bother fetching default value if we're going to use it
6649 if (initialValue == null) {
6650 var defaultValue = props.defaultValue;
6651 // TODO (yungsters): Remove support for children content in <textarea>.
6652 var children = props.children;
6653 if (children != null) {
6654 {
6655 warning$1(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
6656 }
6657 (function () {
6658 if (!(defaultValue == null)) {
6659 {
6660 throw ReactError('If you supply `defaultValue` on a <textarea>, do not pass children.');
6661 }
6662 }
6663 })();
6664 if (Array.isArray(children)) {
6665 (function () {
6666 if (!(children.length <= 1)) {
6667 {
6668 throw ReactError('<textarea> can only have at most one child.');
6669 }
6670 }
6671 })();
6672 children = children[0];
6673 }
6674
6675 defaultValue = children;
6676 }
6677 if (defaultValue == null) {
6678 defaultValue = '';
6679 }
6680 initialValue = defaultValue;
6681 }
6682
6683 node._wrapperState = {
6684 initialValue: getToStringValue(initialValue)
6685 };
6686}
6687
6688function updateWrapper$1(element, props) {
6689 var node = element;
6690 var value = getToStringValue(props.value);
6691 var defaultValue = getToStringValue(props.defaultValue);
6692 if (value != null) {
6693 // Cast `value` to a string to ensure the value is set correctly. While
6694 // browsers typically do this as necessary, jsdom doesn't.
6695 var newValue = toString(value);
6696 // To avoid side effects (such as losing text selection), only set value if changed
6697 if (newValue !== node.value) {
6698 node.value = newValue;
6699 }
6700 if (props.defaultValue == null && node.defaultValue !== newValue) {
6701 node.defaultValue = newValue;
6702 }
6703 }
6704 if (defaultValue != null) {
6705 node.defaultValue = toString(defaultValue);
6706 }
6707}
6708
6709function postMountWrapper$3(element, props) {
6710 var node = element;
6711 // This is in postMount because we need access to the DOM node, which is not
6712 // available until after the component has mounted.
6713 var textContent = node.textContent;
6714
6715 // Only set node.value if textContent is equal to the expected
6716 // initial value. In IE10/IE11 there is a bug where the placeholder attribute
6717 // will populate textContent as well.
6718 // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
6719 if (textContent === node._wrapperState.initialValue) {
6720 node.value = textContent;
6721 }
6722}
6723
6724function restoreControlledState$3(element, props) {
6725 // DOM component is still mounted; update
6726 updateWrapper$1(element, props);
6727}
6728
6729var HTML_NAMESPACE$1 = 'http://www.w3.org/1999/xhtml';
6730var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
6731var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
6732
6733var Namespaces = {
6734 html: HTML_NAMESPACE$1,
6735 mathml: MATH_NAMESPACE,
6736 svg: SVG_NAMESPACE
6737};
6738
6739// Assumes there is no parent namespace.
6740function getIntrinsicNamespace(type) {
6741 switch (type) {
6742 case 'svg':
6743 return SVG_NAMESPACE;
6744 case 'math':
6745 return MATH_NAMESPACE;
6746 default:
6747 return HTML_NAMESPACE$1;
6748 }
6749}
6750
6751function getChildNamespace(parentNamespace, type) {
6752 if (parentNamespace == null || parentNamespace === HTML_NAMESPACE$1) {
6753 // No (or default) parent namespace: potential entry point.
6754 return getIntrinsicNamespace(type);
6755 }
6756 if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
6757 // We're leaving SVG.
6758 return HTML_NAMESPACE$1;
6759 }
6760 // By default, pass namespace below.
6761 return parentNamespace;
6762}
6763
6764/* globals MSApp */
6765
6766/**
6767 * Create a function which has 'unsafe' privileges (required by windows8 apps)
6768 */
6769var createMicrosoftUnsafeLocalFunction = function (func) {
6770 if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
6771 return function (arg0, arg1, arg2, arg3) {
6772 MSApp.execUnsafeLocalFunction(function () {
6773 return func(arg0, arg1, arg2, arg3);
6774 });
6775 };
6776 } else {
6777 return func;
6778 }
6779};
6780
6781// SVG temp container for IE lacking innerHTML
6782var reusableSVGContainer = void 0;
6783
6784/**
6785 * Set the innerHTML property of a node
6786 *
6787 * @param {DOMElement} node
6788 * @param {string} html
6789 * @internal
6790 */
6791var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
6792 // IE does not have innerHTML for SVG nodes, so instead we inject the
6793 // new markup in a temp node and then move the child nodes across into
6794 // the target node
6795
6796 if (node.namespaceURI === Namespaces.svg && !('innerHTML' in node)) {
6797 reusableSVGContainer = reusableSVGContainer || document.createElement('div');
6798 reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
6799 var svgNode = reusableSVGContainer.firstChild;
6800 while (node.firstChild) {
6801 node.removeChild(node.firstChild);
6802 }
6803 while (svgNode.firstChild) {
6804 node.appendChild(svgNode.firstChild);
6805 }
6806 } else {
6807 node.innerHTML = html;
6808 }
6809});
6810
6811/**
6812 * Set the textContent property of a node. For text updates, it's faster
6813 * to set the `nodeValue` of the Text node directly instead of using
6814 * `.textContent` which will remove the existing node and create a new one.
6815 *
6816 * @param {DOMElement} node
6817 * @param {string} text
6818 * @internal
6819 */
6820var setTextContent = function (node, text) {
6821 if (text) {
6822 var firstChild = node.firstChild;
6823
6824 if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
6825 firstChild.nodeValue = text;
6826 return;
6827 }
6828 }
6829 node.textContent = text;
6830};
6831
6832// List derived from Gecko source code:
6833// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
6834var shorthandToLonghand = {
6835 animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
6836 background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
6837 backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
6838 border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6839 borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
6840 borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
6841 borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
6842 borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
6843 borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
6844 borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
6845 borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
6846 borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
6847 borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
6848 borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
6849 borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
6850 borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6851 borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
6852 columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
6853 columns: ['columnCount', 'columnWidth'],
6854 flex: ['flexBasis', 'flexGrow', 'flexShrink'],
6855 flexFlow: ['flexDirection', 'flexWrap'],
6856 font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
6857 fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
6858 gap: ['columnGap', 'rowGap'],
6859 grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6860 gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
6861 gridColumn: ['gridColumnEnd', 'gridColumnStart'],
6862 gridColumnGap: ['columnGap'],
6863 gridGap: ['columnGap', 'rowGap'],
6864 gridRow: ['gridRowEnd', 'gridRowStart'],
6865 gridRowGap: ['rowGap'],
6866 gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6867 listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
6868 margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
6869 marker: ['markerEnd', 'markerMid', 'markerStart'],
6870 mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
6871 maskPosition: ['maskPositionX', 'maskPositionY'],
6872 outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
6873 overflow: ['overflowX', 'overflowY'],
6874 padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
6875 placeContent: ['alignContent', 'justifyContent'],
6876 placeItems: ['alignItems', 'justifyItems'],
6877 placeSelf: ['alignSelf', 'justifySelf'],
6878 textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
6879 textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
6880 transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
6881 wordWrap: ['overflowWrap']
6882};
6883
6884/**
6885 * CSS properties which accept numbers but are not in units of "px".
6886 */
6887var isUnitlessNumber = {
6888 animationIterationCount: true,
6889 borderImageOutset: true,
6890 borderImageSlice: true,
6891 borderImageWidth: true,
6892 boxFlex: true,
6893 boxFlexGroup: true,
6894 boxOrdinalGroup: true,
6895 columnCount: true,
6896 columns: true,
6897 flex: true,
6898 flexGrow: true,
6899 flexPositive: true,
6900 flexShrink: true,
6901 flexNegative: true,
6902 flexOrder: true,
6903 gridArea: true,
6904 gridRow: true,
6905 gridRowEnd: true,
6906 gridRowSpan: true,
6907 gridRowStart: true,
6908 gridColumn: true,
6909 gridColumnEnd: true,
6910 gridColumnSpan: true,
6911 gridColumnStart: true,
6912 fontWeight: true,
6913 lineClamp: true,
6914 lineHeight: true,
6915 opacity: true,
6916 order: true,
6917 orphans: true,
6918 tabSize: true,
6919 widows: true,
6920 zIndex: true,
6921 zoom: true,
6922
6923 // SVG-related properties
6924 fillOpacity: true,
6925 floodOpacity: true,
6926 stopOpacity: true,
6927 strokeDasharray: true,
6928 strokeDashoffset: true,
6929 strokeMiterlimit: true,
6930 strokeOpacity: true,
6931 strokeWidth: true
6932};
6933
6934/**
6935 * @param {string} prefix vendor-specific prefix, eg: Webkit
6936 * @param {string} key style name, eg: transitionDuration
6937 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
6938 * WebkitTransitionDuration
6939 */
6940function prefixKey(prefix, key) {
6941 return prefix + key.charAt(0).toUpperCase() + key.substring(1);
6942}
6943
6944/**
6945 * Support style names that may come passed in prefixed by adding permutations
6946 * of vendor prefixes.
6947 */
6948var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
6949
6950// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
6951// infinite loop, because it iterates over the newly added props too.
6952Object.keys(isUnitlessNumber).forEach(function (prop) {
6953 prefixes.forEach(function (prefix) {
6954 isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
6955 });
6956});
6957
6958/**
6959 * Convert a value into the proper css writable value. The style name `name`
6960 * should be logical (no hyphens), as specified
6961 * in `CSSProperty.isUnitlessNumber`.
6962 *
6963 * @param {string} name CSS property name such as `topMargin`.
6964 * @param {*} value CSS property value such as `10px`.
6965 * @return {string} Normalized style value with dimensions applied.
6966 */
6967function dangerousStyleValue(name, value, isCustomProperty) {
6968 // Note that we've removed escapeTextForBrowser() calls here since the
6969 // whole string will be escaped when the attribute is injected into
6970 // the markup. If you provide unsafe user data here they can inject
6971 // arbitrary CSS which may be problematic (I couldn't repro this):
6972 // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
6973 // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
6974 // This is not an XSS hole but instead a potential CSS injection issue
6975 // which has lead to a greater discussion about how we're going to
6976 // trust URLs moving forward. See #2115901
6977
6978 var isEmpty = value == null || typeof value === 'boolean' || value === '';
6979 if (isEmpty) {
6980 return '';
6981 }
6982
6983 if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
6984 return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
6985 }
6986
6987 return ('' + value).trim();
6988}
6989
6990var uppercasePattern = /([A-Z])/g;
6991var msPattern = /^ms-/;
6992
6993/**
6994 * Hyphenates a camelcased CSS property name, for example:
6995 *
6996 * > hyphenateStyleName('backgroundColor')
6997 * < "background-color"
6998 * > hyphenateStyleName('MozTransition')
6999 * < "-moz-transition"
7000 * > hyphenateStyleName('msTransition')
7001 * < "-ms-transition"
7002 *
7003 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
7004 * is converted to `-ms-`.
7005 */
7006function hyphenateStyleName(name) {
7007 return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
7008}
7009
7010var warnValidStyle = function () {};
7011
7012{
7013 // 'msTransform' is correct, but the other prefixes should be capitalized
7014 var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
7015 var msPattern$1 = /^-ms-/;
7016 var hyphenPattern = /-(.)/g;
7017
7018 // style values shouldn't contain a semicolon
7019 var badStyleValueWithSemicolonPattern = /;\s*$/;
7020
7021 var warnedStyleNames = {};
7022 var warnedStyleValues = {};
7023 var warnedForNaNValue = false;
7024 var warnedForInfinityValue = false;
7025
7026 var camelize = function (string) {
7027 return string.replace(hyphenPattern, function (_, character) {
7028 return character.toUpperCase();
7029 });
7030 };
7031
7032 var warnHyphenatedStyleName = function (name) {
7033 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
7034 return;
7035 }
7036
7037 warnedStyleNames[name] = true;
7038 warning$1(false, 'Unsupported style property %s. Did you mean %s?', name,
7039 // As Andi Smith suggests
7040 // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
7041 // is converted to lowercase `ms`.
7042 camelize(name.replace(msPattern$1, 'ms-')));
7043 };
7044
7045 var warnBadVendoredStyleName = function (name) {
7046 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
7047 return;
7048 }
7049
7050 warnedStyleNames[name] = true;
7051 warning$1(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
7052 };
7053
7054 var warnStyleValueWithSemicolon = function (name, value) {
7055 if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
7056 return;
7057 }
7058
7059 warnedStyleValues[value] = true;
7060 warning$1(false, "Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
7061 };
7062
7063 var warnStyleValueIsNaN = function (name, value) {
7064 if (warnedForNaNValue) {
7065 return;
7066 }
7067
7068 warnedForNaNValue = true;
7069 warning$1(false, '`NaN` is an invalid value for the `%s` css style property.', name);
7070 };
7071
7072 var warnStyleValueIsInfinity = function (name, value) {
7073 if (warnedForInfinityValue) {
7074 return;
7075 }
7076
7077 warnedForInfinityValue = true;
7078 warning$1(false, '`Infinity` is an invalid value for the `%s` css style property.', name);
7079 };
7080
7081 warnValidStyle = function (name, value) {
7082 if (name.indexOf('-') > -1) {
7083 warnHyphenatedStyleName(name);
7084 } else if (badVendoredStyleNamePattern.test(name)) {
7085 warnBadVendoredStyleName(name);
7086 } else if (badStyleValueWithSemicolonPattern.test(value)) {
7087 warnStyleValueWithSemicolon(name, value);
7088 }
7089
7090 if (typeof value === 'number') {
7091 if (isNaN(value)) {
7092 warnStyleValueIsNaN(name, value);
7093 } else if (!isFinite(value)) {
7094 warnStyleValueIsInfinity(name, value);
7095 }
7096 }
7097 };
7098}
7099
7100var warnValidStyle$1 = warnValidStyle;
7101
7102/**
7103 * Operations for dealing with CSS properties.
7104 */
7105
7106/**
7107 * This creates a string that is expected to be equivalent to the style
7108 * attribute generated by server-side rendering. It by-passes warnings and
7109 * security checks so it's not safe to use this value for anything other than
7110 * comparison. It is only used in DEV for SSR validation.
7111 */
7112function createDangerousStringForStyles(styles) {
7113 {
7114 var serialized = '';
7115 var delimiter = '';
7116 for (var styleName in styles) {
7117 if (!styles.hasOwnProperty(styleName)) {
7118 continue;
7119 }
7120 var styleValue = styles[styleName];
7121 if (styleValue != null) {
7122 var isCustomProperty = styleName.indexOf('--') === 0;
7123 serialized += delimiter + hyphenateStyleName(styleName) + ':';
7124 serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
7125
7126 delimiter = ';';
7127 }
7128 }
7129 return serialized || null;
7130 }
7131}
7132
7133/**
7134 * Sets the value for multiple styles on a node. If a value is specified as
7135 * '' (empty string), the corresponding style property will be unset.
7136 *
7137 * @param {DOMElement} node
7138 * @param {object} styles
7139 */
7140function setValueForStyles(node, styles) {
7141 var style = node.style;
7142 for (var styleName in styles) {
7143 if (!styles.hasOwnProperty(styleName)) {
7144 continue;
7145 }
7146 var isCustomProperty = styleName.indexOf('--') === 0;
7147 {
7148 if (!isCustomProperty) {
7149 warnValidStyle$1(styleName, styles[styleName]);
7150 }
7151 }
7152 var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
7153 if (styleName === 'float') {
7154 styleName = 'cssFloat';
7155 }
7156 if (isCustomProperty) {
7157 style.setProperty(styleName, styleValue);
7158 } else {
7159 style[styleName] = styleValue;
7160 }
7161 }
7162}
7163
7164function isValueEmpty(value) {
7165 return value == null || typeof value === 'boolean' || value === '';
7166}
7167
7168/**
7169 * Given {color: 'red', overflow: 'hidden'} returns {
7170 * color: 'color',
7171 * overflowX: 'overflow',
7172 * overflowY: 'overflow',
7173 * }. This can be read as "the overflowY property was set by the overflow
7174 * shorthand". That is, the values are the property that each was derived from.
7175 */
7176function expandShorthandMap(styles) {
7177 var expanded = {};
7178 for (var key in styles) {
7179 var longhands = shorthandToLonghand[key] || [key];
7180 for (var i = 0; i < longhands.length; i++) {
7181 expanded[longhands[i]] = key;
7182 }
7183 }
7184 return expanded;
7185}
7186
7187/**
7188 * When mixing shorthand and longhand property names, we warn during updates if
7189 * we expect an incorrect result to occur. In particular, we warn for:
7190 *
7191 * Updating a shorthand property (longhand gets overwritten):
7192 * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
7193 * becomes .style.font = 'baz'
7194 * Removing a shorthand property (longhand gets lost too):
7195 * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
7196 * becomes .style.font = ''
7197 * Removing a longhand property (should revert to shorthand; doesn't):
7198 * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
7199 * becomes .style.fontVariant = ''
7200 */
7201function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
7202 if (!warnAboutShorthandPropertyCollision) {
7203 return;
7204 }
7205
7206 if (!nextStyles) {
7207 return;
7208 }
7209
7210 var expandedUpdates = expandShorthandMap(styleUpdates);
7211 var expandedStyles = expandShorthandMap(nextStyles);
7212 var warnedAbout = {};
7213 for (var key in expandedUpdates) {
7214 var originalKey = expandedUpdates[key];
7215 var correctOriginalKey = expandedStyles[key];
7216 if (correctOriginalKey && originalKey !== correctOriginalKey) {
7217 var warningKey = originalKey + ',' + correctOriginalKey;
7218 if (warnedAbout[warningKey]) {
7219 continue;
7220 }
7221 warnedAbout[warningKey] = true;
7222 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);
7223 }
7224 }
7225}
7226
7227// For HTML, certain tags should omit their close tag. We keep a whitelist for
7228// those special-case tags.
7229
7230var omittedCloseTags = {
7231 area: true,
7232 base: true,
7233 br: true,
7234 col: true,
7235 embed: true,
7236 hr: true,
7237 img: true,
7238 input: true,
7239 keygen: true,
7240 link: true,
7241 meta: true,
7242 param: true,
7243 source: true,
7244 track: true,
7245 wbr: true
7246 // NOTE: menuitem's close tag should be omitted, but that causes problems.
7247};
7248
7249// For HTML, certain tags cannot have children. This has the same purpose as
7250// `omittedCloseTags` except that `menuitem` should still have its closing tag.
7251
7252var voidElementTags = _assign({
7253 menuitem: true
7254}, omittedCloseTags);
7255
7256// TODO: We can remove this if we add invariantWithStack()
7257// or add stack by default to invariants where possible.
7258var HTML$1 = '__html';
7259
7260var ReactDebugCurrentFrame$3 = null;
7261{
7262 ReactDebugCurrentFrame$3 = ReactSharedInternals.ReactDebugCurrentFrame;
7263}
7264
7265function assertValidProps(tag, props) {
7266 if (!props) {
7267 return;
7268 }
7269 // Note the use of `==` which checks for null or undefined.
7270 if (voidElementTags[tag]) {
7271 (function () {
7272 if (!(props.children == null && props.dangerouslySetInnerHTML == null)) {
7273 {
7274 throw ReactError(tag + ' is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.' + (ReactDebugCurrentFrame$3.getStackAddendum()));
7275 }
7276 }
7277 })();
7278 }
7279 if (props.dangerouslySetInnerHTML != null) {
7280 (function () {
7281 if (!(props.children == null)) {
7282 {
7283 throw ReactError('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
7284 }
7285 }
7286 })();
7287 (function () {
7288 if (!(typeof props.dangerouslySetInnerHTML === 'object' && HTML$1 in props.dangerouslySetInnerHTML)) {
7289 {
7290 throw ReactError('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.');
7291 }
7292 }
7293 })();
7294 }
7295 {
7296 !(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;
7297 }
7298 (function () {
7299 if (!(props.style == null || typeof props.style === 'object')) {
7300 {
7301 throw ReactError('The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}} when using JSX.' + (ReactDebugCurrentFrame$3.getStackAddendum()));
7302 }
7303 }
7304 })();
7305}
7306
7307function isCustomComponent(tagName, props) {
7308 if (tagName.indexOf('-') === -1) {
7309 return typeof props.is === 'string';
7310 }
7311 switch (tagName) {
7312 // These are reserved SVG and MathML elements.
7313 // We don't mind this whitelist too much because we expect it to never grow.
7314 // The alternative is to track the namespace in a few places which is convoluted.
7315 // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
7316 case 'annotation-xml':
7317 case 'color-profile':
7318 case 'font-face':
7319 case 'font-face-src':
7320 case 'font-face-uri':
7321 case 'font-face-format':
7322 case 'font-face-name':
7323 case 'missing-glyph':
7324 return false;
7325 default:
7326 return true;
7327 }
7328}
7329
7330// When adding attributes to the HTML or SVG whitelist, be sure to
7331// also add them to this module to ensure casing and incorrect name
7332// warnings.
7333var possibleStandardNames = {
7334 // HTML
7335 accept: 'accept',
7336 acceptcharset: 'acceptCharset',
7337 'accept-charset': 'acceptCharset',
7338 accesskey: 'accessKey',
7339 action: 'action',
7340 allowfullscreen: 'allowFullScreen',
7341 alt: 'alt',
7342 as: 'as',
7343 async: 'async',
7344 autocapitalize: 'autoCapitalize',
7345 autocomplete: 'autoComplete',
7346 autocorrect: 'autoCorrect',
7347 autofocus: 'autoFocus',
7348 autoplay: 'autoPlay',
7349 autosave: 'autoSave',
7350 capture: 'capture',
7351 cellpadding: 'cellPadding',
7352 cellspacing: 'cellSpacing',
7353 challenge: 'challenge',
7354 charset: 'charSet',
7355 checked: 'checked',
7356 children: 'children',
7357 cite: 'cite',
7358 class: 'className',
7359 classid: 'classID',
7360 classname: 'className',
7361 cols: 'cols',
7362 colspan: 'colSpan',
7363 content: 'content',
7364 contenteditable: 'contentEditable',
7365 contextmenu: 'contextMenu',
7366 controls: 'controls',
7367 controlslist: 'controlsList',
7368 coords: 'coords',
7369 crossorigin: 'crossOrigin',
7370 dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
7371 data: 'data',
7372 datetime: 'dateTime',
7373 default: 'default',
7374 defaultchecked: 'defaultChecked',
7375 defaultvalue: 'defaultValue',
7376 defer: 'defer',
7377 dir: 'dir',
7378 disabled: 'disabled',
7379 download: 'download',
7380 draggable: 'draggable',
7381 enctype: 'encType',
7382 for: 'htmlFor',
7383 form: 'form',
7384 formmethod: 'formMethod',
7385 formaction: 'formAction',
7386 formenctype: 'formEncType',
7387 formnovalidate: 'formNoValidate',
7388 formtarget: 'formTarget',
7389 frameborder: 'frameBorder',
7390 headers: 'headers',
7391 height: 'height',
7392 hidden: 'hidden',
7393 high: 'high',
7394 href: 'href',
7395 hreflang: 'hrefLang',
7396 htmlfor: 'htmlFor',
7397 httpequiv: 'httpEquiv',
7398 'http-equiv': 'httpEquiv',
7399 icon: 'icon',
7400 id: 'id',
7401 innerhtml: 'innerHTML',
7402 inputmode: 'inputMode',
7403 integrity: 'integrity',
7404 is: 'is',
7405 itemid: 'itemID',
7406 itemprop: 'itemProp',
7407 itemref: 'itemRef',
7408 itemscope: 'itemScope',
7409 itemtype: 'itemType',
7410 keyparams: 'keyParams',
7411 keytype: 'keyType',
7412 kind: 'kind',
7413 label: 'label',
7414 lang: 'lang',
7415 list: 'list',
7416 loop: 'loop',
7417 low: 'low',
7418 manifest: 'manifest',
7419 marginwidth: 'marginWidth',
7420 marginheight: 'marginHeight',
7421 max: 'max',
7422 maxlength: 'maxLength',
7423 media: 'media',
7424 mediagroup: 'mediaGroup',
7425 method: 'method',
7426 min: 'min',
7427 minlength: 'minLength',
7428 multiple: 'multiple',
7429 muted: 'muted',
7430 name: 'name',
7431 nomodule: 'noModule',
7432 nonce: 'nonce',
7433 novalidate: 'noValidate',
7434 open: 'open',
7435 optimum: 'optimum',
7436 pattern: 'pattern',
7437 placeholder: 'placeholder',
7438 playsinline: 'playsInline',
7439 poster: 'poster',
7440 preload: 'preload',
7441 profile: 'profile',
7442 radiogroup: 'radioGroup',
7443 readonly: 'readOnly',
7444 referrerpolicy: 'referrerPolicy',
7445 rel: 'rel',
7446 required: 'required',
7447 reversed: 'reversed',
7448 role: 'role',
7449 rows: 'rows',
7450 rowspan: 'rowSpan',
7451 sandbox: 'sandbox',
7452 scope: 'scope',
7453 scoped: 'scoped',
7454 scrolling: 'scrolling',
7455 seamless: 'seamless',
7456 selected: 'selected',
7457 shape: 'shape',
7458 size: 'size',
7459 sizes: 'sizes',
7460 span: 'span',
7461 spellcheck: 'spellCheck',
7462 src: 'src',
7463 srcdoc: 'srcDoc',
7464 srclang: 'srcLang',
7465 srcset: 'srcSet',
7466 start: 'start',
7467 step: 'step',
7468 style: 'style',
7469 summary: 'summary',
7470 tabindex: 'tabIndex',
7471 target: 'target',
7472 title: 'title',
7473 type: 'type',
7474 usemap: 'useMap',
7475 value: 'value',
7476 width: 'width',
7477 wmode: 'wmode',
7478 wrap: 'wrap',
7479
7480 // SVG
7481 about: 'about',
7482 accentheight: 'accentHeight',
7483 'accent-height': 'accentHeight',
7484 accumulate: 'accumulate',
7485 additive: 'additive',
7486 alignmentbaseline: 'alignmentBaseline',
7487 'alignment-baseline': 'alignmentBaseline',
7488 allowreorder: 'allowReorder',
7489 alphabetic: 'alphabetic',
7490 amplitude: 'amplitude',
7491 arabicform: 'arabicForm',
7492 'arabic-form': 'arabicForm',
7493 ascent: 'ascent',
7494 attributename: 'attributeName',
7495 attributetype: 'attributeType',
7496 autoreverse: 'autoReverse',
7497 azimuth: 'azimuth',
7498 basefrequency: 'baseFrequency',
7499 baselineshift: 'baselineShift',
7500 'baseline-shift': 'baselineShift',
7501 baseprofile: 'baseProfile',
7502 bbox: 'bbox',
7503 begin: 'begin',
7504 bias: 'bias',
7505 by: 'by',
7506 calcmode: 'calcMode',
7507 capheight: 'capHeight',
7508 'cap-height': 'capHeight',
7509 clip: 'clip',
7510 clippath: 'clipPath',
7511 'clip-path': 'clipPath',
7512 clippathunits: 'clipPathUnits',
7513 cliprule: 'clipRule',
7514 'clip-rule': 'clipRule',
7515 color: 'color',
7516 colorinterpolation: 'colorInterpolation',
7517 'color-interpolation': 'colorInterpolation',
7518 colorinterpolationfilters: 'colorInterpolationFilters',
7519 'color-interpolation-filters': 'colorInterpolationFilters',
7520 colorprofile: 'colorProfile',
7521 'color-profile': 'colorProfile',
7522 colorrendering: 'colorRendering',
7523 'color-rendering': 'colorRendering',
7524 contentscripttype: 'contentScriptType',
7525 contentstyletype: 'contentStyleType',
7526 cursor: 'cursor',
7527 cx: 'cx',
7528 cy: 'cy',
7529 d: 'd',
7530 datatype: 'datatype',
7531 decelerate: 'decelerate',
7532 descent: 'descent',
7533 diffuseconstant: 'diffuseConstant',
7534 direction: 'direction',
7535 display: 'display',
7536 divisor: 'divisor',
7537 dominantbaseline: 'dominantBaseline',
7538 'dominant-baseline': 'dominantBaseline',
7539 dur: 'dur',
7540 dx: 'dx',
7541 dy: 'dy',
7542 edgemode: 'edgeMode',
7543 elevation: 'elevation',
7544 enablebackground: 'enableBackground',
7545 'enable-background': 'enableBackground',
7546 end: 'end',
7547 exponent: 'exponent',
7548 externalresourcesrequired: 'externalResourcesRequired',
7549 fill: 'fill',
7550 fillopacity: 'fillOpacity',
7551 'fill-opacity': 'fillOpacity',
7552 fillrule: 'fillRule',
7553 'fill-rule': 'fillRule',
7554 filter: 'filter',
7555 filterres: 'filterRes',
7556 filterunits: 'filterUnits',
7557 floodopacity: 'floodOpacity',
7558 'flood-opacity': 'floodOpacity',
7559 floodcolor: 'floodColor',
7560 'flood-color': 'floodColor',
7561 focusable: 'focusable',
7562 fontfamily: 'fontFamily',
7563 'font-family': 'fontFamily',
7564 fontsize: 'fontSize',
7565 'font-size': 'fontSize',
7566 fontsizeadjust: 'fontSizeAdjust',
7567 'font-size-adjust': 'fontSizeAdjust',
7568 fontstretch: 'fontStretch',
7569 'font-stretch': 'fontStretch',
7570 fontstyle: 'fontStyle',
7571 'font-style': 'fontStyle',
7572 fontvariant: 'fontVariant',
7573 'font-variant': 'fontVariant',
7574 fontweight: 'fontWeight',
7575 'font-weight': 'fontWeight',
7576 format: 'format',
7577 from: 'from',
7578 fx: 'fx',
7579 fy: 'fy',
7580 g1: 'g1',
7581 g2: 'g2',
7582 glyphname: 'glyphName',
7583 'glyph-name': 'glyphName',
7584 glyphorientationhorizontal: 'glyphOrientationHorizontal',
7585 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
7586 glyphorientationvertical: 'glyphOrientationVertical',
7587 'glyph-orientation-vertical': 'glyphOrientationVertical',
7588 glyphref: 'glyphRef',
7589 gradienttransform: 'gradientTransform',
7590 gradientunits: 'gradientUnits',
7591 hanging: 'hanging',
7592 horizadvx: 'horizAdvX',
7593 'horiz-adv-x': 'horizAdvX',
7594 horizoriginx: 'horizOriginX',
7595 'horiz-origin-x': 'horizOriginX',
7596 ideographic: 'ideographic',
7597 imagerendering: 'imageRendering',
7598 'image-rendering': 'imageRendering',
7599 in2: 'in2',
7600 in: 'in',
7601 inlist: 'inlist',
7602 intercept: 'intercept',
7603 k1: 'k1',
7604 k2: 'k2',
7605 k3: 'k3',
7606 k4: 'k4',
7607 k: 'k',
7608 kernelmatrix: 'kernelMatrix',
7609 kernelunitlength: 'kernelUnitLength',
7610 kerning: 'kerning',
7611 keypoints: 'keyPoints',
7612 keysplines: 'keySplines',
7613 keytimes: 'keyTimes',
7614 lengthadjust: 'lengthAdjust',
7615 letterspacing: 'letterSpacing',
7616 'letter-spacing': 'letterSpacing',
7617 lightingcolor: 'lightingColor',
7618 'lighting-color': 'lightingColor',
7619 limitingconeangle: 'limitingConeAngle',
7620 local: 'local',
7621 markerend: 'markerEnd',
7622 'marker-end': 'markerEnd',
7623 markerheight: 'markerHeight',
7624 markermid: 'markerMid',
7625 'marker-mid': 'markerMid',
7626 markerstart: 'markerStart',
7627 'marker-start': 'markerStart',
7628 markerunits: 'markerUnits',
7629 markerwidth: 'markerWidth',
7630 mask: 'mask',
7631 maskcontentunits: 'maskContentUnits',
7632 maskunits: 'maskUnits',
7633 mathematical: 'mathematical',
7634 mode: 'mode',
7635 numoctaves: 'numOctaves',
7636 offset: 'offset',
7637 opacity: 'opacity',
7638 operator: 'operator',
7639 order: 'order',
7640 orient: 'orient',
7641 orientation: 'orientation',
7642 origin: 'origin',
7643 overflow: 'overflow',
7644 overlineposition: 'overlinePosition',
7645 'overline-position': 'overlinePosition',
7646 overlinethickness: 'overlineThickness',
7647 'overline-thickness': 'overlineThickness',
7648 paintorder: 'paintOrder',
7649 'paint-order': 'paintOrder',
7650 panose1: 'panose1',
7651 'panose-1': 'panose1',
7652 pathlength: 'pathLength',
7653 patterncontentunits: 'patternContentUnits',
7654 patterntransform: 'patternTransform',
7655 patternunits: 'patternUnits',
7656 pointerevents: 'pointerEvents',
7657 'pointer-events': 'pointerEvents',
7658 points: 'points',
7659 pointsatx: 'pointsAtX',
7660 pointsaty: 'pointsAtY',
7661 pointsatz: 'pointsAtZ',
7662 prefix: 'prefix',
7663 preservealpha: 'preserveAlpha',
7664 preserveaspectratio: 'preserveAspectRatio',
7665 primitiveunits: 'primitiveUnits',
7666 property: 'property',
7667 r: 'r',
7668 radius: 'radius',
7669 refx: 'refX',
7670 refy: 'refY',
7671 renderingintent: 'renderingIntent',
7672 'rendering-intent': 'renderingIntent',
7673 repeatcount: 'repeatCount',
7674 repeatdur: 'repeatDur',
7675 requiredextensions: 'requiredExtensions',
7676 requiredfeatures: 'requiredFeatures',
7677 resource: 'resource',
7678 restart: 'restart',
7679 result: 'result',
7680 results: 'results',
7681 rotate: 'rotate',
7682 rx: 'rx',
7683 ry: 'ry',
7684 scale: 'scale',
7685 security: 'security',
7686 seed: 'seed',
7687 shaperendering: 'shapeRendering',
7688 'shape-rendering': 'shapeRendering',
7689 slope: 'slope',
7690 spacing: 'spacing',
7691 specularconstant: 'specularConstant',
7692 specularexponent: 'specularExponent',
7693 speed: 'speed',
7694 spreadmethod: 'spreadMethod',
7695 startoffset: 'startOffset',
7696 stddeviation: 'stdDeviation',
7697 stemh: 'stemh',
7698 stemv: 'stemv',
7699 stitchtiles: 'stitchTiles',
7700 stopcolor: 'stopColor',
7701 'stop-color': 'stopColor',
7702 stopopacity: 'stopOpacity',
7703 'stop-opacity': 'stopOpacity',
7704 strikethroughposition: 'strikethroughPosition',
7705 'strikethrough-position': 'strikethroughPosition',
7706 strikethroughthickness: 'strikethroughThickness',
7707 'strikethrough-thickness': 'strikethroughThickness',
7708 string: 'string',
7709 stroke: 'stroke',
7710 strokedasharray: 'strokeDasharray',
7711 'stroke-dasharray': 'strokeDasharray',
7712 strokedashoffset: 'strokeDashoffset',
7713 'stroke-dashoffset': 'strokeDashoffset',
7714 strokelinecap: 'strokeLinecap',
7715 'stroke-linecap': 'strokeLinecap',
7716 strokelinejoin: 'strokeLinejoin',
7717 'stroke-linejoin': 'strokeLinejoin',
7718 strokemiterlimit: 'strokeMiterlimit',
7719 'stroke-miterlimit': 'strokeMiterlimit',
7720 strokewidth: 'strokeWidth',
7721 'stroke-width': 'strokeWidth',
7722 strokeopacity: 'strokeOpacity',
7723 'stroke-opacity': 'strokeOpacity',
7724 suppresscontenteditablewarning: 'suppressContentEditableWarning',
7725 suppresshydrationwarning: 'suppressHydrationWarning',
7726 surfacescale: 'surfaceScale',
7727 systemlanguage: 'systemLanguage',
7728 tablevalues: 'tableValues',
7729 targetx: 'targetX',
7730 targety: 'targetY',
7731 textanchor: 'textAnchor',
7732 'text-anchor': 'textAnchor',
7733 textdecoration: 'textDecoration',
7734 'text-decoration': 'textDecoration',
7735 textlength: 'textLength',
7736 textrendering: 'textRendering',
7737 'text-rendering': 'textRendering',
7738 to: 'to',
7739 transform: 'transform',
7740 typeof: 'typeof',
7741 u1: 'u1',
7742 u2: 'u2',
7743 underlineposition: 'underlinePosition',
7744 'underline-position': 'underlinePosition',
7745 underlinethickness: 'underlineThickness',
7746 'underline-thickness': 'underlineThickness',
7747 unicode: 'unicode',
7748 unicodebidi: 'unicodeBidi',
7749 'unicode-bidi': 'unicodeBidi',
7750 unicoderange: 'unicodeRange',
7751 'unicode-range': 'unicodeRange',
7752 unitsperem: 'unitsPerEm',
7753 'units-per-em': 'unitsPerEm',
7754 unselectable: 'unselectable',
7755 valphabetic: 'vAlphabetic',
7756 'v-alphabetic': 'vAlphabetic',
7757 values: 'values',
7758 vectoreffect: 'vectorEffect',
7759 'vector-effect': 'vectorEffect',
7760 version: 'version',
7761 vertadvy: 'vertAdvY',
7762 'vert-adv-y': 'vertAdvY',
7763 vertoriginx: 'vertOriginX',
7764 'vert-origin-x': 'vertOriginX',
7765 vertoriginy: 'vertOriginY',
7766 'vert-origin-y': 'vertOriginY',
7767 vhanging: 'vHanging',
7768 'v-hanging': 'vHanging',
7769 videographic: 'vIdeographic',
7770 'v-ideographic': 'vIdeographic',
7771 viewbox: 'viewBox',
7772 viewtarget: 'viewTarget',
7773 visibility: 'visibility',
7774 vmathematical: 'vMathematical',
7775 'v-mathematical': 'vMathematical',
7776 vocab: 'vocab',
7777 widths: 'widths',
7778 wordspacing: 'wordSpacing',
7779 'word-spacing': 'wordSpacing',
7780 writingmode: 'writingMode',
7781 'writing-mode': 'writingMode',
7782 x1: 'x1',
7783 x2: 'x2',
7784 x: 'x',
7785 xchannelselector: 'xChannelSelector',
7786 xheight: 'xHeight',
7787 'x-height': 'xHeight',
7788 xlinkactuate: 'xlinkActuate',
7789 'xlink:actuate': 'xlinkActuate',
7790 xlinkarcrole: 'xlinkArcrole',
7791 'xlink:arcrole': 'xlinkArcrole',
7792 xlinkhref: 'xlinkHref',
7793 'xlink:href': 'xlinkHref',
7794 xlinkrole: 'xlinkRole',
7795 'xlink:role': 'xlinkRole',
7796 xlinkshow: 'xlinkShow',
7797 'xlink:show': 'xlinkShow',
7798 xlinktitle: 'xlinkTitle',
7799 'xlink:title': 'xlinkTitle',
7800 xlinktype: 'xlinkType',
7801 'xlink:type': 'xlinkType',
7802 xmlbase: 'xmlBase',
7803 'xml:base': 'xmlBase',
7804 xmllang: 'xmlLang',
7805 'xml:lang': 'xmlLang',
7806 xmlns: 'xmlns',
7807 'xml:space': 'xmlSpace',
7808 xmlnsxlink: 'xmlnsXlink',
7809 'xmlns:xlink': 'xmlnsXlink',
7810 xmlspace: 'xmlSpace',
7811 y1: 'y1',
7812 y2: 'y2',
7813 y: 'y',
7814 ychannelselector: 'yChannelSelector',
7815 z: 'z',
7816 zoomandpan: 'zoomAndPan'
7817};
7818
7819var ariaProperties = {
7820 'aria-current': 0, // state
7821 'aria-details': 0,
7822 'aria-disabled': 0, // state
7823 'aria-hidden': 0, // state
7824 'aria-invalid': 0, // state
7825 'aria-keyshortcuts': 0,
7826 'aria-label': 0,
7827 'aria-roledescription': 0,
7828 // Widget Attributes
7829 'aria-autocomplete': 0,
7830 'aria-checked': 0,
7831 'aria-expanded': 0,
7832 'aria-haspopup': 0,
7833 'aria-level': 0,
7834 'aria-modal': 0,
7835 'aria-multiline': 0,
7836 'aria-multiselectable': 0,
7837 'aria-orientation': 0,
7838 'aria-placeholder': 0,
7839 'aria-pressed': 0,
7840 'aria-readonly': 0,
7841 'aria-required': 0,
7842 'aria-selected': 0,
7843 'aria-sort': 0,
7844 'aria-valuemax': 0,
7845 'aria-valuemin': 0,
7846 'aria-valuenow': 0,
7847 'aria-valuetext': 0,
7848 // Live Region Attributes
7849 'aria-atomic': 0,
7850 'aria-busy': 0,
7851 'aria-live': 0,
7852 'aria-relevant': 0,
7853 // Drag-and-Drop Attributes
7854 'aria-dropeffect': 0,
7855 'aria-grabbed': 0,
7856 // Relationship Attributes
7857 'aria-activedescendant': 0,
7858 'aria-colcount': 0,
7859 'aria-colindex': 0,
7860 'aria-colspan': 0,
7861 'aria-controls': 0,
7862 'aria-describedby': 0,
7863 'aria-errormessage': 0,
7864 'aria-flowto': 0,
7865 'aria-labelledby': 0,
7866 'aria-owns': 0,
7867 'aria-posinset': 0,
7868 'aria-rowcount': 0,
7869 'aria-rowindex': 0,
7870 'aria-rowspan': 0,
7871 'aria-setsize': 0
7872};
7873
7874var warnedProperties = {};
7875var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7876var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7877
7878var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
7879
7880function validateProperty(tagName, name) {
7881 if (hasOwnProperty$2.call(warnedProperties, name) && warnedProperties[name]) {
7882 return true;
7883 }
7884
7885 if (rARIACamel.test(name)) {
7886 var ariaName = 'aria-' + name.slice(4).toLowerCase();
7887 var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null;
7888
7889 // If this is an aria-* attribute, but is not listed in the known DOM
7890 // DOM properties, then it is an invalid aria-* attribute.
7891 if (correctName == null) {
7892 warning$1(false, 'Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
7893 warnedProperties[name] = true;
7894 return true;
7895 }
7896 // aria-* attributes should be lowercase; suggest the lowercase version.
7897 if (name !== correctName) {
7898 warning$1(false, 'Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
7899 warnedProperties[name] = true;
7900 return true;
7901 }
7902 }
7903
7904 if (rARIA.test(name)) {
7905 var lowerCasedName = name.toLowerCase();
7906 var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null;
7907
7908 // If this is an aria-* attribute, but is not listed in the known DOM
7909 // DOM properties, then it is an invalid aria-* attribute.
7910 if (standardName == null) {
7911 warnedProperties[name] = true;
7912 return false;
7913 }
7914 // aria-* attributes should be lowercase; suggest the lowercase version.
7915 if (name !== standardName) {
7916 warning$1(false, 'Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
7917 warnedProperties[name] = true;
7918 return true;
7919 }
7920 }
7921
7922 return true;
7923}
7924
7925function warnInvalidARIAProps(type, props) {
7926 var invalidProps = [];
7927
7928 for (var key in props) {
7929 var isValid = validateProperty(type, key);
7930 if (!isValid) {
7931 invalidProps.push(key);
7932 }
7933 }
7934
7935 var unknownPropString = invalidProps.map(function (prop) {
7936 return '`' + prop + '`';
7937 }).join(', ');
7938
7939 if (invalidProps.length === 1) {
7940 warning$1(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7941 } else if (invalidProps.length > 1) {
7942 warning$1(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7943 }
7944}
7945
7946function validateProperties(type, props) {
7947 if (isCustomComponent(type, props)) {
7948 return;
7949 }
7950 warnInvalidARIAProps(type, props);
7951}
7952
7953var didWarnValueNull = false;
7954
7955function validateProperties$1(type, props) {
7956 if (type !== 'input' && type !== 'textarea' && type !== 'select') {
7957 return;
7958 }
7959
7960 if (props != null && props.value === null && !didWarnValueNull) {
7961 didWarnValueNull = true;
7962 if (type === 'select' && props.multiple) {
7963 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);
7964 } else {
7965 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);
7966 }
7967 }
7968}
7969
7970var validateProperty$1 = function () {};
7971
7972{
7973 var warnedProperties$1 = {};
7974 var _hasOwnProperty = Object.prototype.hasOwnProperty;
7975 var EVENT_NAME_REGEX = /^on./;
7976 var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
7977 var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7978 var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7979
7980 validateProperty$1 = function (tagName, name, value, canUseEventSystem) {
7981 if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
7982 return true;
7983 }
7984
7985 var lowerCasedName = name.toLowerCase();
7986 if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
7987 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.');
7988 warnedProperties$1[name] = true;
7989 return true;
7990 }
7991
7992 // We can't rely on the event system being injected on the server.
7993 if (canUseEventSystem) {
7994 if (registrationNameModules.hasOwnProperty(name)) {
7995 return true;
7996 }
7997 var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
7998 if (registrationName != null) {
7999 warning$1(false, 'Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
8000 warnedProperties$1[name] = true;
8001 return true;
8002 }
8003 if (EVENT_NAME_REGEX.test(name)) {
8004 warning$1(false, 'Unknown event handler property `%s`. It will be ignored.', name);
8005 warnedProperties$1[name] = true;
8006 return true;
8007 }
8008 } else if (EVENT_NAME_REGEX.test(name)) {
8009 // If no event plugins have been injected, we are in a server environment.
8010 // So we can't tell if the event name is correct for sure, but we can filter
8011 // out known bad ones like `onclick`. We can't suggest a specific replacement though.
8012 if (INVALID_EVENT_NAME_REGEX.test(name)) {
8013 warning$1(false, 'Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
8014 }
8015 warnedProperties$1[name] = true;
8016 return true;
8017 }
8018
8019 // Let the ARIA attribute hook validate ARIA attributes
8020 if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
8021 return true;
8022 }
8023
8024 if (lowerCasedName === 'innerhtml') {
8025 warning$1(false, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
8026 warnedProperties$1[name] = true;
8027 return true;
8028 }
8029
8030 if (lowerCasedName === 'aria') {
8031 warning$1(false, 'The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
8032 warnedProperties$1[name] = true;
8033 return true;
8034 }
8035
8036 if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
8037 warning$1(false, 'Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
8038 warnedProperties$1[name] = true;
8039 return true;
8040 }
8041
8042 if (typeof value === 'number' && isNaN(value)) {
8043 warning$1(false, 'Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
8044 warnedProperties$1[name] = true;
8045 return true;
8046 }
8047
8048 var propertyInfo = getPropertyInfo(name);
8049 var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED;
8050
8051 // Known attributes should match the casing specified in the property config.
8052 if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
8053 var standardName = possibleStandardNames[lowerCasedName];
8054 if (standardName !== name) {
8055 warning$1(false, 'Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
8056 warnedProperties$1[name] = true;
8057 return true;
8058 }
8059 } else if (!isReserved && name !== lowerCasedName) {
8060 // Unknown attributes should have lowercase casing since that's how they
8061 // will be cased anyway with server rendering.
8062 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);
8063 warnedProperties$1[name] = true;
8064 return true;
8065 }
8066
8067 if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
8068 if (value) {
8069 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);
8070 } else {
8071 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);
8072 }
8073 warnedProperties$1[name] = true;
8074 return true;
8075 }
8076
8077 // Now that we've validated casing, do not validate
8078 // data types for reserved props
8079 if (isReserved) {
8080 return true;
8081 }
8082
8083 // Warn when a known attribute is a bad type
8084 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
8085 warnedProperties$1[name] = true;
8086 return false;
8087 }
8088
8089 // Warn when passing the strings 'false' or 'true' into a boolean prop
8090 if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
8091 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);
8092 warnedProperties$1[name] = true;
8093 return true;
8094 }
8095
8096 return true;
8097 };
8098}
8099
8100var warnUnknownProperties = function (type, props, canUseEventSystem) {
8101 var unknownProps = [];
8102 for (var key in props) {
8103 var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);
8104 if (!isValid) {
8105 unknownProps.push(key);
8106 }
8107 }
8108
8109 var unknownPropString = unknownProps.map(function (prop) {
8110 return '`' + prop + '`';
8111 }).join(', ');
8112 if (unknownProps.length === 1) {
8113 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);
8114 } else if (unknownProps.length > 1) {
8115 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);
8116 }
8117};
8118
8119function validateProperties$2(type, props, canUseEventSystem) {
8120 if (isCustomComponent(type, props)) {
8121 return;
8122 }
8123 warnUnknownProperties(type, props, canUseEventSystem);
8124}
8125
8126// TODO: direct imports like some-package/src/* are bad. Fix me.
8127var didWarnInvalidHydration = false;
8128var didWarnShadyDOM = false;
8129
8130var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
8131var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
8132var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
8133var AUTOFOCUS = 'autoFocus';
8134var CHILDREN = 'children';
8135var STYLE$1 = 'style';
8136var HTML = '__html';
8137
8138var HTML_NAMESPACE = Namespaces.html;
8139
8140
8141var warnedUnknownTags = void 0;
8142var suppressHydrationWarning = void 0;
8143
8144var validatePropertiesInDevelopment = void 0;
8145var warnForTextDifference = void 0;
8146var warnForPropDifference = void 0;
8147var warnForExtraAttributes = void 0;
8148var warnForInvalidEventListener = void 0;
8149var canDiffStyleForHydrationWarning = void 0;
8150
8151var normalizeMarkupForTextOrAttribute = void 0;
8152var normalizeHTML = void 0;
8153
8154{
8155 warnedUnknownTags = {
8156 // Chrome is the only major browser not shipping <time>. But as of July
8157 // 2017 it intends to ship it due to widespread usage. We intentionally
8158 // *don't* warn for <time> even if it's unrecognized by Chrome because
8159 // it soon will be, and many apps have been using it anyway.
8160 time: true,
8161 // There are working polyfills for <dialog>. Let people use it.
8162 dialog: true,
8163 // Electron ships a custom <webview> tag to display external web content in
8164 // an isolated frame and process.
8165 // This tag is not present in non Electron environments such as JSDom which
8166 // is often used for testing purposes.
8167 // @see https://electronjs.org/docs/api/webview-tag
8168 webview: true
8169 };
8170
8171 validatePropertiesInDevelopment = function (type, props) {
8172 validateProperties(type, props);
8173 validateProperties$1(type, props);
8174 validateProperties$2(type, props, /* canUseEventSystem */true);
8175 };
8176
8177 // IE 11 parses & normalizes the style attribute as opposed to other
8178 // browsers. It adds spaces and sorts the properties in some
8179 // non-alphabetical order. Handling that would require sorting CSS
8180 // properties in the client & server versions or applying
8181 // `expectedStyle` to a temporary DOM node to read its `style` attribute
8182 // normalized. Since it only affects IE, we're skipping style warnings
8183 // in that browser completely in favor of doing all that work.
8184 // See https://github.com/facebook/react/issues/11807
8185 canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode;
8186
8187 // HTML parsing normalizes CR and CRLF to LF.
8188 // It also can turn \u0000 into \uFFFD inside attributes.
8189 // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
8190 // If we have a mismatch, it might be caused by that.
8191 // We will still patch up in this case but not fire the warning.
8192 var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
8193 var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
8194
8195 normalizeMarkupForTextOrAttribute = function (markup) {
8196 var markupString = typeof markup === 'string' ? markup : '' + markup;
8197 return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
8198 };
8199
8200 warnForTextDifference = function (serverText, clientText) {
8201 if (didWarnInvalidHydration) {
8202 return;
8203 }
8204 var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
8205 var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
8206 if (normalizedServerText === normalizedClientText) {
8207 return;
8208 }
8209 didWarnInvalidHydration = true;
8210 warningWithoutStack$1(false, 'Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
8211 };
8212
8213 warnForPropDifference = function (propName, serverValue, clientValue) {
8214 if (didWarnInvalidHydration) {
8215 return;
8216 }
8217 var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
8218 var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
8219 if (normalizedServerValue === normalizedClientValue) {
8220 return;
8221 }
8222 didWarnInvalidHydration = true;
8223 warningWithoutStack$1(false, 'Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
8224 };
8225
8226 warnForExtraAttributes = function (attributeNames) {
8227 if (didWarnInvalidHydration) {
8228 return;
8229 }
8230 didWarnInvalidHydration = true;
8231 var names = [];
8232 attributeNames.forEach(function (name) {
8233 names.push(name);
8234 });
8235 warningWithoutStack$1(false, 'Extra attributes from the server: %s', names);
8236 };
8237
8238 warnForInvalidEventListener = function (registrationName, listener) {
8239 if (listener === false) {
8240 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);
8241 } else {
8242 warning$1(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
8243 }
8244 };
8245
8246 // Parse the HTML and read it back to normalize the HTML string so that it
8247 // can be used for comparison.
8248 normalizeHTML = function (parent, html) {
8249 // We could have created a separate document here to avoid
8250 // re-initializing custom elements if they exist. But this breaks
8251 // how <noscript> is being handled. So we use the same document.
8252 // See the discussion in https://github.com/facebook/react/pull/11157.
8253 var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
8254 testElement.innerHTML = html;
8255 return testElement.innerHTML;
8256 };
8257}
8258
8259function ensureListeningTo(rootContainerElement, registrationName) {
8260 var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;
8261 var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;
8262 listenTo(registrationName, doc);
8263}
8264
8265function getOwnerDocumentFromRootContainer(rootContainerElement) {
8266 return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
8267}
8268
8269function noop() {}
8270
8271function trapClickOnNonInteractiveElement(node) {
8272 // Mobile Safari does not fire properly bubble click events on
8273 // non-interactive elements, which means delegated click listeners do not
8274 // fire. The workaround for this bug involves attaching an empty click
8275 // listener on the target node.
8276 // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
8277 // Just set it using the onclick property so that we don't have to manage any
8278 // bookkeeping for it. Not sure if we need to clear it when the listener is
8279 // removed.
8280 // TODO: Only do this for the relevant Safaris maybe?
8281 node.onclick = noop;
8282}
8283
8284function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
8285 for (var propKey in nextProps) {
8286 if (!nextProps.hasOwnProperty(propKey)) {
8287 continue;
8288 }
8289 var nextProp = nextProps[propKey];
8290 if (propKey === STYLE$1) {
8291 {
8292 if (nextProp) {
8293 // Freeze the next style object so that we can assume it won't be
8294 // mutated. We have already warned for this in the past.
8295 Object.freeze(nextProp);
8296 }
8297 }
8298 // Relies on `updateStylesByID` not mutating `styleUpdates`.
8299 setValueForStyles(domElement, nextProp);
8300 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8301 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8302 if (nextHtml != null) {
8303 setInnerHTML(domElement, nextHtml);
8304 }
8305 } else if (propKey === CHILDREN) {
8306 if (typeof nextProp === 'string') {
8307 // Avoid setting initial textContent when the text is empty. In IE11 setting
8308 // textContent on a <textarea> will cause the placeholder to not
8309 // show within the <textarea> until it has been focused and blurred again.
8310 // https://github.com/facebook/react/issues/6731#issuecomment-254874553
8311 var canSetTextContent = tag !== 'textarea' || nextProp !== '';
8312 if (canSetTextContent) {
8313 setTextContent(domElement, nextProp);
8314 }
8315 } else if (typeof nextProp === 'number') {
8316 setTextContent(domElement, '' + nextProp);
8317 }
8318 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
8319 // Noop
8320 } else if (propKey === AUTOFOCUS) {
8321 // We polyfill it separately on the client during commit.
8322 // We could have excluded it in the property list instead of
8323 // adding a special case here, but then it wouldn't be emitted
8324 // on server rendering (but we *do* want to emit it in SSR).
8325 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8326 if (nextProp != null) {
8327 if (true && typeof nextProp !== 'function') {
8328 warnForInvalidEventListener(propKey, nextProp);
8329 }
8330 ensureListeningTo(rootContainerElement, propKey);
8331 }
8332 } else if (nextProp != null) {
8333 setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
8334 }
8335 }
8336}
8337
8338function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
8339 // TODO: Handle wasCustomComponentTag
8340 for (var i = 0; i < updatePayload.length; i += 2) {
8341 var propKey = updatePayload[i];
8342 var propValue = updatePayload[i + 1];
8343 if (propKey === STYLE$1) {
8344 setValueForStyles(domElement, propValue);
8345 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8346 setInnerHTML(domElement, propValue);
8347 } else if (propKey === CHILDREN) {
8348 setTextContent(domElement, propValue);
8349 } else {
8350 setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
8351 }
8352 }
8353}
8354
8355function createElement(type, props, rootContainerElement, parentNamespace) {
8356 var isCustomComponentTag = void 0;
8357
8358 // We create tags in the namespace of their parent container, except HTML
8359 // tags get no namespace.
8360 var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
8361 var domElement = void 0;
8362 var namespaceURI = parentNamespace;
8363 if (namespaceURI === HTML_NAMESPACE) {
8364 namespaceURI = getIntrinsicNamespace(type);
8365 }
8366 if (namespaceURI === HTML_NAMESPACE) {
8367 {
8368 isCustomComponentTag = isCustomComponent(type, props);
8369 // Should this check be gated by parent namespace? Not sure we want to
8370 // allow <SVG> or <mATH>.
8371 !(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;
8372 }
8373
8374 if (type === 'script') {
8375 // Create the script via .innerHTML so its "parser-inserted" flag is
8376 // set to true and it does not execute
8377 var div = ownerDocument.createElement('div');
8378 div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
8379 // This is guaranteed to yield a script element.
8380 var firstChild = div.firstChild;
8381 domElement = div.removeChild(firstChild);
8382 } else if (typeof props.is === 'string') {
8383 // $FlowIssue `createElement` should be updated for Web Components
8384 domElement = ownerDocument.createElement(type, { is: props.is });
8385 } else {
8386 // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
8387 // See discussion in https://github.com/facebook/react/pull/6896
8388 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
8389 domElement = ownerDocument.createElement(type);
8390 // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
8391 // attributes on `select`s needs to be added before `option`s are inserted.
8392 // This prevents:
8393 // - a bug where the `select` does not scroll to the correct option because singular
8394 // `select` elements automatically pick the first item #13222
8395 // - a bug where the `select` set the first item as selected despite the `size` attribute #14239
8396 // See https://github.com/facebook/react/issues/13222
8397 // and https://github.com/facebook/react/issues/14239
8398 if (type === 'select') {
8399 var node = domElement;
8400 if (props.multiple) {
8401 node.multiple = true;
8402 } else if (props.size) {
8403 // Setting a size greater than 1 causes a select to behave like `multiple=true`, where
8404 // it is possible that no option is selected.
8405 //
8406 // This is only necessary when a select in "single selection mode".
8407 node.size = props.size;
8408 }
8409 }
8410 }
8411 } else {
8412 domElement = ownerDocument.createElementNS(namespaceURI, type);
8413 }
8414
8415 {
8416 if (namespaceURI === HTML_NAMESPACE) {
8417 if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {
8418 warnedUnknownTags[type] = true;
8419 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);
8420 }
8421 }
8422 }
8423
8424 return domElement;
8425}
8426
8427function createTextNode(text, rootContainerElement) {
8428 return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
8429}
8430
8431function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
8432 var isCustomComponentTag = isCustomComponent(tag, rawProps);
8433 {
8434 validatePropertiesInDevelopment(tag, rawProps);
8435 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
8436 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
8437 didWarnShadyDOM = true;
8438 }
8439 }
8440
8441 // TODO: Make sure that we check isMounted before firing any of these events.
8442 var props = void 0;
8443 switch (tag) {
8444 case 'iframe':
8445 case 'object':
8446 trapBubbledEvent(TOP_LOAD, domElement);
8447 props = rawProps;
8448 break;
8449 case 'video':
8450 case 'audio':
8451 // Create listener for each media event
8452 for (var i = 0; i < mediaEventTypes.length; i++) {
8453 trapBubbledEvent(mediaEventTypes[i], domElement);
8454 }
8455 props = rawProps;
8456 break;
8457 case 'source':
8458 trapBubbledEvent(TOP_ERROR, domElement);
8459 props = rawProps;
8460 break;
8461 case 'img':
8462 case 'image':
8463 case 'link':
8464 trapBubbledEvent(TOP_ERROR, domElement);
8465 trapBubbledEvent(TOP_LOAD, domElement);
8466 props = rawProps;
8467 break;
8468 case 'form':
8469 trapBubbledEvent(TOP_RESET, domElement);
8470 trapBubbledEvent(TOP_SUBMIT, domElement);
8471 props = rawProps;
8472 break;
8473 case 'details':
8474 trapBubbledEvent(TOP_TOGGLE, domElement);
8475 props = rawProps;
8476 break;
8477 case 'input':
8478 initWrapperState(domElement, rawProps);
8479 props = getHostProps(domElement, rawProps);
8480 trapBubbledEvent(TOP_INVALID, domElement);
8481 // For controlled components we always need to ensure we're listening
8482 // to onChange. Even if there is no listener.
8483 ensureListeningTo(rootContainerElement, 'onChange');
8484 break;
8485 case 'option':
8486 validateProps(domElement, rawProps);
8487 props = getHostProps$1(domElement, rawProps);
8488 break;
8489 case 'select':
8490 initWrapperState$1(domElement, rawProps);
8491 props = getHostProps$2(domElement, rawProps);
8492 trapBubbledEvent(TOP_INVALID, domElement);
8493 // For controlled components we always need to ensure we're listening
8494 // to onChange. Even if there is no listener.
8495 ensureListeningTo(rootContainerElement, 'onChange');
8496 break;
8497 case 'textarea':
8498 initWrapperState$2(domElement, rawProps);
8499 props = getHostProps$3(domElement, rawProps);
8500 trapBubbledEvent(TOP_INVALID, domElement);
8501 // For controlled components we always need to ensure we're listening
8502 // to onChange. Even if there is no listener.
8503 ensureListeningTo(rootContainerElement, 'onChange');
8504 break;
8505 default:
8506 props = rawProps;
8507 }
8508
8509 assertValidProps(tag, props);
8510
8511 setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
8512
8513 switch (tag) {
8514 case 'input':
8515 // TODO: Make sure we check if this is still unmounted or do any clean
8516 // up necessary since we never stop tracking anymore.
8517 track(domElement);
8518 postMountWrapper(domElement, rawProps, false);
8519 break;
8520 case 'textarea':
8521 // TODO: Make sure we check if this is still unmounted or do any clean
8522 // up necessary since we never stop tracking anymore.
8523 track(domElement);
8524 postMountWrapper$3(domElement, rawProps);
8525 break;
8526 case 'option':
8527 postMountWrapper$1(domElement, rawProps);
8528 break;
8529 case 'select':
8530 postMountWrapper$2(domElement, rawProps);
8531 break;
8532 default:
8533 if (typeof props.onClick === 'function') {
8534 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8535 trapClickOnNonInteractiveElement(domElement);
8536 }
8537 break;
8538 }
8539}
8540
8541// Calculate the diff between the two objects.
8542function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
8543 {
8544 validatePropertiesInDevelopment(tag, nextRawProps);
8545 }
8546
8547 var updatePayload = null;
8548
8549 var lastProps = void 0;
8550 var nextProps = void 0;
8551 switch (tag) {
8552 case 'input':
8553 lastProps = getHostProps(domElement, lastRawProps);
8554 nextProps = getHostProps(domElement, nextRawProps);
8555 updatePayload = [];
8556 break;
8557 case 'option':
8558 lastProps = getHostProps$1(domElement, lastRawProps);
8559 nextProps = getHostProps$1(domElement, nextRawProps);
8560 updatePayload = [];
8561 break;
8562 case 'select':
8563 lastProps = getHostProps$2(domElement, lastRawProps);
8564 nextProps = getHostProps$2(domElement, nextRawProps);
8565 updatePayload = [];
8566 break;
8567 case 'textarea':
8568 lastProps = getHostProps$3(domElement, lastRawProps);
8569 nextProps = getHostProps$3(domElement, nextRawProps);
8570 updatePayload = [];
8571 break;
8572 default:
8573 lastProps = lastRawProps;
8574 nextProps = nextRawProps;
8575 if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
8576 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8577 trapClickOnNonInteractiveElement(domElement);
8578 }
8579 break;
8580 }
8581
8582 assertValidProps(tag, nextProps);
8583
8584 var propKey = void 0;
8585 var styleName = void 0;
8586 var styleUpdates = null;
8587 for (propKey in lastProps) {
8588 if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
8589 continue;
8590 }
8591 if (propKey === STYLE$1) {
8592 var lastStyle = lastProps[propKey];
8593 for (styleName in lastStyle) {
8594 if (lastStyle.hasOwnProperty(styleName)) {
8595 if (!styleUpdates) {
8596 styleUpdates = {};
8597 }
8598 styleUpdates[styleName] = '';
8599 }
8600 }
8601 } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) {
8602 // Noop. This is handled by the clear text mechanism.
8603 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
8604 // Noop
8605 } else if (propKey === AUTOFOCUS) {
8606 // Noop. It doesn't work on updates anyway.
8607 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8608 // This is a special case. If any listener updates we need to ensure
8609 // that the "current" fiber pointer gets updated so we need a commit
8610 // to update this element.
8611 if (!updatePayload) {
8612 updatePayload = [];
8613 }
8614 } else {
8615 // For all other deleted properties we add it to the queue. We use
8616 // the whitelist in the commit phase instead.
8617 (updatePayload = updatePayload || []).push(propKey, null);
8618 }
8619 }
8620 for (propKey in nextProps) {
8621 var nextProp = nextProps[propKey];
8622 var lastProp = lastProps != null ? lastProps[propKey] : undefined;
8623 if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
8624 continue;
8625 }
8626 if (propKey === STYLE$1) {
8627 {
8628 if (nextProp) {
8629 // Freeze the next style object so that we can assume it won't be
8630 // mutated. We have already warned for this in the past.
8631 Object.freeze(nextProp);
8632 }
8633 }
8634 if (lastProp) {
8635 // Unset styles on `lastProp` but not on `nextProp`.
8636 for (styleName in lastProp) {
8637 if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
8638 if (!styleUpdates) {
8639 styleUpdates = {};
8640 }
8641 styleUpdates[styleName] = '';
8642 }
8643 }
8644 // Update styles that changed since `lastProp`.
8645 for (styleName in nextProp) {
8646 if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
8647 if (!styleUpdates) {
8648 styleUpdates = {};
8649 }
8650 styleUpdates[styleName] = nextProp[styleName];
8651 }
8652 }
8653 } else {
8654 // Relies on `updateStylesByID` not mutating `styleUpdates`.
8655 if (!styleUpdates) {
8656 if (!updatePayload) {
8657 updatePayload = [];
8658 }
8659 updatePayload.push(propKey, styleUpdates);
8660 }
8661 styleUpdates = nextProp;
8662 }
8663 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8664 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8665 var lastHtml = lastProp ? lastProp[HTML] : undefined;
8666 if (nextHtml != null) {
8667 if (lastHtml !== nextHtml) {
8668 (updatePayload = updatePayload || []).push(propKey, '' + nextHtml);
8669 }
8670 } else {
8671 // TODO: It might be too late to clear this if we have children
8672 // inserted already.
8673 }
8674 } else if (propKey === CHILDREN) {
8675 if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {
8676 (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
8677 }
8678 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {
8679 // Noop
8680 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8681 if (nextProp != null) {
8682 // We eagerly listen to this even though we haven't committed yet.
8683 if (true && typeof nextProp !== 'function') {
8684 warnForInvalidEventListener(propKey, nextProp);
8685 }
8686 ensureListeningTo(rootContainerElement, propKey);
8687 }
8688 if (!updatePayload && lastProp !== nextProp) {
8689 // This is a special case. If any listener updates we need to ensure
8690 // that the "current" props pointer gets updated so we need a commit
8691 // to update this element.
8692 updatePayload = [];
8693 }
8694 } else {
8695 // For any other property we always add it to the queue and then we
8696 // filter it out using the whitelist during the commit.
8697 (updatePayload = updatePayload || []).push(propKey, nextProp);
8698 }
8699 }
8700 if (styleUpdates) {
8701 {
8702 validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE$1]);
8703 }
8704 (updatePayload = updatePayload || []).push(STYLE$1, styleUpdates);
8705 }
8706 return updatePayload;
8707}
8708
8709// Apply the diff.
8710function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
8711 // Update checked *before* name.
8712 // In the middle of an update, it is possible to have multiple checked.
8713 // When a checked radio tries to change name, browser makes another radio's checked false.
8714 if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
8715 updateChecked(domElement, nextRawProps);
8716 }
8717
8718 var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
8719 var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
8720 // Apply the diff.
8721 updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag);
8722
8723 // TODO: Ensure that an update gets scheduled if any of the special props
8724 // changed.
8725 switch (tag) {
8726 case 'input':
8727 // Update the wrapper around inputs *after* updating props. This has to
8728 // happen after `updateDOMProperties`. Otherwise HTML5 input validations
8729 // raise warnings and prevent the new value from being assigned.
8730 updateWrapper(domElement, nextRawProps);
8731 break;
8732 case 'textarea':
8733 updateWrapper$1(domElement, nextRawProps);
8734 break;
8735 case 'select':
8736 // <select> value update needs to occur after <option> children
8737 // reconciliation
8738 postUpdateWrapper(domElement, nextRawProps);
8739 break;
8740 }
8741}
8742
8743function getPossibleStandardName(propName) {
8744 {
8745 var lowerCasedName = propName.toLowerCase();
8746 if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
8747 return null;
8748 }
8749 return possibleStandardNames[lowerCasedName] || null;
8750 }
8751 return null;
8752}
8753
8754function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {
8755 var isCustomComponentTag = void 0;
8756 var extraAttributeNames = void 0;
8757
8758 {
8759 suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING$1] === true;
8760 isCustomComponentTag = isCustomComponent(tag, rawProps);
8761 validatePropertiesInDevelopment(tag, rawProps);
8762 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
8763 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
8764 didWarnShadyDOM = true;
8765 }
8766 }
8767
8768 // TODO: Make sure that we check isMounted before firing any of these events.
8769 switch (tag) {
8770 case 'iframe':
8771 case 'object':
8772 trapBubbledEvent(TOP_LOAD, domElement);
8773 break;
8774 case 'video':
8775 case 'audio':
8776 // Create listener for each media event
8777 for (var i = 0; i < mediaEventTypes.length; i++) {
8778 trapBubbledEvent(mediaEventTypes[i], domElement);
8779 }
8780 break;
8781 case 'source':
8782 trapBubbledEvent(TOP_ERROR, domElement);
8783 break;
8784 case 'img':
8785 case 'image':
8786 case 'link':
8787 trapBubbledEvent(TOP_ERROR, domElement);
8788 trapBubbledEvent(TOP_LOAD, domElement);
8789 break;
8790 case 'form':
8791 trapBubbledEvent(TOP_RESET, domElement);
8792 trapBubbledEvent(TOP_SUBMIT, domElement);
8793 break;
8794 case 'details':
8795 trapBubbledEvent(TOP_TOGGLE, domElement);
8796 break;
8797 case 'input':
8798 initWrapperState(domElement, rawProps);
8799 trapBubbledEvent(TOP_INVALID, domElement);
8800 // For controlled components we always need to ensure we're listening
8801 // to onChange. Even if there is no listener.
8802 ensureListeningTo(rootContainerElement, 'onChange');
8803 break;
8804 case 'option':
8805 validateProps(domElement, rawProps);
8806 break;
8807 case 'select':
8808 initWrapperState$1(domElement, rawProps);
8809 trapBubbledEvent(TOP_INVALID, domElement);
8810 // For controlled components we always need to ensure we're listening
8811 // to onChange. Even if there is no listener.
8812 ensureListeningTo(rootContainerElement, 'onChange');
8813 break;
8814 case 'textarea':
8815 initWrapperState$2(domElement, rawProps);
8816 trapBubbledEvent(TOP_INVALID, domElement);
8817 // For controlled components we always need to ensure we're listening
8818 // to onChange. Even if there is no listener.
8819 ensureListeningTo(rootContainerElement, 'onChange');
8820 break;
8821 }
8822
8823 assertValidProps(tag, rawProps);
8824
8825 {
8826 extraAttributeNames = new Set();
8827 var attributes = domElement.attributes;
8828 for (var _i = 0; _i < attributes.length; _i++) {
8829 var _name = attributes[_i].name.toLowerCase();
8830 switch (_name) {
8831 // Built-in SSR attribute is whitelisted
8832 case 'data-reactroot':
8833 break;
8834 // Controlled attributes are not validated
8835 // TODO: Only ignore them on controlled tags.
8836 case 'value':
8837 break;
8838 case 'checked':
8839 break;
8840 case 'selected':
8841 break;
8842 default:
8843 // Intentionally use the original name.
8844 // See discussion in https://github.com/facebook/react/pull/10676.
8845 extraAttributeNames.add(attributes[_i].name);
8846 }
8847 }
8848 }
8849
8850 var updatePayload = null;
8851 for (var propKey in rawProps) {
8852 if (!rawProps.hasOwnProperty(propKey)) {
8853 continue;
8854 }
8855 var nextProp = rawProps[propKey];
8856 if (propKey === CHILDREN) {
8857 // For text content children we compare against textContent. This
8858 // might match additional HTML that is hidden when we read it using
8859 // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
8860 // satisfies our requirement. Our requirement is not to produce perfect
8861 // HTML and attributes. Ideally we should preserve structure but it's
8862 // ok not to if the visible content is still enough to indicate what
8863 // even listeners these nodes might be wired up to.
8864 // TODO: Warn if there is more than a single textNode as a child.
8865 // TODO: Should we use domElement.firstChild.nodeValue to compare?
8866 if (typeof nextProp === 'string') {
8867 if (domElement.textContent !== nextProp) {
8868 if (true && !suppressHydrationWarning) {
8869 warnForTextDifference(domElement.textContent, nextProp);
8870 }
8871 updatePayload = [CHILDREN, nextProp];
8872 }
8873 } else if (typeof nextProp === 'number') {
8874 if (domElement.textContent !== '' + nextProp) {
8875 if (true && !suppressHydrationWarning) {
8876 warnForTextDifference(domElement.textContent, nextProp);
8877 }
8878 updatePayload = [CHILDREN, '' + nextProp];
8879 }
8880 }
8881 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8882 if (nextProp != null) {
8883 if (true && typeof nextProp !== 'function') {
8884 warnForInvalidEventListener(propKey, nextProp);
8885 }
8886 ensureListeningTo(rootContainerElement, propKey);
8887 }
8888 } else if (true &&
8889 // Convince Flow we've calculated it (it's DEV-only in this method.)
8890 typeof isCustomComponentTag === 'boolean') {
8891 // Validate that the properties correspond to their expected values.
8892 var serverValue = void 0;
8893 var propertyInfo = getPropertyInfo(propKey);
8894 if (suppressHydrationWarning) {
8895 // Don't bother comparing. We're ignoring all these warnings.
8896 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1 ||
8897 // Controlled attributes are not validated
8898 // TODO: Only ignore them on controlled tags.
8899 propKey === 'value' || propKey === 'checked' || propKey === 'selected') {
8900 // Noop
8901 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8902 var serverHTML = domElement.innerHTML;
8903 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8904 var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : '');
8905 if (expectedHTML !== serverHTML) {
8906 warnForPropDifference(propKey, serverHTML, expectedHTML);
8907 }
8908 } else if (propKey === STYLE$1) {
8909 // $FlowFixMe - Should be inferred as not undefined.
8910 extraAttributeNames.delete(propKey);
8911
8912 if (canDiffStyleForHydrationWarning) {
8913 var expectedStyle = createDangerousStringForStyles(nextProp);
8914 serverValue = domElement.getAttribute('style');
8915 if (expectedStyle !== serverValue) {
8916 warnForPropDifference(propKey, serverValue, expectedStyle);
8917 }
8918 }
8919 } else if (isCustomComponentTag) {
8920 // $FlowFixMe - Should be inferred as not undefined.
8921 extraAttributeNames.delete(propKey.toLowerCase());
8922 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8923
8924 if (nextProp !== serverValue) {
8925 warnForPropDifference(propKey, serverValue, nextProp);
8926 }
8927 } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
8928 var isMismatchDueToBadCasing = false;
8929 if (propertyInfo !== null) {
8930 // $FlowFixMe - Should be inferred as not undefined.
8931 extraAttributeNames.delete(propertyInfo.attributeName);
8932 serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
8933 } else {
8934 var ownNamespace = parentNamespace;
8935 if (ownNamespace === HTML_NAMESPACE) {
8936 ownNamespace = getIntrinsicNamespace(tag);
8937 }
8938 if (ownNamespace === HTML_NAMESPACE) {
8939 // $FlowFixMe - Should be inferred as not undefined.
8940 extraAttributeNames.delete(propKey.toLowerCase());
8941 } else {
8942 var standardName = getPossibleStandardName(propKey);
8943 if (standardName !== null && standardName !== propKey) {
8944 // If an SVG prop is supplied with bad casing, it will
8945 // be successfully parsed from HTML, but will produce a mismatch
8946 // (and would be incorrectly rendered on the client).
8947 // However, we already warn about bad casing elsewhere.
8948 // So we'll skip the misleading extra mismatch warning in this case.
8949 isMismatchDueToBadCasing = true;
8950 // $FlowFixMe - Should be inferred as not undefined.
8951 extraAttributeNames.delete(standardName);
8952 }
8953 // $FlowFixMe - Should be inferred as not undefined.
8954 extraAttributeNames.delete(propKey);
8955 }
8956 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8957 }
8958
8959 if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
8960 warnForPropDifference(propKey, serverValue, nextProp);
8961 }
8962 }
8963 }
8964 }
8965
8966 {
8967 // $FlowFixMe - Should be inferred as not undefined.
8968 if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
8969 // $FlowFixMe - Should be inferred as not undefined.
8970 warnForExtraAttributes(extraAttributeNames);
8971 }
8972 }
8973
8974 switch (tag) {
8975 case 'input':
8976 // TODO: Make sure we check if this is still unmounted or do any clean
8977 // up necessary since we never stop tracking anymore.
8978 track(domElement);
8979 postMountWrapper(domElement, rawProps, true);
8980 break;
8981 case 'textarea':
8982 // TODO: Make sure we check if this is still unmounted or do any clean
8983 // up necessary since we never stop tracking anymore.
8984 track(domElement);
8985 postMountWrapper$3(domElement, rawProps);
8986 break;
8987 case 'select':
8988 case 'option':
8989 // For input and textarea we current always set the value property at
8990 // post mount to force it to diverge from attributes. However, for
8991 // option and select we don't quite do the same thing and select
8992 // is not resilient to the DOM state changing so we don't do that here.
8993 // TODO: Consider not doing this for input and textarea.
8994 break;
8995 default:
8996 if (typeof rawProps.onClick === 'function') {
8997 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8998 trapClickOnNonInteractiveElement(domElement);
8999 }
9000 break;
9001 }
9002
9003 return updatePayload;
9004}
9005
9006function diffHydratedText(textNode, text) {
9007 var isDifferent = textNode.nodeValue !== text;
9008 return isDifferent;
9009}
9010
9011function warnForUnmatchedText(textNode, text) {
9012 {
9013 warnForTextDifference(textNode.nodeValue, text);
9014 }
9015}
9016
9017function warnForDeletedHydratableElement(parentNode, child) {
9018 {
9019 if (didWarnInvalidHydration) {
9020 return;
9021 }
9022 didWarnInvalidHydration = true;
9023 warningWithoutStack$1(false, 'Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
9024 }
9025}
9026
9027function warnForDeletedHydratableText(parentNode, child) {
9028 {
9029 if (didWarnInvalidHydration) {
9030 return;
9031 }
9032 didWarnInvalidHydration = true;
9033 warningWithoutStack$1(false, 'Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
9034 }
9035}
9036
9037function warnForInsertedHydratedElement(parentNode, tag, props) {
9038 {
9039 if (didWarnInvalidHydration) {
9040 return;
9041 }
9042 didWarnInvalidHydration = true;
9043 warningWithoutStack$1(false, 'Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
9044 }
9045}
9046
9047function warnForInsertedHydratedText(parentNode, text) {
9048 {
9049 if (text === '') {
9050 // We expect to insert empty text nodes since they're not represented in
9051 // the HTML.
9052 // TODO: Remove this special case if we can just avoid inserting empty
9053 // text nodes.
9054 return;
9055 }
9056 if (didWarnInvalidHydration) {
9057 return;
9058 }
9059 didWarnInvalidHydration = true;
9060 warningWithoutStack$1(false, 'Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
9061 }
9062}
9063
9064function restoreControlledState$1(domElement, tag, props) {
9065 switch (tag) {
9066 case 'input':
9067 restoreControlledState(domElement, props);
9068 return;
9069 case 'textarea':
9070 restoreControlledState$3(domElement, props);
9071 return;
9072 case 'select':
9073 restoreControlledState$2(domElement, props);
9074 return;
9075 }
9076}
9077
9078function listenToEventResponderEventTypes(eventTypes, element) {
9079 if (enableEventAPI) {
9080 // Get the listening Set for this element. We use this to track
9081 // what events we're listening to.
9082 var listeningSet = getListeningSetForElement(element);
9083
9084 // Go through each target event type of the event responder
9085 for (var i = 0, length = eventTypes.length; i < length; ++i) {
9086 var targetEventType = eventTypes[i];
9087 var topLevelType = void 0;
9088 var capture = false;
9089 var passive = true;
9090
9091 // If no event config object is provided (i.e. - only a string),
9092 // we default to enabling passive and not capture.
9093 if (typeof targetEventType === 'string') {
9094 topLevelType = targetEventType;
9095 } else {
9096 {
9097 !(typeof targetEventType === 'object' && targetEventType !== null) ? warning$1(false, 'Event Responder: invalid entry in targetEventTypes array. ' + 'Entry must be string or an object. Instead, got %s.', targetEventType) : void 0;
9098 }
9099 var targetEventConfigObject = targetEventType;
9100 topLevelType = targetEventConfigObject.name;
9101 if (targetEventConfigObject.passive !== undefined) {
9102 passive = targetEventConfigObject.passive;
9103 }
9104 if (targetEventConfigObject.capture !== undefined) {
9105 capture = targetEventConfigObject.capture;
9106 }
9107 }
9108 // Create a unique name for this event, plus its properties. We'll
9109 // use this to ensure we don't listen to the same event with the same
9110 // properties again.
9111 var passiveKey = passive ? '_passive' : '_active';
9112 var captureKey = capture ? '_capture' : '';
9113 var listeningName = '' + topLevelType + passiveKey + captureKey;
9114 if (!listeningSet.has(listeningName)) {
9115 trapEventForResponderEventSystem(element, topLevelType, capture, passive);
9116 listeningSet.add(listeningName);
9117 }
9118 }
9119 }
9120}
9121
9122// We can remove this once the event API is stable and out of a flag
9123if (enableEventAPI) {
9124 setListenToResponderEventTypes(listenToEventResponderEventTypes);
9125}
9126
9127// TODO: direct imports like some-package/src/* are bad. Fix me.
9128var validateDOMNesting = function () {};
9129var updatedAncestorInfo = function () {};
9130
9131{
9132 // This validation code was written based on the HTML5 parsing spec:
9133 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
9134 //
9135 // Note: this does not catch all invalid nesting, nor does it try to (as it's
9136 // not clear what practical benefit doing so provides); instead, we warn only
9137 // for cases where the parser will give a parse tree differing from what React
9138 // intended. For example, <b><div></div></b> is invalid but we don't warn
9139 // because it still parses correctly; we do warn for other cases like nested
9140 // <p> tags where the beginning of the second element implicitly closes the
9141 // first, causing a confusing mess.
9142
9143 // https://html.spec.whatwg.org/multipage/syntax.html#special
9144 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'];
9145
9146 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
9147 var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template',
9148
9149 // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
9150 // TODO: Distinguish by namespace here -- for <title>, including it here
9151 // errs on the side of fewer warnings
9152 'foreignObject', 'desc', 'title'];
9153
9154 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
9155 var buttonScopeTags = inScopeTags.concat(['button']);
9156
9157 // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
9158 var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
9159
9160 var emptyAncestorInfo = {
9161 current: null,
9162
9163 formTag: null,
9164 aTagInScope: null,
9165 buttonTagInScope: null,
9166 nobrTagInScope: null,
9167 pTagInButtonScope: null,
9168
9169 listItemTagAutoclosing: null,
9170 dlItemTagAutoclosing: null
9171 };
9172
9173 updatedAncestorInfo = function (oldInfo, tag) {
9174 var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
9175 var info = { tag: tag };
9176
9177 if (inScopeTags.indexOf(tag) !== -1) {
9178 ancestorInfo.aTagInScope = null;
9179 ancestorInfo.buttonTagInScope = null;
9180 ancestorInfo.nobrTagInScope = null;
9181 }
9182 if (buttonScopeTags.indexOf(tag) !== -1) {
9183 ancestorInfo.pTagInButtonScope = null;
9184 }
9185
9186 // See rules for 'li', 'dd', 'dt' start tags in
9187 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
9188 if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
9189 ancestorInfo.listItemTagAutoclosing = null;
9190 ancestorInfo.dlItemTagAutoclosing = null;
9191 }
9192
9193 ancestorInfo.current = info;
9194
9195 if (tag === 'form') {
9196 ancestorInfo.formTag = info;
9197 }
9198 if (tag === 'a') {
9199 ancestorInfo.aTagInScope = info;
9200 }
9201 if (tag === 'button') {
9202 ancestorInfo.buttonTagInScope = info;
9203 }
9204 if (tag === 'nobr') {
9205 ancestorInfo.nobrTagInScope = info;
9206 }
9207 if (tag === 'p') {
9208 ancestorInfo.pTagInButtonScope = info;
9209 }
9210 if (tag === 'li') {
9211 ancestorInfo.listItemTagAutoclosing = info;
9212 }
9213 if (tag === 'dd' || tag === 'dt') {
9214 ancestorInfo.dlItemTagAutoclosing = info;
9215 }
9216
9217 return ancestorInfo;
9218 };
9219
9220 /**
9221 * Returns whether
9222 */
9223 var isTagValidWithParent = function (tag, parentTag) {
9224 // First, let's check if we're in an unusual parsing mode...
9225 switch (parentTag) {
9226 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
9227 case 'select':
9228 return tag === 'option' || tag === 'optgroup' || tag === '#text';
9229 case 'optgroup':
9230 return tag === 'option' || tag === '#text';
9231 // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
9232 // but
9233 case 'option':
9234 return tag === '#text';
9235 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
9236 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
9237 // No special behavior since these rules fall back to "in body" mode for
9238 // all except special table nodes which cause bad parsing behavior anyway.
9239
9240 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
9241 case 'tr':
9242 return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
9243 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
9244 case 'tbody':
9245 case 'thead':
9246 case 'tfoot':
9247 return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
9248 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
9249 case 'colgroup':
9250 return tag === 'col' || tag === 'template';
9251 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
9252 case 'table':
9253 return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
9254 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
9255 case 'head':
9256 return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
9257 // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
9258 case 'html':
9259 return tag === 'head' || tag === 'body' || tag === 'frameset';
9260 case 'frameset':
9261 return tag === 'frame';
9262 case '#document':
9263 return tag === 'html';
9264 }
9265
9266 // Probably in the "in body" parsing mode, so we outlaw only tag combos
9267 // where the parsing rules cause implicit opens or closes to be added.
9268 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
9269 switch (tag) {
9270 case 'h1':
9271 case 'h2':
9272 case 'h3':
9273 case 'h4':
9274 case 'h5':
9275 case 'h6':
9276 return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
9277
9278 case 'rp':
9279 case 'rt':
9280 return impliedEndTags.indexOf(parentTag) === -1;
9281
9282 case 'body':
9283 case 'caption':
9284 case 'col':
9285 case 'colgroup':
9286 case 'frameset':
9287 case 'frame':
9288 case 'head':
9289 case 'html':
9290 case 'tbody':
9291 case 'td':
9292 case 'tfoot':
9293 case 'th':
9294 case 'thead':
9295 case 'tr':
9296 // These tags are only valid with a few parents that have special child
9297 // parsing rules -- if we're down here, then none of those matched and
9298 // so we allow it only if we don't know what the parent is, as all other
9299 // cases are invalid.
9300 return parentTag == null;
9301 }
9302
9303 return true;
9304 };
9305
9306 /**
9307 * Returns whether
9308 */
9309 var findInvalidAncestorForTag = function (tag, ancestorInfo) {
9310 switch (tag) {
9311 case 'address':
9312 case 'article':
9313 case 'aside':
9314 case 'blockquote':
9315 case 'center':
9316 case 'details':
9317 case 'dialog':
9318 case 'dir':
9319 case 'div':
9320 case 'dl':
9321 case 'fieldset':
9322 case 'figcaption':
9323 case 'figure':
9324 case 'footer':
9325 case 'header':
9326 case 'hgroup':
9327 case 'main':
9328 case 'menu':
9329 case 'nav':
9330 case 'ol':
9331 case 'p':
9332 case 'section':
9333 case 'summary':
9334 case 'ul':
9335 case 'pre':
9336 case 'listing':
9337 case 'table':
9338 case 'hr':
9339 case 'xmp':
9340 case 'h1':
9341 case 'h2':
9342 case 'h3':
9343 case 'h4':
9344 case 'h5':
9345 case 'h6':
9346 return ancestorInfo.pTagInButtonScope;
9347
9348 case 'form':
9349 return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
9350
9351 case 'li':
9352 return ancestorInfo.listItemTagAutoclosing;
9353
9354 case 'dd':
9355 case 'dt':
9356 return ancestorInfo.dlItemTagAutoclosing;
9357
9358 case 'button':
9359 return ancestorInfo.buttonTagInScope;
9360
9361 case 'a':
9362 // Spec says something about storing a list of markers, but it sounds
9363 // equivalent to this check.
9364 return ancestorInfo.aTagInScope;
9365
9366 case 'nobr':
9367 return ancestorInfo.nobrTagInScope;
9368 }
9369
9370 return null;
9371 };
9372
9373 var didWarn$1 = {};
9374
9375 validateDOMNesting = function (childTag, childText, ancestorInfo) {
9376 ancestorInfo = ancestorInfo || emptyAncestorInfo;
9377 var parentInfo = ancestorInfo.current;
9378 var parentTag = parentInfo && parentInfo.tag;
9379
9380 if (childText != null) {
9381 !(childTag == null) ? warningWithoutStack$1(false, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0;
9382 childTag = '#text';
9383 }
9384
9385 var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
9386 var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
9387 var invalidParentOrAncestor = invalidParent || invalidAncestor;
9388 if (!invalidParentOrAncestor) {
9389 return;
9390 }
9391
9392 var ancestorTag = invalidParentOrAncestor.tag;
9393 var addendum = getCurrentFiberStackInDev();
9394
9395 var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;
9396 if (didWarn$1[warnKey]) {
9397 return;
9398 }
9399 didWarn$1[warnKey] = true;
9400
9401 var tagDisplayName = childTag;
9402 var whitespaceInfo = '';
9403 if (childTag === '#text') {
9404 if (/\S/.test(childText)) {
9405 tagDisplayName = 'Text nodes';
9406 } else {
9407 tagDisplayName = 'Whitespace text nodes';
9408 whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
9409 }
9410 } else {
9411 tagDisplayName = '<' + childTag + '>';
9412 }
9413
9414 if (invalidParent) {
9415 var info = '';
9416 if (ancestorTag === 'table' && childTag === 'tr') {
9417 info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.';
9418 }
9419 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info, addendum);
9420 } else {
9421 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.%s', tagDisplayName, ancestorTag, addendum);
9422 }
9423 };
9424}
9425
9426// Renderers that don't support persistence
9427// can re-export everything from this module.
9428
9429function shim() {
9430 (function () {
9431 {
9432 {
9433 throw ReactError('The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.');
9434 }
9435 }
9436 })();
9437}
9438
9439// Persistence (when unsupported)
9440var supportsPersistence = false;
9441var cloneInstance = shim;
9442var createContainerChildSet = shim;
9443var appendChildToContainerChildSet = shim;
9444var finalizeContainerChildren = shim;
9445var replaceContainerChildren = shim;
9446var cloneHiddenInstance = shim;
9447var cloneHiddenTextInstance = shim;
9448
9449var SUPPRESS_HYDRATION_WARNING = void 0;
9450{
9451 SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
9452}
9453
9454var SUSPENSE_START_DATA = '$';
9455var SUSPENSE_END_DATA = '/$';
9456var SUSPENSE_PENDING_START_DATA = '$?';
9457var SUSPENSE_FALLBACK_START_DATA = '$!';
9458
9459var STYLE = 'style';
9460
9461var eventsEnabled = null;
9462var selectionInformation = null;
9463
9464function shouldAutoFocusHostComponent(type, props) {
9465 switch (type) {
9466 case 'button':
9467 case 'input':
9468 case 'select':
9469 case 'textarea':
9470 return !!props.autoFocus;
9471 }
9472 return false;
9473}
9474
9475function getRootHostContext(rootContainerInstance) {
9476 var type = void 0;
9477 var namespace = void 0;
9478 var nodeType = rootContainerInstance.nodeType;
9479 switch (nodeType) {
9480 case DOCUMENT_NODE:
9481 case DOCUMENT_FRAGMENT_NODE:
9482 {
9483 type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
9484 var root = rootContainerInstance.documentElement;
9485 namespace = root ? root.namespaceURI : getChildNamespace(null, '');
9486 break;
9487 }
9488 default:
9489 {
9490 var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
9491 var ownNamespace = container.namespaceURI || null;
9492 type = container.tagName;
9493 namespace = getChildNamespace(ownNamespace, type);
9494 break;
9495 }
9496 }
9497 {
9498 var validatedTag = type.toLowerCase();
9499 var _ancestorInfo = updatedAncestorInfo(null, validatedTag);
9500 return { namespace: namespace, ancestorInfo: _ancestorInfo, eventData: null };
9501 }
9502 return namespace;
9503}
9504
9505function getChildHostContext(parentHostContext, type, rootContainerInstance) {
9506 {
9507 var parentHostContextDev = parentHostContext;
9508 var _namespace = getChildNamespace(parentHostContextDev.namespace, type);
9509 var _ancestorInfo2 = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
9510 return { namespace: _namespace, ancestorInfo: _ancestorInfo2, eventData: null };
9511 }
9512 var parentNamespace = parentHostContext;
9513 return getChildNamespace(parentNamespace, type);
9514}
9515
9516function getChildHostContextForEventComponent(parentHostContext) {
9517 {
9518 var parentHostContextDev = parentHostContext;
9519 var _namespace2 = parentHostContextDev.namespace,
9520 _ancestorInfo3 = parentHostContextDev.ancestorInfo;
9521
9522 !(parentHostContextDev.eventData === null || !parentHostContextDev.eventData.isEventTarget) ? warning$1(false, 'validateDOMNesting: React event targets must not have event components as children.') : void 0;
9523 var _eventData = {
9524 isEventComponent: true,
9525 isEventTarget: false,
9526 eventTargetType: null
9527 };
9528 return { namespace: _namespace2, ancestorInfo: _ancestorInfo3, eventData: _eventData };
9529 }
9530 return parentHostContext;
9531}
9532
9533function getChildHostContextForEventTarget(parentHostContext, type) {
9534 {
9535 var parentHostContextDev = parentHostContext;
9536 var _namespace3 = parentHostContextDev.namespace,
9537 _ancestorInfo4 = parentHostContextDev.ancestorInfo;
9538
9539 !(parentHostContextDev.eventData === null || !parentHostContextDev.eventData.isEventComponent || type !== REACT_EVENT_TARGET_TOUCH_HIT) ? warning$1(false, 'validateDOMNesting: <TouchHitTarget> cannot not be a direct child of an event component. ' + 'Ensure <TouchHitTarget> is a direct child of a DOM element.') : void 0;
9540 var _eventData2 = {
9541 isEventComponent: false,
9542 isEventTarget: true,
9543 eventTargetType: type
9544 };
9545 return { namespace: _namespace3, ancestorInfo: _ancestorInfo4, eventData: _eventData2 };
9546 }
9547 return parentHostContext;
9548}
9549
9550function getPublicInstance(instance) {
9551 return instance;
9552}
9553
9554function prepareForCommit(containerInfo) {
9555 eventsEnabled = isEnabled();
9556 selectionInformation = getSelectionInformation();
9557 setEnabled(false);
9558}
9559
9560function resetAfterCommit(containerInfo) {
9561 restoreSelection(selectionInformation);
9562 selectionInformation = null;
9563 setEnabled(eventsEnabled);
9564 eventsEnabled = null;
9565}
9566
9567function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
9568 var parentNamespace = void 0;
9569 {
9570 // TODO: take namespace into account when validating.
9571 var hostContextDev = hostContext;
9572 if (enableEventAPI) {
9573 var _eventData3 = hostContextDev.eventData;
9574 if (_eventData3 !== null) {
9575 !(!_eventData3.isEventTarget || _eventData3.eventTargetType !== REACT_EVENT_TARGET_TOUCH_HIT) ? warning$1(false, 'Warning: validateDOMNesting: <TouchHitTarget> must not have any children.') : void 0;
9576 }
9577 }
9578 validateDOMNesting(type, null, hostContextDev.ancestorInfo);
9579 if (typeof props.children === 'string' || typeof props.children === 'number') {
9580 var string = '' + props.children;
9581 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
9582 validateDOMNesting(null, string, ownAncestorInfo);
9583 }
9584 parentNamespace = hostContextDev.namespace;
9585 }
9586 var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
9587 precacheFiberNode(internalInstanceHandle, domElement);
9588 updateFiberProps(domElement, props);
9589 return domElement;
9590}
9591
9592function appendInitialChild(parentInstance, child) {
9593 parentInstance.appendChild(child);
9594}
9595
9596function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
9597 setInitialProperties(domElement, type, props, rootContainerInstance);
9598 return shouldAutoFocusHostComponent(type, props);
9599}
9600
9601function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
9602 {
9603 var hostContextDev = hostContext;
9604 if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
9605 var string = '' + newProps.children;
9606 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
9607 validateDOMNesting(null, string, ownAncestorInfo);
9608 }
9609 }
9610 return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);
9611}
9612
9613function shouldSetTextContent(type, props) {
9614 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;
9615}
9616
9617function shouldDeprioritizeSubtree(type, props) {
9618 return !!props.hidden;
9619}
9620
9621function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
9622 {
9623 var hostContextDev = hostContext;
9624 validateDOMNesting(null, text, hostContextDev.ancestorInfo);
9625 if (enableEventAPI) {
9626 var _eventData4 = hostContextDev.eventData;
9627 if (_eventData4 !== null) {
9628 !(_eventData4 === null || !_eventData4.isEventTarget || _eventData4.eventTargetType !== REACT_EVENT_TARGET_TOUCH_HIT) ? warning$1(false, 'Warning: validateDOMNesting: <TouchHitTarget> must not have any children.') : void 0;
9629 !!_eventData4.isEventComponent ? warning$1(false, 'validateDOMNesting: React event components cannot have text DOM nodes as children. ' + 'Wrap the child text "%s" in an element.', text) : void 0;
9630 !(!_eventData4.isEventTarget || _eventData4.eventTargetType === REACT_EVENT_TARGET_TOUCH_HIT) ? warning$1(false, 'validateDOMNesting: React event targets cannot have text DOM nodes as children. ' + 'Wrap the child text "%s" in an element.', text) : void 0;
9631 }
9632 }
9633 }
9634 var textNode = createTextNode(text, rootContainerInstance);
9635 precacheFiberNode(internalInstanceHandle, textNode);
9636 return textNode;
9637}
9638
9639var isPrimaryRenderer = true;
9640// This initialization code may run even on server environments
9641// if a component just imports ReactDOM (e.g. for findDOMNode).
9642// Some environments might not have setTimeout or clearTimeout.
9643var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
9644var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
9645var noTimeout = -1;
9646
9647// -------------------
9648// Mutation
9649// -------------------
9650
9651var supportsMutation = true;
9652
9653function commitMount(domElement, type, newProps, internalInstanceHandle) {
9654 // Despite the naming that might imply otherwise, this method only
9655 // fires if there is an `Update` effect scheduled during mounting.
9656 // This happens if `finalizeInitialChildren` returns `true` (which it
9657 // does to implement the `autoFocus` attribute on the client). But
9658 // there are also other cases when this might happen (such as patching
9659 // up text content during hydration mismatch). So we'll check this again.
9660 if (shouldAutoFocusHostComponent(type, newProps)) {
9661 domElement.focus();
9662 }
9663}
9664
9665function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
9666 // Update the props handle so that we know which props are the ones with
9667 // with current event handlers.
9668 updateFiberProps(domElement, newProps);
9669 // Apply the diff to the DOM node.
9670 updateProperties(domElement, updatePayload, type, oldProps, newProps);
9671}
9672
9673function resetTextContent(domElement) {
9674 setTextContent(domElement, '');
9675}
9676
9677function commitTextUpdate(textInstance, oldText, newText) {
9678 textInstance.nodeValue = newText;
9679}
9680
9681function appendChild(parentInstance, child) {
9682 parentInstance.appendChild(child);
9683}
9684
9685function appendChildToContainer(container, child) {
9686 var parentNode = void 0;
9687 if (container.nodeType === COMMENT_NODE) {
9688 parentNode = container.parentNode;
9689 parentNode.insertBefore(child, container);
9690 } else {
9691 parentNode = container;
9692 parentNode.appendChild(child);
9693 }
9694 // This container might be used for a portal.
9695 // If something inside a portal is clicked, that click should bubble
9696 // through the React tree. However, on Mobile Safari the click would
9697 // never bubble through the *DOM* tree unless an ancestor with onclick
9698 // event exists. So we wouldn't see it and dispatch it.
9699 // This is why we ensure that non React root containers have inline onclick
9700 // defined.
9701 // https://github.com/facebook/react/issues/11918
9702 var reactRootContainer = container._reactRootContainer;
9703 if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
9704 // TODO: This cast may not be sound for SVG, MathML or custom elements.
9705 trapClickOnNonInteractiveElement(parentNode);
9706 }
9707}
9708
9709function insertBefore(parentInstance, child, beforeChild) {
9710 parentInstance.insertBefore(child, beforeChild);
9711}
9712
9713function insertInContainerBefore(container, child, beforeChild) {
9714 if (container.nodeType === COMMENT_NODE) {
9715 container.parentNode.insertBefore(child, beforeChild);
9716 } else {
9717 container.insertBefore(child, beforeChild);
9718 }
9719}
9720
9721function removeChild(parentInstance, child) {
9722 parentInstance.removeChild(child);
9723}
9724
9725function removeChildFromContainer(container, child) {
9726 if (container.nodeType === COMMENT_NODE) {
9727 container.parentNode.removeChild(child);
9728 } else {
9729 container.removeChild(child);
9730 }
9731}
9732
9733function clearSuspenseBoundary(parentInstance, suspenseInstance) {
9734 var node = suspenseInstance;
9735 // Delete all nodes within this suspense boundary.
9736 // There might be nested nodes so we need to keep track of how
9737 // deep we are and only break out when we're back on top.
9738 var depth = 0;
9739 do {
9740 var nextNode = node.nextSibling;
9741 parentInstance.removeChild(node);
9742 if (nextNode && nextNode.nodeType === COMMENT_NODE) {
9743 var data = nextNode.data;
9744 if (data === SUSPENSE_END_DATA) {
9745 if (depth === 0) {
9746 parentInstance.removeChild(nextNode);
9747 return;
9748 } else {
9749 depth--;
9750 }
9751 } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_FALLBACK_START_DATA) {
9752 depth++;
9753 }
9754 }
9755 node = nextNode;
9756 } while (node);
9757 // TODO: Warn, we didn't find the end comment boundary.
9758}
9759
9760function clearSuspenseBoundaryFromContainer(container, suspenseInstance) {
9761 if (container.nodeType === COMMENT_NODE) {
9762 clearSuspenseBoundary(container.parentNode, suspenseInstance);
9763 } else if (container.nodeType === ELEMENT_NODE) {
9764 clearSuspenseBoundary(container, suspenseInstance);
9765 } else {
9766 // Document nodes should never contain suspense boundaries.
9767 }
9768}
9769
9770function hideInstance(instance) {
9771 // TODO: Does this work for all element types? What about MathML? Should we
9772 // pass host context to this method?
9773 instance = instance;
9774 instance.style.display = 'none';
9775}
9776
9777function hideTextInstance(textInstance) {
9778 textInstance.nodeValue = '';
9779}
9780
9781function unhideInstance(instance, props) {
9782 instance = instance;
9783 var styleProp = props[STYLE];
9784 var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
9785 instance.style.display = dangerousStyleValue('display', display);
9786}
9787
9788function unhideTextInstance(textInstance, text) {
9789 textInstance.nodeValue = text;
9790}
9791
9792// -------------------
9793// Hydration
9794// -------------------
9795
9796var supportsHydration = true;
9797
9798function canHydrateInstance(instance, type, props) {
9799 if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
9800 return null;
9801 }
9802 // This has now been refined to an element node.
9803 return instance;
9804}
9805
9806function canHydrateTextInstance(instance, text) {
9807 if (text === '' || instance.nodeType !== TEXT_NODE) {
9808 // Empty strings are not parsed by HTML so there won't be a correct match here.
9809 return null;
9810 }
9811 // This has now been refined to a text node.
9812 return instance;
9813}
9814
9815function canHydrateSuspenseInstance(instance) {
9816 if (instance.nodeType !== COMMENT_NODE) {
9817 // Empty strings are not parsed by HTML so there won't be a correct match here.
9818 return null;
9819 }
9820 // This has now been refined to a suspense node.
9821 return instance;
9822}
9823
9824function isSuspenseInstancePending(instance) {
9825 return instance.data === SUSPENSE_PENDING_START_DATA;
9826}
9827
9828function isSuspenseInstanceFallback(instance) {
9829 return instance.data === SUSPENSE_FALLBACK_START_DATA;
9830}
9831
9832function registerSuspenseInstanceRetry(instance, callback) {
9833 instance._reactRetry = callback;
9834}
9835
9836function getNextHydratableSibling(instance) {
9837 var node = instance.nextSibling;
9838 // Skip non-hydratable nodes.
9839 while (node && node.nodeType !== ELEMENT_NODE && node.nodeType !== TEXT_NODE && (!enableSuspenseServerRenderer || node.nodeType !== COMMENT_NODE || node.data !== SUSPENSE_START_DATA && node.data !== SUSPENSE_PENDING_START_DATA && node.data !== SUSPENSE_FALLBACK_START_DATA)) {
9840 node = node.nextSibling;
9841 }
9842 return node;
9843}
9844
9845function getFirstHydratableChild(parentInstance) {
9846 var next = parentInstance.firstChild;
9847 // Skip non-hydratable nodes.
9848 while (next && next.nodeType !== ELEMENT_NODE && next.nodeType !== TEXT_NODE && (!enableSuspenseServerRenderer || next.nodeType !== COMMENT_NODE || next.data !== SUSPENSE_START_DATA && next.data !== SUSPENSE_FALLBACK_START_DATA && next.data !== SUSPENSE_PENDING_START_DATA)) {
9849 next = next.nextSibling;
9850 }
9851 return next;
9852}
9853
9854function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
9855 precacheFiberNode(internalInstanceHandle, instance);
9856 // TODO: Possibly defer this until the commit phase where all the events
9857 // get attached.
9858 updateFiberProps(instance, props);
9859 var parentNamespace = void 0;
9860 {
9861 var hostContextDev = hostContext;
9862 parentNamespace = hostContextDev.namespace;
9863 }
9864 return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);
9865}
9866
9867function hydrateTextInstance(textInstance, text, internalInstanceHandle) {
9868 precacheFiberNode(internalInstanceHandle, textInstance);
9869 return diffHydratedText(textInstance, text);
9870}
9871
9872function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
9873 var node = suspenseInstance.nextSibling;
9874 // Skip past all nodes within this suspense boundary.
9875 // There might be nested nodes so we need to keep track of how
9876 // deep we are and only break out when we're back on top.
9877 var depth = 0;
9878 while (node) {
9879 if (node.nodeType === COMMENT_NODE) {
9880 var data = node.data;
9881 if (data === SUSPENSE_END_DATA) {
9882 if (depth === 0) {
9883 return getNextHydratableSibling(node);
9884 } else {
9885 depth--;
9886 }
9887 } else if (data === SUSPENSE_START_DATA) {
9888 depth++;
9889 }
9890 }
9891 node = node.nextSibling;
9892 }
9893 // TODO: Warn, we didn't find the end comment boundary.
9894 return null;
9895}
9896
9897function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {
9898 {
9899 warnForUnmatchedText(textInstance, text);
9900 }
9901}
9902
9903function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {
9904 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9905 warnForUnmatchedText(textInstance, text);
9906 }
9907}
9908
9909function didNotHydrateContainerInstance(parentContainer, instance) {
9910 {
9911 if (instance.nodeType === ELEMENT_NODE) {
9912 warnForDeletedHydratableElement(parentContainer, instance);
9913 } else if (instance.nodeType === COMMENT_NODE) {
9914 // TODO: warnForDeletedHydratableSuspenseBoundary
9915 } else {
9916 warnForDeletedHydratableText(parentContainer, instance);
9917 }
9918 }
9919}
9920
9921function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {
9922 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9923 if (instance.nodeType === ELEMENT_NODE) {
9924 warnForDeletedHydratableElement(parentInstance, instance);
9925 } else if (instance.nodeType === COMMENT_NODE) {
9926 // TODO: warnForDeletedHydratableSuspenseBoundary
9927 } else {
9928 warnForDeletedHydratableText(parentInstance, instance);
9929 }
9930 }
9931}
9932
9933function didNotFindHydratableContainerInstance(parentContainer, type, props) {
9934 {
9935 warnForInsertedHydratedElement(parentContainer, type, props);
9936 }
9937}
9938
9939function didNotFindHydratableContainerTextInstance(parentContainer, text) {
9940 {
9941 warnForInsertedHydratedText(parentContainer, text);
9942 }
9943}
9944
9945
9946
9947function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {
9948 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9949 warnForInsertedHydratedElement(parentInstance, type, props);
9950 }
9951}
9952
9953function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {
9954 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9955 warnForInsertedHydratedText(parentInstance, text);
9956 }
9957}
9958
9959function didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance) {
9960 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9961 // TODO: warnForInsertedHydratedSuspense(parentInstance);
9962 }
9963}
9964
9965function handleEventComponent(eventResponder, rootContainerInstance, internalInstanceHandle) {
9966 if (enableEventAPI) {
9967 var rootElement = rootContainerInstance.ownerDocument;
9968 listenToEventResponderEventTypes(eventResponder.targetEventTypes, rootElement);
9969 }
9970}
9971
9972// Prefix measurements so that it's possible to filter them.
9973// Longer prefixes are hard to read in DevTools.
9974var reactEmoji = '\u269B';
9975var warningEmoji = '\u26D4';
9976var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function';
9977
9978// Keep track of current fiber so that we know the path to unwind on pause.
9979// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
9980var currentFiber = null;
9981// If we're in the middle of user code, which fiber and method is it?
9982// Reusing `currentFiber` would be confusing for this because user code fiber
9983// can change during commit phase too, but we don't need to unwind it (since
9984// lifecycles in the commit phase don't resemble a tree).
9985var currentPhase = null;
9986var currentPhaseFiber = null;
9987// Did lifecycle hook schedule an update? This is often a performance problem,
9988// so we will keep track of it, and include it in the report.
9989// Track commits caused by cascading updates.
9990var isCommitting = false;
9991var hasScheduledUpdateInCurrentCommit = false;
9992var hasScheduledUpdateInCurrentPhase = false;
9993var commitCountInCurrentWorkLoop = 0;
9994var effectCountInCurrentCommit = 0;
9995var isWaitingForCallback = false;
9996// During commits, we only show a measurement once per method name
9997// to avoid stretch the commit phase with measurement overhead.
9998var labelsInCurrentCommit = new Set();
9999
10000var formatMarkName = function (markName) {
10001 return reactEmoji + ' ' + markName;
10002};
10003
10004var formatLabel = function (label, warning) {
10005 var prefix = warning ? warningEmoji + ' ' : reactEmoji + ' ';
10006 var suffix = warning ? ' Warning: ' + warning : '';
10007 return '' + prefix + label + suffix;
10008};
10009
10010var beginMark = function (markName) {
10011 performance.mark(formatMarkName(markName));
10012};
10013
10014var clearMark = function (markName) {
10015 performance.clearMarks(formatMarkName(markName));
10016};
10017
10018var endMark = function (label, markName, warning) {
10019 var formattedMarkName = formatMarkName(markName);
10020 var formattedLabel = formatLabel(label, warning);
10021 try {
10022 performance.measure(formattedLabel, formattedMarkName);
10023 } catch (err) {}
10024 // If previous mark was missing for some reason, this will throw.
10025 // This could only happen if React crashed in an unexpected place earlier.
10026 // Don't pile on with more errors.
10027
10028 // Clear marks immediately to avoid growing buffer.
10029 performance.clearMarks(formattedMarkName);
10030 performance.clearMeasures(formattedLabel);
10031};
10032
10033var getFiberMarkName = function (label, debugID) {
10034 return label + ' (#' + debugID + ')';
10035};
10036
10037var getFiberLabel = function (componentName, isMounted, phase) {
10038 if (phase === null) {
10039 // These are composite component total time measurements.
10040 return componentName + ' [' + (isMounted ? 'update' : 'mount') + ']';
10041 } else {
10042 // Composite component methods.
10043 return componentName + '.' + phase;
10044 }
10045};
10046
10047var beginFiberMark = function (fiber, phase) {
10048 var componentName = getComponentName(fiber.type) || 'Unknown';
10049 var debugID = fiber._debugID;
10050 var isMounted = fiber.alternate !== null;
10051 var label = getFiberLabel(componentName, isMounted, phase);
10052
10053 if (isCommitting && labelsInCurrentCommit.has(label)) {
10054 // During the commit phase, we don't show duplicate labels because
10055 // there is a fixed overhead for every measurement, and we don't
10056 // want to stretch the commit phase beyond necessary.
10057 return false;
10058 }
10059 labelsInCurrentCommit.add(label);
10060
10061 var markName = getFiberMarkName(label, debugID);
10062 beginMark(markName);
10063 return true;
10064};
10065
10066var clearFiberMark = function (fiber, phase) {
10067 var componentName = getComponentName(fiber.type) || 'Unknown';
10068 var debugID = fiber._debugID;
10069 var isMounted = fiber.alternate !== null;
10070 var label = getFiberLabel(componentName, isMounted, phase);
10071 var markName = getFiberMarkName(label, debugID);
10072 clearMark(markName);
10073};
10074
10075var endFiberMark = function (fiber, phase, warning) {
10076 var componentName = getComponentName(fiber.type) || 'Unknown';
10077 var debugID = fiber._debugID;
10078 var isMounted = fiber.alternate !== null;
10079 var label = getFiberLabel(componentName, isMounted, phase);
10080 var markName = getFiberMarkName(label, debugID);
10081 endMark(label, markName, warning);
10082};
10083
10084var shouldIgnoreFiber = function (fiber) {
10085 // Host components should be skipped in the timeline.
10086 // We could check typeof fiber.type, but does this work with RN?
10087 switch (fiber.tag) {
10088 case HostRoot:
10089 case HostComponent:
10090 case HostText:
10091 case HostPortal:
10092 case Fragment:
10093 case ContextProvider:
10094 case ContextConsumer:
10095 case Mode:
10096 return true;
10097 default:
10098 return false;
10099 }
10100};
10101
10102var clearPendingPhaseMeasurement = function () {
10103 if (currentPhase !== null && currentPhaseFiber !== null) {
10104 clearFiberMark(currentPhaseFiber, currentPhase);
10105 }
10106 currentPhaseFiber = null;
10107 currentPhase = null;
10108 hasScheduledUpdateInCurrentPhase = false;
10109};
10110
10111var pauseTimers = function () {
10112 // Stops all currently active measurements so that they can be resumed
10113 // if we continue in a later deferred loop from the same unit of work.
10114 var fiber = currentFiber;
10115 while (fiber) {
10116 if (fiber._debugIsCurrentlyTiming) {
10117 endFiberMark(fiber, null, null);
10118 }
10119 fiber = fiber.return;
10120 }
10121};
10122
10123var resumeTimersRecursively = function (fiber) {
10124 if (fiber.return !== null) {
10125 resumeTimersRecursively(fiber.return);
10126 }
10127 if (fiber._debugIsCurrentlyTiming) {
10128 beginFiberMark(fiber, null);
10129 }
10130};
10131
10132var resumeTimers = function () {
10133 // Resumes all measurements that were active during the last deferred loop.
10134 if (currentFiber !== null) {
10135 resumeTimersRecursively(currentFiber);
10136 }
10137};
10138
10139function recordEffect() {
10140 if (enableUserTimingAPI) {
10141 effectCountInCurrentCommit++;
10142 }
10143}
10144
10145function recordScheduleUpdate() {
10146 if (enableUserTimingAPI) {
10147 if (isCommitting) {
10148 hasScheduledUpdateInCurrentCommit = true;
10149 }
10150 if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
10151 hasScheduledUpdateInCurrentPhase = true;
10152 }
10153 }
10154}
10155
10156function startRequestCallbackTimer() {
10157 if (enableUserTimingAPI) {
10158 if (supportsUserTiming && !isWaitingForCallback) {
10159 isWaitingForCallback = true;
10160 beginMark('(Waiting for async callback...)');
10161 }
10162 }
10163}
10164
10165function stopRequestCallbackTimer(didExpire, expirationTime) {
10166 if (enableUserTimingAPI) {
10167 if (supportsUserTiming) {
10168 isWaitingForCallback = false;
10169 var warning = didExpire ? 'React was blocked by main thread' : null;
10170 endMark('(Waiting for async callback... will force flush in ' + expirationTime + ' ms)', '(Waiting for async callback...)', warning);
10171 }
10172 }
10173}
10174
10175function startWorkTimer(fiber) {
10176 if (enableUserTimingAPI) {
10177 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
10178 return;
10179 }
10180 // If we pause, this is the fiber to unwind from.
10181 currentFiber = fiber;
10182 if (!beginFiberMark(fiber, null)) {
10183 return;
10184 }
10185 fiber._debugIsCurrentlyTiming = true;
10186 }
10187}
10188
10189function cancelWorkTimer(fiber) {
10190 if (enableUserTimingAPI) {
10191 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
10192 return;
10193 }
10194 // Remember we shouldn't complete measurement for this fiber.
10195 // Otherwise flamechart will be deep even for small updates.
10196 fiber._debugIsCurrentlyTiming = false;
10197 clearFiberMark(fiber, null);
10198 }
10199}
10200
10201function stopWorkTimer(fiber) {
10202 if (enableUserTimingAPI) {
10203 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
10204 return;
10205 }
10206 // If we pause, its parent is the fiber to unwind from.
10207 currentFiber = fiber.return;
10208 if (!fiber._debugIsCurrentlyTiming) {
10209 return;
10210 }
10211 fiber._debugIsCurrentlyTiming = false;
10212 endFiberMark(fiber, null, null);
10213 }
10214}
10215
10216function stopFailedWorkTimer(fiber) {
10217 if (enableUserTimingAPI) {
10218 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
10219 return;
10220 }
10221 // If we pause, its parent is the fiber to unwind from.
10222 currentFiber = fiber.return;
10223 if (!fiber._debugIsCurrentlyTiming) {
10224 return;
10225 }
10226 fiber._debugIsCurrentlyTiming = false;
10227 var warning = fiber.tag === SuspenseComponent || fiber.tag === DehydratedSuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
10228 endFiberMark(fiber, null, warning);
10229 }
10230}
10231
10232function startPhaseTimer(fiber, phase) {
10233 if (enableUserTimingAPI) {
10234 if (!supportsUserTiming) {
10235 return;
10236 }
10237 clearPendingPhaseMeasurement();
10238 if (!beginFiberMark(fiber, phase)) {
10239 return;
10240 }
10241 currentPhaseFiber = fiber;
10242 currentPhase = phase;
10243 }
10244}
10245
10246function stopPhaseTimer() {
10247 if (enableUserTimingAPI) {
10248 if (!supportsUserTiming) {
10249 return;
10250 }
10251 if (currentPhase !== null && currentPhaseFiber !== null) {
10252 var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
10253 endFiberMark(currentPhaseFiber, currentPhase, warning);
10254 }
10255 currentPhase = null;
10256 currentPhaseFiber = null;
10257 }
10258}
10259
10260function startWorkLoopTimer(nextUnitOfWork) {
10261 if (enableUserTimingAPI) {
10262 currentFiber = nextUnitOfWork;
10263 if (!supportsUserTiming) {
10264 return;
10265 }
10266 commitCountInCurrentWorkLoop = 0;
10267 // This is top level call.
10268 // Any other measurements are performed within.
10269 beginMark('(React Tree Reconciliation)');
10270 // Resume any measurements that were in progress during the last loop.
10271 resumeTimers();
10272 }
10273}
10274
10275function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
10276 if (enableUserTimingAPI) {
10277 if (!supportsUserTiming) {
10278 return;
10279 }
10280 var warning = null;
10281 if (interruptedBy !== null) {
10282 if (interruptedBy.tag === HostRoot) {
10283 warning = 'A top-level update interrupted the previous render';
10284 } else {
10285 var componentName = getComponentName(interruptedBy.type) || 'Unknown';
10286 warning = 'An update to ' + componentName + ' interrupted the previous render';
10287 }
10288 } else if (commitCountInCurrentWorkLoop > 1) {
10289 warning = 'There were cascading updates';
10290 }
10291 commitCountInCurrentWorkLoop = 0;
10292 var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)';
10293 // Pause any measurements until the next loop.
10294 pauseTimers();
10295 endMark(label, '(React Tree Reconciliation)', warning);
10296 }
10297}
10298
10299function startCommitTimer() {
10300 if (enableUserTimingAPI) {
10301 if (!supportsUserTiming) {
10302 return;
10303 }
10304 isCommitting = true;
10305 hasScheduledUpdateInCurrentCommit = false;
10306 labelsInCurrentCommit.clear();
10307 beginMark('(Committing Changes)');
10308 }
10309}
10310
10311function stopCommitTimer() {
10312 if (enableUserTimingAPI) {
10313 if (!supportsUserTiming) {
10314 return;
10315 }
10316
10317 var warning = null;
10318 if (hasScheduledUpdateInCurrentCommit) {
10319 warning = 'Lifecycle hook scheduled a cascading update';
10320 } else if (commitCountInCurrentWorkLoop > 0) {
10321 warning = 'Caused by a cascading update in earlier commit';
10322 }
10323 hasScheduledUpdateInCurrentCommit = false;
10324 commitCountInCurrentWorkLoop++;
10325 isCommitting = false;
10326 labelsInCurrentCommit.clear();
10327
10328 endMark('(Committing Changes)', '(Committing Changes)', warning);
10329 }
10330}
10331
10332function startCommitSnapshotEffectsTimer() {
10333 if (enableUserTimingAPI) {
10334 if (!supportsUserTiming) {
10335 return;
10336 }
10337 effectCountInCurrentCommit = 0;
10338 beginMark('(Committing Snapshot Effects)');
10339 }
10340}
10341
10342function stopCommitSnapshotEffectsTimer() {
10343 if (enableUserTimingAPI) {
10344 if (!supportsUserTiming) {
10345 return;
10346 }
10347 var count = effectCountInCurrentCommit;
10348 effectCountInCurrentCommit = 0;
10349 endMark('(Committing Snapshot Effects: ' + count + ' Total)', '(Committing Snapshot Effects)', null);
10350 }
10351}
10352
10353function startCommitHostEffectsTimer() {
10354 if (enableUserTimingAPI) {
10355 if (!supportsUserTiming) {
10356 return;
10357 }
10358 effectCountInCurrentCommit = 0;
10359 beginMark('(Committing Host Effects)');
10360 }
10361}
10362
10363function stopCommitHostEffectsTimer() {
10364 if (enableUserTimingAPI) {
10365 if (!supportsUserTiming) {
10366 return;
10367 }
10368 var count = effectCountInCurrentCommit;
10369 effectCountInCurrentCommit = 0;
10370 endMark('(Committing Host Effects: ' + count + ' Total)', '(Committing Host Effects)', null);
10371 }
10372}
10373
10374function startCommitLifeCyclesTimer() {
10375 if (enableUserTimingAPI) {
10376 if (!supportsUserTiming) {
10377 return;
10378 }
10379 effectCountInCurrentCommit = 0;
10380 beginMark('(Calling Lifecycle Methods)');
10381 }
10382}
10383
10384function stopCommitLifeCyclesTimer() {
10385 if (enableUserTimingAPI) {
10386 if (!supportsUserTiming) {
10387 return;
10388 }
10389 var count = effectCountInCurrentCommit;
10390 effectCountInCurrentCommit = 0;
10391 endMark('(Calling Lifecycle Methods: ' + count + ' Total)', '(Calling Lifecycle Methods)', null);
10392 }
10393}
10394
10395var valueStack = [];
10396
10397var fiberStack = void 0;
10398
10399{
10400 fiberStack = [];
10401}
10402
10403var index = -1;
10404
10405function createCursor(defaultValue) {
10406 return {
10407 current: defaultValue
10408 };
10409}
10410
10411function pop(cursor, fiber) {
10412 if (index < 0) {
10413 {
10414 warningWithoutStack$1(false, 'Unexpected pop.');
10415 }
10416 return;
10417 }
10418
10419 {
10420 if (fiber !== fiberStack[index]) {
10421 warningWithoutStack$1(false, 'Unexpected Fiber popped.');
10422 }
10423 }
10424
10425 cursor.current = valueStack[index];
10426
10427 valueStack[index] = null;
10428
10429 {
10430 fiberStack[index] = null;
10431 }
10432
10433 index--;
10434}
10435
10436function push(cursor, value, fiber) {
10437 index++;
10438
10439 valueStack[index] = cursor.current;
10440
10441 {
10442 fiberStack[index] = fiber;
10443 }
10444
10445 cursor.current = value;
10446}
10447
10448function checkThatStackIsEmpty() {
10449 {
10450 if (index !== -1) {
10451 warningWithoutStack$1(false, 'Expected an empty stack. Something was not reset properly.');
10452 }
10453 }
10454}
10455
10456function resetStackAfterFatalErrorInDev() {
10457 {
10458 index = -1;
10459 valueStack.length = 0;
10460 fiberStack.length = 0;
10461 }
10462}
10463
10464var warnedAboutMissingGetChildContext = void 0;
10465
10466{
10467 warnedAboutMissingGetChildContext = {};
10468}
10469
10470var emptyContextObject = {};
10471{
10472 Object.freeze(emptyContextObject);
10473}
10474
10475// A cursor to the current merged context object on the stack.
10476var contextStackCursor = createCursor(emptyContextObject);
10477// A cursor to a boolean indicating whether the context has changed.
10478var didPerformWorkStackCursor = createCursor(false);
10479// Keep track of the previous context object that was on the stack.
10480// We use this to get access to the parent context after we have already
10481// pushed the next context provider, and now need to merge their contexts.
10482var previousContext = emptyContextObject;
10483
10484function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
10485 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
10486 // If the fiber is a context provider itself, when we read its context
10487 // we may have already pushed its own child context on the stack. A context
10488 // provider should not "see" its own child context. Therefore we read the
10489 // previous (parent) context instead for a context provider.
10490 return previousContext;
10491 }
10492 return contextStackCursor.current;
10493}
10494
10495function cacheContext(workInProgress, unmaskedContext, maskedContext) {
10496 var instance = workInProgress.stateNode;
10497 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
10498 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
10499}
10500
10501function getMaskedContext(workInProgress, unmaskedContext) {
10502 var type = workInProgress.type;
10503 var contextTypes = type.contextTypes;
10504 if (!contextTypes) {
10505 return emptyContextObject;
10506 }
10507
10508 // Avoid recreating masked context unless unmasked context has changed.
10509 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
10510 // This may trigger infinite loops if componentWillReceiveProps calls setState.
10511 var instance = workInProgress.stateNode;
10512 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
10513 return instance.__reactInternalMemoizedMaskedChildContext;
10514 }
10515
10516 var context = {};
10517 for (var key in contextTypes) {
10518 context[key] = unmaskedContext[key];
10519 }
10520
10521 {
10522 var name = getComponentName(type) || 'Unknown';
10523 checkPropTypes_1(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
10524 }
10525
10526 // Cache unmasked context so we can avoid recreating masked context unless necessary.
10527 // Context is created before the class component is instantiated so check for instance.
10528 if (instance) {
10529 cacheContext(workInProgress, unmaskedContext, context);
10530 }
10531
10532 return context;
10533}
10534
10535function hasContextChanged() {
10536 return didPerformWorkStackCursor.current;
10537}
10538
10539function isContextProvider(type) {
10540 var childContextTypes = type.childContextTypes;
10541 return childContextTypes !== null && childContextTypes !== undefined;
10542}
10543
10544function popContext(fiber) {
10545 pop(didPerformWorkStackCursor, fiber);
10546 pop(contextStackCursor, fiber);
10547}
10548
10549function popTopLevelContextObject(fiber) {
10550 pop(didPerformWorkStackCursor, fiber);
10551 pop(contextStackCursor, fiber);
10552}
10553
10554function pushTopLevelContextObject(fiber, context, didChange) {
10555 (function () {
10556 if (!(contextStackCursor.current === emptyContextObject)) {
10557 {
10558 throw ReactError('Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.');
10559 }
10560 }
10561 })();
10562
10563 push(contextStackCursor, context, fiber);
10564 push(didPerformWorkStackCursor, didChange, fiber);
10565}
10566
10567function processChildContext(fiber, type, parentContext) {
10568 var instance = fiber.stateNode;
10569 var childContextTypes = type.childContextTypes;
10570
10571 // TODO (bvaughn) Replace this behavior with an invariant() in the future.
10572 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
10573 if (typeof instance.getChildContext !== 'function') {
10574 {
10575 var componentName = getComponentName(type) || 'Unknown';
10576
10577 if (!warnedAboutMissingGetChildContext[componentName]) {
10578 warnedAboutMissingGetChildContext[componentName] = true;
10579 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);
10580 }
10581 }
10582 return parentContext;
10583 }
10584
10585 var childContext = void 0;
10586 {
10587 setCurrentPhase('getChildContext');
10588 }
10589 startPhaseTimer(fiber, 'getChildContext');
10590 childContext = instance.getChildContext();
10591 stopPhaseTimer();
10592 {
10593 setCurrentPhase(null);
10594 }
10595 for (var contextKey in childContext) {
10596 (function () {
10597 if (!(contextKey in childContextTypes)) {
10598 {
10599 throw ReactError((getComponentName(type) || 'Unknown') + '.getChildContext(): key "' + contextKey + '" is not defined in childContextTypes.');
10600 }
10601 }
10602 })();
10603 }
10604 {
10605 var name = getComponentName(type) || 'Unknown';
10606 checkPropTypes_1(childContextTypes, childContext, 'child context', name,
10607 // In practice, there is one case in which we won't get a stack. It's when
10608 // somebody calls unstable_renderSubtreeIntoContainer() and we process
10609 // context from the parent component instance. The stack will be missing
10610 // because it's outside of the reconciliation, and so the pointer has not
10611 // been set. This is rare and doesn't matter. We'll also remove that API.
10612 getCurrentFiberStackInDev);
10613 }
10614
10615 return _assign({}, parentContext, childContext);
10616}
10617
10618function pushContextProvider(workInProgress) {
10619 var instance = workInProgress.stateNode;
10620 // We push the context as early as possible to ensure stack integrity.
10621 // If the instance does not exist yet, we will push null at first,
10622 // and replace it on the stack later when invalidating the context.
10623 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject;
10624
10625 // Remember the parent context so we can merge with it later.
10626 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
10627 previousContext = contextStackCursor.current;
10628 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
10629 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
10630
10631 return true;
10632}
10633
10634function invalidateContextProvider(workInProgress, type, didChange) {
10635 var instance = workInProgress.stateNode;
10636 (function () {
10637 if (!instance) {
10638 {
10639 throw ReactError('Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.');
10640 }
10641 }
10642 })();
10643
10644 if (didChange) {
10645 // Merge parent and own context.
10646 // Skip this if we're not updating due to sCU.
10647 // This avoids unnecessarily recomputing memoized values.
10648 var mergedContext = processChildContext(workInProgress, type, previousContext);
10649 instance.__reactInternalMemoizedMergedChildContext = mergedContext;
10650
10651 // Replace the old (or empty) context with the new one.
10652 // It is important to unwind the context in the reverse order.
10653 pop(didPerformWorkStackCursor, workInProgress);
10654 pop(contextStackCursor, workInProgress);
10655 // Now push the new context and mark that it has changed.
10656 push(contextStackCursor, mergedContext, workInProgress);
10657 push(didPerformWorkStackCursor, didChange, workInProgress);
10658 } else {
10659 pop(didPerformWorkStackCursor, workInProgress);
10660 push(didPerformWorkStackCursor, didChange, workInProgress);
10661 }
10662}
10663
10664function findCurrentUnmaskedContext(fiber) {
10665 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
10666 // makes sense elsewhere
10667 (function () {
10668 if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {
10669 {
10670 throw ReactError('Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.');
10671 }
10672 }
10673 })();
10674
10675 var node = fiber;
10676 do {
10677 switch (node.tag) {
10678 case HostRoot:
10679 return node.stateNode.context;
10680 case ClassComponent:
10681 {
10682 var Component = node.type;
10683 if (isContextProvider(Component)) {
10684 return node.stateNode.__reactInternalMemoizedMergedChildContext;
10685 }
10686 break;
10687 }
10688 }
10689 node = node.return;
10690 } while (node !== null);
10691 (function () {
10692 {
10693 {
10694 throw ReactError('Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.');
10695 }
10696 }
10697 })();
10698}
10699
10700var onCommitFiberRoot = null;
10701var onCommitFiberUnmount = null;
10702var hasLoggedError = false;
10703
10704function catchErrors(fn) {
10705 return function (arg) {
10706 try {
10707 return fn(arg);
10708 } catch (err) {
10709 if (true && !hasLoggedError) {
10710 hasLoggedError = true;
10711 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
10712 }
10713 }
10714 };
10715}
10716
10717var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
10718
10719function injectInternals(internals) {
10720 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
10721 // No DevTools
10722 return false;
10723 }
10724 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
10725 if (hook.isDisabled) {
10726 // This isn't a real property on the hook, but it can be set to opt out
10727 // of DevTools integration and associated warnings and logs.
10728 // https://github.com/facebook/react/issues/3877
10729 return true;
10730 }
10731 if (!hook.supportsFiber) {
10732 {
10733 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');
10734 }
10735 // DevTools exists, even though it doesn't support Fiber.
10736 return true;
10737 }
10738 try {
10739 var rendererID = hook.inject(internals);
10740 // We have successfully injected, so now it is safe to set up hooks.
10741 onCommitFiberRoot = catchErrors(function (root) {
10742 return hook.onCommitFiberRoot(rendererID, root);
10743 });
10744 onCommitFiberUnmount = catchErrors(function (fiber) {
10745 return hook.onCommitFiberUnmount(rendererID, fiber);
10746 });
10747 } catch (err) {
10748 // Catch all errors because it is unsafe to throw during initialization.
10749 {
10750 warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
10751 }
10752 }
10753 // DevTools exists
10754 return true;
10755}
10756
10757function onCommitRoot(root) {
10758 if (typeof onCommitFiberRoot === 'function') {
10759 onCommitFiberRoot(root);
10760 }
10761}
10762
10763function onCommitUnmount(fiber) {
10764 if (typeof onCommitFiberUnmount === 'function') {
10765 onCommitFiberUnmount(fiber);
10766 }
10767}
10768
10769// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
10770// Math.pow(2, 30) - 1
10771// 0b111111111111111111111111111111
10772var maxSigned31BitInt = 1073741823;
10773
10774// Intentionally not named imports because Rollup would use dynamic dispatch for
10775// CommonJS interop named imports.
10776var Scheduler_runWithPriority = unstable_runWithPriority;
10777var Scheduler_scheduleCallback = unstable_scheduleCallback;
10778var Scheduler_cancelCallback = unstable_cancelCallback;
10779var Scheduler_shouldYield = unstable_shouldYield;
10780var Scheduler_now = unstable_now;
10781var Scheduler_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
10782var Scheduler_ImmediatePriority = unstable_ImmediatePriority;
10783var Scheduler_UserBlockingPriority = unstable_UserBlockingPriority;
10784var Scheduler_NormalPriority = unstable_NormalPriority;
10785var Scheduler_LowPriority = unstable_LowPriority;
10786var Scheduler_IdlePriority = unstable_IdlePriority;
10787
10788
10789var fakeCallbackNode = {};
10790
10791// Except for NoPriority, these correspond to Scheduler priorities. We use
10792// ascending numbers so we can compare them like numbers. They start at 90 to
10793// avoid clashing with Scheduler's priorities.
10794var ImmediatePriority = 99;
10795var UserBlockingPriority = 98;
10796var NormalPriority = 97;
10797var LowPriority = 96;
10798var IdlePriority = 95;
10799// NoPriority is the absence of priority. Also React-only.
10800
10801
10802var now$1 = Scheduler_now;
10803var shouldYield$1 = disableYielding ? function () {
10804 return false;
10805} // Never yield when `disableYielding` is on
10806: Scheduler_shouldYield;
10807
10808var immediateQueue = null;
10809var immediateQueueCallbackNode = null;
10810var isFlushingImmediate = false;
10811
10812function getCurrentPriorityLevel() {
10813 switch (Scheduler_getCurrentPriorityLevel()) {
10814 case Scheduler_ImmediatePriority:
10815 return ImmediatePriority;
10816 case Scheduler_UserBlockingPriority:
10817 return UserBlockingPriority;
10818 case Scheduler_NormalPriority:
10819 return NormalPriority;
10820 case Scheduler_LowPriority:
10821 return LowPriority;
10822 case Scheduler_IdlePriority:
10823 return IdlePriority;
10824 default:
10825 (function () {
10826 {
10827 {
10828 throw ReactError('Unknown priority level.');
10829 }
10830 }
10831 })();
10832 }
10833}
10834
10835function reactPriorityToSchedulerPriority(reactPriorityLevel) {
10836 switch (reactPriorityLevel) {
10837 case ImmediatePriority:
10838 return Scheduler_ImmediatePriority;
10839 case UserBlockingPriority:
10840 return Scheduler_UserBlockingPriority;
10841 case NormalPriority:
10842 return Scheduler_NormalPriority;
10843 case LowPriority:
10844 return Scheduler_LowPriority;
10845 case IdlePriority:
10846 return Scheduler_IdlePriority;
10847 default:
10848 (function () {
10849 {
10850 {
10851 throw ReactError('Unknown priority level.');
10852 }
10853 }
10854 })();
10855 }
10856}
10857
10858function runWithPriority(reactPriorityLevel, fn) {
10859 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
10860 return Scheduler_runWithPriority(priorityLevel, fn);
10861}
10862
10863function scheduleCallback(reactPriorityLevel, callback, options) {
10864 if (reactPriorityLevel === ImmediatePriority) {
10865 // Push this callback into an internal queue. We'll flush these either in
10866 // the next tick, or earlier if something calls `flushImmediateQueue`.
10867 if (immediateQueue === null) {
10868 immediateQueue = [callback];
10869 // Flush the queue in the next tick, at the earliest.
10870 immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushImmediateQueueImpl);
10871 } else {
10872 // Push onto existing queue. Don't need to schedule a callback because
10873 // we already scheduled one when we created the queue.
10874 immediateQueue.push(callback);
10875 }
10876 return fakeCallbackNode;
10877 }
10878 // Otherwise pass through to Scheduler.
10879 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
10880 return Scheduler_scheduleCallback(priorityLevel, callback, options);
10881}
10882
10883function cancelCallback(callbackNode) {
10884 if (callbackNode !== fakeCallbackNode) {
10885 Scheduler_cancelCallback(callbackNode);
10886 }
10887}
10888
10889function flushImmediateQueue() {
10890 if (immediateQueueCallbackNode !== null) {
10891 Scheduler_cancelCallback(immediateQueueCallbackNode);
10892 }
10893 flushImmediateQueueImpl();
10894}
10895
10896function flushImmediateQueueImpl() {
10897 if (!isFlushingImmediate && immediateQueue !== null) {
10898 // Prevent re-entrancy.
10899 isFlushingImmediate = true;
10900 var i = 0;
10901 try {
10902 var _isSync = true;
10903 for (; i < immediateQueue.length; i++) {
10904 var callback = immediateQueue[i];
10905 do {
10906 callback = callback(_isSync);
10907 } while (callback !== null);
10908 }
10909 immediateQueue = null;
10910 } catch (error) {
10911 // If something throws, leave the remaining callbacks on the queue.
10912 if (immediateQueue !== null) {
10913 immediateQueue = immediateQueue.slice(i + 1);
10914 }
10915 // Resume flushing in the next tick
10916 Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushImmediateQueue);
10917 throw error;
10918 } finally {
10919 isFlushingImmediate = false;
10920 }
10921 }
10922}
10923
10924var NoWork = 0;
10925var Never = 1;
10926var Sync = maxSigned31BitInt;
10927
10928var UNIT_SIZE = 10;
10929var MAGIC_NUMBER_OFFSET = maxSigned31BitInt - 1;
10930
10931// 1 unit of expiration time represents 10ms.
10932function msToExpirationTime(ms) {
10933 // Always add an offset so that we don't clash with the magic number for NoWork.
10934 return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
10935}
10936
10937function expirationTimeToMs(expirationTime) {
10938 return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
10939}
10940
10941function ceiling(num, precision) {
10942 return ((num / precision | 0) + 1) * precision;
10943}
10944
10945function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
10946 return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
10947}
10948
10949// TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update
10950// the names to reflect.
10951var LOW_PRIORITY_EXPIRATION = 5000;
10952var LOW_PRIORITY_BATCH_SIZE = 250;
10953
10954function computeAsyncExpiration(currentTime) {
10955 return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
10956}
10957
10958// We intentionally set a higher expiration time for interactive updates in
10959// dev than in production.
10960//
10961// If the main thread is being blocked so long that you hit the expiration,
10962// it's a problem that could be solved with better scheduling.
10963//
10964// People will be more likely to notice this and fix it with the long
10965// expiration time in development.
10966//
10967// In production we opt for better UX at the risk of masking scheduling
10968// problems, by expiring fast.
10969var HIGH_PRIORITY_EXPIRATION = 500;
10970var HIGH_PRIORITY_BATCH_SIZE = 100;
10971
10972function computeInteractiveExpiration(currentTime) {
10973 return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
10974}
10975
10976function inferPriorityFromExpirationTime(currentTime, expirationTime) {
10977 if (expirationTime === Sync) {
10978 return ImmediatePriority;
10979 }
10980 if (expirationTime === Never) {
10981 return IdlePriority;
10982 }
10983 var msUntil = msToExpirationTime(expirationTime) - msToExpirationTime(currentTime);
10984 if (msUntil <= 0) {
10985 return ImmediatePriority;
10986 }
10987 if (msUntil <= HIGH_PRIORITY_EXPIRATION) {
10988 return UserBlockingPriority;
10989 }
10990 if (msUntil <= LOW_PRIORITY_EXPIRATION) {
10991 return NormalPriority;
10992 }
10993
10994 // TODO: Handle LowPriority
10995
10996 // Assume anything lower has idle priority
10997 return IdlePriority;
10998}
10999
11000var NoContext = 0;
11001var ConcurrentMode = 1;
11002var StrictMode = 2;
11003var ProfileMode = 4;
11004
11005var hasBadMapPolyfill = void 0;
11006
11007{
11008 hasBadMapPolyfill = false;
11009 try {
11010 var nonExtensibleObject = Object.preventExtensions({});
11011 var testMap = new Map([[nonExtensibleObject, null]]);
11012 var testSet = new Set([nonExtensibleObject]);
11013 // This is necessary for Rollup to not consider these unused.
11014 // https://github.com/rollup/rollup/issues/1771
11015 // TODO: we can remove these if Rollup fixes the bug.
11016 testMap.set(0, 0);
11017 testSet.add(0);
11018 } catch (e) {
11019 // TODO: Consider warning about bad polyfills
11020 hasBadMapPolyfill = true;
11021 }
11022}
11023
11024// A Fiber is work on a Component that needs to be done or was done. There can
11025// be more than one per component.
11026
11027
11028var debugCounter = void 0;
11029
11030{
11031 debugCounter = 1;
11032}
11033
11034function FiberNode(tag, pendingProps, key, mode) {
11035 // Instance
11036 this.tag = tag;
11037 this.key = key;
11038 this.elementType = null;
11039 this.type = null;
11040 this.stateNode = null;
11041
11042 // Fiber
11043 this.return = null;
11044 this.child = null;
11045 this.sibling = null;
11046 this.index = 0;
11047
11048 this.ref = null;
11049
11050 this.pendingProps = pendingProps;
11051 this.memoizedProps = null;
11052 this.updateQueue = null;
11053 this.memoizedState = null;
11054 this.contextDependencies = null;
11055
11056 this.mode = mode;
11057
11058 // Effects
11059 this.effectTag = NoEffect;
11060 this.nextEffect = null;
11061
11062 this.firstEffect = null;
11063 this.lastEffect = null;
11064
11065 this.expirationTime = NoWork;
11066 this.childExpirationTime = NoWork;
11067
11068 this.alternate = null;
11069
11070 if (enableProfilerTimer) {
11071 // Note: The following is done to avoid a v8 performance cliff.
11072 //
11073 // Initializing the fields below to smis and later updating them with
11074 // double values will cause Fibers to end up having separate shapes.
11075 // This behavior/bug has something to do with Object.preventExtension().
11076 // Fortunately this only impacts DEV builds.
11077 // Unfortunately it makes React unusably slow for some applications.
11078 // To work around this, initialize the fields below with doubles.
11079 //
11080 // Learn more about this here:
11081 // https://github.com/facebook/react/issues/14365
11082 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
11083 this.actualDuration = Number.NaN;
11084 this.actualStartTime = Number.NaN;
11085 this.selfBaseDuration = Number.NaN;
11086 this.treeBaseDuration = Number.NaN;
11087
11088 // It's okay to replace the initial doubles with smis after initialization.
11089 // This won't trigger the performance cliff mentioned above,
11090 // and it simplifies other profiler code (including DevTools).
11091 this.actualDuration = 0;
11092 this.actualStartTime = -1;
11093 this.selfBaseDuration = 0;
11094 this.treeBaseDuration = 0;
11095 }
11096
11097 {
11098 this._debugID = debugCounter++;
11099 this._debugSource = null;
11100 this._debugOwner = null;
11101 this._debugIsCurrentlyTiming = false;
11102 this._debugHookTypes = null;
11103 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
11104 Object.preventExtensions(this);
11105 }
11106 }
11107}
11108
11109// This is a constructor function, rather than a POJO constructor, still
11110// please ensure we do the following:
11111// 1) Nobody should add any instance methods on this. Instance methods can be
11112// more difficult to predict when they get optimized and they are almost
11113// never inlined properly in static compilers.
11114// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
11115// always know when it is a fiber.
11116// 3) We might want to experiment with using numeric keys since they are easier
11117// to optimize in a non-JIT environment.
11118// 4) We can easily go from a constructor to a createFiber object literal if that
11119// is faster.
11120// 5) It should be easy to port this to a C struct and keep a C implementation
11121// compatible.
11122var createFiber = function (tag, pendingProps, key, mode) {
11123 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
11124 return new FiberNode(tag, pendingProps, key, mode);
11125};
11126
11127function shouldConstruct(Component) {
11128 var prototype = Component.prototype;
11129 return !!(prototype && prototype.isReactComponent);
11130}
11131
11132function isSimpleFunctionComponent(type) {
11133 return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
11134}
11135
11136function resolveLazyComponentTag(Component) {
11137 if (typeof Component === 'function') {
11138 return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
11139 } else if (Component !== undefined && Component !== null) {
11140 var $$typeof = Component.$$typeof;
11141 if ($$typeof === REACT_FORWARD_REF_TYPE) {
11142 return ForwardRef;
11143 }
11144 if ($$typeof === REACT_MEMO_TYPE) {
11145 return MemoComponent;
11146 }
11147 }
11148 return IndeterminateComponent;
11149}
11150
11151// This is used to create an alternate fiber to do work on.
11152function createWorkInProgress(current, pendingProps, expirationTime) {
11153 var workInProgress = current.alternate;
11154 if (workInProgress === null) {
11155 // We use a double buffering pooling technique because we know that we'll
11156 // only ever need at most two versions of a tree. We pool the "other" unused
11157 // node that we're free to reuse. This is lazily created to avoid allocating
11158 // extra objects for things that are never updated. It also allow us to
11159 // reclaim the extra memory if needed.
11160 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
11161 workInProgress.elementType = current.elementType;
11162 workInProgress.type = current.type;
11163 workInProgress.stateNode = current.stateNode;
11164
11165 {
11166 // DEV-only fields
11167 workInProgress._debugID = current._debugID;
11168 workInProgress._debugSource = current._debugSource;
11169 workInProgress._debugOwner = current._debugOwner;
11170 workInProgress._debugHookTypes = current._debugHookTypes;
11171 }
11172
11173 workInProgress.alternate = current;
11174 current.alternate = workInProgress;
11175 } else {
11176 workInProgress.pendingProps = pendingProps;
11177
11178 // We already have an alternate.
11179 // Reset the effect tag.
11180 workInProgress.effectTag = NoEffect;
11181
11182 // The effect list is no longer valid.
11183 workInProgress.nextEffect = null;
11184 workInProgress.firstEffect = null;
11185 workInProgress.lastEffect = null;
11186
11187 if (enableProfilerTimer) {
11188 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
11189 // This prevents time from endlessly accumulating in new commits.
11190 // This has the downside of resetting values for different priority renders,
11191 // But works for yielding (the common case) and should support resuming.
11192 workInProgress.actualDuration = 0;
11193 workInProgress.actualStartTime = -1;
11194 }
11195 }
11196
11197 workInProgress.childExpirationTime = current.childExpirationTime;
11198 workInProgress.expirationTime = current.expirationTime;
11199
11200 workInProgress.child = current.child;
11201 workInProgress.memoizedProps = current.memoizedProps;
11202 workInProgress.memoizedState = current.memoizedState;
11203 workInProgress.updateQueue = current.updateQueue;
11204 workInProgress.contextDependencies = current.contextDependencies;
11205
11206 // These will be overridden during the parent's reconciliation
11207 workInProgress.sibling = current.sibling;
11208 workInProgress.index = current.index;
11209 workInProgress.ref = current.ref;
11210
11211 if (enableProfilerTimer) {
11212 workInProgress.selfBaseDuration = current.selfBaseDuration;
11213 workInProgress.treeBaseDuration = current.treeBaseDuration;
11214 }
11215
11216 return workInProgress;
11217}
11218
11219function createHostRootFiber(isConcurrent) {
11220 var mode = isConcurrent ? ConcurrentMode | StrictMode : NoContext;
11221
11222 if (enableProfilerTimer && isDevToolsPresent) {
11223 // Always collect profile timings when DevTools are present.
11224 // This enables DevTools to start capturing timing at any point–
11225 // Without some nodes in the tree having empty base times.
11226 mode |= ProfileMode;
11227 }
11228
11229 return createFiber(HostRoot, null, null, mode);
11230}
11231
11232function createFiberFromTypeAndProps(type, // React$ElementType
11233key, pendingProps, owner, mode, expirationTime) {
11234 var fiber = void 0;
11235
11236 var fiberTag = IndeterminateComponent;
11237 // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
11238 var resolvedType = type;
11239 if (typeof type === 'function') {
11240 if (shouldConstruct(type)) {
11241 fiberTag = ClassComponent;
11242 }
11243 } else if (typeof type === 'string') {
11244 fiberTag = HostComponent;
11245 } else {
11246 getTag: switch (type) {
11247 case REACT_FRAGMENT_TYPE:
11248 return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
11249 case REACT_CONCURRENT_MODE_TYPE:
11250 return createFiberFromMode(pendingProps, mode | ConcurrentMode | StrictMode, expirationTime, key);
11251 case REACT_STRICT_MODE_TYPE:
11252 return createFiberFromMode(pendingProps, mode | StrictMode, expirationTime, key);
11253 case REACT_PROFILER_TYPE:
11254 return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
11255 case REACT_SUSPENSE_TYPE:
11256 return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
11257 default:
11258 {
11259 if (typeof type === 'object' && type !== null) {
11260 switch (type.$$typeof) {
11261 case REACT_PROVIDER_TYPE:
11262 fiberTag = ContextProvider;
11263 break getTag;
11264 case REACT_CONTEXT_TYPE:
11265 // This is a consumer
11266 fiberTag = ContextConsumer;
11267 break getTag;
11268 case REACT_FORWARD_REF_TYPE:
11269 fiberTag = ForwardRef;
11270 break getTag;
11271 case REACT_MEMO_TYPE:
11272 fiberTag = MemoComponent;
11273 break getTag;
11274 case REACT_LAZY_TYPE:
11275 fiberTag = LazyComponent;
11276 resolvedType = null;
11277 break getTag;
11278 case REACT_EVENT_COMPONENT_TYPE:
11279 if (enableEventAPI) {
11280 return createFiberFromEventComponent(type, pendingProps, mode, expirationTime, key);
11281 }
11282 break;
11283 case REACT_EVENT_TARGET_TYPE:
11284 if (enableEventAPI) {
11285 return createFiberFromEventTarget(type, pendingProps, mode, expirationTime, key);
11286 }
11287 break;
11288 }
11289 }
11290 var info = '';
11291 {
11292 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
11293 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.';
11294 }
11295 var ownerName = owner ? getComponentName(owner.type) : null;
11296 if (ownerName) {
11297 info += '\n\nCheck the render method of `' + ownerName + '`.';
11298 }
11299 }
11300 (function () {
11301 {
11302 {
11303 throw ReactError('Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: ' + (type == null ? type : typeof type) + '.' + info);
11304 }
11305 }
11306 })();
11307 }
11308 }
11309 }
11310
11311 fiber = createFiber(fiberTag, pendingProps, key, mode);
11312 fiber.elementType = type;
11313 fiber.type = resolvedType;
11314 fiber.expirationTime = expirationTime;
11315
11316 return fiber;
11317}
11318
11319function createFiberFromElement(element, mode, expirationTime) {
11320 var owner = null;
11321 {
11322 owner = element._owner;
11323 }
11324 var type = element.type;
11325 var key = element.key;
11326 var pendingProps = element.props;
11327 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
11328 {
11329 fiber._debugSource = element._source;
11330 fiber._debugOwner = element._owner;
11331 }
11332 return fiber;
11333}
11334
11335function createFiberFromFragment(elements, mode, expirationTime, key) {
11336 var fiber = createFiber(Fragment, elements, key, mode);
11337 fiber.expirationTime = expirationTime;
11338 return fiber;
11339}
11340
11341function createFiberFromEventComponent(eventComponent, pendingProps, mode, expirationTime, key) {
11342 var fiber = createFiber(EventComponent, pendingProps, key, mode);
11343 fiber.elementType = eventComponent;
11344 fiber.type = eventComponent;
11345 fiber.stateNode = {
11346 props: pendingProps,
11347 state: null
11348 };
11349 fiber.expirationTime = expirationTime;
11350 return fiber;
11351}
11352
11353function createFiberFromEventTarget(eventTarget, pendingProps, mode, expirationTime, key) {
11354 var fiber = createFiber(EventTarget, pendingProps, key, mode);
11355 fiber.elementType = eventTarget;
11356 fiber.type = eventTarget;
11357 fiber.expirationTime = expirationTime;
11358 return fiber;
11359}
11360
11361function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
11362 {
11363 if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
11364 warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
11365 }
11366 }
11367
11368 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
11369 // TODO: The Profiler fiber shouldn't have a type. It has a tag.
11370 fiber.elementType = REACT_PROFILER_TYPE;
11371 fiber.type = REACT_PROFILER_TYPE;
11372 fiber.expirationTime = expirationTime;
11373
11374 return fiber;
11375}
11376
11377function createFiberFromMode(pendingProps, mode, expirationTime, key) {
11378 var fiber = createFiber(Mode, pendingProps, key, mode);
11379
11380 // TODO: The Mode fiber shouldn't have a type. It has a tag.
11381 var type = (mode & ConcurrentMode) === NoContext ? REACT_STRICT_MODE_TYPE : REACT_CONCURRENT_MODE_TYPE;
11382 fiber.elementType = type;
11383 fiber.type = type;
11384
11385 fiber.expirationTime = expirationTime;
11386 return fiber;
11387}
11388
11389function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
11390 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
11391
11392 // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
11393 var type = REACT_SUSPENSE_TYPE;
11394 fiber.elementType = type;
11395 fiber.type = type;
11396
11397 fiber.expirationTime = expirationTime;
11398 return fiber;
11399}
11400
11401function createFiberFromText(content, mode, expirationTime) {
11402 var fiber = createFiber(HostText, content, null, mode);
11403 fiber.expirationTime = expirationTime;
11404 return fiber;
11405}
11406
11407function createFiberFromHostInstanceForDeletion() {
11408 var fiber = createFiber(HostComponent, null, null, NoContext);
11409 // TODO: These should not need a type.
11410 fiber.elementType = 'DELETED';
11411 fiber.type = 'DELETED';
11412 return fiber;
11413}
11414
11415function createFiberFromPortal(portal, mode, expirationTime) {
11416 var pendingProps = portal.children !== null ? portal.children : [];
11417 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
11418 fiber.expirationTime = expirationTime;
11419 fiber.stateNode = {
11420 containerInfo: portal.containerInfo,
11421 pendingChildren: null, // Used by persistent updates
11422 implementation: portal.implementation
11423 };
11424 return fiber;
11425}
11426
11427// Used for stashing WIP properties to replay failed work in DEV.
11428function assignFiberPropertiesInDEV(target, source) {
11429 if (target === null) {
11430 // This Fiber's initial properties will always be overwritten.
11431 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
11432 target = createFiber(IndeterminateComponent, null, null, NoContext);
11433 }
11434
11435 // This is intentionally written as a list of all properties.
11436 // We tried to use Object.assign() instead but this is called in
11437 // the hottest path, and Object.assign() was too slow:
11438 // https://github.com/facebook/react/issues/12502
11439 // This code is DEV-only so size is not a concern.
11440
11441 target.tag = source.tag;
11442 target.key = source.key;
11443 target.elementType = source.elementType;
11444 target.type = source.type;
11445 target.stateNode = source.stateNode;
11446 target.return = source.return;
11447 target.child = source.child;
11448 target.sibling = source.sibling;
11449 target.index = source.index;
11450 target.ref = source.ref;
11451 target.pendingProps = source.pendingProps;
11452 target.memoizedProps = source.memoizedProps;
11453 target.updateQueue = source.updateQueue;
11454 target.memoizedState = source.memoizedState;
11455 target.contextDependencies = source.contextDependencies;
11456 target.mode = source.mode;
11457 target.effectTag = source.effectTag;
11458 target.nextEffect = source.nextEffect;
11459 target.firstEffect = source.firstEffect;
11460 target.lastEffect = source.lastEffect;
11461 target.expirationTime = source.expirationTime;
11462 target.childExpirationTime = source.childExpirationTime;
11463 target.alternate = source.alternate;
11464 if (enableProfilerTimer) {
11465 target.actualDuration = source.actualDuration;
11466 target.actualStartTime = source.actualStartTime;
11467 target.selfBaseDuration = source.selfBaseDuration;
11468 target.treeBaseDuration = source.treeBaseDuration;
11469 }
11470 target._debugID = source._debugID;
11471 target._debugSource = source._debugSource;
11472 target._debugOwner = source._debugOwner;
11473 target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
11474 target._debugHookTypes = source._debugHookTypes;
11475 return target;
11476}
11477
11478var ReactInternals$2 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
11479
11480var _ReactInternals$Sched$1 = ReactInternals$2.SchedulerTracing;
11481var __interactionsRef = _ReactInternals$Sched$1.__interactionsRef;
11482var __subscriberRef = _ReactInternals$Sched$1.__subscriberRef;
11483var unstable_clear = _ReactInternals$Sched$1.unstable_clear;
11484var unstable_getCurrent = _ReactInternals$Sched$1.unstable_getCurrent;
11485var unstable_getThreadID = _ReactInternals$Sched$1.unstable_getThreadID;
11486var unstable_subscribe = _ReactInternals$Sched$1.unstable_subscribe;
11487var unstable_trace = _ReactInternals$Sched$1.unstable_trace;
11488var unstable_unsubscribe = _ReactInternals$Sched$1.unstable_unsubscribe;
11489var unstable_wrap = _ReactInternals$Sched$1.unstable_wrap;
11490
11491// TODO: This should be lifted into the renderer.
11492
11493
11494// The following attributes are only used by interaction tracing builds.
11495// They enable interactions to be associated with their async work,
11496// And expose interaction metadata to the React DevTools Profiler plugin.
11497// Note that these attributes are only defined when the enableSchedulerTracing flag is enabled.
11498
11499
11500// Exported FiberRoot type includes all properties,
11501// To avoid requiring potentially error-prone :any casts throughout the project.
11502// Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true).
11503// The types are defined separately within this file to ensure they stay in sync.
11504// (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.)
11505
11506
11507function FiberRootNode(containerInfo, hydrate) {
11508 this.current = null;
11509 this.containerInfo = containerInfo;
11510 this.pendingChildren = null;
11511 this.pingCache = null;
11512 this.pendingCommitExpirationTime = NoWork;
11513 this.finishedWork = null;
11514 this.timeoutHandle = noTimeout;
11515 this.context = null;
11516 this.pendingContext = null;
11517 this.hydrate = hydrate;
11518 this.firstBatch = null;
11519
11520 if (enableNewScheduler) {
11521 this.callbackNode = null;
11522 this.callbackExpirationTime = NoWork;
11523 this.firstPendingTime = NoWork;
11524 this.lastPendingTime = NoWork;
11525 this.pingTime = NoWork;
11526 } else {
11527 this.earliestPendingTime = NoWork;
11528 this.latestPendingTime = NoWork;
11529 this.earliestSuspendedTime = NoWork;
11530 this.latestSuspendedTime = NoWork;
11531 this.latestPingedTime = NoWork;
11532 this.didError = false;
11533 this.nextExpirationTimeToWorkOn = NoWork;
11534 this.expirationTime = NoWork;
11535 this.nextScheduledRoot = null;
11536 }
11537
11538 if (enableSchedulerTracing) {
11539 this.interactionThreadID = unstable_getThreadID();
11540 this.memoizedInteractions = new Set();
11541 this.pendingInteractionMap = new Map();
11542 }
11543}
11544
11545function createFiberRoot(containerInfo, isConcurrent, hydrate) {
11546 var root = new FiberRootNode(containerInfo, hydrate);
11547
11548 // Cyclic construction. This cheats the type system right now because
11549 // stateNode is any.
11550 var uninitializedFiber = createHostRootFiber(isConcurrent);
11551 root.current = uninitializedFiber;
11552 uninitializedFiber.stateNode = root;
11553
11554 return root;
11555}
11556
11557/**
11558 * Forked from fbjs/warning:
11559 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
11560 *
11561 * Only change is we use console.warn instead of console.error,
11562 * and do nothing when 'console' is not supported.
11563 * This really simplifies the code.
11564 * ---
11565 * Similar to invariant but only logs a warning if the condition is not met.
11566 * This can be used to log issues in development environments in critical
11567 * paths. Removing the logging code for production environments will keep the
11568 * same logic and follow the same code paths.
11569 */
11570
11571var lowPriorityWarning = function () {};
11572
11573{
11574 var printWarning$1 = function (format) {
11575 for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
11576 args[_key - 1] = arguments[_key];
11577 }
11578
11579 var argIndex = 0;
11580 var message = 'Warning: ' + format.replace(/%s/g, function () {
11581 return args[argIndex++];
11582 });
11583 if (typeof console !== 'undefined') {
11584 console.warn(message);
11585 }
11586 try {
11587 // --- Welcome to debugging React ---
11588 // This error was thrown as a convenience so that you can use this stack
11589 // to find the callsite that caused this warning to fire.
11590 throw new Error(message);
11591 } catch (x) {}
11592 };
11593
11594 lowPriorityWarning = function (condition, format) {
11595 if (format === undefined) {
11596 throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
11597 }
11598 if (!condition) {
11599 for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
11600 args[_key2 - 2] = arguments[_key2];
11601 }
11602
11603 printWarning$1.apply(undefined, [format].concat(args));
11604 }
11605 };
11606}
11607
11608var lowPriorityWarning$1 = lowPriorityWarning;
11609
11610var ReactStrictModeWarnings = {
11611 discardPendingWarnings: function () {},
11612 flushPendingDeprecationWarnings: function () {},
11613 flushPendingUnsafeLifecycleWarnings: function () {},
11614 recordDeprecationWarnings: function (fiber, instance) {},
11615 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
11616 recordLegacyContextWarning: function (fiber, instance) {},
11617 flushLegacyContextWarning: function () {}
11618};
11619
11620{
11621 var LIFECYCLE_SUGGESTIONS = {
11622 UNSAFE_componentWillMount: 'componentDidMount',
11623 UNSAFE_componentWillReceiveProps: 'static getDerivedStateFromProps',
11624 UNSAFE_componentWillUpdate: 'componentDidUpdate'
11625 };
11626
11627 var pendingComponentWillMountWarnings = [];
11628 var pendingComponentWillReceivePropsWarnings = [];
11629 var pendingComponentWillUpdateWarnings = [];
11630 var pendingUnsafeLifecycleWarnings = new Map();
11631 var pendingLegacyContextWarning = new Map();
11632
11633 // Tracks components we have already warned about.
11634 var didWarnAboutDeprecatedLifecycles = new Set();
11635 var didWarnAboutUnsafeLifecycles = new Set();
11636 var didWarnAboutLegacyContext = new Set();
11637
11638 var setToSortedString = function (set) {
11639 var array = [];
11640 set.forEach(function (value) {
11641 array.push(value);
11642 });
11643 return array.sort().join(', ');
11644 };
11645
11646 ReactStrictModeWarnings.discardPendingWarnings = function () {
11647 pendingComponentWillMountWarnings = [];
11648 pendingComponentWillReceivePropsWarnings = [];
11649 pendingComponentWillUpdateWarnings = [];
11650 pendingUnsafeLifecycleWarnings = new Map();
11651 pendingLegacyContextWarning = new Map();
11652 };
11653
11654 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
11655 pendingUnsafeLifecycleWarnings.forEach(function (lifecycleWarningsMap, strictRoot) {
11656 var lifecyclesWarningMessages = [];
11657
11658 Object.keys(lifecycleWarningsMap).forEach(function (lifecycle) {
11659 var lifecycleWarnings = lifecycleWarningsMap[lifecycle];
11660 if (lifecycleWarnings.length > 0) {
11661 var componentNames = new Set();
11662 lifecycleWarnings.forEach(function (fiber) {
11663 componentNames.add(getComponentName(fiber.type) || 'Component');
11664 didWarnAboutUnsafeLifecycles.add(fiber.type);
11665 });
11666
11667 var formatted = lifecycle.replace('UNSAFE_', '');
11668 var suggestion = LIFECYCLE_SUGGESTIONS[lifecycle];
11669 var sortedComponentNames = setToSortedString(componentNames);
11670
11671 lifecyclesWarningMessages.push(formatted + ': Please update the following components to use ' + (suggestion + ' instead: ' + sortedComponentNames));
11672 }
11673 });
11674
11675 if (lifecyclesWarningMessages.length > 0) {
11676 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
11677
11678 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'));
11679 }
11680 });
11681
11682 pendingUnsafeLifecycleWarnings = new Map();
11683 };
11684
11685 var findStrictRoot = function (fiber) {
11686 var maybeStrictRoot = null;
11687
11688 var node = fiber;
11689 while (node !== null) {
11690 if (node.mode & StrictMode) {
11691 maybeStrictRoot = node;
11692 }
11693 node = node.return;
11694 }
11695
11696 return maybeStrictRoot;
11697 };
11698
11699 ReactStrictModeWarnings.flushPendingDeprecationWarnings = function () {
11700 if (pendingComponentWillMountWarnings.length > 0) {
11701 var uniqueNames = new Set();
11702 pendingComponentWillMountWarnings.forEach(function (fiber) {
11703 uniqueNames.add(getComponentName(fiber.type) || 'Component');
11704 didWarnAboutDeprecatedLifecycles.add(fiber.type);
11705 });
11706
11707 var sortedNames = setToSortedString(uniqueNames);
11708
11709 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);
11710
11711 pendingComponentWillMountWarnings = [];
11712 }
11713
11714 if (pendingComponentWillReceivePropsWarnings.length > 0) {
11715 var _uniqueNames = new Set();
11716 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
11717 _uniqueNames.add(getComponentName(fiber.type) || 'Component');
11718 didWarnAboutDeprecatedLifecycles.add(fiber.type);
11719 });
11720
11721 var _sortedNames = setToSortedString(_uniqueNames);
11722
11723 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);
11724
11725 pendingComponentWillReceivePropsWarnings = [];
11726 }
11727
11728 if (pendingComponentWillUpdateWarnings.length > 0) {
11729 var _uniqueNames2 = new Set();
11730 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
11731 _uniqueNames2.add(getComponentName(fiber.type) || 'Component');
11732 didWarnAboutDeprecatedLifecycles.add(fiber.type);
11733 });
11734
11735 var _sortedNames2 = setToSortedString(_uniqueNames2);
11736
11737 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);
11738
11739 pendingComponentWillUpdateWarnings = [];
11740 }
11741 };
11742
11743 ReactStrictModeWarnings.recordDeprecationWarnings = function (fiber, instance) {
11744 // Dedup strategy: Warn once per component.
11745 if (didWarnAboutDeprecatedLifecycles.has(fiber.type)) {
11746 return;
11747 }
11748
11749 // Don't warn about react-lifecycles-compat polyfilled components.
11750 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
11751 pendingComponentWillMountWarnings.push(fiber);
11752 }
11753 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
11754 pendingComponentWillReceivePropsWarnings.push(fiber);
11755 }
11756 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
11757 pendingComponentWillUpdateWarnings.push(fiber);
11758 }
11759 };
11760
11761 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
11762 var strictRoot = findStrictRoot(fiber);
11763 if (strictRoot === null) {
11764 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.');
11765 return;
11766 }
11767
11768 // Dedup strategy: Warn once per component.
11769 // This is difficult to track any other way since component names
11770 // are often vague and are likely to collide between 3rd party libraries.
11771 // An expand property is probably okay to use here since it's DEV-only,
11772 // and will only be set in the event of serious warnings.
11773 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
11774 return;
11775 }
11776
11777 var warningsForRoot = void 0;
11778 if (!pendingUnsafeLifecycleWarnings.has(strictRoot)) {
11779 warningsForRoot = {
11780 UNSAFE_componentWillMount: [],
11781 UNSAFE_componentWillReceiveProps: [],
11782 UNSAFE_componentWillUpdate: []
11783 };
11784
11785 pendingUnsafeLifecycleWarnings.set(strictRoot, warningsForRoot);
11786 } else {
11787 warningsForRoot = pendingUnsafeLifecycleWarnings.get(strictRoot);
11788 }
11789
11790 var unsafeLifecycles = [];
11791 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillMount === 'function') {
11792 unsafeLifecycles.push('UNSAFE_componentWillMount');
11793 }
11794 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
11795 unsafeLifecycles.push('UNSAFE_componentWillReceiveProps');
11796 }
11797 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillUpdate === 'function') {
11798 unsafeLifecycles.push('UNSAFE_componentWillUpdate');
11799 }
11800
11801 if (unsafeLifecycles.length > 0) {
11802 unsafeLifecycles.forEach(function (lifecycle) {
11803 warningsForRoot[lifecycle].push(fiber);
11804 });
11805 }
11806 };
11807
11808 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
11809 var strictRoot = findStrictRoot(fiber);
11810 if (strictRoot === null) {
11811 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.');
11812 return;
11813 }
11814
11815 // Dedup strategy: Warn once per component.
11816 if (didWarnAboutLegacyContext.has(fiber.type)) {
11817 return;
11818 }
11819
11820 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
11821
11822 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
11823 if (warningsForRoot === undefined) {
11824 warningsForRoot = [];
11825 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
11826 }
11827 warningsForRoot.push(fiber);
11828 }
11829 };
11830
11831 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
11832 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
11833 var uniqueNames = new Set();
11834 fiberArray.forEach(function (fiber) {
11835 uniqueNames.add(getComponentName(fiber.type) || 'Component');
11836 didWarnAboutLegacyContext.add(fiber.type);
11837 });
11838
11839 var sortedNames = setToSortedString(uniqueNames);
11840 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
11841
11842 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);
11843 });
11844 };
11845}
11846
11847// This lets us hook into Fiber to debug what it's doing.
11848// See https://github.com/facebook/react/pull/8033.
11849// This is not part of the public API, not even for React DevTools.
11850// You may only inject a debugTool if you work on React Fiber itself.
11851var ReactFiberInstrumentation = {
11852 debugTool: null
11853};
11854
11855var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
11856
11857// TODO: Offscreen updates should never suspend. However, a promise that
11858// suspended inside an offscreen subtree should be able to ping at the priority
11859// of the outer render.
11860
11861function markPendingPriorityLevel(root, expirationTime) {
11862 // If there's a gap between completing a failed root and retrying it,
11863 // additional updates may be scheduled. Clear `didError`, in case the update
11864 // is sufficient to fix the error.
11865 root.didError = false;
11866
11867 // Update the latest and earliest pending times
11868 var earliestPendingTime = root.earliestPendingTime;
11869 if (earliestPendingTime === NoWork) {
11870 // No other pending updates.
11871 root.earliestPendingTime = root.latestPendingTime = expirationTime;
11872 } else {
11873 if (earliestPendingTime < expirationTime) {
11874 // This is the earliest pending update.
11875 root.earliestPendingTime = expirationTime;
11876 } else {
11877 var latestPendingTime = root.latestPendingTime;
11878 if (latestPendingTime > expirationTime) {
11879 // This is the latest pending update
11880 root.latestPendingTime = expirationTime;
11881 }
11882 }
11883 }
11884 findNextExpirationTimeToWorkOn(expirationTime, root);
11885}
11886
11887function markCommittedPriorityLevels(root, earliestRemainingTime) {
11888 root.didError = false;
11889
11890 if (earliestRemainingTime === NoWork) {
11891 // Fast path. There's no remaining work. Clear everything.
11892 root.earliestPendingTime = NoWork;
11893 root.latestPendingTime = NoWork;
11894 root.earliestSuspendedTime = NoWork;
11895 root.latestSuspendedTime = NoWork;
11896 root.latestPingedTime = NoWork;
11897 findNextExpirationTimeToWorkOn(NoWork, root);
11898 return;
11899 }
11900
11901 if (earliestRemainingTime < root.latestPingedTime) {
11902 root.latestPingedTime = NoWork;
11903 }
11904
11905 // Let's see if the previous latest known pending level was just flushed.
11906 var latestPendingTime = root.latestPendingTime;
11907 if (latestPendingTime !== NoWork) {
11908 if (latestPendingTime > earliestRemainingTime) {
11909 // We've flushed all the known pending levels.
11910 root.earliestPendingTime = root.latestPendingTime = NoWork;
11911 } else {
11912 var earliestPendingTime = root.earliestPendingTime;
11913 if (earliestPendingTime > earliestRemainingTime) {
11914 // We've flushed the earliest known pending level. Set this to the
11915 // latest pending time.
11916 root.earliestPendingTime = root.latestPendingTime;
11917 }
11918 }
11919 }
11920
11921 // Now let's handle the earliest remaining level in the whole tree. We need to
11922 // decide whether to treat it as a pending level or as suspended. Check
11923 // it falls within the range of known suspended levels.
11924
11925 var earliestSuspendedTime = root.earliestSuspendedTime;
11926 if (earliestSuspendedTime === NoWork) {
11927 // There's no suspended work. Treat the earliest remaining level as a
11928 // pending level.
11929 markPendingPriorityLevel(root, earliestRemainingTime);
11930 findNextExpirationTimeToWorkOn(NoWork, root);
11931 return;
11932 }
11933
11934 var latestSuspendedTime = root.latestSuspendedTime;
11935 if (earliestRemainingTime < latestSuspendedTime) {
11936 // The earliest remaining level is later than all the suspended work. That
11937 // means we've flushed all the suspended work.
11938 root.earliestSuspendedTime = NoWork;
11939 root.latestSuspendedTime = NoWork;
11940 root.latestPingedTime = NoWork;
11941
11942 // There's no suspended work. Treat the earliest remaining level as a
11943 // pending level.
11944 markPendingPriorityLevel(root, earliestRemainingTime);
11945 findNextExpirationTimeToWorkOn(NoWork, root);
11946 return;
11947 }
11948
11949 if (earliestRemainingTime > earliestSuspendedTime) {
11950 // The earliest remaining time is earlier than all the suspended work.
11951 // Treat it as a pending update.
11952 markPendingPriorityLevel(root, earliestRemainingTime);
11953 findNextExpirationTimeToWorkOn(NoWork, root);
11954 return;
11955 }
11956
11957 // The earliest remaining time falls within the range of known suspended
11958 // levels. We should treat this as suspended work.
11959 findNextExpirationTimeToWorkOn(NoWork, root);
11960}
11961
11962function hasLowerPriorityWork(root, erroredExpirationTime) {
11963 var latestPendingTime = root.latestPendingTime;
11964 var latestSuspendedTime = root.latestSuspendedTime;
11965 var latestPingedTime = root.latestPingedTime;
11966 return latestPendingTime !== NoWork && latestPendingTime < erroredExpirationTime || latestSuspendedTime !== NoWork && latestSuspendedTime < erroredExpirationTime || latestPingedTime !== NoWork && latestPingedTime < erroredExpirationTime;
11967}
11968
11969function isPriorityLevelSuspended(root, expirationTime) {
11970 var earliestSuspendedTime = root.earliestSuspendedTime;
11971 var latestSuspendedTime = root.latestSuspendedTime;
11972 return earliestSuspendedTime !== NoWork && expirationTime <= earliestSuspendedTime && expirationTime >= latestSuspendedTime;
11973}
11974
11975function markSuspendedPriorityLevel(root, suspendedTime) {
11976 root.didError = false;
11977 clearPing(root, suspendedTime);
11978
11979 // First, check the known pending levels and update them if needed.
11980 var earliestPendingTime = root.earliestPendingTime;
11981 var latestPendingTime = root.latestPendingTime;
11982 if (earliestPendingTime === suspendedTime) {
11983 if (latestPendingTime === suspendedTime) {
11984 // Both known pending levels were suspended. Clear them.
11985 root.earliestPendingTime = root.latestPendingTime = NoWork;
11986 } else {
11987 // The earliest pending level was suspended. Clear by setting it to the
11988 // latest pending level.
11989 root.earliestPendingTime = latestPendingTime;
11990 }
11991 } else if (latestPendingTime === suspendedTime) {
11992 // The latest pending level was suspended. Clear by setting it to the
11993 // latest pending level.
11994 root.latestPendingTime = earliestPendingTime;
11995 }
11996
11997 // Finally, update the known suspended levels.
11998 var earliestSuspendedTime = root.earliestSuspendedTime;
11999 var latestSuspendedTime = root.latestSuspendedTime;
12000 if (earliestSuspendedTime === NoWork) {
12001 // No other suspended levels.
12002 root.earliestSuspendedTime = root.latestSuspendedTime = suspendedTime;
12003 } else {
12004 if (earliestSuspendedTime < suspendedTime) {
12005 // This is the earliest suspended level.
12006 root.earliestSuspendedTime = suspendedTime;
12007 } else if (latestSuspendedTime > suspendedTime) {
12008 // This is the latest suspended level
12009 root.latestSuspendedTime = suspendedTime;
12010 }
12011 }
12012
12013 findNextExpirationTimeToWorkOn(suspendedTime, root);
12014}
12015
12016function markPingedPriorityLevel(root, pingedTime) {
12017 root.didError = false;
12018
12019 // TODO: When we add back resuming, we need to ensure the progressed work
12020 // is thrown out and not reused during the restarted render. One way to
12021 // invalidate the progressed work is to restart at expirationTime + 1.
12022 var latestPingedTime = root.latestPingedTime;
12023 if (latestPingedTime === NoWork || latestPingedTime > pingedTime) {
12024 root.latestPingedTime = pingedTime;
12025 }
12026 findNextExpirationTimeToWorkOn(pingedTime, root);
12027}
12028
12029function clearPing(root, completedTime) {
12030 var latestPingedTime = root.latestPingedTime;
12031 if (latestPingedTime >= completedTime) {
12032 root.latestPingedTime = NoWork;
12033 }
12034}
12035
12036function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) {
12037 var earliestExpirationTime = renderExpirationTime;
12038
12039 var earliestPendingTime = root.earliestPendingTime;
12040 var earliestSuspendedTime = root.earliestSuspendedTime;
12041 if (earliestPendingTime > earliestExpirationTime) {
12042 earliestExpirationTime = earliestPendingTime;
12043 }
12044 if (earliestSuspendedTime > earliestExpirationTime) {
12045 earliestExpirationTime = earliestSuspendedTime;
12046 }
12047 return earliestExpirationTime;
12048}
12049
12050function didExpireAtExpirationTime(root, currentTime) {
12051 var expirationTime = root.expirationTime;
12052 if (expirationTime !== NoWork && currentTime <= expirationTime) {
12053 // The root has expired. Flush all work up to the current time.
12054 root.nextExpirationTimeToWorkOn = currentTime;
12055 }
12056}
12057
12058function findNextExpirationTimeToWorkOn(completedExpirationTime, root) {
12059 var earliestSuspendedTime = root.earliestSuspendedTime;
12060 var latestSuspendedTime = root.latestSuspendedTime;
12061 var earliestPendingTime = root.earliestPendingTime;
12062 var latestPingedTime = root.latestPingedTime;
12063
12064 // Work on the earliest pending time. Failing that, work on the latest
12065 // pinged time.
12066 var nextExpirationTimeToWorkOn = earliestPendingTime !== NoWork ? earliestPendingTime : latestPingedTime;
12067
12068 // If there is no pending or pinged work, check if there's suspended work
12069 // that's lower priority than what we just completed.
12070 if (nextExpirationTimeToWorkOn === NoWork && (completedExpirationTime === NoWork || latestSuspendedTime < completedExpirationTime)) {
12071 // The lowest priority suspended work is the work most likely to be
12072 // committed next. Let's start rendering it again, so that if it times out,
12073 // it's ready to commit.
12074 nextExpirationTimeToWorkOn = latestSuspendedTime;
12075 }
12076
12077 var expirationTime = nextExpirationTimeToWorkOn;
12078 if (expirationTime !== NoWork && earliestSuspendedTime > expirationTime) {
12079 // Expire using the earliest known expiration time.
12080 expirationTime = earliestSuspendedTime;
12081 }
12082
12083 root.nextExpirationTimeToWorkOn = nextExpirationTimeToWorkOn;
12084 root.expirationTime = expirationTime;
12085}
12086
12087function resolveDefaultProps(Component, baseProps) {
12088 if (Component && Component.defaultProps) {
12089 // Resolve default props. Taken from ReactElement
12090 var props = _assign({}, baseProps);
12091 var defaultProps = Component.defaultProps;
12092 for (var propName in defaultProps) {
12093 if (props[propName] === undefined) {
12094 props[propName] = defaultProps[propName];
12095 }
12096 }
12097 return props;
12098 }
12099 return baseProps;
12100}
12101
12102function readLazyComponentType(lazyComponent) {
12103 var status = lazyComponent._status;
12104 var result = lazyComponent._result;
12105 switch (status) {
12106 case Resolved:
12107 {
12108 var Component = result;
12109 return Component;
12110 }
12111 case Rejected:
12112 {
12113 var error = result;
12114 throw error;
12115 }
12116 case Pending:
12117 {
12118 var thenable = result;
12119 throw thenable;
12120 }
12121 default:
12122 {
12123 lazyComponent._status = Pending;
12124 var ctor = lazyComponent._ctor;
12125 var _thenable = ctor();
12126 _thenable.then(function (moduleObject) {
12127 if (lazyComponent._status === Pending) {
12128 var defaultExport = moduleObject.default;
12129 {
12130 if (defaultExport === undefined) {
12131 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);
12132 }
12133 }
12134 lazyComponent._status = Resolved;
12135 lazyComponent._result = defaultExport;
12136 }
12137 }, function (error) {
12138 if (lazyComponent._status === Pending) {
12139 lazyComponent._status = Rejected;
12140 lazyComponent._result = error;
12141 }
12142 });
12143 // Handle synchronous thenables.
12144 switch (lazyComponent._status) {
12145 case Resolved:
12146 return lazyComponent._result;
12147 case Rejected:
12148 throw lazyComponent._result;
12149 }
12150 lazyComponent._result = _thenable;
12151 throw _thenable;
12152 }
12153 }
12154}
12155
12156var fakeInternalInstance = {};
12157var isArray$1 = Array.isArray;
12158
12159// React.Component uses a shared frozen object by default.
12160// We'll use it to determine whether we need to initialize legacy refs.
12161var emptyRefsObject = new React.Component().refs;
12162
12163var didWarnAboutStateAssignmentForComponent = void 0;
12164var didWarnAboutUninitializedState = void 0;
12165var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0;
12166var didWarnAboutLegacyLifecyclesAndDerivedState = void 0;
12167var didWarnAboutUndefinedDerivedState = void 0;
12168var warnOnUndefinedDerivedState = void 0;
12169var warnOnInvalidCallback$1 = void 0;
12170var didWarnAboutDirectlyAssigningPropsToState = void 0;
12171var didWarnAboutContextTypeAndContextTypes = void 0;
12172var didWarnAboutInvalidateContextType = void 0;
12173
12174{
12175 didWarnAboutStateAssignmentForComponent = new Set();
12176 didWarnAboutUninitializedState = new Set();
12177 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
12178 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
12179 didWarnAboutDirectlyAssigningPropsToState = new Set();
12180 didWarnAboutUndefinedDerivedState = new Set();
12181 didWarnAboutContextTypeAndContextTypes = new Set();
12182 didWarnAboutInvalidateContextType = new Set();
12183
12184 var didWarnOnInvalidCallback = new Set();
12185
12186 warnOnInvalidCallback$1 = function (callback, callerName) {
12187 if (callback === null || typeof callback === 'function') {
12188 return;
12189 }
12190 var key = callerName + '_' + callback;
12191 if (!didWarnOnInvalidCallback.has(key)) {
12192 didWarnOnInvalidCallback.add(key);
12193 warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
12194 }
12195 };
12196
12197 warnOnUndefinedDerivedState = function (type, partialState) {
12198 if (partialState === undefined) {
12199 var componentName = getComponentName(type) || 'Component';
12200 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
12201 didWarnAboutUndefinedDerivedState.add(componentName);
12202 warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
12203 }
12204 }
12205 };
12206
12207 // This is so gross but it's at least non-critical and can be removed if
12208 // it causes problems. This is meant to give a nicer error message for
12209 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
12210 // ...)) which otherwise throws a "_processChildContext is not a function"
12211 // exception.
12212 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
12213 enumerable: false,
12214 value: function () {
12215 (function () {
12216 {
12217 {
12218 throw ReactError('_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).');
12219 }
12220 }
12221 })();
12222 }
12223 });
12224 Object.freeze(fakeInternalInstance);
12225}
12226
12227function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
12228 var prevState = workInProgress.memoizedState;
12229
12230 {
12231 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
12232 // Invoke the function an extra time to help detect side-effects.
12233 getDerivedStateFromProps(nextProps, prevState);
12234 }
12235 }
12236
12237 var partialState = getDerivedStateFromProps(nextProps, prevState);
12238
12239 {
12240 warnOnUndefinedDerivedState(ctor, partialState);
12241 }
12242 // Merge the partial state and the previous state.
12243 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
12244 workInProgress.memoizedState = memoizedState;
12245
12246 // Once the update queue is empty, persist the derived state onto the
12247 // base state.
12248 var updateQueue = workInProgress.updateQueue;
12249 if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
12250 updateQueue.baseState = memoizedState;
12251 }
12252}
12253
12254var classComponentUpdater = {
12255 isMounted: isMounted,
12256 enqueueSetState: function (inst, payload, callback) {
12257 var fiber = get(inst);
12258 var currentTime = requestCurrentTime$$1();
12259 var expirationTime = computeExpirationForFiber$$1(currentTime, fiber);
12260
12261 var update = createUpdate(expirationTime);
12262 update.payload = payload;
12263 if (callback !== undefined && callback !== null) {
12264 {
12265 warnOnInvalidCallback$1(callback, 'setState');
12266 }
12267 update.callback = callback;
12268 }
12269
12270 flushPassiveEffects$$1();
12271 enqueueUpdate(fiber, update);
12272 scheduleWork$$1(fiber, expirationTime);
12273 },
12274 enqueueReplaceState: function (inst, payload, callback) {
12275 var fiber = get(inst);
12276 var currentTime = requestCurrentTime$$1();
12277 var expirationTime = computeExpirationForFiber$$1(currentTime, fiber);
12278
12279 var update = createUpdate(expirationTime);
12280 update.tag = ReplaceState;
12281 update.payload = payload;
12282
12283 if (callback !== undefined && callback !== null) {
12284 {
12285 warnOnInvalidCallback$1(callback, 'replaceState');
12286 }
12287 update.callback = callback;
12288 }
12289
12290 flushPassiveEffects$$1();
12291 enqueueUpdate(fiber, update);
12292 scheduleWork$$1(fiber, expirationTime);
12293 },
12294 enqueueForceUpdate: function (inst, callback) {
12295 var fiber = get(inst);
12296 var currentTime = requestCurrentTime$$1();
12297 var expirationTime = computeExpirationForFiber$$1(currentTime, fiber);
12298
12299 var update = createUpdate(expirationTime);
12300 update.tag = ForceUpdate;
12301
12302 if (callback !== undefined && callback !== null) {
12303 {
12304 warnOnInvalidCallback$1(callback, 'forceUpdate');
12305 }
12306 update.callback = callback;
12307 }
12308
12309 flushPassiveEffects$$1();
12310 enqueueUpdate(fiber, update);
12311 scheduleWork$$1(fiber, expirationTime);
12312 }
12313};
12314
12315function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
12316 var instance = workInProgress.stateNode;
12317 if (typeof instance.shouldComponentUpdate === 'function') {
12318 startPhaseTimer(workInProgress, 'shouldComponentUpdate');
12319 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
12320 stopPhaseTimer();
12321
12322 {
12323 !(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;
12324 }
12325
12326 return shouldUpdate;
12327 }
12328
12329 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
12330 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
12331 }
12332
12333 return true;
12334}
12335
12336function checkClassInstance(workInProgress, ctor, newProps) {
12337 var instance = workInProgress.stateNode;
12338 {
12339 var name = getComponentName(ctor) || 'Component';
12340 var renderPresent = instance.render;
12341
12342 if (!renderPresent) {
12343 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
12344 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
12345 } else {
12346 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
12347 }
12348 }
12349
12350 var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
12351 !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;
12352 var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
12353 !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;
12354 var noInstancePropTypes = !instance.propTypes;
12355 !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
12356 var noInstanceContextType = !instance.contextType;
12357 !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0;
12358 var noInstanceContextTypes = !instance.contextTypes;
12359 !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
12360
12361 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
12362 didWarnAboutContextTypeAndContextTypes.add(ctor);
12363 warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
12364 }
12365
12366 var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
12367 !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;
12368 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
12369 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');
12370 }
12371 var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
12372 !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
12373 var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
12374 !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;
12375 var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
12376 !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
12377 var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
12378 !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
12379 var hasMutatedProps = instance.props !== newProps;
12380 !(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;
12381 var noInstanceDefaultProps = !instance.defaultProps;
12382 !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;
12383
12384 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
12385 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
12386 warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
12387 }
12388
12389 var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
12390 !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;
12391 var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function';
12392 !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;
12393 var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function';
12394 !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;
12395 var _state = instance.state;
12396 if (_state && (typeof _state !== 'object' || isArray$1(_state))) {
12397 warningWithoutStack$1(false, '%s.state: must be set to an object or null', name);
12398 }
12399 if (typeof instance.getChildContext === 'function') {
12400 !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
12401 }
12402 }
12403}
12404
12405function adoptClassInstance(workInProgress, instance) {
12406 instance.updater = classComponentUpdater;
12407 workInProgress.stateNode = instance;
12408 // The instance needs access to the fiber so that it can schedule updates
12409 set(instance, workInProgress);
12410 {
12411 instance._reactInternalInstance = fakeInternalInstance;
12412 }
12413}
12414
12415function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) {
12416 var isLegacyContextConsumer = false;
12417 var unmaskedContext = emptyContextObject;
12418 var context = null;
12419 var contextType = ctor.contextType;
12420
12421 {
12422 if ('contextType' in ctor) {
12423 var isValid =
12424 // Allow null for conditional declaration
12425 contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
12426
12427 if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
12428 didWarnAboutInvalidateContextType.add(ctor);
12429
12430 var addendum = '';
12431 if (contextType === undefined) {
12432 addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
12433 } else if (typeof contextType !== 'object') {
12434 addendum = ' However, it is set to a ' + typeof contextType + '.';
12435 } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
12436 addendum = ' Did you accidentally pass the Context.Provider instead?';
12437 } else if (contextType._context !== undefined) {
12438 // <Context.Consumer>
12439 addendum = ' Did you accidentally pass the Context.Consumer instead?';
12440 } else {
12441 addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
12442 }
12443 warningWithoutStack$1(false, '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);
12444 }
12445 }
12446 }
12447
12448 if (typeof contextType === 'object' && contextType !== null) {
12449 context = readContext(contextType);
12450 } else {
12451 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
12452 var contextTypes = ctor.contextTypes;
12453 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
12454 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
12455 }
12456
12457 // Instantiate twice to help detect side-effects.
12458 {
12459 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
12460 new ctor(props, context); // eslint-disable-line no-new
12461 }
12462 }
12463
12464 var instance = new ctor(props, context);
12465 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
12466 adoptClassInstance(workInProgress, instance);
12467
12468 {
12469 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
12470 var componentName = getComponentName(ctor) || 'Component';
12471 if (!didWarnAboutUninitializedState.has(componentName)) {
12472 didWarnAboutUninitializedState.add(componentName);
12473 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);
12474 }
12475 }
12476
12477 // If new component APIs are defined, "unsafe" lifecycles won't be called.
12478 // Warn about these lifecycles if they are present.
12479 // Don't warn about react-lifecycles-compat polyfilled methods though.
12480 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
12481 var foundWillMountName = null;
12482 var foundWillReceivePropsName = null;
12483 var foundWillUpdateName = null;
12484 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
12485 foundWillMountName = 'componentWillMount';
12486 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
12487 foundWillMountName = 'UNSAFE_componentWillMount';
12488 }
12489 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
12490 foundWillReceivePropsName = 'componentWillReceiveProps';
12491 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
12492 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
12493 }
12494 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
12495 foundWillUpdateName = 'componentWillUpdate';
12496 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
12497 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
12498 }
12499 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
12500 var _componentName = getComponentName(ctor) || 'Component';
12501 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
12502 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
12503 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
12504 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 : '');
12505 }
12506 }
12507 }
12508 }
12509
12510 // Cache unmasked context so we can avoid recreating masked context unless necessary.
12511 // ReactFiberContext usually updates this cache but can't for newly-created instances.
12512 if (isLegacyContextConsumer) {
12513 cacheContext(workInProgress, unmaskedContext, context);
12514 }
12515
12516 return instance;
12517}
12518
12519function callComponentWillMount(workInProgress, instance) {
12520 startPhaseTimer(workInProgress, 'componentWillMount');
12521 var oldState = instance.state;
12522
12523 if (typeof instance.componentWillMount === 'function') {
12524 instance.componentWillMount();
12525 }
12526 if (typeof instance.UNSAFE_componentWillMount === 'function') {
12527 instance.UNSAFE_componentWillMount();
12528 }
12529
12530 stopPhaseTimer();
12531
12532 if (oldState !== instance.state) {
12533 {
12534 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');
12535 }
12536 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
12537 }
12538}
12539
12540function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
12541 var oldState = instance.state;
12542 startPhaseTimer(workInProgress, 'componentWillReceiveProps');
12543 if (typeof instance.componentWillReceiveProps === 'function') {
12544 instance.componentWillReceiveProps(newProps, nextContext);
12545 }
12546 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
12547 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
12548 }
12549 stopPhaseTimer();
12550
12551 if (instance.state !== oldState) {
12552 {
12553 var componentName = getComponentName(workInProgress.type) || 'Component';
12554 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
12555 didWarnAboutStateAssignmentForComponent.add(componentName);
12556 warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
12557 }
12558 }
12559 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
12560 }
12561}
12562
12563// Invokes the mount life-cycles on a previously never rendered instance.
12564function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
12565 {
12566 checkClassInstance(workInProgress, ctor, newProps);
12567 }
12568
12569 var instance = workInProgress.stateNode;
12570 instance.props = newProps;
12571 instance.state = workInProgress.memoizedState;
12572 instance.refs = emptyRefsObject;
12573
12574 var contextType = ctor.contextType;
12575 if (typeof contextType === 'object' && contextType !== null) {
12576 instance.context = readContext(contextType);
12577 } else {
12578 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
12579 instance.context = getMaskedContext(workInProgress, unmaskedContext);
12580 }
12581
12582 {
12583 if (instance.state === newProps) {
12584 var componentName = getComponentName(ctor) || 'Component';
12585 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
12586 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
12587 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);
12588 }
12589 }
12590
12591 if (workInProgress.mode & StrictMode) {
12592 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
12593
12594 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
12595 }
12596
12597 if (warnAboutDeprecatedLifecycles) {
12598 ReactStrictModeWarnings.recordDeprecationWarnings(workInProgress, instance);
12599 }
12600 }
12601
12602 var updateQueue = workInProgress.updateQueue;
12603 if (updateQueue !== null) {
12604 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
12605 instance.state = workInProgress.memoizedState;
12606 }
12607
12608 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
12609 if (typeof getDerivedStateFromProps === 'function') {
12610 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
12611 instance.state = workInProgress.memoizedState;
12612 }
12613
12614 // In order to support react-lifecycles-compat polyfilled components,
12615 // Unsafe lifecycles should not be invoked for components using the new APIs.
12616 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
12617 callComponentWillMount(workInProgress, instance);
12618 // If we had additional state updates during this life-cycle, let's
12619 // process them now.
12620 updateQueue = workInProgress.updateQueue;
12621 if (updateQueue !== null) {
12622 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
12623 instance.state = workInProgress.memoizedState;
12624 }
12625 }
12626
12627 if (typeof instance.componentDidMount === 'function') {
12628 workInProgress.effectTag |= Update;
12629 }
12630}
12631
12632function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
12633 var instance = workInProgress.stateNode;
12634
12635 var oldProps = workInProgress.memoizedProps;
12636 instance.props = oldProps;
12637
12638 var oldContext = instance.context;
12639 var contextType = ctor.contextType;
12640 var nextContext = void 0;
12641 if (typeof contextType === 'object' && contextType !== null) {
12642 nextContext = readContext(contextType);
12643 } else {
12644 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
12645 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
12646 }
12647
12648 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
12649 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
12650
12651 // Note: During these life-cycles, instance.props/instance.state are what
12652 // ever the previously attempted to render - not the "current". However,
12653 // during componentDidUpdate we pass the "current" props.
12654
12655 // In order to support react-lifecycles-compat polyfilled components,
12656 // Unsafe lifecycles should not be invoked for components using the new APIs.
12657 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
12658 if (oldProps !== newProps || oldContext !== nextContext) {
12659 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
12660 }
12661 }
12662
12663 resetHasForceUpdateBeforeProcessing();
12664
12665 var oldState = workInProgress.memoizedState;
12666 var newState = instance.state = oldState;
12667 var updateQueue = workInProgress.updateQueue;
12668 if (updateQueue !== null) {
12669 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
12670 newState = workInProgress.memoizedState;
12671 }
12672 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
12673 // If an update was already in progress, we should schedule an Update
12674 // effect even though we're bailing out, so that cWU/cDU are called.
12675 if (typeof instance.componentDidMount === 'function') {
12676 workInProgress.effectTag |= Update;
12677 }
12678 return false;
12679 }
12680
12681 if (typeof getDerivedStateFromProps === 'function') {
12682 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
12683 newState = workInProgress.memoizedState;
12684 }
12685
12686 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
12687
12688 if (shouldUpdate) {
12689 // In order to support react-lifecycles-compat polyfilled components,
12690 // Unsafe lifecycles should not be invoked for components using the new APIs.
12691 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
12692 startPhaseTimer(workInProgress, 'componentWillMount');
12693 if (typeof instance.componentWillMount === 'function') {
12694 instance.componentWillMount();
12695 }
12696 if (typeof instance.UNSAFE_componentWillMount === 'function') {
12697 instance.UNSAFE_componentWillMount();
12698 }
12699 stopPhaseTimer();
12700 }
12701 if (typeof instance.componentDidMount === 'function') {
12702 workInProgress.effectTag |= Update;
12703 }
12704 } else {
12705 // If an update was already in progress, we should schedule an Update
12706 // effect even though we're bailing out, so that cWU/cDU are called.
12707 if (typeof instance.componentDidMount === 'function') {
12708 workInProgress.effectTag |= Update;
12709 }
12710
12711 // If shouldComponentUpdate returned false, we should still update the
12712 // memoized state to indicate that this work can be reused.
12713 workInProgress.memoizedProps = newProps;
12714 workInProgress.memoizedState = newState;
12715 }
12716
12717 // Update the existing instance's state, props, and context pointers even
12718 // if shouldComponentUpdate returns false.
12719 instance.props = newProps;
12720 instance.state = newState;
12721 instance.context = nextContext;
12722
12723 return shouldUpdate;
12724}
12725
12726// Invokes the update life-cycles and returns false if it shouldn't rerender.
12727function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
12728 var instance = workInProgress.stateNode;
12729
12730 var oldProps = workInProgress.memoizedProps;
12731 instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
12732
12733 var oldContext = instance.context;
12734 var contextType = ctor.contextType;
12735 var nextContext = void 0;
12736 if (typeof contextType === 'object' && contextType !== null) {
12737 nextContext = readContext(contextType);
12738 } else {
12739 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
12740 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
12741 }
12742
12743 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
12744 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
12745
12746 // Note: During these life-cycles, instance.props/instance.state are what
12747 // ever the previously attempted to render - not the "current". However,
12748 // during componentDidUpdate we pass the "current" props.
12749
12750 // In order to support react-lifecycles-compat polyfilled components,
12751 // Unsafe lifecycles should not be invoked for components using the new APIs.
12752 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
12753 if (oldProps !== newProps || oldContext !== nextContext) {
12754 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
12755 }
12756 }
12757
12758 resetHasForceUpdateBeforeProcessing();
12759
12760 var oldState = workInProgress.memoizedState;
12761 var newState = instance.state = oldState;
12762 var updateQueue = workInProgress.updateQueue;
12763 if (updateQueue !== null) {
12764 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
12765 newState = workInProgress.memoizedState;
12766 }
12767
12768 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
12769 // If an update was already in progress, we should schedule an Update
12770 // effect even though we're bailing out, so that cWU/cDU are called.
12771 if (typeof instance.componentDidUpdate === 'function') {
12772 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
12773 workInProgress.effectTag |= Update;
12774 }
12775 }
12776 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
12777 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
12778 workInProgress.effectTag |= Snapshot;
12779 }
12780 }
12781 return false;
12782 }
12783
12784 if (typeof getDerivedStateFromProps === 'function') {
12785 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
12786 newState = workInProgress.memoizedState;
12787 }
12788
12789 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
12790
12791 if (shouldUpdate) {
12792 // In order to support react-lifecycles-compat polyfilled components,
12793 // Unsafe lifecycles should not be invoked for components using the new APIs.
12794 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
12795 startPhaseTimer(workInProgress, 'componentWillUpdate');
12796 if (typeof instance.componentWillUpdate === 'function') {
12797 instance.componentWillUpdate(newProps, newState, nextContext);
12798 }
12799 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
12800 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
12801 }
12802 stopPhaseTimer();
12803 }
12804 if (typeof instance.componentDidUpdate === 'function') {
12805 workInProgress.effectTag |= Update;
12806 }
12807 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
12808 workInProgress.effectTag |= Snapshot;
12809 }
12810 } else {
12811 // If an update was already in progress, we should schedule an Update
12812 // effect even though we're bailing out, so that cWU/cDU are called.
12813 if (typeof instance.componentDidUpdate === 'function') {
12814 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
12815 workInProgress.effectTag |= Update;
12816 }
12817 }
12818 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
12819 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
12820 workInProgress.effectTag |= Snapshot;
12821 }
12822 }
12823
12824 // If shouldComponentUpdate returned false, we should still update the
12825 // memoized props/state to indicate that this work can be reused.
12826 workInProgress.memoizedProps = newProps;
12827 workInProgress.memoizedState = newState;
12828 }
12829
12830 // Update the existing instance's state, props, and context pointers even
12831 // if shouldComponentUpdate returns false.
12832 instance.props = newProps;
12833 instance.state = newState;
12834 instance.context = nextContext;
12835
12836 return shouldUpdate;
12837}
12838
12839var didWarnAboutMaps = void 0;
12840var didWarnAboutGenerators = void 0;
12841var didWarnAboutStringRefInStrictMode = void 0;
12842var ownerHasKeyUseWarning = void 0;
12843var ownerHasFunctionTypeWarning = void 0;
12844var warnForMissingKey = function (child) {};
12845
12846{
12847 didWarnAboutMaps = false;
12848 didWarnAboutGenerators = false;
12849 didWarnAboutStringRefInStrictMode = {};
12850
12851 /**
12852 * Warn if there's no key explicitly set on dynamic arrays of children or
12853 * object keys are not valid. This allows us to keep track of children between
12854 * updates.
12855 */
12856 ownerHasKeyUseWarning = {};
12857 ownerHasFunctionTypeWarning = {};
12858
12859 warnForMissingKey = function (child) {
12860 if (child === null || typeof child !== 'object') {
12861 return;
12862 }
12863 if (!child._store || child._store.validated || child.key != null) {
12864 return;
12865 }
12866 (function () {
12867 if (!(typeof child._store === 'object')) {
12868 {
12869 throw ReactError('React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.');
12870 }
12871 }
12872 })();
12873 child._store.validated = true;
12874
12875 var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
12876 if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
12877 return;
12878 }
12879 ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
12880
12881 warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
12882 };
12883}
12884
12885var isArray = Array.isArray;
12886
12887function coerceRef(returnFiber, current$$1, element) {
12888 var mixedRef = element.ref;
12889 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
12890 {
12891 if (returnFiber.mode & StrictMode) {
12892 var componentName = getComponentName(returnFiber.type) || 'Component';
12893 if (!didWarnAboutStringRefInStrictMode[componentName]) {
12894 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));
12895 didWarnAboutStringRefInStrictMode[componentName] = true;
12896 }
12897 }
12898 }
12899
12900 if (element._owner) {
12901 var owner = element._owner;
12902 var inst = void 0;
12903 if (owner) {
12904 var ownerFiber = owner;
12905 (function () {
12906 if (!(ownerFiber.tag === ClassComponent)) {
12907 {
12908 throw ReactError('Function components cannot have refs. Did you mean to use React.forwardRef()?');
12909 }
12910 }
12911 })();
12912 inst = ownerFiber.stateNode;
12913 }
12914 (function () {
12915 if (!inst) {
12916 {
12917 throw ReactError('Missing owner for string ref ' + mixedRef + '. This error is likely caused by a bug in React. Please file an issue.');
12918 }
12919 }
12920 })();
12921 var stringRef = '' + mixedRef;
12922 // Check if previous string ref matches new string ref
12923 if (current$$1 !== null && current$$1.ref !== null && typeof current$$1.ref === 'function' && current$$1.ref._stringRef === stringRef) {
12924 return current$$1.ref;
12925 }
12926 var ref = function (value) {
12927 var refs = inst.refs;
12928 if (refs === emptyRefsObject) {
12929 // This is a lazy pooled frozen object, so we need to initialize.
12930 refs = inst.refs = {};
12931 }
12932 if (value === null) {
12933 delete refs[stringRef];
12934 } else {
12935 refs[stringRef] = value;
12936 }
12937 };
12938 ref._stringRef = stringRef;
12939 return ref;
12940 } else {
12941 (function () {
12942 if (!(typeof mixedRef === 'string')) {
12943 {
12944 throw ReactError('Expected ref to be a function, a string, an object returned by React.createRef(), or null.');
12945 }
12946 }
12947 })();
12948 (function () {
12949 if (!element._owner) {
12950 {
12951 throw ReactError('Element ref was specified as a string (' + mixedRef + ') but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component\'s render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information.');
12952 }
12953 }
12954 })();
12955 }
12956 }
12957 return mixedRef;
12958}
12959
12960function throwOnInvalidObjectType(returnFiber, newChild) {
12961 if (returnFiber.type !== 'textarea') {
12962 var addendum = '';
12963 {
12964 addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
12965 }
12966 (function () {
12967 {
12968 {
12969 throw ReactError('Objects are not valid as a React child (found: ' + (Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild) + ').' + addendum);
12970 }
12971 }
12972 })();
12973 }
12974}
12975
12976function warnOnFunctionType() {
12977 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();
12978
12979 if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
12980 return;
12981 }
12982 ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
12983
12984 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.');
12985}
12986
12987// This wrapper function exists because I expect to clone the code in each path
12988// to be able to optimize each path individually by branching early. This needs
12989// a compiler or we can do it manually. Helpers that don't need this branching
12990// live outside of this function.
12991function ChildReconciler(shouldTrackSideEffects) {
12992 function deleteChild(returnFiber, childToDelete) {
12993 if (!shouldTrackSideEffects) {
12994 // Noop.
12995 return;
12996 }
12997 // Deletions are added in reversed order so we add it to the front.
12998 // At this point, the return fiber's effect list is empty except for
12999 // deletions, so we can just append the deletion to the list. The remaining
13000 // effects aren't added until the complete phase. Once we implement
13001 // resuming, this may not be true.
13002 var last = returnFiber.lastEffect;
13003 if (last !== null) {
13004 last.nextEffect = childToDelete;
13005 returnFiber.lastEffect = childToDelete;
13006 } else {
13007 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
13008 }
13009 childToDelete.nextEffect = null;
13010 childToDelete.effectTag = Deletion;
13011 }
13012
13013 function deleteRemainingChildren(returnFiber, currentFirstChild) {
13014 if (!shouldTrackSideEffects) {
13015 // Noop.
13016 return null;
13017 }
13018
13019 // TODO: For the shouldClone case, this could be micro-optimized a bit by
13020 // assuming that after the first child we've already added everything.
13021 var childToDelete = currentFirstChild;
13022 while (childToDelete !== null) {
13023 deleteChild(returnFiber, childToDelete);
13024 childToDelete = childToDelete.sibling;
13025 }
13026 return null;
13027 }
13028
13029 function mapRemainingChildren(returnFiber, currentFirstChild) {
13030 // Add the remaining children to a temporary map so that we can find them by
13031 // keys quickly. Implicit (null) keys get added to this set with their index
13032 var existingChildren = new Map();
13033
13034 var existingChild = currentFirstChild;
13035 while (existingChild !== null) {
13036 if (existingChild.key !== null) {
13037 existingChildren.set(existingChild.key, existingChild);
13038 } else {
13039 existingChildren.set(existingChild.index, existingChild);
13040 }
13041 existingChild = existingChild.sibling;
13042 }
13043 return existingChildren;
13044 }
13045
13046 function useFiber(fiber, pendingProps, expirationTime) {
13047 // We currently set sibling to null and index to 0 here because it is easy
13048 // to forget to do before returning it. E.g. for the single child case.
13049 var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
13050 clone.index = 0;
13051 clone.sibling = null;
13052 return clone;
13053 }
13054
13055 function placeChild(newFiber, lastPlacedIndex, newIndex) {
13056 newFiber.index = newIndex;
13057 if (!shouldTrackSideEffects) {
13058 // Noop.
13059 return lastPlacedIndex;
13060 }
13061 var current$$1 = newFiber.alternate;
13062 if (current$$1 !== null) {
13063 var oldIndex = current$$1.index;
13064 if (oldIndex < lastPlacedIndex) {
13065 // This is a move.
13066 newFiber.effectTag = Placement;
13067 return lastPlacedIndex;
13068 } else {
13069 // This item can stay in place.
13070 return oldIndex;
13071 }
13072 } else {
13073 // This is an insertion.
13074 newFiber.effectTag = Placement;
13075 return lastPlacedIndex;
13076 }
13077 }
13078
13079 function placeSingleChild(newFiber) {
13080 // This is simpler for the single child case. We only need to do a
13081 // placement for inserting new children.
13082 if (shouldTrackSideEffects && newFiber.alternate === null) {
13083 newFiber.effectTag = Placement;
13084 }
13085 return newFiber;
13086 }
13087
13088 function updateTextNode(returnFiber, current$$1, textContent, expirationTime) {
13089 if (current$$1 === null || current$$1.tag !== HostText) {
13090 // Insert
13091 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
13092 created.return = returnFiber;
13093 return created;
13094 } else {
13095 // Update
13096 var existing = useFiber(current$$1, textContent, expirationTime);
13097 existing.return = returnFiber;
13098 return existing;
13099 }
13100 }
13101
13102 function updateElement(returnFiber, current$$1, element, expirationTime) {
13103 if (current$$1 !== null && current$$1.elementType === element.type) {
13104 // Move based on index
13105 var existing = useFiber(current$$1, element.props, expirationTime);
13106 existing.ref = coerceRef(returnFiber, current$$1, element);
13107 existing.return = returnFiber;
13108 {
13109 existing._debugSource = element._source;
13110 existing._debugOwner = element._owner;
13111 }
13112 return existing;
13113 } else {
13114 // Insert
13115 var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
13116 created.ref = coerceRef(returnFiber, current$$1, element);
13117 created.return = returnFiber;
13118 return created;
13119 }
13120 }
13121
13122 function updatePortal(returnFiber, current$$1, portal, expirationTime) {
13123 if (current$$1 === null || current$$1.tag !== HostPortal || current$$1.stateNode.containerInfo !== portal.containerInfo || current$$1.stateNode.implementation !== portal.implementation) {
13124 // Insert
13125 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
13126 created.return = returnFiber;
13127 return created;
13128 } else {
13129 // Update
13130 var existing = useFiber(current$$1, portal.children || [], expirationTime);
13131 existing.return = returnFiber;
13132 return existing;
13133 }
13134 }
13135
13136 function updateFragment(returnFiber, current$$1, fragment, expirationTime, key) {
13137 if (current$$1 === null || current$$1.tag !== Fragment) {
13138 // Insert
13139 var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
13140 created.return = returnFiber;
13141 return created;
13142 } else {
13143 // Update
13144 var existing = useFiber(current$$1, fragment, expirationTime);
13145 existing.return = returnFiber;
13146 return existing;
13147 }
13148 }
13149
13150 function createChild(returnFiber, newChild, expirationTime) {
13151 if (typeof newChild === 'string' || typeof newChild === 'number') {
13152 // Text nodes don't have keys. If the previous node is implicitly keyed
13153 // we can continue to replace it without aborting even if it is not a text
13154 // node.
13155 var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
13156 created.return = returnFiber;
13157 return created;
13158 }
13159
13160 if (typeof newChild === 'object' && newChild !== null) {
13161 switch (newChild.$$typeof) {
13162 case REACT_ELEMENT_TYPE:
13163 {
13164 var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
13165 _created.ref = coerceRef(returnFiber, null, newChild);
13166 _created.return = returnFiber;
13167 return _created;
13168 }
13169 case REACT_PORTAL_TYPE:
13170 {
13171 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
13172 _created2.return = returnFiber;
13173 return _created2;
13174 }
13175 }
13176
13177 if (isArray(newChild) || getIteratorFn(newChild)) {
13178 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
13179 _created3.return = returnFiber;
13180 return _created3;
13181 }
13182
13183 throwOnInvalidObjectType(returnFiber, newChild);
13184 }
13185
13186 {
13187 if (typeof newChild === 'function') {
13188 warnOnFunctionType();
13189 }
13190 }
13191
13192 return null;
13193 }
13194
13195 function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
13196 // Update the fiber if the keys match, otherwise return null.
13197
13198 var key = oldFiber !== null ? oldFiber.key : null;
13199
13200 if (typeof newChild === 'string' || typeof newChild === 'number') {
13201 // Text nodes don't have keys. If the previous node is implicitly keyed
13202 // we can continue to replace it without aborting even if it is not a text
13203 // node.
13204 if (key !== null) {
13205 return null;
13206 }
13207 return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
13208 }
13209
13210 if (typeof newChild === 'object' && newChild !== null) {
13211 switch (newChild.$$typeof) {
13212 case REACT_ELEMENT_TYPE:
13213 {
13214 if (newChild.key === key) {
13215 if (newChild.type === REACT_FRAGMENT_TYPE) {
13216 return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
13217 }
13218 return updateElement(returnFiber, oldFiber, newChild, expirationTime);
13219 } else {
13220 return null;
13221 }
13222 }
13223 case REACT_PORTAL_TYPE:
13224 {
13225 if (newChild.key === key) {
13226 return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
13227 } else {
13228 return null;
13229 }
13230 }
13231 }
13232
13233 if (isArray(newChild) || getIteratorFn(newChild)) {
13234 if (key !== null) {
13235 return null;
13236 }
13237
13238 return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
13239 }
13240
13241 throwOnInvalidObjectType(returnFiber, newChild);
13242 }
13243
13244 {
13245 if (typeof newChild === 'function') {
13246 warnOnFunctionType();
13247 }
13248 }
13249
13250 return null;
13251 }
13252
13253 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
13254 if (typeof newChild === 'string' || typeof newChild === 'number') {
13255 // Text nodes don't have keys, so we neither have to check the old nor
13256 // new node for the key. If both are text nodes, they match.
13257 var matchedFiber = existingChildren.get(newIdx) || null;
13258 return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
13259 }
13260
13261 if (typeof newChild === 'object' && newChild !== null) {
13262 switch (newChild.$$typeof) {
13263 case REACT_ELEMENT_TYPE:
13264 {
13265 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
13266 if (newChild.type === REACT_FRAGMENT_TYPE) {
13267 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
13268 }
13269 return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
13270 }
13271 case REACT_PORTAL_TYPE:
13272 {
13273 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
13274 return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
13275 }
13276 }
13277
13278 if (isArray(newChild) || getIteratorFn(newChild)) {
13279 var _matchedFiber3 = existingChildren.get(newIdx) || null;
13280 return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
13281 }
13282
13283 throwOnInvalidObjectType(returnFiber, newChild);
13284 }
13285
13286 {
13287 if (typeof newChild === 'function') {
13288 warnOnFunctionType();
13289 }
13290 }
13291
13292 return null;
13293 }
13294
13295 /**
13296 * Warns if there is a duplicate or missing key
13297 */
13298 function warnOnInvalidKey(child, knownKeys) {
13299 {
13300 if (typeof child !== 'object' || child === null) {
13301 return knownKeys;
13302 }
13303 switch (child.$$typeof) {
13304 case REACT_ELEMENT_TYPE:
13305 case REACT_PORTAL_TYPE:
13306 warnForMissingKey(child);
13307 var key = child.key;
13308 if (typeof key !== 'string') {
13309 break;
13310 }
13311 if (knownKeys === null) {
13312 knownKeys = new Set();
13313 knownKeys.add(key);
13314 break;
13315 }
13316 if (!knownKeys.has(key)) {
13317 knownKeys.add(key);
13318 break;
13319 }
13320 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);
13321 break;
13322 default:
13323 break;
13324 }
13325 }
13326 return knownKeys;
13327 }
13328
13329 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
13330 // This algorithm can't optimize by searching from both ends since we
13331 // don't have backpointers on fibers. I'm trying to see how far we can get
13332 // with that model. If it ends up not being worth the tradeoffs, we can
13333 // add it later.
13334
13335 // Even with a two ended optimization, we'd want to optimize for the case
13336 // where there are few changes and brute force the comparison instead of
13337 // going for the Map. It'd like to explore hitting that path first in
13338 // forward-only mode and only go for the Map once we notice that we need
13339 // lots of look ahead. This doesn't handle reversal as well as two ended
13340 // search but that's unusual. Besides, for the two ended optimization to
13341 // work on Iterables, we'd need to copy the whole set.
13342
13343 // In this first iteration, we'll just live with hitting the bad case
13344 // (adding everything to a Map) in for every insert/move.
13345
13346 // If you change this code, also update reconcileChildrenIterator() which
13347 // uses the same algorithm.
13348
13349 {
13350 // First, validate keys.
13351 var knownKeys = null;
13352 for (var i = 0; i < newChildren.length; i++) {
13353 var child = newChildren[i];
13354 knownKeys = warnOnInvalidKey(child, knownKeys);
13355 }
13356 }
13357
13358 var resultingFirstChild = null;
13359 var previousNewFiber = null;
13360
13361 var oldFiber = currentFirstChild;
13362 var lastPlacedIndex = 0;
13363 var newIdx = 0;
13364 var nextOldFiber = null;
13365 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
13366 if (oldFiber.index > newIdx) {
13367 nextOldFiber = oldFiber;
13368 oldFiber = null;
13369 } else {
13370 nextOldFiber = oldFiber.sibling;
13371 }
13372 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
13373 if (newFiber === null) {
13374 // TODO: This breaks on empty slots like null children. That's
13375 // unfortunate because it triggers the slow path all the time. We need
13376 // a better way to communicate whether this was a miss or null,
13377 // boolean, undefined, etc.
13378 if (oldFiber === null) {
13379 oldFiber = nextOldFiber;
13380 }
13381 break;
13382 }
13383 if (shouldTrackSideEffects) {
13384 if (oldFiber && newFiber.alternate === null) {
13385 // We matched the slot, but we didn't reuse the existing fiber, so we
13386 // need to delete the existing child.
13387 deleteChild(returnFiber, oldFiber);
13388 }
13389 }
13390 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
13391 if (previousNewFiber === null) {
13392 // TODO: Move out of the loop. This only happens for the first run.
13393 resultingFirstChild = newFiber;
13394 } else {
13395 // TODO: Defer siblings if we're not at the right index for this slot.
13396 // I.e. if we had null values before, then we want to defer this
13397 // for each null value. However, we also don't want to call updateSlot
13398 // with the previous one.
13399 previousNewFiber.sibling = newFiber;
13400 }
13401 previousNewFiber = newFiber;
13402 oldFiber = nextOldFiber;
13403 }
13404
13405 if (newIdx === newChildren.length) {
13406 // We've reached the end of the new children. We can delete the rest.
13407 deleteRemainingChildren(returnFiber, oldFiber);
13408 return resultingFirstChild;
13409 }
13410
13411 if (oldFiber === null) {
13412 // If we don't have any more existing children we can choose a fast path
13413 // since the rest will all be insertions.
13414 for (; newIdx < newChildren.length; newIdx++) {
13415 var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
13416 if (!_newFiber) {
13417 continue;
13418 }
13419 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
13420 if (previousNewFiber === null) {
13421 // TODO: Move out of the loop. This only happens for the first run.
13422 resultingFirstChild = _newFiber;
13423 } else {
13424 previousNewFiber.sibling = _newFiber;
13425 }
13426 previousNewFiber = _newFiber;
13427 }
13428 return resultingFirstChild;
13429 }
13430
13431 // Add all children to a key map for quick lookups.
13432 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
13433
13434 // Keep scanning and use the map to restore deleted items as moves.
13435 for (; newIdx < newChildren.length; newIdx++) {
13436 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
13437 if (_newFiber2) {
13438 if (shouldTrackSideEffects) {
13439 if (_newFiber2.alternate !== null) {
13440 // The new fiber is a work in progress, but if there exists a
13441 // current, that means that we reused the fiber. We need to delete
13442 // it from the child list so that we don't add it to the deletion
13443 // list.
13444 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
13445 }
13446 }
13447 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
13448 if (previousNewFiber === null) {
13449 resultingFirstChild = _newFiber2;
13450 } else {
13451 previousNewFiber.sibling = _newFiber2;
13452 }
13453 previousNewFiber = _newFiber2;
13454 }
13455 }
13456
13457 if (shouldTrackSideEffects) {
13458 // Any existing children that weren't consumed above were deleted. We need
13459 // to add them to the deletion list.
13460 existingChildren.forEach(function (child) {
13461 return deleteChild(returnFiber, child);
13462 });
13463 }
13464
13465 return resultingFirstChild;
13466 }
13467
13468 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
13469 // This is the same implementation as reconcileChildrenArray(),
13470 // but using the iterator instead.
13471
13472 var iteratorFn = getIteratorFn(newChildrenIterable);
13473 (function () {
13474 if (!(typeof iteratorFn === 'function')) {
13475 {
13476 throw ReactError('An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.');
13477 }
13478 }
13479 })();
13480
13481 {
13482 // We don't support rendering Generators because it's a mutation.
13483 // See https://github.com/facebook/react/issues/12995
13484 if (typeof Symbol === 'function' &&
13485 // $FlowFixMe Flow doesn't know about toStringTag
13486 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
13487 !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;
13488 didWarnAboutGenerators = true;
13489 }
13490
13491 // Warn about using Maps as children
13492 if (newChildrenIterable.entries === iteratorFn) {
13493 !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;
13494 didWarnAboutMaps = true;
13495 }
13496
13497 // First, validate keys.
13498 // We'll get a different iterator later for the main pass.
13499 var _newChildren = iteratorFn.call(newChildrenIterable);
13500 if (_newChildren) {
13501 var knownKeys = null;
13502 var _step = _newChildren.next();
13503 for (; !_step.done; _step = _newChildren.next()) {
13504 var child = _step.value;
13505 knownKeys = warnOnInvalidKey(child, knownKeys);
13506 }
13507 }
13508 }
13509
13510 var newChildren = iteratorFn.call(newChildrenIterable);
13511 (function () {
13512 if (!(newChildren != null)) {
13513 {
13514 throw ReactError('An iterable object provided no iterator.');
13515 }
13516 }
13517 })();
13518
13519 var resultingFirstChild = null;
13520 var previousNewFiber = null;
13521
13522 var oldFiber = currentFirstChild;
13523 var lastPlacedIndex = 0;
13524 var newIdx = 0;
13525 var nextOldFiber = null;
13526
13527 var step = newChildren.next();
13528 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
13529 if (oldFiber.index > newIdx) {
13530 nextOldFiber = oldFiber;
13531 oldFiber = null;
13532 } else {
13533 nextOldFiber = oldFiber.sibling;
13534 }
13535 var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
13536 if (newFiber === null) {
13537 // TODO: This breaks on empty slots like null children. That's
13538 // unfortunate because it triggers the slow path all the time. We need
13539 // a better way to communicate whether this was a miss or null,
13540 // boolean, undefined, etc.
13541 if (!oldFiber) {
13542 oldFiber = nextOldFiber;
13543 }
13544 break;
13545 }
13546 if (shouldTrackSideEffects) {
13547 if (oldFiber && newFiber.alternate === null) {
13548 // We matched the slot, but we didn't reuse the existing fiber, so we
13549 // need to delete the existing child.
13550 deleteChild(returnFiber, oldFiber);
13551 }
13552 }
13553 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
13554 if (previousNewFiber === null) {
13555 // TODO: Move out of the loop. This only happens for the first run.
13556 resultingFirstChild = newFiber;
13557 } else {
13558 // TODO: Defer siblings if we're not at the right index for this slot.
13559 // I.e. if we had null values before, then we want to defer this
13560 // for each null value. However, we also don't want to call updateSlot
13561 // with the previous one.
13562 previousNewFiber.sibling = newFiber;
13563 }
13564 previousNewFiber = newFiber;
13565 oldFiber = nextOldFiber;
13566 }
13567
13568 if (step.done) {
13569 // We've reached the end of the new children. We can delete the rest.
13570 deleteRemainingChildren(returnFiber, oldFiber);
13571 return resultingFirstChild;
13572 }
13573
13574 if (oldFiber === null) {
13575 // If we don't have any more existing children we can choose a fast path
13576 // since the rest will all be insertions.
13577 for (; !step.done; newIdx++, step = newChildren.next()) {
13578 var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
13579 if (_newFiber3 === null) {
13580 continue;
13581 }
13582 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
13583 if (previousNewFiber === null) {
13584 // TODO: Move out of the loop. This only happens for the first run.
13585 resultingFirstChild = _newFiber3;
13586 } else {
13587 previousNewFiber.sibling = _newFiber3;
13588 }
13589 previousNewFiber = _newFiber3;
13590 }
13591 return resultingFirstChild;
13592 }
13593
13594 // Add all children to a key map for quick lookups.
13595 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
13596
13597 // Keep scanning and use the map to restore deleted items as moves.
13598 for (; !step.done; newIdx++, step = newChildren.next()) {
13599 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
13600 if (_newFiber4 !== null) {
13601 if (shouldTrackSideEffects) {
13602 if (_newFiber4.alternate !== null) {
13603 // The new fiber is a work in progress, but if there exists a
13604 // current, that means that we reused the fiber. We need to delete
13605 // it from the child list so that we don't add it to the deletion
13606 // list.
13607 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
13608 }
13609 }
13610 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
13611 if (previousNewFiber === null) {
13612 resultingFirstChild = _newFiber4;
13613 } else {
13614 previousNewFiber.sibling = _newFiber4;
13615 }
13616 previousNewFiber = _newFiber4;
13617 }
13618 }
13619
13620 if (shouldTrackSideEffects) {
13621 // Any existing children that weren't consumed above were deleted. We need
13622 // to add them to the deletion list.
13623 existingChildren.forEach(function (child) {
13624 return deleteChild(returnFiber, child);
13625 });
13626 }
13627
13628 return resultingFirstChild;
13629 }
13630
13631 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
13632 // There's no need to check for keys on text nodes since we don't have a
13633 // way to define them.
13634 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
13635 // We already have an existing node so let's just update it and delete
13636 // the rest.
13637 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
13638 var existing = useFiber(currentFirstChild, textContent, expirationTime);
13639 existing.return = returnFiber;
13640 return existing;
13641 }
13642 // The existing first child is not a text node so we need to create one
13643 // and delete the existing ones.
13644 deleteRemainingChildren(returnFiber, currentFirstChild);
13645 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
13646 created.return = returnFiber;
13647 return created;
13648 }
13649
13650 function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
13651 var key = element.key;
13652 var child = currentFirstChild;
13653 while (child !== null) {
13654 // TODO: If key === null and child.key === null, then this only applies to
13655 // the first item in the list.
13656 if (child.key === key) {
13657 if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.elementType === element.type) {
13658 deleteRemainingChildren(returnFiber, child.sibling);
13659 var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
13660 existing.ref = coerceRef(returnFiber, child, element);
13661 existing.return = returnFiber;
13662 {
13663 existing._debugSource = element._source;
13664 existing._debugOwner = element._owner;
13665 }
13666 return existing;
13667 } else {
13668 deleteRemainingChildren(returnFiber, child);
13669 break;
13670 }
13671 } else {
13672 deleteChild(returnFiber, child);
13673 }
13674 child = child.sibling;
13675 }
13676
13677 if (element.type === REACT_FRAGMENT_TYPE) {
13678 var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
13679 created.return = returnFiber;
13680 return created;
13681 } else {
13682 var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
13683 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
13684 _created4.return = returnFiber;
13685 return _created4;
13686 }
13687 }
13688
13689 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
13690 var key = portal.key;
13691 var child = currentFirstChild;
13692 while (child !== null) {
13693 // TODO: If key === null and child.key === null, then this only applies to
13694 // the first item in the list.
13695 if (child.key === key) {
13696 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
13697 deleteRemainingChildren(returnFiber, child.sibling);
13698 var existing = useFiber(child, portal.children || [], expirationTime);
13699 existing.return = returnFiber;
13700 return existing;
13701 } else {
13702 deleteRemainingChildren(returnFiber, child);
13703 break;
13704 }
13705 } else {
13706 deleteChild(returnFiber, child);
13707 }
13708 child = child.sibling;
13709 }
13710
13711 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
13712 created.return = returnFiber;
13713 return created;
13714 }
13715
13716 // This API will tag the children with the side-effect of the reconciliation
13717 // itself. They will be added to the side-effect list as we pass through the
13718 // children and the parent.
13719 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
13720 // This function is not recursive.
13721 // If the top level item is an array, we treat it as a set of children,
13722 // not as a fragment. Nested arrays on the other hand will be treated as
13723 // fragment nodes. Recursion happens at the normal flow.
13724
13725 // Handle top level unkeyed fragments as if they were arrays.
13726 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
13727 // We treat the ambiguous cases above the same.
13728 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
13729 if (isUnkeyedTopLevelFragment) {
13730 newChild = newChild.props.children;
13731 }
13732
13733 // Handle object types
13734 var isObject = typeof newChild === 'object' && newChild !== null;
13735
13736 if (isObject) {
13737 switch (newChild.$$typeof) {
13738 case REACT_ELEMENT_TYPE:
13739 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
13740 case REACT_PORTAL_TYPE:
13741 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
13742 }
13743 }
13744
13745 if (typeof newChild === 'string' || typeof newChild === 'number') {
13746 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
13747 }
13748
13749 if (isArray(newChild)) {
13750 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
13751 }
13752
13753 if (getIteratorFn(newChild)) {
13754 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
13755 }
13756
13757 if (isObject) {
13758 throwOnInvalidObjectType(returnFiber, newChild);
13759 }
13760
13761 {
13762 if (typeof newChild === 'function') {
13763 warnOnFunctionType();
13764 }
13765 }
13766 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
13767 // If the new child is undefined, and the return fiber is a composite
13768 // component, throw an error. If Fiber return types are disabled,
13769 // we already threw above.
13770 switch (returnFiber.tag) {
13771 case ClassComponent:
13772 {
13773 {
13774 var instance = returnFiber.stateNode;
13775 if (instance.render._isMockFunction) {
13776 // We allow auto-mocks to proceed as if they're returning null.
13777 break;
13778 }
13779 }
13780 }
13781 // Intentionally fall through to the next case, which handles both
13782 // functions and classes
13783 // eslint-disable-next-lined no-fallthrough
13784 case FunctionComponent:
13785 {
13786 var Component = returnFiber.type;
13787 (function () {
13788 {
13789 {
13790 throw ReactError((Component.displayName || Component.name || 'Component') + '(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.');
13791 }
13792 }
13793 })();
13794 }
13795 }
13796 }
13797
13798 // Remaining cases are all treated as empty.
13799 return deleteRemainingChildren(returnFiber, currentFirstChild);
13800 }
13801
13802 return reconcileChildFibers;
13803}
13804
13805var reconcileChildFibers = ChildReconciler(true);
13806var mountChildFibers = ChildReconciler(false);
13807
13808function cloneChildFibers(current$$1, workInProgress) {
13809 (function () {
13810 if (!(current$$1 === null || workInProgress.child === current$$1.child)) {
13811 {
13812 throw ReactError('Resuming work not yet implemented.');
13813 }
13814 }
13815 })();
13816
13817 if (workInProgress.child === null) {
13818 return;
13819 }
13820
13821 var currentChild = workInProgress.child;
13822 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
13823 workInProgress.child = newChild;
13824
13825 newChild.return = workInProgress;
13826 while (currentChild.sibling !== null) {
13827 currentChild = currentChild.sibling;
13828 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
13829 newChild.return = workInProgress;
13830 }
13831 newChild.sibling = null;
13832}
13833
13834var NO_CONTEXT = {};
13835
13836var contextStackCursor$1 = createCursor(NO_CONTEXT);
13837var contextFiberStackCursor = createCursor(NO_CONTEXT);
13838var rootInstanceStackCursor = createCursor(NO_CONTEXT);
13839
13840function requiredContext(c) {
13841 (function () {
13842 if (!(c !== NO_CONTEXT)) {
13843 {
13844 throw ReactError('Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.');
13845 }
13846 }
13847 })();
13848 return c;
13849}
13850
13851function getRootHostContainer() {
13852 var rootInstance = requiredContext(rootInstanceStackCursor.current);
13853 return rootInstance;
13854}
13855
13856function pushHostContainer(fiber, nextRootInstance) {
13857 // Push current root instance onto the stack;
13858 // This allows us to reset root when portals are popped.
13859 push(rootInstanceStackCursor, nextRootInstance, fiber);
13860 // Track the context and the Fiber that provided it.
13861 // This enables us to pop only Fibers that provide unique contexts.
13862 push(contextFiberStackCursor, fiber, fiber);
13863
13864 // Finally, we need to push the host context to the stack.
13865 // However, we can't just call getRootHostContext() and push it because
13866 // we'd have a different number of entries on the stack depending on
13867 // whether getRootHostContext() throws somewhere in renderer code or not.
13868 // So we push an empty value first. This lets us safely unwind on errors.
13869 push(contextStackCursor$1, NO_CONTEXT, fiber);
13870 var nextRootContext = getRootHostContext(nextRootInstance);
13871 // Now that we know this function doesn't throw, replace it.
13872 pop(contextStackCursor$1, fiber);
13873 push(contextStackCursor$1, nextRootContext, fiber);
13874}
13875
13876function popHostContainer(fiber) {
13877 pop(contextStackCursor$1, fiber);
13878 pop(contextFiberStackCursor, fiber);
13879 pop(rootInstanceStackCursor, fiber);
13880}
13881
13882function getHostContext() {
13883 var context = requiredContext(contextStackCursor$1.current);
13884 return context;
13885}
13886
13887function pushHostContext(fiber) {
13888 var rootInstance = requiredContext(rootInstanceStackCursor.current);
13889 var context = requiredContext(contextStackCursor$1.current);
13890 var nextContext = getChildHostContext(context, fiber.type, rootInstance);
13891
13892 // Don't push this Fiber's context unless it's unique.
13893 if (context === nextContext) {
13894 return;
13895 }
13896
13897 // Track the context and the Fiber that provided it.
13898 // This enables us to pop only Fibers that provide unique contexts.
13899 push(contextFiberStackCursor, fiber, fiber);
13900 push(contextStackCursor$1, nextContext, fiber);
13901}
13902
13903function pushHostContextForEventComponent(fiber) {
13904 var context = requiredContext(contextStackCursor$1.current);
13905 var nextContext = getChildHostContextForEventComponent(context);
13906
13907 // Don't push this Fiber's context unless it's unique.
13908 if (context === nextContext) {
13909 return;
13910 }
13911
13912 // Track the context and the Fiber that provided it.
13913 // This enables us to pop only Fibers that provide unique contexts.
13914 push(contextFiberStackCursor, fiber, fiber);
13915 push(contextStackCursor$1, nextContext, fiber);
13916}
13917
13918function pushHostContextForEventTarget(fiber) {
13919 var context = requiredContext(contextStackCursor$1.current);
13920 var eventTargetType = fiber.type.type;
13921 var nextContext = getChildHostContextForEventTarget(context, eventTargetType);
13922
13923 // Don't push this Fiber's context unless it's unique.
13924 if (context === nextContext) {
13925 return;
13926 }
13927
13928 // Track the context and the Fiber that provided it.
13929 // This enables us to pop only Fibers that provide unique contexts.
13930 push(contextFiberStackCursor, fiber, fiber);
13931 push(contextStackCursor$1, nextContext, fiber);
13932}
13933
13934function popHostContext(fiber) {
13935 // Do not pop unless this Fiber provided the current context.
13936 // pushHostContext() only pushes Fibers that provide unique contexts.
13937 if (contextFiberStackCursor.current !== fiber) {
13938 return;
13939 }
13940
13941 pop(contextStackCursor$1, fiber);
13942 pop(contextFiberStackCursor, fiber);
13943}
13944
13945var NoEffect$1 = /* */0;
13946var UnmountSnapshot = /* */2;
13947var UnmountMutation = /* */4;
13948var MountMutation = /* */8;
13949var UnmountLayout = /* */16;
13950var MountLayout = /* */32;
13951var MountPassive = /* */64;
13952var UnmountPassive = /* */128;
13953
13954var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
13955
13956
13957var didWarnAboutMismatchedHooksForComponent = void 0;
13958{
13959 didWarnAboutMismatchedHooksForComponent = new Set();
13960}
13961
13962// These are set right before calling the component.
13963var renderExpirationTime = NoWork;
13964// The work-in-progress fiber. I've named it differently to distinguish it from
13965// the work-in-progress hook.
13966var currentlyRenderingFiber$1 = null;
13967
13968// Hooks are stored as a linked list on the fiber's memoizedState field. The
13969// current hook list is the list that belongs to the current fiber. The
13970// work-in-progress hook list is a new list that will be added to the
13971// work-in-progress fiber.
13972var currentHook = null;
13973var nextCurrentHook = null;
13974var firstWorkInProgressHook = null;
13975var workInProgressHook = null;
13976var nextWorkInProgressHook = null;
13977
13978var remainingExpirationTime = NoWork;
13979var componentUpdateQueue = null;
13980var sideEffectTag = 0;
13981
13982// Updates scheduled during render will trigger an immediate re-render at the
13983// end of the current pass. We can't store these updates on the normal queue,
13984// because if the work is aborted, they should be discarded. Because this is
13985// a relatively rare case, we also don't want to add an additional field to
13986// either the hook or queue object types. So we store them in a lazily create
13987// map of queue -> render-phase updates, which are discarded once the component
13988// completes without re-rendering.
13989
13990// Whether an update was scheduled during the currently executing render pass.
13991var didScheduleRenderPhaseUpdate = false;
13992// Lazily created map of render-phase updates
13993var renderPhaseUpdates = null;
13994// Counter to prevent infinite loops.
13995var numberOfReRenders = 0;
13996var RE_RENDER_LIMIT = 25;
13997
13998// In DEV, this is the name of the currently executing primitive hook
13999var currentHookNameInDev = null;
14000
14001// In DEV, this list ensures that hooks are called in the same order between renders.
14002// The list stores the order of hooks used during the initial render (mount).
14003// Subsequent renders (updates) reference this list.
14004var hookTypesDev = null;
14005var hookTypesUpdateIndexDev = -1;
14006
14007function mountHookTypesDev() {
14008 {
14009 var hookName = currentHookNameInDev;
14010
14011 if (hookTypesDev === null) {
14012 hookTypesDev = [hookName];
14013 } else {
14014 hookTypesDev.push(hookName);
14015 }
14016 }
14017}
14018
14019function updateHookTypesDev() {
14020 {
14021 var hookName = currentHookNameInDev;
14022
14023 if (hookTypesDev !== null) {
14024 hookTypesUpdateIndexDev++;
14025 if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
14026 warnOnHookMismatchInDev(hookName);
14027 }
14028 }
14029 }
14030}
14031
14032function checkDepsAreArrayDev(deps) {
14033 {
14034 if (deps !== undefined && deps !== null && !Array.isArray(deps)) {
14035 // Verify deps, but only on mount to avoid extra checks.
14036 // It's unlikely their type would change as usually you define them inline.
14037 warning$1(false, '%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps);
14038 }
14039 }
14040}
14041
14042function warnOnHookMismatchInDev(currentHookName) {
14043 {
14044 var componentName = getComponentName(currentlyRenderingFiber$1.type);
14045 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
14046 didWarnAboutMismatchedHooksForComponent.add(componentName);
14047
14048 if (hookTypesDev !== null) {
14049 var table = '';
14050
14051 var secondColumnStart = 30;
14052
14053 for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
14054 var oldHookName = hookTypesDev[i];
14055 var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
14056
14057 var row = i + 1 + '. ' + oldHookName;
14058
14059 // Extra space so second column lines up
14060 // lol @ IE not supporting String#repeat
14061 while (row.length < secondColumnStart) {
14062 row += ' ';
14063 }
14064
14065 row += newHookName + '\n';
14066
14067 table += row;
14068 }
14069
14070 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);
14071 }
14072 }
14073 }
14074}
14075
14076function throwInvalidHookError() {
14077 (function () {
14078 {
14079 {
14080 throw ReactError('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.');
14081 }
14082 }
14083 })();
14084}
14085
14086function areHookInputsEqual(nextDeps, prevDeps) {
14087 if (prevDeps === null) {
14088 {
14089 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);
14090 }
14091 return false;
14092 }
14093
14094 {
14095 // Don't bother comparing lengths in prod because these arrays should be
14096 // passed inline.
14097 if (nextDeps.length !== prevDeps.length) {
14098 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(', ') + ']');
14099 }
14100 }
14101 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
14102 if (is(nextDeps[i], prevDeps[i])) {
14103 continue;
14104 }
14105 return false;
14106 }
14107 return true;
14108}
14109
14110function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) {
14111 renderExpirationTime = nextRenderExpirationTime;
14112 currentlyRenderingFiber$1 = workInProgress;
14113 nextCurrentHook = current !== null ? current.memoizedState : null;
14114
14115 {
14116 hookTypesDev = current !== null ? current._debugHookTypes : null;
14117 hookTypesUpdateIndexDev = -1;
14118 }
14119
14120 // The following should have already been reset
14121 // currentHook = null;
14122 // workInProgressHook = null;
14123
14124 // remainingExpirationTime = NoWork;
14125 // componentUpdateQueue = null;
14126
14127 // didScheduleRenderPhaseUpdate = false;
14128 // renderPhaseUpdates = null;
14129 // numberOfReRenders = 0;
14130 // sideEffectTag = 0;
14131
14132 // TODO Warn if no hooks are used at all during mount, then some are used during update.
14133 // Currently we will identify the update render as a mount because nextCurrentHook === null.
14134 // This is tricky because it's valid for certain types of components (e.g. React.lazy)
14135
14136 // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used.
14137 // Non-stateful hooks (e.g. context) don't get added to memoizedState,
14138 // so nextCurrentHook would be null during updates and mounts.
14139 {
14140 if (nextCurrentHook !== null) {
14141 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
14142 } else if (hookTypesDev !== null) {
14143 // This dispatcher handles an edge case where a component is updating,
14144 // but no stateful hooks have been used.
14145 // We want to match the production code behavior (which will use HooksDispatcherOnMount),
14146 // but with the extra DEV validation to ensure hooks ordering hasn't changed.
14147 // This dispatcher does that.
14148 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
14149 } else {
14150 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
14151 }
14152 }
14153
14154 var children = Component(props, refOrContext);
14155
14156 if (didScheduleRenderPhaseUpdate) {
14157 do {
14158 didScheduleRenderPhaseUpdate = false;
14159 numberOfReRenders += 1;
14160
14161 // Start over from the beginning of the list
14162 nextCurrentHook = current !== null ? current.memoizedState : null;
14163 nextWorkInProgressHook = firstWorkInProgressHook;
14164
14165 currentHook = null;
14166 workInProgressHook = null;
14167 componentUpdateQueue = null;
14168
14169 {
14170 // Also validate hook order for cascading updates.
14171 hookTypesUpdateIndexDev = -1;
14172 }
14173
14174 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
14175
14176 children = Component(props, refOrContext);
14177 } while (didScheduleRenderPhaseUpdate);
14178
14179 renderPhaseUpdates = null;
14180 numberOfReRenders = 0;
14181 }
14182
14183 // We can assume the previous dispatcher is always this one, since we set it
14184 // at the beginning of the render phase and there's no re-entrancy.
14185 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
14186
14187 var renderedWork = currentlyRenderingFiber$1;
14188
14189 renderedWork.memoizedState = firstWorkInProgressHook;
14190 renderedWork.expirationTime = remainingExpirationTime;
14191 renderedWork.updateQueue = componentUpdateQueue;
14192 renderedWork.effectTag |= sideEffectTag;
14193
14194 {
14195 renderedWork._debugHookTypes = hookTypesDev;
14196 }
14197
14198 // This check uses currentHook so that it works the same in DEV and prod bundles.
14199 // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
14200 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
14201
14202 renderExpirationTime = NoWork;
14203 currentlyRenderingFiber$1 = null;
14204
14205 currentHook = null;
14206 nextCurrentHook = null;
14207 firstWorkInProgressHook = null;
14208 workInProgressHook = null;
14209 nextWorkInProgressHook = null;
14210
14211 {
14212 currentHookNameInDev = null;
14213 hookTypesDev = null;
14214 hookTypesUpdateIndexDev = -1;
14215 }
14216
14217 remainingExpirationTime = NoWork;
14218 componentUpdateQueue = null;
14219 sideEffectTag = 0;
14220
14221 // These were reset above
14222 // didScheduleRenderPhaseUpdate = false;
14223 // renderPhaseUpdates = null;
14224 // numberOfReRenders = 0;
14225
14226 (function () {
14227 if (!!didRenderTooFewHooks) {
14228 {
14229 throw ReactError('Rendered fewer hooks than expected. This may be caused by an accidental early return statement.');
14230 }
14231 }
14232 })();
14233
14234 return children;
14235}
14236
14237function bailoutHooks(current, workInProgress, expirationTime) {
14238 workInProgress.updateQueue = current.updateQueue;
14239 workInProgress.effectTag &= ~(Passive | Update);
14240 if (current.expirationTime <= expirationTime) {
14241 current.expirationTime = NoWork;
14242 }
14243}
14244
14245function resetHooks() {
14246 // We can assume the previous dispatcher is always this one, since we set it
14247 // at the beginning of the render phase and there's no re-entrancy.
14248 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
14249
14250 // This is used to reset the state of this module when a component throws.
14251 // It's also called inside mountIndeterminateComponent if we determine the
14252 // component is a module-style component.
14253 renderExpirationTime = NoWork;
14254 currentlyRenderingFiber$1 = null;
14255
14256 currentHook = null;
14257 nextCurrentHook = null;
14258 firstWorkInProgressHook = null;
14259 workInProgressHook = null;
14260 nextWorkInProgressHook = null;
14261
14262 {
14263 hookTypesDev = null;
14264 hookTypesUpdateIndexDev = -1;
14265
14266 currentHookNameInDev = null;
14267 }
14268
14269 remainingExpirationTime = NoWork;
14270 componentUpdateQueue = null;
14271 sideEffectTag = 0;
14272
14273 didScheduleRenderPhaseUpdate = false;
14274 renderPhaseUpdates = null;
14275 numberOfReRenders = 0;
14276}
14277
14278function mountWorkInProgressHook() {
14279 var hook = {
14280 memoizedState: null,
14281
14282 baseState: null,
14283 queue: null,
14284 baseUpdate: null,
14285
14286 next: null
14287 };
14288
14289 if (workInProgressHook === null) {
14290 // This is the first hook in the list
14291 firstWorkInProgressHook = workInProgressHook = hook;
14292 } else {
14293 // Append to the end of the list
14294 workInProgressHook = workInProgressHook.next = hook;
14295 }
14296 return workInProgressHook;
14297}
14298
14299function updateWorkInProgressHook() {
14300 // This function is used both for updates and for re-renders triggered by a
14301 // render phase update. It assumes there is either a current hook we can
14302 // clone, or a work-in-progress hook from a previous render pass that we can
14303 // use as a base. When we reach the end of the base list, we must switch to
14304 // the dispatcher used for mounts.
14305 if (nextWorkInProgressHook !== null) {
14306 // There's already a work-in-progress. Reuse it.
14307 workInProgressHook = nextWorkInProgressHook;
14308 nextWorkInProgressHook = workInProgressHook.next;
14309
14310 currentHook = nextCurrentHook;
14311 nextCurrentHook = currentHook !== null ? currentHook.next : null;
14312 } else {
14313 // Clone from the current hook.
14314 (function () {
14315 if (!(nextCurrentHook !== null)) {
14316 {
14317 throw ReactError('Rendered more hooks than during the previous render.');
14318 }
14319 }
14320 })();
14321 currentHook = nextCurrentHook;
14322
14323 var newHook = {
14324 memoizedState: currentHook.memoizedState,
14325
14326 baseState: currentHook.baseState,
14327 queue: currentHook.queue,
14328 baseUpdate: currentHook.baseUpdate,
14329
14330 next: null
14331 };
14332
14333 if (workInProgressHook === null) {
14334 // This is the first hook in the list.
14335 workInProgressHook = firstWorkInProgressHook = newHook;
14336 } else {
14337 // Append to the end of the list.
14338 workInProgressHook = workInProgressHook.next = newHook;
14339 }
14340 nextCurrentHook = currentHook.next;
14341 }
14342 return workInProgressHook;
14343}
14344
14345function createFunctionComponentUpdateQueue() {
14346 return {
14347 lastEffect: null
14348 };
14349}
14350
14351function basicStateReducer(state, action) {
14352 return typeof action === 'function' ? action(state) : action;
14353}
14354
14355function mountReducer(reducer, initialArg, init) {
14356 var hook = mountWorkInProgressHook();
14357 var initialState = void 0;
14358 if (init !== undefined) {
14359 initialState = init(initialArg);
14360 } else {
14361 initialState = initialArg;
14362 }
14363 hook.memoizedState = hook.baseState = initialState;
14364 var queue = hook.queue = {
14365 last: null,
14366 dispatch: null,
14367 lastRenderedReducer: reducer,
14368 lastRenderedState: initialState
14369 };
14370 var dispatch = queue.dispatch = dispatchAction.bind(null,
14371 // Flow doesn't know this is non-null, but we do.
14372 currentlyRenderingFiber$1, queue);
14373 return [hook.memoizedState, dispatch];
14374}
14375
14376function updateReducer(reducer, initialArg, init) {
14377 var hook = updateWorkInProgressHook();
14378 var queue = hook.queue;
14379 (function () {
14380 if (!(queue !== null)) {
14381 {
14382 throw ReactError('Should have a queue. This is likely a bug in React. Please file an issue.');
14383 }
14384 }
14385 })();
14386
14387 queue.lastRenderedReducer = reducer;
14388
14389 if (numberOfReRenders > 0) {
14390 // This is a re-render. Apply the new render phase updates to the previous
14391 var _dispatch = queue.dispatch;
14392 if (renderPhaseUpdates !== null) {
14393 // Render phase updates are stored in a map of queue -> linked list
14394 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
14395 if (firstRenderPhaseUpdate !== undefined) {
14396 renderPhaseUpdates.delete(queue);
14397 var newState = hook.memoizedState;
14398 var update = firstRenderPhaseUpdate;
14399 do {
14400 // Process this render phase update. We don't have to check the
14401 // priority because it will always be the same as the current
14402 // render's.
14403 var _action = update.action;
14404 newState = reducer(newState, _action);
14405 update = update.next;
14406 } while (update !== null);
14407
14408 // Mark that the fiber performed work, but only if the new state is
14409 // different from the current state.
14410 if (!is(newState, hook.memoizedState)) {
14411 markWorkInProgressReceivedUpdate();
14412 }
14413
14414 hook.memoizedState = newState;
14415 // Don't persist the state accumlated from the render phase updates to
14416 // the base state unless the queue is empty.
14417 // TODO: Not sure if this is the desired semantics, but it's what we
14418 // do for gDSFP. I can't remember why.
14419 if (hook.baseUpdate === queue.last) {
14420 hook.baseState = newState;
14421 }
14422
14423 queue.lastRenderedState = newState;
14424
14425 return [newState, _dispatch];
14426 }
14427 }
14428 return [hook.memoizedState, _dispatch];
14429 }
14430
14431 // The last update in the entire queue
14432 var last = queue.last;
14433 // The last update that is part of the base state.
14434 var baseUpdate = hook.baseUpdate;
14435 var baseState = hook.baseState;
14436
14437 // Find the first unprocessed update.
14438 var first = void 0;
14439 if (baseUpdate !== null) {
14440 if (last !== null) {
14441 // For the first update, the queue is a circular linked list where
14442 // `queue.last.next = queue.first`. Once the first update commits, and
14443 // the `baseUpdate` is no longer empty, we can unravel the list.
14444 last.next = null;
14445 }
14446 first = baseUpdate.next;
14447 } else {
14448 first = last !== null ? last.next : null;
14449 }
14450 if (first !== null) {
14451 var _newState = baseState;
14452 var newBaseState = null;
14453 var newBaseUpdate = null;
14454 var prevUpdate = baseUpdate;
14455 var _update = first;
14456 var didSkip = false;
14457 do {
14458 var updateExpirationTime = _update.expirationTime;
14459 if (updateExpirationTime < renderExpirationTime) {
14460 // Priority is insufficient. Skip this update. If this is the first
14461 // skipped update, the previous update/state is the new base
14462 // update/state.
14463 if (!didSkip) {
14464 didSkip = true;
14465 newBaseUpdate = prevUpdate;
14466 newBaseState = _newState;
14467 }
14468 // Update the remaining priority in the queue.
14469 if (updateExpirationTime > remainingExpirationTime) {
14470 remainingExpirationTime = updateExpirationTime;
14471 }
14472 } else {
14473 // Process this update.
14474 if (_update.eagerReducer === reducer) {
14475 // If this update was processed eagerly, and its reducer matches the
14476 // current reducer, we can use the eagerly computed state.
14477 _newState = _update.eagerState;
14478 } else {
14479 var _action2 = _update.action;
14480 _newState = reducer(_newState, _action2);
14481 }
14482 }
14483 prevUpdate = _update;
14484 _update = _update.next;
14485 } while (_update !== null && _update !== first);
14486
14487 if (!didSkip) {
14488 newBaseUpdate = prevUpdate;
14489 newBaseState = _newState;
14490 }
14491
14492 // Mark that the fiber performed work, but only if the new state is
14493 // different from the current state.
14494 if (!is(_newState, hook.memoizedState)) {
14495 markWorkInProgressReceivedUpdate();
14496 }
14497
14498 hook.memoizedState = _newState;
14499 hook.baseUpdate = newBaseUpdate;
14500 hook.baseState = newBaseState;
14501
14502 queue.lastRenderedState = _newState;
14503 }
14504
14505 var dispatch = queue.dispatch;
14506 return [hook.memoizedState, dispatch];
14507}
14508
14509function mountState(initialState) {
14510 var hook = mountWorkInProgressHook();
14511 if (typeof initialState === 'function') {
14512 initialState = initialState();
14513 }
14514 hook.memoizedState = hook.baseState = initialState;
14515 var queue = hook.queue = {
14516 last: null,
14517 dispatch: null,
14518 lastRenderedReducer: basicStateReducer,
14519 lastRenderedState: initialState
14520 };
14521 var dispatch = queue.dispatch = dispatchAction.bind(null,
14522 // Flow doesn't know this is non-null, but we do.
14523 currentlyRenderingFiber$1, queue);
14524 return [hook.memoizedState, dispatch];
14525}
14526
14527function updateState(initialState) {
14528 return updateReducer(basicStateReducer, initialState);
14529}
14530
14531function pushEffect(tag, create, destroy, deps) {
14532 var effect = {
14533 tag: tag,
14534 create: create,
14535 destroy: destroy,
14536 deps: deps,
14537 // Circular
14538 next: null
14539 };
14540 if (componentUpdateQueue === null) {
14541 componentUpdateQueue = createFunctionComponentUpdateQueue();
14542 componentUpdateQueue.lastEffect = effect.next = effect;
14543 } else {
14544 var _lastEffect = componentUpdateQueue.lastEffect;
14545 if (_lastEffect === null) {
14546 componentUpdateQueue.lastEffect = effect.next = effect;
14547 } else {
14548 var firstEffect = _lastEffect.next;
14549 _lastEffect.next = effect;
14550 effect.next = firstEffect;
14551 componentUpdateQueue.lastEffect = effect;
14552 }
14553 }
14554 return effect;
14555}
14556
14557function mountRef(initialValue) {
14558 var hook = mountWorkInProgressHook();
14559 var ref = { current: initialValue };
14560 {
14561 Object.seal(ref);
14562 }
14563 hook.memoizedState = ref;
14564 return ref;
14565}
14566
14567function updateRef(initialValue) {
14568 var hook = updateWorkInProgressHook();
14569 return hook.memoizedState;
14570}
14571
14572function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
14573 var hook = mountWorkInProgressHook();
14574 var nextDeps = deps === undefined ? null : deps;
14575 sideEffectTag |= fiberEffectTag;
14576 hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps);
14577}
14578
14579function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
14580 var hook = updateWorkInProgressHook();
14581 var nextDeps = deps === undefined ? null : deps;
14582 var destroy = undefined;
14583
14584 if (currentHook !== null) {
14585 var prevEffect = currentHook.memoizedState;
14586 destroy = prevEffect.destroy;
14587 if (nextDeps !== null) {
14588 var prevDeps = prevEffect.deps;
14589 if (areHookInputsEqual(nextDeps, prevDeps)) {
14590 pushEffect(NoEffect$1, create, destroy, nextDeps);
14591 return;
14592 }
14593 }
14594 }
14595
14596 sideEffectTag |= fiberEffectTag;
14597 hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps);
14598}
14599
14600function mountEffect(create, deps) {
14601 return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
14602}
14603
14604function updateEffect(create, deps) {
14605 return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
14606}
14607
14608function mountLayoutEffect(create, deps) {
14609 return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
14610}
14611
14612function updateLayoutEffect(create, deps) {
14613 return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
14614}
14615
14616function imperativeHandleEffect(create, ref) {
14617 if (typeof ref === 'function') {
14618 var refCallback = ref;
14619 var _inst = create();
14620 refCallback(_inst);
14621 return function () {
14622 refCallback(null);
14623 };
14624 } else if (ref !== null && ref !== undefined) {
14625 var refObject = ref;
14626 {
14627 !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;
14628 }
14629 var _inst2 = create();
14630 refObject.current = _inst2;
14631 return function () {
14632 refObject.current = null;
14633 };
14634 }
14635}
14636
14637function mountImperativeHandle(ref, create, deps) {
14638 {
14639 !(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;
14640 }
14641
14642 // TODO: If deps are provided, should we skip comparing the ref itself?
14643 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
14644
14645 return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
14646}
14647
14648function updateImperativeHandle(ref, create, deps) {
14649 {
14650 !(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;
14651 }
14652
14653 // TODO: If deps are provided, should we skip comparing the ref itself?
14654 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
14655
14656 return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
14657}
14658
14659function mountDebugValue(value, formatterFn) {
14660 // This hook is normally a no-op.
14661 // The react-debug-hooks package injects its own implementation
14662 // so that e.g. DevTools can display custom hook values.
14663}
14664
14665var updateDebugValue = mountDebugValue;
14666
14667function mountCallback(callback, deps) {
14668 var hook = mountWorkInProgressHook();
14669 var nextDeps = deps === undefined ? null : deps;
14670 hook.memoizedState = [callback, nextDeps];
14671 return callback;
14672}
14673
14674function updateCallback(callback, deps) {
14675 var hook = updateWorkInProgressHook();
14676 var nextDeps = deps === undefined ? null : deps;
14677 var prevState = hook.memoizedState;
14678 if (prevState !== null) {
14679 if (nextDeps !== null) {
14680 var prevDeps = prevState[1];
14681 if (areHookInputsEqual(nextDeps, prevDeps)) {
14682 return prevState[0];
14683 }
14684 }
14685 }
14686 hook.memoizedState = [callback, nextDeps];
14687 return callback;
14688}
14689
14690function mountMemo(nextCreate, deps) {
14691 var hook = mountWorkInProgressHook();
14692 var nextDeps = deps === undefined ? null : deps;
14693 var nextValue = nextCreate();
14694 hook.memoizedState = [nextValue, nextDeps];
14695 return nextValue;
14696}
14697
14698function updateMemo(nextCreate, deps) {
14699 var hook = updateWorkInProgressHook();
14700 var nextDeps = deps === undefined ? null : deps;
14701 var prevState = hook.memoizedState;
14702 if (prevState !== null) {
14703 // Assume these are defined. If they're not, areHookInputsEqual will warn.
14704 if (nextDeps !== null) {
14705 var prevDeps = prevState[1];
14706 if (areHookInputsEqual(nextDeps, prevDeps)) {
14707 return prevState[0];
14708 }
14709 }
14710 }
14711 var nextValue = nextCreate();
14712 hook.memoizedState = [nextValue, nextDeps];
14713 return nextValue;
14714}
14715
14716function dispatchAction(fiber, queue, action) {
14717 (function () {
14718 if (!(numberOfReRenders < RE_RENDER_LIMIT)) {
14719 {
14720 throw ReactError('Too many re-renders. React limits the number of renders to prevent an infinite loop.');
14721 }
14722 }
14723 })();
14724
14725 {
14726 !(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;
14727 }
14728
14729 var alternate = fiber.alternate;
14730 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
14731 // This is a render phase update. Stash it in a lazily-created map of
14732 // queue -> linked list of updates. After this render pass, we'll restart
14733 // and apply the stashed updates on top of the work-in-progress hook.
14734 didScheduleRenderPhaseUpdate = true;
14735 var update = {
14736 expirationTime: renderExpirationTime,
14737 action: action,
14738 eagerReducer: null,
14739 eagerState: null,
14740 next: null
14741 };
14742 if (renderPhaseUpdates === null) {
14743 renderPhaseUpdates = new Map();
14744 }
14745 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
14746 if (firstRenderPhaseUpdate === undefined) {
14747 renderPhaseUpdates.set(queue, update);
14748 } else {
14749 // Append the update to the end of the list.
14750 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
14751 while (lastRenderPhaseUpdate.next !== null) {
14752 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
14753 }
14754 lastRenderPhaseUpdate.next = update;
14755 }
14756 } else {
14757 flushPassiveEffects$$1();
14758
14759 var currentTime = requestCurrentTime$$1();
14760 var _expirationTime = computeExpirationForFiber$$1(currentTime, fiber);
14761
14762 var _update2 = {
14763 expirationTime: _expirationTime,
14764 action: action,
14765 eagerReducer: null,
14766 eagerState: null,
14767 next: null
14768 };
14769
14770 // Append the update to the end of the list.
14771 var _last = queue.last;
14772 if (_last === null) {
14773 // This is the first update. Create a circular list.
14774 _update2.next = _update2;
14775 } else {
14776 var first = _last.next;
14777 if (first !== null) {
14778 // Still circular.
14779 _update2.next = first;
14780 }
14781 _last.next = _update2;
14782 }
14783 queue.last = _update2;
14784
14785 if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
14786 // The queue is currently empty, which means we can eagerly compute the
14787 // next state before entering the render phase. If the new state is the
14788 // same as the current state, we may be able to bail out entirely.
14789 var _lastRenderedReducer = queue.lastRenderedReducer;
14790 if (_lastRenderedReducer !== null) {
14791 var prevDispatcher = void 0;
14792 {
14793 prevDispatcher = ReactCurrentDispatcher$1.current;
14794 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
14795 }
14796 try {
14797 var currentState = queue.lastRenderedState;
14798 var _eagerState = _lastRenderedReducer(currentState, action);
14799 // Stash the eagerly computed state, and the reducer used to compute
14800 // it, on the update object. If the reducer hasn't changed by the
14801 // time we enter the render phase, then the eager state can be used
14802 // without calling the reducer again.
14803 _update2.eagerReducer = _lastRenderedReducer;
14804 _update2.eagerState = _eagerState;
14805 if (is(_eagerState, currentState)) {
14806 // Fast path. We can bail out without scheduling React to re-render.
14807 // It's still possible that we'll need to rebase this update later,
14808 // if the component re-renders for a different reason and by that
14809 // time the reducer has changed.
14810 return;
14811 }
14812 } catch (error) {
14813 // Suppress the error. It will throw again in the render phase.
14814 } finally {
14815 {
14816 ReactCurrentDispatcher$1.current = prevDispatcher;
14817 }
14818 }
14819 }
14820 }
14821 {
14822 // jest isn't a 'global', it's just exposed to tests via a wrapped function
14823 // further, this isn't a test file, so flow doesn't recognize the symbol. So...
14824 // $FlowExpectedError - because requirements don't give a damn about your type sigs.
14825 if ('undefined' !== typeof jest) {
14826 warnIfNotCurrentlyActingUpdatesInDev$$1(fiber);
14827 }
14828 }
14829 scheduleWork$$1(fiber, _expirationTime);
14830 }
14831}
14832
14833var ContextOnlyDispatcher = {
14834 readContext: readContext,
14835
14836 useCallback: throwInvalidHookError,
14837 useContext: throwInvalidHookError,
14838 useEffect: throwInvalidHookError,
14839 useImperativeHandle: throwInvalidHookError,
14840 useLayoutEffect: throwInvalidHookError,
14841 useMemo: throwInvalidHookError,
14842 useReducer: throwInvalidHookError,
14843 useRef: throwInvalidHookError,
14844 useState: throwInvalidHookError,
14845 useDebugValue: throwInvalidHookError
14846};
14847
14848var HooksDispatcherOnMountInDEV = null;
14849var HooksDispatcherOnMountWithHookTypesInDEV = null;
14850var HooksDispatcherOnUpdateInDEV = null;
14851var InvalidNestedHooksDispatcherOnMountInDEV = null;
14852var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
14853
14854{
14855 var warnInvalidContextAccess = function () {
14856 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().');
14857 };
14858
14859 var warnInvalidHookAccess = function () {
14860 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');
14861 };
14862
14863 HooksDispatcherOnMountInDEV = {
14864 readContext: function (context, observedBits) {
14865 return readContext(context, observedBits);
14866 },
14867 useCallback: function (callback, deps) {
14868 currentHookNameInDev = 'useCallback';
14869 mountHookTypesDev();
14870 checkDepsAreArrayDev(deps);
14871 return mountCallback(callback, deps);
14872 },
14873 useContext: function (context, observedBits) {
14874 currentHookNameInDev = 'useContext';
14875 mountHookTypesDev();
14876 return readContext(context, observedBits);
14877 },
14878 useEffect: function (create, deps) {
14879 currentHookNameInDev = 'useEffect';
14880 mountHookTypesDev();
14881 checkDepsAreArrayDev(deps);
14882 return mountEffect(create, deps);
14883 },
14884 useImperativeHandle: function (ref, create, deps) {
14885 currentHookNameInDev = 'useImperativeHandle';
14886 mountHookTypesDev();
14887 checkDepsAreArrayDev(deps);
14888 return mountImperativeHandle(ref, create, deps);
14889 },
14890 useLayoutEffect: function (create, deps) {
14891 currentHookNameInDev = 'useLayoutEffect';
14892 mountHookTypesDev();
14893 checkDepsAreArrayDev(deps);
14894 return mountLayoutEffect(create, deps);
14895 },
14896 useMemo: function (create, deps) {
14897 currentHookNameInDev = 'useMemo';
14898 mountHookTypesDev();
14899 checkDepsAreArrayDev(deps);
14900 var prevDispatcher = ReactCurrentDispatcher$1.current;
14901 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14902 try {
14903 return mountMemo(create, deps);
14904 } finally {
14905 ReactCurrentDispatcher$1.current = prevDispatcher;
14906 }
14907 },
14908 useReducer: function (reducer, initialArg, init) {
14909 currentHookNameInDev = 'useReducer';
14910 mountHookTypesDev();
14911 var prevDispatcher = ReactCurrentDispatcher$1.current;
14912 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14913 try {
14914 return mountReducer(reducer, initialArg, init);
14915 } finally {
14916 ReactCurrentDispatcher$1.current = prevDispatcher;
14917 }
14918 },
14919 useRef: function (initialValue) {
14920 currentHookNameInDev = 'useRef';
14921 mountHookTypesDev();
14922 return mountRef(initialValue);
14923 },
14924 useState: function (initialState) {
14925 currentHookNameInDev = 'useState';
14926 mountHookTypesDev();
14927 var prevDispatcher = ReactCurrentDispatcher$1.current;
14928 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14929 try {
14930 return mountState(initialState);
14931 } finally {
14932 ReactCurrentDispatcher$1.current = prevDispatcher;
14933 }
14934 },
14935 useDebugValue: function (value, formatterFn) {
14936 currentHookNameInDev = 'useDebugValue';
14937 mountHookTypesDev();
14938 return mountDebugValue(value, formatterFn);
14939 }
14940 };
14941
14942 HooksDispatcherOnMountWithHookTypesInDEV = {
14943 readContext: function (context, observedBits) {
14944 return readContext(context, observedBits);
14945 },
14946 useCallback: function (callback, deps) {
14947 currentHookNameInDev = 'useCallback';
14948 updateHookTypesDev();
14949 return mountCallback(callback, deps);
14950 },
14951 useContext: function (context, observedBits) {
14952 currentHookNameInDev = 'useContext';
14953 updateHookTypesDev();
14954 return readContext(context, observedBits);
14955 },
14956 useEffect: function (create, deps) {
14957 currentHookNameInDev = 'useEffect';
14958 updateHookTypesDev();
14959 return mountEffect(create, deps);
14960 },
14961 useImperativeHandle: function (ref, create, deps) {
14962 currentHookNameInDev = 'useImperativeHandle';
14963 updateHookTypesDev();
14964 return mountImperativeHandle(ref, create, deps);
14965 },
14966 useLayoutEffect: function (create, deps) {
14967 currentHookNameInDev = 'useLayoutEffect';
14968 updateHookTypesDev();
14969 return mountLayoutEffect(create, deps);
14970 },
14971 useMemo: function (create, deps) {
14972 currentHookNameInDev = 'useMemo';
14973 updateHookTypesDev();
14974 var prevDispatcher = ReactCurrentDispatcher$1.current;
14975 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14976 try {
14977 return mountMemo(create, deps);
14978 } finally {
14979 ReactCurrentDispatcher$1.current = prevDispatcher;
14980 }
14981 },
14982 useReducer: function (reducer, initialArg, init) {
14983 currentHookNameInDev = 'useReducer';
14984 updateHookTypesDev();
14985 var prevDispatcher = ReactCurrentDispatcher$1.current;
14986 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14987 try {
14988 return mountReducer(reducer, initialArg, init);
14989 } finally {
14990 ReactCurrentDispatcher$1.current = prevDispatcher;
14991 }
14992 },
14993 useRef: function (initialValue) {
14994 currentHookNameInDev = 'useRef';
14995 updateHookTypesDev();
14996 return mountRef(initialValue);
14997 },
14998 useState: function (initialState) {
14999 currentHookNameInDev = 'useState';
15000 updateHookTypesDev();
15001 var prevDispatcher = ReactCurrentDispatcher$1.current;
15002 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
15003 try {
15004 return mountState(initialState);
15005 } finally {
15006 ReactCurrentDispatcher$1.current = prevDispatcher;
15007 }
15008 },
15009 useDebugValue: function (value, formatterFn) {
15010 currentHookNameInDev = 'useDebugValue';
15011 updateHookTypesDev();
15012 return mountDebugValue(value, formatterFn);
15013 }
15014 };
15015
15016 HooksDispatcherOnUpdateInDEV = {
15017 readContext: function (context, observedBits) {
15018 return readContext(context, observedBits);
15019 },
15020 useCallback: function (callback, deps) {
15021 currentHookNameInDev = 'useCallback';
15022 updateHookTypesDev();
15023 return updateCallback(callback, deps);
15024 },
15025 useContext: function (context, observedBits) {
15026 currentHookNameInDev = 'useContext';
15027 updateHookTypesDev();
15028 return readContext(context, observedBits);
15029 },
15030 useEffect: function (create, deps) {
15031 currentHookNameInDev = 'useEffect';
15032 updateHookTypesDev();
15033 return updateEffect(create, deps);
15034 },
15035 useImperativeHandle: function (ref, create, deps) {
15036 currentHookNameInDev = 'useImperativeHandle';
15037 updateHookTypesDev();
15038 return updateImperativeHandle(ref, create, deps);
15039 },
15040 useLayoutEffect: function (create, deps) {
15041 currentHookNameInDev = 'useLayoutEffect';
15042 updateHookTypesDev();
15043 return updateLayoutEffect(create, deps);
15044 },
15045 useMemo: function (create, deps) {
15046 currentHookNameInDev = 'useMemo';
15047 updateHookTypesDev();
15048 var prevDispatcher = ReactCurrentDispatcher$1.current;
15049 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
15050 try {
15051 return updateMemo(create, deps);
15052 } finally {
15053 ReactCurrentDispatcher$1.current = prevDispatcher;
15054 }
15055 },
15056 useReducer: function (reducer, initialArg, init) {
15057 currentHookNameInDev = 'useReducer';
15058 updateHookTypesDev();
15059 var prevDispatcher = ReactCurrentDispatcher$1.current;
15060 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
15061 try {
15062 return updateReducer(reducer, initialArg, init);
15063 } finally {
15064 ReactCurrentDispatcher$1.current = prevDispatcher;
15065 }
15066 },
15067 useRef: function (initialValue) {
15068 currentHookNameInDev = 'useRef';
15069 updateHookTypesDev();
15070 return updateRef(initialValue);
15071 },
15072 useState: function (initialState) {
15073 currentHookNameInDev = 'useState';
15074 updateHookTypesDev();
15075 var prevDispatcher = ReactCurrentDispatcher$1.current;
15076 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
15077 try {
15078 return updateState(initialState);
15079 } finally {
15080 ReactCurrentDispatcher$1.current = prevDispatcher;
15081 }
15082 },
15083 useDebugValue: function (value, formatterFn) {
15084 currentHookNameInDev = 'useDebugValue';
15085 updateHookTypesDev();
15086 return updateDebugValue(value, formatterFn);
15087 }
15088 };
15089
15090 InvalidNestedHooksDispatcherOnMountInDEV = {
15091 readContext: function (context, observedBits) {
15092 warnInvalidContextAccess();
15093 return readContext(context, observedBits);
15094 },
15095 useCallback: function (callback, deps) {
15096 currentHookNameInDev = 'useCallback';
15097 warnInvalidHookAccess();
15098 mountHookTypesDev();
15099 return mountCallback(callback, deps);
15100 },
15101 useContext: function (context, observedBits) {
15102 currentHookNameInDev = 'useContext';
15103 warnInvalidHookAccess();
15104 mountHookTypesDev();
15105 return readContext(context, observedBits);
15106 },
15107 useEffect: function (create, deps) {
15108 currentHookNameInDev = 'useEffect';
15109 warnInvalidHookAccess();
15110 mountHookTypesDev();
15111 return mountEffect(create, deps);
15112 },
15113 useImperativeHandle: function (ref, create, deps) {
15114 currentHookNameInDev = 'useImperativeHandle';
15115 warnInvalidHookAccess();
15116 mountHookTypesDev();
15117 return mountImperativeHandle(ref, create, deps);
15118 },
15119 useLayoutEffect: function (create, deps) {
15120 currentHookNameInDev = 'useLayoutEffect';
15121 warnInvalidHookAccess();
15122 mountHookTypesDev();
15123 return mountLayoutEffect(create, deps);
15124 },
15125 useMemo: function (create, deps) {
15126 currentHookNameInDev = 'useMemo';
15127 warnInvalidHookAccess();
15128 mountHookTypesDev();
15129 var prevDispatcher = ReactCurrentDispatcher$1.current;
15130 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
15131 try {
15132 return mountMemo(create, deps);
15133 } finally {
15134 ReactCurrentDispatcher$1.current = prevDispatcher;
15135 }
15136 },
15137 useReducer: function (reducer, initialArg, init) {
15138 currentHookNameInDev = 'useReducer';
15139 warnInvalidHookAccess();
15140 mountHookTypesDev();
15141 var prevDispatcher = ReactCurrentDispatcher$1.current;
15142 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
15143 try {
15144 return mountReducer(reducer, initialArg, init);
15145 } finally {
15146 ReactCurrentDispatcher$1.current = prevDispatcher;
15147 }
15148 },
15149 useRef: function (initialValue) {
15150 currentHookNameInDev = 'useRef';
15151 warnInvalidHookAccess();
15152 mountHookTypesDev();
15153 return mountRef(initialValue);
15154 },
15155 useState: function (initialState) {
15156 currentHookNameInDev = 'useState';
15157 warnInvalidHookAccess();
15158 mountHookTypesDev();
15159 var prevDispatcher = ReactCurrentDispatcher$1.current;
15160 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
15161 try {
15162 return mountState(initialState);
15163 } finally {
15164 ReactCurrentDispatcher$1.current = prevDispatcher;
15165 }
15166 },
15167 useDebugValue: function (value, formatterFn) {
15168 currentHookNameInDev = 'useDebugValue';
15169 warnInvalidHookAccess();
15170 mountHookTypesDev();
15171 return mountDebugValue(value, formatterFn);
15172 }
15173 };
15174
15175 InvalidNestedHooksDispatcherOnUpdateInDEV = {
15176 readContext: function (context, observedBits) {
15177 warnInvalidContextAccess();
15178 return readContext(context, observedBits);
15179 },
15180 useCallback: function (callback, deps) {
15181 currentHookNameInDev = 'useCallback';
15182 warnInvalidHookAccess();
15183 updateHookTypesDev();
15184 return updateCallback(callback, deps);
15185 },
15186 useContext: function (context, observedBits) {
15187 currentHookNameInDev = 'useContext';
15188 warnInvalidHookAccess();
15189 updateHookTypesDev();
15190 return readContext(context, observedBits);
15191 },
15192 useEffect: function (create, deps) {
15193 currentHookNameInDev = 'useEffect';
15194 warnInvalidHookAccess();
15195 updateHookTypesDev();
15196 return updateEffect(create, deps);
15197 },
15198 useImperativeHandle: function (ref, create, deps) {
15199 currentHookNameInDev = 'useImperativeHandle';
15200 warnInvalidHookAccess();
15201 updateHookTypesDev();
15202 return updateImperativeHandle(ref, create, deps);
15203 },
15204 useLayoutEffect: function (create, deps) {
15205 currentHookNameInDev = 'useLayoutEffect';
15206 warnInvalidHookAccess();
15207 updateHookTypesDev();
15208 return updateLayoutEffect(create, deps);
15209 },
15210 useMemo: function (create, deps) {
15211 currentHookNameInDev = 'useMemo';
15212 warnInvalidHookAccess();
15213 updateHookTypesDev();
15214 var prevDispatcher = ReactCurrentDispatcher$1.current;
15215 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
15216 try {
15217 return updateMemo(create, deps);
15218 } finally {
15219 ReactCurrentDispatcher$1.current = prevDispatcher;
15220 }
15221 },
15222 useReducer: function (reducer, initialArg, init) {
15223 currentHookNameInDev = 'useReducer';
15224 warnInvalidHookAccess();
15225 updateHookTypesDev();
15226 var prevDispatcher = ReactCurrentDispatcher$1.current;
15227 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
15228 try {
15229 return updateReducer(reducer, initialArg, init);
15230 } finally {
15231 ReactCurrentDispatcher$1.current = prevDispatcher;
15232 }
15233 },
15234 useRef: function (initialValue) {
15235 currentHookNameInDev = 'useRef';
15236 warnInvalidHookAccess();
15237 updateHookTypesDev();
15238 return updateRef(initialValue);
15239 },
15240 useState: function (initialState) {
15241 currentHookNameInDev = 'useState';
15242 warnInvalidHookAccess();
15243 updateHookTypesDev();
15244 var prevDispatcher = ReactCurrentDispatcher$1.current;
15245 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
15246 try {
15247 return updateState(initialState);
15248 } finally {
15249 ReactCurrentDispatcher$1.current = prevDispatcher;
15250 }
15251 },
15252 useDebugValue: function (value, formatterFn) {
15253 currentHookNameInDev = 'useDebugValue';
15254 warnInvalidHookAccess();
15255 updateHookTypesDev();
15256 return updateDebugValue(value, formatterFn);
15257 }
15258 };
15259}
15260
15261// Intentionally not named imports because Rollup would use dynamic dispatch for
15262// CommonJS interop named imports.
15263var now$3 = unstable_now;
15264
15265
15266var commitTime = 0;
15267var profilerStartTime = -1;
15268
15269function getCommitTime() {
15270 return commitTime;
15271}
15272
15273function recordCommitTime() {
15274 if (!enableProfilerTimer) {
15275 return;
15276 }
15277 commitTime = now$3();
15278}
15279
15280function startProfilerTimer(fiber) {
15281 if (!enableProfilerTimer) {
15282 return;
15283 }
15284
15285 profilerStartTime = now$3();
15286
15287 if (fiber.actualStartTime < 0) {
15288 fiber.actualStartTime = now$3();
15289 }
15290}
15291
15292function stopProfilerTimerIfRunning(fiber) {
15293 if (!enableProfilerTimer) {
15294 return;
15295 }
15296 profilerStartTime = -1;
15297}
15298
15299function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
15300 if (!enableProfilerTimer) {
15301 return;
15302 }
15303
15304 if (profilerStartTime >= 0) {
15305 var elapsedTime = now$3() - profilerStartTime;
15306 fiber.actualDuration += elapsedTime;
15307 if (overrideBaseTime) {
15308 fiber.selfBaseDuration = elapsedTime;
15309 }
15310 profilerStartTime = -1;
15311 }
15312}
15313
15314// The deepest Fiber on the stack involved in a hydration context.
15315// This may have been an insertion or a hydration.
15316var hydrationParentFiber = null;
15317var nextHydratableInstance = null;
15318var isHydrating = false;
15319
15320function enterHydrationState(fiber) {
15321 if (!supportsHydration) {
15322 return false;
15323 }
15324
15325 var parentInstance = fiber.stateNode.containerInfo;
15326 nextHydratableInstance = getFirstHydratableChild(parentInstance);
15327 hydrationParentFiber = fiber;
15328 isHydrating = true;
15329 return true;
15330}
15331
15332function reenterHydrationStateFromDehydratedSuspenseInstance(fiber) {
15333 if (!supportsHydration) {
15334 return false;
15335 }
15336
15337 var suspenseInstance = fiber.stateNode;
15338 nextHydratableInstance = getNextHydratableSibling(suspenseInstance);
15339 popToNextHostParent(fiber);
15340 isHydrating = true;
15341 return true;
15342}
15343
15344function deleteHydratableInstance(returnFiber, instance) {
15345 {
15346 switch (returnFiber.tag) {
15347 case HostRoot:
15348 didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
15349 break;
15350 case HostComponent:
15351 didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
15352 break;
15353 }
15354 }
15355
15356 var childToDelete = createFiberFromHostInstanceForDeletion();
15357 childToDelete.stateNode = instance;
15358 childToDelete.return = returnFiber;
15359 childToDelete.effectTag = Deletion;
15360
15361 // This might seem like it belongs on progressedFirstDeletion. However,
15362 // these children are not part of the reconciliation list of children.
15363 // Even if we abort and rereconcile the children, that will try to hydrate
15364 // again and the nodes are still in the host tree so these will be
15365 // recreated.
15366 if (returnFiber.lastEffect !== null) {
15367 returnFiber.lastEffect.nextEffect = childToDelete;
15368 returnFiber.lastEffect = childToDelete;
15369 } else {
15370 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
15371 }
15372}
15373
15374function insertNonHydratedInstance(returnFiber, fiber) {
15375 fiber.effectTag |= Placement;
15376 {
15377 switch (returnFiber.tag) {
15378 case HostRoot:
15379 {
15380 var parentContainer = returnFiber.stateNode.containerInfo;
15381 switch (fiber.tag) {
15382 case HostComponent:
15383 var type = fiber.type;
15384 var props = fiber.pendingProps;
15385 didNotFindHydratableContainerInstance(parentContainer, type, props);
15386 break;
15387 case HostText:
15388 var text = fiber.pendingProps;
15389 didNotFindHydratableContainerTextInstance(parentContainer, text);
15390 break;
15391 case SuspenseComponent:
15392
15393 break;
15394 }
15395 break;
15396 }
15397 case HostComponent:
15398 {
15399 var parentType = returnFiber.type;
15400 var parentProps = returnFiber.memoizedProps;
15401 var parentInstance = returnFiber.stateNode;
15402 switch (fiber.tag) {
15403 case HostComponent:
15404 var _type = fiber.type;
15405 var _props = fiber.pendingProps;
15406 didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
15407 break;
15408 case HostText:
15409 var _text = fiber.pendingProps;
15410 didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
15411 break;
15412 case SuspenseComponent:
15413 didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance);
15414 break;
15415 }
15416 break;
15417 }
15418 default:
15419 return;
15420 }
15421 }
15422}
15423
15424function tryHydrate(fiber, nextInstance) {
15425 switch (fiber.tag) {
15426 case HostComponent:
15427 {
15428 var type = fiber.type;
15429 var props = fiber.pendingProps;
15430 var instance = canHydrateInstance(nextInstance, type, props);
15431 if (instance !== null) {
15432 fiber.stateNode = instance;
15433 return true;
15434 }
15435 return false;
15436 }
15437 case HostText:
15438 {
15439 var text = fiber.pendingProps;
15440 var textInstance = canHydrateTextInstance(nextInstance, text);
15441 if (textInstance !== null) {
15442 fiber.stateNode = textInstance;
15443 return true;
15444 }
15445 return false;
15446 }
15447 case SuspenseComponent:
15448 {
15449 if (enableSuspenseServerRenderer) {
15450 var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
15451 if (suspenseInstance !== null) {
15452 // Downgrade the tag to a dehydrated component until we've hydrated it.
15453 fiber.tag = DehydratedSuspenseComponent;
15454 fiber.stateNode = suspenseInstance;
15455 return true;
15456 }
15457 }
15458 return false;
15459 }
15460 default:
15461 return false;
15462 }
15463}
15464
15465function tryToClaimNextHydratableInstance(fiber) {
15466 if (!isHydrating) {
15467 return;
15468 }
15469 var nextInstance = nextHydratableInstance;
15470 if (!nextInstance) {
15471 // Nothing to hydrate. Make it an insertion.
15472 insertNonHydratedInstance(hydrationParentFiber, fiber);
15473 isHydrating = false;
15474 hydrationParentFiber = fiber;
15475 return;
15476 }
15477 var firstAttemptedInstance = nextInstance;
15478 if (!tryHydrate(fiber, nextInstance)) {
15479 // If we can't hydrate this instance let's try the next one.
15480 // We use this as a heuristic. It's based on intuition and not data so it
15481 // might be flawed or unnecessary.
15482 nextInstance = getNextHydratableSibling(firstAttemptedInstance);
15483 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
15484 // Nothing to hydrate. Make it an insertion.
15485 insertNonHydratedInstance(hydrationParentFiber, fiber);
15486 isHydrating = false;
15487 hydrationParentFiber = fiber;
15488 return;
15489 }
15490 // We matched the next one, we'll now assume that the first one was
15491 // superfluous and we'll delete it. Since we can't eagerly delete it
15492 // we'll have to schedule a deletion. To do that, this node needs a dummy
15493 // fiber associated with it.
15494 deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
15495 }
15496 hydrationParentFiber = fiber;
15497 nextHydratableInstance = getFirstHydratableChild(nextInstance);
15498}
15499
15500function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
15501 if (!supportsHydration) {
15502 (function () {
15503 {
15504 {
15505 throw ReactError('Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
15506 }
15507 }
15508 })();
15509 }
15510
15511 var instance = fiber.stateNode;
15512 var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber);
15513 // TODO: Type this specific to this type of component.
15514 fiber.updateQueue = updatePayload;
15515 // If the update payload indicates that there is a change or if there
15516 // is a new ref we mark this as an update.
15517 if (updatePayload !== null) {
15518 return true;
15519 }
15520 return false;
15521}
15522
15523function prepareToHydrateHostTextInstance(fiber) {
15524 if (!supportsHydration) {
15525 (function () {
15526 {
15527 {
15528 throw ReactError('Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
15529 }
15530 }
15531 })();
15532 }
15533
15534 var textInstance = fiber.stateNode;
15535 var textContent = fiber.memoizedProps;
15536 var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
15537 {
15538 if (shouldUpdate) {
15539 // We assume that prepareToHydrateHostTextInstance is called in a context where the
15540 // hydration parent is the parent host component of this host text.
15541 var returnFiber = hydrationParentFiber;
15542 if (returnFiber !== null) {
15543 switch (returnFiber.tag) {
15544 case HostRoot:
15545 {
15546 var parentContainer = returnFiber.stateNode.containerInfo;
15547 didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
15548 break;
15549 }
15550 case HostComponent:
15551 {
15552 var parentType = returnFiber.type;
15553 var parentProps = returnFiber.memoizedProps;
15554 var parentInstance = returnFiber.stateNode;
15555 didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
15556 break;
15557 }
15558 }
15559 }
15560 }
15561 }
15562 return shouldUpdate;
15563}
15564
15565function skipPastDehydratedSuspenseInstance(fiber) {
15566 if (!supportsHydration) {
15567 (function () {
15568 {
15569 {
15570 throw ReactError('Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
15571 }
15572 }
15573 })();
15574 }
15575 var suspenseInstance = fiber.stateNode;
15576 (function () {
15577 if (!suspenseInstance) {
15578 {
15579 throw ReactError('Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.');
15580 }
15581 }
15582 })();
15583 nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
15584}
15585
15586function popToNextHostParent(fiber) {
15587 var parent = fiber.return;
15588 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== DehydratedSuspenseComponent) {
15589 parent = parent.return;
15590 }
15591 hydrationParentFiber = parent;
15592}
15593
15594function popHydrationState(fiber) {
15595 if (!supportsHydration) {
15596 return false;
15597 }
15598 if (fiber !== hydrationParentFiber) {
15599 // We're deeper than the current hydration context, inside an inserted
15600 // tree.
15601 return false;
15602 }
15603 if (!isHydrating) {
15604 // If we're not currently hydrating but we're in a hydration context, then
15605 // we were an insertion and now need to pop up reenter hydration of our
15606 // siblings.
15607 popToNextHostParent(fiber);
15608 isHydrating = true;
15609 return false;
15610 }
15611
15612 var type = fiber.type;
15613
15614 // If we have any remaining hydratable nodes, we need to delete them now.
15615 // We only do this deeper than head and body since they tend to have random
15616 // other nodes in them. We also ignore components with pure text content in
15617 // side of them.
15618 // TODO: Better heuristic.
15619 if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
15620 var nextInstance = nextHydratableInstance;
15621 while (nextInstance) {
15622 deleteHydratableInstance(fiber, nextInstance);
15623 nextInstance = getNextHydratableSibling(nextInstance);
15624 }
15625 }
15626
15627 popToNextHostParent(fiber);
15628 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
15629 return true;
15630}
15631
15632function resetHydrationState() {
15633 if (!supportsHydration) {
15634 return;
15635 }
15636
15637 hydrationParentFiber = null;
15638 nextHydratableInstance = null;
15639 isHydrating = false;
15640}
15641
15642var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
15643
15644var didReceiveUpdate = false;
15645
15646var didWarnAboutBadClass = void 0;
15647var didWarnAboutModulePatternComponent = void 0;
15648var didWarnAboutContextTypeOnFunctionComponent = void 0;
15649var didWarnAboutGetDerivedStateOnFunctionComponent = void 0;
15650var didWarnAboutFunctionRefs = void 0;
15651var didWarnAboutReassigningProps = void 0;
15652var didWarnAboutMaxDuration = void 0;
15653
15654{
15655 didWarnAboutBadClass = {};
15656 didWarnAboutModulePatternComponent = {};
15657 didWarnAboutContextTypeOnFunctionComponent = {};
15658 didWarnAboutGetDerivedStateOnFunctionComponent = {};
15659 didWarnAboutFunctionRefs = {};
15660 didWarnAboutReassigningProps = false;
15661 didWarnAboutMaxDuration = false;
15662}
15663
15664function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) {
15665 if (current$$1 === null) {
15666 // If this is a fresh new component that hasn't been rendered yet, we
15667 // won't update its child set by applying minimal side-effects. Instead,
15668 // we will add them all to the child before it gets rendered. That means
15669 // we can optimize this reconciliation pass by not tracking side-effects.
15670 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
15671 } else {
15672 // If the current child is the same as the work in progress, it means that
15673 // we haven't yet started any work on these children. Therefore, we use
15674 // the clone algorithm to create a copy of all the current children.
15675
15676 // If we had any progressed work already, that is invalid at this point so
15677 // let's throw it out.
15678 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime);
15679 }
15680}
15681
15682function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) {
15683 // This function is fork of reconcileChildren. It's used in cases where we
15684 // want to reconcile without matching against the existing set. This has the
15685 // effect of all current children being unmounted; even if the type and key
15686 // are the same, the old child is unmounted and a new child is created.
15687 //
15688 // To do this, we're going to go through the reconcile algorithm twice. In
15689 // the first pass, we schedule a deletion for all the current children by
15690 // passing null.
15691 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime);
15692 // In the second pass, we mount the new children. The trick here is that we
15693 // pass null in place of where we usually pass the current child set. This has
15694 // the effect of remounting all children regardless of whether their their
15695 // identity matches.
15696 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
15697}
15698
15699function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
15700 // TODO: current can be non-null here even if the component
15701 // hasn't yet mounted. This happens after the first render suspends.
15702 // We'll need to figure out if this is fine or can cause issues.
15703
15704 {
15705 if (workInProgress.type !== workInProgress.elementType) {
15706 // Lazy component props can't be validated in createElement
15707 // because they're only guaranteed to be resolved here.
15708 var innerPropTypes = Component.propTypes;
15709 if (innerPropTypes) {
15710 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
15711 'prop', getComponentName(Component), getCurrentFiberStackInDev);
15712 }
15713 }
15714 }
15715
15716 var render = Component.render;
15717 var ref = workInProgress.ref;
15718
15719 // The rest is a fork of updateFunctionComponent
15720 var nextChildren = void 0;
15721 prepareToReadContext(workInProgress, renderExpirationTime);
15722 {
15723 ReactCurrentOwner$3.current = workInProgress;
15724 setCurrentPhase('render');
15725 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
15726 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
15727 // Only double-render components with Hooks
15728 if (workInProgress.memoizedState !== null) {
15729 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
15730 }
15731 }
15732 setCurrentPhase(null);
15733 }
15734
15735 if (current$$1 !== null && !didReceiveUpdate) {
15736 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
15737 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15738 }
15739
15740 // React DevTools reads this flag.
15741 workInProgress.effectTag |= PerformedWork;
15742 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15743 return workInProgress.child;
15744}
15745
15746function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
15747 if (current$$1 === null) {
15748 var type = Component.type;
15749 if (isSimpleFunctionComponent(type) && Component.compare === null &&
15750 // SimpleMemoComponent codepath doesn't resolve outer props either.
15751 Component.defaultProps === undefined) {
15752 // If this is a plain function component without default props,
15753 // and with only the default shallow comparison, we upgrade it
15754 // to a SimpleMemoComponent to allow fast path updates.
15755 workInProgress.tag = SimpleMemoComponent;
15756 workInProgress.type = type;
15757 {
15758 validateFunctionComponentInDev(workInProgress, type);
15759 }
15760 return updateSimpleMemoComponent(current$$1, workInProgress, type, nextProps, updateExpirationTime, renderExpirationTime);
15761 }
15762 {
15763 var innerPropTypes = type.propTypes;
15764 if (innerPropTypes) {
15765 // Inner memo component props aren't currently validated in createElement.
15766 // We could move it there, but we'd still need this for lazy code path.
15767 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
15768 'prop', getComponentName(type), getCurrentFiberStackInDev);
15769 }
15770 }
15771 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
15772 child.ref = workInProgress.ref;
15773 child.return = workInProgress;
15774 workInProgress.child = child;
15775 return child;
15776 }
15777 {
15778 var _type = Component.type;
15779 var _innerPropTypes = _type.propTypes;
15780 if (_innerPropTypes) {
15781 // Inner memo component props aren't currently validated in createElement.
15782 // We could move it there, but we'd still need this for lazy code path.
15783 checkPropTypes_1(_innerPropTypes, nextProps, // Resolved props
15784 'prop', getComponentName(_type), getCurrentFiberStackInDev);
15785 }
15786 }
15787 var currentChild = current$$1.child; // This is always exactly one child
15788 if (updateExpirationTime < renderExpirationTime) {
15789 // This will be the props with resolved defaultProps,
15790 // unlike current.memoizedProps which will be the unresolved ones.
15791 var prevProps = currentChild.memoizedProps;
15792 // Default to shallow comparison
15793 var compare = Component.compare;
15794 compare = compare !== null ? compare : shallowEqual;
15795 if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
15796 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15797 }
15798 }
15799 // React DevTools reads this flag.
15800 workInProgress.effectTag |= PerformedWork;
15801 var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
15802 newChild.ref = workInProgress.ref;
15803 newChild.return = workInProgress;
15804 workInProgress.child = newChild;
15805 return newChild;
15806}
15807
15808function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
15809 // TODO: current can be non-null here even if the component
15810 // hasn't yet mounted. This happens when the inner render suspends.
15811 // We'll need to figure out if this is fine or can cause issues.
15812
15813 {
15814 if (workInProgress.type !== workInProgress.elementType) {
15815 // Lazy component props can't be validated in createElement
15816 // because they're only guaranteed to be resolved here.
15817 var outerMemoType = workInProgress.elementType;
15818 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
15819 // We warn when you define propTypes on lazy()
15820 // so let's just skip over it to find memo() outer wrapper.
15821 // Inner props for memo are validated later.
15822 outerMemoType = refineResolvedLazyComponent(outerMemoType);
15823 }
15824 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
15825 if (outerPropTypes) {
15826 checkPropTypes_1(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
15827 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
15828 }
15829 // Inner propTypes will be validated in the function component path.
15830 }
15831 }
15832 if (current$$1 !== null) {
15833 var prevProps = current$$1.memoizedProps;
15834 if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
15835 didReceiveUpdate = false;
15836 if (updateExpirationTime < renderExpirationTime) {
15837 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15838 }
15839 }
15840 }
15841 return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
15842}
15843
15844function updateFragment(current$$1, workInProgress, renderExpirationTime) {
15845 var nextChildren = workInProgress.pendingProps;
15846 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15847 return workInProgress.child;
15848}
15849
15850function updateMode(current$$1, workInProgress, renderExpirationTime) {
15851 var nextChildren = workInProgress.pendingProps.children;
15852 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15853 return workInProgress.child;
15854}
15855
15856function updateProfiler(current$$1, workInProgress, renderExpirationTime) {
15857 if (enableProfilerTimer) {
15858 workInProgress.effectTag |= Update;
15859 }
15860 var nextProps = workInProgress.pendingProps;
15861 var nextChildren = nextProps.children;
15862 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15863 return workInProgress.child;
15864}
15865
15866function markRef(current$$1, workInProgress) {
15867 var ref = workInProgress.ref;
15868 if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) {
15869 // Schedule a Ref effect
15870 workInProgress.effectTag |= Ref;
15871 }
15872}
15873
15874function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
15875 {
15876 if (workInProgress.type !== workInProgress.elementType) {
15877 // Lazy component props can't be validated in createElement
15878 // because they're only guaranteed to be resolved here.
15879 var innerPropTypes = Component.propTypes;
15880 if (innerPropTypes) {
15881 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
15882 'prop', getComponentName(Component), getCurrentFiberStackInDev);
15883 }
15884 }
15885 }
15886
15887 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
15888 var context = getMaskedContext(workInProgress, unmaskedContext);
15889
15890 var nextChildren = void 0;
15891 prepareToReadContext(workInProgress, renderExpirationTime);
15892 {
15893 ReactCurrentOwner$3.current = workInProgress;
15894 setCurrentPhase('render');
15895 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
15896 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
15897 // Only double-render components with Hooks
15898 if (workInProgress.memoizedState !== null) {
15899 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
15900 }
15901 }
15902 setCurrentPhase(null);
15903 }
15904
15905 if (current$$1 !== null && !didReceiveUpdate) {
15906 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
15907 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15908 }
15909
15910 // React DevTools reads this flag.
15911 workInProgress.effectTag |= PerformedWork;
15912 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15913 return workInProgress.child;
15914}
15915
15916function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
15917 {
15918 if (workInProgress.type !== workInProgress.elementType) {
15919 // Lazy component props can't be validated in createElement
15920 // because they're only guaranteed to be resolved here.
15921 var innerPropTypes = Component.propTypes;
15922 if (innerPropTypes) {
15923 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
15924 'prop', getComponentName(Component), getCurrentFiberStackInDev);
15925 }
15926 }
15927 }
15928
15929 // Push context providers early to prevent context stack mismatches.
15930 // During mounting we don't know the child context yet as the instance doesn't exist.
15931 // We will invalidate the child context in finishClassComponent() right after rendering.
15932 var hasContext = void 0;
15933 if (isContextProvider(Component)) {
15934 hasContext = true;
15935 pushContextProvider(workInProgress);
15936 } else {
15937 hasContext = false;
15938 }
15939 prepareToReadContext(workInProgress, renderExpirationTime);
15940
15941 var instance = workInProgress.stateNode;
15942 var shouldUpdate = void 0;
15943 if (instance === null) {
15944 if (current$$1 !== null) {
15945 // An class component without an instance only mounts if it suspended
15946 // inside a non- concurrent tree, in an inconsistent state. We want to
15947 // tree it like a new mount, even though an empty version of it already
15948 // committed. Disconnect the alternate pointers.
15949 current$$1.alternate = null;
15950 workInProgress.alternate = null;
15951 // Since this is conceptually a new fiber, schedule a Placement effect
15952 workInProgress.effectTag |= Placement;
15953 }
15954 // In the initial pass we might need to construct the instance.
15955 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
15956 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
15957 shouldUpdate = true;
15958 } else if (current$$1 === null) {
15959 // In a resume, we'll already have an instance we can reuse.
15960 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
15961 } else {
15962 shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
15963 }
15964 var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
15965 {
15966 var inst = workInProgress.stateNode;
15967 if (inst.props !== nextProps) {
15968 !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;
15969 didWarnAboutReassigningProps = true;
15970 }
15971 }
15972 return nextUnitOfWork;
15973}
15974
15975function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
15976 // Refs should update even if shouldComponentUpdate returns false
15977 markRef(current$$1, workInProgress);
15978
15979 var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
15980
15981 if (!shouldUpdate && !didCaptureError) {
15982 // Context providers should defer to sCU for rendering
15983 if (hasContext) {
15984 invalidateContextProvider(workInProgress, Component, false);
15985 }
15986
15987 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15988 }
15989
15990 var instance = workInProgress.stateNode;
15991
15992 // Rerender
15993 ReactCurrentOwner$3.current = workInProgress;
15994 var nextChildren = void 0;
15995 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
15996 // If we captured an error, but getDerivedStateFrom catch is not defined,
15997 // unmount all the children. componentDidCatch will schedule an update to
15998 // re-render a fallback. This is temporary until we migrate everyone to
15999 // the new API.
16000 // TODO: Warn in a future release.
16001 nextChildren = null;
16002
16003 if (enableProfilerTimer) {
16004 stopProfilerTimerIfRunning(workInProgress);
16005 }
16006 } else {
16007 {
16008 setCurrentPhase('render');
16009 nextChildren = instance.render();
16010 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
16011 instance.render();
16012 }
16013 setCurrentPhase(null);
16014 }
16015 }
16016
16017 // React DevTools reads this flag.
16018 workInProgress.effectTag |= PerformedWork;
16019 if (current$$1 !== null && didCaptureError) {
16020 // If we're recovering from an error, reconcile without reusing any of
16021 // the existing children. Conceptually, the normal children and the children
16022 // that are shown on error are two different sets, so we shouldn't reuse
16023 // normal children even if their identities match.
16024 forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime);
16025 } else {
16026 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
16027 }
16028
16029 // Memoize state using the values we just used to render.
16030 // TODO: Restructure so we never read values from the instance.
16031 workInProgress.memoizedState = instance.state;
16032
16033 // The context might have changed so we need to recalculate it.
16034 if (hasContext) {
16035 invalidateContextProvider(workInProgress, Component, true);
16036 }
16037
16038 return workInProgress.child;
16039}
16040
16041function pushHostRootContext(workInProgress) {
16042 var root = workInProgress.stateNode;
16043 if (root.pendingContext) {
16044 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
16045 } else if (root.context) {
16046 // Should always be set
16047 pushTopLevelContextObject(workInProgress, root.context, false);
16048 }
16049 pushHostContainer(workInProgress, root.containerInfo);
16050}
16051
16052function updateHostRoot(current$$1, workInProgress, renderExpirationTime) {
16053 pushHostRootContext(workInProgress);
16054 var updateQueue = workInProgress.updateQueue;
16055 (function () {
16056 if (!(updateQueue !== null)) {
16057 {
16058 throw ReactError('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.');
16059 }
16060 }
16061 })();
16062 var nextProps = workInProgress.pendingProps;
16063 var prevState = workInProgress.memoizedState;
16064 var prevChildren = prevState !== null ? prevState.element : null;
16065 processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
16066 var nextState = workInProgress.memoizedState;
16067 // Caution: React DevTools currently depends on this property
16068 // being called "element".
16069 var nextChildren = nextState.element;
16070 if (nextChildren === prevChildren) {
16071 // If the state is the same as before, that's a bailout because we had
16072 // no work that expires at this time.
16073 resetHydrationState();
16074 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
16075 }
16076 var root = workInProgress.stateNode;
16077 if ((current$$1 === null || current$$1.child === null) && root.hydrate && enterHydrationState(workInProgress)) {
16078 // If we don't have any current children this might be the first pass.
16079 // We always try to hydrate. If this isn't a hydration pass there won't
16080 // be any children to hydrate which is effectively the same thing as
16081 // not hydrating.
16082
16083 // This is a bit of a hack. We track the host root as a placement to
16084 // know that we're currently in a mounting state. That way isMounted
16085 // works as expected. We must reset this before committing.
16086 // TODO: Delete this when we delete isMounted and findDOMNode.
16087 workInProgress.effectTag |= Placement;
16088
16089 // Ensure that children mount into this root without tracking
16090 // side-effects. This ensures that we don't store Placement effects on
16091 // nodes that will be hydrated.
16092 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
16093 } else {
16094 // Otherwise reset hydration state in case we aborted and resumed another
16095 // root.
16096 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
16097 resetHydrationState();
16098 }
16099 return workInProgress.child;
16100}
16101
16102function updateHostComponent(current$$1, workInProgress, renderExpirationTime) {
16103 pushHostContext(workInProgress);
16104
16105 if (current$$1 === null) {
16106 tryToClaimNextHydratableInstance(workInProgress);
16107 }
16108
16109 var type = workInProgress.type;
16110 var nextProps = workInProgress.pendingProps;
16111 var prevProps = current$$1 !== null ? current$$1.memoizedProps : null;
16112
16113 var nextChildren = nextProps.children;
16114 var isDirectTextChild = shouldSetTextContent(type, nextProps);
16115
16116 if (isDirectTextChild) {
16117 // We special case a direct text child of a host node. This is a common
16118 // case. We won't handle it as a reified child. We will instead handle
16119 // this in the host environment that also have access to this prop. That
16120 // avoids allocating another HostText fiber and traversing it.
16121 nextChildren = null;
16122 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
16123 // If we're switching from a direct text child to a normal child, or to
16124 // empty, we need to schedule the text content to be reset.
16125 workInProgress.effectTag |= ContentReset;
16126 }
16127
16128 markRef(current$$1, workInProgress);
16129
16130 // Check the host config to see if the children are offscreen/hidden.
16131 if (renderExpirationTime !== Never && workInProgress.mode & ConcurrentMode && shouldDeprioritizeSubtree(type, nextProps)) {
16132 // Schedule this fiber to re-render at offscreen priority. Then bailout.
16133 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
16134 return null;
16135 }
16136
16137 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
16138 return workInProgress.child;
16139}
16140
16141function updateHostText(current$$1, workInProgress) {
16142 if (current$$1 === null) {
16143 tryToClaimNextHydratableInstance(workInProgress);
16144 }
16145 // Nothing to do here. This is terminal. We'll do the completion step
16146 // immediately after.
16147 return null;
16148}
16149
16150function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
16151 if (_current !== null) {
16152 // An lazy component only mounts if it suspended inside a non-
16153 // concurrent tree, in an inconsistent state. We want to treat it like
16154 // a new mount, even though an empty version of it already committed.
16155 // Disconnect the alternate pointers.
16156 _current.alternate = null;
16157 workInProgress.alternate = null;
16158 // Since this is conceptually a new fiber, schedule a Placement effect
16159 workInProgress.effectTag |= Placement;
16160 }
16161
16162 var props = workInProgress.pendingProps;
16163 // We can't start a User Timing measurement with correct label yet.
16164 // Cancel and resume right after we know the tag.
16165 cancelWorkTimer(workInProgress);
16166 var Component = readLazyComponentType(elementType);
16167 // Store the unwrapped component in the type.
16168 workInProgress.type = Component;
16169 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
16170 startWorkTimer(workInProgress);
16171 var resolvedProps = resolveDefaultProps(Component, props);
16172 var child = void 0;
16173 switch (resolvedTag) {
16174 case FunctionComponent:
16175 {
16176 {
16177 validateFunctionComponentInDev(workInProgress, Component);
16178 }
16179 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
16180 break;
16181 }
16182 case ClassComponent:
16183 {
16184 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
16185 break;
16186 }
16187 case ForwardRef:
16188 {
16189 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
16190 break;
16191 }
16192 case MemoComponent:
16193 {
16194 {
16195 if (workInProgress.type !== workInProgress.elementType) {
16196 var outerPropTypes = Component.propTypes;
16197 if (outerPropTypes) {
16198 checkPropTypes_1(outerPropTypes, resolvedProps, // Resolved for outer only
16199 'prop', getComponentName(Component), getCurrentFiberStackInDev);
16200 }
16201 }
16202 }
16203 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
16204 updateExpirationTime, renderExpirationTime);
16205 break;
16206 }
16207 default:
16208 {
16209 var hint = '';
16210 {
16211 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
16212 hint = ' Did you wrap a component in React.lazy() more than once?';
16213 }
16214 }
16215 // This message intentionally doesn't mention ForwardRef or MemoComponent
16216 // because the fact that it's a separate type of work is an
16217 // implementation detail.
16218 (function () {
16219 {
16220 {
16221 throw ReactError('Element type is invalid. Received a promise that resolves to: ' + Component + '. Lazy element type must resolve to a class or function.' + hint);
16222 }
16223 }
16224 })();
16225 }
16226 }
16227 return child;
16228}
16229
16230function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
16231 if (_current !== null) {
16232 // An incomplete component only mounts if it suspended inside a non-
16233 // concurrent tree, in an inconsistent state. We want to treat it like
16234 // a new mount, even though an empty version of it already committed.
16235 // Disconnect the alternate pointers.
16236 _current.alternate = null;
16237 workInProgress.alternate = null;
16238 // Since this is conceptually a new fiber, schedule a Placement effect
16239 workInProgress.effectTag |= Placement;
16240 }
16241
16242 // Promote the fiber to a class and try rendering again.
16243 workInProgress.tag = ClassComponent;
16244
16245 // The rest of this function is a fork of `updateClassComponent`
16246
16247 // Push context providers early to prevent context stack mismatches.
16248 // During mounting we don't know the child context yet as the instance doesn't exist.
16249 // We will invalidate the child context in finishClassComponent() right after rendering.
16250 var hasContext = void 0;
16251 if (isContextProvider(Component)) {
16252 hasContext = true;
16253 pushContextProvider(workInProgress);
16254 } else {
16255 hasContext = false;
16256 }
16257 prepareToReadContext(workInProgress, renderExpirationTime);
16258
16259 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
16260 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
16261
16262 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
16263}
16264
16265function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
16266 if (_current !== null) {
16267 // An indeterminate component only mounts if it suspended inside a non-
16268 // concurrent tree, in an inconsistent state. We want to treat it like
16269 // a new mount, even though an empty version of it already committed.
16270 // Disconnect the alternate pointers.
16271 _current.alternate = null;
16272 workInProgress.alternate = null;
16273 // Since this is conceptually a new fiber, schedule a Placement effect
16274 workInProgress.effectTag |= Placement;
16275 }
16276
16277 var props = workInProgress.pendingProps;
16278 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
16279 var context = getMaskedContext(workInProgress, unmaskedContext);
16280
16281 prepareToReadContext(workInProgress, renderExpirationTime);
16282
16283 var value = void 0;
16284
16285 {
16286 if (Component.prototype && typeof Component.prototype.render === 'function') {
16287 var componentName = getComponentName(Component) || 'Unknown';
16288
16289 if (!didWarnAboutBadClass[componentName]) {
16290 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);
16291 didWarnAboutBadClass[componentName] = true;
16292 }
16293 }
16294
16295 if (workInProgress.mode & StrictMode) {
16296 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
16297 }
16298
16299 ReactCurrentOwner$3.current = workInProgress;
16300 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
16301 }
16302 // React DevTools reads this flag.
16303 workInProgress.effectTag |= PerformedWork;
16304
16305 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
16306 {
16307 var _componentName = getComponentName(Component) || 'Unknown';
16308 if (!didWarnAboutModulePatternComponent[_componentName]) {
16309 warningWithoutStack$1(false, 'The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);
16310 didWarnAboutModulePatternComponent[_componentName] = true;
16311 }
16312 }
16313
16314 // Proceed under the assumption that this is a class instance
16315 workInProgress.tag = ClassComponent;
16316
16317 // Throw out any hooks that were used.
16318 resetHooks();
16319
16320 // Push context providers early to prevent context stack mismatches.
16321 // During mounting we don't know the child context yet as the instance doesn't exist.
16322 // We will invalidate the child context in finishClassComponent() right after rendering.
16323 var hasContext = false;
16324 if (isContextProvider(Component)) {
16325 hasContext = true;
16326 pushContextProvider(workInProgress);
16327 } else {
16328 hasContext = false;
16329 }
16330
16331 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
16332
16333 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
16334 if (typeof getDerivedStateFromProps === 'function') {
16335 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
16336 }
16337
16338 adoptClassInstance(workInProgress, value);
16339 mountClassInstance(workInProgress, Component, props, renderExpirationTime);
16340 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
16341 } else {
16342 // Proceed under the assumption that this is a function component
16343 workInProgress.tag = FunctionComponent;
16344 {
16345 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
16346 // Only double-render components with Hooks
16347 if (workInProgress.memoizedState !== null) {
16348 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
16349 }
16350 }
16351 }
16352 reconcileChildren(null, workInProgress, value, renderExpirationTime);
16353 {
16354 validateFunctionComponentInDev(workInProgress, Component);
16355 }
16356 return workInProgress.child;
16357 }
16358}
16359
16360function validateFunctionComponentInDev(workInProgress, Component) {
16361 if (Component) {
16362 !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
16363 }
16364 if (workInProgress.ref !== null) {
16365 var info = '';
16366 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
16367 if (ownerName) {
16368 info += '\n\nCheck the render method of `' + ownerName + '`.';
16369 }
16370
16371 var warningKey = ownerName || workInProgress._debugID || '';
16372 var debugSource = workInProgress._debugSource;
16373 if (debugSource) {
16374 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
16375 }
16376 if (!didWarnAboutFunctionRefs[warningKey]) {
16377 didWarnAboutFunctionRefs[warningKey] = true;
16378 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);
16379 }
16380 }
16381
16382 if (typeof Component.getDerivedStateFromProps === 'function') {
16383 var componentName = getComponentName(Component) || 'Unknown';
16384
16385 if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) {
16386 warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', componentName);
16387 didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true;
16388 }
16389 }
16390
16391 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
16392 var _componentName2 = getComponentName(Component) || 'Unknown';
16393
16394 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName2]) {
16395 warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName2);
16396 didWarnAboutContextTypeOnFunctionComponent[_componentName2] = true;
16397 }
16398 }
16399}
16400
16401function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
16402 var mode = workInProgress.mode;
16403 var nextProps = workInProgress.pendingProps;
16404
16405 // We should attempt to render the primary children unless this boundary
16406 // already suspended during this render (`alreadyCaptured` is true).
16407 var nextState = workInProgress.memoizedState;
16408
16409 var nextDidTimeout = void 0;
16410 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
16411 // This is the first attempt.
16412 nextState = null;
16413 nextDidTimeout = false;
16414 } else {
16415 // Something in this boundary's subtree already suspended. Switch to
16416 // rendering the fallback children.
16417 nextState = {
16418 timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork
16419 };
16420 nextDidTimeout = true;
16421 workInProgress.effectTag &= ~DidCapture;
16422 }
16423
16424 {
16425 if ('maxDuration' in nextProps) {
16426 if (!didWarnAboutMaxDuration) {
16427 didWarnAboutMaxDuration = true;
16428 warning$1(false, 'maxDuration has been removed from React. ' + 'Remove the maxDuration prop.');
16429 }
16430 }
16431 }
16432
16433 // This next part is a bit confusing. If the children timeout, we switch to
16434 // showing the fallback children in place of the "primary" children.
16435 // However, we don't want to delete the primary children because then their
16436 // state will be lost (both the React state and the host state, e.g.
16437 // uncontrolled form inputs). Instead we keep them mounted and hide them.
16438 // Both the fallback children AND the primary children are rendered at the
16439 // same time. Once the primary children are un-suspended, we can delete
16440 // the fallback children — don't need to preserve their state.
16441 //
16442 // The two sets of children are siblings in the host environment, but
16443 // semantically, for purposes of reconciliation, they are two separate sets.
16444 // So we store them using two fragment fibers.
16445 //
16446 // However, we want to avoid allocating extra fibers for every placeholder.
16447 // They're only necessary when the children time out, because that's the
16448 // only time when both sets are mounted.
16449 //
16450 // So, the extra fragment fibers are only used if the children time out.
16451 // Otherwise, we render the primary children directly. This requires some
16452 // custom reconciliation logic to preserve the state of the primary
16453 // children. It's essentially a very basic form of re-parenting.
16454
16455 // `child` points to the child fiber. In the normal case, this is the first
16456 // fiber of the primary children set. In the timed-out case, it's a
16457 // a fragment fiber containing the primary children.
16458 var child = void 0;
16459 // `next` points to the next fiber React should render. In the normal case,
16460 // it's the same as `child`: the first fiber of the primary children set.
16461 // In the timed-out case, it's a fragment fiber containing the *fallback*
16462 // children -- we skip over the primary children entirely.
16463 var next = void 0;
16464 if (current$$1 === null) {
16465 if (enableSuspenseServerRenderer) {
16466 // If we're currently hydrating, try to hydrate this boundary.
16467 // But only if this has a fallback.
16468 if (nextProps.fallback !== undefined) {
16469 tryToClaimNextHydratableInstance(workInProgress);
16470 // This could've changed the tag if this was a dehydrated suspense component.
16471 if (workInProgress.tag === DehydratedSuspenseComponent) {
16472 return updateDehydratedSuspenseComponent(null, workInProgress, renderExpirationTime);
16473 }
16474 }
16475 }
16476
16477 // This is the initial mount. This branch is pretty simple because there's
16478 // no previous state that needs to be preserved.
16479 if (nextDidTimeout) {
16480 // Mount separate fragments for primary and fallback children.
16481 var nextFallbackChildren = nextProps.fallback;
16482 var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
16483
16484 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
16485 // Outside of concurrent mode, we commit the effects from the
16486 var progressedState = workInProgress.memoizedState;
16487 var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
16488 primaryChildFragment.child = progressedPrimaryChild;
16489 }
16490
16491 var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
16492 primaryChildFragment.sibling = fallbackChildFragment;
16493 child = primaryChildFragment;
16494 // Skip the primary children, and continue working on the
16495 // fallback children.
16496 next = fallbackChildFragment;
16497 child.return = next.return = workInProgress;
16498 } else {
16499 // Mount the primary children without an intermediate fragment fiber.
16500 var nextPrimaryChildren = nextProps.children;
16501 child = next = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
16502 }
16503 } else {
16504 // This is an update. This branch is more complicated because we need to
16505 // ensure the state of the primary children is preserved.
16506 var prevState = current$$1.memoizedState;
16507 var prevDidTimeout = prevState !== null;
16508 if (prevDidTimeout) {
16509 // The current tree already timed out. That means each child set is
16510 var currentPrimaryChildFragment = current$$1.child;
16511 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
16512 if (nextDidTimeout) {
16513 // Still timed out. Reuse the current primary children by cloning
16514 // its fragment. We're going to skip over these entirely.
16515 var _nextFallbackChildren = nextProps.fallback;
16516 var _primaryChildFragment = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
16517
16518 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
16519 // Outside of concurrent mode, we commit the effects from the
16520 var _progressedState = workInProgress.memoizedState;
16521 var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
16522 if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
16523 _primaryChildFragment.child = _progressedPrimaryChild;
16524 }
16525 }
16526
16527 // Because primaryChildFragment is a new fiber that we're inserting as the
16528 // parent of a new tree, we need to set its treeBaseDuration.
16529 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
16530 // treeBaseDuration is the sum of all the child tree base durations.
16531 var treeBaseDuration = 0;
16532 var hiddenChild = _primaryChildFragment.child;
16533 while (hiddenChild !== null) {
16534 treeBaseDuration += hiddenChild.treeBaseDuration;
16535 hiddenChild = hiddenChild.sibling;
16536 }
16537 _primaryChildFragment.treeBaseDuration = treeBaseDuration;
16538 }
16539
16540 // Clone the fallback child fragment, too. These we'll continue
16541 // working on.
16542 var _fallbackChildFragment = _primaryChildFragment.sibling = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren, currentFallbackChildFragment.expirationTime);
16543 child = _primaryChildFragment;
16544 _primaryChildFragment.childExpirationTime = NoWork;
16545 // Skip the primary children, and continue working on the
16546 // fallback children.
16547 next = _fallbackChildFragment;
16548 child.return = next.return = workInProgress;
16549 } else {
16550 // No longer suspended. Switch back to showing the primary children,
16551 // and remove the intermediate fragment fiber.
16552 var _nextPrimaryChildren = nextProps.children;
16553 var currentPrimaryChild = currentPrimaryChildFragment.child;
16554 var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime);
16555
16556 // If this render doesn't suspend, we need to delete the fallback
16557 // children. Wait until the complete phase, after we've confirmed the
16558 // fallback is no longer needed.
16559 // TODO: Would it be better to store the fallback fragment on
16560 // the stateNode?
16561
16562 // Continue rendering the children, like we normally do.
16563 child = next = primaryChild;
16564 }
16565 } else {
16566 // The current tree has not already timed out. That means the primary
16567 // children are not wrapped in a fragment fiber.
16568 var _currentPrimaryChild = current$$1.child;
16569 if (nextDidTimeout) {
16570 // Timed out. Wrap the children in a fragment fiber to keep them
16571 // separate from the fallback children.
16572 var _nextFallbackChildren2 = nextProps.fallback;
16573 var _primaryChildFragment2 = createFiberFromFragment(
16574 // It shouldn't matter what the pending props are because we aren't
16575 // going to render this fragment.
16576 null, mode, NoWork, null);
16577 _primaryChildFragment2.child = _currentPrimaryChild;
16578
16579 // Even though we're creating a new fiber, there are no new children,
16580 // because we're reusing an already mounted tree. So we don't need to
16581 // schedule a placement.
16582 // primaryChildFragment.effectTag |= Placement;
16583
16584 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
16585 // Outside of concurrent mode, we commit the effects from the
16586 var _progressedState2 = workInProgress.memoizedState;
16587 var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
16588 _primaryChildFragment2.child = _progressedPrimaryChild2;
16589 }
16590
16591 // Because primaryChildFragment is a new fiber that we're inserting as the
16592 // parent of a new tree, we need to set its treeBaseDuration.
16593 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
16594 // treeBaseDuration is the sum of all the child tree base durations.
16595 var _treeBaseDuration = 0;
16596 var _hiddenChild = _primaryChildFragment2.child;
16597 while (_hiddenChild !== null) {
16598 _treeBaseDuration += _hiddenChild.treeBaseDuration;
16599 _hiddenChild = _hiddenChild.sibling;
16600 }
16601 _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
16602 }
16603
16604 // Create a fragment from the fallback children, too.
16605 var _fallbackChildFragment2 = _primaryChildFragment2.sibling = createFiberFromFragment(_nextFallbackChildren2, mode, renderExpirationTime, null);
16606 _fallbackChildFragment2.effectTag |= Placement;
16607 child = _primaryChildFragment2;
16608 _primaryChildFragment2.childExpirationTime = NoWork;
16609 // Skip the primary children, and continue working on the
16610 // fallback children.
16611 next = _fallbackChildFragment2;
16612 child.return = next.return = workInProgress;
16613 } else {
16614 // Still haven't timed out. Continue rendering the children, like we
16615 // normally do.
16616 var _nextPrimaryChildren2 = nextProps.children;
16617 next = child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
16618 }
16619 }
16620 workInProgress.stateNode = current$$1.stateNode;
16621 }
16622
16623 workInProgress.memoizedState = nextState;
16624 workInProgress.child = child;
16625 return next;
16626}
16627
16628function retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime) {
16629 // Detach from the current dehydrated boundary.
16630 current$$1.alternate = null;
16631 workInProgress.alternate = null;
16632
16633 // Insert a deletion in the effect list.
16634 var returnFiber = workInProgress.return;
16635 (function () {
16636 if (!(returnFiber !== null)) {
16637 {
16638 throw ReactError('Suspense boundaries are never on the root. This is probably a bug in React.');
16639 }
16640 }
16641 })();
16642 var last = returnFiber.lastEffect;
16643 if (last !== null) {
16644 last.nextEffect = current$$1;
16645 returnFiber.lastEffect = current$$1;
16646 } else {
16647 returnFiber.firstEffect = returnFiber.lastEffect = current$$1;
16648 }
16649 current$$1.nextEffect = null;
16650 current$$1.effectTag = Deletion;
16651
16652 // Upgrade this work in progress to a real Suspense component.
16653 workInProgress.tag = SuspenseComponent;
16654 workInProgress.stateNode = null;
16655 workInProgress.memoizedState = null;
16656 // This is now an insertion.
16657 workInProgress.effectTag |= Placement;
16658 // Retry as a real Suspense component.
16659 return updateSuspenseComponent(null, workInProgress, renderExpirationTime);
16660}
16661
16662function updateDehydratedSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
16663 var suspenseInstance = workInProgress.stateNode;
16664 if (current$$1 === null) {
16665 // During the first pass, we'll bail out and not drill into the children.
16666 // Instead, we'll leave the content in place and try to hydrate it later.
16667 if (isSuspenseInstanceFallback(suspenseInstance)) {
16668 // This is a client-only boundary. Since we won't get any content from the server
16669 // for this, we need to schedule that at a higher priority based on when it would
16670 // have timed out. In theory we could render it in this pass but it would have the
16671 // wrong priority associated with it and will prevent hydration of parent path.
16672 // Instead, we'll leave work left on it to render it in a separate commit.
16673
16674 // TODO This time should be the time at which the server rendered response that is
16675 // a parent to this boundary was displayed. However, since we currently don't have
16676 // a protocol to transfer that time, we'll just estimate it by using the current
16677 // time. This will mean that Suspense timeouts are slightly shifted to later than
16678 // they should be.
16679 var serverDisplayTime = requestCurrentTime$$1();
16680 // Schedule a normal pri update to render this content.
16681 workInProgress.expirationTime = computeAsyncExpiration(serverDisplayTime);
16682 } else {
16683 // We'll continue hydrating the rest at offscreen priority since we'll already
16684 // be showing the right content coming from the server, it is no rush.
16685 workInProgress.expirationTime = Never;
16686 }
16687 return null;
16688 }
16689 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
16690 // Something suspended. Leave the existing children in place.
16691 // TODO: In non-concurrent mode, should we commit the nodes we have hydrated so far?
16692 workInProgress.child = null;
16693 return null;
16694 }
16695 if (isSuspenseInstanceFallback(suspenseInstance)) {
16696 // This boundary is in a permanent fallback state. In this case, we'll never
16697 // get an update and we'll never be able to hydrate the final content. Let's just try the
16698 // client side render instead.
16699 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
16700 }
16701 // We use childExpirationTime to indicate that a child might depend on context, so if
16702 // any context has changed, we need to treat is as if the input might have changed.
16703 var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime;
16704 if (didReceiveUpdate || hasContextChanged$$1) {
16705 // This boundary has changed since the first render. This means that we are now unable to
16706 // hydrate it. We might still be able to hydrate it using an earlier expiration time but
16707 // during this render we can't. Instead, we're going to delete the whole subtree and
16708 // instead inject a new real Suspense boundary to take its place, which may render content
16709 // or fallback. The real Suspense boundary will suspend for a while so we have some time
16710 // to ensure it can produce real content, but all state and pending events will be lost.
16711 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
16712 } else if (isSuspenseInstancePending(suspenseInstance)) {
16713 // This component is still pending more data from the server, so we can't hydrate its
16714 // content. We treat it as if this component suspended itself. It might seem as if
16715 // we could just try to render it client-side instead. However, this will perform a
16716 // lot of unnecessary work and is unlikely to complete since it often will suspend
16717 // on missing data anyway. Additionally, the server might be able to render more
16718 // than we can on the client yet. In that case we'd end up with more fallback states
16719 // on the client than if we just leave it alone. If the server times out or errors
16720 // these should update this boundary to the permanent Fallback state instead.
16721 // Mark it as having captured (i.e. suspended).
16722 workInProgress.effectTag |= DidCapture;
16723 // Leave the children in place. I.e. empty.
16724 workInProgress.child = null;
16725 // Register a callback to retry this boundary once the server has sent the result.
16726 registerSuspenseInstanceRetry(suspenseInstance, retryTimedOutBoundary$$1.bind(null, current$$1));
16727 return null;
16728 } else {
16729 // This is the first attempt.
16730 reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress);
16731 var nextProps = workInProgress.pendingProps;
16732 var nextChildren = nextProps.children;
16733 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
16734 return workInProgress.child;
16735 }
16736}
16737
16738function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) {
16739 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
16740 var nextChildren = workInProgress.pendingProps;
16741 if (current$$1 === null) {
16742 // Portals are special because we don't append the children during mount
16743 // but at commit. Therefore we need to track insertions which the normal
16744 // flow doesn't do during mount. This doesn't happen at the root because
16745 // the root always starts with a "current" with a null child.
16746 // TODO: Consider unifying this with how the root works.
16747 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
16748 } else {
16749 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
16750 }
16751 return workInProgress.child;
16752}
16753
16754function updateContextProvider(current$$1, workInProgress, renderExpirationTime) {
16755 var providerType = workInProgress.type;
16756 var context = providerType._context;
16757
16758 var newProps = workInProgress.pendingProps;
16759 var oldProps = workInProgress.memoizedProps;
16760
16761 var newValue = newProps.value;
16762
16763 {
16764 var providerPropTypes = workInProgress.type.propTypes;
16765
16766 if (providerPropTypes) {
16767 checkPropTypes_1(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
16768 }
16769 }
16770
16771 pushProvider(workInProgress, newValue);
16772
16773 if (oldProps !== null) {
16774 var oldValue = oldProps.value;
16775 var changedBits = calculateChangedBits(context, newValue, oldValue);
16776 if (changedBits === 0) {
16777 // No change. Bailout early if children are the same.
16778 if (oldProps.children === newProps.children && !hasContextChanged()) {
16779 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
16780 }
16781 } else {
16782 // The context value changed. Search for matching consumers and schedule
16783 // them to update.
16784 propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
16785 }
16786 }
16787
16788 var newChildren = newProps.children;
16789 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
16790 return workInProgress.child;
16791}
16792
16793var hasWarnedAboutUsingContextAsConsumer = false;
16794
16795function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) {
16796 var context = workInProgress.type;
16797 // The logic below for Context differs depending on PROD or DEV mode. In
16798 // DEV mode, we create a separate object for Context.Consumer that acts
16799 // like a proxy to Context. This proxy object adds unnecessary code in PROD
16800 // so we use the old behaviour (Context.Consumer references Context) to
16801 // reduce size and overhead. The separate object references context via
16802 // a property called "_context", which also gives us the ability to check
16803 // in DEV mode if this property exists or not and warn if it does not.
16804 {
16805 if (context._context === undefined) {
16806 // This may be because it's a Context (rather than a Consumer).
16807 // Or it may be because it's older React where they're the same thing.
16808 // We only want to warn if we're sure it's a new React.
16809 if (context !== context.Consumer) {
16810 if (!hasWarnedAboutUsingContextAsConsumer) {
16811 hasWarnedAboutUsingContextAsConsumer = true;
16812 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?');
16813 }
16814 }
16815 } else {
16816 context = context._context;
16817 }
16818 }
16819 var newProps = workInProgress.pendingProps;
16820 var render = newProps.children;
16821
16822 {
16823 !(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;
16824 }
16825
16826 prepareToReadContext(workInProgress, renderExpirationTime);
16827 var newValue = readContext(context, newProps.unstable_observedBits);
16828 var newChildren = void 0;
16829 {
16830 ReactCurrentOwner$3.current = workInProgress;
16831 setCurrentPhase('render');
16832 newChildren = render(newValue);
16833 setCurrentPhase(null);
16834 }
16835
16836 // React DevTools reads this flag.
16837 workInProgress.effectTag |= PerformedWork;
16838 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
16839 return workInProgress.child;
16840}
16841
16842function updateEventComponent(current$$1, workInProgress, renderExpirationTime) {
16843 var nextProps = workInProgress.pendingProps;
16844 var nextChildren = nextProps.children;
16845
16846 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
16847 pushHostContextForEventComponent(workInProgress);
16848 return workInProgress.child;
16849}
16850
16851function updateEventTarget(current$$1, workInProgress, renderExpirationTime) {
16852 var nextProps = workInProgress.pendingProps;
16853 var nextChildren = nextProps.children;
16854
16855 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
16856 pushHostContextForEventTarget(workInProgress);
16857 return workInProgress.child;
16858}
16859
16860function markWorkInProgressReceivedUpdate() {
16861 didReceiveUpdate = true;
16862}
16863
16864function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) {
16865 cancelWorkTimer(workInProgress);
16866
16867 if (current$$1 !== null) {
16868 // Reuse previous context list
16869 workInProgress.contextDependencies = current$$1.contextDependencies;
16870 }
16871
16872 if (enableProfilerTimer) {
16873 // Don't update "base" render times for bailouts.
16874 stopProfilerTimerIfRunning(workInProgress);
16875 }
16876
16877 // Check if the children have any pending work.
16878 var childExpirationTime = workInProgress.childExpirationTime;
16879 if (childExpirationTime < renderExpirationTime) {
16880 // The children don't have any work either. We can skip them.
16881 // TODO: Once we add back resuming, we should check if the children are
16882 // a work-in-progress set. If so, we need to transfer their effects.
16883 return null;
16884 } else {
16885 // This fiber doesn't have work, but its subtree does. Clone the child
16886 // fibers and continue.
16887 cloneChildFibers(current$$1, workInProgress);
16888 return workInProgress.child;
16889 }
16890}
16891
16892function beginWork(current$$1, workInProgress, renderExpirationTime) {
16893 var updateExpirationTime = workInProgress.expirationTime;
16894
16895 if (current$$1 !== null) {
16896 var oldProps = current$$1.memoizedProps;
16897 var newProps = workInProgress.pendingProps;
16898
16899 if (oldProps !== newProps || hasContextChanged()) {
16900 // If props or context changed, mark the fiber as having performed work.
16901 // This may be unset if the props are determined to be equal later (memo).
16902 didReceiveUpdate = true;
16903 } else if (updateExpirationTime < renderExpirationTime) {
16904 didReceiveUpdate = false;
16905 // This fiber does not have any pending work. Bailout without entering
16906 // the begin phase. There's still some bookkeeping we that needs to be done
16907 // in this optimized path, mostly pushing stuff onto the stack.
16908 switch (workInProgress.tag) {
16909 case HostRoot:
16910 pushHostRootContext(workInProgress);
16911 resetHydrationState();
16912 break;
16913 case HostComponent:
16914 pushHostContext(workInProgress);
16915 break;
16916 case ClassComponent:
16917 {
16918 var Component = workInProgress.type;
16919 if (isContextProvider(Component)) {
16920 pushContextProvider(workInProgress);
16921 }
16922 break;
16923 }
16924 case HostPortal:
16925 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
16926 break;
16927 case ContextProvider:
16928 {
16929 var newValue = workInProgress.memoizedProps.value;
16930 pushProvider(workInProgress, newValue);
16931 break;
16932 }
16933 case Profiler:
16934 if (enableProfilerTimer) {
16935 workInProgress.effectTag |= Update;
16936 }
16937 break;
16938 case SuspenseComponent:
16939 {
16940 var state = workInProgress.memoizedState;
16941 var didTimeout = state !== null;
16942 if (didTimeout) {
16943 // If this boundary is currently timed out, we need to decide
16944 // whether to retry the primary children, or to skip over it and
16945 // go straight to the fallback. Check the priority of the primary
16946 var primaryChildFragment = workInProgress.child;
16947 var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
16948 if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
16949 // The primary children have pending work. Use the normal path
16950 // to attempt to render the primary children again.
16951 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
16952 } else {
16953 // The primary children do not have pending work with sufficient
16954 // priority. Bailout.
16955 var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
16956 if (child !== null) {
16957 // The fallback children have pending work. Skip over the
16958 // primary children and work on the fallback.
16959 return child.sibling;
16960 } else {
16961 return null;
16962 }
16963 }
16964 }
16965 break;
16966 }
16967 case DehydratedSuspenseComponent:
16968 {
16969 if (enableSuspenseServerRenderer) {
16970 // We know that this component will suspend again because if it has
16971 // been unsuspended it has committed as a regular Suspense component.
16972 // If it needs to be retried, it should have work scheduled on it.
16973 workInProgress.effectTag |= DidCapture;
16974 }
16975 break;
16976 }
16977 case EventComponent:
16978 if (enableEventAPI) {
16979 pushHostContextForEventComponent(workInProgress);
16980 }
16981 break;
16982 case EventTarget:
16983 {
16984 if (enableEventAPI) {
16985 pushHostContextForEventTarget(workInProgress);
16986 }
16987 break;
16988 }
16989 }
16990 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
16991 }
16992 } else {
16993 didReceiveUpdate = false;
16994 }
16995
16996 // Before entering the begin phase, clear the expiration time.
16997 workInProgress.expirationTime = NoWork;
16998
16999 switch (workInProgress.tag) {
17000 case IndeterminateComponent:
17001 {
17002 var elementType = workInProgress.elementType;
17003 return mountIndeterminateComponent(current$$1, workInProgress, elementType, renderExpirationTime);
17004 }
17005 case LazyComponent:
17006 {
17007 var _elementType = workInProgress.elementType;
17008 return mountLazyComponent(current$$1, workInProgress, _elementType, updateExpirationTime, renderExpirationTime);
17009 }
17010 case FunctionComponent:
17011 {
17012 var _Component = workInProgress.type;
17013 var unresolvedProps = workInProgress.pendingProps;
17014 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
17015 return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime);
17016 }
17017 case ClassComponent:
17018 {
17019 var _Component2 = workInProgress.type;
17020 var _unresolvedProps = workInProgress.pendingProps;
17021 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
17022 return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
17023 }
17024 case HostRoot:
17025 return updateHostRoot(current$$1, workInProgress, renderExpirationTime);
17026 case HostComponent:
17027 return updateHostComponent(current$$1, workInProgress, renderExpirationTime);
17028 case HostText:
17029 return updateHostText(current$$1, workInProgress);
17030 case SuspenseComponent:
17031 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
17032 case HostPortal:
17033 return updatePortalComponent(current$$1, workInProgress, renderExpirationTime);
17034 case ForwardRef:
17035 {
17036 var type = workInProgress.type;
17037 var _unresolvedProps2 = workInProgress.pendingProps;
17038 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
17039 return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime);
17040 }
17041 case Fragment:
17042 return updateFragment(current$$1, workInProgress, renderExpirationTime);
17043 case Mode:
17044 return updateMode(current$$1, workInProgress, renderExpirationTime);
17045 case Profiler:
17046 return updateProfiler(current$$1, workInProgress, renderExpirationTime);
17047 case ContextProvider:
17048 return updateContextProvider(current$$1, workInProgress, renderExpirationTime);
17049 case ContextConsumer:
17050 return updateContextConsumer(current$$1, workInProgress, renderExpirationTime);
17051 case MemoComponent:
17052 {
17053 var _type2 = workInProgress.type;
17054 var _unresolvedProps3 = workInProgress.pendingProps;
17055 // Resolve outer props first, then resolve inner props.
17056 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
17057 {
17058 if (workInProgress.type !== workInProgress.elementType) {
17059 var outerPropTypes = _type2.propTypes;
17060 if (outerPropTypes) {
17061 checkPropTypes_1(outerPropTypes, _resolvedProps3, // Resolved for outer only
17062 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
17063 }
17064 }
17065 }
17066 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
17067 return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
17068 }
17069 case SimpleMemoComponent:
17070 {
17071 return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
17072 }
17073 case IncompleteClassComponent:
17074 {
17075 var _Component3 = workInProgress.type;
17076 var _unresolvedProps4 = workInProgress.pendingProps;
17077 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
17078 return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
17079 }
17080 case DehydratedSuspenseComponent:
17081 {
17082 if (enableSuspenseServerRenderer) {
17083 return updateDehydratedSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
17084 }
17085 break;
17086 }
17087 case EventComponent:
17088 {
17089 if (enableEventAPI) {
17090 return updateEventComponent(current$$1, workInProgress, renderExpirationTime);
17091 }
17092 break;
17093 }
17094 case EventTarget:
17095 {
17096 if (enableEventAPI) {
17097 return updateEventTarget(current$$1, workInProgress, renderExpirationTime);
17098 }
17099 break;
17100 }
17101 }
17102 (function () {
17103 {
17104 {
17105 throw ReactError('Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
17106 }
17107 }
17108 })();
17109}
17110
17111var valueCursor = createCursor(null);
17112
17113var rendererSigil = void 0;
17114{
17115 // Use this to detect multiple renderers using the same context
17116 rendererSigil = {};
17117}
17118
17119var currentlyRenderingFiber = null;
17120var lastContextDependency = null;
17121var lastContextWithAllBitsObserved = null;
17122
17123var isDisallowedContextReadInDEV = false;
17124
17125function resetContextDependences() {
17126 // This is called right before React yields execution, to ensure `readContext`
17127 // cannot be called outside the render phase.
17128 currentlyRenderingFiber = null;
17129 lastContextDependency = null;
17130 lastContextWithAllBitsObserved = null;
17131 {
17132 isDisallowedContextReadInDEV = false;
17133 }
17134}
17135
17136function enterDisallowedContextReadInDEV() {
17137 {
17138 isDisallowedContextReadInDEV = true;
17139 }
17140}
17141
17142function exitDisallowedContextReadInDEV() {
17143 {
17144 isDisallowedContextReadInDEV = false;
17145 }
17146}
17147
17148function pushProvider(providerFiber, nextValue) {
17149 var context = providerFiber.type._context;
17150
17151 if (isPrimaryRenderer) {
17152 push(valueCursor, context._currentValue, providerFiber);
17153
17154 context._currentValue = nextValue;
17155 {
17156 !(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;
17157 context._currentRenderer = rendererSigil;
17158 }
17159 } else {
17160 push(valueCursor, context._currentValue2, providerFiber);
17161
17162 context._currentValue2 = nextValue;
17163 {
17164 !(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;
17165 context._currentRenderer2 = rendererSigil;
17166 }
17167 }
17168}
17169
17170function popProvider(providerFiber) {
17171 var currentValue = valueCursor.current;
17172
17173 pop(valueCursor, providerFiber);
17174
17175 var context = providerFiber.type._context;
17176 if (isPrimaryRenderer) {
17177 context._currentValue = currentValue;
17178 } else {
17179 context._currentValue2 = currentValue;
17180 }
17181}
17182
17183function calculateChangedBits(context, newValue, oldValue) {
17184 if (is(oldValue, newValue)) {
17185 // No change
17186 return 0;
17187 } else {
17188 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : maxSigned31BitInt;
17189
17190 {
17191 !((changedBits & maxSigned31BitInt) === changedBits) ? warning$1(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0;
17192 }
17193 return changedBits | 0;
17194 }
17195}
17196
17197function scheduleWorkOnParentPath(parent, renderExpirationTime) {
17198 // Update the child expiration time of all the ancestors, including
17199 // the alternates.
17200 var node = parent;
17201 while (node !== null) {
17202 var alternate = node.alternate;
17203 if (node.childExpirationTime < renderExpirationTime) {
17204 node.childExpirationTime = renderExpirationTime;
17205 if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
17206 alternate.childExpirationTime = renderExpirationTime;
17207 }
17208 } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
17209 alternate.childExpirationTime = renderExpirationTime;
17210 } else {
17211 // Neither alternate was updated, which means the rest of the
17212 // ancestor path already has sufficient priority.
17213 break;
17214 }
17215 node = node.return;
17216 }
17217}
17218
17219function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
17220 var fiber = workInProgress.child;
17221 if (fiber !== null) {
17222 // Set the return pointer of the child to the work-in-progress fiber.
17223 fiber.return = workInProgress;
17224 }
17225 while (fiber !== null) {
17226 var nextFiber = void 0;
17227
17228 // Visit this fiber.
17229 var list = fiber.contextDependencies;
17230 if (list !== null) {
17231 nextFiber = fiber.child;
17232
17233 var dependency = list.first;
17234 while (dependency !== null) {
17235 // Check if the context matches.
17236 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
17237 // Match! Schedule an update on this fiber.
17238
17239 if (fiber.tag === ClassComponent) {
17240 // Schedule a force update on the work-in-progress.
17241 var update = createUpdate(renderExpirationTime);
17242 update.tag = ForceUpdate;
17243 // TODO: Because we don't have a work-in-progress, this will add the
17244 // update to the current fiber, too, which means it will persist even if
17245 // this render is thrown away. Since it's a race condition, not sure it's
17246 // worth fixing.
17247 enqueueUpdate(fiber, update);
17248 }
17249
17250 if (fiber.expirationTime < renderExpirationTime) {
17251 fiber.expirationTime = renderExpirationTime;
17252 }
17253 var alternate = fiber.alternate;
17254 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
17255 alternate.expirationTime = renderExpirationTime;
17256 }
17257
17258 scheduleWorkOnParentPath(fiber.return, renderExpirationTime);
17259
17260 // Mark the expiration time on the list, too.
17261 if (list.expirationTime < renderExpirationTime) {
17262 list.expirationTime = renderExpirationTime;
17263 }
17264
17265 // Since we already found a match, we can stop traversing the
17266 // dependency list.
17267 break;
17268 }
17269 dependency = dependency.next;
17270 }
17271 } else if (fiber.tag === ContextProvider) {
17272 // Don't scan deeper if this is a matching provider
17273 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
17274 } else if (enableSuspenseServerRenderer && fiber.tag === DehydratedSuspenseComponent) {
17275 // If a dehydrated suspense component is in this subtree, we don't know
17276 // if it will have any context consumers in it. The best we can do is
17277 // mark it as having updates on its children.
17278 if (fiber.expirationTime < renderExpirationTime) {
17279 fiber.expirationTime = renderExpirationTime;
17280 }
17281 var _alternate = fiber.alternate;
17282 if (_alternate !== null && _alternate.expirationTime < renderExpirationTime) {
17283 _alternate.expirationTime = renderExpirationTime;
17284 }
17285 // This is intentionally passing this fiber as the parent
17286 // because we want to schedule this fiber as having work
17287 // on its children. We'll use the childExpirationTime on
17288 // this fiber to indicate that a context has changed.
17289 scheduleWorkOnParentPath(fiber, renderExpirationTime);
17290 nextFiber = fiber.sibling;
17291 } else {
17292 // Traverse down.
17293 nextFiber = fiber.child;
17294 }
17295
17296 if (nextFiber !== null) {
17297 // Set the return pointer of the child to the work-in-progress fiber.
17298 nextFiber.return = fiber;
17299 } else {
17300 // No child. Traverse to next sibling.
17301 nextFiber = fiber;
17302 while (nextFiber !== null) {
17303 if (nextFiber === workInProgress) {
17304 // We're back to the root of this subtree. Exit.
17305 nextFiber = null;
17306 break;
17307 }
17308 var sibling = nextFiber.sibling;
17309 if (sibling !== null) {
17310 // Set the return pointer of the sibling to the work-in-progress fiber.
17311 sibling.return = nextFiber.return;
17312 nextFiber = sibling;
17313 break;
17314 }
17315 // No more siblings. Traverse up.
17316 nextFiber = nextFiber.return;
17317 }
17318 }
17319 fiber = nextFiber;
17320 }
17321}
17322
17323function prepareToReadContext(workInProgress, renderExpirationTime) {
17324 currentlyRenderingFiber = workInProgress;
17325 lastContextDependency = null;
17326 lastContextWithAllBitsObserved = null;
17327
17328 var currentDependencies = workInProgress.contextDependencies;
17329 if (currentDependencies !== null && currentDependencies.expirationTime >= renderExpirationTime) {
17330 // Context list has a pending update. Mark that this fiber performed work.
17331 markWorkInProgressReceivedUpdate();
17332 }
17333
17334 // Reset the work-in-progress list
17335 workInProgress.contextDependencies = null;
17336}
17337
17338function readContext(context, observedBits) {
17339 {
17340 // This warning would fire if you read context inside a Hook like useMemo.
17341 // Unlike the class check below, it's not enforced in production for perf.
17342 !!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;
17343 }
17344
17345 if (lastContextWithAllBitsObserved === context) {
17346 // Nothing to do. We already observe everything in this context.
17347 } else if (observedBits === false || observedBits === 0) {
17348 // Do not observe any updates.
17349 } else {
17350 var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types.
17351 if (typeof observedBits !== 'number' || observedBits === maxSigned31BitInt) {
17352 // Observe all updates.
17353 lastContextWithAllBitsObserved = context;
17354 resolvedObservedBits = maxSigned31BitInt;
17355 } else {
17356 resolvedObservedBits = observedBits;
17357 }
17358
17359 var contextItem = {
17360 context: context,
17361 observedBits: resolvedObservedBits,
17362 next: null
17363 };
17364
17365 if (lastContextDependency === null) {
17366 (function () {
17367 if (!(currentlyRenderingFiber !== null)) {
17368 {
17369 throw ReactError('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().');
17370 }
17371 }
17372 })();
17373
17374 // This is the first dependency for this component. Create a new list.
17375 lastContextDependency = contextItem;
17376 currentlyRenderingFiber.contextDependencies = {
17377 first: contextItem,
17378 expirationTime: NoWork
17379 };
17380 } else {
17381 // Append a new context item.
17382 lastContextDependency = lastContextDependency.next = contextItem;
17383 }
17384 }
17385 return isPrimaryRenderer ? context._currentValue : context._currentValue2;
17386}
17387
17388// UpdateQueue is a linked list of prioritized updates.
17389//
17390// Like fibers, update queues come in pairs: a current queue, which represents
17391// the visible state of the screen, and a work-in-progress queue, which can be
17392// mutated and processed asynchronously before it is committed — a form of
17393// double buffering. If a work-in-progress render is discarded before finishing,
17394// we create a new work-in-progress by cloning the current queue.
17395//
17396// Both queues share a persistent, singly-linked list structure. To schedule an
17397// update, we append it to the end of both queues. Each queue maintains a
17398// pointer to first update in the persistent list that hasn't been processed.
17399// The work-in-progress pointer always has a position equal to or greater than
17400// the current queue, since we always work on that one. The current queue's
17401// pointer is only updated during the commit phase, when we swap in the
17402// work-in-progress.
17403//
17404// For example:
17405//
17406// Current pointer: A - B - C - D - E - F
17407// Work-in-progress pointer: D - E - F
17408// ^
17409// The work-in-progress queue has
17410// processed more updates than current.
17411//
17412// The reason we append to both queues is because otherwise we might drop
17413// updates without ever processing them. For example, if we only add updates to
17414// the work-in-progress queue, some updates could be lost whenever a work-in
17415// -progress render restarts by cloning from current. Similarly, if we only add
17416// updates to the current queue, the updates will be lost whenever an already
17417// in-progress queue commits and swaps with the current queue. However, by
17418// adding to both queues, we guarantee that the update will be part of the next
17419// work-in-progress. (And because the work-in-progress queue becomes the
17420// current queue once it commits, there's no danger of applying the same
17421// update twice.)
17422//
17423// Prioritization
17424// --------------
17425//
17426// Updates are not sorted by priority, but by insertion; new updates are always
17427// appended to the end of the list.
17428//
17429// The priority is still important, though. When processing the update queue
17430// during the render phase, only the updates with sufficient priority are
17431// included in the result. If we skip an update because it has insufficient
17432// priority, it remains in the queue to be processed later, during a lower
17433// priority render. Crucially, all updates subsequent to a skipped update also
17434// remain in the queue *regardless of their priority*. That means high priority
17435// updates are sometimes processed twice, at two separate priorities. We also
17436// keep track of a base state, that represents the state before the first
17437// update in the queue is applied.
17438//
17439// For example:
17440//
17441// Given a base state of '', and the following queue of updates
17442//
17443// A1 - B2 - C1 - D2
17444//
17445// where the number indicates the priority, and the update is applied to the
17446// previous state by appending a letter, React will process these updates as
17447// two separate renders, one per distinct priority level:
17448//
17449// First render, at priority 1:
17450// Base state: ''
17451// Updates: [A1, C1]
17452// Result state: 'AC'
17453//
17454// Second render, at priority 2:
17455// Base state: 'A' <- The base state does not include C1,
17456// because B2 was skipped.
17457// Updates: [B2, C1, D2] <- C1 was rebased on top of B2
17458// Result state: 'ABCD'
17459//
17460// Because we process updates in insertion order, and rebase high priority
17461// updates when preceding updates are skipped, the final result is deterministic
17462// regardless of priority. Intermediate state may vary according to system
17463// resources, but the final state is always the same.
17464
17465var UpdateState = 0;
17466var ReplaceState = 1;
17467var ForceUpdate = 2;
17468var CaptureUpdate = 3;
17469
17470// Global state that is reset at the beginning of calling `processUpdateQueue`.
17471// It should only be read right after calling `processUpdateQueue`, via
17472// `checkHasForceUpdateAfterProcessing`.
17473var hasForceUpdate = false;
17474
17475var didWarnUpdateInsideUpdate = void 0;
17476var currentlyProcessingQueue = void 0;
17477var resetCurrentlyProcessingQueue = void 0;
17478{
17479 didWarnUpdateInsideUpdate = false;
17480 currentlyProcessingQueue = null;
17481 resetCurrentlyProcessingQueue = function () {
17482 currentlyProcessingQueue = null;
17483 };
17484}
17485
17486function createUpdateQueue(baseState) {
17487 var queue = {
17488 baseState: baseState,
17489 firstUpdate: null,
17490 lastUpdate: null,
17491 firstCapturedUpdate: null,
17492 lastCapturedUpdate: null,
17493 firstEffect: null,
17494 lastEffect: null,
17495 firstCapturedEffect: null,
17496 lastCapturedEffect: null
17497 };
17498 return queue;
17499}
17500
17501function cloneUpdateQueue(currentQueue) {
17502 var queue = {
17503 baseState: currentQueue.baseState,
17504 firstUpdate: currentQueue.firstUpdate,
17505 lastUpdate: currentQueue.lastUpdate,
17506
17507 // TODO: With resuming, if we bail out and resuse the child tree, we should
17508 // keep these effects.
17509 firstCapturedUpdate: null,
17510 lastCapturedUpdate: null,
17511
17512 firstEffect: null,
17513 lastEffect: null,
17514
17515 firstCapturedEffect: null,
17516 lastCapturedEffect: null
17517 };
17518 return queue;
17519}
17520
17521function createUpdate(expirationTime) {
17522 return {
17523 expirationTime: expirationTime,
17524
17525 tag: UpdateState,
17526 payload: null,
17527 callback: null,
17528
17529 next: null,
17530 nextEffect: null
17531 };
17532}
17533
17534function appendUpdateToQueue(queue, update) {
17535 // Append the update to the end of the list.
17536 if (queue.lastUpdate === null) {
17537 // Queue is empty
17538 queue.firstUpdate = queue.lastUpdate = update;
17539 } else {
17540 queue.lastUpdate.next = update;
17541 queue.lastUpdate = update;
17542 }
17543}
17544
17545function enqueueUpdate(fiber, update) {
17546 // Update queues are created lazily.
17547 var alternate = fiber.alternate;
17548 var queue1 = void 0;
17549 var queue2 = void 0;
17550 if (alternate === null) {
17551 // There's only one fiber.
17552 queue1 = fiber.updateQueue;
17553 queue2 = null;
17554 if (queue1 === null) {
17555 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
17556 }
17557 } else {
17558 // There are two owners.
17559 queue1 = fiber.updateQueue;
17560 queue2 = alternate.updateQueue;
17561 if (queue1 === null) {
17562 if (queue2 === null) {
17563 // Neither fiber has an update queue. Create new ones.
17564 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
17565 queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
17566 } else {
17567 // Only one fiber has an update queue. Clone to create a new one.
17568 queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
17569 }
17570 } else {
17571 if (queue2 === null) {
17572 // Only one fiber has an update queue. Clone to create a new one.
17573 queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
17574 } else {
17575 // Both owners have an update queue.
17576 }
17577 }
17578 }
17579 if (queue2 === null || queue1 === queue2) {
17580 // There's only a single queue.
17581 appendUpdateToQueue(queue1, update);
17582 } else {
17583 // There are two queues. We need to append the update to both queues,
17584 // while accounting for the persistent structure of the list — we don't
17585 // want the same update to be added multiple times.
17586 if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
17587 // One of the queues is not empty. We must add the update to both queues.
17588 appendUpdateToQueue(queue1, update);
17589 appendUpdateToQueue(queue2, update);
17590 } else {
17591 // Both queues are non-empty. The last update is the same in both lists,
17592 // because of structural sharing. So, only append to one of the lists.
17593 appendUpdateToQueue(queue1, update);
17594 // But we still need to update the `lastUpdate` pointer of queue2.
17595 queue2.lastUpdate = update;
17596 }
17597 }
17598
17599 {
17600 if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
17601 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.');
17602 didWarnUpdateInsideUpdate = true;
17603 }
17604 }
17605}
17606
17607function enqueueCapturedUpdate(workInProgress, update) {
17608 // Captured updates go into a separate list, and only on the work-in-
17609 // progress queue.
17610 var workInProgressQueue = workInProgress.updateQueue;
17611 if (workInProgressQueue === null) {
17612 workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
17613 } else {
17614 // TODO: I put this here rather than createWorkInProgress so that we don't
17615 // clone the queue unnecessarily. There's probably a better way to
17616 // structure this.
17617 workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
17618 }
17619
17620 // Append the update to the end of the list.
17621 if (workInProgressQueue.lastCapturedUpdate === null) {
17622 // This is the first render phase update
17623 workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
17624 } else {
17625 workInProgressQueue.lastCapturedUpdate.next = update;
17626 workInProgressQueue.lastCapturedUpdate = update;
17627 }
17628}
17629
17630function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
17631 var current = workInProgress.alternate;
17632 if (current !== null) {
17633 // If the work-in-progress queue is equal to the current queue,
17634 // we need to clone it first.
17635 if (queue === current.updateQueue) {
17636 queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
17637 }
17638 }
17639 return queue;
17640}
17641
17642function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
17643 switch (update.tag) {
17644 case ReplaceState:
17645 {
17646 var _payload = update.payload;
17647 if (typeof _payload === 'function') {
17648 // Updater function
17649 {
17650 enterDisallowedContextReadInDEV();
17651 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
17652 _payload.call(instance, prevState, nextProps);
17653 }
17654 }
17655 var nextState = _payload.call(instance, prevState, nextProps);
17656 {
17657 exitDisallowedContextReadInDEV();
17658 }
17659 return nextState;
17660 }
17661 // State object
17662 return _payload;
17663 }
17664 case CaptureUpdate:
17665 {
17666 workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
17667 }
17668 // Intentional fallthrough
17669 case UpdateState:
17670 {
17671 var _payload2 = update.payload;
17672 var partialState = void 0;
17673 if (typeof _payload2 === 'function') {
17674 // Updater function
17675 {
17676 enterDisallowedContextReadInDEV();
17677 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
17678 _payload2.call(instance, prevState, nextProps);
17679 }
17680 }
17681 partialState = _payload2.call(instance, prevState, nextProps);
17682 {
17683 exitDisallowedContextReadInDEV();
17684 }
17685 } else {
17686 // Partial state object
17687 partialState = _payload2;
17688 }
17689 if (partialState === null || partialState === undefined) {
17690 // Null and undefined are treated as no-ops.
17691 return prevState;
17692 }
17693 // Merge the partial state and the previous state.
17694 return _assign({}, prevState, partialState);
17695 }
17696 case ForceUpdate:
17697 {
17698 hasForceUpdate = true;
17699 return prevState;
17700 }
17701 }
17702 return prevState;
17703}
17704
17705function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
17706 hasForceUpdate = false;
17707
17708 queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
17709
17710 {
17711 currentlyProcessingQueue = queue;
17712 }
17713
17714 // These values may change as we process the queue.
17715 var newBaseState = queue.baseState;
17716 var newFirstUpdate = null;
17717 var newExpirationTime = NoWork;
17718
17719 // Iterate through the list of updates to compute the result.
17720 var update = queue.firstUpdate;
17721 var resultState = newBaseState;
17722 while (update !== null) {
17723 var updateExpirationTime = update.expirationTime;
17724 if (updateExpirationTime < renderExpirationTime) {
17725 // This update does not have sufficient priority. Skip it.
17726 if (newFirstUpdate === null) {
17727 // This is the first skipped update. It will be the first update in
17728 // the new list.
17729 newFirstUpdate = update;
17730 // Since this is the first update that was skipped, the current result
17731 // is the new base state.
17732 newBaseState = resultState;
17733 }
17734 // Since this update will remain in the list, update the remaining
17735 // expiration time.
17736 if (newExpirationTime < updateExpirationTime) {
17737 newExpirationTime = updateExpirationTime;
17738 }
17739 } else {
17740 // This update does have sufficient priority. Process it and compute
17741 // a new result.
17742 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
17743 var _callback = update.callback;
17744 if (_callback !== null) {
17745 workInProgress.effectTag |= Callback;
17746 // Set this to null, in case it was mutated during an aborted render.
17747 update.nextEffect = null;
17748 if (queue.lastEffect === null) {
17749 queue.firstEffect = queue.lastEffect = update;
17750 } else {
17751 queue.lastEffect.nextEffect = update;
17752 queue.lastEffect = update;
17753 }
17754 }
17755 }
17756 // Continue to the next update.
17757 update = update.next;
17758 }
17759
17760 // Separately, iterate though the list of captured updates.
17761 var newFirstCapturedUpdate = null;
17762 update = queue.firstCapturedUpdate;
17763 while (update !== null) {
17764 var _updateExpirationTime = update.expirationTime;
17765 if (_updateExpirationTime < renderExpirationTime) {
17766 // This update does not have sufficient priority. Skip it.
17767 if (newFirstCapturedUpdate === null) {
17768 // This is the first skipped captured update. It will be the first
17769 // update in the new list.
17770 newFirstCapturedUpdate = update;
17771 // If this is the first update that was skipped, the current result is
17772 // the new base state.
17773 if (newFirstUpdate === null) {
17774 newBaseState = resultState;
17775 }
17776 }
17777 // Since this update will remain in the list, update the remaining
17778 // expiration time.
17779 if (newExpirationTime < _updateExpirationTime) {
17780 newExpirationTime = _updateExpirationTime;
17781 }
17782 } else {
17783 // This update does have sufficient priority. Process it and compute
17784 // a new result.
17785 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
17786 var _callback2 = update.callback;
17787 if (_callback2 !== null) {
17788 workInProgress.effectTag |= Callback;
17789 // Set this to null, in case it was mutated during an aborted render.
17790 update.nextEffect = null;
17791 if (queue.lastCapturedEffect === null) {
17792 queue.firstCapturedEffect = queue.lastCapturedEffect = update;
17793 } else {
17794 queue.lastCapturedEffect.nextEffect = update;
17795 queue.lastCapturedEffect = update;
17796 }
17797 }
17798 }
17799 update = update.next;
17800 }
17801
17802 if (newFirstUpdate === null) {
17803 queue.lastUpdate = null;
17804 }
17805 if (newFirstCapturedUpdate === null) {
17806 queue.lastCapturedUpdate = null;
17807 } else {
17808 workInProgress.effectTag |= Callback;
17809 }
17810 if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
17811 // We processed every update, without skipping. That means the new base
17812 // state is the same as the result state.
17813 newBaseState = resultState;
17814 }
17815
17816 queue.baseState = newBaseState;
17817 queue.firstUpdate = newFirstUpdate;
17818 queue.firstCapturedUpdate = newFirstCapturedUpdate;
17819
17820 // Set the remaining expiration time to be whatever is remaining in the queue.
17821 // This should be fine because the only two other things that contribute to
17822 // expiration time are props and context. We're already in the middle of the
17823 // begin phase by the time we start processing the queue, so we've already
17824 // dealt with the props. Context in components that specify
17825 // shouldComponentUpdate is tricky; but we'll have to account for
17826 // that regardless.
17827 workInProgress.expirationTime = newExpirationTime;
17828 workInProgress.memoizedState = resultState;
17829
17830 {
17831 currentlyProcessingQueue = null;
17832 }
17833}
17834
17835function callCallback(callback, context) {
17836 (function () {
17837 if (!(typeof callback === 'function')) {
17838 {
17839 throw ReactError('Invalid argument passed as callback. Expected a function. Instead received: ' + callback);
17840 }
17841 }
17842 })();
17843 callback.call(context);
17844}
17845
17846function resetHasForceUpdateBeforeProcessing() {
17847 hasForceUpdate = false;
17848}
17849
17850function checkHasForceUpdateAfterProcessing() {
17851 return hasForceUpdate;
17852}
17853
17854function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
17855 // If the finished render included captured updates, and there are still
17856 // lower priority updates left over, we need to keep the captured updates
17857 // in the queue so that they are rebased and not dropped once we process the
17858 // queue again at the lower priority.
17859 if (finishedQueue.firstCapturedUpdate !== null) {
17860 // Join the captured update list to the end of the normal list.
17861 if (finishedQueue.lastUpdate !== null) {
17862 finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
17863 finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
17864 }
17865 // Clear the list of captured updates.
17866 finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
17867 }
17868
17869 // Commit the effects
17870 commitUpdateEffects(finishedQueue.firstEffect, instance);
17871 finishedQueue.firstEffect = finishedQueue.lastEffect = null;
17872
17873 commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
17874 finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
17875}
17876
17877function commitUpdateEffects(effect, instance) {
17878 while (effect !== null) {
17879 var _callback3 = effect.callback;
17880 if (_callback3 !== null) {
17881 effect.callback = null;
17882 callCallback(_callback3, instance);
17883 }
17884 effect = effect.nextEffect;
17885 }
17886}
17887
17888function createCapturedValue(value, source) {
17889 // If the value is an error, call this function immediately after it is thrown
17890 // so the stack is accurate.
17891 return {
17892 value: value,
17893 source: source,
17894 stack: getStackByFiberInDevAndProd(source)
17895 };
17896}
17897
17898function markUpdate(workInProgress) {
17899 // Tag the fiber with an update effect. This turns a Placement into
17900 // a PlacementAndUpdate.
17901 workInProgress.effectTag |= Update;
17902}
17903
17904function markRef$1(workInProgress) {
17905 workInProgress.effectTag |= Ref;
17906}
17907
17908var appendAllChildren = void 0;
17909var updateHostContainer = void 0;
17910var updateHostComponent$1 = void 0;
17911var updateHostText$1 = void 0;
17912if (supportsMutation) {
17913 // Mutation mode
17914
17915 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
17916 // We only have the top Fiber that was created but we need recurse down its
17917 // children to find all the terminal nodes.
17918 var node = workInProgress.child;
17919 while (node !== null) {
17920 if (node.tag === HostComponent || node.tag === HostText) {
17921 appendInitialChild(parent, node.stateNode);
17922 } else if (node.tag === HostPortal) {
17923 // If we have a portal child, then we don't want to traverse
17924 // down its children. Instead, we'll get insertions from each child in
17925 // the portal directly.
17926 } else if (node.child !== null) {
17927 node.child.return = node;
17928 node = node.child;
17929 continue;
17930 }
17931 if (node === workInProgress) {
17932 return;
17933 }
17934 while (node.sibling === null) {
17935 if (node.return === null || node.return === workInProgress) {
17936 return;
17937 }
17938 node = node.return;
17939 }
17940 node.sibling.return = node.return;
17941 node = node.sibling;
17942 }
17943 };
17944
17945 updateHostContainer = function (workInProgress) {
17946 // Noop
17947 };
17948 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
17949 // If we have an alternate, that means this is an update and we need to
17950 // schedule a side-effect to do the updates.
17951 var oldProps = current.memoizedProps;
17952 if (oldProps === newProps) {
17953 // In mutation mode, this is sufficient for a bailout because
17954 // we won't touch this node even if children changed.
17955 return;
17956 }
17957
17958 // If we get updated because one of our children updated, we don't
17959 // have newProps so we'll have to reuse them.
17960 // TODO: Split the update API as separate for the props vs. children.
17961 // Even better would be if children weren't special cased at all tho.
17962 var instance = workInProgress.stateNode;
17963 var currentHostContext = getHostContext();
17964 // TODO: Experiencing an error where oldProps is null. Suggests a host
17965 // component is hitting the resume path. Figure out why. Possibly
17966 // related to `hidden`.
17967 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
17968 // TODO: Type this specific to this type of component.
17969 workInProgress.updateQueue = updatePayload;
17970 // If the update payload indicates that there is a change or if there
17971 // is a new ref we mark this as an update. All the work is done in commitWork.
17972 if (updatePayload) {
17973 markUpdate(workInProgress);
17974 }
17975 };
17976 updateHostText$1 = function (current, workInProgress, oldText, newText) {
17977 // If the text differs, mark it as an update. All the work in done in commitWork.
17978 if (oldText !== newText) {
17979 markUpdate(workInProgress);
17980 }
17981 };
17982} else if (supportsPersistence) {
17983 // Persistent host tree mode
17984
17985 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
17986 // We only have the top Fiber that was created but we need recurse down its
17987 // children to find all the terminal nodes.
17988 var node = workInProgress.child;
17989 while (node !== null) {
17990 // eslint-disable-next-line no-labels
17991 branches: if (node.tag === HostComponent) {
17992 var instance = node.stateNode;
17993 if (needsVisibilityToggle && isHidden) {
17994 // This child is inside a timed out tree. Hide it.
17995 var props = node.memoizedProps;
17996 var type = node.type;
17997 instance = cloneHiddenInstance(instance, type, props, node);
17998 }
17999 appendInitialChild(parent, instance);
18000 } else if (node.tag === HostText) {
18001 var _instance = node.stateNode;
18002 if (needsVisibilityToggle && isHidden) {
18003 // This child is inside a timed out tree. Hide it.
18004 var text = node.memoizedProps;
18005 _instance = cloneHiddenTextInstance(_instance, text, node);
18006 }
18007 appendInitialChild(parent, _instance);
18008 } else if (node.tag === HostPortal) {
18009 // If we have a portal child, then we don't want to traverse
18010 // down its children. Instead, we'll get insertions from each child in
18011 // the portal directly.
18012 } else if (node.tag === SuspenseComponent) {
18013 if ((node.effectTag & Update) !== NoEffect) {
18014 // Need to toggle the visibility of the primary children.
18015 var newIsHidden = node.memoizedState !== null;
18016 if (newIsHidden) {
18017 var primaryChildParent = node.child;
18018 if (primaryChildParent !== null) {
18019 if (primaryChildParent.child !== null) {
18020 primaryChildParent.child.return = primaryChildParent;
18021 appendAllChildren(parent, primaryChildParent, true, newIsHidden);
18022 }
18023 var fallbackChildParent = primaryChildParent.sibling;
18024 if (fallbackChildParent !== null) {
18025 fallbackChildParent.return = node;
18026 node = fallbackChildParent;
18027 continue;
18028 }
18029 }
18030 }
18031 }
18032 if (node.child !== null) {
18033 // Continue traversing like normal
18034 node.child.return = node;
18035 node = node.child;
18036 continue;
18037 }
18038 } else if (node.child !== null) {
18039 node.child.return = node;
18040 node = node.child;
18041 continue;
18042 }
18043 // $FlowFixMe This is correct but Flow is confused by the labeled break.
18044 node = node;
18045 if (node === workInProgress) {
18046 return;
18047 }
18048 while (node.sibling === null) {
18049 if (node.return === null || node.return === workInProgress) {
18050 return;
18051 }
18052 node = node.return;
18053 }
18054 node.sibling.return = node.return;
18055 node = node.sibling;
18056 }
18057 };
18058
18059 // An unfortunate fork of appendAllChildren because we have two different parent types.
18060 var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
18061 // We only have the top Fiber that was created but we need recurse down its
18062 // children to find all the terminal nodes.
18063 var node = workInProgress.child;
18064 while (node !== null) {
18065 // eslint-disable-next-line no-labels
18066 branches: if (node.tag === HostComponent) {
18067 var instance = node.stateNode;
18068 if (needsVisibilityToggle && isHidden) {
18069 // This child is inside a timed out tree. Hide it.
18070 var props = node.memoizedProps;
18071 var type = node.type;
18072 instance = cloneHiddenInstance(instance, type, props, node);
18073 }
18074 appendChildToContainerChildSet(containerChildSet, instance);
18075 } else if (node.tag === HostText) {
18076 var _instance2 = node.stateNode;
18077 if (needsVisibilityToggle && isHidden) {
18078 // This child is inside a timed out tree. Hide it.
18079 var text = node.memoizedProps;
18080 _instance2 = cloneHiddenTextInstance(_instance2, text, node);
18081 }
18082 appendChildToContainerChildSet(containerChildSet, _instance2);
18083 } else if (node.tag === HostPortal) {
18084 // If we have a portal child, then we don't want to traverse
18085 // down its children. Instead, we'll get insertions from each child in
18086 // the portal directly.
18087 } else if (node.tag === SuspenseComponent) {
18088 if ((node.effectTag & Update) !== NoEffect) {
18089 // Need to toggle the visibility of the primary children.
18090 var newIsHidden = node.memoizedState !== null;
18091 if (newIsHidden) {
18092 var primaryChildParent = node.child;
18093 if (primaryChildParent !== null) {
18094 if (primaryChildParent.child !== null) {
18095 primaryChildParent.child.return = primaryChildParent;
18096 appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
18097 }
18098 var fallbackChildParent = primaryChildParent.sibling;
18099 if (fallbackChildParent !== null) {
18100 fallbackChildParent.return = node;
18101 node = fallbackChildParent;
18102 continue;
18103 }
18104 }
18105 }
18106 }
18107 if (node.child !== null) {
18108 // Continue traversing like normal
18109 node.child.return = node;
18110 node = node.child;
18111 continue;
18112 }
18113 } else if (node.child !== null) {
18114 node.child.return = node;
18115 node = node.child;
18116 continue;
18117 }
18118 // $FlowFixMe This is correct but Flow is confused by the labeled break.
18119 node = node;
18120 if (node === workInProgress) {
18121 return;
18122 }
18123 while (node.sibling === null) {
18124 if (node.return === null || node.return === workInProgress) {
18125 return;
18126 }
18127 node = node.return;
18128 }
18129 node.sibling.return = node.return;
18130 node = node.sibling;
18131 }
18132 };
18133 updateHostContainer = function (workInProgress) {
18134 var portalOrRoot = workInProgress.stateNode;
18135 var childrenUnchanged = workInProgress.firstEffect === null;
18136 if (childrenUnchanged) {
18137 // No changes, just reuse the existing instance.
18138 } else {
18139 var container = portalOrRoot.containerInfo;
18140 var newChildSet = createContainerChildSet(container);
18141 // If children might have changed, we have to add them all to the set.
18142 appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
18143 portalOrRoot.pendingChildren = newChildSet;
18144 // Schedule an update on the container to swap out the container.
18145 markUpdate(workInProgress);
18146 finalizeContainerChildren(container, newChildSet);
18147 }
18148 };
18149 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
18150 var currentInstance = current.stateNode;
18151 var oldProps = current.memoizedProps;
18152 // If there are no effects associated with this node, then none of our children had any updates.
18153 // This guarantees that we can reuse all of them.
18154 var childrenUnchanged = workInProgress.firstEffect === null;
18155 if (childrenUnchanged && oldProps === newProps) {
18156 // No changes, just reuse the existing instance.
18157 // Note that this might release a previous clone.
18158 workInProgress.stateNode = currentInstance;
18159 return;
18160 }
18161 var recyclableInstance = workInProgress.stateNode;
18162 var currentHostContext = getHostContext();
18163 var updatePayload = null;
18164 if (oldProps !== newProps) {
18165 updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
18166 }
18167 if (childrenUnchanged && updatePayload === null) {
18168 // No changes, just reuse the existing instance.
18169 // Note that this might release a previous clone.
18170 workInProgress.stateNode = currentInstance;
18171 return;
18172 }
18173 var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
18174 if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
18175 markUpdate(workInProgress);
18176 }
18177 workInProgress.stateNode = newInstance;
18178 if (childrenUnchanged) {
18179 // If there are no other effects in this tree, we need to flag this node as having one.
18180 // Even though we're not going to use it for anything.
18181 // Otherwise parents won't know that there are new children to propagate upwards.
18182 markUpdate(workInProgress);
18183 } else {
18184 // If children might have changed, we have to add them all to the set.
18185 appendAllChildren(newInstance, workInProgress, false, false);
18186 }
18187 };
18188 updateHostText$1 = function (current, workInProgress, oldText, newText) {
18189 if (oldText !== newText) {
18190 // If the text content differs, we'll create a new text instance for it.
18191 var rootContainerInstance = getRootHostContainer();
18192 var currentHostContext = getHostContext();
18193 workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress);
18194 // We'll have to mark it as having an effect, even though we won't use the effect for anything.
18195 // This lets the parents know that at least one of their children has changed.
18196 markUpdate(workInProgress);
18197 }
18198 };
18199} else {
18200 // No host operations
18201 updateHostContainer = function (workInProgress) {
18202 // Noop
18203 };
18204 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
18205 // Noop
18206 };
18207 updateHostText$1 = function (current, workInProgress, oldText, newText) {
18208 // Noop
18209 };
18210}
18211
18212function completeWork(current, workInProgress, renderExpirationTime) {
18213 var newProps = workInProgress.pendingProps;
18214
18215 switch (workInProgress.tag) {
18216 case IndeterminateComponent:
18217 break;
18218 case LazyComponent:
18219 break;
18220 case SimpleMemoComponent:
18221 case FunctionComponent:
18222 break;
18223 case ClassComponent:
18224 {
18225 var Component = workInProgress.type;
18226 if (isContextProvider(Component)) {
18227 popContext(workInProgress);
18228 }
18229 break;
18230 }
18231 case HostRoot:
18232 {
18233 popHostContainer(workInProgress);
18234 popTopLevelContextObject(workInProgress);
18235 var fiberRoot = workInProgress.stateNode;
18236 if (fiberRoot.pendingContext) {
18237 fiberRoot.context = fiberRoot.pendingContext;
18238 fiberRoot.pendingContext = null;
18239 }
18240 if (current === null || current.child === null) {
18241 // If we hydrated, pop so that we can delete any remaining children
18242 // that weren't hydrated.
18243 popHydrationState(workInProgress);
18244 // This resets the hacky state to fix isMounted before committing.
18245 // TODO: Delete this when we delete isMounted and findDOMNode.
18246 workInProgress.effectTag &= ~Placement;
18247 }
18248 updateHostContainer(workInProgress);
18249 break;
18250 }
18251 case HostComponent:
18252 {
18253 popHostContext(workInProgress);
18254 var rootContainerInstance = getRootHostContainer();
18255 var type = workInProgress.type;
18256 if (current !== null && workInProgress.stateNode != null) {
18257 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
18258
18259 if (current.ref !== workInProgress.ref) {
18260 markRef$1(workInProgress);
18261 }
18262 } else {
18263 if (!newProps) {
18264 (function () {
18265 if (!(workInProgress.stateNode !== null)) {
18266 {
18267 throw ReactError('We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.');
18268 }
18269 }
18270 })();
18271 // This can happen when we abort work.
18272 break;
18273 }
18274
18275 var currentHostContext = getHostContext();
18276 // TODO: Move createInstance to beginWork and keep it on a context
18277 // "stack" as the parent. Then append children as we go in beginWork
18278 // or completeWork depending on we want to add then top->down or
18279 // bottom->up. Top->down is faster in IE11.
18280 var wasHydrated = popHydrationState(workInProgress);
18281 if (wasHydrated) {
18282 // TODO: Move this and createInstance step into the beginPhase
18283 // to consolidate.
18284 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
18285 // If changes to the hydrated node needs to be applied at the
18286 // commit-phase we mark this as such.
18287 markUpdate(workInProgress);
18288 }
18289 } else {
18290 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
18291
18292 appendAllChildren(instance, workInProgress, false, false);
18293
18294 // Certain renderers require commit-time effects for initial mount.
18295 // (eg DOM renderer supports auto-focus for certain elements).
18296 // Make sure such renderers get scheduled for later work.
18297 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
18298 markUpdate(workInProgress);
18299 }
18300 workInProgress.stateNode = instance;
18301 }
18302
18303 if (workInProgress.ref !== null) {
18304 // If there is a ref on a host node we need to schedule a callback
18305 markRef$1(workInProgress);
18306 }
18307 }
18308 break;
18309 }
18310 case HostText:
18311 {
18312 var newText = newProps;
18313 if (current && workInProgress.stateNode != null) {
18314 var oldText = current.memoizedProps;
18315 // If we have an alternate, that means this is an update and we need
18316 // to schedule a side-effect to do the updates.
18317 updateHostText$1(current, workInProgress, oldText, newText);
18318 } else {
18319 if (typeof newText !== 'string') {
18320 (function () {
18321 if (!(workInProgress.stateNode !== null)) {
18322 {
18323 throw ReactError('We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.');
18324 }
18325 }
18326 })();
18327 // This can happen when we abort work.
18328 }
18329 var _rootContainerInstance = getRootHostContainer();
18330 var _currentHostContext = getHostContext();
18331 var _wasHydrated = popHydrationState(workInProgress);
18332 if (_wasHydrated) {
18333 if (prepareToHydrateHostTextInstance(workInProgress)) {
18334 markUpdate(workInProgress);
18335 }
18336 } else {
18337 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
18338 }
18339 }
18340 break;
18341 }
18342 case ForwardRef:
18343 break;
18344 case SuspenseComponent:
18345 {
18346 var nextState = workInProgress.memoizedState;
18347 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
18348 // Something suspended. Re-render with the fallback children.
18349 workInProgress.expirationTime = renderExpirationTime;
18350 // Do not reset the effect list.
18351 return workInProgress;
18352 }
18353
18354 var nextDidTimeout = nextState !== null;
18355 var prevDidTimeout = current !== null && current.memoizedState !== null;
18356
18357 if (current === null) {
18358 // In cases where we didn't find a suitable hydration boundary we never
18359 // downgraded this to a DehydratedSuspenseComponent, but we still need to
18360 // pop the hydration state since we might be inside the insertion tree.
18361 popHydrationState(workInProgress);
18362 } else if (!nextDidTimeout && prevDidTimeout) {
18363 // We just switched from the fallback to the normal children. Delete
18364 // the fallback.
18365 // TODO: Would it be better to store the fallback fragment on
18366 var currentFallbackChild = current.child.sibling;
18367 if (currentFallbackChild !== null) {
18368 // Deletions go at the beginning of the return fiber's effect list
18369 var first = workInProgress.firstEffect;
18370 if (first !== null) {
18371 workInProgress.firstEffect = currentFallbackChild;
18372 currentFallbackChild.nextEffect = first;
18373 } else {
18374 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
18375 currentFallbackChild.nextEffect = null;
18376 }
18377 currentFallbackChild.effectTag = Deletion;
18378 }
18379 }
18380
18381 if (supportsPersistence) {
18382 if (nextDidTimeout) {
18383 // If this boundary just timed out, schedule an effect to attach a
18384 // retry listener to the proimse. This flag is also used to hide the
18385 // primary children.
18386 workInProgress.effectTag |= Update;
18387 }
18388 }
18389 if (supportsMutation) {
18390 if (nextDidTimeout || prevDidTimeout) {
18391 // If this boundary just timed out, schedule an effect to attach a
18392 // retry listener to the proimse. This flag is also used to hide the
18393 // primary children. In mutation mode, we also need the flag to
18394 // *unhide* children that were previously hidden, so check if the
18395 // is currently timed out, too.
18396 workInProgress.effectTag |= Update;
18397 }
18398 }
18399 break;
18400 }
18401 case Fragment:
18402 break;
18403 case Mode:
18404 break;
18405 case Profiler:
18406 break;
18407 case HostPortal:
18408 popHostContainer(workInProgress);
18409 updateHostContainer(workInProgress);
18410 break;
18411 case ContextProvider:
18412 // Pop provider fiber
18413 popProvider(workInProgress);
18414 break;
18415 case ContextConsumer:
18416 break;
18417 case MemoComponent:
18418 break;
18419 case IncompleteClassComponent:
18420 {
18421 // Same as class component case. I put it down here so that the tags are
18422 // sequential to ensure this switch is compiled to a jump table.
18423 var _Component = workInProgress.type;
18424 if (isContextProvider(_Component)) {
18425 popContext(workInProgress);
18426 }
18427 break;
18428 }
18429 case DehydratedSuspenseComponent:
18430 {
18431 if (enableSuspenseServerRenderer) {
18432 if (current === null) {
18433 var _wasHydrated2 = popHydrationState(workInProgress);
18434 (function () {
18435 if (!_wasHydrated2) {
18436 {
18437 throw ReactError('A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React.');
18438 }
18439 }
18440 })();
18441 skipPastDehydratedSuspenseInstance(workInProgress);
18442 } else if ((workInProgress.effectTag & DidCapture) === NoEffect) {
18443 // This boundary did not suspend so it's now hydrated.
18444 // To handle any future suspense cases, we're going to now upgrade it
18445 // to a Suspense component. We detach it from the existing current fiber.
18446 current.alternate = null;
18447 workInProgress.alternate = null;
18448 workInProgress.tag = SuspenseComponent;
18449 workInProgress.memoizedState = null;
18450 workInProgress.stateNode = null;
18451 }
18452 }
18453 break;
18454 }
18455 case EventComponent:
18456 {
18457 if (enableEventAPI) {
18458 popHostContext(workInProgress);
18459 var _rootContainerInstance2 = getRootHostContainer();
18460 var responder = workInProgress.type.responder;
18461 // Update the props on the event component state node
18462 workInProgress.stateNode.props = newProps;
18463 handleEventComponent(responder, _rootContainerInstance2, workInProgress);
18464 }
18465 break;
18466 }
18467 case EventTarget:
18468 {
18469 if (enableEventAPI) {
18470 popHostContext(workInProgress);
18471 var _type = workInProgress.type.type;
18472 var node = workInProgress.return;
18473 var parentHostInstance = null;
18474 // Traverse up the fiber tree till we find a host component fiber
18475 while (node !== null) {
18476 if (node.tag === HostComponent) {
18477 parentHostInstance = node.stateNode;
18478 break;
18479 }
18480 node = node.return;
18481 }
18482
18483 }
18484 break;
18485 }
18486 default:
18487 (function () {
18488 {
18489 {
18490 throw ReactError('Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
18491 }
18492 }
18493 })();
18494 }
18495
18496 return null;
18497}
18498
18499function shouldCaptureSuspense(workInProgress) {
18500 // In order to capture, the Suspense component must have a fallback prop.
18501 if (workInProgress.memoizedProps.fallback === undefined) {
18502 return false;
18503 }
18504 // If it was the primary children that just suspended, capture and render the
18505 // fallback. Otherwise, don't capture and bubble to the next boundary.
18506 var nextState = workInProgress.memoizedState;
18507 return nextState === null;
18508}
18509
18510// This module is forked in different environments.
18511// By default, return `true` to log errors to the console.
18512// Forks can return `false` if this isn't desirable.
18513function showErrorDialog(capturedError) {
18514 return true;
18515}
18516
18517function logCapturedError(capturedError) {
18518 var logError = showErrorDialog(capturedError);
18519
18520 // Allow injected showErrorDialog() to prevent default console.error logging.
18521 // This enables renderers like ReactNative to better manage redbox behavior.
18522 if (logError === false) {
18523 return;
18524 }
18525
18526 var error = capturedError.error;
18527 {
18528 var componentName = capturedError.componentName,
18529 componentStack = capturedError.componentStack,
18530 errorBoundaryName = capturedError.errorBoundaryName,
18531 errorBoundaryFound = capturedError.errorBoundaryFound,
18532 willRetry = capturedError.willRetry;
18533
18534 // Browsers support silencing uncaught errors by calling
18535 // `preventDefault()` in window `error` handler.
18536 // We record this information as an expando on the error.
18537
18538 if (error != null && error._suppressLogging) {
18539 if (errorBoundaryFound && willRetry) {
18540 // The error is recoverable and was silenced.
18541 // Ignore it and don't print the stack addendum.
18542 // This is handy for testing error boundaries without noise.
18543 return;
18544 }
18545 // The error is fatal. Since the silencing might have
18546 // been accidental, we'll surface it anyway.
18547 // However, the browser would have silenced the original error
18548 // so we'll print it first, and then print the stack addendum.
18549 console.error(error);
18550 // For a more detailed description of this block, see:
18551 // https://github.com/facebook/react/pull/13384
18552 }
18553
18554 var componentNameMessage = componentName ? 'The above error occurred in the <' + componentName + '> component:' : 'The above error occurred in one of your React components:';
18555
18556 var errorBoundaryMessage = void 0;
18557 // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
18558 if (errorBoundaryFound && errorBoundaryName) {
18559 if (willRetry) {
18560 errorBoundaryMessage = 'React will try to recreate this component tree from scratch ' + ('using the error boundary you provided, ' + errorBoundaryName + '.');
18561 } else {
18562 errorBoundaryMessage = 'This error was initially handled by the error boundary ' + errorBoundaryName + '.\n' + 'Recreating the tree from scratch failed so React will unmount the tree.';
18563 }
18564 } else {
18565 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.';
18566 }
18567 var combinedMessage = '' + componentNameMessage + componentStack + '\n\n' + ('' + errorBoundaryMessage);
18568
18569 // In development, we provide our own message with just the component stack.
18570 // We don't include the original error message and JS stack because the browser
18571 // has already printed it. Even if the application swallows the error, it is still
18572 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
18573 console.error(combinedMessage);
18574 }
18575}
18576
18577var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
18578{
18579 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
18580}
18581
18582var PossiblyWeakSet$2 = typeof WeakSet === 'function' ? WeakSet : Set;
18583
18584function logError(boundary, errorInfo) {
18585 var source = errorInfo.source;
18586 var stack = errorInfo.stack;
18587 if (stack === null && source !== null) {
18588 stack = getStackByFiberInDevAndProd(source);
18589 }
18590
18591 var capturedError = {
18592 componentName: source !== null ? getComponentName(source.type) : null,
18593 componentStack: stack !== null ? stack : '',
18594 error: errorInfo.value,
18595 errorBoundary: null,
18596 errorBoundaryName: null,
18597 errorBoundaryFound: false,
18598 willRetry: false
18599 };
18600
18601 if (boundary !== null && boundary.tag === ClassComponent) {
18602 capturedError.errorBoundary = boundary.stateNode;
18603 capturedError.errorBoundaryName = getComponentName(boundary.type);
18604 capturedError.errorBoundaryFound = true;
18605 capturedError.willRetry = true;
18606 }
18607
18608 try {
18609 logCapturedError(capturedError);
18610 } catch (e) {
18611 // This method must not throw, or React internal state will get messed up.
18612 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
18613 // we want to report this error outside of the normal stack as a last resort.
18614 // https://github.com/facebook/react/issues/13188
18615 setTimeout(function () {
18616 throw e;
18617 });
18618 }
18619}
18620
18621var callComponentWillUnmountWithTimer = function (current$$1, instance) {
18622 startPhaseTimer(current$$1, 'componentWillUnmount');
18623 instance.props = current$$1.memoizedProps;
18624 instance.state = current$$1.memoizedState;
18625 instance.componentWillUnmount();
18626 stopPhaseTimer();
18627};
18628
18629// Capture errors so they don't interrupt unmounting.
18630function safelyCallComponentWillUnmount(current$$1, instance) {
18631 {
18632 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
18633 if (hasCaughtError()) {
18634 var unmountError = clearCaughtError();
18635 captureCommitPhaseError$$1(current$$1, unmountError);
18636 }
18637 }
18638}
18639
18640function safelyDetachRef(current$$1) {
18641 var ref = current$$1.ref;
18642 if (ref !== null) {
18643 if (typeof ref === 'function') {
18644 {
18645 invokeGuardedCallback(null, ref, null, null);
18646 if (hasCaughtError()) {
18647 var refError = clearCaughtError();
18648 captureCommitPhaseError$$1(current$$1, refError);
18649 }
18650 }
18651 } else {
18652 ref.current = null;
18653 }
18654 }
18655}
18656
18657function safelyCallDestroy(current$$1, destroy) {
18658 {
18659 invokeGuardedCallback(null, destroy, null);
18660 if (hasCaughtError()) {
18661 var error = clearCaughtError();
18662 captureCommitPhaseError$$1(current$$1, error);
18663 }
18664 }
18665}
18666
18667function commitBeforeMutationLifeCycles(current$$1, finishedWork) {
18668 switch (finishedWork.tag) {
18669 case FunctionComponent:
18670 case ForwardRef:
18671 case SimpleMemoComponent:
18672 {
18673 commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
18674 return;
18675 }
18676 case ClassComponent:
18677 {
18678 if (finishedWork.effectTag & Snapshot) {
18679 if (current$$1 !== null) {
18680 var prevProps = current$$1.memoizedProps;
18681 var prevState = current$$1.memoizedState;
18682 startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
18683 var instance = finishedWork.stateNode;
18684 // We could update instance props and state here,
18685 // but instead we rely on them being set during last render.
18686 // TODO: revisit this when we implement resuming.
18687 {
18688 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
18689 !(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;
18690 !(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;
18691 }
18692 }
18693 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
18694 {
18695 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
18696 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
18697 didWarnSet.add(finishedWork.type);
18698 warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
18699 }
18700 }
18701 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
18702 stopPhaseTimer();
18703 }
18704 }
18705 return;
18706 }
18707 case HostRoot:
18708 case HostComponent:
18709 case HostText:
18710 case HostPortal:
18711 case IncompleteClassComponent:
18712 // Nothing to do for these component types
18713 return;
18714 default:
18715 {
18716 (function () {
18717 {
18718 {
18719 throw ReactError('This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
18720 }
18721 }
18722 })();
18723 }
18724 }
18725}
18726
18727function commitHookEffectList(unmountTag, mountTag, finishedWork) {
18728 var updateQueue = finishedWork.updateQueue;
18729 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
18730 if (lastEffect !== null) {
18731 var firstEffect = lastEffect.next;
18732 var effect = firstEffect;
18733 do {
18734 if ((effect.tag & unmountTag) !== NoEffect$1) {
18735 // Unmount
18736 var destroy = effect.destroy;
18737 effect.destroy = undefined;
18738 if (destroy !== undefined) {
18739 destroy();
18740 }
18741 }
18742 if ((effect.tag & mountTag) !== NoEffect$1) {
18743 // Mount
18744 var create = effect.create;
18745 effect.destroy = create();
18746
18747 {
18748 var _destroy = effect.destroy;
18749 if (_destroy !== undefined && typeof _destroy !== 'function') {
18750 var addendum = void 0;
18751 if (_destroy === null) {
18752 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
18753 } else if (typeof _destroy.then === 'function') {
18754 addendum = '\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + 'useEffect(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + '}, [someId]); // Or [] if effect doesn\'t need props or state\n\n' + 'Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching';
18755 } else {
18756 addendum = ' You returned: ' + _destroy;
18757 }
18758 warningWithoutStack$1(false, 'An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
18759 }
18760 }
18761 }
18762 effect = effect.next;
18763 } while (effect !== firstEffect);
18764 }
18765}
18766
18767function commitPassiveHookEffects(finishedWork) {
18768 commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
18769 commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
18770}
18771
18772function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) {
18773 switch (finishedWork.tag) {
18774 case FunctionComponent:
18775 case ForwardRef:
18776 case SimpleMemoComponent:
18777 {
18778 commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
18779 break;
18780 }
18781 case ClassComponent:
18782 {
18783 var instance = finishedWork.stateNode;
18784 if (finishedWork.effectTag & Update) {
18785 if (current$$1 === null) {
18786 startPhaseTimer(finishedWork, 'componentDidMount');
18787 // We could update instance props and state here,
18788 // but instead we rely on them being set during last render.
18789 // TODO: revisit this when we implement resuming.
18790 {
18791 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
18792 !(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;
18793 !(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;
18794 }
18795 }
18796 instance.componentDidMount();
18797 stopPhaseTimer();
18798 } else {
18799 var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);
18800 var prevState = current$$1.memoizedState;
18801 startPhaseTimer(finishedWork, 'componentDidUpdate');
18802 // We could update instance props and state here,
18803 // but instead we rely on them being set during last render.
18804 // TODO: revisit this when we implement resuming.
18805 {
18806 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
18807 !(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;
18808 !(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;
18809 }
18810 }
18811 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
18812 stopPhaseTimer();
18813 }
18814 }
18815 var updateQueue = finishedWork.updateQueue;
18816 if (updateQueue !== null) {
18817 {
18818 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
18819 !(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;
18820 !(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;
18821 }
18822 }
18823 // We could update instance props and state here,
18824 // but instead we rely on them being set during last render.
18825 // TODO: revisit this when we implement resuming.
18826 commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
18827 }
18828 return;
18829 }
18830 case HostRoot:
18831 {
18832 var _updateQueue = finishedWork.updateQueue;
18833 if (_updateQueue !== null) {
18834 var _instance = null;
18835 if (finishedWork.child !== null) {
18836 switch (finishedWork.child.tag) {
18837 case HostComponent:
18838 _instance = getPublicInstance(finishedWork.child.stateNode);
18839 break;
18840 case ClassComponent:
18841 _instance = finishedWork.child.stateNode;
18842 break;
18843 }
18844 }
18845 commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
18846 }
18847 return;
18848 }
18849 case HostComponent:
18850 {
18851 var _instance2 = finishedWork.stateNode;
18852
18853 // Renderers may schedule work to be done after host components are mounted
18854 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
18855 // These effects should only be committed when components are first mounted,
18856 // aka when there is no current/alternate.
18857 if (current$$1 === null && finishedWork.effectTag & Update) {
18858 var type = finishedWork.type;
18859 var props = finishedWork.memoizedProps;
18860 commitMount(_instance2, type, props, finishedWork);
18861 }
18862
18863 return;
18864 }
18865 case HostText:
18866 {
18867 // We have no life-cycles associated with text.
18868 return;
18869 }
18870 case HostPortal:
18871 {
18872 // We have no life-cycles associated with portals.
18873 return;
18874 }
18875 case Profiler:
18876 {
18877 if (enableProfilerTimer) {
18878 var onRender = finishedWork.memoizedProps.onRender;
18879
18880 if (enableSchedulerTracing) {
18881 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
18882 } else {
18883 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
18884 }
18885 }
18886 return;
18887 }
18888 case SuspenseComponent:
18889 case IncompleteClassComponent:
18890 break;
18891 default:
18892 {
18893 (function () {
18894 {
18895 {
18896 throw ReactError('This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
18897 }
18898 }
18899 })();
18900 }
18901 }
18902}
18903
18904function hideOrUnhideAllChildren(finishedWork, isHidden) {
18905 if (supportsMutation) {
18906 // We only have the top Fiber that was inserted but we need to recurse down its
18907 var node = finishedWork;
18908 while (true) {
18909 if (node.tag === HostComponent) {
18910 var instance = node.stateNode;
18911 if (isHidden) {
18912 hideInstance(instance);
18913 } else {
18914 unhideInstance(node.stateNode, node.memoizedProps);
18915 }
18916 } else if (node.tag === HostText) {
18917 var _instance3 = node.stateNode;
18918 if (isHidden) {
18919 hideTextInstance(_instance3);
18920 } else {
18921 unhideTextInstance(_instance3, node.memoizedProps);
18922 }
18923 } else if (node.tag === SuspenseComponent && node.memoizedState !== null) {
18924 // Found a nested Suspense component that timed out. Skip over the
18925 var fallbackChildFragment = node.child.sibling;
18926 fallbackChildFragment.return = node;
18927 node = fallbackChildFragment;
18928 continue;
18929 } else if (node.child !== null) {
18930 node.child.return = node;
18931 node = node.child;
18932 continue;
18933 }
18934 if (node === finishedWork) {
18935 return;
18936 }
18937 while (node.sibling === null) {
18938 if (node.return === null || node.return === finishedWork) {
18939 return;
18940 }
18941 node = node.return;
18942 }
18943 node.sibling.return = node.return;
18944 node = node.sibling;
18945 }
18946 }
18947}
18948
18949function commitAttachRef(finishedWork) {
18950 var ref = finishedWork.ref;
18951 if (ref !== null) {
18952 var instance = finishedWork.stateNode;
18953 var instanceToUse = void 0;
18954 switch (finishedWork.tag) {
18955 case HostComponent:
18956 instanceToUse = getPublicInstance(instance);
18957 break;
18958 default:
18959 instanceToUse = instance;
18960 }
18961 if (typeof ref === 'function') {
18962 ref(instanceToUse);
18963 } else {
18964 {
18965 if (!ref.hasOwnProperty('current')) {
18966 warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
18967 }
18968 }
18969
18970 ref.current = instanceToUse;
18971 }
18972 }
18973}
18974
18975function commitDetachRef(current$$1) {
18976 var currentRef = current$$1.ref;
18977 if (currentRef !== null) {
18978 if (typeof currentRef === 'function') {
18979 currentRef(null);
18980 } else {
18981 currentRef.current = null;
18982 }
18983 }
18984}
18985
18986// User-originating errors (lifecycles and refs) should not interrupt
18987// deletion, so don't let them throw. Host-originating errors should
18988// interrupt deletion, so it's okay
18989function commitUnmount(current$$1) {
18990 onCommitUnmount(current$$1);
18991
18992 switch (current$$1.tag) {
18993 case FunctionComponent:
18994 case ForwardRef:
18995 case MemoComponent:
18996 case SimpleMemoComponent:
18997 {
18998 var updateQueue = current$$1.updateQueue;
18999 if (updateQueue !== null) {
19000 var lastEffect = updateQueue.lastEffect;
19001 if (lastEffect !== null) {
19002 var firstEffect = lastEffect.next;
19003 var effect = firstEffect;
19004 do {
19005 var destroy = effect.destroy;
19006 if (destroy !== undefined) {
19007 safelyCallDestroy(current$$1, destroy);
19008 }
19009 effect = effect.next;
19010 } while (effect !== firstEffect);
19011 }
19012 }
19013 break;
19014 }
19015 case ClassComponent:
19016 {
19017 safelyDetachRef(current$$1);
19018 var instance = current$$1.stateNode;
19019 if (typeof instance.componentWillUnmount === 'function') {
19020 safelyCallComponentWillUnmount(current$$1, instance);
19021 }
19022 return;
19023 }
19024 case HostComponent:
19025 {
19026 safelyDetachRef(current$$1);
19027 return;
19028 }
19029 case HostPortal:
19030 {
19031 // TODO: this is recursive.
19032 // We are also not using this parent because
19033 // the portal will get pushed immediately.
19034 if (supportsMutation) {
19035 unmountHostComponents(current$$1);
19036 } else if (supportsPersistence) {
19037 emptyPortalContainer(current$$1);
19038 }
19039 return;
19040 }
19041 }
19042}
19043
19044function commitNestedUnmounts(root) {
19045 // While we're inside a removed host node we don't want to call
19046 // removeChild on the inner nodes because they're removed by the top
19047 // call anyway. We also want to call componentWillUnmount on all
19048 // composites before this host node is removed from the tree. Therefore
19049 var node = root;
19050 while (true) {
19051 commitUnmount(node);
19052 // Visit children because they may contain more composite or host nodes.
19053 // Skip portals because commitUnmount() currently visits them recursively.
19054 if (node.child !== null && (
19055 // If we use mutation we drill down into portals using commitUnmount above.
19056 // If we don't use mutation we drill down into portals here instead.
19057 !supportsMutation || node.tag !== HostPortal)) {
19058 node.child.return = node;
19059 node = node.child;
19060 continue;
19061 }
19062 if (node === root) {
19063 return;
19064 }
19065 while (node.sibling === null) {
19066 if (node.return === null || node.return === root) {
19067 return;
19068 }
19069 node = node.return;
19070 }
19071 node.sibling.return = node.return;
19072 node = node.sibling;
19073 }
19074}
19075
19076function detachFiber(current$$1) {
19077 // Cut off the return pointers to disconnect it from the tree. Ideally, we
19078 // should clear the child pointer of the parent alternate to let this
19079 // get GC:ed but we don't know which for sure which parent is the current
19080 // one so we'll settle for GC:ing the subtree of this child. This child
19081 // itself will be GC:ed when the parent updates the next time.
19082 current$$1.return = null;
19083 current$$1.child = null;
19084 current$$1.memoizedState = null;
19085 current$$1.updateQueue = null;
19086 var alternate = current$$1.alternate;
19087 if (alternate !== null) {
19088 alternate.return = null;
19089 alternate.child = null;
19090 alternate.memoizedState = null;
19091 alternate.updateQueue = null;
19092 }
19093}
19094
19095function emptyPortalContainer(current$$1) {
19096 if (!supportsPersistence) {
19097 return;
19098 }
19099
19100 var portal = current$$1.stateNode;
19101 var containerInfo = portal.containerInfo;
19102
19103 var emptyChildSet = createContainerChildSet(containerInfo);
19104 replaceContainerChildren(containerInfo, emptyChildSet);
19105}
19106
19107function commitContainer(finishedWork) {
19108 if (!supportsPersistence) {
19109 return;
19110 }
19111
19112 switch (finishedWork.tag) {
19113 case ClassComponent:
19114 case HostComponent:
19115 case HostText:
19116 {
19117 return;
19118 }
19119 case HostRoot:
19120 case HostPortal:
19121 {
19122 var portalOrRoot = finishedWork.stateNode;
19123 var containerInfo = portalOrRoot.containerInfo,
19124 _pendingChildren = portalOrRoot.pendingChildren;
19125
19126 replaceContainerChildren(containerInfo, _pendingChildren);
19127 return;
19128 }
19129 default:
19130 {
19131 (function () {
19132 {
19133 {
19134 throw ReactError('This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
19135 }
19136 }
19137 })();
19138 }
19139 }
19140}
19141
19142function getHostParentFiber(fiber) {
19143 var parent = fiber.return;
19144 while (parent !== null) {
19145 if (isHostParent(parent)) {
19146 return parent;
19147 }
19148 parent = parent.return;
19149 }
19150 (function () {
19151 {
19152 {
19153 throw ReactError('Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.');
19154 }
19155 }
19156 })();
19157}
19158
19159function isHostParent(fiber) {
19160 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
19161}
19162
19163function getHostSibling(fiber) {
19164 // We're going to search forward into the tree until we find a sibling host
19165 // node. Unfortunately, if multiple insertions are done in a row we have to
19166 // search past them. This leads to exponential search for the next sibling.
19167 var node = fiber;
19168 siblings: while (true) {
19169 // If we didn't find anything, let's try the next sibling.
19170 while (node.sibling === null) {
19171 if (node.return === null || isHostParent(node.return)) {
19172 // If we pop out of the root or hit the parent the fiber we are the
19173 // last sibling.
19174 return null;
19175 }
19176 node = node.return;
19177 }
19178 node.sibling.return = node.return;
19179 node = node.sibling;
19180 while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedSuspenseComponent) {
19181 // If it is not host node and, we might have a host node inside it.
19182 // Try to search down until we find one.
19183 if (node.effectTag & Placement) {
19184 // If we don't have a child, try the siblings instead.
19185 continue siblings;
19186 }
19187 // If we don't have a child, try the siblings instead.
19188 // We also skip portals because they are not part of this host tree.
19189 if (node.child === null || node.tag === HostPortal) {
19190 continue siblings;
19191 } else {
19192 node.child.return = node;
19193 node = node.child;
19194 }
19195 }
19196 // Check if this host node is stable or about to be placed.
19197 if (!(node.effectTag & Placement)) {
19198 // Found it!
19199 return node.stateNode;
19200 }
19201 }
19202}
19203
19204function commitPlacement(finishedWork) {
19205 if (!supportsMutation) {
19206 return;
19207 }
19208
19209 // Recursively insert all host nodes into the parent.
19210 var parentFiber = getHostParentFiber(finishedWork);
19211
19212 // Note: these two variables *must* always be updated together.
19213 var parent = void 0;
19214 var isContainer = void 0;
19215
19216 switch (parentFiber.tag) {
19217 case HostComponent:
19218 parent = parentFiber.stateNode;
19219 isContainer = false;
19220 break;
19221 case HostRoot:
19222 parent = parentFiber.stateNode.containerInfo;
19223 isContainer = true;
19224 break;
19225 case HostPortal:
19226 parent = parentFiber.stateNode.containerInfo;
19227 isContainer = true;
19228 break;
19229 default:
19230 (function () {
19231 {
19232 {
19233 throw ReactError('Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.');
19234 }
19235 }
19236 })();
19237 }
19238 if (parentFiber.effectTag & ContentReset) {
19239 // Reset the text content of the parent before doing any insertions
19240 resetTextContent(parent);
19241 // Clear ContentReset from the effect tag
19242 parentFiber.effectTag &= ~ContentReset;
19243 }
19244
19245 var before = getHostSibling(finishedWork);
19246 // We only have the top Fiber that was inserted but we need to recurse down its
19247 // children to find all the terminal nodes.
19248 var node = finishedWork;
19249 while (true) {
19250 if (node.tag === HostComponent || node.tag === HostText) {
19251 if (before) {
19252 if (isContainer) {
19253 insertInContainerBefore(parent, node.stateNode, before);
19254 } else {
19255 insertBefore(parent, node.stateNode, before);
19256 }
19257 } else {
19258 if (isContainer) {
19259 appendChildToContainer(parent, node.stateNode);
19260 } else {
19261 appendChild(parent, node.stateNode);
19262 }
19263 }
19264 } else if (node.tag === HostPortal) {
19265 // If the insertion itself is a portal, then we don't want to traverse
19266 // down its children. Instead, we'll get insertions from each child in
19267 // the portal directly.
19268 } else if (node.child !== null) {
19269 node.child.return = node;
19270 node = node.child;
19271 continue;
19272 }
19273 if (node === finishedWork) {
19274 return;
19275 }
19276 while (node.sibling === null) {
19277 if (node.return === null || node.return === finishedWork) {
19278 return;
19279 }
19280 node = node.return;
19281 }
19282 node.sibling.return = node.return;
19283 node = node.sibling;
19284 }
19285}
19286
19287function unmountHostComponents(current$$1) {
19288 // We only have the top Fiber that was deleted but we need to recurse down its
19289 var node = current$$1;
19290
19291 // Each iteration, currentParent is populated with node's host parent if not
19292 // currentParentIsValid.
19293 var currentParentIsValid = false;
19294
19295 // Note: these two variables *must* always be updated together.
19296 var currentParent = void 0;
19297 var currentParentIsContainer = void 0;
19298
19299 while (true) {
19300 if (!currentParentIsValid) {
19301 var parent = node.return;
19302 findParent: while (true) {
19303 (function () {
19304 if (!(parent !== null)) {
19305 {
19306 throw ReactError('Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.');
19307 }
19308 }
19309 })();
19310 switch (parent.tag) {
19311 case HostComponent:
19312 currentParent = parent.stateNode;
19313 currentParentIsContainer = false;
19314 break findParent;
19315 case HostRoot:
19316 currentParent = parent.stateNode.containerInfo;
19317 currentParentIsContainer = true;
19318 break findParent;
19319 case HostPortal:
19320 currentParent = parent.stateNode.containerInfo;
19321 currentParentIsContainer = true;
19322 break findParent;
19323 }
19324 parent = parent.return;
19325 }
19326 currentParentIsValid = true;
19327 }
19328
19329 if (node.tag === HostComponent || node.tag === HostText) {
19330 commitNestedUnmounts(node);
19331 // After all the children have unmounted, it is now safe to remove the
19332 // node from the tree.
19333 if (currentParentIsContainer) {
19334 removeChildFromContainer(currentParent, node.stateNode);
19335 } else {
19336 removeChild(currentParent, node.stateNode);
19337 }
19338 // Don't visit children because we already visited them.
19339 } else if (enableSuspenseServerRenderer && node.tag === DehydratedSuspenseComponent) {
19340 // Delete the dehydrated suspense boundary and all of its content.
19341 if (currentParentIsContainer) {
19342 clearSuspenseBoundaryFromContainer(currentParent, node.stateNode);
19343 } else {
19344 clearSuspenseBoundary(currentParent, node.stateNode);
19345 }
19346 } else if (node.tag === HostPortal) {
19347 if (node.child !== null) {
19348 // When we go into a portal, it becomes the parent to remove from.
19349 // We will reassign it back when we pop the portal on the way up.
19350 currentParent = node.stateNode.containerInfo;
19351 currentParentIsContainer = true;
19352 // Visit children because portals might contain host components.
19353 node.child.return = node;
19354 node = node.child;
19355 continue;
19356 }
19357 } else {
19358 commitUnmount(node);
19359 // Visit children because we may find more host components below.
19360 if (node.child !== null) {
19361 node.child.return = node;
19362 node = node.child;
19363 continue;
19364 }
19365 }
19366 if (node === current$$1) {
19367 return;
19368 }
19369 while (node.sibling === null) {
19370 if (node.return === null || node.return === current$$1) {
19371 return;
19372 }
19373 node = node.return;
19374 if (node.tag === HostPortal) {
19375 // When we go out of the portal, we need to restore the parent.
19376 // Since we don't keep a stack of them, we will search for it.
19377 currentParentIsValid = false;
19378 }
19379 }
19380 node.sibling.return = node.return;
19381 node = node.sibling;
19382 }
19383}
19384
19385function commitDeletion(current$$1) {
19386 if (supportsMutation) {
19387 // Recursively delete all host nodes from the parent.
19388 // Detach refs and call componentWillUnmount() on the whole subtree.
19389 unmountHostComponents(current$$1);
19390 } else {
19391 // Detach refs and call componentWillUnmount() on the whole subtree.
19392 commitNestedUnmounts(current$$1);
19393 }
19394 detachFiber(current$$1);
19395}
19396
19397function commitWork(current$$1, finishedWork) {
19398 if (!supportsMutation) {
19399 switch (finishedWork.tag) {
19400 case FunctionComponent:
19401 case ForwardRef:
19402 case MemoComponent:
19403 case SimpleMemoComponent:
19404 {
19405 // Note: We currently never use MountMutation, but useLayout uses
19406 // UnmountMutation.
19407 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
19408 return;
19409 }
19410 case Profiler:
19411 {
19412 return;
19413 }
19414 case SuspenseComponent:
19415 {
19416 commitSuspenseComponent(finishedWork);
19417 return;
19418 }
19419 }
19420
19421 commitContainer(finishedWork);
19422 return;
19423 }
19424
19425 switch (finishedWork.tag) {
19426 case FunctionComponent:
19427 case ForwardRef:
19428 case MemoComponent:
19429 case SimpleMemoComponent:
19430 {
19431 // Note: We currently never use MountMutation, but useLayout uses
19432 // UnmountMutation.
19433 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
19434 return;
19435 }
19436 case ClassComponent:
19437 {
19438 return;
19439 }
19440 case HostComponent:
19441 {
19442 var instance = finishedWork.stateNode;
19443 if (instance != null) {
19444 // Commit the work prepared earlier.
19445 var newProps = finishedWork.memoizedProps;
19446 // For hydration we reuse the update path but we treat the oldProps
19447 // as the newProps. The updatePayload will contain the real change in
19448 // this case.
19449 var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps;
19450 var type = finishedWork.type;
19451 // TODO: Type the updateQueue to be specific to host components.
19452 var updatePayload = finishedWork.updateQueue;
19453 finishedWork.updateQueue = null;
19454 if (updatePayload !== null) {
19455 commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
19456 }
19457 }
19458 return;
19459 }
19460 case HostText:
19461 {
19462 (function () {
19463 if (!(finishedWork.stateNode !== null)) {
19464 {
19465 throw ReactError('This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.');
19466 }
19467 }
19468 })();
19469 var textInstance = finishedWork.stateNode;
19470 var newText = finishedWork.memoizedProps;
19471 // For hydration we reuse the update path but we treat the oldProps
19472 // as the newProps. The updatePayload will contain the real change in
19473 // this case.
19474 var oldText = current$$1 !== null ? current$$1.memoizedProps : newText;
19475 commitTextUpdate(textInstance, oldText, newText);
19476 return;
19477 }
19478 case HostRoot:
19479 {
19480 return;
19481 }
19482 case Profiler:
19483 {
19484 return;
19485 }
19486 case SuspenseComponent:
19487 {
19488 commitSuspenseComponent(finishedWork);
19489 return;
19490 }
19491 case IncompleteClassComponent:
19492 {
19493 return;
19494 }
19495 default:
19496 {
19497 (function () {
19498 {
19499 {
19500 throw ReactError('This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
19501 }
19502 }
19503 })();
19504 }
19505 }
19506}
19507
19508function commitSuspenseComponent(finishedWork) {
19509 var newState = finishedWork.memoizedState;
19510
19511 var newDidTimeout = void 0;
19512 var primaryChildParent = finishedWork;
19513 if (newState === null) {
19514 newDidTimeout = false;
19515 } else {
19516 newDidTimeout = true;
19517 primaryChildParent = finishedWork.child;
19518 if (newState.timedOutAt === NoWork) {
19519 // If the children had not already timed out, record the time.
19520 // This is used to compute the elapsed time during subsequent
19521 // attempts to render the children.
19522 newState.timedOutAt = requestCurrentTime$$1();
19523 }
19524 }
19525
19526 if (supportsMutation && primaryChildParent !== null) {
19527 hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
19528 }
19529
19530 // If this boundary just timed out, then it will have a set of thenables.
19531 // For each thenable, attach a listener so that when it resolves, React
19532 // attempts to re-render the boundary in the primary (pre-timeout) state.
19533 var thenables = finishedWork.updateQueue;
19534 if (thenables !== null) {
19535 finishedWork.updateQueue = null;
19536 var retryCache = finishedWork.stateNode;
19537 if (retryCache === null) {
19538 retryCache = finishedWork.stateNode = new PossiblyWeakSet$2();
19539 }
19540 thenables.forEach(function (thenable) {
19541 // Memoize using the boundary fiber to prevent redundant listeners.
19542 var retry = resolveRetryThenable$$1.bind(null, finishedWork, thenable);
19543 if (enableSchedulerTracing) {
19544 retry = unstable_wrap(retry);
19545 }
19546 if (!retryCache.has(thenable)) {
19547 retryCache.add(thenable);
19548 thenable.then(retry, retry);
19549 }
19550 });
19551 }
19552}
19553
19554function commitResetTextContent(current$$1) {
19555 if (!supportsMutation) {
19556 return;
19557 }
19558 resetTextContent(current$$1.stateNode);
19559}
19560
19561var PossiblyWeakSet$1 = typeof WeakSet === 'function' ? WeakSet : Set;
19562var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;
19563
19564function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
19565 var update = createUpdate(expirationTime);
19566 // Unmount the root by rendering null.
19567 update.tag = CaptureUpdate;
19568 // Caution: React DevTools currently depends on this property
19569 // being called "element".
19570 update.payload = { element: null };
19571 var error = errorInfo.value;
19572 update.callback = function () {
19573 onUncaughtError$$1(error);
19574 logError(fiber, errorInfo);
19575 };
19576 return update;
19577}
19578
19579function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
19580 var update = createUpdate(expirationTime);
19581 update.tag = CaptureUpdate;
19582 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
19583 if (typeof getDerivedStateFromError === 'function') {
19584 var error = errorInfo.value;
19585 update.payload = function () {
19586 return getDerivedStateFromError(error);
19587 };
19588 }
19589
19590 var inst = fiber.stateNode;
19591 if (inst !== null && typeof inst.componentDidCatch === 'function') {
19592 update.callback = function callback() {
19593 if (typeof getDerivedStateFromError !== 'function') {
19594 // To preserve the preexisting retry behavior of error boundaries,
19595 // we keep track of which ones already failed during this batch.
19596 // This gets reset before we yield back to the browser.
19597 // TODO: Warn in strict mode if getDerivedStateFromError is
19598 // not defined.
19599 markLegacyErrorBoundaryAsFailed$$1(this);
19600 }
19601 var error = errorInfo.value;
19602 var stack = errorInfo.stack;
19603 logError(fiber, errorInfo);
19604 this.componentDidCatch(error, {
19605 componentStack: stack !== null ? stack : ''
19606 });
19607 {
19608 if (typeof getDerivedStateFromError !== 'function') {
19609 // If componentDidCatch is the only error boundary method defined,
19610 // then it needs to call setState to recover from errors.
19611 // If no state update is scheduled then the boundary will swallow the error.
19612 !(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;
19613 }
19614 }
19615 };
19616 }
19617 return update;
19618}
19619
19620function attachPingListener(root, renderExpirationTime, thenable) {
19621 // Attach a listener to the promise to "ping" the root and retry. But
19622 // only if one does not already exist for the current render expiration
19623 // time (which acts like a "thread ID" here).
19624 var pingCache = root.pingCache;
19625 var threadIDs = void 0;
19626 if (pingCache === null) {
19627 pingCache = root.pingCache = new PossiblyWeakMap$1();
19628 threadIDs = new Set();
19629 pingCache.set(thenable, threadIDs);
19630 } else {
19631 threadIDs = pingCache.get(thenable);
19632 if (threadIDs === undefined) {
19633 threadIDs = new Set();
19634 pingCache.set(thenable, threadIDs);
19635 }
19636 }
19637 if (!threadIDs.has(renderExpirationTime)) {
19638 // Memoize using the thread ID to prevent redundant listeners.
19639 threadIDs.add(renderExpirationTime);
19640 var ping = pingSuspendedRoot$$1.bind(null, root, thenable, renderExpirationTime);
19641 if (enableSchedulerTracing) {
19642 ping = unstable_wrap(ping);
19643 }
19644 thenable.then(ping, ping);
19645 }
19646}
19647
19648function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
19649 // The source fiber did not complete.
19650 sourceFiber.effectTag |= Incomplete;
19651 // Its effect list is no longer valid.
19652 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
19653
19654 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
19655 // This is a thenable.
19656 var thenable = value;
19657
19658 // Find the earliest timeout threshold of all the placeholders in the
19659 // ancestor path. We could avoid this traversal by storing the thresholds on
19660 // the stack, but we choose not to because we only hit this path if we're
19661 // IO-bound (i.e. if something suspends). Whereas the stack is used even in
19662 // the non-IO- bound case.
19663 var _workInProgress = returnFiber;
19664 var earliestTimeoutMs = -1;
19665 var startTimeMs = -1;
19666 do {
19667 if (_workInProgress.tag === SuspenseComponent) {
19668 var current$$1 = _workInProgress.alternate;
19669 if (current$$1 !== null) {
19670 var currentState = current$$1.memoizedState;
19671 if (currentState !== null) {
19672 // Reached a boundary that already timed out. Do not search
19673 // any further.
19674 var timedOutAt = currentState.timedOutAt;
19675 startTimeMs = expirationTimeToMs(timedOutAt);
19676 // Do not search any further.
19677 break;
19678 }
19679 }
19680 var defaultSuspenseTimeout = 150;
19681 if (earliestTimeoutMs === -1 || defaultSuspenseTimeout < earliestTimeoutMs) {
19682 earliestTimeoutMs = defaultSuspenseTimeout;
19683 }
19684 }
19685 // If there is a DehydratedSuspenseComponent we don't have to do anything because
19686 // if something suspends inside it, we will simply leave that as dehydrated. It
19687 // will never timeout.
19688 _workInProgress = _workInProgress.return;
19689 } while (_workInProgress !== null);
19690
19691 // Schedule the nearest Suspense to re-render the timed out view.
19692 _workInProgress = returnFiber;
19693 do {
19694 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress)) {
19695 // Found the nearest boundary.
19696
19697 // Stash the promise on the boundary fiber. If the boundary times out, we'll
19698 var thenables = _workInProgress.updateQueue;
19699 if (thenables === null) {
19700 var updateQueue = new Set();
19701 updateQueue.add(thenable);
19702 _workInProgress.updateQueue = updateQueue;
19703 } else {
19704 thenables.add(thenable);
19705 }
19706
19707 // If the boundary is outside of concurrent mode, we should *not*
19708 // suspend the commit. Pretend as if the suspended component rendered
19709 // null and keep rendering. In the commit phase, we'll schedule a
19710 // subsequent synchronous update to re-render the Suspense.
19711 //
19712 // Note: It doesn't matter whether the component that suspended was
19713 // inside a concurrent mode tree. If the Suspense is outside of it, we
19714 // should *not* suspend the commit.
19715 if ((_workInProgress.mode & ConcurrentMode) === NoEffect) {
19716 _workInProgress.effectTag |= DidCapture;
19717
19718 // We're going to commit this fiber even though it didn't complete.
19719 // But we shouldn't call any lifecycle methods or callbacks. Remove
19720 // all lifecycle effect tags.
19721 sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
19722
19723 if (sourceFiber.tag === ClassComponent) {
19724 var currentSourceFiber = sourceFiber.alternate;
19725 if (currentSourceFiber === null) {
19726 // This is a new mount. Change the tag so it's not mistaken for a
19727 // completed class component. For example, we should not call
19728 // componentWillUnmount if it is deleted.
19729 sourceFiber.tag = IncompleteClassComponent;
19730 } else {
19731 // When we try rendering again, we should not reuse the current fiber,
19732 // since it's known to be in an inconsistent state. Use a force updte to
19733 // prevent a bail out.
19734 var update = createUpdate(Sync);
19735 update.tag = ForceUpdate;
19736 enqueueUpdate(sourceFiber, update);
19737 }
19738 }
19739
19740 // The source fiber did not complete. Mark it with Sync priority to
19741 // indicate that it still has pending work.
19742 sourceFiber.expirationTime = Sync;
19743
19744 // Exit without suspending.
19745 return;
19746 }
19747
19748 // Confirmed that the boundary is in a concurrent mode tree. Continue
19749 // with the normal suspend path.
19750
19751 attachPingListener(root, renderExpirationTime, thenable);
19752
19753 var absoluteTimeoutMs = void 0;
19754 if (earliestTimeoutMs === -1) {
19755 // If no explicit threshold is given, default to an arbitrarily large
19756 // value. The actual size doesn't matter because the threshold for the
19757 // whole tree will be clamped to the expiration time.
19758 absoluteTimeoutMs = maxSigned31BitInt;
19759 } else {
19760 if (startTimeMs === -1) {
19761 // This suspend happened outside of any already timed-out
19762 // placeholders. We don't know exactly when the update was
19763 // scheduled, but we can infer an approximate start time based on
19764 // the expiration time and the priority.
19765 startTimeMs = inferStartTimeFromExpirationTime$$1(root, renderExpirationTime);
19766 }
19767 absoluteTimeoutMs = startTimeMs + earliestTimeoutMs;
19768 }
19769
19770 // Mark the earliest timeout in the suspended fiber's ancestor path.
19771 // After completing the root, we'll take the largest of all the
19772 // suspended fiber's timeouts and use it to compute a timeout for the
19773 // whole tree.
19774 renderDidSuspend$$1(root, absoluteTimeoutMs, renderExpirationTime);
19775
19776 _workInProgress.effectTag |= ShouldCapture;
19777 _workInProgress.expirationTime = renderExpirationTime;
19778 return;
19779 } else if (enableSuspenseServerRenderer && _workInProgress.tag === DehydratedSuspenseComponent) {
19780 attachPingListener(root, renderExpirationTime, thenable);
19781
19782 // Since we already have a current fiber, we can eagerly add a retry listener.
19783 var retryCache = _workInProgress.memoizedState;
19784 if (retryCache === null) {
19785 retryCache = _workInProgress.memoizedState = new PossiblyWeakSet$1();
19786 var _current = _workInProgress.alternate;
19787 (function () {
19788 if (!_current) {
19789 {
19790 throw ReactError('A dehydrated suspense boundary must commit before trying to render. This is probably a bug in React.');
19791 }
19792 }
19793 })();
19794 _current.memoizedState = retryCache;
19795 }
19796 // Memoize using the boundary fiber to prevent redundant listeners.
19797 if (!retryCache.has(thenable)) {
19798 retryCache.add(thenable);
19799 var retry = resolveRetryThenable$$1.bind(null, _workInProgress, thenable);
19800 if (enableSchedulerTracing) {
19801 retry = unstable_wrap(retry);
19802 }
19803 thenable.then(retry, retry);
19804 }
19805 _workInProgress.effectTag |= ShouldCapture;
19806 _workInProgress.expirationTime = renderExpirationTime;
19807 return;
19808 }
19809 // This boundary already captured during this render. Continue to the next
19810 // boundary.
19811 _workInProgress = _workInProgress.return;
19812 } while (_workInProgress !== null);
19813 // No boundary was found. Fallthrough to error mode.
19814 // TODO: Use invariant so the message is stripped in prod?
19815 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));
19816 }
19817
19818 // We didn't find a boundary that could handle this type of exception. Start
19819 // over and traverse parent path again, this time treating the exception
19820 // as an error.
19821 renderDidError$$1();
19822 value = createCapturedValue(value, sourceFiber);
19823 var workInProgress = returnFiber;
19824 do {
19825 switch (workInProgress.tag) {
19826 case HostRoot:
19827 {
19828 var _errorInfo = value;
19829 workInProgress.effectTag |= ShouldCapture;
19830 workInProgress.expirationTime = renderExpirationTime;
19831 var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
19832 enqueueCapturedUpdate(workInProgress, _update);
19833 return;
19834 }
19835 case ClassComponent:
19836 // Capture and retry
19837 var errorInfo = value;
19838 var ctor = workInProgress.type;
19839 var instance = workInProgress.stateNode;
19840 if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary$$1(instance))) {
19841 workInProgress.effectTag |= ShouldCapture;
19842 workInProgress.expirationTime = renderExpirationTime;
19843 // Schedule the error boundary to re-render using updated state
19844 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
19845 enqueueCapturedUpdate(workInProgress, _update2);
19846 return;
19847 }
19848 break;
19849 default:
19850 break;
19851 }
19852 workInProgress = workInProgress.return;
19853 } while (workInProgress !== null);
19854}
19855
19856function unwindWork(workInProgress, renderExpirationTime) {
19857 switch (workInProgress.tag) {
19858 case ClassComponent:
19859 {
19860 var Component = workInProgress.type;
19861 if (isContextProvider(Component)) {
19862 popContext(workInProgress);
19863 }
19864 var effectTag = workInProgress.effectTag;
19865 if (effectTag & ShouldCapture) {
19866 workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
19867 return workInProgress;
19868 }
19869 return null;
19870 }
19871 case HostRoot:
19872 {
19873 popHostContainer(workInProgress);
19874 popTopLevelContextObject(workInProgress);
19875 var _effectTag = workInProgress.effectTag;
19876 (function () {
19877 if (!((_effectTag & DidCapture) === NoEffect)) {
19878 {
19879 throw ReactError('The root failed to unmount after an error. This is likely a bug in React. Please file an issue.');
19880 }
19881 }
19882 })();
19883 workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
19884 return workInProgress;
19885 }
19886 case HostComponent:
19887 {
19888 // TODO: popHydrationState
19889 popHostContext(workInProgress);
19890 return null;
19891 }
19892 case SuspenseComponent:
19893 {
19894 var _effectTag2 = workInProgress.effectTag;
19895 if (_effectTag2 & ShouldCapture) {
19896 workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture;
19897 // Captured a suspense effect. Re-render the boundary.
19898 return workInProgress;
19899 }
19900 return null;
19901 }
19902 case DehydratedSuspenseComponent:
19903 {
19904 if (enableSuspenseServerRenderer) {
19905 // TODO: popHydrationState
19906 var _effectTag3 = workInProgress.effectTag;
19907 if (_effectTag3 & ShouldCapture) {
19908 workInProgress.effectTag = _effectTag3 & ~ShouldCapture | DidCapture;
19909 // Captured a suspense effect. Re-render the boundary.
19910 return workInProgress;
19911 }
19912 }
19913 return null;
19914 }
19915 case HostPortal:
19916 popHostContainer(workInProgress);
19917 return null;
19918 case ContextProvider:
19919 popProvider(workInProgress);
19920 return null;
19921 case EventComponent:
19922 case EventTarget:
19923 if (enableEventAPI) {
19924 popHostContext(workInProgress);
19925 }
19926 return null;
19927 default:
19928 return null;
19929 }
19930}
19931
19932function unwindInterruptedWork(interruptedWork) {
19933 switch (interruptedWork.tag) {
19934 case ClassComponent:
19935 {
19936 var childContextTypes = interruptedWork.type.childContextTypes;
19937 if (childContextTypes !== null && childContextTypes !== undefined) {
19938 popContext(interruptedWork);
19939 }
19940 break;
19941 }
19942 case HostRoot:
19943 {
19944 popHostContainer(interruptedWork);
19945 popTopLevelContextObject(interruptedWork);
19946 break;
19947 }
19948 case HostComponent:
19949 {
19950 popHostContext(interruptedWork);
19951 break;
19952 }
19953 case HostPortal:
19954 popHostContainer(interruptedWork);
19955 break;
19956 case ContextProvider:
19957 popProvider(interruptedWork);
19958 break;
19959 default:
19960 break;
19961 }
19962}
19963
19964// Intentionally not named imports because Rollup would use dynamic dispatch for
19965// CommonJS interop named imports.
19966// Intentionally not named imports because Rollup would use dynamic dispatch for
19967// CommonJS interop named imports.
19968var scheduleCallback$1 = unstable_scheduleCallback;
19969var cancelCallback$1 = unstable_cancelCallback;
19970var shouldYield$2 = unstable_shouldYield;
19971var now$2 = unstable_now;
19972var getCurrentPriorityLevel$1 = unstable_getCurrentPriorityLevel;
19973var NormalPriority$1 = unstable_NormalPriority;
19974var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
19975var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
19976var ReactShouldWarnActingUpdates = ReactSharedInternals.ReactShouldWarnActingUpdates;
19977
19978
19979var didWarnAboutStateTransition = void 0;
19980var didWarnSetStateChildContext = void 0;
19981var warnAboutUpdateOnUnmounted = void 0;
19982var warnAboutInvalidUpdates = void 0;
19983
19984if (enableSchedulerTracing) {
19985 // Provide explicit error message when production+profiling bundle of e.g. react-dom
19986 // is used with production (non-profiling) bundle of scheduler/tracing
19987 (function () {
19988 if (!(__interactionsRef != null && __interactionsRef.current != null)) {
19989 {
19990 throw ReactError('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');
19991 }
19992 }
19993 })();
19994}
19995
19996{
19997 didWarnAboutStateTransition = false;
19998 didWarnSetStateChildContext = false;
19999 var didWarnStateUpdateForUnmountedComponent = {};
20000
20001 warnAboutUpdateOnUnmounted = function (fiber, isClass) {
20002 // We show the whole stack but dedupe on the top component's name because
20003 // the problematic code almost always lies inside that component.
20004 var componentName = getComponentName(fiber.type) || 'ReactComponent';
20005 if (didWarnStateUpdateForUnmountedComponent[componentName]) {
20006 return;
20007 }
20008 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));
20009 didWarnStateUpdateForUnmountedComponent[componentName] = true;
20010 };
20011
20012 warnAboutInvalidUpdates = function (instance) {
20013 switch (phase) {
20014 case 'getChildContext':
20015 if (didWarnSetStateChildContext) {
20016 return;
20017 }
20018 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
20019 didWarnSetStateChildContext = true;
20020 break;
20021 case 'render':
20022 if (didWarnAboutStateTransition) {
20023 return;
20024 }
20025 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.');
20026 didWarnAboutStateTransition = true;
20027 break;
20028 }
20029 };
20030}
20031
20032// Used to ensure computeUniqueAsyncExpiration is monotonically decreasing.
20033var lastUniqueAsyncExpiration = Sync - 1;
20034
20035// Represents the expiration time that incoming updates should use. (If this
20036// is NoWork, use the default strategy: async updates in async mode, sync
20037// updates in sync mode.)
20038var expirationContext = NoWork;
20039
20040var isWorking = false;
20041
20042// The next work in progress fiber that we're currently working on.
20043var nextUnitOfWork = null;
20044var nextRoot = null;
20045// The time at which we're currently rendering work.
20046var nextRenderExpirationTime = NoWork;
20047var nextLatestAbsoluteTimeoutMs = -1;
20048var nextRenderDidError = false;
20049
20050// The next fiber with an effect that we're currently committing.
20051var nextEffect = null;
20052
20053var isCommitting$1 = false;
20054var rootWithPendingPassiveEffects = null;
20055var passiveEffectCallbackHandle = null;
20056var passiveEffectCallback = null;
20057
20058var legacyErrorBoundariesThatAlreadyFailed = null;
20059
20060// Used for performance tracking.
20061var interruptedBy = null;
20062
20063var stashedWorkInProgressProperties = void 0;
20064var replayUnitOfWork = void 0;
20065var mayReplayFailedUnitOfWork = void 0;
20066var isReplayingFailedUnitOfWork = void 0;
20067var originalReplayError = void 0;
20068var rethrowOriginalError = void 0;
20069if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
20070 stashedWorkInProgressProperties = null;
20071 mayReplayFailedUnitOfWork = true;
20072 isReplayingFailedUnitOfWork = false;
20073 originalReplayError = null;
20074 replayUnitOfWork = function (failedUnitOfWork, thrownValue, isYieldy) {
20075 if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
20076 // Don't replay promises. Treat everything else like an error.
20077 // TODO: Need to figure out a different strategy if/when we add
20078 // support for catching other types.
20079 return;
20080 }
20081
20082 // Restore the original state of the work-in-progress
20083 if (stashedWorkInProgressProperties === null) {
20084 // This should never happen. Don't throw because this code is DEV-only.
20085 warningWithoutStack$1(false, 'Could not replay rendering after an error. This is likely a bug in React. ' + 'Please file an issue.');
20086 return;
20087 }
20088 assignFiberPropertiesInDEV(failedUnitOfWork, stashedWorkInProgressProperties);
20089
20090 switch (failedUnitOfWork.tag) {
20091 case HostRoot:
20092 popHostContainer(failedUnitOfWork);
20093 popTopLevelContextObject(failedUnitOfWork);
20094 break;
20095 case HostComponent:
20096 popHostContext(failedUnitOfWork);
20097 break;
20098 case ClassComponent:
20099 {
20100 var Component = failedUnitOfWork.type;
20101 if (isContextProvider(Component)) {
20102 popContext(failedUnitOfWork);
20103 }
20104 break;
20105 }
20106 case HostPortal:
20107 popHostContainer(failedUnitOfWork);
20108 break;
20109 case ContextProvider:
20110 popProvider(failedUnitOfWork);
20111 break;
20112 }
20113 // Replay the begin phase.
20114 isReplayingFailedUnitOfWork = true;
20115 originalReplayError = thrownValue;
20116 invokeGuardedCallback(null, workLoop, null, isYieldy);
20117 isReplayingFailedUnitOfWork = false;
20118 originalReplayError = null;
20119 if (hasCaughtError()) {
20120 var replayError = clearCaughtError();
20121 if (replayError != null && thrownValue != null) {
20122 try {
20123 // Reading the expando property is intentionally
20124 // inside `try` because it might be a getter or Proxy.
20125 if (replayError._suppressLogging) {
20126 // Also suppress logging for the original error.
20127 thrownValue._suppressLogging = true;
20128 }
20129 } catch (inner) {
20130 // Ignore.
20131 }
20132 }
20133 } else {
20134 // If the begin phase did not fail the second time, set this pointer
20135 // back to the original value.
20136 nextUnitOfWork = failedUnitOfWork;
20137 }
20138 };
20139 rethrowOriginalError = function () {
20140 throw originalReplayError;
20141 };
20142}
20143
20144function resetStack() {
20145 if (nextUnitOfWork !== null) {
20146 var interruptedWork = nextUnitOfWork.return;
20147 while (interruptedWork !== null) {
20148 unwindInterruptedWork(interruptedWork);
20149 interruptedWork = interruptedWork.return;
20150 }
20151 }
20152
20153 {
20154 ReactStrictModeWarnings.discardPendingWarnings();
20155 checkThatStackIsEmpty();
20156 }
20157
20158 nextRoot = null;
20159 nextRenderExpirationTime = NoWork;
20160 nextLatestAbsoluteTimeoutMs = -1;
20161 nextRenderDidError = false;
20162 nextUnitOfWork = null;
20163}
20164
20165function commitAllHostEffects() {
20166 while (nextEffect !== null) {
20167 {
20168 setCurrentFiber(nextEffect);
20169 }
20170 recordEffect();
20171
20172 var effectTag = nextEffect.effectTag;
20173
20174 if (effectTag & ContentReset) {
20175 commitResetTextContent(nextEffect);
20176 }
20177
20178 if (effectTag & Ref) {
20179 var current$$1 = nextEffect.alternate;
20180 if (current$$1 !== null) {
20181 commitDetachRef(current$$1);
20182 }
20183 }
20184
20185 // The following switch statement is only concerned about placement,
20186 // updates, and deletions. To avoid needing to add a case for every
20187 // possible bitmap value, we remove the secondary effects from the
20188 // effect tag and switch on that value.
20189 var primaryEffectTag = effectTag & (Placement | Update | Deletion);
20190 switch (primaryEffectTag) {
20191 case Placement:
20192 {
20193 commitPlacement(nextEffect);
20194 // Clear the "placement" from effect tag so that we know that this is inserted, before
20195 // any life-cycles like componentDidMount gets called.
20196 // TODO: findDOMNode doesn't rely on this any more but isMounted
20197 // does and isMounted is deprecated anyway so we should be able
20198 // to kill this.
20199 nextEffect.effectTag &= ~Placement;
20200 break;
20201 }
20202 case PlacementAndUpdate:
20203 {
20204 // Placement
20205 commitPlacement(nextEffect);
20206 // Clear the "placement" from effect tag so that we know that this is inserted, before
20207 // any life-cycles like componentDidMount gets called.
20208 nextEffect.effectTag &= ~Placement;
20209
20210 // Update
20211 var _current = nextEffect.alternate;
20212 commitWork(_current, nextEffect);
20213 break;
20214 }
20215 case Update:
20216 {
20217 var _current2 = nextEffect.alternate;
20218 commitWork(_current2, nextEffect);
20219 break;
20220 }
20221 case Deletion:
20222 {
20223 commitDeletion(nextEffect);
20224 break;
20225 }
20226 }
20227 nextEffect = nextEffect.nextEffect;
20228 }
20229
20230 {
20231 resetCurrentFiber();
20232 }
20233}
20234
20235function commitBeforeMutationLifecycles() {
20236 while (nextEffect !== null) {
20237 {
20238 setCurrentFiber(nextEffect);
20239 }
20240
20241 var effectTag = nextEffect.effectTag;
20242 if (effectTag & Snapshot) {
20243 recordEffect();
20244 var current$$1 = nextEffect.alternate;
20245 commitBeforeMutationLifeCycles(current$$1, nextEffect);
20246 }
20247
20248 nextEffect = nextEffect.nextEffect;
20249 }
20250
20251 {
20252 resetCurrentFiber();
20253 }
20254}
20255
20256function commitAllLifeCycles(finishedRoot, committedExpirationTime) {
20257 {
20258 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
20259 ReactStrictModeWarnings.flushLegacyContextWarning();
20260
20261 if (warnAboutDeprecatedLifecycles) {
20262 ReactStrictModeWarnings.flushPendingDeprecationWarnings();
20263 }
20264 }
20265 while (nextEffect !== null) {
20266 {
20267 setCurrentFiber(nextEffect);
20268 }
20269 var effectTag = nextEffect.effectTag;
20270
20271 if (effectTag & (Update | Callback)) {
20272 recordEffect();
20273 var current$$1 = nextEffect.alternate;
20274 commitLifeCycles(finishedRoot, current$$1, nextEffect, committedExpirationTime);
20275 }
20276
20277 if (effectTag & Ref) {
20278 recordEffect();
20279 commitAttachRef(nextEffect);
20280 }
20281
20282 if (effectTag & Passive) {
20283 rootWithPendingPassiveEffects = finishedRoot;
20284 }
20285
20286 nextEffect = nextEffect.nextEffect;
20287 }
20288 {
20289 resetCurrentFiber();
20290 }
20291}
20292
20293function commitPassiveEffects(root, firstEffect) {
20294 rootWithPendingPassiveEffects = null;
20295 passiveEffectCallbackHandle = null;
20296 passiveEffectCallback = null;
20297
20298 // Set this to true to prevent re-entrancy
20299 var previousIsRendering = isRendering;
20300 isRendering = true;
20301
20302 var effect = firstEffect;
20303 do {
20304 {
20305 setCurrentFiber(effect);
20306 }
20307
20308 if (effect.effectTag & Passive) {
20309 var didError = false;
20310 var error = void 0;
20311 {
20312 isInPassiveEffectDEV = true;
20313 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
20314 isInPassiveEffectDEV = false;
20315 if (hasCaughtError()) {
20316 didError = true;
20317 error = clearCaughtError();
20318 }
20319 }
20320 if (didError) {
20321 captureCommitPhaseError$1(effect, error);
20322 }
20323 }
20324 effect = effect.nextEffect;
20325 } while (effect !== null);
20326 {
20327 resetCurrentFiber();
20328 }
20329
20330 isRendering = previousIsRendering;
20331
20332 // Check if work was scheduled by one of the effects
20333 var rootExpirationTime = root.expirationTime;
20334 if (rootExpirationTime !== NoWork) {
20335 requestWork(root, rootExpirationTime);
20336 }
20337 // Flush any sync work that was scheduled by effects
20338 if (!isBatchingUpdates && !isRendering) {
20339 performSyncWork();
20340 }
20341
20342 {
20343 if (rootWithPendingPassiveEffects === root) {
20344 nestedPassiveEffectCountDEV++;
20345 } else {
20346 nestedPassiveEffectCountDEV = 0;
20347 }
20348 }
20349}
20350
20351function isAlreadyFailedLegacyErrorBoundary$1(instance) {
20352 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
20353}
20354
20355function markLegacyErrorBoundaryAsFailed$1(instance) {
20356 if (legacyErrorBoundariesThatAlreadyFailed === null) {
20357 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
20358 } else {
20359 legacyErrorBoundariesThatAlreadyFailed.add(instance);
20360 }
20361}
20362
20363function flushPassiveEffects$1() {
20364 var didFlushEffects = passiveEffectCallback !== null;
20365 if (passiveEffectCallbackHandle !== null) {
20366 cancelCallback$1(passiveEffectCallbackHandle);
20367 }
20368 if (passiveEffectCallback !== null) {
20369 // We call the scheduled callback instead of commitPassiveEffects directly
20370 // to ensure tracing works correctly.
20371 passiveEffectCallback();
20372 }
20373 return didFlushEffects;
20374}
20375
20376function commitRoot(root, finishedWork) {
20377 isWorking = true;
20378 isCommitting$1 = true;
20379 startCommitTimer();
20380
20381 (function () {
20382 if (!(root.current !== finishedWork)) {
20383 {
20384 throw ReactError('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.');
20385 }
20386 }
20387 })();
20388 var committedExpirationTime = root.pendingCommitExpirationTime;
20389 (function () {
20390 if (!(committedExpirationTime !== NoWork)) {
20391 {
20392 throw ReactError('Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.');
20393 }
20394 }
20395 })();
20396 root.pendingCommitExpirationTime = NoWork;
20397
20398 // Update the pending priority levels to account for the work that we are
20399 // about to commit. This needs to happen before calling the lifecycles, since
20400 // they may schedule additional updates.
20401 var updateExpirationTimeBeforeCommit = finishedWork.expirationTime;
20402 var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime;
20403 var earliestRemainingTimeBeforeCommit = childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit ? childExpirationTimeBeforeCommit : updateExpirationTimeBeforeCommit;
20404 markCommittedPriorityLevels(root, earliestRemainingTimeBeforeCommit);
20405
20406 var prevInteractions = null;
20407 if (enableSchedulerTracing) {
20408 // Restore any pending interactions at this point,
20409 // So that cascading work triggered during the render phase will be accounted for.
20410 prevInteractions = __interactionsRef.current;
20411 __interactionsRef.current = root.memoizedInteractions;
20412 }
20413
20414 // Reset this to null before calling lifecycles
20415 ReactCurrentOwner$2.current = null;
20416
20417 var firstEffect = void 0;
20418 if (finishedWork.effectTag > PerformedWork) {
20419 // A fiber's effect list consists only of its children, not itself. So if
20420 // the root has an effect, we need to add it to the end of the list. The
20421 // resulting list is the set that would belong to the root's parent, if
20422 // it had one; that is, all the effects in the tree including the root.
20423 if (finishedWork.lastEffect !== null) {
20424 finishedWork.lastEffect.nextEffect = finishedWork;
20425 firstEffect = finishedWork.firstEffect;
20426 } else {
20427 firstEffect = finishedWork;
20428 }
20429 } else {
20430 // There is no effect on the root.
20431 firstEffect = finishedWork.firstEffect;
20432 }
20433
20434 prepareForCommit(root.containerInfo);
20435
20436 // Invoke instances of getSnapshotBeforeUpdate before mutation.
20437 nextEffect = firstEffect;
20438 startCommitSnapshotEffectsTimer();
20439 while (nextEffect !== null) {
20440 var didError = false;
20441 var error = void 0;
20442 {
20443 invokeGuardedCallback(null, commitBeforeMutationLifecycles, null);
20444 if (hasCaughtError()) {
20445 didError = true;
20446 error = clearCaughtError();
20447 }
20448 }
20449 if (didError) {
20450 (function () {
20451 if (!(nextEffect !== null)) {
20452 {
20453 throw ReactError('Should have next effect. This error is likely caused by a bug in React. Please file an issue.');
20454 }
20455 }
20456 })();
20457 captureCommitPhaseError$1(nextEffect, error);
20458 // Clean-up
20459 if (nextEffect !== null) {
20460 nextEffect = nextEffect.nextEffect;
20461 }
20462 }
20463 }
20464 stopCommitSnapshotEffectsTimer();
20465
20466 if (enableProfilerTimer) {
20467 // Mark the current commit time to be shared by all Profilers in this batch.
20468 // This enables them to be grouped later.
20469 recordCommitTime();
20470 }
20471
20472 // Commit all the side-effects within a tree. We'll do this in two passes.
20473 // The first pass performs all the host insertions, updates, deletions and
20474 // ref unmounts.
20475 nextEffect = firstEffect;
20476 startCommitHostEffectsTimer();
20477 while (nextEffect !== null) {
20478 var _didError = false;
20479 var _error = void 0;
20480 {
20481 invokeGuardedCallback(null, commitAllHostEffects, null);
20482 if (hasCaughtError()) {
20483 _didError = true;
20484 _error = clearCaughtError();
20485 }
20486 }
20487 if (_didError) {
20488 (function () {
20489 if (!(nextEffect !== null)) {
20490 {
20491 throw ReactError('Should have next effect. This error is likely caused by a bug in React. Please file an issue.');
20492 }
20493 }
20494 })();
20495 captureCommitPhaseError$1(nextEffect, _error);
20496 // Clean-up
20497 if (nextEffect !== null) {
20498 nextEffect = nextEffect.nextEffect;
20499 }
20500 }
20501 }
20502 stopCommitHostEffectsTimer();
20503
20504 resetAfterCommit(root.containerInfo);
20505
20506 // The work-in-progress tree is now the current tree. This must come after
20507 // the first pass of the commit phase, so that the previous tree is still
20508 // current during componentWillUnmount, but before the second pass, so that
20509 // the finished work is current during componentDidMount/Update.
20510 root.current = finishedWork;
20511
20512 // In the second pass we'll perform all life-cycles and ref callbacks.
20513 // Life-cycles happen as a separate pass so that all placements, updates,
20514 // and deletions in the entire tree have already been invoked.
20515 // This pass also triggers any renderer-specific initial effects.
20516 nextEffect = firstEffect;
20517 startCommitLifeCyclesTimer();
20518 while (nextEffect !== null) {
20519 var _didError2 = false;
20520 var _error2 = void 0;
20521 {
20522 invokeGuardedCallback(null, commitAllLifeCycles, null, root, committedExpirationTime);
20523 if (hasCaughtError()) {
20524 _didError2 = true;
20525 _error2 = clearCaughtError();
20526 }
20527 }
20528 if (_didError2) {
20529 (function () {
20530 if (!(nextEffect !== null)) {
20531 {
20532 throw ReactError('Should have next effect. This error is likely caused by a bug in React. Please file an issue.');
20533 }
20534 }
20535 })();
20536 captureCommitPhaseError$1(nextEffect, _error2);
20537 if (nextEffect !== null) {
20538 nextEffect = nextEffect.nextEffect;
20539 }
20540 }
20541 }
20542
20543 if (firstEffect !== null && rootWithPendingPassiveEffects !== null) {
20544 // This commit included a passive effect. These do not need to fire until
20545 // after the next paint. Schedule an callback to fire them in an async
20546 // event. To ensure serial execution, the callback will be flushed early if
20547 // we enter rootWithPendingPassiveEffects commit phase before then.
20548 var callback = commitPassiveEffects.bind(null, root, firstEffect);
20549 if (enableSchedulerTracing) {
20550 // TODO: Avoid this extra callback by mutating the tracing ref directly,
20551 // like we do at the beginning of commitRoot. I've opted not to do that
20552 // here because that code is still in flux.
20553 callback = unstable_wrap(callback);
20554 }
20555 passiveEffectCallbackHandle = scheduleCallback$1(NormalPriority$1, callback);
20556 passiveEffectCallback = callback;
20557 }
20558
20559 isCommitting$1 = false;
20560 isWorking = false;
20561 stopCommitLifeCyclesTimer();
20562 stopCommitTimer();
20563 onCommitRoot(finishedWork.stateNode);
20564 if (true && ReactFiberInstrumentation_1.debugTool) {
20565 ReactFiberInstrumentation_1.debugTool.onCommitWork(finishedWork);
20566 }
20567
20568 var updateExpirationTimeAfterCommit = finishedWork.expirationTime;
20569 var childExpirationTimeAfterCommit = finishedWork.childExpirationTime;
20570 var earliestRemainingTimeAfterCommit = childExpirationTimeAfterCommit > updateExpirationTimeAfterCommit ? childExpirationTimeAfterCommit : updateExpirationTimeAfterCommit;
20571 if (earliestRemainingTimeAfterCommit === NoWork) {
20572 // If there's no remaining work, we can clear the set of already failed
20573 // error boundaries.
20574 legacyErrorBoundariesThatAlreadyFailed = null;
20575 }
20576 onCommit(root, earliestRemainingTimeAfterCommit);
20577
20578 if (enableSchedulerTracing) {
20579 __interactionsRef.current = prevInteractions;
20580
20581 var subscriber = void 0;
20582
20583 try {
20584 subscriber = __subscriberRef.current;
20585 if (subscriber !== null && root.memoizedInteractions.size > 0) {
20586 var threadID = computeThreadID(committedExpirationTime, root.interactionThreadID);
20587 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
20588 }
20589 } catch (error) {
20590 // It's not safe for commitRoot() to throw.
20591 // Store the error for now and we'll re-throw in finishRendering().
20592 if (!hasUnhandledError) {
20593 hasUnhandledError = true;
20594 unhandledError = error;
20595 }
20596 } finally {
20597 // Clear completed interactions from the pending Map.
20598 // Unless the render was suspended or cascading work was scheduled,
20599 // In which case– leave pending interactions until the subsequent render.
20600 var pendingInteractionMap = root.pendingInteractionMap;
20601 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
20602 // Only decrement the pending interaction count if we're done.
20603 // If there's still work at the current priority,
20604 // That indicates that we are waiting for suspense data.
20605 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
20606 pendingInteractionMap.delete(scheduledExpirationTime);
20607
20608 scheduledInteractions.forEach(function (interaction) {
20609 interaction.__count--;
20610
20611 if (subscriber !== null && interaction.__count === 0) {
20612 try {
20613 subscriber.onInteractionScheduledWorkCompleted(interaction);
20614 } catch (error) {
20615 // It's not safe for commitRoot() to throw.
20616 // Store the error for now and we'll re-throw in finishRendering().
20617 if (!hasUnhandledError) {
20618 hasUnhandledError = true;
20619 unhandledError = error;
20620 }
20621 }
20622 }
20623 });
20624 }
20625 });
20626 }
20627 }
20628}
20629
20630function resetChildExpirationTime(workInProgress, renderTime) {
20631 if (renderTime !== Never && workInProgress.childExpirationTime === Never) {
20632 // The children of this component are hidden. Don't bubble their
20633 // expiration times.
20634 return;
20635 }
20636
20637 var newChildExpirationTime = NoWork;
20638
20639 // Bubble up the earliest expiration time.
20640 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
20641 // We're in profiling mode.
20642 // Let's use this same traversal to update the render durations.
20643 var actualDuration = workInProgress.actualDuration;
20644 var treeBaseDuration = workInProgress.selfBaseDuration;
20645
20646 // When a fiber is cloned, its actualDuration is reset to 0.
20647 // This value will only be updated if work is done on the fiber (i.e. it doesn't bailout).
20648 // When work is done, it should bubble to the parent's actualDuration.
20649 // If the fiber has not been cloned though, (meaning no work was done),
20650 // Then this value will reflect the amount of time spent working on a previous render.
20651 // In that case it should not bubble.
20652 // We determine whether it was cloned by comparing the child pointer.
20653 var shouldBubbleActualDurations = workInProgress.alternate === null || workInProgress.child !== workInProgress.alternate.child;
20654
20655 var child = workInProgress.child;
20656 while (child !== null) {
20657 var childUpdateExpirationTime = child.expirationTime;
20658 var childChildExpirationTime = child.childExpirationTime;
20659 if (childUpdateExpirationTime > newChildExpirationTime) {
20660 newChildExpirationTime = childUpdateExpirationTime;
20661 }
20662 if (childChildExpirationTime > newChildExpirationTime) {
20663 newChildExpirationTime = childChildExpirationTime;
20664 }
20665 if (shouldBubbleActualDurations) {
20666 actualDuration += child.actualDuration;
20667 }
20668 treeBaseDuration += child.treeBaseDuration;
20669 child = child.sibling;
20670 }
20671 workInProgress.actualDuration = actualDuration;
20672 workInProgress.treeBaseDuration = treeBaseDuration;
20673 } else {
20674 var _child = workInProgress.child;
20675 while (_child !== null) {
20676 var _childUpdateExpirationTime = _child.expirationTime;
20677 var _childChildExpirationTime = _child.childExpirationTime;
20678 if (_childUpdateExpirationTime > newChildExpirationTime) {
20679 newChildExpirationTime = _childUpdateExpirationTime;
20680 }
20681 if (_childChildExpirationTime > newChildExpirationTime) {
20682 newChildExpirationTime = _childChildExpirationTime;
20683 }
20684 _child = _child.sibling;
20685 }
20686 }
20687
20688 workInProgress.childExpirationTime = newChildExpirationTime;
20689}
20690
20691function completeUnitOfWork(workInProgress) {
20692 // Attempt to complete the current unit of work, then move to the
20693 // next sibling. If there are no more siblings, return to the
20694 // parent fiber.
20695 while (true) {
20696 // The current, flushed, state of this fiber is the alternate.
20697 // Ideally nothing should rely on this, but relying on it here
20698 // means that we don't need an additional field on the work in
20699 // progress.
20700 var current$$1 = workInProgress.alternate;
20701 {
20702 setCurrentFiber(workInProgress);
20703 }
20704
20705 var returnFiber = workInProgress.return;
20706 var siblingFiber = workInProgress.sibling;
20707
20708 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
20709 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
20710 // Don't replay if it fails during completion phase.
20711 mayReplayFailedUnitOfWork = false;
20712 }
20713 // This fiber completed.
20714 // Remember we're completing this unit so we can find a boundary if it fails.
20715 nextUnitOfWork = workInProgress;
20716 if (enableProfilerTimer) {
20717 if (workInProgress.mode & ProfileMode) {
20718 startProfilerTimer(workInProgress);
20719 }
20720 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
20721 if (workInProgress.mode & ProfileMode) {
20722 // Update render duration assuming we didn't error.
20723 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
20724 }
20725 } else {
20726 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
20727 }
20728 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
20729 // We're out of completion phase so replaying is fine now.
20730 mayReplayFailedUnitOfWork = true;
20731 }
20732 stopWorkTimer(workInProgress);
20733 resetChildExpirationTime(workInProgress, nextRenderExpirationTime);
20734 {
20735 resetCurrentFiber();
20736 }
20737
20738 if (nextUnitOfWork !== null) {
20739 // Completing this fiber spawned new work. Work on that next.
20740 return nextUnitOfWork;
20741 }
20742
20743 if (returnFiber !== null &&
20744 // Do not append effects to parents if a sibling failed to complete
20745 (returnFiber.effectTag & Incomplete) === NoEffect) {
20746 // Append all the effects of the subtree and this fiber onto the effect
20747 // list of the parent. The completion order of the children affects the
20748 // side-effect order.
20749 if (returnFiber.firstEffect === null) {
20750 returnFiber.firstEffect = workInProgress.firstEffect;
20751 }
20752 if (workInProgress.lastEffect !== null) {
20753 if (returnFiber.lastEffect !== null) {
20754 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
20755 }
20756 returnFiber.lastEffect = workInProgress.lastEffect;
20757 }
20758
20759 // If this fiber had side-effects, we append it AFTER the children's
20760 // side-effects. We can perform certain side-effects earlier if
20761 // needed, by doing multiple passes over the effect list. We don't want
20762 // to schedule our own side-effect on our own list because if end up
20763 // reusing children we'll schedule this effect onto itself since we're
20764 // at the end.
20765 var effectTag = workInProgress.effectTag;
20766 // Skip both NoWork and PerformedWork tags when creating the effect list.
20767 // PerformedWork effect is read by React DevTools but shouldn't be committed.
20768 if (effectTag > PerformedWork) {
20769 if (returnFiber.lastEffect !== null) {
20770 returnFiber.lastEffect.nextEffect = workInProgress;
20771 } else {
20772 returnFiber.firstEffect = workInProgress;
20773 }
20774 returnFiber.lastEffect = workInProgress;
20775 }
20776 }
20777
20778 if (true && ReactFiberInstrumentation_1.debugTool) {
20779 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
20780 }
20781
20782 if (siblingFiber !== null) {
20783 // If there is more work to do in this returnFiber, do that next.
20784 return siblingFiber;
20785 } else if (returnFiber !== null) {
20786 // If there's no more work in this returnFiber. Complete the returnFiber.
20787 workInProgress = returnFiber;
20788 continue;
20789 } else {
20790 // We've reached the root.
20791 return null;
20792 }
20793 } else {
20794 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
20795 // Record the render duration for the fiber that errored.
20796 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
20797
20798 // Include the time spent working on failed children before continuing.
20799 var actualDuration = workInProgress.actualDuration;
20800 var child = workInProgress.child;
20801 while (child !== null) {
20802 actualDuration += child.actualDuration;
20803 child = child.sibling;
20804 }
20805 workInProgress.actualDuration = actualDuration;
20806 }
20807
20808 // This fiber did not complete because something threw. Pop values off
20809 // the stack without entering the complete phase. If this is a boundary,
20810 // capture values if possible.
20811 var next = unwindWork(workInProgress, nextRenderExpirationTime);
20812 // Because this fiber did not complete, don't reset its expiration time.
20813 if (workInProgress.effectTag & DidCapture) {
20814 // Restarting an error boundary
20815 stopFailedWorkTimer(workInProgress);
20816 } else {
20817 stopWorkTimer(workInProgress);
20818 }
20819
20820 {
20821 resetCurrentFiber();
20822 }
20823
20824 if (next !== null) {
20825 stopWorkTimer(workInProgress);
20826 if (true && ReactFiberInstrumentation_1.debugTool) {
20827 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
20828 }
20829
20830 // If completing this work spawned new work, do that next. We'll come
20831 // back here again.
20832 // Since we're restarting, remove anything that is not a host effect
20833 // from the effect tag.
20834 next.effectTag &= HostEffectMask;
20835 return next;
20836 }
20837
20838 if (returnFiber !== null) {
20839 // Mark the parent fiber as incomplete and clear its effect list.
20840 returnFiber.firstEffect = returnFiber.lastEffect = null;
20841 returnFiber.effectTag |= Incomplete;
20842 }
20843
20844 if (true && ReactFiberInstrumentation_1.debugTool) {
20845 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
20846 }
20847
20848 if (siblingFiber !== null) {
20849 // If there is more work to do in this returnFiber, do that next.
20850 return siblingFiber;
20851 } else if (returnFiber !== null) {
20852 // If there's no more work in this returnFiber. Complete the returnFiber.
20853 workInProgress = returnFiber;
20854 continue;
20855 } else {
20856 return null;
20857 }
20858 }
20859 }
20860
20861 // Without this explicit null return Flow complains of invalid return type
20862 // TODO Remove the above while(true) loop
20863 // eslint-disable-next-line no-unreachable
20864 return null;
20865}
20866
20867function performUnitOfWork(workInProgress) {
20868 // The current, flushed, state of this fiber is the alternate.
20869 // Ideally nothing should rely on this, but relying on it here
20870 // means that we don't need an additional field on the work in
20871 // progress.
20872 var current$$1 = workInProgress.alternate;
20873
20874 // See if beginning this work spawns more work.
20875 startWorkTimer(workInProgress);
20876 {
20877 setCurrentFiber(workInProgress);
20878 }
20879
20880 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
20881 stashedWorkInProgressProperties = assignFiberPropertiesInDEV(stashedWorkInProgressProperties, workInProgress);
20882 }
20883
20884 var next = void 0;
20885 if (enableProfilerTimer) {
20886 if (workInProgress.mode & ProfileMode) {
20887 startProfilerTimer(workInProgress);
20888 }
20889
20890 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
20891 workInProgress.memoizedProps = workInProgress.pendingProps;
20892
20893 if (workInProgress.mode & ProfileMode) {
20894 // Record the render duration assuming we didn't bailout (or error).
20895 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
20896 }
20897 } else {
20898 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
20899 workInProgress.memoizedProps = workInProgress.pendingProps;
20900 }
20901
20902 {
20903 resetCurrentFiber();
20904 if (isReplayingFailedUnitOfWork) {
20905 // Currently replaying a failed unit of work. This should be unreachable,
20906 // because the render phase is meant to be idempotent, and it should
20907 // have thrown again. Since it didn't, rethrow the original error, so
20908 // React's internal stack is not misaligned.
20909 rethrowOriginalError();
20910 }
20911 }
20912 if (true && ReactFiberInstrumentation_1.debugTool) {
20913 ReactFiberInstrumentation_1.debugTool.onBeginWork(workInProgress);
20914 }
20915
20916 if (next === null) {
20917 // If this doesn't spawn new work, complete the current work.
20918 next = completeUnitOfWork(workInProgress);
20919 }
20920
20921 ReactCurrentOwner$2.current = null;
20922
20923 return next;
20924}
20925
20926function workLoop(isYieldy) {
20927 if (!isYieldy) {
20928 // Flush work without yielding
20929 while (nextUnitOfWork !== null) {
20930 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
20931 }
20932 } else {
20933 // Flush asynchronous work until there's a higher priority event
20934 while (nextUnitOfWork !== null && !shouldYield$2()) {
20935 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
20936 }
20937 }
20938}
20939
20940function renderRoot(root, isYieldy) {
20941 (function () {
20942 if (!!isWorking) {
20943 {
20944 throw ReactError('renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.');
20945 }
20946 }
20947 })();
20948
20949 flushPassiveEffects$1();
20950
20951 isWorking = true;
20952 var previousDispatcher = ReactCurrentDispatcher.current;
20953 ReactCurrentDispatcher.current = ContextOnlyDispatcher;
20954
20955 var expirationTime = root.nextExpirationTimeToWorkOn;
20956
20957 // Check if we're starting from a fresh stack, or if we're resuming from
20958 // previously yielded work.
20959 if (expirationTime !== nextRenderExpirationTime || root !== nextRoot || nextUnitOfWork === null) {
20960 // Reset the stack and start working from the root.
20961 resetStack();
20962 nextRoot = root;
20963 nextRenderExpirationTime = expirationTime;
20964 nextUnitOfWork = createWorkInProgress(nextRoot.current, null, nextRenderExpirationTime);
20965 root.pendingCommitExpirationTime = NoWork;
20966
20967 if (enableSchedulerTracing) {
20968 // Determine which interactions this batch of work currently includes,
20969 // So that we can accurately attribute time spent working on it,
20970 var interactions = new Set();
20971 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
20972 if (scheduledExpirationTime >= expirationTime) {
20973 scheduledInteractions.forEach(function (interaction) {
20974 return interactions.add(interaction);
20975 });
20976 }
20977 });
20978
20979 // Store the current set of interactions on the FiberRoot for a few reasons:
20980 // We can re-use it in hot functions like renderRoot() without having to recalculate it.
20981 // We will also use it in commitWork() to pass to any Profiler onRender() hooks.
20982 // This also provides DevTools with a way to access it when the onCommitRoot() hook is called.
20983 root.memoizedInteractions = interactions;
20984
20985 if (interactions.size > 0) {
20986 var subscriber = __subscriberRef.current;
20987 if (subscriber !== null) {
20988 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
20989 try {
20990 subscriber.onWorkStarted(interactions, threadID);
20991 } catch (error) {
20992 // Work thrown by an interaction tracing subscriber should be rethrown,
20993 // But only once it's safe (to avoid leaving the scheduler in an invalid state).
20994 // Store the error for now and we'll re-throw in finishRendering().
20995 if (!hasUnhandledError) {
20996 hasUnhandledError = true;
20997 unhandledError = error;
20998 }
20999 }
21000 }
21001 }
21002 }
21003 }
21004
21005 var prevInteractions = null;
21006 if (enableSchedulerTracing) {
21007 // We're about to start new traced work.
21008 // Restore pending interactions so cascading work triggered during the render phase will be accounted for.
21009 prevInteractions = __interactionsRef.current;
21010 __interactionsRef.current = root.memoizedInteractions;
21011 }
21012
21013 var didFatal = false;
21014
21015 startWorkLoopTimer(nextUnitOfWork);
21016
21017 do {
21018 try {
21019 workLoop(isYieldy);
21020 } catch (thrownValue) {
21021 resetContextDependences();
21022 resetHooks();
21023
21024 // Reset in case completion throws.
21025 // This is only used in DEV and when replaying is on.
21026 var mayReplay = void 0;
21027 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
21028 mayReplay = mayReplayFailedUnitOfWork;
21029 mayReplayFailedUnitOfWork = true;
21030 }
21031
21032 if (nextUnitOfWork === null) {
21033 // This is a fatal error.
21034 didFatal = true;
21035 onUncaughtError$1(thrownValue);
21036 } else {
21037 if (enableProfilerTimer && nextUnitOfWork.mode & ProfileMode) {
21038 // Record the time spent rendering before an error was thrown.
21039 // This avoids inaccurate Profiler durations in the case of a suspended render.
21040 stopProfilerTimerIfRunningAndRecordDelta(nextUnitOfWork, true);
21041 }
21042
21043 {
21044 // Reset global debug state
21045 // We assume this is defined in DEV
21046 resetCurrentlyProcessingQueue();
21047 }
21048
21049 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
21050 if (mayReplay) {
21051 var failedUnitOfWork = nextUnitOfWork;
21052 replayUnitOfWork(failedUnitOfWork, thrownValue, isYieldy);
21053 }
21054 }
21055
21056 // TODO: we already know this isn't true in some cases.
21057 // At least this shows a nicer error message until we figure out the cause.
21058 // https://github.com/facebook/react/issues/12449#issuecomment-386727431
21059 (function () {
21060 if (!(nextUnitOfWork !== null)) {
21061 {
21062 throw ReactError('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.');
21063 }
21064 }
21065 })();
21066
21067 var sourceFiber = nextUnitOfWork;
21068 var returnFiber = sourceFiber.return;
21069 if (returnFiber === null) {
21070 // This is the root. The root could capture its own errors. However,
21071 // we don't know if it errors before or after we pushed the host
21072 // context. This information is needed to avoid a stack mismatch.
21073 // Because we're not sure, treat this as a fatal error. We could track
21074 // which phase it fails in, but doesn't seem worth it. At least
21075 // for now.
21076 didFatal = true;
21077 onUncaughtError$1(thrownValue);
21078 } else {
21079 throwException(root, returnFiber, sourceFiber, thrownValue, nextRenderExpirationTime);
21080 nextUnitOfWork = completeUnitOfWork(sourceFiber);
21081 continue;
21082 }
21083 }
21084 }
21085 break;
21086 } while (true);
21087
21088 if (enableSchedulerTracing) {
21089 // Traced work is done for now; restore the previous interactions.
21090 __interactionsRef.current = prevInteractions;
21091 }
21092
21093 // We're done performing work. Time to clean up.
21094 isWorking = false;
21095 ReactCurrentDispatcher.current = previousDispatcher;
21096 resetContextDependences();
21097 resetHooks();
21098
21099 // Yield back to main thread.
21100 if (didFatal) {
21101 var _didCompleteRoot = false;
21102 stopWorkLoopTimer(interruptedBy, _didCompleteRoot);
21103 interruptedBy = null;
21104 // There was a fatal error.
21105 {
21106 resetStackAfterFatalErrorInDev();
21107 }
21108 // `nextRoot` points to the in-progress root. A non-null value indicates
21109 // that we're in the middle of an async render. Set it to null to indicate
21110 // there's no more work to be done in the current batch.
21111 nextRoot = null;
21112 onFatal(root);
21113 return;
21114 }
21115
21116 if (nextUnitOfWork !== null) {
21117 // There's still remaining async work in this tree, but we ran out of time
21118 // in the current frame. Yield back to the renderer. Unless we're
21119 // interrupted by a higher priority update, we'll continue later from where
21120 // we left off.
21121 var _didCompleteRoot2 = false;
21122 stopWorkLoopTimer(interruptedBy, _didCompleteRoot2);
21123 interruptedBy = null;
21124 onYield(root);
21125 return;
21126 }
21127
21128 // We completed the whole tree.
21129 var didCompleteRoot = true;
21130 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
21131 var rootWorkInProgress = root.current.alternate;
21132 (function () {
21133 if (!(rootWorkInProgress !== null)) {
21134 {
21135 throw ReactError('Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue.');
21136 }
21137 }
21138 })();
21139
21140 // `nextRoot` points to the in-progress root. A non-null value indicates
21141 // that we're in the middle of an async render. Set it to null to indicate
21142 // there's no more work to be done in the current batch.
21143 nextRoot = null;
21144 interruptedBy = null;
21145
21146 if (nextRenderDidError) {
21147 // There was an error
21148 if (hasLowerPriorityWork(root, expirationTime)) {
21149 // There's lower priority work. If so, it may have the effect of fixing
21150 // the exception that was just thrown. Exit without committing. This is
21151 // similar to a suspend, but without a timeout because we're not waiting
21152 // for a promise to resolve. React will restart at the lower
21153 // priority level.
21154 markSuspendedPriorityLevel(root, expirationTime);
21155 var suspendedExpirationTime = expirationTime;
21156 var rootExpirationTime = root.expirationTime;
21157 onSuspend(root, rootWorkInProgress, suspendedExpirationTime, rootExpirationTime, -1 // Indicates no timeout
21158 );
21159 return;
21160 } else if (
21161 // There's no lower priority work, but we're rendering asynchronously.
21162 // Synchronously attempt to render the same level one more time. This is
21163 // similar to a suspend, but without a timeout because we're not waiting
21164 // for a promise to resolve.
21165 !root.didError && isYieldy) {
21166 root.didError = true;
21167 var _suspendedExpirationTime = root.nextExpirationTimeToWorkOn = expirationTime;
21168 var _rootExpirationTime = root.expirationTime = Sync;
21169 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime, _rootExpirationTime, -1 // Indicates no timeout
21170 );
21171 return;
21172 }
21173 }
21174
21175 if (isYieldy && nextLatestAbsoluteTimeoutMs !== -1) {
21176 // The tree was suspended.
21177 var _suspendedExpirationTime2 = expirationTime;
21178 markSuspendedPriorityLevel(root, _suspendedExpirationTime2);
21179
21180 // Find the earliest uncommitted expiration time in the tree, including
21181 // work that is suspended. The timeout threshold cannot be longer than
21182 // the overall expiration.
21183 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, expirationTime);
21184 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
21185 if (earliestExpirationTimeMs < nextLatestAbsoluteTimeoutMs) {
21186 nextLatestAbsoluteTimeoutMs = earliestExpirationTimeMs;
21187 }
21188
21189 // Subtract the current time from the absolute timeout to get the number
21190 // of milliseconds until the timeout. In other words, convert an absolute
21191 // timestamp to a relative time. This is the value that is passed
21192 // to `setTimeout`.
21193 var currentTimeMs = expirationTimeToMs(requestCurrentTime$1());
21194 var msUntilTimeout = nextLatestAbsoluteTimeoutMs - currentTimeMs;
21195 msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout;
21196
21197 // TODO: Account for the Just Noticeable Difference
21198
21199 var _rootExpirationTime2 = root.expirationTime;
21200 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime2, _rootExpirationTime2, msUntilTimeout);
21201 return;
21202 }
21203
21204 // Ready to commit.
21205 onComplete(root, rootWorkInProgress, expirationTime);
21206}
21207
21208function captureCommitPhaseError$1(sourceFiber, value) {
21209 var expirationTime = Sync;
21210 var fiber = sourceFiber.return;
21211 while (fiber !== null) {
21212 switch (fiber.tag) {
21213 case ClassComponent:
21214 var ctor = fiber.type;
21215 var instance = fiber.stateNode;
21216 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary$1(instance)) {
21217 var errorInfo = createCapturedValue(value, sourceFiber);
21218 var update = createClassErrorUpdate(fiber, errorInfo, expirationTime);
21219 enqueueUpdate(fiber, update);
21220 scheduleWork$1(fiber, expirationTime);
21221 return;
21222 }
21223 break;
21224 case HostRoot:
21225 {
21226 var _errorInfo = createCapturedValue(value, sourceFiber);
21227 var _update = createRootErrorUpdate(fiber, _errorInfo, expirationTime);
21228 enqueueUpdate(fiber, _update);
21229 scheduleWork$1(fiber, expirationTime);
21230 return;
21231 }
21232 }
21233 fiber = fiber.return;
21234 }
21235
21236 if (sourceFiber.tag === HostRoot) {
21237 // Error was thrown at the root. There is no parent, so the root
21238 // itself should capture it.
21239 var rootFiber = sourceFiber;
21240 var _errorInfo2 = createCapturedValue(value, rootFiber);
21241 var _update2 = createRootErrorUpdate(rootFiber, _errorInfo2, expirationTime);
21242 enqueueUpdate(rootFiber, _update2);
21243 scheduleWork$1(rootFiber, expirationTime);
21244 }
21245}
21246
21247function computeThreadID(expirationTime, interactionThreadID) {
21248 // Interaction threads are unique per root and expiration time.
21249 return expirationTime * 1000 + interactionThreadID;
21250}
21251
21252// Creates a unique async expiration time.
21253function computeUniqueAsyncExpiration$1() {
21254 var currentTime = requestCurrentTime$1();
21255 var result = computeAsyncExpiration(currentTime);
21256 if (result >= lastUniqueAsyncExpiration) {
21257 // Since we assume the current time monotonically increases, we only hit
21258 // this branch when computeUniqueAsyncExpiration is fired multiple times
21259 // within a 200ms window (or whatever the async bucket size is).
21260 result = lastUniqueAsyncExpiration - 1;
21261 }
21262 lastUniqueAsyncExpiration = result;
21263 return lastUniqueAsyncExpiration;
21264}
21265
21266function computeExpirationForFiber$1(currentTime, fiber) {
21267 var expirationTime = void 0;
21268 if (expirationContext !== NoWork) {
21269 // An explicit expiration context was set;
21270 expirationTime = expirationContext;
21271 } else if (isWorking) {
21272 if (isCommitting$1) {
21273 // Updates that occur during the commit phase should have sync priority
21274 // by default.
21275 expirationTime = Sync;
21276 } else {
21277 // Updates during the render phase should expire at the same time as
21278 // the work that is being rendered.
21279 expirationTime = nextRenderExpirationTime;
21280 }
21281 } else {
21282 // No explicit expiration context was set, and we're not currently
21283 // performing work. Calculate a new expiration time.
21284 if (fiber.mode & ConcurrentMode) {
21285 if (isBatchingInteractiveUpdates) {
21286 // This is an interactive update
21287 expirationTime = computeInteractiveExpiration(currentTime);
21288 } else {
21289 // This is an async update
21290 expirationTime = computeAsyncExpiration(currentTime);
21291 }
21292 // If we're in the middle of rendering a tree, do not update at the same
21293 // expiration time that is already rendering.
21294 if (nextRoot !== null && expirationTime === nextRenderExpirationTime) {
21295 expirationTime -= 1;
21296 }
21297 } else {
21298 // This is a sync update
21299 expirationTime = Sync;
21300 }
21301 }
21302 if (isBatchingInteractiveUpdates) {
21303 // This is an interactive update. Keep track of the lowest pending
21304 // interactive expiration time. This allows us to synchronously flush
21305 // all interactive updates when needed.
21306 if (lowestPriorityPendingInteractiveExpirationTime === NoWork || expirationTime < lowestPriorityPendingInteractiveExpirationTime) {
21307 lowestPriorityPendingInteractiveExpirationTime = expirationTime;
21308 }
21309 }
21310 return expirationTime;
21311}
21312
21313function renderDidSuspend$1(root, absoluteTimeoutMs, suspendedTime) {
21314 // Schedule the timeout.
21315 if (absoluteTimeoutMs >= 0 && nextLatestAbsoluteTimeoutMs < absoluteTimeoutMs) {
21316 nextLatestAbsoluteTimeoutMs = absoluteTimeoutMs;
21317 }
21318}
21319
21320function renderDidError$1() {
21321 nextRenderDidError = true;
21322}
21323
21324function inferStartTimeFromExpirationTime$1(root, expirationTime) {
21325 // We don't know exactly when the update was scheduled, but we can infer an
21326 // approximate start time from the expiration time. First, find the earliest
21327 // uncommitted expiration time in the tree, including work that is suspended.
21328 // Then subtract the offset used to compute an async update's expiration time.
21329 // This will cause high priority (interactive) work to expire earlier than
21330 // necessary, but we can account for this by adjusting for the Just
21331 // Noticeable Difference.
21332 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, expirationTime);
21333 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
21334 return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
21335}
21336
21337function pingSuspendedRoot$1(root, thenable, pingTime) {
21338 // A promise that previously suspended React from committing has resolved.
21339 // If React is still suspended, try again at the previous level (pingTime).
21340
21341 var pingCache = root.pingCache;
21342 if (pingCache !== null) {
21343 // The thenable resolved, so we no longer need to memoize, because it will
21344 // never be thrown again.
21345 pingCache.delete(thenable);
21346 }
21347
21348 if (nextRoot !== null && nextRenderExpirationTime === pingTime) {
21349 // Received a ping at the same priority level at which we're currently
21350 // rendering. Restart from the root.
21351 nextRoot = null;
21352 } else {
21353 // Confirm that the root is still suspended at this level. Otherwise exit.
21354 if (isPriorityLevelSuspended(root, pingTime)) {
21355 // Ping at the original level
21356 markPingedPriorityLevel(root, pingTime);
21357 var rootExpirationTime = root.expirationTime;
21358 if (rootExpirationTime !== NoWork) {
21359 requestWork(root, rootExpirationTime);
21360 }
21361 }
21362 }
21363}
21364
21365function retryTimedOutBoundary$1(boundaryFiber) {
21366 var currentTime = requestCurrentTime$1();
21367 var retryTime = computeExpirationForFiber$1(currentTime, boundaryFiber);
21368 var root = scheduleWorkToRoot(boundaryFiber, retryTime);
21369 if (root !== null) {
21370 markPendingPriorityLevel(root, retryTime);
21371 var rootExpirationTime = root.expirationTime;
21372 if (rootExpirationTime !== NoWork) {
21373 requestWork(root, rootExpirationTime);
21374 }
21375 }
21376}
21377
21378function resolveRetryThenable$1(boundaryFiber, thenable) {
21379 // The boundary fiber (a Suspense component) previously timed out and was
21380 // rendered in its fallback state. One of the promises that suspended it has
21381 // resolved, which means at least part of the tree was likely unblocked. Try
21382 var retryCache = void 0;
21383 if (enableSuspenseServerRenderer) {
21384 switch (boundaryFiber.tag) {
21385 case SuspenseComponent:
21386 retryCache = boundaryFiber.stateNode;
21387 break;
21388 case DehydratedSuspenseComponent:
21389 retryCache = boundaryFiber.memoizedState;
21390 break;
21391 default:
21392 (function () {
21393 {
21394 {
21395 throw ReactError('Pinged unknown suspense boundary type. This is probably a bug in React.');
21396 }
21397 }
21398 })();
21399 }
21400 } else {
21401 retryCache = boundaryFiber.stateNode;
21402 }
21403 if (retryCache !== null) {
21404 // The thenable resolved, so we no longer need to memoize, because it will
21405 // never be thrown again.
21406 retryCache.delete(thenable);
21407 }
21408
21409 retryTimedOutBoundary$1(boundaryFiber);
21410}
21411
21412function scheduleWorkToRoot(fiber, expirationTime) {
21413 recordScheduleUpdate();
21414
21415 {
21416 if (fiber.tag === ClassComponent) {
21417 var instance = fiber.stateNode;
21418 warnAboutInvalidUpdates(instance);
21419 }
21420 }
21421
21422 // Update the source fiber's expiration time
21423 if (fiber.expirationTime < expirationTime) {
21424 fiber.expirationTime = expirationTime;
21425 }
21426 var alternate = fiber.alternate;
21427 if (alternate !== null && alternate.expirationTime < expirationTime) {
21428 alternate.expirationTime = expirationTime;
21429 }
21430 // Walk the parent path to the root and update the child expiration time.
21431 var node = fiber.return;
21432 var root = null;
21433 if (node === null && fiber.tag === HostRoot) {
21434 root = fiber.stateNode;
21435 } else {
21436 while (node !== null) {
21437 alternate = node.alternate;
21438 if (node.childExpirationTime < expirationTime) {
21439 node.childExpirationTime = expirationTime;
21440 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
21441 alternate.childExpirationTime = expirationTime;
21442 }
21443 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
21444 alternate.childExpirationTime = expirationTime;
21445 }
21446 if (node.return === null && node.tag === HostRoot) {
21447 root = node.stateNode;
21448 break;
21449 }
21450 node = node.return;
21451 }
21452 }
21453
21454 if (enableSchedulerTracing) {
21455 if (root !== null) {
21456 var interactions = __interactionsRef.current;
21457 if (interactions.size > 0) {
21458 var pendingInteractionMap = root.pendingInteractionMap;
21459 var pendingInteractions = pendingInteractionMap.get(expirationTime);
21460 if (pendingInteractions != null) {
21461 interactions.forEach(function (interaction) {
21462 if (!pendingInteractions.has(interaction)) {
21463 // Update the pending async work count for previously unscheduled interaction.
21464 interaction.__count++;
21465 }
21466
21467 pendingInteractions.add(interaction);
21468 });
21469 } else {
21470 pendingInteractionMap.set(expirationTime, new Set(interactions));
21471
21472 // Update the pending async work count for the current interactions.
21473 interactions.forEach(function (interaction) {
21474 interaction.__count++;
21475 });
21476 }
21477
21478 var subscriber = __subscriberRef.current;
21479 if (subscriber !== null) {
21480 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
21481 subscriber.onWorkScheduled(interactions, threadID);
21482 }
21483 }
21484 }
21485 }
21486 return root;
21487}
21488
21489// in a test-like environment, we want to warn if dispatchAction() is
21490// called outside of a TestUtils.act(...)/batchedUpdates/render call.
21491// so we have a a step counter for when we descend/ascend from
21492// act() calls, and test on it for when to warn
21493// It's a tuple with a single value. Look for shared/createAct to
21494// see how we change the value inside act() calls
21495
21496function warnIfNotCurrentlyActingUpdatesInDev$1(fiber) {
21497 {
21498 if (isBatchingUpdates === false && isRendering === false && ReactShouldWarnActingUpdates.current === false) {
21499 warningWithoutStack$1(false, 'An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see in the browser." + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));
21500 }
21501 }
21502}
21503
21504function scheduleWork$1(fiber, expirationTime) {
21505 var root = scheduleWorkToRoot(fiber, expirationTime);
21506 if (root === null) {
21507 {
21508 switch (fiber.tag) {
21509 case ClassComponent:
21510 warnAboutUpdateOnUnmounted(fiber, true);
21511 break;
21512 case FunctionComponent:
21513 case ForwardRef:
21514 case MemoComponent:
21515 case SimpleMemoComponent:
21516 warnAboutUpdateOnUnmounted(fiber, false);
21517 break;
21518 }
21519 }
21520 return;
21521 }
21522
21523 if (!isWorking && nextRenderExpirationTime !== NoWork && expirationTime > nextRenderExpirationTime) {
21524 // This is an interruption. (Used for performance tracking.)
21525 interruptedBy = fiber;
21526 resetStack();
21527 }
21528 markPendingPriorityLevel(root, expirationTime);
21529 if (
21530 // If we're in the render phase, we don't need to schedule this root
21531 // for an update, because we'll do it before we exit...
21532 !isWorking || isCommitting$1 ||
21533 // ...unless this is a different root than the one we're rendering.
21534 nextRoot !== root) {
21535 var rootExpirationTime = root.expirationTime;
21536 requestWork(root, rootExpirationTime);
21537 }
21538 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
21539 // Reset this back to zero so subsequent updates don't throw.
21540 nestedUpdateCount = 0;
21541 (function () {
21542 {
21543 {
21544 throw ReactError('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.');
21545 }
21546 }
21547 })();
21548 }
21549 {
21550 if (isInPassiveEffectDEV && nestedPassiveEffectCountDEV > NESTED_PASSIVE_UPDATE_LIMIT) {
21551 nestedPassiveEffectCountDEV = 0;
21552 warning$1(false, 'Maximum update depth exceeded. This can happen when a ' + 'component calls setState inside useEffect, but ' + "useEffect either doesn't have a dependency array, or " + 'one of the dependencies changes on every render.');
21553 }
21554 }
21555}
21556
21557function syncUpdates$1(fn, a, b, c, d) {
21558 var previousExpirationContext = expirationContext;
21559 expirationContext = Sync;
21560 try {
21561 return fn(a, b, c, d);
21562 } finally {
21563 expirationContext = previousExpirationContext;
21564 }
21565}
21566
21567// TODO: Everything below this is written as if it has been lifted to the
21568// renderers. I'll do this in a follow-up.
21569
21570// Linked-list of roots
21571var firstScheduledRoot = null;
21572var lastScheduledRoot = null;
21573
21574var callbackExpirationTime = NoWork;
21575var callbackID = void 0;
21576var isRendering = false;
21577var nextFlushedRoot = null;
21578var nextFlushedExpirationTime = NoWork;
21579var lowestPriorityPendingInteractiveExpirationTime = NoWork;
21580var hasUnhandledError = false;
21581var unhandledError = null;
21582
21583var isBatchingUpdates = false;
21584var isUnbatchingUpdates = false;
21585var isBatchingInteractiveUpdates = false;
21586
21587var completedBatches = null;
21588
21589var originalStartTimeMs = now$2();
21590var currentRendererTime = msToExpirationTime(originalStartTimeMs);
21591var currentSchedulerTime = currentRendererTime;
21592
21593// Use these to prevent an infinite loop of nested updates
21594var NESTED_UPDATE_LIMIT = 50;
21595var nestedUpdateCount = 0;
21596var lastCommittedRootDuringThisBatch = null;
21597
21598// Similar, but for useEffect infinite loops. These are DEV-only.
21599var NESTED_PASSIVE_UPDATE_LIMIT = 50;
21600var nestedPassiveEffectCountDEV = void 0;
21601var isInPassiveEffectDEV = void 0;
21602{
21603 nestedPassiveEffectCountDEV = 0;
21604 isInPassiveEffectDEV = false;
21605}
21606
21607function recomputeCurrentRendererTime() {
21608 var currentTimeMs = now$2() - originalStartTimeMs;
21609 currentRendererTime = msToExpirationTime(currentTimeMs);
21610}
21611
21612function scheduleCallbackWithExpirationTime(root, expirationTime) {
21613 if (callbackExpirationTime !== NoWork) {
21614 // A callback is already scheduled. Check its expiration time (timeout).
21615 if (expirationTime < callbackExpirationTime) {
21616 // Existing callback has sufficient timeout. Exit.
21617 return;
21618 } else {
21619 if (callbackID !== null) {
21620 // Existing callback has insufficient timeout. Cancel and schedule a
21621 // new one.
21622 cancelCallback$1(callbackID);
21623 }
21624 }
21625 // The request callback timer is already running. Don't start a new one.
21626 } else {
21627 startRequestCallbackTimer();
21628 }
21629
21630 callbackExpirationTime = expirationTime;
21631 var currentMs = now$2() - originalStartTimeMs;
21632 var expirationTimeMs = expirationTimeToMs(expirationTime);
21633 var timeout = expirationTimeMs - currentMs;
21634 var priorityLevel = getCurrentPriorityLevel$1();
21635 callbackID = scheduleCallback$1(priorityLevel, performAsyncWork, { timeout: timeout });
21636}
21637
21638// For every call to renderRoot, one of onFatal, onComplete, onSuspend, and
21639// onYield is called upon exiting. We use these in lieu of returning a tuple.
21640// I've also chosen not to inline them into renderRoot because these will
21641// eventually be lifted into the renderer.
21642function onFatal(root) {
21643 root.finishedWork = null;
21644}
21645
21646function onComplete(root, finishedWork, expirationTime) {
21647 root.pendingCommitExpirationTime = expirationTime;
21648 root.finishedWork = finishedWork;
21649}
21650
21651function onSuspend(root, finishedWork, suspendedExpirationTime, rootExpirationTime, msUntilTimeout) {
21652 root.expirationTime = rootExpirationTime;
21653 if (msUntilTimeout === 0 && (disableYielding || !shouldYield$2())) {
21654 // Don't wait an additional tick. Commit the tree immediately.
21655 root.pendingCommitExpirationTime = suspendedExpirationTime;
21656 root.finishedWork = finishedWork;
21657 } else if (msUntilTimeout > 0) {
21658 // Wait `msUntilTimeout` milliseconds before committing.
21659 root.timeoutHandle = scheduleTimeout(onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), msUntilTimeout);
21660 }
21661}
21662
21663function onYield(root) {
21664 root.finishedWork = null;
21665}
21666
21667function onTimeout(root, finishedWork, suspendedExpirationTime) {
21668 // The root timed out. Commit it.
21669 root.pendingCommitExpirationTime = suspendedExpirationTime;
21670 root.finishedWork = finishedWork;
21671 // Read the current time before entering the commit phase. We can be
21672 // certain this won't cause tearing related to batching of event updates
21673 // because we're at the top of a timer event.
21674 recomputeCurrentRendererTime();
21675 currentSchedulerTime = currentRendererTime;
21676 flushRoot$1(root, suspendedExpirationTime);
21677}
21678
21679function onCommit(root, expirationTime) {
21680 root.expirationTime = expirationTime;
21681 root.finishedWork = null;
21682}
21683
21684function requestCurrentTime$1() {
21685 // requestCurrentTime is called by the scheduler to compute an expiration
21686 // time.
21687 //
21688 // Expiration times are computed by adding to the current time (the start
21689 // time). However, if two updates are scheduled within the same event, we
21690 // should treat their start times as simultaneous, even if the actual clock
21691 // time has advanced between the first and second call.
21692
21693 // In other words, because expiration times determine how updates are batched,
21694 // we want all updates of like priority that occur within the same event to
21695 // receive the same expiration time. Otherwise we get tearing.
21696 //
21697 // We keep track of two separate times: the current "renderer" time and the
21698 // current "scheduler" time. The renderer time can be updated whenever; it
21699 // only exists to minimize the calls performance.now.
21700 //
21701 // But the scheduler time can only be updated if there's no pending work, or
21702 // if we know for certain that we're not in the middle of an event.
21703
21704 if (isRendering) {
21705 // We're already rendering. Return the most recently read time.
21706 return currentSchedulerTime;
21707 }
21708 // Check if there's pending work.
21709 findHighestPriorityRoot();
21710 if (nextFlushedExpirationTime === NoWork || nextFlushedExpirationTime === Never) {
21711 // If there's no pending work, or if the pending work is offscreen, we can
21712 // read the current time without risk of tearing.
21713 recomputeCurrentRendererTime();
21714 currentSchedulerTime = currentRendererTime;
21715 return currentSchedulerTime;
21716 }
21717 // There's already pending work. We might be in the middle of a browser
21718 // event. If we were to read the current time, it could cause multiple updates
21719 // within the same event to receive different expiration times, leading to
21720 // tearing. Return the last read time. During the next idle callback, the
21721 // time will be updated.
21722 return currentSchedulerTime;
21723}
21724
21725// requestWork is called by the scheduler whenever a root receives an update.
21726// It's up to the renderer to call renderRoot at some point in the future.
21727function requestWork(root, expirationTime) {
21728 addRootToSchedule(root, expirationTime);
21729 if (isRendering) {
21730 // Prevent reentrancy. Remaining work will be scheduled at the end of
21731 // the currently rendering batch.
21732 return;
21733 }
21734
21735 if (isBatchingUpdates) {
21736 // Flush work at the end of the batch.
21737 if (isUnbatchingUpdates) {
21738 // ...unless we're inside unbatchedUpdates, in which case we should
21739 // flush it now.
21740 nextFlushedRoot = root;
21741 nextFlushedExpirationTime = Sync;
21742 performWorkOnRoot(root, Sync, false);
21743 }
21744 return;
21745 }
21746
21747 // TODO: Get rid of Sync and use current time?
21748 if (expirationTime === Sync) {
21749 performSyncWork();
21750 } else {
21751 scheduleCallbackWithExpirationTime(root, expirationTime);
21752 }
21753}
21754
21755function addRootToSchedule(root, expirationTime) {
21756 // Add the root to the schedule.
21757 // Check if this root is already part of the schedule.
21758 if (root.nextScheduledRoot === null) {
21759 // This root is not already scheduled. Add it.
21760 root.expirationTime = expirationTime;
21761 if (lastScheduledRoot === null) {
21762 firstScheduledRoot = lastScheduledRoot = root;
21763 root.nextScheduledRoot = root;
21764 } else {
21765 lastScheduledRoot.nextScheduledRoot = root;
21766 lastScheduledRoot = root;
21767 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
21768 }
21769 } else {
21770 // This root is already scheduled, but its priority may have increased.
21771 var remainingExpirationTime = root.expirationTime;
21772 if (expirationTime > remainingExpirationTime) {
21773 // Update the priority.
21774 root.expirationTime = expirationTime;
21775 }
21776 }
21777}
21778
21779function findHighestPriorityRoot() {
21780 var highestPriorityWork = NoWork;
21781 var highestPriorityRoot = null;
21782 if (lastScheduledRoot !== null) {
21783 var previousScheduledRoot = lastScheduledRoot;
21784 var root = firstScheduledRoot;
21785 while (root !== null) {
21786 var remainingExpirationTime = root.expirationTime;
21787 if (remainingExpirationTime === NoWork) {
21788 // This root no longer has work. Remove it from the scheduler.
21789
21790 // TODO: This check is redudant, but Flow is confused by the branch
21791 // below where we set lastScheduledRoot to null, even though we break
21792 // from the loop right after.
21793 (function () {
21794 if (!(previousScheduledRoot !== null && lastScheduledRoot !== null)) {
21795 {
21796 throw ReactError('Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue.');
21797 }
21798 }
21799 })();
21800 if (root === root.nextScheduledRoot) {
21801 // This is the only root in the list.
21802 root.nextScheduledRoot = null;
21803 firstScheduledRoot = lastScheduledRoot = null;
21804 break;
21805 } else if (root === firstScheduledRoot) {
21806 // This is the first root in the list.
21807 var next = root.nextScheduledRoot;
21808 firstScheduledRoot = next;
21809 lastScheduledRoot.nextScheduledRoot = next;
21810 root.nextScheduledRoot = null;
21811 } else if (root === lastScheduledRoot) {
21812 // This is the last root in the list.
21813 lastScheduledRoot = previousScheduledRoot;
21814 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
21815 root.nextScheduledRoot = null;
21816 break;
21817 } else {
21818 previousScheduledRoot.nextScheduledRoot = root.nextScheduledRoot;
21819 root.nextScheduledRoot = null;
21820 }
21821 root = previousScheduledRoot.nextScheduledRoot;
21822 } else {
21823 if (remainingExpirationTime > highestPriorityWork) {
21824 // Update the priority, if it's higher
21825 highestPriorityWork = remainingExpirationTime;
21826 highestPriorityRoot = root;
21827 }
21828 if (root === lastScheduledRoot) {
21829 break;
21830 }
21831 if (highestPriorityWork === Sync) {
21832 // Sync is highest priority by definition so
21833 // we can stop searching.
21834 break;
21835 }
21836 previousScheduledRoot = root;
21837 root = root.nextScheduledRoot;
21838 }
21839 }
21840 }
21841
21842 nextFlushedRoot = highestPriorityRoot;
21843 nextFlushedExpirationTime = highestPriorityWork;
21844}
21845
21846function performAsyncWork(didTimeout) {
21847 if (didTimeout) {
21848 // The callback timed out. That means at least one update has expired.
21849 // Iterate through the root schedule. If they contain expired work, set
21850 // the next render expiration time to the current time. This has the effect
21851 // of flushing all expired work in a single batch, instead of flushing each
21852 // level one at a time.
21853 if (firstScheduledRoot !== null) {
21854 recomputeCurrentRendererTime();
21855 var root = firstScheduledRoot;
21856 do {
21857 didExpireAtExpirationTime(root, currentRendererTime);
21858 // The root schedule is circular, so this is never null.
21859 root = root.nextScheduledRoot;
21860 } while (root !== firstScheduledRoot);
21861 }
21862 }
21863
21864 // Keep working on roots until there's no more work, or until there's a higher
21865 // priority event.
21866 findHighestPriorityRoot();
21867
21868 if (disableYielding) {
21869 // Just do it all
21870 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork) {
21871 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false);
21872 findHighestPriorityRoot();
21873 }
21874 } else {
21875 recomputeCurrentRendererTime();
21876 currentSchedulerTime = currentRendererTime;
21877
21878 if (enableUserTimingAPI) {
21879 var didExpire = nextFlushedExpirationTime > currentRendererTime;
21880 var timeout = expirationTimeToMs(nextFlushedExpirationTime);
21881 stopRequestCallbackTimer(didExpire, timeout);
21882 }
21883
21884 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && !(shouldYield$2() && currentRendererTime > nextFlushedExpirationTime)) {
21885 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, currentRendererTime > nextFlushedExpirationTime);
21886 findHighestPriorityRoot();
21887 recomputeCurrentRendererTime();
21888 currentSchedulerTime = currentRendererTime;
21889 }
21890 }
21891
21892 // We're done flushing work. Either we ran out of time in this callback,
21893 // or there's no more work left with sufficient priority.
21894
21895 // If we're inside a callback, set this to false since we just completed it.
21896 callbackExpirationTime = NoWork;
21897 callbackID = null;
21898
21899 // If there's work left over, schedule a new callback.
21900 if (nextFlushedExpirationTime !== NoWork) {
21901 scheduleCallbackWithExpirationTime(nextFlushedRoot, nextFlushedExpirationTime);
21902 }
21903
21904 // Clean-up.
21905 finishRendering();
21906}
21907
21908function performSyncWork() {
21909 performWork(Sync);
21910}
21911
21912function performWork(minExpirationTime) {
21913 // Keep working on roots until there's no more work, or until there's a higher
21914 // priority event.
21915 findHighestPriorityRoot();
21916
21917 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime) {
21918 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false);
21919 findHighestPriorityRoot();
21920 }
21921
21922 // We're done flushing work. Either we ran out of time in this callback,
21923 // or there's no more work left with sufficient priority.
21924
21925 // If there's work left over, schedule a new callback.
21926 if (nextFlushedExpirationTime !== NoWork) {
21927 scheduleCallbackWithExpirationTime(nextFlushedRoot, nextFlushedExpirationTime);
21928 }
21929
21930 // Clean-up.
21931 finishRendering();
21932}
21933
21934function flushRoot$1(root, expirationTime) {
21935 (function () {
21936 if (!!isRendering) {
21937 {
21938 throw ReactError('work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.');
21939 }
21940 }
21941 })();
21942 // Perform work on root as if the given expiration time is the current time.
21943 // This has the effect of synchronously flushing all work up to and
21944 // including the given time.
21945 nextFlushedRoot = root;
21946 nextFlushedExpirationTime = expirationTime;
21947 performWorkOnRoot(root, expirationTime, false);
21948 // Flush any sync work that was scheduled by lifecycles
21949 performSyncWork();
21950}
21951
21952function finishRendering() {
21953 nestedUpdateCount = 0;
21954 lastCommittedRootDuringThisBatch = null;
21955
21956 {
21957 if (rootWithPendingPassiveEffects === null) {
21958 nestedPassiveEffectCountDEV = 0;
21959 }
21960 }
21961
21962 if (completedBatches !== null) {
21963 var batches = completedBatches;
21964 completedBatches = null;
21965 for (var i = 0; i < batches.length; i++) {
21966 var batch = batches[i];
21967 try {
21968 batch._onComplete();
21969 } catch (error) {
21970 if (!hasUnhandledError) {
21971 hasUnhandledError = true;
21972 unhandledError = error;
21973 }
21974 }
21975 }
21976 }
21977
21978 if (hasUnhandledError) {
21979 var error = unhandledError;
21980 unhandledError = null;
21981 hasUnhandledError = false;
21982 throw error;
21983 }
21984}
21985
21986function performWorkOnRoot(root, expirationTime, isYieldy) {
21987 (function () {
21988 if (!!isRendering) {
21989 {
21990 throw ReactError('performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.');
21991 }
21992 }
21993 })();
21994
21995 isRendering = true;
21996
21997 // Check if this is async work or sync/expired work.
21998 if (!isYieldy) {
21999 // Flush work without yielding.
22000 // TODO: Non-yieldy work does not necessarily imply expired work. A renderer
22001 // may want to perform some work without yielding, but also without
22002 // requiring the root to complete (by triggering placeholders).
22003
22004 var finishedWork = root.finishedWork;
22005 if (finishedWork !== null) {
22006 // This root is already complete. We can commit it.
22007 completeRoot(root, finishedWork, expirationTime);
22008 } else {
22009 root.finishedWork = null;
22010 // If this root previously suspended, clear its existing timeout, since
22011 // we're about to try rendering again.
22012 var timeoutHandle = root.timeoutHandle;
22013 if (timeoutHandle !== noTimeout) {
22014 root.timeoutHandle = noTimeout;
22015 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
22016 cancelTimeout(timeoutHandle);
22017 }
22018 renderRoot(root, isYieldy);
22019 finishedWork = root.finishedWork;
22020 if (finishedWork !== null) {
22021 // We've completed the root. Commit it.
22022 completeRoot(root, finishedWork, expirationTime);
22023 }
22024 }
22025 } else {
22026 // Flush async work.
22027 var _finishedWork = root.finishedWork;
22028 if (_finishedWork !== null) {
22029 // This root is already complete. We can commit it.
22030 completeRoot(root, _finishedWork, expirationTime);
22031 } else {
22032 root.finishedWork = null;
22033 // If this root previously suspended, clear its existing timeout, since
22034 // we're about to try rendering again.
22035 var _timeoutHandle = root.timeoutHandle;
22036 if (_timeoutHandle !== noTimeout) {
22037 root.timeoutHandle = noTimeout;
22038 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
22039 cancelTimeout(_timeoutHandle);
22040 }
22041 renderRoot(root, isYieldy);
22042 _finishedWork = root.finishedWork;
22043 if (_finishedWork !== null) {
22044 // We've completed the root. Check the if we should yield one more time
22045 // before committing.
22046 if (!shouldYield$2()) {
22047 // Still time left. Commit the root.
22048 completeRoot(root, _finishedWork, expirationTime);
22049 } else {
22050 // There's no time left. Mark this root as complete. We'll come
22051 // back and commit it later.
22052 root.finishedWork = _finishedWork;
22053 }
22054 }
22055 }
22056 }
22057
22058 isRendering = false;
22059}
22060
22061function completeRoot(root, finishedWork, expirationTime) {
22062 // Check if there's a batch that matches this expiration time.
22063 var firstBatch = root.firstBatch;
22064 if (firstBatch !== null && firstBatch._expirationTime >= expirationTime) {
22065 if (completedBatches === null) {
22066 completedBatches = [firstBatch];
22067 } else {
22068 completedBatches.push(firstBatch);
22069 }
22070 if (firstBatch._defer) {
22071 // This root is blocked from committing by a batch. Unschedule it until
22072 // we receive another update.
22073 root.finishedWork = finishedWork;
22074 root.expirationTime = NoWork;
22075 return;
22076 }
22077 }
22078
22079 // Commit the root.
22080 root.finishedWork = null;
22081
22082 // Check if this is a nested update (a sync update scheduled during the
22083 // commit phase).
22084 if (root === lastCommittedRootDuringThisBatch) {
22085 // If the next root is the same as the previous root, this is a nested
22086 // update. To prevent an infinite loop, increment the nested update count.
22087 nestedUpdateCount++;
22088 } else {
22089 // Reset whenever we switch roots.
22090 lastCommittedRootDuringThisBatch = root;
22091 nestedUpdateCount = 0;
22092 }
22093 commitRoot(root, finishedWork);
22094}
22095
22096function onUncaughtError$1(error) {
22097 (function () {
22098 if (!(nextFlushedRoot !== null)) {
22099 {
22100 throw ReactError('Should be working on a root. This error is likely caused by a bug in React. Please file an issue.');
22101 }
22102 }
22103 })();
22104 // Unschedule this root so we don't work on it again until there's
22105 // another update.
22106 nextFlushedRoot.expirationTime = NoWork;
22107 if (!hasUnhandledError) {
22108 hasUnhandledError = true;
22109 unhandledError = error;
22110 }
22111}
22112
22113// TODO: Batching should be implemented at the renderer level, not inside
22114// the reconciler.
22115function batchedUpdates$2(fn, a) {
22116 var previousIsBatchingUpdates = isBatchingUpdates;
22117 isBatchingUpdates = true;
22118 try {
22119 return fn(a);
22120 } finally {
22121 isBatchingUpdates = previousIsBatchingUpdates;
22122 if (!isBatchingUpdates && !isRendering) {
22123 performSyncWork();
22124 }
22125 }
22126}
22127
22128// TODO: Batching should be implemented at the renderer level, not inside
22129// the reconciler.
22130function unbatchedUpdates$1(fn, a) {
22131 if (isBatchingUpdates && !isUnbatchingUpdates) {
22132 isUnbatchingUpdates = true;
22133 try {
22134 return fn(a);
22135 } finally {
22136 isUnbatchingUpdates = false;
22137 }
22138 }
22139 return fn(a);
22140}
22141
22142// TODO: Batching should be implemented at the renderer level, not within
22143// the reconciler.
22144function flushSync$1(fn, a) {
22145 (function () {
22146 if (!!isRendering) {
22147 {
22148 throw ReactError('flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.');
22149 }
22150 }
22151 })();
22152 var previousIsBatchingUpdates = isBatchingUpdates;
22153 isBatchingUpdates = true;
22154 try {
22155 return syncUpdates$1(fn, a);
22156 } finally {
22157 isBatchingUpdates = previousIsBatchingUpdates;
22158 performSyncWork();
22159 }
22160}
22161
22162function interactiveUpdates$2(fn, a, b, c) {
22163 if (isBatchingInteractiveUpdates) {
22164 return fn(a, b, c);
22165 }
22166 // If there are any pending interactive updates, synchronously flush them.
22167 // This needs to happen before we read any handlers, because the effect of
22168 // the previous event may influence which handlers are called during
22169 // this event.
22170 if (!isBatchingUpdates && !isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) {
22171 // Synchronously flush pending interactive updates.
22172 performWork(lowestPriorityPendingInteractiveExpirationTime);
22173 lowestPriorityPendingInteractiveExpirationTime = NoWork;
22174 }
22175 var previousIsBatchingInteractiveUpdates = isBatchingInteractiveUpdates;
22176 var previousIsBatchingUpdates = isBatchingUpdates;
22177 isBatchingInteractiveUpdates = true;
22178 isBatchingUpdates = true;
22179 try {
22180 return fn(a, b, c);
22181 } finally {
22182 isBatchingInteractiveUpdates = previousIsBatchingInteractiveUpdates;
22183 isBatchingUpdates = previousIsBatchingUpdates;
22184 if (!isBatchingUpdates && !isRendering) {
22185 performSyncWork();
22186 }
22187 }
22188}
22189
22190function flushInteractiveUpdates$2() {
22191 if (!isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) {
22192 // Synchronously flush pending interactive updates.
22193 performWork(lowestPriorityPendingInteractiveExpirationTime);
22194 lowestPriorityPendingInteractiveExpirationTime = NoWork;
22195 }
22196}
22197
22198function flushControlled$1(fn) {
22199 var previousIsBatchingUpdates = isBatchingUpdates;
22200 isBatchingUpdates = true;
22201 try {
22202 syncUpdates$1(fn);
22203 } finally {
22204 isBatchingUpdates = previousIsBatchingUpdates;
22205 if (!isBatchingUpdates && !isRendering) {
22206 performSyncWork();
22207 }
22208 }
22209}
22210
22211// TODO: Ahaha Andrew is bad at spellling
22212// DEV stuff
22213var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher;
22214var ReactCurrentOwner$4 = ReactSharedInternals.ReactCurrentOwner;
22215var ReactShouldWarnActingUpdates$1 = ReactSharedInternals.ReactShouldWarnActingUpdates;
22216
22217var NotWorking = 0;
22218var BatchedPhase = 1;
22219var LegacyUnbatchedPhase = 2;
22220var FlushSyncPhase = 3;
22221var RenderPhase = 4;
22222var CommitPhase = 5;
22223
22224var RootIncomplete = 0;
22225var RootErrored = 1;
22226var RootSuspended = 2;
22227var RootCompleted = 3;
22228
22229// The phase of work we're currently in
22230var workPhase = NotWorking;
22231// The root we're working on
22232var workInProgressRoot = null;
22233// The fiber we're working on
22234var workInProgress = null;
22235// The expiration time we're rendering
22236var renderExpirationTime$1 = NoWork;
22237// Whether to root completed, errored, suspended, etc.
22238var workInProgressRootExitStatus = RootIncomplete;
22239var workInProgressRootAbsoluteTimeoutMs = -1;
22240
22241var nextEffect$1 = null;
22242var hasUncaughtError = false;
22243var firstUncaughtError = null;
22244var legacyErrorBoundariesThatAlreadyFailed$1 = null;
22245
22246var rootDoesHavePassiveEffects = false;
22247var rootWithPendingPassiveEffects$1 = null;
22248var pendingPassiveEffectsExpirationTime = NoWork;
22249
22250var rootsWithPendingDiscreteUpdates = null;
22251
22252// Use these to prevent an infinite loop of nested updates
22253var NESTED_UPDATE_LIMIT$1 = 50;
22254var nestedUpdateCount$1 = 0;
22255var rootWithNestedUpdates = null;
22256
22257var NESTED_PASSIVE_UPDATE_LIMIT$1 = 50;
22258var nestedPassiveUpdateCount = 0;
22259
22260var interruptedBy$1 = null;
22261
22262// Expiration times are computed by adding to the current time (the start
22263// time). However, if two updates are scheduled within the same event, we
22264// should treat their start times as simultaneous, even if the actual clock
22265// time has advanced between the first and second call.
22266
22267// In other words, because expiration times determine how updates are batched,
22268// we want all updates of like priority that occur within the same event to
22269// receive the same expiration time. Otherwise we get tearing.
22270var currentEventTime = NoWork;
22271
22272function requestCurrentTime$2() {
22273 if (workPhase === RenderPhase || workPhase === CommitPhase) {
22274 // We're inside React, so it's fine to read the actual time.
22275 return msToExpirationTime(now$1());
22276 }
22277 // We're not inside React, so we may be in the middle of a browser event.
22278 if (currentEventTime !== NoWork) {
22279 // Use the same start time for all updates until we enter React again.
22280 return currentEventTime;
22281 }
22282 // This is the first update since React yielded. Compute a new start time.
22283 currentEventTime = msToExpirationTime(now$1());
22284 return currentEventTime;
22285}
22286
22287function computeExpirationForFiber$2(currentTime, fiber) {
22288 if ((fiber.mode & ConcurrentMode) === NoContext) {
22289 return Sync;
22290 }
22291
22292 if (workPhase === RenderPhase) {
22293 // Use whatever time we're already rendering
22294 return renderExpirationTime$1;
22295 }
22296
22297 // Compute an expiration time based on the Scheduler priority.
22298 var expirationTime = void 0;
22299 var priorityLevel = getCurrentPriorityLevel();
22300 switch (priorityLevel) {
22301 case ImmediatePriority:
22302 expirationTime = Sync;
22303 break;
22304 case UserBlockingPriority:
22305 // TODO: Rename this to computeUserBlockingExpiration
22306 expirationTime = computeInteractiveExpiration(currentTime);
22307 break;
22308 case NormalPriority:
22309 case LowPriority:
22310 // TODO: Handle LowPriority
22311 // TODO: Rename this to... something better.
22312 expirationTime = computeAsyncExpiration(currentTime);
22313 break;
22314 case IdlePriority:
22315 expirationTime = Never;
22316 break;
22317 default:
22318 (function () {
22319 {
22320 {
22321 throw ReactError('Expected a valid priority level');
22322 }
22323 }
22324 })();
22325 }
22326
22327 // If we're in the middle of rendering a tree, do not update at the same
22328 // expiration time that is already rendering.
22329 if (workInProgressRoot !== null && expirationTime === renderExpirationTime$1) {
22330 // This is a trick to move this update into a separate batch
22331 expirationTime -= 1;
22332 }
22333
22334 return expirationTime;
22335}
22336
22337var lastUniqueAsyncExpiration$1 = NoWork;
22338function computeUniqueAsyncExpiration$2() {
22339 var currentTime = requestCurrentTime$2();
22340 var result = computeAsyncExpiration(currentTime);
22341 if (result <= lastUniqueAsyncExpiration$1) {
22342 // Since we assume the current time monotonically increases, we only hit
22343 // this branch when computeUniqueAsyncExpiration is fired multiple times
22344 // within a 200ms window (or whatever the async bucket size is).
22345 result -= 1;
22346 }
22347 lastUniqueAsyncExpiration$1 = result;
22348 return result;
22349}
22350
22351function scheduleUpdateOnFiber(fiber, expirationTime) {
22352 checkForNestedUpdates();
22353 warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber);
22354
22355 var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime);
22356 if (root === null) {
22357 warnAboutUpdateOnUnmountedFiberInDEV(fiber);
22358 return;
22359 }
22360
22361 root.pingTime = NoWork;
22362
22363 checkForInterruption(fiber, expirationTime);
22364 recordScheduleUpdate();
22365
22366 if (expirationTime === Sync) {
22367 if (workPhase === LegacyUnbatchedPhase) {
22368 // This is a legacy edge case. The initial mount of a ReactDOM.render-ed
22369 // root inside of batchedUpdates should be synchronous, but layout updates
22370 // should be deferred until the end of the batch.
22371 var callback = renderRoot$1(root, Sync, true);
22372 while (callback !== null) {
22373 callback = callback(true);
22374 }
22375 } else {
22376 scheduleCallbackForRoot(root, ImmediatePriority, Sync);
22377 if (workPhase === NotWorking) {
22378 // Flush the synchronous work now, wnless we're already working or inside
22379 // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
22380 // scheduleCallbackForFiber to preserve the ability to schedule a callback
22381 // without immediately flushing it. We only do this for user-initated
22382 // updates, to preserve historical behavior of sync mode.
22383 flushImmediateQueue();
22384 }
22385 }
22386 } else {
22387 // TODO: computeExpirationForFiber also reads the priority. Pass the
22388 // priority as an argument to that function and this one.
22389 var priorityLevel = getCurrentPriorityLevel();
22390 if (priorityLevel === UserBlockingPriority) {
22391 // This is the result of a discrete event. Track the lowest priority
22392 // discrete update per root so we can flush them early, if needed.
22393 if (rootsWithPendingDiscreteUpdates === null) {
22394 rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]);
22395 } else {
22396 var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);
22397 if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) {
22398 rootsWithPendingDiscreteUpdates.set(root, expirationTime);
22399 }
22400 }
22401 }
22402 scheduleCallbackForRoot(root, priorityLevel, expirationTime);
22403 }
22404}
22405var scheduleWork$2 = scheduleUpdateOnFiber;
22406
22407// This is split into a separate function so we can mark a fiber with pending
22408// work without treating it as a typical update that originates from an event;
22409// e.g. retrying a Suspense boundary isn't an update, but it does schedule work
22410// on a fiber.
22411function markUpdateTimeFromFiberToRoot(fiber, expirationTime) {
22412 // Update the source fiber's expiration time
22413 if (fiber.expirationTime < expirationTime) {
22414 fiber.expirationTime = expirationTime;
22415 }
22416 var alternate = fiber.alternate;
22417 if (alternate !== null && alternate.expirationTime < expirationTime) {
22418 alternate.expirationTime = expirationTime;
22419 }
22420 // Walk the parent path to the root and update the child expiration time.
22421 var node = fiber.return;
22422 var root = null;
22423 if (node === null && fiber.tag === HostRoot) {
22424 root = fiber.stateNode;
22425 } else {
22426 while (node !== null) {
22427 alternate = node.alternate;
22428 if (node.childExpirationTime < expirationTime) {
22429 node.childExpirationTime = expirationTime;
22430 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
22431 alternate.childExpirationTime = expirationTime;
22432 }
22433 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
22434 alternate.childExpirationTime = expirationTime;
22435 }
22436 if (node.return === null && node.tag === HostRoot) {
22437 root = node.stateNode;
22438 break;
22439 }
22440 node = node.return;
22441 }
22442 }
22443
22444 if (root !== null) {
22445 // Update the first and last pending expiration times in this root
22446 var firstPendingTime = root.firstPendingTime;
22447 if (expirationTime > firstPendingTime) {
22448 root.firstPendingTime = expirationTime;
22449 }
22450 var lastPendingTime = root.lastPendingTime;
22451 if (lastPendingTime === NoWork || expirationTime < lastPendingTime) {
22452 root.lastPendingTime = expirationTime;
22453 }
22454 }
22455
22456 return root;
22457}
22458
22459// Use this function, along with runRootCallback, to ensure that only a single
22460// callback per root is scheduled. It's still possible to call renderRoot
22461// directly, but scheduling via this function helps avoid excessive callbacks.
22462// It works by storing the callback node and expiration time on the root. When a
22463// new callback comes in, it compares the expiration time to determine if it
22464// should cancel the previous one. It also relies on commitRoot scheduling a
22465// callback to render the next level, because that means we don't need a
22466// separate callback per expiration time.
22467function scheduleCallbackForRoot(root, priorityLevel, expirationTime) {
22468 var existingCallbackExpirationTime = root.callbackExpirationTime;
22469 if (existingCallbackExpirationTime < expirationTime) {
22470 // New callback has higher priority than the existing one.
22471 var existingCallbackNode = root.callbackNode;
22472 if (existingCallbackNode !== null) {
22473 cancelCallback(existingCallbackNode);
22474 }
22475 root.callbackExpirationTime = expirationTime;
22476 var options = expirationTime === Sync ? null : { timeout: expirationTimeToMs(expirationTime) };
22477 root.callbackNode = scheduleCallback(priorityLevel, runRootCallback.bind(null, root, renderRoot$1.bind(null, root, expirationTime)), options);
22478 if (enableUserTimingAPI && expirationTime !== Sync && workPhase !== RenderPhase && workPhase !== CommitPhase) {
22479 // Scheduled an async callback, and we're not already working. Add an
22480 // entry to the flamegraph that shows we're waiting for a callback
22481 // to fire.
22482 startRequestCallbackTimer();
22483 }
22484 }
22485
22486 var timeoutHandle = root.timeoutHandle;
22487 if (timeoutHandle !== noTimeout) {
22488 // The root previous suspended and scheduled a timeout to commit a fallback
22489 // state. Now that we have additional work, cancel the timeout.
22490 root.timeoutHandle = noTimeout;
22491 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
22492 cancelTimeout(timeoutHandle);
22493 }
22494
22495 // Add the current set of interactions to the pending set associated with
22496 // this root.
22497 schedulePendingInteraction(root, expirationTime);
22498}
22499
22500function runRootCallback(root, callback, isSync) {
22501 var prevCallbackNode = root.callbackNode;
22502 var continuation = null;
22503 try {
22504 continuation = callback(isSync);
22505 if (continuation !== null) {
22506 return runRootCallback.bind(null, root, continuation);
22507 } else {
22508 return null;
22509 }
22510 } finally {
22511 // If the callback exits without returning a continuation, remove the
22512 // corresponding callback node from the root. Unless the callback node
22513 // has changed, which implies that it was already cancelled by a high
22514 // priority update.
22515 if (continuation === null && prevCallbackNode === root.callbackNode) {
22516 root.callbackNode = null;
22517 root.callbackExpirationTime = NoWork;
22518 }
22519 }
22520}
22521
22522function flushRoot$2(root, expirationTime) {
22523 if (workPhase === RenderPhase || workPhase === CommitPhase) {
22524 (function () {
22525 {
22526 {
22527 throw ReactError('work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.');
22528 }
22529 }
22530 })();
22531 }
22532 scheduleCallback(ImmediatePriority, renderRoot$1.bind(null, root, expirationTime));
22533 flushImmediateQueue();
22534}
22535
22536function flushInteractiveUpdates$3() {
22537 if (workPhase === RenderPhase || workPhase === CommitPhase) {
22538 // Can't synchronously flush interactive updates if React is already
22539 // working. This is currently a no-op.
22540 // TODO: Should we fire a warning? This happens if you synchronously invoke
22541 // an input event inside an effect, like with `element.click()`.
22542 return;
22543 }
22544 flushPendingDiscreteUpdates();
22545}
22546
22547function resolveLocksOnRoot(root, expirationTime) {
22548 var firstBatch = root.firstBatch;
22549 if (firstBatch !== null && firstBatch._defer && firstBatch._expirationTime >= expirationTime) {
22550 root.finishedWork = root.current.alternate;
22551 root.pendingCommitExpirationTime = expirationTime;
22552 scheduleCallback(NormalPriority, function () {
22553 firstBatch._onComplete();
22554 return null;
22555 });
22556 return true;
22557 } else {
22558 return false;
22559 }
22560}
22561
22562
22563
22564function interactiveUpdates$3(fn, a, b, c) {
22565 if (workPhase === NotWorking) {
22566 // TODO: Remove this call. Instead of doing this automatically, the caller
22567 // should explicitly call flushInteractiveUpdates.
22568 flushPendingDiscreteUpdates();
22569 }
22570 return runWithPriority(UserBlockingPriority, fn.bind(null, a, b, c));
22571}
22572
22573
22574
22575function flushPendingDiscreteUpdates() {
22576 if (rootsWithPendingDiscreteUpdates !== null) {
22577 // For each root with pending discrete updates, schedule a callback to
22578 // immediately flush them.
22579 var roots = rootsWithPendingDiscreteUpdates;
22580 rootsWithPendingDiscreteUpdates = null;
22581 roots.forEach(function (expirationTime, root) {
22582 scheduleCallback(ImmediatePriority, renderRoot$1.bind(null, root, expirationTime));
22583 });
22584 // Now flush the immediate queue.
22585 flushImmediateQueue();
22586 }
22587}
22588
22589function batchedUpdates$3(fn, a) {
22590 if (workPhase !== NotWorking) {
22591 // We're already working, or inside a batch, so batchedUpdates is a no-op.
22592 return fn(a);
22593 }
22594 workPhase = BatchedPhase;
22595 try {
22596 return fn(a);
22597 } finally {
22598 workPhase = NotWorking;
22599 // Flush the immediate callbacks that were scheduled during this batch
22600 flushImmediateQueue();
22601 }
22602}
22603
22604function unbatchedUpdates$2(fn, a) {
22605 if (workPhase !== BatchedPhase && workPhase !== FlushSyncPhase) {
22606 // We're not inside batchedUpdates or flushSync, so unbatchedUpdates is
22607 // a no-op.
22608 return fn(a);
22609 }
22610 var prevWorkPhase = workPhase;
22611 workPhase = LegacyUnbatchedPhase;
22612 try {
22613 return fn(a);
22614 } finally {
22615 workPhase = prevWorkPhase;
22616 }
22617}
22618
22619function flushSync$2(fn, a) {
22620 if (workPhase === RenderPhase || workPhase === CommitPhase) {
22621 (function () {
22622 {
22623 {
22624 throw ReactError('flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.');
22625 }
22626 }
22627 })();
22628 }
22629 var prevWorkPhase = workPhase;
22630 workPhase = FlushSyncPhase;
22631 try {
22632 return runWithPriority(ImmediatePriority, fn.bind(null, a));
22633 } finally {
22634 workPhase = prevWorkPhase;
22635 // Flush the immediate callbacks that were scheduled during this batch.
22636 // Note that this will happen even if batchedUpdates is higher up
22637 // the stack.
22638 flushImmediateQueue();
22639 }
22640}
22641
22642function flushControlled$2(fn) {
22643 var prevWorkPhase = workPhase;
22644 workPhase = BatchedPhase;
22645 try {
22646 runWithPriority(ImmediatePriority, fn);
22647 } finally {
22648 workPhase = prevWorkPhase;
22649 if (workPhase === NotWorking) {
22650 // Flush the immediate callbacks that were scheduled during this batch
22651 flushImmediateQueue();
22652 }
22653 }
22654}
22655
22656function prepareFreshStack(root, expirationTime) {
22657 root.pendingCommitExpirationTime = NoWork;
22658
22659 if (workInProgress !== null) {
22660 var interruptedWork = workInProgress.return;
22661 while (interruptedWork !== null) {
22662 unwindInterruptedWork(interruptedWork);
22663 interruptedWork = interruptedWork.return;
22664 }
22665 }
22666 workInProgressRoot = root;
22667 workInProgress = createWorkInProgress(root.current, null, expirationTime);
22668 renderExpirationTime$1 = expirationTime;
22669 workInProgressRootExitStatus = RootIncomplete;
22670 workInProgressRootAbsoluteTimeoutMs = -1;
22671
22672 {
22673 ReactStrictModeWarnings.discardPendingWarnings();
22674 }
22675}
22676
22677function renderRoot$1(root, expirationTime, isSync) {
22678 (function () {
22679 if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) {
22680 {
22681 throw ReactError('Should not already be working.');
22682 }
22683 }
22684 })();
22685
22686 if (enableUserTimingAPI && expirationTime !== Sync) {
22687 var didExpire = isSync;
22688 var timeoutMs = expirationTimeToMs(expirationTime);
22689 stopRequestCallbackTimer(didExpire, timeoutMs);
22690 }
22691
22692 if (root.firstPendingTime < expirationTime) {
22693 // If there's no work left at this expiration time, exit immediately. This
22694 // happens when multiple callbacks are scheduled for a single root, but an
22695 // earlier callback flushes the work of a later one.
22696 return null;
22697 }
22698
22699 if (root.pendingCommitExpirationTime === expirationTime) {
22700 // There's already a pending commit at this expiration time.
22701 root.pendingCommitExpirationTime = NoWork;
22702 return commitRoot$1.bind(null, root, expirationTime);
22703 }
22704
22705 flushPassiveEffects$2();
22706
22707 // If the root or expiration time have changed, throw out the existing stack
22708 // and prepare a fresh one. Otherwise we'll continue where we left off.
22709 if (root !== workInProgressRoot || expirationTime !== renderExpirationTime$1) {
22710 prepareFreshStack(root, expirationTime);
22711 startWorkOnPendingInteraction(root, expirationTime);
22712 }
22713
22714 // If we have a work-in-progress fiber, it means there's still work to do
22715 // in this root.
22716 if (workInProgress !== null) {
22717 var prevWorkPhase = workPhase;
22718 workPhase = RenderPhase;
22719 var prevDispatcher = ReactCurrentDispatcher$2.current;
22720 if (prevDispatcher === null) {
22721 // The React isomorphic package does not include a default dispatcher.
22722 // Instead the first renderer will lazily attach one, in order to give
22723 // nicer error messages.
22724 prevDispatcher = ContextOnlyDispatcher;
22725 }
22726 ReactCurrentDispatcher$2.current = ContextOnlyDispatcher;
22727 var prevInteractions = null;
22728 if (enableSchedulerTracing) {
22729 prevInteractions = __interactionsRef.current;
22730 __interactionsRef.current = root.memoizedInteractions;
22731 }
22732
22733 startWorkLoopTimer(workInProgress);
22734 do {
22735 try {
22736 if (isSync) {
22737 if (expirationTime !== Sync) {
22738 // An async update expired. There may be other expired updates on
22739 // this root. We should render all the expired work in a
22740 // single batch.
22741 var currentTime = requestCurrentTime$2();
22742 if (currentTime < expirationTime) {
22743 // Restart at the current time.
22744 workPhase = prevWorkPhase;
22745 ReactCurrentDispatcher$2.current = prevDispatcher;
22746 return renderRoot$1.bind(null, root, currentTime);
22747 }
22748 }
22749 workLoopSync();
22750 } else {
22751 // Since we know we're in a React event, we can clear the current
22752 // event time. The next update will compute a new event time.
22753 currentEventTime = NoWork;
22754 workLoop$1();
22755 }
22756 break;
22757 } catch (thrownValue) {
22758 // Reset module-level state that was set during the render phase.
22759 resetContextDependences();
22760 resetHooks();
22761
22762 var sourceFiber = workInProgress;
22763 if (sourceFiber === null || sourceFiber.return === null) {
22764 // Expected to be working on a non-root fiber. This is a fatal error
22765 // because there's no ancestor that can handle it; the root is
22766 // supposed to capture all errors that weren't caught by an error
22767 // boundary.
22768 prepareFreshStack(root, expirationTime);
22769 workPhase = prevWorkPhase;
22770 throw thrownValue;
22771 }
22772
22773 if (enableProfilerTimer && sourceFiber.mode & ProfileMode) {
22774 // Record the time spent rendering before an error was thrown. This
22775 // avoids inaccurate Profiler durations in the case of a
22776 // suspended render.
22777 stopProfilerTimerIfRunningAndRecordDelta(sourceFiber, true);
22778 }
22779
22780 var returnFiber = sourceFiber.return;
22781 throwException(root, returnFiber, sourceFiber, thrownValue, renderExpirationTime$1);
22782 workInProgress = completeUnitOfWork$1(sourceFiber);
22783 }
22784 } while (true);
22785
22786 workPhase = prevWorkPhase;
22787 resetContextDependences();
22788 ReactCurrentDispatcher$2.current = prevDispatcher;
22789 if (enableSchedulerTracing) {
22790 __interactionsRef.current = prevInteractions;
22791 }
22792
22793 if (workInProgress !== null) {
22794 // There's still work left over. Return a continuation.
22795 stopInterruptedWorkLoopTimer();
22796 if (expirationTime !== Sync) {
22797 startRequestCallbackTimer();
22798 }
22799 return renderRoot$1.bind(null, root, expirationTime);
22800 }
22801 }
22802
22803 // We now have a consistent tree. The next step is either to commit it, or, if
22804 // something suspended, wait to commit it after a timeout.
22805 stopFinishedWorkLoopTimer();
22806
22807 var isLocked = resolveLocksOnRoot(root, expirationTime);
22808 if (isLocked) {
22809 // This root has a lock that prevents it from committing. Exit. If we begin
22810 // work on the root again, without any intervening updates, it will finish
22811 // without doing additional work.
22812 return null;
22813 }
22814
22815 // Set this to null to indicate there's no in-progress render.
22816 workInProgressRoot = null;
22817
22818 switch (workInProgressRootExitStatus) {
22819 case RootIncomplete:
22820 {
22821 (function () {
22822 {
22823 {
22824 throw ReactError('Should have a work-in-progress.');
22825 }
22826 }
22827 })();
22828 }
22829 // Flow knows about invariant, so it compains if I add a break statement,
22830 // but eslint doesn't know about invariant, so it complains if I do.
22831 // eslint-disable-next-line no-fallthrough
22832 case RootErrored:
22833 {
22834 // An error was thrown. First check if there is lower priority work
22835 // scheduled on this root.
22836 var lastPendingTime = root.lastPendingTime;
22837 if (root.lastPendingTime < expirationTime) {
22838 // There's lower priority work. Before raising the error, try rendering
22839 // at the lower priority to see if it fixes it. Use a continuation to
22840 // maintain the existing priority and position in the queue.
22841 return renderRoot$1.bind(null, root, lastPendingTime);
22842 }
22843 if (!isSync) {
22844 // If we're rendering asynchronously, it's possible the error was
22845 // caused by tearing due to a mutation during an event. Try rendering
22846 // one more time without yiedling to events.
22847 prepareFreshStack(root, expirationTime);
22848 scheduleCallback(ImmediatePriority, renderRoot$1.bind(null, root, expirationTime));
22849 return null;
22850 }
22851 // If we're already rendering synchronously, commit the root in its
22852 // errored state.
22853 return commitRoot$1.bind(null, root, expirationTime);
22854 }
22855 case RootSuspended:
22856 {
22857 var _lastPendingTime = root.lastPendingTime;
22858 if (root.lastPendingTime < expirationTime) {
22859 // There's lower priority work. It might be unsuspended. Try rendering
22860 // at that level.
22861 return renderRoot$1.bind(null, root, _lastPendingTime);
22862 }
22863 if (!isSync) {
22864 var msUntilTimeout = computeMsUntilTimeout(root, workInProgressRootAbsoluteTimeoutMs);
22865 if (msUntilTimeout > 0) {
22866 // The render is suspended, it hasn't timed out, and there's no lower
22867 // priority work to do. Instead of committing the fallback
22868 // immediately, wait for more data to arrive.
22869 root.timeoutHandle = scheduleTimeout(commitRoot$1.bind(null, root, expirationTime), msUntilTimeout);
22870 return null;
22871 }
22872 }
22873 // The work expired. Commit immediately.
22874 return commitRoot$1.bind(null, root, expirationTime);
22875 }
22876 case RootCompleted:
22877 {
22878 // The work completed. Ready to commit.
22879 return commitRoot$1.bind(null, root, expirationTime);
22880 }
22881 default:
22882 {
22883 (function () {
22884 {
22885 {
22886 throw ReactError('Unknown root exit status.');
22887 }
22888 }
22889 })();
22890 }
22891 }
22892}
22893
22894function renderDidSuspend$2(root, absoluteTimeoutMs,
22895// TODO: Don't need this argument anymore
22896suspendedTime) {
22897 if (absoluteTimeoutMs >= 0 && workInProgressRootAbsoluteTimeoutMs < absoluteTimeoutMs) {
22898 workInProgressRootAbsoluteTimeoutMs = absoluteTimeoutMs;
22899 if (workInProgressRootExitStatus === RootIncomplete) {
22900 workInProgressRootExitStatus = RootSuspended;
22901 }
22902 }
22903}
22904
22905function renderDidError$2() {
22906 if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {
22907 workInProgressRootExitStatus = RootErrored;
22908 }
22909}
22910
22911function workLoopSync() {
22912 // Already timed out, so perform work without checking if we need to yield.
22913 while (workInProgress !== null) {
22914 workInProgress = performUnitOfWork$1(workInProgress);
22915 }
22916}
22917
22918function workLoop$1() {
22919 // Perform work until Scheduler asks us to yield
22920 while (workInProgress !== null && !shouldYield$1()) {
22921 workInProgress = performUnitOfWork$1(workInProgress);
22922 }
22923}
22924
22925function performUnitOfWork$1(unitOfWork) {
22926 // The current, flushed, state of this fiber is the alternate. Ideally
22927 // nothing should rely on this, but relying on it here means that we don't
22928 // need an additional field on the work in progress.
22929 var current$$1 = unitOfWork.alternate;
22930
22931 startWorkTimer(unitOfWork);
22932 setCurrentFiber(unitOfWork);
22933
22934 var next = void 0;
22935 if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoContext) {
22936 startProfilerTimer(unitOfWork);
22937 next = beginWork$1(current$$1, unitOfWork, renderExpirationTime$1);
22938 stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
22939 } else {
22940 next = beginWork$1(current$$1, unitOfWork, renderExpirationTime$1);
22941 }
22942
22943 resetCurrentFiber();
22944 unitOfWork.memoizedProps = unitOfWork.pendingProps;
22945 if (next === null) {
22946 // If this doesn't spawn new work, complete the current work.
22947 next = completeUnitOfWork$1(unitOfWork);
22948 }
22949
22950 ReactCurrentOwner$4.current = null;
22951 return next;
22952}
22953
22954function completeUnitOfWork$1(unitOfWork) {
22955 // Attempt to complete the current unit of work, then move to the next
22956 // sibling. If there are no more siblings, return to the parent fiber.
22957 workInProgress = unitOfWork;
22958 do {
22959 // The current, flushed, state of this fiber is the alternate. Ideally
22960 // nothing should rely on this, but relying on it here means that we don't
22961 // need an additional field on the work in progress.
22962 var current$$1 = workInProgress.alternate;
22963 var returnFiber = workInProgress.return;
22964
22965 // Check if the work completed or if something threw.
22966 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
22967 setCurrentFiber(workInProgress);
22968 var next = void 0;
22969 if (!enableProfilerTimer || (workInProgress.mode & ProfileMode) === NoContext) {
22970 next = completeWork(current$$1, workInProgress, renderExpirationTime$1);
22971 } else {
22972 startProfilerTimer(workInProgress);
22973 next = completeWork(current$$1, workInProgress, renderExpirationTime$1);
22974 // Update render duration assuming we didn't error.
22975 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
22976 }
22977 stopWorkTimer(workInProgress);
22978 resetCurrentFiber();
22979 resetChildExpirationTime$1(workInProgress);
22980
22981 if (next !== null) {
22982 // Completing this fiber spawned new work. Work on that next.
22983 return next;
22984 }
22985
22986 if (returnFiber !== null &&
22987 // Do not append effects to parents if a sibling failed to complete
22988 (returnFiber.effectTag & Incomplete) === NoEffect) {
22989 // Append all the effects of the subtree and this fiber onto the effect
22990 // list of the parent. The completion order of the children affects the
22991 // side-effect order.
22992 if (returnFiber.firstEffect === null) {
22993 returnFiber.firstEffect = workInProgress.firstEffect;
22994 }
22995 if (workInProgress.lastEffect !== null) {
22996 if (returnFiber.lastEffect !== null) {
22997 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
22998 }
22999 returnFiber.lastEffect = workInProgress.lastEffect;
23000 }
23001
23002 // If this fiber had side-effects, we append it AFTER the children's
23003 // side-effects. We can perform certain side-effects earlier if needed,
23004 // by doing multiple passes over the effect list. We don't want to
23005 // schedule our own side-effect on our own list because if end up
23006 // reusing children we'll schedule this effect onto itself since we're
23007 // at the end.
23008 var effectTag = workInProgress.effectTag;
23009
23010 // Skip both NoWork and PerformedWork tags when creating the effect
23011 // list. PerformedWork effect is read by React DevTools but shouldn't be
23012 // committed.
23013 if (effectTag > PerformedWork) {
23014 if (returnFiber.lastEffect !== null) {
23015 returnFiber.lastEffect.nextEffect = workInProgress;
23016 } else {
23017 returnFiber.firstEffect = workInProgress;
23018 }
23019 returnFiber.lastEffect = workInProgress;
23020 }
23021 }
23022 } else {
23023 // This fiber did not complete because something threw. Pop values off
23024 // the stack without entering the complete phase. If this is a boundary,
23025 // capture values if possible.
23026 var _next = unwindWork(workInProgress, renderExpirationTime$1);
23027
23028 // Because this fiber did not complete, don't reset its expiration time.
23029
23030 if (enableProfilerTimer && (workInProgress.mode & ProfileMode) !== NoContext) {
23031 // Record the render duration for the fiber that errored.
23032 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
23033
23034 // Include the time spent working on failed children before continuing.
23035 var actualDuration = workInProgress.actualDuration;
23036 var child = workInProgress.child;
23037 while (child !== null) {
23038 actualDuration += child.actualDuration;
23039 child = child.sibling;
23040 }
23041 workInProgress.actualDuration = actualDuration;
23042 }
23043
23044 if (_next !== null) {
23045 // If completing this work spawned new work, do that next. We'll come
23046 // back here again.
23047 // Since we're restarting, remove anything that is not a host effect
23048 // from the effect tag.
23049 // TODO: The name stopFailedWorkTimer is misleading because Suspense
23050 // also captures and restarts.
23051 stopFailedWorkTimer(workInProgress);
23052 _next.effectTag &= HostEffectMask;
23053 return _next;
23054 }
23055 stopWorkTimer(workInProgress);
23056
23057 if (returnFiber !== null) {
23058 // Mark the parent fiber as incomplete and clear its effect list.
23059 returnFiber.firstEffect = returnFiber.lastEffect = null;
23060 returnFiber.effectTag |= Incomplete;
23061 }
23062 }
23063
23064 var siblingFiber = workInProgress.sibling;
23065 if (siblingFiber !== null) {
23066 // If there is more work to do in this returnFiber, do that next.
23067 return siblingFiber;
23068 }
23069 // Otherwise, return to the parent
23070 workInProgress = returnFiber;
23071 } while (workInProgress !== null);
23072
23073 // We've reached the root.
23074 if (workInProgressRootExitStatus === RootIncomplete) {
23075 workInProgressRootExitStatus = RootCompleted;
23076 }
23077 return null;
23078}
23079
23080function resetChildExpirationTime$1(completedWork) {
23081 if (renderExpirationTime$1 !== Never && completedWork.childExpirationTime === Never) {
23082 // The children of this component are hidden. Don't bubble their
23083 // expiration times.
23084 return;
23085 }
23086
23087 var newChildExpirationTime = NoWork;
23088
23089 // Bubble up the earliest expiration time.
23090 if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoContext) {
23091 // In profiling mode, resetChildExpirationTime is also used to reset
23092 // profiler durations.
23093 var actualDuration = completedWork.actualDuration;
23094 var treeBaseDuration = completedWork.selfBaseDuration;
23095
23096 // When a fiber is cloned, its actualDuration is reset to 0. This value will
23097 // only be updated if work is done on the fiber (i.e. it doesn't bailout).
23098 // When work is done, it should bubble to the parent's actualDuration. If
23099 // the fiber has not been cloned though, (meaning no work was done), then
23100 // this value will reflect the amount of time spent working on a previous
23101 // render. In that case it should not bubble. We determine whether it was
23102 // cloned by comparing the child pointer.
23103 var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;
23104
23105 var child = completedWork.child;
23106 while (child !== null) {
23107 var childUpdateExpirationTime = child.expirationTime;
23108 var childChildExpirationTime = child.childExpirationTime;
23109 if (childUpdateExpirationTime > newChildExpirationTime) {
23110 newChildExpirationTime = childUpdateExpirationTime;
23111 }
23112 if (childChildExpirationTime > newChildExpirationTime) {
23113 newChildExpirationTime = childChildExpirationTime;
23114 }
23115 if (shouldBubbleActualDurations) {
23116 actualDuration += child.actualDuration;
23117 }
23118 treeBaseDuration += child.treeBaseDuration;
23119 child = child.sibling;
23120 }
23121 completedWork.actualDuration = actualDuration;
23122 completedWork.treeBaseDuration = treeBaseDuration;
23123 } else {
23124 var _child = completedWork.child;
23125 while (_child !== null) {
23126 var _childUpdateExpirationTime = _child.expirationTime;
23127 var _childChildExpirationTime = _child.childExpirationTime;
23128 if (_childUpdateExpirationTime > newChildExpirationTime) {
23129 newChildExpirationTime = _childUpdateExpirationTime;
23130 }
23131 if (_childChildExpirationTime > newChildExpirationTime) {
23132 newChildExpirationTime = _childChildExpirationTime;
23133 }
23134 _child = _child.sibling;
23135 }
23136 }
23137
23138 completedWork.childExpirationTime = newChildExpirationTime;
23139}
23140
23141function commitRoot$1(root, expirationTime) {
23142 runWithPriority(ImmediatePriority, commitRootImpl.bind(null, root, expirationTime));
23143 // If there are passive effects, schedule a callback to flush them. This goes
23144 // outside commitRootImpl so that it inherits the priority of the render.
23145 if (rootWithPendingPassiveEffects$1 !== null) {
23146 var priorityLevel = getCurrentPriorityLevel();
23147 scheduleCallback(priorityLevel, function () {
23148 flushPassiveEffects$2();
23149 return null;
23150 });
23151 }
23152 return null;
23153}
23154
23155function commitRootImpl(root, expirationTime) {
23156 flushPassiveEffects$2();
23157 flushRenderPhaseStrictModeWarningsInDEV();
23158
23159 (function () {
23160 if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) {
23161 {
23162 throw ReactError('Should not already be working.');
23163 }
23164 }
23165 })();
23166 var finishedWork = root.current.alternate;
23167 (function () {
23168 if (!(finishedWork !== null)) {
23169 {
23170 throw ReactError('Should have a work-in-progress root.');
23171 }
23172 }
23173 })();
23174
23175 // commitRoot never returns a continuation; it always finishes synchronously.
23176 // So we can clear these now to allow a new callback to be scheduled.
23177 root.callbackNode = null;
23178 root.callbackExpirationTime = NoWork;
23179
23180 startCommitTimer();
23181
23182 // Update the first and last pending times on this root. The new first
23183 // pending time is whatever is left on the root fiber.
23184 var updateExpirationTimeBeforeCommit = finishedWork.expirationTime;
23185 var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime;
23186 var firstPendingTimeBeforeCommit = childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit ? childExpirationTimeBeforeCommit : updateExpirationTimeBeforeCommit;
23187 root.firstPendingTime = firstPendingTimeBeforeCommit;
23188 if (firstPendingTimeBeforeCommit < root.lastPendingTime) {
23189 // This usually means we've finished all the work, but it can also happen
23190 // when something gets downprioritized during render, like a hidden tree.
23191 root.lastPendingTime = firstPendingTimeBeforeCommit;
23192 }
23193
23194 if (root === workInProgressRoot) {
23195 // We can reset these now that they are finished.
23196 workInProgressRoot = null;
23197 workInProgress = null;
23198 renderExpirationTime$1 = NoWork;
23199 } else {}
23200 // This indicates that the last root we worked on is not the same one that
23201 // we're committing now. This most commonly happens when a suspended root
23202 // times out.
23203
23204
23205 // Get the list of effects.
23206 var firstEffect = void 0;
23207 if (finishedWork.effectTag > PerformedWork) {
23208 // A fiber's effect list consists only of its children, not itself. So if
23209 // the root has an effect, we need to add it to the end of the list. The
23210 // resulting list is the set that would belong to the root's parent, if it
23211 // had one; that is, all the effects in the tree including the root.
23212 if (finishedWork.lastEffect !== null) {
23213 finishedWork.lastEffect.nextEffect = finishedWork;
23214 firstEffect = finishedWork.firstEffect;
23215 } else {
23216 firstEffect = finishedWork;
23217 }
23218 } else {
23219 // There is no effect on the root.
23220 firstEffect = finishedWork.firstEffect;
23221 }
23222
23223 if (firstEffect !== null) {
23224 var prevWorkPhase = workPhase;
23225 workPhase = CommitPhase;
23226 var prevInteractions = null;
23227 if (enableSchedulerTracing) {
23228 prevInteractions = __interactionsRef.current;
23229 __interactionsRef.current = root.memoizedInteractions;
23230 }
23231
23232 // Reset this to null before calling lifecycles
23233 ReactCurrentOwner$4.current = null;
23234
23235 // The commit phase is broken into several sub-phases. We do a separate pass
23236 // of the effect list for each phase: all mutation effects come before all
23237 // layout effects, and so on.
23238
23239 // The first phase a "before mutation" phase. We use this phase to read the
23240 // state of the host tree right before we mutate it. This is where
23241 // getSnapshotBeforeUpdate is called.
23242 startCommitSnapshotEffectsTimer();
23243 prepareForCommit(root.containerInfo);
23244 nextEffect$1 = firstEffect;
23245 do {
23246 {
23247 invokeGuardedCallback(null, commitBeforeMutationEffects, null);
23248 if (hasCaughtError()) {
23249 (function () {
23250 if (!(nextEffect$1 !== null)) {
23251 {
23252 throw ReactError('Should be working on an effect.');
23253 }
23254 }
23255 })();
23256 var error = clearCaughtError();
23257 captureCommitPhaseError$2(nextEffect$1, error);
23258 nextEffect$1 = nextEffect$1.nextEffect;
23259 }
23260 }
23261 } while (nextEffect$1 !== null);
23262 stopCommitSnapshotEffectsTimer();
23263
23264 if (enableProfilerTimer) {
23265 // Mark the current commit time to be shared by all Profilers in this
23266 // batch. This enables them to be grouped later.
23267 recordCommitTime();
23268 }
23269
23270 // The next phase is the mutation phase, where we mutate the host tree.
23271 startCommitHostEffectsTimer();
23272 nextEffect$1 = firstEffect;
23273 do {
23274 {
23275 invokeGuardedCallback(null, commitMutationEffects, null);
23276 if (hasCaughtError()) {
23277 (function () {
23278 if (!(nextEffect$1 !== null)) {
23279 {
23280 throw ReactError('Should be working on an effect.');
23281 }
23282 }
23283 })();
23284 var _error = clearCaughtError();
23285 captureCommitPhaseError$2(nextEffect$1, _error);
23286 nextEffect$1 = nextEffect$1.nextEffect;
23287 }
23288 }
23289 } while (nextEffect$1 !== null);
23290 stopCommitHostEffectsTimer();
23291 resetAfterCommit(root.containerInfo);
23292
23293 // The work-in-progress tree is now the current tree. This must come after
23294 // the mutation phase, so that the previous tree is still current during
23295 // componentWillUnmount, but before the layout phase, so that the finished
23296 // work is current during componentDidMount/Update.
23297 root.current = finishedWork;
23298
23299 // The next phase is the layout phase, where we call effects that read
23300 // the host tree after it's been mutated. The idiomatic use case for this is
23301 // layout, but class component lifecycles also fire here for legacy reasons.
23302 startCommitLifeCyclesTimer();
23303 nextEffect$1 = firstEffect;
23304 do {
23305 {
23306 invokeGuardedCallback(null, commitLayoutEffects, null, root, expirationTime);
23307 if (hasCaughtError()) {
23308 (function () {
23309 if (!(nextEffect$1 !== null)) {
23310 {
23311 throw ReactError('Should be working on an effect.');
23312 }
23313 }
23314 })();
23315 var _error2 = clearCaughtError();
23316 captureCommitPhaseError$2(nextEffect$1, _error2);
23317 nextEffect$1 = nextEffect$1.nextEffect;
23318 }
23319 }
23320 } while (nextEffect$1 !== null);
23321 stopCommitLifeCyclesTimer();
23322
23323 nextEffect$1 = null;
23324
23325 if (enableSchedulerTracing) {
23326 __interactionsRef.current = prevInteractions;
23327 }
23328 workPhase = prevWorkPhase;
23329 } else {
23330 // No effects.
23331 root.current = finishedWork;
23332 // Measure these anyway so the flamegraph explicitly shows that there were
23333 // no effects.
23334 // TODO: Maybe there's a better way to report this.
23335 startCommitSnapshotEffectsTimer();
23336 stopCommitSnapshotEffectsTimer();
23337 if (enableProfilerTimer) {
23338 recordCommitTime();
23339 }
23340 startCommitHostEffectsTimer();
23341 stopCommitHostEffectsTimer();
23342 startCommitLifeCyclesTimer();
23343 stopCommitLifeCyclesTimer();
23344 }
23345
23346 stopCommitTimer();
23347
23348 if (rootDoesHavePassiveEffects) {
23349 // This commit has passive effects. Stash a reference to them. But don't
23350 // schedule a callback until after flushing layout work.
23351 rootDoesHavePassiveEffects = false;
23352 rootWithPendingPassiveEffects$1 = root;
23353 pendingPassiveEffectsExpirationTime = expirationTime;
23354 } else {
23355 if (enableSchedulerTracing) {
23356 // If there are no passive effects, then we can complete the pending
23357 // interactions. Otherwise, we'll wait until after the passive effects
23358 // are flushed.
23359 finishPendingInteractions(root, expirationTime);
23360 }
23361 }
23362
23363 // Check if there's remaining work on this root
23364 var remainingExpirationTime = root.firstPendingTime;
23365 if (remainingExpirationTime !== NoWork) {
23366 var currentTime = requestCurrentTime$2();
23367 var priorityLevel = inferPriorityFromExpirationTime(currentTime, remainingExpirationTime);
23368 scheduleCallbackForRoot(root, priorityLevel, remainingExpirationTime);
23369 } else {
23370 // If there's no remaining work, we can clear the set of already failed
23371 // error boundaries.
23372 legacyErrorBoundariesThatAlreadyFailed$1 = null;
23373 }
23374
23375 onCommitRoot(finishedWork.stateNode);
23376
23377 if (remainingExpirationTime === Sync) {
23378 // Count the number of times the root synchronously re-renders without
23379 // finishing. If there are too many, it indicates an infinite update loop.
23380 if (root === rootWithNestedUpdates) {
23381 nestedUpdateCount$1++;
23382 } else {
23383 nestedUpdateCount$1 = 0;
23384 rootWithNestedUpdates = root;
23385 }
23386 } else {
23387 nestedUpdateCount$1 = 0;
23388 }
23389
23390 if (hasUncaughtError) {
23391 hasUncaughtError = false;
23392 var _error3 = firstUncaughtError;
23393 firstUncaughtError = null;
23394 throw _error3;
23395 }
23396
23397 if (workPhase === LegacyUnbatchedPhase) {
23398 // This is a legacy edge case. We just committed the initial mount of
23399 // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
23400 // synchronously, but layout updates should be deferred until the end
23401 // of the batch.
23402 return null;
23403 }
23404
23405 // If layout work was scheduled, flush it now.
23406 flushImmediateQueue();
23407 return null;
23408}
23409
23410function commitBeforeMutationEffects() {
23411 while (nextEffect$1 !== null) {
23412 if ((nextEffect$1.effectTag & Snapshot) !== NoEffect) {
23413 setCurrentFiber(nextEffect$1);
23414 recordEffect();
23415
23416 var current$$1 = nextEffect$1.alternate;
23417 commitBeforeMutationLifeCycles(current$$1, nextEffect$1);
23418
23419 resetCurrentFiber();
23420 }
23421 nextEffect$1 = nextEffect$1.nextEffect;
23422 }
23423}
23424
23425function commitMutationEffects() {
23426 // TODO: Should probably move the bulk of this function to commitWork.
23427 while (nextEffect$1 !== null) {
23428 setCurrentFiber(nextEffect$1);
23429
23430 var effectTag = nextEffect$1.effectTag;
23431
23432 if (effectTag & ContentReset) {
23433 commitResetTextContent(nextEffect$1);
23434 }
23435
23436 if (effectTag & Ref) {
23437 var current$$1 = nextEffect$1.alternate;
23438 if (current$$1 !== null) {
23439 commitDetachRef(current$$1);
23440 }
23441 }
23442
23443 // The following switch statement is only concerned about placement,
23444 // updates, and deletions. To avoid needing to add a case for every possible
23445 // bitmap value, we remove the secondary effects from the effect tag and
23446 // switch on that value.
23447 var primaryEffectTag = effectTag & (Placement | Update | Deletion);
23448 switch (primaryEffectTag) {
23449 case Placement:
23450 {
23451 commitPlacement(nextEffect$1);
23452 // Clear the "placement" from effect tag so that we know that this is
23453 // inserted, before any life-cycles like componentDidMount gets called.
23454 // TODO: findDOMNode doesn't rely on this any more but isMounted does
23455 // and isMounted is deprecated anyway so we should be able to kill this.
23456 nextEffect$1.effectTag &= ~Placement;
23457 break;
23458 }
23459 case PlacementAndUpdate:
23460 {
23461 // Placement
23462 commitPlacement(nextEffect$1);
23463 // Clear the "placement" from effect tag so that we know that this is
23464 // inserted, before any life-cycles like componentDidMount gets called.
23465 nextEffect$1.effectTag &= ~Placement;
23466
23467 // Update
23468 var _current = nextEffect$1.alternate;
23469 commitWork(_current, nextEffect$1);
23470 break;
23471 }
23472 case Update:
23473 {
23474 var _current2 = nextEffect$1.alternate;
23475 commitWork(_current2, nextEffect$1);
23476 break;
23477 }
23478 case Deletion:
23479 {
23480 commitDeletion(nextEffect$1);
23481 break;
23482 }
23483 }
23484
23485 // TODO: Only record a mutation effect if primaryEffectTag is non-zero.
23486 recordEffect();
23487
23488 resetCurrentFiber();
23489 nextEffect$1 = nextEffect$1.nextEffect;
23490 }
23491}
23492
23493function commitLayoutEffects(root, committedExpirationTime) {
23494 // TODO: Should probably move the bulk of this function to commitWork.
23495 while (nextEffect$1 !== null) {
23496 setCurrentFiber(nextEffect$1);
23497
23498 var effectTag = nextEffect$1.effectTag;
23499
23500 if (effectTag & (Update | Callback)) {
23501 recordEffect();
23502 var current$$1 = nextEffect$1.alternate;
23503 commitLifeCycles(root, current$$1, nextEffect$1, committedExpirationTime);
23504 }
23505
23506 if (effectTag & Ref) {
23507 recordEffect();
23508 commitAttachRef(nextEffect$1);
23509 }
23510
23511 if (effectTag & Passive) {
23512 rootDoesHavePassiveEffects = true;
23513 }
23514
23515 resetCurrentFiber();
23516 nextEffect$1 = nextEffect$1.nextEffect;
23517 }
23518}
23519
23520function flushPassiveEffects$2() {
23521 if (rootWithPendingPassiveEffects$1 === null) {
23522 return false;
23523 }
23524 var root = rootWithPendingPassiveEffects$1;
23525 var expirationTime = pendingPassiveEffectsExpirationTime;
23526 rootWithPendingPassiveEffects$1 = null;
23527 pendingPassiveEffectsExpirationTime = NoWork;
23528
23529 var prevInteractions = null;
23530 if (enableSchedulerTracing) {
23531 prevInteractions = __interactionsRef.current;
23532 __interactionsRef.current = root.memoizedInteractions;
23533 }
23534
23535 (function () {
23536 if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) {
23537 {
23538 throw ReactError('Cannot flush passive effects while already rendering.');
23539 }
23540 }
23541 })();
23542 var prevWorkPhase = workPhase;
23543 workPhase = CommitPhase;
23544
23545 // Note: This currently assumes there are no passive effects on the root
23546 // fiber, because the root is not part of its own effect list. This could
23547 // change in the future.
23548 var effect = root.current.firstEffect;
23549 while (effect !== null) {
23550 {
23551 setCurrentFiber(effect);
23552 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
23553 if (hasCaughtError()) {
23554 (function () {
23555 if (!(effect !== null)) {
23556 {
23557 throw ReactError('Should be working on an effect.');
23558 }
23559 }
23560 })();
23561 var error = clearCaughtError();
23562 captureCommitPhaseError$2(effect, error);
23563 }
23564 resetCurrentFiber();
23565 }
23566 effect = effect.nextEffect;
23567 }
23568
23569 if (enableSchedulerTracing) {
23570 __interactionsRef.current = prevInteractions;
23571 finishPendingInteractions(root, expirationTime);
23572 }
23573
23574 workPhase = prevWorkPhase;
23575 flushImmediateQueue();
23576
23577 // If additional passive effects were scheduled, increment a counter. If this
23578 // exceeds the limit, we'll fire a warning.
23579 nestedPassiveUpdateCount = rootWithPendingPassiveEffects$1 === null ? 0 : nestedPassiveUpdateCount + 1;
23580
23581 return true;
23582}
23583
23584function isAlreadyFailedLegacyErrorBoundary$2(instance) {
23585 return legacyErrorBoundariesThatAlreadyFailed$1 !== null && legacyErrorBoundariesThatAlreadyFailed$1.has(instance);
23586}
23587
23588function markLegacyErrorBoundaryAsFailed$2(instance) {
23589 if (legacyErrorBoundariesThatAlreadyFailed$1 === null) {
23590 legacyErrorBoundariesThatAlreadyFailed$1 = new Set([instance]);
23591 } else {
23592 legacyErrorBoundariesThatAlreadyFailed$1.add(instance);
23593 }
23594}
23595
23596function prepareToThrowUncaughtError(error) {
23597 if (!hasUncaughtError) {
23598 hasUncaughtError = true;
23599 firstUncaughtError = error;
23600 }
23601}
23602var onUncaughtError$2 = prepareToThrowUncaughtError;
23603
23604function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
23605 var errorInfo = createCapturedValue(error, sourceFiber);
23606 var update = createRootErrorUpdate(rootFiber, errorInfo, Sync);
23607 enqueueUpdate(rootFiber, update);
23608 var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync);
23609 if (root !== null) {
23610 scheduleCallbackForRoot(root, ImmediatePriority, Sync);
23611 }
23612}
23613
23614function captureCommitPhaseError$2(sourceFiber, error) {
23615 if (sourceFiber.tag === HostRoot) {
23616 // Error was thrown at the root. There is no parent, so the root
23617 // itself should capture it.
23618 captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
23619 return;
23620 }
23621
23622 var fiber = sourceFiber.return;
23623 while (fiber !== null) {
23624 if (fiber.tag === HostRoot) {
23625 captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
23626 return;
23627 } else if (fiber.tag === ClassComponent) {
23628 var ctor = fiber.type;
23629 var instance = fiber.stateNode;
23630 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary$2(instance)) {
23631 var errorInfo = createCapturedValue(error, sourceFiber);
23632 var update = createClassErrorUpdate(fiber, errorInfo,
23633 // TODO: This is always sync
23634 Sync);
23635 enqueueUpdate(fiber, update);
23636 var root = markUpdateTimeFromFiberToRoot(fiber, Sync);
23637 if (root !== null) {
23638 scheduleCallbackForRoot(root, ImmediatePriority, Sync);
23639 }
23640 return;
23641 }
23642 }
23643 fiber = fiber.return;
23644 }
23645}
23646
23647function pingSuspendedRoot$2(root, thenable, suspendedTime) {
23648 var pingCache = root.pingCache;
23649 if (pingCache !== null) {
23650 // The thenable resolved, so we no longer need to memoize, because it will
23651 // never be thrown again.
23652 pingCache.delete(thenable);
23653 }
23654
23655 if (workInProgressRoot === root && renderExpirationTime$1 === suspendedTime) {
23656 // Received a ping at the same priority level at which we're currently
23657 // rendering. Restart from the root. Don't need to schedule a ping because
23658 // we're already working on this tree.
23659 prepareFreshStack(root, renderExpirationTime$1);
23660 return;
23661 }
23662
23663 var lastPendingTime = root.lastPendingTime;
23664 if (lastPendingTime < suspendedTime) {
23665 // The root is no longer suspended at this time.
23666 return;
23667 }
23668
23669 var pingTime = root.pingTime;
23670 if (pingTime !== NoWork && pingTime < suspendedTime) {
23671 // There's already a lower priority ping scheduled.
23672 return;
23673 }
23674
23675 // Mark the time at which this ping was scheduled.
23676 root.pingTime = suspendedTime;
23677
23678 var currentTime = requestCurrentTime$2();
23679 var priorityLevel = inferPriorityFromExpirationTime(currentTime, suspendedTime);
23680 scheduleCallbackForRoot(root, priorityLevel, suspendedTime);
23681}
23682
23683function retryTimedOutBoundary$2(boundaryFiber) {
23684 // The boundary fiber (a Suspense component) previously timed out and was
23685 // rendered in its fallback state. One of the promises that suspended it has
23686 // resolved, which means at least part of the tree was likely unblocked. Try
23687 // rendering again, at a new expiration time.
23688 var currentTime = requestCurrentTime$2();
23689 var retryTime = computeExpirationForFiber$2(currentTime, boundaryFiber);
23690 // TODO: Special case idle priority?
23691 var priorityLevel = inferPriorityFromExpirationTime(currentTime, retryTime);
23692 var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime);
23693 if (root !== null) {
23694 scheduleCallbackForRoot(root, priorityLevel, retryTime);
23695 }
23696}
23697
23698function resolveRetryThenable$2(boundaryFiber, thenable) {
23699 var retryCache = void 0;
23700 if (enableSuspenseServerRenderer) {
23701 switch (boundaryFiber.tag) {
23702 case SuspenseComponent:
23703 retryCache = boundaryFiber.stateNode;
23704 break;
23705 case DehydratedSuspenseComponent:
23706 retryCache = boundaryFiber.memoizedState;
23707 break;
23708 default:
23709 (function () {
23710 {
23711 {
23712 throw ReactError('Pinged unknown suspense boundary type. This is probably a bug in React.');
23713 }
23714 }
23715 })();
23716 }
23717 } else {
23718 retryCache = boundaryFiber.stateNode;
23719 }
23720
23721 if (retryCache !== null) {
23722 // The thenable resolved, so we no longer need to memoize, because it will
23723 // never be thrown again.
23724 retryCache.delete(thenable);
23725 }
23726
23727 retryTimedOutBoundary$2(boundaryFiber);
23728}
23729
23730function inferStartTimeFromExpirationTime$2(root, expirationTime) {
23731 // We don't know exactly when the update was scheduled, but we can infer an
23732 // approximate start time from the expiration time.
23733 var earliestExpirationTimeMs = expirationTimeToMs(root.firstPendingTime);
23734 // TODO: Track this on the root instead. It's more accurate, doesn't rely on
23735 // assumptions about priority, and isn't coupled to Scheduler details.
23736 return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
23737}
23738
23739function computeMsUntilTimeout(root, absoluteTimeoutMs) {
23740 if (disableYielding) {
23741 // Timeout immediately when yielding is disabled.
23742 return 0;
23743 }
23744
23745 // Find the earliest uncommitted expiration time in the tree, including
23746 // work that is suspended. The timeout threshold cannot be longer than
23747 // the overall expiration.
23748 var earliestExpirationTimeMs = expirationTimeToMs(root.firstPendingTime);
23749 if (earliestExpirationTimeMs < absoluteTimeoutMs) {
23750 absoluteTimeoutMs = earliestExpirationTimeMs;
23751 }
23752
23753 // Subtract the current time from the absolute timeout to get the number
23754 // of milliseconds until the timeout. In other words, convert an absolute
23755 // timestamp to a relative time. This is the value that is passed
23756 // to `setTimeout`.
23757 var msUntilTimeout = absoluteTimeoutMs - now$1();
23758 return msUntilTimeout < 0 ? 0 : msUntilTimeout;
23759}
23760
23761function checkForNestedUpdates() {
23762 if (nestedUpdateCount$1 > NESTED_UPDATE_LIMIT$1) {
23763 nestedUpdateCount$1 = 0;
23764 rootWithNestedUpdates = null;
23765 (function () {
23766 {
23767 {
23768 throw ReactError('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.');
23769 }
23770 }
23771 })();
23772 }
23773
23774 {
23775 if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT$1) {
23776 nestedPassiveUpdateCount = 0;
23777 warning$1(false, 'Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.');
23778 }
23779 }
23780}
23781
23782function flushRenderPhaseStrictModeWarningsInDEV() {
23783 {
23784 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
23785 ReactStrictModeWarnings.flushLegacyContextWarning();
23786
23787 if (warnAboutDeprecatedLifecycles) {
23788 ReactStrictModeWarnings.flushPendingDeprecationWarnings();
23789 }
23790 }
23791}
23792
23793function stopFinishedWorkLoopTimer() {
23794 var didCompleteRoot = true;
23795 stopWorkLoopTimer(interruptedBy$1, didCompleteRoot);
23796 interruptedBy$1 = null;
23797}
23798
23799function stopInterruptedWorkLoopTimer() {
23800 // TODO: Track which fiber caused the interruption.
23801 var didCompleteRoot = false;
23802 stopWorkLoopTimer(interruptedBy$1, didCompleteRoot);
23803 interruptedBy$1 = null;
23804}
23805
23806function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) {
23807 if (enableUserTimingAPI && workInProgressRoot !== null && updateExpirationTime > renderExpirationTime$1) {
23808 interruptedBy$1 = fiberThatReceivedUpdate;
23809 }
23810}
23811
23812var didWarnStateUpdateForUnmountedComponent$1 = null;
23813function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
23814 {
23815 var tag = fiber.tag;
23816 if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
23817 // Only warn for user-defined components, not internal ones like Suspense.
23818 return;
23819 }
23820 // We show the whole stack but dedupe on the top component's name because
23821 // the problematic code almost always lies inside that component.
23822 var componentName = getComponentName(fiber.type) || 'ReactComponent';
23823 if (didWarnStateUpdateForUnmountedComponent$1 !== null) {
23824 if (didWarnStateUpdateForUnmountedComponent$1.has(componentName)) {
23825 return;
23826 }
23827 didWarnStateUpdateForUnmountedComponent$1.add(componentName);
23828 } else {
23829 didWarnStateUpdateForUnmountedComponent$1 = new Set([componentName]);
23830 }
23831 warningWithoutStack$1(false, "Can't perform a React state update on an unmounted component. This " + 'is a no-op, but it indicates a memory leak in your application. To ' + 'fix, cancel all subscriptions and asynchronous tasks in %s.%s', tag === ClassComponent ? 'the componentWillUnmount method' : 'a useEffect cleanup function', getStackByFiberInDevAndProd(fiber));
23832 }
23833}
23834
23835var beginWork$1 = void 0;
23836if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
23837 var dummyFiber = null;
23838 beginWork$1 = function (current$$1, unitOfWork, expirationTime) {
23839 // If a component throws an error, we replay it again in a synchronously
23840 // dispatched event, so that the debugger will treat it as an uncaught
23841 // error See ReactErrorUtils for more information.
23842
23843 // Before entering the begin phase, copy the work-in-progress onto a dummy
23844 // fiber. If beginWork throws, we'll use this to reset the state.
23845 var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
23846 try {
23847 return beginWork(current$$1, unitOfWork, expirationTime);
23848 } catch (originalError) {
23849 if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
23850 // Don't replay promises. Treat everything else like an error.
23851 throw originalError;
23852 }
23853
23854 // Keep this code in sync with renderRoot; any changes here must have
23855 // corresponding changes there.
23856 resetContextDependences();
23857 resetHooks();
23858
23859 // Unwind the failed stack frame
23860 unwindInterruptedWork(unitOfWork);
23861
23862 // Restore the original properties of the fiber.
23863 assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
23864
23865 if (enableProfilerTimer && unitOfWork.mode & ProfileMode) {
23866 // Reset the profiler timer.
23867 startProfilerTimer(unitOfWork);
23868 }
23869
23870 // Run beginWork again.
23871 invokeGuardedCallback(null, beginWork, null, current$$1, unitOfWork, expirationTime);
23872
23873 if (hasCaughtError()) {
23874 var replayError = clearCaughtError();
23875 // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
23876 // Rethrow this error instead of the original one.
23877 throw replayError;
23878 } else {
23879 // This branch is reachable if the render phase is impure.
23880 throw originalError;
23881 }
23882 }
23883 };
23884} else {
23885 beginWork$1 = beginWork;
23886}
23887
23888var didWarnAboutUpdateInRender = false;
23889var didWarnAboutUpdateInGetChildContext = false;
23890function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) {
23891 {
23892 if (fiber.tag === ClassComponent) {
23893 switch (phase) {
23894 case 'getChildContext':
23895 if (didWarnAboutUpdateInGetChildContext) {
23896 return;
23897 }
23898 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
23899 didWarnAboutUpdateInGetChildContext = true;
23900 break;
23901 case 'render':
23902 if (didWarnAboutUpdateInRender) {
23903 return;
23904 }
23905 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.');
23906 didWarnAboutUpdateInRender = true;
23907 break;
23908 }
23909 }
23910 }
23911}
23912
23913function warnIfNotCurrentlyActingUpdatesInDEV(fiber) {
23914 {
23915 if (workPhase === NotWorking && ReactShouldWarnActingUpdates$1.current === false) {
23916 warningWithoutStack$1(false, 'An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));
23917 }
23918 }
23919}
23920
23921var warnIfNotCurrentlyActingUpdatesInDev$2 = warnIfNotCurrentlyActingUpdatesInDEV;
23922
23923function computeThreadID$1(root, expirationTime) {
23924 // Interaction threads are unique per root and expiration time.
23925 return expirationTime * 1000 + root.interactionThreadID;
23926}
23927
23928function schedulePendingInteraction(root, expirationTime) {
23929 // This is called when work is scheduled on a root. It sets up a pending
23930 // interaction, which is completed once the work commits.
23931 if (!enableSchedulerTracing) {
23932 return;
23933 }
23934
23935 var interactions = __interactionsRef.current;
23936 if (interactions.size > 0) {
23937 var pendingInteractionMap = root.pendingInteractionMap;
23938 var pendingInteractions = pendingInteractionMap.get(expirationTime);
23939 if (pendingInteractions != null) {
23940 interactions.forEach(function (interaction) {
23941 if (!pendingInteractions.has(interaction)) {
23942 // Update the pending async work count for previously unscheduled interaction.
23943 interaction.__count++;
23944 }
23945
23946 pendingInteractions.add(interaction);
23947 });
23948 } else {
23949 pendingInteractionMap.set(expirationTime, new Set(interactions));
23950
23951 // Update the pending async work count for the current interactions.
23952 interactions.forEach(function (interaction) {
23953 interaction.__count++;
23954 });
23955 }
23956
23957 var subscriber = __subscriberRef.current;
23958 if (subscriber !== null) {
23959 var threadID = computeThreadID$1(root, expirationTime);
23960 subscriber.onWorkScheduled(interactions, threadID);
23961 }
23962 }
23963}
23964
23965function startWorkOnPendingInteraction(root, expirationTime) {
23966 // This is called when new work is started on a root.
23967 if (!enableSchedulerTracing) {
23968 return;
23969 }
23970
23971 // Determine which interactions this batch of work currently includes, So that
23972 // we can accurately attribute time spent working on it, And so that cascading
23973 // work triggered during the render phase will be associated with it.
23974 var interactions = new Set();
23975 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
23976 if (scheduledExpirationTime >= expirationTime) {
23977 scheduledInteractions.forEach(function (interaction) {
23978 return interactions.add(interaction);
23979 });
23980 }
23981 });
23982
23983 // Store the current set of interactions on the FiberRoot for a few reasons:
23984 // We can re-use it in hot functions like renderRoot() without having to
23985 // recalculate it. We will also use it in commitWork() to pass to any Profiler
23986 // onRender() hooks. This also provides DevTools with a way to access it when
23987 // the onCommitRoot() hook is called.
23988 root.memoizedInteractions = interactions;
23989
23990 if (interactions.size > 0) {
23991 var subscriber = __subscriberRef.current;
23992 if (subscriber !== null) {
23993 var threadID = computeThreadID$1(root, expirationTime);
23994 try {
23995 subscriber.onWorkStarted(interactions, threadID);
23996 } catch (error) {
23997 // If the subscriber throws, rethrow it in a separate task
23998 scheduleCallback(ImmediatePriority, function () {
23999 throw error;
24000 });
24001 }
24002 }
24003 }
24004}
24005
24006function finishPendingInteractions(root, committedExpirationTime) {
24007 if (!enableSchedulerTracing) {
24008 return;
24009 }
24010
24011 var earliestRemainingTimeAfterCommit = root.firstPendingTime;
24012
24013 var subscriber = void 0;
24014
24015 try {
24016 subscriber = __subscriberRef.current;
24017 if (subscriber !== null && root.memoizedInteractions.size > 0) {
24018 var threadID = computeThreadID$1(root, committedExpirationTime);
24019 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
24020 }
24021 } catch (error) {
24022 // If the subscriber throws, rethrow it in a separate task
24023 scheduleCallback(ImmediatePriority, function () {
24024 throw error;
24025 });
24026 } finally {
24027 // Clear completed interactions from the pending Map.
24028 // Unless the render was suspended or cascading work was scheduled,
24029 // In which case– leave pending interactions until the subsequent render.
24030 var pendingInteractionMap = root.pendingInteractionMap;
24031 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
24032 // Only decrement the pending interaction count if we're done.
24033 // If there's still work at the current priority,
24034 // That indicates that we are waiting for suspense data.
24035 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
24036 pendingInteractionMap.delete(scheduledExpirationTime);
24037
24038 scheduledInteractions.forEach(function (interaction) {
24039 interaction.__count--;
24040
24041 if (subscriber !== null && interaction.__count === 0) {
24042 try {
24043 subscriber.onInteractionScheduledWorkCompleted(interaction);
24044 } catch (error) {
24045 // If the subscriber throws, rethrow it in a separate task
24046 scheduleCallback(ImmediatePriority, function () {
24047 throw error;
24048 });
24049 }
24050 }
24051 });
24052 }
24053 });
24054 }
24055}
24056
24057var requestCurrentTime$$1 = enableNewScheduler ? requestCurrentTime$2 : requestCurrentTime$1;
24058var computeExpirationForFiber$$1 = enableNewScheduler ? computeExpirationForFiber$2 : computeExpirationForFiber$1;
24059var captureCommitPhaseError$$1 = enableNewScheduler ? captureCommitPhaseError$2 : captureCommitPhaseError$1;
24060var onUncaughtError$$1 = enableNewScheduler ? onUncaughtError$2 : onUncaughtError$1;
24061var renderDidSuspend$$1 = enableNewScheduler ? renderDidSuspend$2 : renderDidSuspend$1;
24062var renderDidError$$1 = enableNewScheduler ? renderDidError$2 : renderDidError$1;
24063var pingSuspendedRoot$$1 = enableNewScheduler ? pingSuspendedRoot$2 : pingSuspendedRoot$1;
24064var retryTimedOutBoundary$$1 = enableNewScheduler ? retryTimedOutBoundary$2 : retryTimedOutBoundary$1;
24065var resolveRetryThenable$$1 = enableNewScheduler ? resolveRetryThenable$2 : resolveRetryThenable$1;
24066var markLegacyErrorBoundaryAsFailed$$1 = enableNewScheduler ? markLegacyErrorBoundaryAsFailed$2 : markLegacyErrorBoundaryAsFailed$1;
24067var isAlreadyFailedLegacyErrorBoundary$$1 = enableNewScheduler ? isAlreadyFailedLegacyErrorBoundary$2 : isAlreadyFailedLegacyErrorBoundary$1;
24068var scheduleWork$$1 = enableNewScheduler ? scheduleWork$2 : scheduleWork$1;
24069var flushRoot$$1 = enableNewScheduler ? flushRoot$2 : flushRoot$1;
24070var batchedUpdates$1 = enableNewScheduler ? batchedUpdates$3 : batchedUpdates$2;
24071var unbatchedUpdates$$1 = enableNewScheduler ? unbatchedUpdates$2 : unbatchedUpdates$1;
24072var flushSync$$1 = enableNewScheduler ? flushSync$2 : flushSync$1;
24073var flushControlled$$1 = enableNewScheduler ? flushControlled$2 : flushControlled$1;
24074
24075
24076var interactiveUpdates$1 = enableNewScheduler ? interactiveUpdates$3 : interactiveUpdates$2;
24077var flushInteractiveUpdates$1 = enableNewScheduler ? flushInteractiveUpdates$3 : flushInteractiveUpdates$2;
24078var computeUniqueAsyncExpiration$$1 = enableNewScheduler ? computeUniqueAsyncExpiration$2 : computeUniqueAsyncExpiration$1;
24079var flushPassiveEffects$$1 = enableNewScheduler ? flushPassiveEffects$2 : flushPassiveEffects$1;
24080var warnIfNotCurrentlyActingUpdatesInDev$$1 = enableNewScheduler ? warnIfNotCurrentlyActingUpdatesInDev$2 : warnIfNotCurrentlyActingUpdatesInDev$1;
24081var inferStartTimeFromExpirationTime$$1 = enableNewScheduler ? inferStartTimeFromExpirationTime$2 : inferStartTimeFromExpirationTime$1;
24082
24083// 0 is PROD, 1 is DEV.
24084// Might add PROFILE later.
24085
24086
24087var didWarnAboutNestedUpdates = void 0;
24088var didWarnAboutFindNodeInStrictMode = void 0;
24089
24090{
24091 didWarnAboutNestedUpdates = false;
24092 didWarnAboutFindNodeInStrictMode = {};
24093}
24094
24095function getContextForSubtree(parentComponent) {
24096 if (!parentComponent) {
24097 return emptyContextObject;
24098 }
24099
24100 var fiber = get(parentComponent);
24101 var parentContext = findCurrentUnmaskedContext(fiber);
24102
24103 if (fiber.tag === ClassComponent) {
24104 var Component = fiber.type;
24105 if (isContextProvider(Component)) {
24106 return processChildContext(fiber, Component, parentContext);
24107 }
24108 }
24109
24110 return parentContext;
24111}
24112
24113function scheduleRootUpdate(current$$1, element, expirationTime, callback) {
24114 {
24115 if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) {
24116 didWarnAboutNestedUpdates = true;
24117 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');
24118 }
24119 }
24120
24121 var update = createUpdate(expirationTime);
24122 // Caution: React DevTools currently depends on this property
24123 // being called "element".
24124 update.payload = { element: element };
24125
24126 callback = callback === undefined ? null : callback;
24127 if (callback !== null) {
24128 !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
24129 update.callback = callback;
24130 }
24131
24132 flushPassiveEffects$$1();
24133 enqueueUpdate(current$$1, update);
24134 scheduleWork$$1(current$$1, expirationTime);
24135
24136 return expirationTime;
24137}
24138
24139function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback) {
24140 // TODO: If this is a nested container, this won't be the root.
24141 var current$$1 = container.current;
24142
24143 {
24144 if (ReactFiberInstrumentation_1.debugTool) {
24145 if (current$$1.alternate === null) {
24146 ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
24147 } else if (element === null) {
24148 ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
24149 } else {
24150 ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
24151 }
24152 }
24153 }
24154
24155 var context = getContextForSubtree(parentComponent);
24156 if (container.context === null) {
24157 container.context = context;
24158 } else {
24159 container.pendingContext = context;
24160 }
24161
24162 return scheduleRootUpdate(current$$1, element, expirationTime, callback);
24163}
24164
24165function findHostInstance(component) {
24166 var fiber = get(component);
24167 if (fiber === undefined) {
24168 if (typeof component.render === 'function') {
24169 (function () {
24170 {
24171 {
24172 throw ReactError('Unable to find node on an unmounted component.');
24173 }
24174 }
24175 })();
24176 } else {
24177 (function () {
24178 {
24179 {
24180 throw ReactError('Argument appears to not be a ReactComponent. Keys: ' + Object.keys(component));
24181 }
24182 }
24183 })();
24184 }
24185 }
24186 var hostFiber = findCurrentHostFiber(fiber);
24187 if (hostFiber === null) {
24188 return null;
24189 }
24190 return hostFiber.stateNode;
24191}
24192
24193function findHostInstanceWithWarning(component, methodName) {
24194 {
24195 var fiber = get(component);
24196 if (fiber === undefined) {
24197 if (typeof component.render === 'function') {
24198 (function () {
24199 {
24200 {
24201 throw ReactError('Unable to find node on an unmounted component.');
24202 }
24203 }
24204 })();
24205 } else {
24206 (function () {
24207 {
24208 {
24209 throw ReactError('Argument appears to not be a ReactComponent. Keys: ' + Object.keys(component));
24210 }
24211 }
24212 })();
24213 }
24214 }
24215 var hostFiber = findCurrentHostFiber(fiber);
24216 if (hostFiber === null) {
24217 return null;
24218 }
24219 if (hostFiber.mode & StrictMode) {
24220 var componentName = getComponentName(fiber.type) || 'Component';
24221 if (!didWarnAboutFindNodeInStrictMode[componentName]) {
24222 didWarnAboutFindNodeInStrictMode[componentName] = true;
24223 if (fiber.mode & StrictMode) {
24224 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));
24225 } else {
24226 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));
24227 }
24228 }
24229 }
24230 return hostFiber.stateNode;
24231 }
24232 return findHostInstance(component);
24233}
24234
24235function createContainer(containerInfo, isConcurrent, hydrate) {
24236 return createFiberRoot(containerInfo, isConcurrent, hydrate);
24237}
24238
24239function updateContainer(element, container, parentComponent, callback) {
24240 var current$$1 = container.current;
24241 var currentTime = requestCurrentTime$$1();
24242 var expirationTime = computeExpirationForFiber$$1(currentTime, current$$1);
24243 return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback);
24244}
24245
24246function getPublicRootInstance(container) {
24247 var containerFiber = container.current;
24248 if (!containerFiber.child) {
24249 return null;
24250 }
24251 switch (containerFiber.child.tag) {
24252 case HostComponent:
24253 return getPublicInstance(containerFiber.child.stateNode);
24254 default:
24255 return containerFiber.child.stateNode;
24256 }
24257}
24258
24259function findHostInstanceWithNoPortals(fiber) {
24260 var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
24261 if (hostFiber === null) {
24262 return null;
24263 }
24264 return hostFiber.stateNode;
24265}
24266
24267var overrideHookState = null;
24268var overrideProps = null;
24269
24270{
24271 var copyWithSetImpl = function (obj, path, idx, value) {
24272 if (idx >= path.length) {
24273 return value;
24274 }
24275 var key = path[idx];
24276 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
24277 // $FlowFixMe number or string is fine here
24278 updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
24279 return updated;
24280 };
24281
24282 var copyWithSet = function (obj, path, value) {
24283 return copyWithSetImpl(obj, path, 0, value);
24284 };
24285
24286 // Support DevTools editable values for useState and useReducer.
24287 overrideHookState = function (fiber, id, path, value) {
24288 // For now, the "id" of stateful hooks is just the stateful hook index.
24289 // This may change in the future with e.g. nested hooks.
24290 var currentHook = fiber.memoizedState;
24291 while (currentHook !== null && id > 0) {
24292 currentHook = currentHook.next;
24293 id--;
24294 }
24295 if (currentHook !== null) {
24296 flushPassiveEffects$$1();
24297
24298 var newState = copyWithSet(currentHook.memoizedState, path, value);
24299 currentHook.memoizedState = newState;
24300 currentHook.baseState = newState;
24301
24302 // We aren't actually adding an update to the queue,
24303 // because there is no update we can add for useReducer hooks that won't trigger an error.
24304 // (There's no appropriate action type for DevTools overrides.)
24305 // As a result though, React will see the scheduled update as a noop and bailout.
24306 // Shallow cloning props works as a workaround for now to bypass the bailout check.
24307 fiber.memoizedProps = _assign({}, fiber.memoizedProps);
24308
24309 scheduleWork$$1(fiber, Sync);
24310 }
24311 };
24312
24313 // Support DevTools props for function components, forwardRef, memo, host components, etc.
24314 overrideProps = function (fiber, path, value) {
24315 flushPassiveEffects$$1();
24316 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
24317 if (fiber.alternate) {
24318 fiber.alternate.pendingProps = fiber.pendingProps;
24319 }
24320 scheduleWork$$1(fiber, Sync);
24321 };
24322}
24323
24324function injectIntoDevTools(devToolsConfig) {
24325 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
24326 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
24327
24328
24329 return injectInternals(_assign({}, devToolsConfig, {
24330 overrideHookState: overrideHookState,
24331 overrideProps: overrideProps,
24332 currentDispatcherRef: ReactCurrentDispatcher,
24333 findHostInstanceByFiber: function (fiber) {
24334 var hostFiber = findCurrentHostFiber(fiber);
24335 if (hostFiber === null) {
24336 return null;
24337 }
24338 return hostFiber.stateNode;
24339 },
24340 findFiberByHostInstance: function (instance) {
24341 if (!findFiberByHostInstance) {
24342 // Might not be implemented by the renderer.
24343 return null;
24344 }
24345 return findFiberByHostInstance(instance);
24346 }
24347 }));
24348}
24349
24350// This file intentionally does *not* have the Flow annotation.
24351// Don't add it. See `./inline-typed.js` for an explanation.
24352
24353function createPortal$1(children, containerInfo,
24354// TODO: figure out the API for cross-renderer implementation.
24355implementation) {
24356 var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
24357
24358 return {
24359 // This tag allow us to uniquely identify this as a React Portal
24360 $$typeof: REACT_PORTAL_TYPE,
24361 key: key == null ? null : '' + key,
24362 children: children,
24363 containerInfo: containerInfo,
24364 implementation: implementation
24365 };
24366}
24367
24368// TODO: this is special because it gets imported during build.
24369
24370var ReactVersion = '16.9.0-alpha.0';
24371
24372// TODO: This type is shared between the reconciler and ReactDOM, but will
24373// eventually be lifted out to the renderer.
24374
24375var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
24376
24377var topLevelUpdateWarnings = void 0;
24378var warnOnInvalidCallback = void 0;
24379var didWarnAboutUnstableCreatePortal = false;
24380
24381{
24382 if (typeof Map !== 'function' ||
24383 // $FlowIssue Flow incorrectly thinks Map has no prototype
24384 Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' ||
24385 // $FlowIssue Flow incorrectly thinks Set has no prototype
24386 Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
24387 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');
24388 }
24389
24390 topLevelUpdateWarnings = function (container) {
24391 if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
24392 var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
24393 if (hostInstance) {
24394 !(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;
24395 }
24396 }
24397
24398 var isRootRenderedBySomeReact = !!container._reactRootContainer;
24399 var rootEl = getReactRootElementInContainer(container);
24400 var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));
24401
24402 !(!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;
24403
24404 !(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;
24405 };
24406
24407 warnOnInvalidCallback = function (callback, callerName) {
24408 !(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;
24409 };
24410}
24411
24412setRestoreImplementation(restoreControlledState$1);
24413
24414function ReactBatch(root) {
24415 var expirationTime = computeUniqueAsyncExpiration$$1();
24416 this._expirationTime = expirationTime;
24417 this._root = root;
24418 this._next = null;
24419 this._callbacks = null;
24420 this._didComplete = false;
24421 this._hasChildren = false;
24422 this._children = null;
24423 this._defer = true;
24424}
24425ReactBatch.prototype.render = function (children) {
24426 var _this = this;
24427
24428 (function () {
24429 if (!_this._defer) {
24430 {
24431 throw ReactError('batch.render: Cannot render a batch that already committed.');
24432 }
24433 }
24434 })();
24435 this._hasChildren = true;
24436 this._children = children;
24437 var internalRoot = this._root._internalRoot;
24438 var expirationTime = this._expirationTime;
24439 var work = new ReactWork();
24440 updateContainerAtExpirationTime(children, internalRoot, null, expirationTime, work._onCommit);
24441 return work;
24442};
24443ReactBatch.prototype.then = function (onComplete) {
24444 if (this._didComplete) {
24445 onComplete();
24446 return;
24447 }
24448 var callbacks = this._callbacks;
24449 if (callbacks === null) {
24450 callbacks = this._callbacks = [];
24451 }
24452 callbacks.push(onComplete);
24453};
24454ReactBatch.prototype.commit = function () {
24455 var _this2 = this;
24456
24457 var internalRoot = this._root._internalRoot;
24458 var firstBatch = internalRoot.firstBatch;
24459 (function () {
24460 if (!(_this2._defer && firstBatch !== null)) {
24461 {
24462 throw ReactError('batch.commit: Cannot commit a batch multiple times.');
24463 }
24464 }
24465 })();
24466
24467 if (!this._hasChildren) {
24468 // This batch is empty. Return.
24469 this._next = null;
24470 this._defer = false;
24471 return;
24472 }
24473
24474 var expirationTime = this._expirationTime;
24475
24476 // Ensure this is the first batch in the list.
24477 if (firstBatch !== this) {
24478 // This batch is not the earliest batch. We need to move it to the front.
24479 // Update its expiration time to be the expiration time of the earliest
24480 // batch, so that we can flush it without flushing the other batches.
24481 if (this._hasChildren) {
24482 expirationTime = this._expirationTime = firstBatch._expirationTime;
24483 // Rendering this batch again ensures its children will be the final state
24484 // when we flush (updates are processed in insertion order: last
24485 // update wins).
24486 // TODO: This forces a restart. Should we print a warning?
24487 this.render(this._children);
24488 }
24489
24490 // Remove the batch from the list.
24491 var previous = null;
24492 var batch = firstBatch;
24493 while (batch !== this) {
24494 previous = batch;
24495 batch = batch._next;
24496 }
24497 (function () {
24498 if (!(previous !== null)) {
24499 {
24500 throw ReactError('batch.commit: Cannot commit a batch multiple times.');
24501 }
24502 }
24503 })();
24504 previous._next = batch._next;
24505
24506 // Add it to the front.
24507 this._next = firstBatch;
24508 firstBatch = internalRoot.firstBatch = this;
24509 }
24510
24511 // Synchronously flush all the work up to this batch's expiration time.
24512 this._defer = false;
24513 flushRoot$$1(internalRoot, expirationTime);
24514
24515 // Pop the batch from the list.
24516 var next = this._next;
24517 this._next = null;
24518 firstBatch = internalRoot.firstBatch = next;
24519
24520 // Append the next earliest batch's children to the update queue.
24521 if (firstBatch !== null && firstBatch._hasChildren) {
24522 firstBatch.render(firstBatch._children);
24523 }
24524};
24525ReactBatch.prototype._onComplete = function () {
24526 if (this._didComplete) {
24527 return;
24528 }
24529 this._didComplete = true;
24530 var callbacks = this._callbacks;
24531 if (callbacks === null) {
24532 return;
24533 }
24534 // TODO: Error handling.
24535 for (var i = 0; i < callbacks.length; i++) {
24536 var _callback = callbacks[i];
24537 _callback();
24538 }
24539};
24540
24541function ReactWork() {
24542 this._callbacks = null;
24543 this._didCommit = false;
24544 // TODO: Avoid need to bind by replacing callbacks in the update queue with
24545 // list of Work objects.
24546 this._onCommit = this._onCommit.bind(this);
24547}
24548ReactWork.prototype.then = function (onCommit) {
24549 if (this._didCommit) {
24550 onCommit();
24551 return;
24552 }
24553 var callbacks = this._callbacks;
24554 if (callbacks === null) {
24555 callbacks = this._callbacks = [];
24556 }
24557 callbacks.push(onCommit);
24558};
24559ReactWork.prototype._onCommit = function () {
24560 if (this._didCommit) {
24561 return;
24562 }
24563 this._didCommit = true;
24564 var callbacks = this._callbacks;
24565 if (callbacks === null) {
24566 return;
24567 }
24568 // TODO: Error handling.
24569 for (var i = 0; i < callbacks.length; i++) {
24570 var _callback2 = callbacks[i];
24571 (function () {
24572 if (!(typeof _callback2 === 'function')) {
24573 {
24574 throw ReactError('Invalid argument passed as callback. Expected a function. Instead received: ' + _callback2);
24575 }
24576 }
24577 })();
24578 _callback2();
24579 }
24580};
24581
24582function ReactRoot(container, isConcurrent, hydrate) {
24583 var root = createContainer(container, isConcurrent, hydrate);
24584 this._internalRoot = root;
24585}
24586ReactRoot.prototype.render = function (children, callback) {
24587 var root = this._internalRoot;
24588 var work = new ReactWork();
24589 callback = callback === undefined ? null : callback;
24590 {
24591 warnOnInvalidCallback(callback, 'render');
24592 }
24593 if (callback !== null) {
24594 work.then(callback);
24595 }
24596 updateContainer(children, root, null, work._onCommit);
24597 return work;
24598};
24599ReactRoot.prototype.unmount = function (callback) {
24600 var root = this._internalRoot;
24601 var work = new ReactWork();
24602 callback = callback === undefined ? null : callback;
24603 {
24604 warnOnInvalidCallback(callback, 'render');
24605 }
24606 if (callback !== null) {
24607 work.then(callback);
24608 }
24609 updateContainer(null, root, null, work._onCommit);
24610 return work;
24611};
24612ReactRoot.prototype.legacy_renderSubtreeIntoContainer = function (parentComponent, children, callback) {
24613 var root = this._internalRoot;
24614 var work = new ReactWork();
24615 callback = callback === undefined ? null : callback;
24616 {
24617 warnOnInvalidCallback(callback, 'render');
24618 }
24619 if (callback !== null) {
24620 work.then(callback);
24621 }
24622 updateContainer(children, root, parentComponent, work._onCommit);
24623 return work;
24624};
24625ReactRoot.prototype.createBatch = function () {
24626 var batch = new ReactBatch(this);
24627 var expirationTime = batch._expirationTime;
24628
24629 var internalRoot = this._internalRoot;
24630 var firstBatch = internalRoot.firstBatch;
24631 if (firstBatch === null) {
24632 internalRoot.firstBatch = batch;
24633 batch._next = null;
24634 } else {
24635 // Insert sorted by expiration time then insertion order
24636 var insertAfter = null;
24637 var insertBefore = firstBatch;
24638 while (insertBefore !== null && insertBefore._expirationTime >= expirationTime) {
24639 insertAfter = insertBefore;
24640 insertBefore = insertBefore._next;
24641 }
24642 batch._next = insertBefore;
24643 if (insertAfter !== null) {
24644 insertAfter._next = batch;
24645 }
24646 }
24647
24648 return batch;
24649};
24650
24651/**
24652 * True if the supplied DOM node is a valid node element.
24653 *
24654 * @param {?DOMElement} node The candidate DOM node.
24655 * @return {boolean} True if the DOM is a valid DOM node.
24656 * @internal
24657 */
24658function isValidContainer(node) {
24659 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 '));
24660}
24661
24662function getReactRootElementInContainer(container) {
24663 if (!container) {
24664 return null;
24665 }
24666
24667 if (container.nodeType === DOCUMENT_NODE) {
24668 return container.documentElement;
24669 } else {
24670 return container.firstChild;
24671 }
24672}
24673
24674function shouldHydrateDueToLegacyHeuristic(container) {
24675 var rootElement = getReactRootElementInContainer(container);
24676 return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
24677}
24678
24679setBatchingImplementation(batchedUpdates$1, interactiveUpdates$1, flushInteractiveUpdates$1);
24680
24681var warnedAboutHydrateAPI = false;
24682
24683function legacyCreateRootFromDOMContainer(container, forceHydrate) {
24684 var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container);
24685 // First clear any existing content.
24686 if (!shouldHydrate) {
24687 var warned = false;
24688 var rootSibling = void 0;
24689 while (rootSibling = container.lastChild) {
24690 {
24691 if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
24692 warned = true;
24693 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.');
24694 }
24695 }
24696 container.removeChild(rootSibling);
24697 }
24698 }
24699 {
24700 if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
24701 warnedAboutHydrateAPI = true;
24702 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.');
24703 }
24704 }
24705 // Legacy roots are not async by default.
24706 var isConcurrent = false;
24707 return new ReactRoot(container, isConcurrent, shouldHydrate);
24708}
24709
24710function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
24711 {
24712 topLevelUpdateWarnings(container);
24713 }
24714
24715 // TODO: Without `any` type, Flow says "Property cannot be accessed on any
24716 // member of intersection type." Whyyyyyy.
24717 var root = container._reactRootContainer;
24718 if (!root) {
24719 // Initial mount
24720 root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
24721 if (typeof callback === 'function') {
24722 var originalCallback = callback;
24723 callback = function () {
24724 var instance = getPublicRootInstance(root._internalRoot);
24725 originalCallback.call(instance);
24726 };
24727 }
24728 // Initial mount should not be batched.
24729 unbatchedUpdates$$1(function () {
24730 if (parentComponent != null) {
24731 root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
24732 } else {
24733 root.render(children, callback);
24734 }
24735 });
24736 } else {
24737 if (typeof callback === 'function') {
24738 var _originalCallback = callback;
24739 callback = function () {
24740 var instance = getPublicRootInstance(root._internalRoot);
24741 _originalCallback.call(instance);
24742 };
24743 }
24744 // Update
24745 if (parentComponent != null) {
24746 root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
24747 } else {
24748 root.render(children, callback);
24749 }
24750 }
24751 return getPublicRootInstance(root._internalRoot);
24752}
24753
24754function createPortal$$1(children, container) {
24755 var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
24756
24757 (function () {
24758 if (!isValidContainer(container)) {
24759 {
24760 throw ReactError('Target container is not a DOM element.');
24761 }
24762 }
24763 })();
24764 // TODO: pass ReactDOM portal implementation as third argument
24765 return createPortal$1(children, container, null, key);
24766}
24767
24768var ReactDOM = {
24769 createPortal: createPortal$$1,
24770
24771 findDOMNode: function (componentOrElement) {
24772 {
24773 var owner = ReactCurrentOwner.current;
24774 if (owner !== null && owner.stateNode !== null) {
24775 var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
24776 !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;
24777 owner.stateNode._warnedAboutRefsInRender = true;
24778 }
24779 }
24780 if (componentOrElement == null) {
24781 return null;
24782 }
24783 if (componentOrElement.nodeType === ELEMENT_NODE) {
24784 return componentOrElement;
24785 }
24786 {
24787 return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
24788 }
24789 return findHostInstance(componentOrElement);
24790 },
24791 hydrate: function (element, container, callback) {
24792 (function () {
24793 if (!isValidContainer(container)) {
24794 {
24795 throw ReactError('Target container is not a DOM element.');
24796 }
24797 }
24798 })();
24799 {
24800 !!container._reactHasBeenPassedToCreateRootDEV ? warningWithoutStack$1(false, 'You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOM.%s(). This is not supported. ' + 'Did you mean to call createRoot(container, {hydrate: true}).render(element)?', enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot') : void 0;
24801 }
24802 // TODO: throw or warn if we couldn't hydrate?
24803 return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
24804 },
24805 render: function (element, container, callback) {
24806 (function () {
24807 if (!isValidContainer(container)) {
24808 {
24809 throw ReactError('Target container is not a DOM element.');
24810 }
24811 }
24812 })();
24813 {
24814 !!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;
24815 }
24816 return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
24817 },
24818 unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) {
24819 (function () {
24820 if (!isValidContainer(containerNode)) {
24821 {
24822 throw ReactError('Target container is not a DOM element.');
24823 }
24824 }
24825 })();
24826 (function () {
24827 if (!(parentComponent != null && has(parentComponent))) {
24828 {
24829 throw ReactError('parentComponent must be a valid React Component');
24830 }
24831 }
24832 })();
24833 return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
24834 },
24835 unmountComponentAtNode: function (container) {
24836 (function () {
24837 if (!isValidContainer(container)) {
24838 {
24839 throw ReactError('unmountComponentAtNode(...): Target container is not a DOM element.');
24840 }
24841 }
24842 })();
24843
24844 {
24845 !!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;
24846 }
24847
24848 if (container._reactRootContainer) {
24849 {
24850 var rootEl = getReactRootElementInContainer(container);
24851 var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);
24852 !!renderedByDifferentReact ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0;
24853 }
24854
24855 // Unmount should not be batched.
24856 unbatchedUpdates$$1(function () {
24857 legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
24858 container._reactRootContainer = null;
24859 });
24860 });
24861 // If you call unmountComponentAtNode twice in quick succession, you'll
24862 // get `true` twice. That's probably fine?
24863 return true;
24864 } else {
24865 {
24866 var _rootEl = getReactRootElementInContainer(container);
24867 var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl));
24868
24869 // Check if the container itself is a React root node.
24870 var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;
24871
24872 !!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;
24873 }
24874
24875 return false;
24876 }
24877 },
24878
24879
24880 // Temporary alias since we already shipped React 16 RC with it.
24881 // TODO: remove in React 17.
24882 unstable_createPortal: function () {
24883 if (!didWarnAboutUnstableCreatePortal) {
24884 didWarnAboutUnstableCreatePortal = true;
24885 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.');
24886 }
24887 return createPortal$$1.apply(undefined, arguments);
24888 },
24889
24890
24891 unstable_batchedUpdates: batchedUpdates$1,
24892
24893 unstable_interactiveUpdates: interactiveUpdates$1,
24894
24895 flushSync: flushSync$$1,
24896
24897 unstable_createRoot: createRoot,
24898 unstable_flushControlled: flushControlled$$1,
24899
24900 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
24901 // Keep in sync with ReactDOMUnstableNativeDependencies.js
24902 // ReactTestUtils.js, and ReactTestUtilsAct.js. This is an array for better minification.
24903 Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injection.injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch, flushPassiveEffects$$1]
24904 }
24905};
24906
24907function createRoot(container, options) {
24908 var functionName = enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot';
24909 (function () {
24910 if (!isValidContainer(container)) {
24911 {
24912 throw ReactError(functionName + '(...): Target container is not a DOM element.');
24913 }
24914 }
24915 })();
24916 {
24917 !!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;
24918 container._reactHasBeenPassedToCreateRootDEV = true;
24919 }
24920 var hydrate = options != null && options.hydrate === true;
24921 return new ReactRoot(container, true, hydrate);
24922}
24923
24924if (enableStableConcurrentModeAPIs) {
24925 ReactDOM.createRoot = createRoot;
24926 ReactDOM.unstable_createRoot = undefined;
24927}
24928
24929var foundDevTools = injectIntoDevTools({
24930 findFiberByHostInstance: getClosestInstanceFromNode,
24931 bundleType: 1,
24932 version: ReactVersion,
24933 rendererPackageName: 'react-dom'
24934});
24935
24936{
24937 if (!foundDevTools && canUseDOM && window.top === window.self) {
24938 // If we're in Chrome or Firefox, provide a download link if not installed.
24939 if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
24940 var protocol = window.location.protocol;
24941 // Don't warn in exotic cases like chrome-extension://.
24942 if (/^(https?|file):$/.test(protocol)) {
24943 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');
24944 }
24945 }
24946 }
24947}
24948
24949
24950
24951var ReactDOM$2 = Object.freeze({
24952 default: ReactDOM
24953});
24954
24955var ReactDOM$3 = ( ReactDOM$2 && ReactDOM ) || ReactDOM$2;
24956
24957// TODO: decide on the top-level export form.
24958// This is hacky but makes it work with both Rollup and Jest.
24959var reactDom = ReactDOM$3.default || ReactDOM$3;
24960
24961return reactDom;
24962
24963})));